// (c) Alex Bokov 2010


function min( a, b ) { if ( a > b ) return b; else return a; }

function file_name_only(str) 	// (c) not mine
{ 
	var slash = '/';
	if (str.match(/\\/)) { slash = '\\' } 
	return str.substring(str.lastIndexOf(slash) + 1, str.lastIndexOf('.'));
}


function show( div_id )	// div id first chars. shows all matched divs
{
	divs = document.getElementsByTagName('div'); ii = 0;
	for ( i = 0; i<divs.length; i++ ) if ( ( divs[i].id.indexOf(div_id) != -1 ) && ( document.getElementById(divs[i].id).style.display == 'none' ) ){
		setTimeout( "document.getElementById( '"+divs[i].id+"' ).style.display = 'block';", ii*50 );
		ii++;
	}
}
function hide( div_id )	// div id first chars. hide all matched divs
{
	divs = document.getElementsByTagName('div'); ii = 0;
	for ( i = 0; i<divs.length; i++ ) if ( ( divs[i].id.indexOf(div_id) != -1 ) && ( document.getElementById(divs[i].id).style.display == 'block' ) ) {
		setTimeout( "document.getElementById( '"+divs[i].id+"' ).style.display = 'none';", ii*50 );
		ii++;
	}
}
function load( addr )	// load page by url
{
	window.location.href=addr;
}
function currpage( name )	// if current page is named like name.html
{
	page = file_name_only(window.location.href); 
	if ( page.indexOf(name) != -1 ) return Boolean(true); else return Boolean(false);
}
function closemenu() { Set_Cookie( "menu", "closed", 1 ); }
function openmenu() { Set_Cookie( "menu", "open", 1 ); }
function menuclosed() { if ( Get_Cookie("menu") == "closed" ) return Boolean(true); else return Boolean(false); }

var	show_preview_timeout;
function show_preview( imagename )
{
	show_preview_timeout = setTimeout( "blendimage(  'x', 'title', '"+imagename+"', 300 );", 300 );
}
function show_preview_stop( )
{
	clearTimeout( show_preview_timeout );
}

var	scrolling_y	= false;
function scroll_y( dy )
{
	document.getElementById('previews').scrollTop = document.getElementById('previews').scrollTop + dy;
	if ( dy < 0 ) { if ( dy > -30 ) dy--; }
	if ( dy > 0 ) { if ( dy <  30 ) dy++; }
	if ( scrolling_y == true ) setTimeout("scroll_y(" + dy + " )",50);
}
var	scrolling_x	= false;
function scroll_x( dx )
{
	document.getElementById('previews').scrollLeft = document.getElementById('previews').scrollLeft + dx;
	if ( dx < 0 ) { if ( dx > -30 ) dx--; }
	if ( dx > 0 ) { if ( dx <  30 ) dx++; }
	if ( scrolling_x == true ) setTimeout("scroll_x(" + dx + " )",50);
}

function preloadImage( src )
{
	if (document.images) {
		pic1 = new Image; 
		pic1.src = src; 
	}
}

//
// ---
//
function do_onload()
{
}


// ---- (c) not Alex Bokov ;-)

//------------------------------------------------------------------
// Функция установки обработчика события
// Параметры вызова:
//   hElem     - DOM-элемент или его ID
//   eventName - событие
//   callback  - функция, которая будет вызвана при событии
// На выходе:
//   TRUE  - обработчик установлен
//   FALSE - элемент не найден или браузер не поддерживает события
//------------------------------------------------------------------
function hookEvent(hElem, eventName, callback) {
  if (typeof(hElem) == 'string') {
    // Если передан ID, то получить DOM-элемент
    hElem = document.getElementById(hElem);
  }
  // Если такого элемента нет, то возврат с ошибкой
  if (!hElem) { return false; }
 
  if (hElem.addEventListener) {
    if (eventName == 'mousewheel') {
      // Событие вращения колесика для Mozilla
      hElem.addEventListener('DOMMouseScroll', callback, false);
    }
    // Колесико для Opera, WebKit-based, а также любые другие события
    // для всех браузеров кроме Internet Explorer
    hElem.addEventListener(eventName, callback, false);
  }
  else if (hElem.attachEvent) {
    // Все события для Internet Explorer
    hElem.attachEvent('on' + eventName, callback);
  }
  else { return false; }
  return true;
}
//------------------------------------------------------------------
// Кроссбраузерная функция подавления события
//------------------------------------------------------------------
function cancelEvent(e) {
  e = e ? e : window.event;
  if (e.stopPropagation) {
    e.stopPropagation();
  }
  if (e.preventDefault) {
    e.preventDefault();
  }
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  return false;
}
//------------------------------------------------------------------
// Пример функции обработки колесика мыши
//------------------------------------------------------------------
function MouseWheelFunction(e) {
  e = e ? e : window.event;
  // Получить элемент, на котором произошло событие
  var wheelElem = e.target ? e.target : e.srcElement;
  // Получить значение поворота колесика мыши
  var wheelData = e.detail ? e.detail * -1 : e.wheelDelta / 40;
  // В движке WebKit возвращается значение в 100 раз больше
  if (Math.abs(wheelData)>100) { wheelData=Math.round(wheelData/100); }
 
  // Теперь в переменной wheelElem содержится элемент, который получил
  // собщение от колесика мыши, а в wheelData значение поворота колеса
 
	for ( i = 0; i < 15; i++ ) { 
		setTimeout( "document.getElementById('projectlist').scrollTop = document.getElementById('projectlist').scrollTop - "+wheelData*2, i*20 ); 
	}
 
  // Отменить штатные действия браузера при кручении колеса мыши
  return cancelEvent(e);
}


// -------------------
// -------------------
// -------------------

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}



function getNaturalHeight(img) {
        if( img.naturalHeight ) {
            return img.naturalHeight;
        } else {
            lgi = new Image();
            lgi.src = img.src;
            return lgi.height;
        }
}

function getElementPosition(elemID){
	var offsetTrail = document.getElementById(elemID);
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail){
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	return {left:offsetLeft,top:offsetTop};
}

function getElLeft(el) {
var ns4 = (navigator.appName.indexOf("Netscape")>=0 
          && parseFloat(navigator.appVersion) >= 4 
          && parseFloat(navigator.appVersion) < 5)? true : false;
var ns6 = (parseFloat(navigator.appVersion) >= 5 
          && navigator.appName.indexOf("Netscape")>=0 )? true : false;
var ns = (document.layers)? true:false;
var ie = (document.all)? true:false;
    if (ns4) {return el.pageX;} 
    else {
        xPos = el.offsetLeft;
        tempEl = el.offsetParent;
        while (tempEl != null) {
            xPos += tempEl.offsetLeft;
              tempEl = tempEl.offsetParent;
        }
 
       return xPos;
    }
}
function getElTop(el) {
var ns4 = (navigator.appName.indexOf("Netscape")>=0 
          && parseFloat(navigator.appVersion) >= 4 
          && parseFloat(navigator.appVersion) < 5)? true : false;
var ns6 = (parseFloat(navigator.appVersion) >= 5 
          && navigator.appName.indexOf("Netscape")>=0 )? true : false;
var ns = (document.layers)? true:false;
var ie = (document.all)? true:false;
    if (ns4) {return el.pageY;} 
    else {
        yPos = el.offsetTop;
        tempEl = el.offsetParent;
        while (tempEl != null) {
            yPos += tempEl.offsetTop;
              tempEl = tempEl.offsetParent;
        }
        return yPos;
    }
}


function getParam( name )
{
	var start=location.search.indexOf("?"+name+"=");
	if (start<0) start=location.search.indexOf("&"+name+"=");
	if (start<0) return '';
	start += name.length+2;
	var end=location.search.indexOf("&",start)-1;
	if (end<0) end=location.search.length;
	var result='';
	for(var i=start;i<=end;i++) {
		var c=location.search.charAt(i);
		result=result+(c=='+'?' ':c);
	}
	return unescape(result);
}

function showObjId( id ) { if ( document.getElementById( id ) ) showObj( document.getElementById( id ) ); }
function showObj( obj )
{
    if ( ! obj.style ) obj.visibility = "visible"; else obj.style.visibility = "visible";
}

function hideObjId( id ) { if ( document.getElementById( id ) ) hideObj( document.getElementById( id ) ); }
function hideObj( obj )
{
    if ( ! obj.style ) obj.visibility = "hidden"; else obj.style.visibility = "hidden";
}

function moveObjTo( obj, x, y )
{
    if ( ! obj.style ) { obj.top = y; obj.left = x; } else { obj.style.top = y + "px"; obj.style.left = x + "px"; }
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function zeroPad(num,count)		// pad NUM with leading zeroes, '0000x'
{
	var numZeropad = num + '';
	while(numZeropad.length < count) { numZeropad = "0" + numZeropad; }
	return numZeropad;
}

// Cross-browser BlendTrans Filter JavaScript, Fade in/out
// http://brainerror.net/scripts/javascript/blendtrans/
// blendtrans.js
// slightly modified by Alex Bokov - for this site only

function opacity(id, opacStart, opacEnd, millisec) {		// by .id
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++)
			{
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}
function opacityS(src, opacStart, opacEnd, millisec) {		// by .src
	var speed = Math.round(millisec / 20);
	var timer = 0;

	if ( opacStart > opacEnd ) { for(i = opacStart; i >= opacEnd; i--) { setTimeout("changeOpacS(" + i + ",'" + src + "')",(timer * speed)); timer++; } } 
	else if( opacStart < opacEnd ) { for(i = opacStart; i <= opacEnd; i++) { setTimeout("changeOpacS(" + i + ",'" + src + "')",(timer * speed)); timer++; } }
}
function changeOpacS(opacity, src) {				// by .src
	var imgs, i;
	imgs = document.getElementsByTagName('img');
	for ( i = 0; i<imgs.length; i++ ) { if ( imgs[i].src.indexOf(src) != -1 ) { 
		object = imgs[i].style;
		object.opacity = (opacity / 100); object.MozOpacity = (opacity / 100);
		object.KhtmlOpacity = (opacity / 100); object.filter = "alpha(opacity=" + opacity + ")";
	} }
}


//change the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function shiftOpacity(id, millisec) {
	//if an element is invisible, make it visible, else make it ivisible
	if(document.getElementById(id).style.opacity == 0) {
		opacity(id, 0, 100, millisec);
	} else {
		opacity(id, 100, 0, millisec);
	}
}

var	bi_timeout	= new Array();
var	blend_id;
function blendimage(divid, imageid, imagefile, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;

	if ( document.getElementById(imageid).src.substr(document.getElementById(imageid).src.length-imagefile.length, imagefile.length ) != imagefile )	/* don't replace if same already */ 
	{
		//set the current image as background
		document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")";
	
		//make image transparent
		changeOpac(0, imageid);
	
		//make new image
		document.getElementById(imageid).src = imagefile;

		//fade in image
		for(i = 0; i <= 100; i=i+1) {
			if ( blend_id == divid ) clearTimeout( bi_timeout[i] );
			bi_timeout[i] = 
			setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed));
			timer=timer+1;
		}
		blend_id = divid;
	}
}

function currentOpac(id, opacEnd, millisec) {
	//standard opacity is 100
	var currentOpac = 100;
	
	//if the element has an opacity set, get it
	if(document.getElementById(id).style.opacity < 100) {
		currentOpac = document.getElementById(id).style.opacity * 100;
	}

	//call for the function that changes the opacity
	opacity(id, currentOpac, opacEnd, millisec)
}


