//Текущая позиция первой фото для preview 
photo = 0;
//Количество блоков preview
showPhoto = 5;

// Тема письма
mailSubject = 'Cartoon by Russian painter Avdey';

//Массивы, для кэширования фото
smallcache = new Array();
previewcache = new Array();
bigcache = new Array();

//Флаг отображения окна
popup = 0;

//Размеры появляющегося окна
POPUP_WIDTH = 360;
POPUP_HEIGHT = 360;

//Указатель на источник события по отображению popup-окна
target = null;

//Укзатель на таймер
tmr = null;

//Флаг уничтожения popup-окна
hidetmr=0;


//Ширина текущего окна
function getWinWidth() {
	var myWidth = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
          } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
    }
    return myWidth;
}

//Высота текущего окна 
function getWinHeight() {
	var myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myHeight = document.body.clientHeight;
    }
    return myHeight;
}

//Показать новое окно
var fromClick = false;
function showPreload() {
	//Блок инициализация размеров, ориентир на сердину окна
	var target = window.target;
	
	//установка флага
	window.popup = 1;
	
	//определение пути к большой фотке
	smallImageDiv = document.getElementById('smallImg');
	largeImageSrc = smallImageDiv.src.replace("/small/", "/large/")

	var winHeight = getWinHeight();
	var winWidth = getWinWidth();
	
	//установка координат окошка
	newdiv = document.getElementById("popup");
	newdiv.style.height = winHeight;
	newdiv.style.width = winWidth;
	newdiv.style.left = 0; 
	newdiv.style.top = 0;
	newdiv.style.align='centr';


	fromClick = false;
	//назначение обработчика скрытие окна, если указатель мыши покидает облась окна
	newdiv.onmouseout = function() { 
			if(window.hidetmr)
				clearTimeout(window.hidetmr);
		 
			fromClick = true;
			window.hidetmr = setTimeout("hidePreload()", 300);
			
			return;	
		};
	newdiv.onclick = function() { 
			if(window.hidetmr)
				clearTimeout(window.hidetmr);
			 
			fromClick = true;
			window.hidetmr = setTimeout("hidePreload()", 300);
			
			return;	
		};
		
	//назначение обработчика отмены скрытия окна, в случае если указатель мыши возвращается на окно	
	newdiv.onmouseover = function() {
			if(window.hidetmr && !fromClick) {
			 	clearTimeout(window.hidetmr);
			}
			return;	
		};
		
	//заполнение окна - большая картинка
	newdiv.innerHTML = '<table width=100% border="0" cellpadding="100px" cellspacing="0" align=center><tr align=center><td><img src="'+ largeImageSrc +'" border=0 /></td></tr></table>';
	//отображение окна
	newdiv.style.display = 'block';
}


var haveZoom=0;
//Показать новое окно
function createPreload(target) {
	if(haveZoom==0) {
		return;
	}

	if(window.popup == 1) return; 	   //если окно в данный момент показано, ничего не делает

    if(fromClick) {
      fromClick = false;
      return;
    }
	
	window.target = target;		// назачение источника сообщение
	
	window.tmr = setTimeout("showPreload()",50);  // завод таймера на непосредственное отображение
}

//Скрыть новое окно
function hidePreload() {
	//если оно не показано - ничего не делать
	if(window.popup == 0) return;
	
	//установить флаг
	window.popup = 0;
	
	target  = document.getElementById("popup");
	//скрыть окно
	target.style.display = 'none';
	
	//сбросить обработчики
	target.onmouseout = null;
	target.onmouseover = null;
	
	//сбросить таймер
	window.hidetmr = null;

	fromClick = false;
}

//Вспомогательная функция. Отображеие изображений со свойствами в указанном элементе
function showDiv(div,src,alt,path) {
	//alert('showDiv: div='+div+' src='+src+' path='+path);
	window.im = x;
	if(path == 'preview')
      document.getElementById(div).innerHTML = '<a href="javascript:window.bigphoto = '+getIndex(src)+'; bigPic();"><img alt="'+ alt +'" src='+ pagePath + path+'/'+ src +' border=0/></a>';
    else
	  document.getElementById(div).innerHTML = '<img id="smallImg" alt="'+ alt +'" src='+ pagePath + path+'/'+ src +' border=0/>';

	document.getElementById(div).style.visibility = 'visible';
}

//Карта действий с предварительной проверкой. Провеку проходят все действия с интерфейса.
function check(act,src) {
	if(window.total_photo == 0) return;
	if(act == 'doPic') doPic();
	if(act == 'bigPic') bigPic();
	if(act == 'nextPhoto') nextPhoto();
	if(act == 'prevPhoto') prevPhoto();
	if(act == 'nextBigPhoto') nextBigPhoto();
	if(act == 'prevBigPhoto') prevBigPhoto();
	if(act == 'createPreload') createPreload(src); 
}

//Отображение блока изображений preview
function doPic() {
	//размер кеша
	var size = window.smallcache.length;
	
	//вычисление индекса
	var index = window.photo % window.total_photo;
	while(index < 0)
		index += window.total_photo;
	
	//Создание вспомогательного массива имен.
	var names = new Array();
	var alts = new Array();
	
	//Создание массива изображений
	x = new Array();
	for(i = 0;i < 5 && i < window.total_photo; ++ i) {
		x[i] = new Image();
		//инициализация загрузки изображения
		x[i].src = pagePath + "preview/" + window.imgArray[(index + i) % window.total_photo][0];
		names[i] = window.imgArray[(index + i) % window.total_photo][0];
		alts[i] = window.imgArray[(index + i) % window.total_photo][1];
		window.smallcache[size + i] = new Image();
		window.smallcache[size + i].src = x[i].src;
	}
	
	//отображение изобажений в блоках preview
	for(k = 0;k <5 && k < window.total_photo; k++) {
	  showDiv('pr['+k+']', names[k], alts[k], 'preview');
	}
}

//Получить индекс изображения в массиве по наименованию
function getIndex(name) {
	for(i = 0;i < window.total_photo;++i)
		if(window.imgArray[i][0] == name) return i;
	return 0;
}

//Отображение основного изобажения
function bigPic() {
	//определение индекса
	var index = window.bigphoto % window.total_photo;
	while(index < 0)
		index += window.total_photo;
	
	//размер кеша - его берем в качестве следующего элемента
	var size = window.bigcache.length;
	window.bigcache[size] = new Image();
	window.bigcache[size].src =pagePath + "small/"+ window.imgArray[index][0];
	
	//отображение изображения в основном блоке
	showDiv('bigdiv',window.imgArray[index][0],window.imgArray[index][1],'small');

	document.getElementById('zoomImg').src = window.imgArray[index][2] == 1 ? 'pages/images/zoom.jpg' : 'pages/images/zoomno.jpg';
	haveZoom = window.imgArray[index][2];
}

//Обработчик кнопки "next"  блока preview
function nextPhoto() {
	//смена текущей позиции отображения preview
	window.photo = window.photo + 1;
	
	doPic();
	
}

//Обработчик кнопки "previous"  блока preview
function prevPhoto() {
	//смена текущей позиции отображения preview
	window.photo = window.photo - 1;
	
	doPic();
}

//Обработчик кнопки "next"  основного блока
function nextBigPhoto(){
	//смена текущей позиции отображения основного блока
	window.bigphoto = window.bigphoto + 1;
	
	bigPic();
}

//Обработчик кнопки "previous"  основного блока
function prevBigPhoto() {
	//смена текущей позиции отображения основного блока
	window.bigphoto = window.bigphoto - 1;
	
	bigPic();
}

function sendCartoon(){
  var index = window.bigphoto % window.total_photo;
  while(index < 0)
    index += window.total_photo;

  var mailto_link = 'mailto:?subject=' + mailSubject + '&body='+document.location.toString().split("?")[0]+'?name='+window.imgArray[index][0];

  var win = window.open(mailto_link, 'emailWindow');
  if (win && win.open &&!win.closed) win.close();
} 


