var OUT_BORDER = 64;

var m_nChen_SrcX = 0;
var m_nChen_SrcY = 0;
var m_nChen_X = -OUT_BORDER;
var m_nChen_Y = -OUT_BORDER;
var m_nChen_VectorX = 0;
var m_nChen_VectorY = 0;
var m_nCount = 0;
var m_nSpeed = 18;
var m_bBoost = false;

function getChenLeft(){ return Math.round( m_nChen_X - ( m_nChen_SrcX + 64 ) ); }
function getChenTop(){ return Math.round( m_nChen_Y - ( m_nChen_SrcY + 64 ) ); }

function start(){
	document.all.chen.style.visibility = "visible";
	setInterval( "moveChen()", 10 );
}

function moveChen(){
	var nWindowWidth = document.body.clientWidth;
	var nWindowHeight = document.body.clientHeight;
	if(
		m_nChen_Y <= -OUT_BORDER || m_nChen_Y >= nWindowHeight + OUT_BORDER ||
		m_nChen_X <= -OUT_BORDER || m_nChen_X >= nWindowWidth + OUT_BORDER
	){
		if( percent( 50 ) ){
			m_nChen_Y = Math.random() * nWindowHeight;
			m_nChen_VectorY = Math.random() - 2;
			if( percent( 50 ) ){
				m_nChen_X = nWindowWidth + OUT_BORDER / 2;
				m_nChen_VectorX = -m_nSpeed
			}
			else{
				m_nChen_X = -OUT_BORDER / 2;
				m_nChen_VectorX = m_nSpeed
			}
		}
		else{
			m_nChen_X = Math.random() * nWindowWidth;
			m_nChen_VectorX = Math.random() - 2;
			if( percent( 50 ) ){
				m_nChen_Y = nWindowHeight + OUT_BORDER / 2;
				m_nChen_VectorY = -m_nSpeed
			}
			else{
				m_nChen_Y = -OUT_BORDER / 2;
				m_nChen_VectorY = m_nSpeed
			}
		}
	}
	document.all.chen.style.top = getChenTop();
	document.all.chen.style.left = getChenLeft();
	document.all.chen.style.clip = "rect( " + m_nChen_SrcY + ", " + ( m_nChen_SrcX + 128 ) + ", " + ( m_nChen_SrcY + 128 ) + ", " + m_nChen_SrcX + " )";
	if( m_nCount % 4 == 0 ){
		m_nChen_SrcX = ( m_nChen_SrcX + 128 ) % 512;
	}
	m_nChen_X += m_nChen_VectorX * ( m_bBoost ? 2 : 1 );
	m_nChen_Y += m_nChen_VectorY * ( m_bBoost ? 2 : 1 );
	if( percent( 5 ) ){ m_bBoost = !m_bBoost; }
	if( percent( 1 ) ){ m_nChen_VectorY = -m_nChen_VectorY; }
	if( percent( 1 ) ){ m_nChen_VectorX = -m_nChen_VectorX; }
//	document.all.x.innerText = Math.round( m_nChen_X );
//	document.all.y.innerText = Math.round( m_nChen_Y );
	m_nCount++;
}

function doClickAction(){
//	alert( event.offsetX + " " + event.offsetY + "\n" + Math.round( m_nChen_X ) + " " + Math.round( m_nChen_Y ) + "\n" + Math.round( getGapLength( event.offsetX, event.offsetY, m_nChen_X, m_nChen_Y ) ) );
}

function minmax( nExpr, nLimit1, nLimit2 ){
	return Math.max( Math.min( nExpr, Math.max( nLimit1, nLimit2 ) ), Math.min( nLimit1, nLimit2 ) );
}

function percent( nPercent ){
	return ( Math.random() * 100 <= nPercent );
}

function getGapLength( nX1, nY1, nX2, nY2 ){
	return Math.pow( Math.pow( nX2 - nX1, 2 ) + Math.pow( nY2 - nY1, 2 ), 0.5 );
}
