/*
15.05.2008 Maxim Shipko <mashi@artlebedev.ua>
*/

if(!Array.prototype.append) {
	Array.prototype.append = function(newElement){
		this[this.length] = newElement;
	}
};

function initLoupe(oLoupe){
	for(var i=iSqRadius; i<iRadius; i++){
		var l = Math.sqrt(iRadius*iRadius-i*i);
		var L = Math.floor(l);
		aFragments.append( new Fragment(oLoupe, iRadius-L,iRadius-i,2*L,2*i) );
		aFragments.append( new Fragment(oLoupe, iRadius-i,iRadius-L,2*i,2*L) );
	}
	if(anti_aliasing_needed){
		for(var i=0; i<=iSqRadius; i++){
			var l = Math.sqrt(iRadius*iRadius-i*i);
			var L = Math.floor(l);
			var dL = Math.ceil(l)-l;
			var iOpacity = (100-Math.round(dL*100))/100;
			if(iOpacity > 0.95 || iOpacity < 0.2) continue;
			aFragments.append( new Fragment(oLoupe, iRadius-L-1, iRadius-i, 2*L+2, 2*i, iOpacity) );
			aFragments.append( new Fragment(oLoupe, iRadius-i, iRadius-L-1, 2*i, 2*L+2, iOpacity) );
		}
	}
	FragmetsAmount = aFragments.length;
};

function Fragment(oLoupe, left, top, width, height,opacity) {
	this.x = left;
	this.y = top;
	var oFragment = $('<div>').css({left: left, top: top, width: width, height: height,zIndex: 1});
	if(opacity) {
		oFragment.css({
			opacity: opacity, 
			zIndex: 5
		});
	}
	oLoupe.append(oFragment);
	this.style = oFragment[0].style;

};

Fragment.prototype.update = function(x,y){
	this.style.backgroundPosition = (-x - this.x) + 'px ' + (-y - this.y) + 'px';
};

function moveLoupe(evt){
		movementscounter++;
		if( movementscounter%5 ) return;
		var x = evt.pageX-iRadius-AreaPosition.left;
		var y = evt.pageY-iRadius-AreaPosition.top;
		if (x > oLoupeAreaWidth || y > oLoupeAreaHeight ) {
			movementscounter = 0;
			return;
		}
		if (x < -iRadius*3 ) return;
		for(var i=0, il = FragmetsAmount; i < il; i++){
			aFragments[i].update(x,y);
		}
		oLoupe.css( {left: x, top: y} );
};


var iRadius = 80;
var iSqRadius = Math.ceil( Math.sqrt(iRadius*iRadius/2) );
var anti_aliasing_needed = true;
var aFragments = [];
var FragmetsAmount = 0;
var movementscounter = 0;
var oLoupe, oLoupeArea, AreaPosition;


$(function(){
	oLoupe = $('#NudeLoupe');
	oLoupeArea = $('#LoupeArea');
	AreaPosition = oLoupeArea.offset() || {left: 0, top: 0};
	oLoupeAreaWidth = oLoupeArea.width();
	oLoupeAreaHeight = oLoupeArea.height();
	initLoupe( $('#NudeLoupe') );
	if(jQuery.browser.mozilla  && jQuery.browser.version.substr(0,3)=="1.9"){
		// specialy for Firefox 3.x use png variant of black image, because of apacity
		$("#loupe-style").html(" #NudeLoupe div { background-image: url('black_grl.png'); } ");
	}
	$('body').mousemove(moveLoupe);
	//oLoupeArea.mousemove(moveLoupe);
});
