
// Переопределение онлоада с сохранением старых функций
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
		window.onload = func;
	} else {
		window.onload = function(){
			oldonload();
			func();
		}
	}
}


function addResizeEvent(func)
{
	var oldonresize = window.onresize;
	if (typeof window.onresize != 'function'){
		window.onresize = func;
	} else {
		window.onresize = function(){
			oldonresize();
			func();
		}
	}
}



//part from quircksmode.org
function findPos(obj) {
	var curleft = curtop = 0;
	var _width = obj.width;
	var _height = obj.height;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return {left:curleft,top:curtop,width:_width,height:_height};
}



///////////////////////////////////////////////////////
// Анимированное развертывание ужатых картинок
//

//Проценты прозрачностей
var unwrapOpacityArray = new Array(60,70,80,90,100);
var unwrapOpacityPointer1;
var unwrapOpacityInterval1;
var unwrapInterval1;

function resetFadeOut(imId){
	clearInterval(unwrapOpacityInterval1);
	var image = document.getElementById(imId);
	unwrapOpacityPointer1=0;
	image.style.opacity = (unwrapOpacityArray[unwrapOpacityPointer1] == 100) ? '0.99' : unwrapOpacityArray[unwrapOpacityPointer1]/100;
	image.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + unwrapOpacityArray[unwrapOpacityPointer1] + ")";
	unwrapOpacityPointer1++;

}

function doFadeOut(imId,now){
	var image = document.getElementById(imId);
	if(now==1)unwrapOpacityPointer1=unwrapOpacityArray.length-1;
	image.style.opacity = (unwrapOpacityArray[unwrapOpacityPointer1] == 100) ? '0.99' : unwrapOpacityArray[unwrapOpacityPointer1]/100;
	image.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + unwrapOpacityArray[unwrapOpacityPointer1] + ")";
	unwrapOpacityPointer1++;
	if(unwrapOpacityPointer1>=unwrapOpacityArray.length){
		clearInterval(unwrapOpacityInterval1);
	}
}


function startFadeOut(imId){
	var image = document.getElementById(imId);
	clearInterval(unwrapOpacityInterval1);
	unwrapOpacityPointer1 = 0;
	image.style.display="inline";
	unwrapOpacityInterval1 = window.setInterval("doFadeOut('"+imId+"',0)",40);
}

function createUnwrappedDiv(){
	var newImg = document.createElement('img');
	var newAnc = document.createElement('a');
	var newDiv = document.createElement('div');
	newDiv.appendChild(newAnc);
	newAnc.appendChild(newImg);
	document.body.appendChild(newDiv);
	newDiv.style.position = "absolute";
	newDiv.setAttribute('id','unwrappedDiv');
	newImg.setAttribute('id','unwrappedImg');
	newAnc.setAttribute('id','unwrappedAnc');
	newImg.setAttribute('border','1px');
	newDiv.setAttribute('border','1px');
	newImg.style.border = "4px  solid #ffffff";
	newDiv.style.border = "2px  solid #dadada";
	newDiv.style.top = "0px";
	newDiv.style.left = "0px";
	newDiv.style.display="none";

}

function unwrap_img(obj){
	if(!document.getElementById('unwrappedDiv'))createUnwrappedDiv();

	var newImg = document.getElementById('unwrappedImg');
	var newDiv = document.getElementById('unwrappedDiv');
	var newAnc = document.getElementById('unwrappedAnc');

	resetFadeOut('unwrappedDiv');
	newDiv.style.display="none";

	var position = findPos(obj);
	var imgPreload = new Image();

	newDiv.style.top = position.top+"px";
	newDiv.style.left = position.left+"px";

	imgPreload.onload=function(){
		newDiv.style.top = Math.max(Math.floor(position.top-(imgPreload.height+((4+2)*2)-position.height)/2),0)+"px";
		newDiv.style.left = Math.max(Math.floor(position.left-(imgPreload.width+((4+2)*2)-position.width)/2),0)+"px";
		start_waiting_unwrap();
	}

	imgPreload.src = obj.src;
	newImg.src = obj.src;
	newAnc.href = "";
	newAnc.href = obj.parentNode.href;

	newDiv.onmouseout = function(){
		resetFadeOut('unwrappedDiv');
		newDiv.style.display="none";
	}
	newDiv.onmouseover = function(){}
}

function stop_waiting_unwrap(){
	clearInterval(unwrapInterval1);
}
function start_waiting_unwrap(){
	stop_waiting_unwrap();
	unwrapInterval1 = window.setTimeout("startFadeOut('unwrappedDiv')",450);
}

//
//
///////////////////////////////////////////////////////



///////////////////////////////////////////////////////
// Функции для работы с XMLHttpRequest//


function loadGET(url,onreadyFunction) {
	req = false;
	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest && !(window.ActiveXObject)) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
		// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}
	if(req) {
		req.onreadystatechange = onreadyFunction;
		req.open("GET", url, true);
		req.send("");
	}
}

function loadPOST(url,dataArray,onreadyFunction) {
	req = false;
	var postdata = "";
	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest && !(window.ActiveXObject)) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
		// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}
	if(req) {
		for(paramName in dataArray)
		{postdata += paramName + "=" + encodeURIComponent(unescape(dataArray[paramName])) + "&amp;";}
		//alert(postdata);
		req.onreadystatechange = onreadyFunction;
		req.open("POST", url, true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", postdata.length);
		req.send(postdata);
		//window.status='loading...';
	}
}
/*
//Пример функции для обработки запросов
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
window.status='loaded';
dataArray = eval(req.responseText);
for(paramName in dataArray[0])
{
document.getElementById('imagelist'+paramName).src=dataArray[0][paramName];
}
} else {
//alert( req.statusText);
}
}
}*/

//
//
///////////////////////////////////////////////////////




///////////////////////////////////////////////////////
// Обработка ввода с клавиатуры
//

function keyboardInput(e){
	if (e) {cur_event = e;	}
	else {cur_event = event;}


	keycode = (cur_event.keyCode)?cur_event.keyCode:cur_event.keyChar;
	if (keycode == null)	keycode = cur_event.which;


	//key = String.fromCharCode(keycode).toLowerCase();

	//keyCode - код кнопки
	//key - кнопка

	/*
	return     = 13
	escape     = 27
	space bar  = 32
	left       = 37
	right      = 39
	*/

	if(keycode==null)return;

	//Переход на соседнюю страницу
	if (cur_event.ctrlKey && keycode == 37 && !cur_event.shiftKey) {
		var link_to_go = document.getElementById('prev_link_node');
	}
	else if (cur_event.ctrlKey && keycode == 39&& !cur_event.shiftKey) {
		var link_to_go = document.getElementById('next_link_node');
	}
	if (link_to_go && link_to_go.href!="") window.location = link_to_go.href;
}


function listenKey () {	document.onkeydown = keyboardInput; }
listenKey();

//
//
///////////////////////////////////////////////////////

function jsrotate(obj,angle,whence) {//работает правильно только при Pi/2 поворотах
	var p = obj;
	p.angle = angle;
	if (p.angle >= 0) {
		var rotation = Math.PI * p.angle / 180;
	} else {
		var rotation = Math.PI * (360+p.angle) / 180;
	}
	var costheta = Math.cos(rotation);
	var sintheta = Math.sin(rotation);

	if (document.all && !window.opera) {
		var canvas = document.createElement('img');

		canvas.src = p.src;
		canvas.style.filter = "progid:DXImageTransform.Microsoft.Matrix(M11="+costheta+",M12="+(-sintheta)+",M21="+sintheta+",M22="+costheta+",SizingMethod='auto expand')";
		canvas.height = p.height;
		canvas.width = p.width;

	} else {
		var canvas = document.createElement('canvas');
		canvas.oImage = new Image();

		canvas.oImage.onload = function(){
			canvas.style.width = canvas.width = p.width;
			canvas.style.height = canvas.height = p.height;
			var context = canvas.getContext('2d');
			context.save();
			if (rotation <= Math.PI/2) {
				context.translate(sintheta*canvas.oImage.height,0);
			} else if (rotation <= Math.PI) {
				context.translate(canvas.width,-costheta*canvas.oImage.height);
			} else if (rotation <= 1.5*Math.PI) {
				context.translate(-costheta*canvas.oImage.width,canvas.height);
			} else {
				context.translate(0,-sintheta*canvas.oImage.width);
			}
			context.rotate(rotation);
			context.drawImage(canvas.oImage, 0, 0,  p.height,p.width);
			context.restore();
		}
		canvas.oImage.src = p.src;

	}
	canvas.id = p.id;
	p.parentNode.replaceChild(canvas, p);
}



function fixRotation(num,wid,hei){
	previewId = "cal"+num;
	var p = document.getElementById(previewId);
	if(hei==0)hei = p.height;
	if(wid==0)wid = p.width;
	maxHeight = p.parentNode.height;
	maxWidth = p.parentNode.width;
	if (document.all && !window.opera) {
		heiTmp = maxHeight;
		maxHeight=maxWidth;
		maxWidth=heiTmp;
	}
	newH = maxHeight;
	newW = Math.round((newH*wid)/hei);
	if (newW > maxWidth){
		newW = maxWidth;
		newH = Math.round((newW*hei)/wid);
	}
	p.style.height=newH+'px';
	p.style.width=newW+'px';
	jsrotate(p,270);
	document.getElementById(previewId).style.height=newH+'px';
	document.getElementById(previewId).style.width=newW+'px';
}