function GetSecondsTxt(sSecondsNum) {

	sSecondsNum = String(sSecondsNum);
	var sSecondsText = "секунд";
	var nSecondsNumLength = sSecondsNum.length;
	
	if ( sSecondsNum.charAt(nSecondsNumLength - 2) != "1" )
	{
		if (sSecondsNum.charAt(nSecondsNumLength - 1) == "2" || sSecondsNum.charAt(nSecondsNumLength - 1) == "3" || sSecondsNum.charAt(nSecondsNumLength - 1) == "4"){
			sSecondsText = "секунды";
		}else if (sSecondsNum.charAt(nSecondsNumLength - 1) == "1"){
			sSecondsText = "секунду";
		}
	}
	return sSecondsText;
}

function countDown()
{
	var currentTime = parseInt(document.getElementById('timer').innerHTML);
	
	if( currentTime > 1 ) {
		document.getElementById('timer').innerHTML = currentTime - 1;
		document.getElementById('seconds').innerHTML = GetSecondsTxt(currentTime-1);

    	setTimeout('countDown()',1000);
	}
	else
	{
		document.getElementById('timer').innerHTML = "";
		document.getElementById('seconds').innerHTML = "...";
	}
}

function getWorkspaceSize()
{
	return {
		"x":document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth,
		"y":document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight
	};
}

function getScrollSize()
{
	return {
		"x":self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft),
		"y":self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop)
	};
}

function getElementPosition(oElement)
{
    var w = oElement.offsetWidth;
    var h = oElement.offsetHeight;
	
    var l = 0;
    var t = 0;
	
    while (oElement)
    {
        l += oElement.offsetLeft;
        t += oElement.offsetTop;
        oElement = oElement.offsetParent;
    }

    return {"left":l, "top":t, "width": w, "height":h};
}

function mousePageXY(e)
{
  var x = 0, y = 0;

  if (!e) e = window.event;

  if (e.pageX || e.pageY)
  {
    x = e.pageX;
    y = e.pageY;
  }
  else if (e.clientX || e.clientY)
  {
    x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
    y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
  }

  return {"x":x, "y":y};
}

var oReactor =
{
	// исполняется ли в данный момент запрос к серверу
	bProcessing: false,
	
	// div для вывода сообщения на экран
	awaitNotice: false,
	
	// div для вывода сообщения на экран
	divNotice: false,
	
	// время отображения сообщения на экране
	iShowNoticeTime: 3000,
	
	init: function()
	{
		var allElements = document.getElementsByTagName('*');
		
		if ( allElements.length == 0 )
		{
			allElements = document.all;
		}
		
		for ( var i = 0; i < allElements.length; i++ )
		{
			if ( allElements[i].id.length > 0 )
			{
				if ( allElements[i].id.length > 0 )
				{
					this[allElements[i].id] = allElements[i];
				}
			}
		}
		
		this.divNotice = document.createElement('div');
		this.divNotice.style.display = 'none';
		this.divNotice.style.visibility = 'hidden';
		this.divNotice.style.width = '400px';
		this.divNotice.style.padding = '25px';
		this.divNotice.style.backgroundRepeat = 'no-repeat';
		this.divNotice.style.backgroundPosition = '5px 5px';
		this.divNotice.style.fontSize = '12px';
		this.divNotice.style.textAlign = 'center';
		this.divNotice.style.position = 'absolute';
		
		this.awaitNotice = document.createElement('div');
		this.awaitNotice.style.display = 'none';
		this.awaitNotice.style.visibility = 'hidden';
		this.awaitNotice.style.width = '400px';
		this.awaitNotice.style.padding = '25px';
		this.awaitNotice.style.backgroundRepeat = 'no-repeat';
		this.awaitNotice.style.backgroundPosition = '5px 5px';
		this.awaitNotice.style.fontSize = '12px';
		this.awaitNotice.style.textAlign = 'center';
		this.awaitNotice.style.position = 'absolute';
		
		document.body.appendChild(this.awaitNotice);
		document.body.appendChild(this.divNotice);
	},
	
	// выводим сообщение на экран
	showNotice: function(sType, sMessage)
	{
		this.divNotice.className = sType;
		this.divNotice.innerHTML = sMessage;
		this.divNotice.style.display = 'block';
		
		var aWorkSpaceSize = getWorkspaceSize();
		var aScrollSize = getScrollSize();
		
		this.divNotice.style.left = aScrollSize['x']+((aWorkSpaceSize['x'] - this.divNotice.offsetWidth)/2)+'px';
		this.divNotice.style.top = aScrollSize['y']+((aWorkSpaceSize['y'] - this.divNotice.offsetHeight)/2)+'px';		
		
		this.divNotice.style.visibility = 'visible';
		
		setTimeout
		(
		 	function()
			{
				oReactor.divNotice.style.visibility = 'hidden';
			},
			oReactor.iShowNoticeTime
		);
	},
	
	// выводим сообщение на экран
	displayNotice: function(sType, sMessage)
	{
		this.awaitNotice.className = sType;
		this.awaitNotice.innerHTML = sMessage;
		this.awaitNotice.style.display = 'block';
		
		var aWorkSpaceSize = getWorkspaceSize();
		var aScrollSize = getScrollSize();
		
		this.awaitNotice.style.width = '400px';
		
		this.awaitNotice.style.left = aScrollSize['x']+((aWorkSpaceSize['x'] - this.awaitNotice.offsetWidth)/2)+'px';
		this.awaitNotice.style.top = aScrollSize['y']+((aWorkSpaceSize['y'] - this.awaitNotice.offsetHeight)/2)+'px';		
		
		this.awaitNotice.style.visibility = 'visible';
	},
	
	// выводим сообщение на экран
	hideNotice: function()
	{
		this.awaitNotice.style.visibility = 'hidden';
	},
	
	// сообщаем, что в данный момент выполняется соединение
	setProcessing: function(bProcessing)
	{
		this.bProcessing = bProcessing;

		if ( bProcessing )
		{
			this.displayNotice('info', 'Подождите...');
		}
		else
		{
			this.hideNotice();
		}
	},
	
	getRequestBody: function(oForm)
	{
		var aParams = new Array();		
		aParams.push(encodeURIComponent('js')+'='+encodeURIComponent(1));
	
		for ( var i = 0; i < oForm.elements.length; i++ )
		{
			if
			(
				(oForm.elements[i].type != 'radio' && oForm.elements[i].type != 'checkbox')
				||
				(oForm.elements[i].type == 'radio' && oForm.elements[i].checked)
				||
				(oForm.elements[i].type == 'checkbox' && oForm.elements[i].checked)
			)
			{
				aParams.push(encodeURIComponent(oForm.elements[i].name)+'='+encodeURIComponent(oForm.elements[i].value));
			}
		}
	
		return aParams.join('&');
	},
	
	sendRequest: function(oForm, fnCallback)
	{
		if ( this.bProcessing ) return;
		
		try
		{
			this.setProcessing(true);
			var oXmlHttp = zXmlHttp.createRequest();

			oXmlHttp.open('post', oForm.action, true);
			oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			
			oXmlHttp.onreadystatechange = function()
			{
				try
				{
					if ( oXmlHttp.readyState == 4 )
					{
						if ( oXmlHttp.status == 200 )
						{
							fnCallback(oXmlHttp.responseText);
							oReactor.setProcessing(false);
						}
						else
						{
							throw new Error('Ошибка соединения с сервером. Запрос: '+sAction);
						}
					}
				}
				catch ( oException )
				{
					oReactor.setProcessing(false);
					oReactor.showNotice('err', oException.message);
				}
			}
			oXmlHttp.send(this.getRequestBody(oForm));
		}
		catch ( oException )
		{
			oReactor.setProcessing(false);
			oReactor.showNotice('err', oException.message);
		}
	},
	
	sendQuestion: function()
	{
		this.sendRequest(this.faqForm, showResponse);
		
		return false;
	}
}

function showResponse(sResponseText)
{
	oReactor.showNotice('info', sResponseText);
	if ( sResponseText.indexOf('принят') != -1 )
	{	
		setTimeout(function(){location.replace('index.php');}, oReactor.iShowNoticeTime);
	}
	
	return false;
}

function measuringRequest(oForm)
{
	oReactor.sendRequest(oForm, showResponse);
	
	return false;
}

var aCenterImages = new Array();

var iOffset = 20;

function imgDescInit()
{
	var aAllImages = document.images;
	
	iImageCounter = 0;
	
	for ( var i = 0; i < aAllImages.length; i++ )
	{
		if ( aAllImages[i].id.indexOf('piece') != -1 )
		{
			aAllImages[i].style.cursor = 'pointer';
			aAllImages[i].onclick = function()
			{
				if ( typeof aCenterImages[parseInt(this.id)] != 'object' )
				{
					aCenterImages[parseInt(this.id)] = new Image();
				
					var oReg = /\?name=([0-9a-zA-Z]+)/;
					var aReg = oReg.exec(this.src);

					aCenterImages[parseInt(this.id)].src = '/JpgImg.php?name='+aReg[1]+'.gif'
					+'&width='+400
					+'&height='+400
					+'&rand=0';
					
					aCenterImages[parseInt(this.id)].isLoaded = false;
				}
				
				
				var aWorkSpaceSize = getWorkspaceSize();
				var aScrollSize = getScrollSize();

				oDisplay.style.left = aScrollSize['x']+((aWorkSpaceSize['x'] - 200)/2)+'px';
				oDisplay.style.top = aScrollSize['y']+((aWorkSpaceSize['y'] - 30)/2)+'px';
				oDisplay.style.width = '200px';
				oDisplay.style.height = '30px';
				oDisplay.style.padding = '19px';
				oDisplay.innerHTML = 'Подождите...';
				oDisplay.style.display = 'block';
				oDisplay.style.visibility = 'visible';
	
				oClose = document.createElement('div');
				oClose.className = 'imgClose';
				oClose.innerHTML = 'закрыть';
				oClose.id = parseInt(this.id)+'close';

				aCenterImages[parseInt(this.id)].onload = function()
				{
					showCenterImage(this);					
					this.isLoaded = true;
				}
				
				if ( aCenterImages[parseInt(this.id)].isLoaded )
				{
					showCenterImage(aCenterImages[parseInt(this.id)]);
				}

				oClose.onclick = function ()
				{
					oDisplay.style.visibility = 'hidden';
				}
			}
		}
		iImageCounter++;
	}
}

function showCenterImage(oImage)
{
	oDisplay.innerHTML = '';
				
	var aWorkSpaceSize = getWorkspaceSize();
	var aScrollSize = getScrollSize();
					
	oDisplay.style.left = aScrollSize['x'] + (aWorkSpaceSize['x'] - oImage.width)/2+'px';
	oDisplay.style.top = aScrollSize['y'] + (aWorkSpaceSize['y'] - oImage.height)/2+'px';
		
	oDisplay.style.width = oImage.width+'px';
	oDisplay.style.height = oImage.height+'px';		
	oDisplay.style.padding = '0px';
		
	oDisplay.innerHTML = '<img src="'+oImage.src+'" width="'+oImage.width+'" height="'+oImage.height+'" />';
	oDisplay.appendChild(oClose);
}


var aRefCenterImages = new Array();
var iRefCounter = 0;

function referensInit()
{
	var aRefs = document.getElementsByTagName("a");
	var refCounter = 0;
	var tmpId = '';
	
	for ( var i = 0; i < aRefs.length; i++ )
	{
		if ( aRefs[i].id.indexOf('referens') != -1 )
		{
			aRefs[i].style.cursor = 'pointer';
			aRefs[i].name = iRefCounter + 'imageRef';
			aRefs[i].onclick = function()
			{
				if ( typeof aRefCenterImages[parseInt(this.name)] != 'object' )
				{
					aRefCenterImages[parseInt(this.name)] = new Image();
				
					var oReg = /([0-9]+)referens([0-9]+)/;
					var aReg = oReg.exec(this.id);

					aRefCenterImages[parseInt(this.name)].src = '/JpgImg.php?name='+aReg[2]+'piece'+aReg[1]+'.gif&nocache='+Math.floor(Math.random()*1000000);
					
					aRefCenterImages[parseInt(this.name)].isLoaded = false;
				}
				
				
				var aWorkSpaceSize = getWorkspaceSize();
				var aScrollSize = getScrollSize();

				oDisplay.style.left = aScrollSize['x']+((aWorkSpaceSize['x'] - 200)/2)+'px';
				oDisplay.style.top = aScrollSize['y']+((aWorkSpaceSize['y'] - 30)/2)+'px';
				oDisplay.style.width = '200px';
				oDisplay.style.height = '30px';
				oDisplay.style.padding = '19px';
				oDisplay.innerHTML = 'Подождите...';
				oDisplay.style.display = 'block';
				oDisplay.style.visibility = 'visible';
	
				oClose = document.createElement('div');
				oClose.className = 'imgClose';
				oClose.innerHTML = 'закрыть';
				oClose.id = refCounter+'close';

				aRefCenterImages[parseInt(this.name)].onload = function()
				{
					showCenterImage(this);					
					this.isLoaded = true;
				}
				
				if ( aRefCenterImages[parseInt(this.name)].isLoaded )
				{
					showCenterImage(aRefCenterImages[parseInt(this.name)]);
				}

				oClose.onclick = function ()
				{
					oDisplay.style.visibility = 'hidden';
				}
				
				return false;
			}
			iRefCounter++;
		}
	}
}

oCalcHouse =
{
	oHousePosition: new Object(),
	
	init: function()
	{
		this.oHousePosition = getElementPosition(oReactor.calcHouse);
		oReactor['house0'].style.left = this.oHousePosition.left + 'px';
		oReactor['house0'].style.top = this.oHousePosition.top + 'px';
		
		oReactor['house0'].style.visibility = 'visible';
		oReactor['house0'].style.display = 'block';
		
		oReactor['calculate'].focus();
		
		this.hideAdditionals();
		
		oReactor.restartLink.onclick = function()
		{
			oCalcHouse.restart();
			
			return false;
		}
	},
	
	restart: function()
	{
		oReactor.priceDiv.style.visibility = 'hidden';
		oReactor.priceDiv.style.display = 'none';
		oReactor.calcForm.disabled = false;
		oReactor.calcForm.style.visibility = 'visible';
		oReactor.calcForm.style.display = 'block';
		oReactor.measuringForm.disabled = true;
		oReactor.measuringForm.style.visibility = 'hidden';
		oReactor.measuringForm.style.display = 'none';
	},
	
	hideAdditionals: function()
	{
		for ( var i = 1; i < 9; i++ )
		{
			if ( typeof oReactor[('house'+i)] == 'object' )
			{
				oReactor[('house'+i)].style.visibility = 'hidden';
				oReactor[('house'+i)].style.display = 'none';
			}
		}
	},
	
	showAdditional: function(iNumber)
	{
		this.hideAdditionals();
		
		if ( typeof oReactor['house'+iNumber] != 'object' ) return;
		
		oReactor['house'+iNumber].style.left = this.oHousePosition.left + 'px';
		oReactor['house'+iNumber].style.top = this.oHousePosition.top + 'px';
		
		oReactor['house'+iNumber].style.visibility = 'visible';
		oReactor['house'+iNumber].style.display = 'block';
	},
	
	sendRequest: function(oForm)
	{
		oReactor.sendRequest(oForm, showCalcResponse);
	
		return false;
	}
}

function showCalcResponse(sResponseText)
{
	if ( sResponseText == '-1' )
	{
		oReactor.showNotice('info', '<font style="color:#FF0000; font-weight:bold; text-transform:uppercase;">Расчет с такими параметрами невозможен!</font>');
		oReactor.calcForm.disabled = false;
		
		return false;
	}
	
	aPrice = eval(sResponseText);
	
	oReactor.calcForm.disabled = true;
	oReactor.calcForm.style.visibility = 'hidden';
	oReactor.calcForm.style.display = 'none';
	
	oReactor.priceDiv.style.visibility = 'visible';
	oReactor.priceDiv.style.display = 'block';
	
	oReactor.priceDiv.innerHTML = 
	'Стоимость системы без учета монтажа: '
	+ aPrice[1]
	+ 'руб.<br />\nСтоимость системы с учетом монтажа: '
	+ aPrice[0]+ 'руб.';

	oReactor.measuringForm.disabled = false;
	oReactor.measuringForm.style.visibility = 'visible';
	oReactor.measuringForm.style.display = 'block';
}

window.onload = function()
{
	theObjects = document.getElementsByTagName("object");
	for (var i = 0; i < theObjects.length; i++)
	{
		theObjects[i].outerHTML = theObjects[i].outerHTML;
	}
	
	oDisplay = document.createElement('div');
	oDisplay.className = 'imgDisplay';
	document.body.appendChild(oDisplay);
	
	referensInit();
	oReactor.init();
	imgDescInit();
	
	if ( typeof oReactor.calcHouse == 'object' )
	{
		oCalcHouse.init();
	}
}

