var ajax = 0;
var timeout_id;

var sFadeStartColor = "#b15821";  //начальный цвет (белый) 
var sFadeFinishColor = "#d7e4d7"; //конечный цвет (оранжево-красный)

//разбиваем RGB-триплеты на красный, зеленый и синий в виде массива
var aRGBStart = sFadeStartColor.replace("#","").match(/.{2}/g); 
var aRGBFinish = sFadeFinishColor.replace("#","").match(/.{2}/g);

var f_t = 10; //t - время задержки в миллисекундах 
/* n - количество промежуточных цветов, включая конечный 
(т.е. между начальным и конечным цветами будет n-1 цвет) */
var f_n = 500;

var f_i = 0; //индекс текущего промежуточного цвета 


//----------------------------------------------------------------------------------------------------------------------------------

var addListener = function() 
{ 
    if ( window.addEventListener )
    { 
        return function(el, type, fn) 
               { 
                   el.addEventListener(type, fn, false); 
               }; 
    } else if ( window.attachEvent ) 
    { 
        return function(el, type, fn) 
               { 
                   var f = function() 
                   { 
                       fn.call(el, window.event); 
                   }; 
                   el.attachEvent('on'+type, f); 
               }; 
    } else 
    { 
        return function(el, type, fn) 
        { 
            element['on'+type] = fn; 
        } 
    } 
}();



//----------------------------------------------------------------------------------------------------------------------------------

addListener(window, 'load', init);

//----------------------------------------------------------------------------------------------------------------------------------

function init()
{
	addListener(document.getElementById('li_home'), 'mouseover', active_menu);
	addListener(document.getElementById('li_home'), 'mouseout', inactive_menu);
	addListener(document.getElementById('li_menu1'), 'mouseover', active_menu);
	addListener(document.getElementById('li_menu1'), 'mouseout', inactive_menu);
	addListener(document.getElementById('li_menu2'), 'mouseover', active_menu);
	addListener(document.getElementById('li_menu2'), 'mouseout', inactive_menu);
	addListener(document.getElementById('li_menu3'), 'mouseover', active_menu);
	addListener(document.getElementById('li_menu3'), 'mouseout', inactive_menu);
	addListener(document.getElementById('li_menu4'), 'mouseover', active_menu);
	addListener(document.getElementById('li_menu4'), 'mouseout', inactive_menu);
	addListener(document.getElementById('li_forum'), 'mouseover', active_menu);
	addListener(document.getElementById('li_forum'), 'mouseout', inactive_menu);
	addListener(document.getElementById('li_download'), 'mouseover', active_menu);
	addListener(document.getElementById('li_download'), 'mouseout', inactive_menu);
	
	screen_h = getClientHeight();
	
	
	
	
    if (document.getElementById('idmain').clientHeight < screen_h)
	{  	
		document.getElementById('idfill').style.height = (screen_h - document.getElementById('idmain').clientHeight) + 'px';
	}
	else
		document.getElementById('idmain').style.height = 'auto';
}

//----------------------------------------------------------------------------------------------------------------------------------

function active_menu()
{
	//alert(this.className);
	if ( (this.id == 'li_home') && !(this.className == 'active') )
		document.getElementById('li_home').style.background = 'url("http://ruslang.ostu.ru/images/amenu1.gif")';
	else if ( (this.id == 'li_menu1') && !(this.className == 'active') )
		document.getElementById('li_menu1').style.background = 'url("http://ruslang.ostu.ru/images/amenu2.gif")';
	else if ( (this.id == 'li_menu2') && !(this.className == 'active') )
		document.getElementById('li_menu2').style.background = 'url("http://ruslang.ostu.ru/images/amenu3.gif")';
	else if ( (this.id == 'li_menu3') && !(this.className == 'active') )
		document.getElementById('li_menu3').style.background = 'url("http://ruslang.ostu.ru/images/amenu4.gif")';
	else if ( (this.id == 'li_menu4') && !(this.className == 'active') )
		document.getElementById('li_menu4').style.background = 'url("http://ruslang.ostu.ru/images/amenu7.gif")';
	else if ( (this.id == 'li_forum') && !(this.className == 'active') )
		document.getElementById('li_forum').style.background = 'url("http://ruslang.ostu.ru/images/amenu5.gif")';
	else if ( (this.id == 'li_download') && !(this.className == 'active') )
		document.getElementById('li_download').style.background = 'url("http://ruslang.ostu.ru/images/amenu6.gif")';
}

//----------------------------------------------------------------------------------------------------------------------------------

function inactive_menu()
{
	if ( (this.id == 'li_home') && !(this.className == 'active') )
		document.getElementById('li_home').style.background = 'url("http://ruslang.ostu.ru/images/menu1.gif")';
	else if ( (this.id == 'li_menu1') && !(this.className == 'active') )
		document.getElementById('li_menu1').style.background = 'url("http://ruslang.ostu.ru/images/menu2.gif")';
	else if ( (this.id == 'li_menu2') && !(this.className == 'active') )
		document.getElementById('li_menu2').style.background = 'url("http://ruslang.ostu.ru/images/menu3.gif")';
	else if ( (this.id == 'li_menu3') && !(this.className == 'active') )
		document.getElementById('li_menu3').style.background = 'url("http://ruslang.ostu.ru/images/menu4.gif")';
	else if ( (this.id == 'li_menu4') && !(this.className == 'active') )
		document.getElementById('li_menu4').style.background = 'url("http://ruslang.ostu.ru/images/menu7.gif")';
	else if ( (this.id == 'li_forum') && !(this.className == 'active') )
		document.getElementById('li_forum').style.background = 'url("http://ruslang.ostu.ru/images/menu5.gif")';
	else if ( (this.id == 'li_download') && !(this.className == 'active') )
		document.getElementById('li_download').style.background = 'url("http://ruslang.ostu.ru/images/menu6.gif")';

}

//----------------------------------------------------------------------------------------------------------------------------------

function savedoc(link, id)
{
	post='id='+id;
	makeRequest1('save_doc.php',post);
	location.href=link;
}

//----------------------------------------------------------------------------------------------------------------------------------

function makeRequest1(url, arg)
{
	var http_request = false;

	if (window.XMLHttpRequest) 
	{ // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) 
		{
			http_request.overrideMimeType('text/xml');
            // Читайте ниже об этой строке
    	}
	} 
	else if (window.ActiveXObject) 
	{ // IE
		try 
		{
			http_request = new ActiveXObject('Msxml2.XMLHTTP');
		} 
		catch (e) 
		{
			try 
			{
				http_request = new ActiveXObject('Microsoft.XMLHTTP');
			} 
			catch (e)
			{
		
			}
		}
	}

	if (!http_request) 
	{
		alert('Не вышло :( Невозможно создать экземпляр класса XMLHTTP ');
		return false;
	}

	http_request.open('POST', url, true);
	http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=Windows-1251');
	http_request.send(arg);
}	

//----------------------------------------------------------------------------------------------------------------------------------

function makeRequest(url, arg)
{
	var http_request = false;

	if (window.XMLHttpRequest) 
	{ // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) 
		{
			http_request.overrideMimeType('text/xml');
	            // Читайте ниже об этой строке
    	}
	} 
	else if (window.ActiveXObject) 
	{ // IE
		try 
		{
			http_request = new ActiveXObject('Msxml2.XMLHTTP');
		} 
		catch (e) 
		{
			try 
			{
				http_request = new ActiveXObject('Microsoft.XMLHTTP');
			} 
			catch (e)
			{
			}
		}
	}

	if (!http_request) 
	{
		alert('Не вышло :( Невозможно создать экземпляр класса XMLHTTP ');
		return false;
	}
    
	http_request.onreadystatechange = function() 
	{
		alertContents(http_request); 
	};
	http_request.open('POST', url, true);
	http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=Windows-1251');
	http_request.send(arg);
}

//----------------------------------------------------------------------------------------------------------------------------------

function alertContents(http_request) 
{
	if (http_request.readyState == 4) 
	{
		if (http_request.status == 200)
		{
			xmldoc = http_request.responseXML;			 
		}
		else
		{
			alert('С запросом возникла проблема.');
		}
 
		try
		{
			document.getElementById('mapimg').src='images/geo_map_'+xmldoc.getElementsByTagName('map')[0].childNodes[0].nodeValue+'.gif';
		
			count=xmldoc.getElementsByTagName('countarea')[0].childNodes[0].nodeValue;
		
			var objMap=document.getElementById('igm');
		
			while (objMap.childNodes.length)
			{
				objMap.removeChild(objMap.firstChild);
			}
		
			document.getElementById('igm').innerHTML='';
	
			res_str='';		
		
			for (i=0; i<count; i++)
			{
				shape=xmldoc.getElementsByTagName('shape')[i].childNodes[0].nodeValue;
				title=xmldoc.getElementsByTagName('title')[i].childNodes[0].nodeValue;
				coords=xmldoc.getElementsByTagName('coords')[i].childNodes[0].nodeValue;
				action=xmldoc.getElementsByTagName('action')[i].childNodes[0].nodeValue;
	
				str='<area id="ar'+i+'" ';
				str+='shape="'+shape+'" ';
				str+='alt="'+title+'" ';
				str+='coords="'+coords+'"  ';
				str+='onclick="'+action+'" ';
				str+='onmouseover="hand_on();" ';
				str+='onmouseout="hand_off();"  />';
			
				res_str+=str;
			}

			document.getElementById('igm').innerHTML=res_str;

			document.body.style.cursor='default';
			parent1=xmldoc.getElementsByTagName('parent')[0].childNodes[0].nodeValue;

			if (parent1!='-')
			{
				document.getElementById('itdhidden').innerHTML='<a href="javascript:zoom_img('+parent1+')" style=" color:red; ">увеличить';
			}
			else
			{	
				document.getElementById('itdhidden').innerHTML='';
			}
		}
		catch(e)
		{
		} 
	}    
}

//----------------------------------------------------------------------------------------------------------------------------------

function getClientHeight()
{
	return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

//----------------------------------------------------------------------------------------------------------------------------------

function hand_on()
{
	document.body.style.cursor='pointer';
}

//----------------------------------------------------------------------------------------------------------------------------------

function hand_off()
{
	document.body.style.cursor='default';
}

//----------------------------------------------------------------------------------------------------------------------------------

function zoom_on()
{
	asd='url(../images/plus.cur)';
	document.body.style.cursor='pointer';
}

//----------------------------------------------------------------------------------------------------------------------------------

function zoom_off()
{
	document.body.style.cursor='default';
}

//----------------------------------------------------------------------------------------------------------------------------------

function zoom_img1(map)
{
	post='map_id = '+map; 
	makeRequest('ajax_map.php', post);
}

//----------------------------------------------------------------------------------------------------------------------------------

function about_area(obj, arg)
{
	document.getElementById('itd_title').innerHTML = '<div id="idback"><div id="idcaption" style="opacity:1">' + obj + '</div></div>';
	
	document.getElementById('idback').style.backgroundColor = '#ff8900';
//	document.getElementById('idback').style.opacity = '1';
//	alert(document.getElementById('idback'));
//	fade(document.getElementById('idback'), 'fadeRule1');
	
	var c = arg.length;
	for (var i = 0; i < c; i++)
	{
		document.getElementById('id_arg_' + i).innerHTML = arg[i];
	}
	
	clearTimeout(timeout_id);
	document.getElementById('idback').style.backgroundColor = '#b15821';
//	alert('test');
	f_i = 0; 
 

	
	fade();
	
//	setTimeout('down_op()', 100);
}

//----------------------------------------------------------------------------------------------------------------------------------

function fade()
{
	f_i++; //изменяем индекс промежуточного цвета
		  
	//присвоить в качестве фонового цвета кнопки i-тый цвет
	document.getElementById('idback').style.backgroundColor = getFadeMiddleColor();
		  
	/* если ещё не перебраны все промежуточные цвета,
	то вызвать fade() через t миллисекунд опять */
	if ( f_i < f_n ) 
		timeout_id = setTimeout(fade, f_t);  
} 


//----------------------------------------------------------------------------------------------------------------------------------

function getFadeMiddleColor() 
{
	
	/*процент содержания конечного цвета в текущем промежуточном цвете;
	изменяется от 0 (не включая 0) до 1 (1 = 100%)*/
	var finishPercent = f_i / f_n;
	/*процент содержания начального цвета в текущем промежуточном цвете;
	изменяется от 1 до 0 (1 = 100%) */
	var startPercent = 1 - finishPercent;
	  
	var R,G,B;
	  
	//вычисляем значения красного, зеленого, синего промежуточного цвета
	R = Math.floor( ('0x'+aRGBStart[0]) * startPercent + ('0x'+aRGBFinish[0]) * finishPercent );
	G = Math.floor( ('0x'+aRGBStart[1]) * startPercent + ('0x'+aRGBFinish[1]) * finishPercent );
	B = Math.floor( ('0x'+aRGBStart[2]) * startPercent + ('0x'+aRGBFinish[2]) * finishPercent );
	  
	return 'rgb('+R+ ',' + G + ',' + B +')';

}

//----------------------------------------------------------------------------------------------------------------------------------

function down_op()
{
	var op;
	
	if (document.all)
	{
		
	}
	else
	{
		op = document.getElementById('idback').style.opacity;
		op -= 0.01;
		document.getElementById('idback').style.opacity = op;
		
	}
	
	
	
	if (op > 0)
		setTimeout('down_op()', 20);
	
	document.getElementById('idcaption').style.opacity = '1';
	
}


//----------------------------------------------------------------------------------------------------------------------------------

function zoom_img(map)
{	
	if (ajax)
	{
		alert("Выполняется предыдущий запрос");
		return;
	}
	
    var req = new Ajax.Request('./ajax_index.php?p=get_area', 
    		{
				method: 'post',
				parameters:
				{
    				map_id: map
				},
				encoding: 'cp1251',
				onSuccess: function (t) {
											ajax = 0;
											
											response_map(t);
										},
				onFailure: function (t) {
											ajax = 0;
											alert('error');
										}
			}
          );
}

//----------------------------------------------------------------------------------------------------------------------------------

function response_map(t)
{
	xmldoc = t.responseXML;			 

	try
	{
		document.getElementById('mapimg').src='http://ruslang.ostu.ru/images/maps/geo_map_'+xmldoc.getElementsByTagName('map')[0].childNodes[0].nodeValue+'.gif';

		count=xmldoc.getElementsByTagName('countarea')[0].childNodes[0].nodeValue;
		
		var objMap=document.getElementById('igm');

		while (objMap.childNodes.length)
		{
			objMap.removeChild(objMap.firstChild);
		}

		document.getElementById('igm').innerHTML='';
		
		res_str='';		

		for (i=0; i<count; i++)
		{
			shape=xmldoc.getElementsByTagName('shape')[i].childNodes[0].nodeValue;
			title=xmldoc.getElementsByTagName('title')[i].childNodes[0].nodeValue;
			coords=xmldoc.getElementsByTagName('coords')[i].childNodes[0].nodeValue;
			action=xmldoc.getElementsByTagName('action')[i].childNodes[0].nodeValue;

			str='<area id="ar'+i+'" ';
			str+='shape="'+shape+'" ';
			str+='alt="'+title+'" ';
			str+='coords="'+coords+'"  ';
			str+='onclick="'+action+'" ';
			str+='onmouseover="hand_on();" ';
			str+='onmouseout="hand_off();"  />';
	
			res_str+=str;
		}

		document.getElementById('igm').innerHTML=res_str;

		document.body.style.cursor='default';
		parent1=xmldoc.getElementsByTagName('parent')[0].childNodes[0].nodeValue;

		if (parent1!='-')
		{
			document.getElementById('idhidden').innerHTML='<a href="javascript:zoom_img('+parent1+')" style="color:#2c512f; font:bold 0.9em Verdana,sans-serif">Уменьшить';
		}
		else
		{	
			document.getElementById('idhidden').innerHTML='';
		}
	}
	catch(e)
	{
		alert(e);
	} 
}


//----------------------------------------------------------------------------------------------------------------------------------



//----------------------------------------------------------------------------------------------------------------------------------
