var moved = 0;
var q_t1 = '';
var page_id = '';
var q_t2 = '';
var sort = '';
var sorted ='';
var functionadvmove='';
var functionadresize='';
var isMSIE = navigator.userAgent.indexOf('MSIE') >= 0;
// Обявляем глобальный массив для хранения индекса масштабирования
array_index_scalar = [];
// Обявляем глобальный массив для хранения xml масштабирования
array_data_xml = [];
array_swf_name_file = [];
array_mq_id = [];
arrayWidthDialog = [];
arrayHeightDialog = [];

var GridSettings =
{
	UseAnimation: true,
	AutoHideScrollbars: true,
	//CellChangedCallback: "App.onCellChanged",
	Caption: "",
	SubCaption: "",
	UseScrollingToVisible: true,
	//Selection: "1,1,3,1",
	UseFullWidthScrollbars: true,
	UseRowResizing: true,
	UseColumnResizing: true,
	ShowHorizontalGridLine: true,
	ShowVerticalGridLine: true,
	UseSmoothScrolling: true,
	IsUndoAllVisible: false,
	//XmlData: '',
	SelectionChangedCallback: ""//App.selectionChange",
	//UseRowHeightCalculationAfterEdit: true,
	//PleaseWaitBannerUrl: "../Images/intro_test.png"
	//LoadXmlCompletedCallback: "App.onLoadXmlCompleted",
}

function zxc1(){
alert("zxc1");

}

function zxc(){
alert("zxc");
document.getElementById('qwera').title = "zxc1(); return false;"; 
}

function showSpisok (id){
	if(document.getElementById('s'+id).style.display=="none"){
		document.getElementById('s'+id).style.display='block';
	} else {document.getElementById('s'+id).style.display='none';}
	if(document.getElementById('lastId').value != id){
		var lastId = document.getElementById('lastId').value;
		document.getElementById('s'+lastId).style.display='none';
		document.getElementById('lastId').value=id;
	}
 }
	var BComboManager = new ComboManager('TreeElemID', 'TreeCaption');
/*--------------------------------------------------------вспомогательные-------------------------------------------------------------------------*/
if (isMSIE){
    document.attachEvent('onkeypress', new Function ("if((event.ctrlKey) && ((event.keyCode==10)||(event.keyCode==13))) {ShowTT()} if(event.keyCode == 27){HideTT();}"));
}
else{
	document.documentElement.onkeypress = function (event) {
		if((event.ctrlKey) && ((event.which==10)||(event.which==13))) { ShowTT(); } 
		if(event.which == 27) { HideTT(); }
	}
}

function getId(id)
{
	var tmp = document.getElementById(id)
    return tmp;
}

function gup( name ){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
	{
		return "";
	}else{
		return results[1];
	}
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
	c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function implode( glue, pieces ){    // Join array elements with a string
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: _argos
 
    return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
}

function savexmlcookie(xml_id, value, text)
{
	
	if (xml_id)
	{
		setCookie ('xml_select_'+xml_id, value);
	}
	

	select_xml_add_to_log(text);
	
	/*if (text)
	{
		
		add_to_log(page_id, text, 14);
	}*/
}

function select_xml_add_to_log(text)
{
	if (text)
	{
		add_to_log(page_id, text, 14);
	}
}

function add_to_log(page_id, text, type)
{
	downloadPage('ajax.php', 'ajax=addtolog&type='+type+'&pageid='+page_id+'&mq_id='+gup('mq_id')+'&text='+text, 'hidden_content', '', "", 0, 0,13,1,1,0);
}

function reload_analiz_table (id_terr)
{
	reloadxmls('1102', id_terr);
}

// обновление XML из списка  xmlids через запятую.
// id слоя должен быть равен id xml
function reloadxmls (xmlids, newvalue, pda, setcookies)
{
	xmlids.replace(' ',''); // убираем пробелы
	ids = xmlids.split(','); // все слои через запятую

	if (pda == undefined)
	{
		pda = "0";
	}
	if (setcookies == undefined)
	{
		setcookies = 1;
	}
	
	if (ids.length > 1) // если слоев больше одного
	{
			
		id = ids.shift();
		str = ids.join(',');
		if (setcookies)
		{
			setCookie ('xml_'+id, newvalue);
		}
		if (getId('xml_' + id)) {
			downloadPage('ajax.php', 'ajax=xml2&xmlid=' + id + "&mq_id=" + newvalue + "&pda=" + pda, 'xml_' + id, '',
						"reloadxmls ('" + str + "', '" + newvalue + "', '" + pda + "');", 0, 0, 13, 0, 0,1);
		} else {
		    reloadxmls(str, newvalue);
		}
	}else{
	//alert(newvalue);
		if (setcookies)
		{
			setCookie ('xml_'+ids, newvalue);
		}
		if (getId('xml_'+ids))
		{
			downloadPage('ajax.php', 'ajax=xml2&xmlid='+ids+"&mq_id="+newvalue+"&pda="+pda, 'xml_'+ids, '','', 0, 0,13,0,0,1);
		}
	}
}


Array.prototype.join = Array.prototype.join = Array.prototype.join || function(separator){
	var result = '';
	for(var i=0; i < this.length; i++){
		if (i==0) {result += this[i];}
		else {result += separator + this[i];}
	}
	return result;
}

function savexmlcookies(xmlids, newvalue)
{
	xmlids.replace(' ',''); // убираем пробелы
	ids = xmlids.split(','); // все слои через запятую
	if (ids.length > 1) // если слоев больше одного
	{
		id = ids.shift();
		ids = implode(',', ids);
		setCookie ('xml_'+id, newvalue);
		savexmlcookies(ids, newvalue);
	}else{
		setCookie ('xml_'+ids, newvalue);
	}
}


/*-------------------------------------------------------конец-вспомогательных-------------------------------------------------------------------------*/
//для npa_region.php при клики на slgrid таблицу будет загружаться документ
function OpenNPADocument (id)
{
	top.location.href = 'npadocument.php?doc_id='+id;
}
//для паспорта ГРБС
function GoToUslugiGrbs (grbsId)
{
	setCookie('grbsid', grbsId);
	/*паспорт ГРБС*/
	setCookie('type_144', '223');
	top.location.href = 'passportgrbs.php';
}

function Export (page_id, type)
{
	window.location = "export.php?page_id="+page_id+"&type_export="+type+"&rnd"+(Math.random())
}

function Export_original (page_id, type)
{
	window.location = "export.php?page_id="+page_id+"&type_export="+type+"&rnd"+(Math.random())
}


//для finance_dynamic
function cookie_plus_xml__reload(xml_id, value, cookie_name)
{
	cookie_value='';
	if (getCookie(cookie_name))
	{
		cookie_value = getCookie(cookie_name);
	}
	value = cookie_value+'||'+value;
	reloadxmls(xml_id,value);
}

//для region_diagr.php и region_map.php
function UpdateDates(value)
{
	if (getId('xml_1371'))
	{
		setCookie('xml_1371', value);
		downloadPage('ajax.php', 'ajax=xml2&xmlid=1371&mq_id='+value, 'xml_1371', '', "UpdateChartAndMap()", 0, 0,13,0,0,1);
	}else{
		reloadxmls('1369,1384',value);
	}
}


//для region_diagr.php и region_map.php
function UpdateChartAndMap()
{
	indicator = '';
	date = '';
	if (getId('select_1368'))
	{
		indicator = getId('select_1368').value;
	}
	
	if (getId('select_1371'))
	{
		date = getId('select_1371').value;
	}
	if(!indicator || !date)
	{
		alert('Необходимо указать все параметры');
	}else{
		//alert(indicator + '|' + date);
		reloadxmls ('1372,1370,1373,1374', indicator + '|' + date);
	}
}



//для fbdohgad.php
function UpdateIncomeCodes(value)
{
	setCookie('xml_1585',value);
	savexmlcookie('1583', '', '');
	

	downloadPage('ajax.php', 'ajax=xml2&xmlid=1583&mq_id='+value, 'xml_1583', '', "UpdateGADGrid()", 0, 0,13,0,0,0);
	//downloadPage('ajax.php', 'ajax=xml2&xmlid=1583&mq_id='+value, 'xml_1583', '', "UpdateGADGrid();", 0, 0,13,0,0,0);
}

//для fbdohgad.php
function UpdateGADGrid()
{
	admcode = '';
	inccode = '';
	if (getId('select_1582'))
	{
		admcode = getId('select_1582').value;
	}
	
	if (getId('select_1583'))
	{
		inccode = getId('select_1583').value;
	}
	if(!admcode || !inccode)
	{
		alert('Необходимо указать все параметры');
	}else{
		//alert(admcode + '|' + inccode);
		//setTimeout('', 300);
		
		reloadxmls ('1585', admcode + '|' + inccode);
//		setCookie('xml_1585','');
	}
}

//для worldecon.php и его внутрених страниц
//обновление нескольких слоев в качестве value - текущий элемент вставляется первым
function refresh1 (divids, value, xml_id, id_adv_value, id_adv_value2)
{
	var adv_value = '';
	var adv_value2= ''; // Значения для дополнительных переменных
	var ret_m_q; //значение, которое будет возвращено
	ids = divids.split(','); // все слои через запятую
	setCookie ('xml_'+xml_id, value); // сохранили выбранный параметр текущей XML

	if (id_adv_value && id_adv_value != '' && id_adv_value != 'undefined')
	{
		if (getId('select_'+id_adv_value))
		{
			adv_value = getId('select_'+id_adv_value).value;
			if (adv_value.indexOf('|'))
			{
				adv_value = adv_value.split('|')[1];
			}
		}else{
			if(getCookie('xml_'+id_adv_value))
			{
				adv_value = getCookie('xml_'+id_adv_value); 
			}else{
				adv_value = '';
			}
		}
	}
	
	if (id_adv_value2 && id_adv_value2 != '' && id_adv_value2 != 'undefined')
	{
		if (getId('select_'+id_adv_value2))
		{
			adv_value2 = getId('select_'+id_adv_value2).value;
		}else{
			if(getCookie('xml_'+id_adv_value2))
			{
				adv_value2 = getCookie('xml_'+id_adv_value2);
			}else{
				adv_value2 = '';
			}
		}
	}
	if (adv_value2 && adv_value2.indexOf('|'))
	{
		adv_value2 = adv_value2.split('|')[1];
	}

	if (adv_value && adv_value.indexOf('|'))
	{
		adv_value = adv_value.split('|')[1];
	}
	
	ret_m_q = value+'|'+adv_value+((adv_value2)?'|'+adv_value2:'');
	if (ids.length > 1) // если слоев больше одного
	{
		id = ids.shift();
		ids = implode(',', ids);
		setCookie ('xml_'+id, ret_m_q);
		if (getId(id))
		{
			downloadPage('ajax.php', 'ajax=xml2&xmlid='+id+"&mq_id="+ret_m_q, id, '',
						'refresh1 (\''+ids+'\', \''+value+'\', \''+xml_id+'\', \''+id_adv_value+'\', \''+id_adv_value2+'\')', 0, 0,13,0,0,1);
		}else{
			refresh1 (ids,value,xml_id,id_adv_value, id_adv_value2);
		}
	}else{
		setCookie ('xml_'+ids, ret_m_q);
		if (getId(ids))
		{
			downloadPage('ajax.php', 'ajax=xml2&xmlid='+ids+"&mq_id="+ret_m_q, ids, '',
						'sorttable.init()', 0, 0,13,0,0,1);
		}else{
		//	sorttable.init();
		}
	}
}




//при клике на карту
function WorldMapRegionInfo(regionId)
{
	downloadPage('ajax.php', 'ajax=redirect2&flashregion='+regionId, 'hidden_content', '', 1, 1, 1, 5,1);
}



//для списка субъектов
function RegionSelectionManager(){
	this.lastSelected = null;
	this.pageId = null;
	this.selectRegion = function(obj, regionId){
		if (this.lastSelected == obj)
			return;
		
		if (this.lastSelected && (this.lastSelected != null)){
			this.lastSelected.className = 'subject_td';
				if (this.lastSelected.parentNode != undefined)
				{
					this.lastSelected.parentNode.className = 'subject_td';
				}
		}
		
		if (typeof obj == 'string')
		{
			obj = document.getElementById(obj);
		}
		
		obj.parentNode.className ='subject_td_selected';
		this.lastSelected.parentNode.className = 'subject_td';
		obj.parentNode.className ='subject_td_selected'; 
		this.lastSelected = obj;
		
		this.downloadContent(regionId);
	}
	
	this.downloadContent = function(regionId){
		date = '';
		setCookie('xml_1578', regionId);
		date = getCookie('regions_compare_date');
		
		if ( getCookie('type_44') == '108_114')
		{
		
			//date = getCookie('regions_compare_date');
			setCookie('xml_1182', regionId+'|'+date);
		}else{
			setCookie('xml_1182', '');
		}
		
		data = '';
		
		if (getCookie('xml_select_1191'))
		{
			data = getCookie('xml_select_1191');
		}
		
		ukaz_data='';
		if (getCookie('xml_select_1654'))
		{
			ukaz_data=getCookie('xml_select_1654');
		}
		setCookie('russiaregionid', regionId);
		
		if (data)
		{
			setCookie('xml_1194', regionId+'||'+data);
			setCookie('xml_1578', regionId+'||'+data);
		}

		if (ukaz_data)
		{
			setCookie('xml_1653', regionId+'|'+ukaz_data);
		}
		downloadPage('passportr.php', 'mq_id='+regionId/*+(date?'|'+date:'')*/+'&nobody=1&text=Выбран регион '+this.lastSelected.innerHTML+'&addtolod_action=15', 'inner_page', '', "", 0, 0, 0,1,0,1);
	}
	
	this.RegionRF_Info = function(regionId){
		date = '';
		text = $("#"+regionId).text();
		if (getCookie('regions_compare_date') && getCookie('type_44') == '108_114')
		{
			date = getCookie('regions_compare_date');
			//alert(date);
		}

		downloadPage('passportr.php', 'mq_id='+regionId+(date?'|'+date:'')+'&nobody=1&text=Выбран регион '+text+'&addtolod_action=15', 'inner_page', '', "", 0, 0, 0,1,0,1);
		setCookie('russiaregionid', regionId);

	}
}
/*
function RegionRF_Info(regionId)
{
	date = '';
	if (getCookie('regions_compare_date') && getCookie('type_44') == '108_114')
	{
		date = getCookie('regions_compare_date');
	}

	top.location.href='passportr.php?mq_id='+regionId+(date?'|'+date:'');
	setCookie('russiaregionid', regionId);

}
*/
//для списка ГРБС
function GrbsSelectionManager(){
	this.lastSelected = null;
	this.pageId = null;
	this.typeGrbs = null;
	this.selectGrbs = function(obj, grbsId){
		savexmlcookie('1235', ''); 

		
		
		if (this.lastSelected == obj)
			return;
		
		if (this.lastSelected && (this.lastSelected != null)){
			this.lastSelected.style.fontWeight = 'normal';
		}
		if (typeof obj == 'string') 
			obj = document.getElementById(obj);
		obj.style.fontWeight = 'bolder';
		obj.style.fontSize = '8pt';
		this.lastSelected = obj;
		
		
		this.downloadContent(grbsId);
		
	}
	
	this.downloadContent = function(){
		alert(this.typeGrbs);
	}
	
	this.setTypeGrbs = function(typeGrbs)
	{
		this.typeGrbs = typeGrbs;
		if (this.typeGrbs == 1)
		{
			
			this.downloadContent = function(grbsId){
				setCookie ('xml_1647','');
				setCookie ('xml_1648','');
				setCookie ('xml_1303678','');
				UpdateGRBSPage(this, grbsId, 1);
			}
		}else if (this.typeGrbs == 2)
		{
			this.downloadContent = function(grbsId){
				date = '';
				
				if (getCookie('xml_select_1235'))
				{
					date = getCookie('xml_select_1235');
				}
				
				value = grbsId+(date?'|'+date:'');
				
				setCookie('grbsid', grbsId);
				reloadxmls('1387,1388,1390,1391,1392',value);
				add_to_log(page_id, 'Выбран ГРБС '+this.lastSelected.innerHTML, 15);
			}
		}
	}
}

//поиск по листу grbs
function SearchGrbs(value)
{
	value = value.replace('"','');
	value = value.replace('\\','');
	UpdateGrbsTable(value);
	/*if (value){
	clearTimeout(window.GRBSTimeout);
	if (window.GRBSSearchValue != value)
	{
		window.GRBSSearchValue = value;
		window.GRBSTimeout = setTimeout('UpdateGrbsTable("' + value + '");', 300);
	}
	}*/
	clearInterval(window.iIntervalID);
}

function setIntervalSearchGrbs(value)
{
	//alert(1);
	window.iIntervalID = setInterval("SearchGrbs('"+value+"');", 500);
}

//обновление списка ГРБС при поиске
function UpdateGrbsTable(value)
{
	downloadPage('ajax.php', 'ajax=grbstable&text='+value, 'list_grbs_table', '', '', 0, 0,13,0,0,0);
}


// для fbrashgrbs.php
function UpdateGRBSPage (obj, grbsId, download_page)
{
	date = '';
	value = grbsId;
	//добавляем куки для всех объектов
	savexmlcookies ('1230,1233,1234,1195,1230,1231,1232,1244,1245,1484,1478,1479,1480,1481,1482,1483,1553,1552,1551,1550,1549,1548,1565,1647,1648',value);
	setCookie('grbsid', grbsId);
	if (download_page)
	{
		name_grbs = obj.lastSelected.innerHTML.replace("'",'"');
		name_grbs = name_grbs.replace("'",'"');
		downloadPage('passportgrbs.php', 'mq_id='+value+'&nobody=1&text=Выбран ГРБС '+name_grbs+'&addtolod_action=15', 'inner_page', '', "", 0, 0, 0, 0, 0, 1);
	}
}



//поиск по листу measure
function SearchMeasure(value)
{
	value = value.replace('"','');
	value = value.replace('\\','');
	UpdateMeasureTable(value);
	clearInterval(window.iIntervalID);
}


//обновление списка measure при поиске
function UpdateMeasureTable(value)
{
	downloadPage('ajax.php', 'ajax=measuretable&text='+value, 'list_measure_table', '', '', 0, 0,13,0,0,0);
}



//для вложенного меню
function MeasureSelection (measure_id)
{
    $("a'[id]^=measure_'").css("font-size","8pt");
    $("a'[id]^=measure_'").css("font-weight","normal");
    $("#measure_"+measure_id).css("font-weight","bolder");
    $("#measure_"+measure_id).css("font-size","8pt");
	setCookie('measureid', measure_id);
    reloadxmls('1334598,1334418',measure_id);
}


function SearchFoiv(value)
{
    value = value.replace('"','');
	value = value.replace('\\','');
	UpdateFoivTable(value);
	clearInterval(window.iIntervalID);
}
//обновление списка measure при поиске
function UpdateFoivTable(value)
{
	downloadPage('ajax.php', 'ajax=foivtable&text='+value, 'list_foiv_table', '', '', 0, 0,13,0,0,0);
}


//для вложенного меню
function FoivSelection (foiv_id)
{
	
	//$("a'[id]^=foiv_'").css("font-size","8pt");
    $("a'[id]^=foiv_'").css("font-weight","normal");
   $("#foiv_"+foiv_id).css("font-weight","bolder");
    $("#foiv_"+foiv_id).css("font-size","8pt");
    setCookie('foivid', foiv_id);
    reloadxmls('1334518,1334378,1334518,1334538,1334558,1334578,1334498,1334738,1334928,1335268',foiv_id);
}


function SearchFiles_83_fz(value)
{
    value = value.replace('"','');
	value = value.replace('\\','');
	UpdateFiles_83_fzTable(value);
	clearInterval(window.iIntervalID);
}

//обновление списка файлов 83-ФЗ при поиске
function UpdateFiles_83_fzTable(value)
{
	downloadPage('ajax.php', 'ajax=files_83_fz_table&text='+value, 'list_files_83_fz_table', '', '', 0, 0,13,0,0,0);
}


//для списка ФЦП
function FcpSelectionManager(){
	this.lastSelected = null;
	this.pageId = null;
	this.selectFCP = function(obj, fcpId){
		$("[id^='adv_xml_']").remove(); 
		savexmlcookie('1236', ''); 
		if (this.lastSelected == obj)
			return;
		
		if (this.lastSelected && (this.lastSelected != null)){
			this.lastSelected.style.fontWeight = 'normal';
		}
		if (typeof obj == 'string') 
			obj = document.getElementById(obj);
		obj.style.fontWeight = 'bolder';
		obj.style.fontSize = '8pt';
		this.lastSelected = obj;
		this.downloadContent(fcpId);
	}

	this.downloadContent = function(fcpId)
	{
		date = '';
		value = fcpId;
		savexmlcookies('1237,1239,1240,1241,1238,1242,1243,1557',value);
	//	savexmlcookies('1236','');
		setCookie('fcpid', fcpId);
		//alert(value);
		downloadPage('passportfcp.php', 'mq_id='+value+'&nobody=1&text=Выбран ФЦП '+this.lastSelected.innerHTML+'&addtolod_action=15', 'inner_page', '', "", 0, 0, 0,0,0,1);
	}
}


//поиск по спиcку ФЦП
function SearchFcp(value)
{
	value = value.replace('"','');
	value = value.replace('\\','');
	clearTimeout(window.FCPTimeout);
	//alert(2);
	UpdateFcpTable(value);
	/*if (window.FCPSearchValue != value)
	{
		window.FCPSearchValue = value;
		window.FCPTimeout = setTimeout('UpdateFcpTable("' + value + '");', 300);
	}*/
	clearInterval(window.iIntervalID);
}

function setIntervalSearchFcp(value)
{
	//alert(1);
	window.iIntervalID = setInterval("SearchFcp('"+value+"');", 500);
}

//обновление списка ФЦП при поиске
function UpdateFcpTable(value)
{
	//alert(3);
	downloadPage('ajax.php', 'ajax=fcptable&text='+value, 'list_fcp_table', '', '', 0, 0,13,0,0,0);

}
/*--------------------------------------------------------------обратная-связь------------------------------------------------------------------------*/


function SendTT()
{
	form = getId('form_tt');
	var page_id = form.page_id.value;
	var type = form.type.value;
	var text = form.text.value;
	var username = form.username.value;
	var email = form.email.value;
	alert('Спасибо за сообщение и приятной работы!');
	downloadPage('ajax.php', 'ajax=tt&type='+type+'&pageid='+page_id+'&text='+text+'&username='+username+'&email='+email, 'hidden_content', '', "", 0, 0,13,0,0,1);
	HideTT();
}

function ShowTT()
{
	var top = 0;
    if (document.getElementsByTagName('html')[0].scrollTop > 0) { top = document.getElementsByTagName('html')[0].scrollTop; }
    if (document.getElementsByTagName('body')[0].scrollTop > 0 && !isMSIE) { top = document.getElementsByTagName('body')[0].scrollTop; }
    var height = 0;
    var width = 0;
    if (isMSIE) {
        height = getWindowHeight();
        width = getWindowWidth();
    }
    else {
        height = innerHeight;
        width = innerWidth;
    }
    
    var calcTop = top + (height - getId('TTDiv1').offsetHeight) /4;
    var calcLeft = document.getElementsByTagName('html')[0].scrollLeft + (width - getId('TTDiv1').offsetWidth) / 3;
    
    
    getId('TTDiv1').style.top = calcTop + 'px';
    getId('TTDiv1').style.left = calcLeft + 'px';
    
    ShowLoading();
    getId('TTDiv1').style.display='';
}

function HideTT()
{
	HideLoading();
	document.getElementsByTagName('html')[0].style.overflow = 'auto';
	getId('TTDiv1').style.display='none';
}


/*-------------------------------------------------------------конец-обратной-связи------------------------------------------------------------------------*/


//для рейтинга по странам. или перезагружает или подгружает инфу по странам
function RegionInfo2(regionId,type){
	text = $("#"+regionId).text();
	
	if (type){
		$('.subject_td_selected').addClass('subject_td');
		$('.subject_td_selected').removeClass('subject_td_selected');
		$("#"+regionId).addClass('subject_td_selected');
		$("#"+regionId).removeClass('subject_td');
		setCookie('regioninfo', regionId);
		downloadPage('region.php', 'mq_id='+regionId+'&nobody=1&text=Выбрана '+text+'&addtolod_action=15', 'regioninfo', '', "getId('regioninfo').style.display=''", 0, 0, 0,0,0,1);		
	}
	else{
		setCookie('regioninfo', regionId);
		add_to_log(page_id, 'Выбрана '+text, 9);
		top.location.href='region.php';
	}
}
	

//для worldfinance.php и tovar.php
function CandleChartLoad (str)
{
	if (getId('select_'+str))
	{
		value = getId('select_'+str).value;
		if (!value)
		{
			alert('значение по-умолчанию m_q не задано!');
			return;
		}
		if (getId('xml_92'))
		{
			reloadxmls('92',value);
		}else{
			reloadxmls('135',value);
		}
	}else{
		alert('ID'+str+' не найден');
	}
}

//для поиска по порталу
function setvalue_E(id,sw,text){
	  if (sw == 'on'){
	    if (id.value.indexOf(text) > -1) {
	      id.value='';
	    }
	  } else {
	    if (id.value == '') {
	      id.value = text;
	    }
	  }
}


function getFlashObject(o){

	o.quality = 'high';
	var str='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
  	str+='codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+(o.ver ? o.ver : '8')+',0,0,0" ';
  	str+=(o.id     ? 'id="'+o.id+'" ' : '');
  	str+=(o.base   ? 'base="'+o.base+'" ' : '');
  	str+=(o.align  ? 'align="'+o.align+'" ' : '');
  	str+=(o.width  ? 'width="'+o.width+'" ' : '');
  	str+=(o.height ? 'height="'+o.height+'" ' : '');
    str+='>';

  	str+=(o.movie     ? '<param name="movie" value="'+o.movie+'"/>' : '');
  	
  	str+=(o.bgcolor   ? '<param name="bgcolor" value="'+o.bgcolor+'"/>' : '<param name="bgcolor" value="#FFFFFF"/>');
  	
  	str+=(o.quality   ? '<param name="quality" value="'+o.quality+'"/>' : '<param name="quality" value="high"/>');
  	
    str+=(o.flashvars ? '<param name="flashvars" value="'+o.flashvars+'"/>' : '');
    
    //allowScriptAccess - взаимодействие между flash и html (необязательный)
  	//Значения: never | always | sameDomain 
  	//по умолчанию sameDomain Flash Player 7 и выше
  	str+=(o.allowScriptAccess ? '<param name="allowScriptAccess" value="'+o.allowScriptAccess+'"/>' : '');

  	str+=(o.salign    ? '<param name="salign" value="'+o.salign+'"/>' : '');
  	
  	//Window Mode
  	//Значения:  | opaque | transparent
  	str+=(o.wmode     ? '<param name="wmode" value="'+o.wmode+'"/>' : '');
  	
  	//Масштабирование 
  	//Значение: noborder | scale | noscale | exactfit
  	str+=(o.scale     ? '<param name="scale" value="'+o.scale+'"/>' : '<param name="scale" value="noscale"/>');

    //Контекстное меню
    //Значение: true | false
  	str+=(o.menu     ? '<param name="menu" value="'+o.menu+'"/>' : '');  	
  	str+='<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" ';
    	str+=(o.movie     ? 'src="'+o.movie+'" ' : '');
    	str+=(o.id        ? 'id="'+o.id+'-embed" ' : '');
    	str+=(o.bgcolor   ? 'bgcolor="'+o.bgcolor+'" ' : 'bgcolor="#FFFFFF" ');
    	str+=(o.flashvars ? 'flashvars="'+o.flashvars+'" ' : '');

    	//swLiveConnect - загрузка JAVA при первичной загрузке Flash Player
    	//(необязательный, по умолчанию false) только для embed
    	str+=(o.swLiveConnect ? 'swLiveConnect="'+o.swLiveConnect+'" ' : '');

    	str+=(o.allowScriptAccess ? 'allowScriptAccess="'+o.allowScriptAccess+'" ' : '');
    	str+=(o.quality ? 'quality="'+o.quality+'" ' : 'quality="high" ');
    	str+=(o.base    ? 'base="'+o.base+'" ' : '');
    	str+=(o.wmode   ? 'wmode="'+o.wmode+'" ' : '');
    	str+=(o.salign  ? 'salign="'+o.salign+'" ' : '');
    	str+=(o.wmode   ? 'wmode="'+o.wmode+'" ' : '');
    	str+=(o.scale   ? 'scale="'+o.scale+'" ' : 'scale="noscale"');
    	str+=(o.menu    ? 'menu="'+o.menu+'" ' : '');
    	str+=(o.width   ? 'width="'+o.width+'" ' : '');
    	str+=(o.height  ? 'height="'+o.height+'" ' : '');
    	str+='>';
  	str+='</embed>';
	str+='</object>';
  return str;
}


function CheckTypeChart()
{
	var n = navigator;
	output_text = '';	
		var f = -1;
		if (n.plugins) {
			for (var i = 0; i < n.plugins.length; i++) {
				if (n.plugins[i].name.indexOf('Flash') > (-1)) {
					var s = /([0-9\.])+/.exec(n.plugins[i].description);
					s = s[0];
					f = parseFloat(s);
				}
			}
		}
		if (f == -1){
			for (var i = 3; i < 11; i++)
			{
				try {
					if (eval('new ActiveXObject("ShockwaveFlash.ShockwaveFlash.'+i+'")')){ f = i; }
				}
				catch(e) { break;  }
			}
		}		
		if (f >= 8) { 
			output_text = 'flash'; 
		}
		else if (document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Shape", "1.0")){
		
			output_text = 'svg'; 
			
		}
		else{
			output_text = 'img'; 
			
		}
	
	
	return output_text;
}


function insertChart (o, toId, swf_name_file, xml_id, mq_id, width, height,type_chart)
{
		//alert(swf_name_file);	
	if (o != null && getId(toId))
	{
		var verdivid = 'v_'+toId.toString();
		var advbuttdivid = 'adv_button_'+toId.toString();
		var versiontext = '';
		var output_text = '';
		var otherbuttontext = '';
		if (getId(verdivid))
		{
			versiontext = getId(verdivid).innerHTML;
		}
		if (getId(advbuttdivid))
		{
			otherbuttontext = getId(advbuttdivid).innerHTML;
		}
		//otherbuttontext
		var n = navigator;
		
		if (type_chart == "flash"){
			if (n.userAgent.indexOf('Chrome') == -1) {
				var f = -1;
				
				if (n.plugins) {
					for (var i = 0; i < n.plugins.length; i++) {
						if (n.plugins[i].name.indexOf('Flash') > (-1)) {
							var s = /([0-9\.])+/.exec(n.plugins[i].description);
							s = s[0];
							f = parseFloat(s);
						}
					}
				}
				if (f == -1){
					for (var i = 3; i < 11; i++)
					{
						try {
							if (eval('new ActiveXObject("ShockwaveFlash.ShockwaveFlash.'+i+'")')){ f = i; }
						}
						catch(e) { break;  }
					}
				}
				
				if (f >= 8) { 
					output_text = getFlashObject(o); 
				}
				
			}else { output_text = getFlashObject(o); }
			output_text = (otherbuttontext?'<div>'+otherbuttontext + '</div>':'')+output_text + (versiontext?'<div>'+ versiontext + '</div>':'');
			document.getElementById(toId).innerHTML = output_text;
			//alert(output_text);
			//document.getElementById("xml_1001").innerHTML = output_text;
		}else if (type_chart == "svg"){
			FusionCharts.setCurrentRenderer("javascript");
			var chart = new FusionCharts(swf_name_file, "chart_"+xml_id, width, height, "0", "1");
			//Страрая команда, поменял by Kalinin
			//output_text = ((document.all)?getId("textxml_"+xml_id).innerText.replace(/\\r/g, ''):getId("textxml_"+xml_id).textContent);
			output_text = array_data_xml[xml_id];
			//output_text.replace(/dataXML=/g,"");
			chart.setXMLData(output_text.slice(8,-1).replace(/%25/g,'%'));
			
			var step;
			if(xml_id == '1188'){
				step = 7;
			}else{
				step = 1;
			}
				
			if (typeof chart._overrideJSChartConfiguration === 'function') {
				chart._overrideJSChartConfiguration({
					chart: { marginLeft: 10 },
					
					xAxis: {
						labels: {
							rotation: 0,
							step: step,
							align: 'center'
						}
/*						minorTickLength: 0*/
					},
					yAxis: [{
						tickInterval: 10000000,
						title: { margin: 90 }
					}]
				});
			}
			
			chart.render(toId);
			
		}else{
			output_text = '<img src="image_flsh.php?xml_id='+o.xml_id+( o.mq_id  ? '&mq_id='+o.mq_id : '')+ '" '+(o.width   ? 'width="'+o.width+'" ' : '')+' '+(o.height  ? 'height="'+o.height+'" ' : '')+' />'; 
			output_text = (otherbuttontext?'<div>'+otherbuttontext + '</div>':'')+output_text + (versiontext?'<div>'+ versiontext + '</div>':'');
			document.getElementById(toId).innerHTML = output_text; //381552
			//alert(output_text);
		}
		
		
	}
	
	
}

function insertChartSVG(toId, swf_name_file, xml_id, width, height){
	var textXML = ((document.all)?getId("textxml_"+xml_id).innerText.replace(/\r/g, ''):getId("textxml_"+xml_id).textContent);
	FusionCharts.setCurrentRenderer("javascript");
	var chart = new FusionCharts(swf_name_file, "chart_"+xml_id, width, height, "0", "1");
	chart.setXMLData(textXML);
	chart.render(toId);
}

function insertFlashToId (o, toId)
{ 
	if (o != null && getId(toId))
	{
		var verdivid = 'v_'+toId.toString();
		var advbuttdivid = 'adv_button_'+toId.toString();
		var versiontext = '';
		var output_text = '';
		var otherbuttontext = '';
		if (getId(verdivid))
		{
			versiontext = getId(verdivid).innerHTML;
		}
		if (getId(advbuttdivid))
		{
			otherbuttontext = getId(advbuttdivid).innerHTML;
		}
		//otherbuttontext
		var n = navigator;
		
		if (n.userAgent.indexOf('Chrome') == -1) {
			var f = -1;
			
			if (n.plugins) {
				for (var i = 0; i < n.plugins.length; i++) {
					if (n.plugins[i].name.indexOf('Flash') > (-1)) {
					    var s = /([0-9\.])+/.exec(n.plugins[i].description);
					    s = s[0];
					    f = parseFloat(s);
					}
				}
			}
			if (f == -1){
				for (var i = 3; i < 11; i++)
				{
					try {
						if (eval('new ActiveXObject("ShockwaveFlash.ShockwaveFlash.'+i+'")')){ f = i; }
					}
					catch(e) { break;  }
				}
			}
			
			if (f >= 8) { 
				output_text = getFlashObject(o); 
			}
			else {
				output_text = '<img src="image_flsh.php?xml_id='+o.xml_id+( o.mq_id  ? '&mq_id='+o.mq_id : '')+ '" '+(o.width   ? 'width="'+o.width+'" ' : '')+' '+(o.height  ? 'height="'+o.height+'" ' : '')+' />';
				//alert(output_text);
			}
		}
		else { output_text = getFlashObject(o); }
		
		output_text = (otherbuttontext?'<div>'+otherbuttontext + '</div>':'')+output_text + (versiontext?'<div  style="position:relative; z-index:2; float:left;">'+ versiontext + '</div>':'');
		document.getElementById(toId).innerHTML = output_text;
	}
}



//для вложенного меню
function ChangeElemType (curr_page_id, type, page, mq_id, mf_id)
{
	$("a[id^='ondp_']").css('font-weight','normal');
	$("#ondp_"+type).css('font-weight','bolder');
	
	$("a[id^='application_']").css('font-weight','normal');
	$("a[id^='application_']").css('font-size','10px');
	
	$("#application_"+type).css('font-weight','bolder');
	$("#application_"+type).css('font-size','13px');
	
	//alert("curr_page_id = "+curr_page_id+"; "+"type = "+type+"; page = "+page+"; mq_id = "+mq_id+"; "+"; mf_id = "+mf_id);
	

	if (curr_page_id && page)
	{
		setCookie('type_'+curr_page_id, type);
		func = '';
	}
	if (getId('img_export_xls'))
	{
		getId('img_export_xls').style.display = '';
	}
	page_id = type;
	
	Export = Export_original;
	downloadPage(page, 'mq_id=&nobody=1'+ ((type)?'&type='+type:'') 
						+ ((mq_id)?'&mq_id='+mq_id:''), 'inner_page', '', func, 0, 0, 0, 0,0,1);
}




/*-----------------------------------------------------------для всплывающего окна с графиком-------------------------------------------------------------------------------------*/

function ResizeScalar(up_or_down, xml_id, width, height)
{
	
	type_chart = CheckTypeChart();
	var f = {};
	if(up_or_down==1){
		array_index_scalar[xml_id]++;
	}else{
		array_index_scalar[xml_id]--;
	}
	var scalar = 20*array_index_scalar[xml_id];
	f.width = width+scalar;
	f.height = height+scalar;
	f.id = 'xml_'+xml_id;
	f.xml_id = xml_id;
	f.mq_id = array_mq_id[xml_id];
	f.movie = array_swf_name_file[xml_id]+'?chartWidth='+f.width+'&amp;chartHeight='+f.height+'&amp;ChartNoDataText=&amp;PBarLoadingText=&amp;XMLLoadingText='
	f.scal = "noscale";
	f.wmode= "transparent";
	f.flashvars = array_data_xml[xml_id];
	
	insertChart(f,'xml_'+xml_id, array_swf_name_file[xml_id], f.xml_id, array_mq_id[xml_id], f.width, f.height ,type_chart);
} 

function ResizeScalarPop(up_or_down, xml_id)
{
	
	window.isFirsth = true;
	type_chart = CheckTypeChart();
	width = 640;
	height = 520;
	//width=(getCookie('xml_'+xml_id+'_width'))?(getCookie('xml_'+xml_id+'_width')):640;
	//height=(getCookie('xml_'+xml_id+'_height'))?(getCookie('xml_'+xml_id+'_height')):520;
	var f = {};
	if(up_or_down==1){
		array_index_scalar[xml_id]++;
	}else{
		array_index_scalar[xml_id]--;
	}
	var scalar = 20*array_index_scalar[xml_id];
	
	if (getCookie('xml_flash_'+xml_id))
	{
		flashname = getCookie('xml_flash_'+xml_id);
		switch (flashname) {
		   case 'mscolumn2':
			   flashname = 'MSColumn2D';
		      break
		   case 'msline':
			   flashname = 'MSLine';
		      break
		   case 'msbar2':
			   flashname = 'MSBar2D';
		      break
		   case 'stcolumn2d':
			   flashname = 'StackedColumn2D';
		      break
		   case 'msarea':
			   flashname = 'MSArea';
		      break
		}
		//flashname_scale_chart = 'swf\/'+ getCookie('xml_flash_'+xml_id) +'\.swf';
		flashname_scale_chart = 'swf\/'+ flashname +'\.swf';
	}else{
		flashname_scale_chart = array_swf_name_file[xml_id];
	}
	
	f.width = width*1+scalar;
	f.height = height*1+scalar;
	f.id = 'xml_'+xml_id;
	f.xml_id = xml_id;
	f.mq_id = array_mq_id[xml_id];
	f.movie =  flashname_scale_chart +'?chartWidth='+f.width+'&amp;chartHeight='+f.height+'&amp;ChartNoDataText=&amp;PBarLoadingText=&amp;XMLLoadingText='
	f.scal = "noscale";
	f.wmode= "transparent";
	f.flashvars = array_data_xml[xml_id];
	
	//--------------------
	$("#adv_xml_"+xml_id).dialog({
			"width"    : f.width+20,
			"height"   : f.height+80,
			"minWidth" : "400",
			"minHeight": "400",
			open :function(event, ui) {  
				
				if(ui.size.width < 402) {
					ui.size.width = 402;
				}
				if(ui.size.height < 402) {
					ui.size.height = 402;
				}
			}
		 
		 });
	
	setCookie('xml_'+xml_id+'_width', f.width);
	setCookie('xml_'+xml_id+'_height', f.height);
	
	arrayWidthDialog[xml_id] = f.width;
	arrayHeightDialog[xml_id] = f.height;
	//alert ('xml_id: '+'xml_'+xml_id+'  flashname_scale_chart:'+flashname_scale_chart+'   f.xml_id:'+f.xml_id+'   array_mq_id[xml_id]:'+array_mq_id[xml_id]+'    f.width'+f.width+'   f.height: '+f.height+'  type_chart:'+type_chart);
	insertChart (f,'xml_'+xml_id, flashname_scale_chart, f.xml_id, array_mq_id[xml_id], f.width, f.height ,type_chart);
} 

function ResizeScalarDin(xml_id)
{
	type_chart = CheckTypeChart();
	width=(getCookie('xml_'+xml_id+'_width'))?(getCookie('xml_'+xml_id+'_width')):640;
	height=(getCookie('xml_'+xml_id+'_height'))?(getCookie('xml_'+xml_id+'_height')):520;
	if (getCookie('xml_flash_'+xml_id))
	{
		flashname_scale_chart = 'swf\/'+ getCookie('xml_flash_'+xml_id) +'\.swf';
	}else{
		flashname_scale_chart = array_swf_name_file[xml_id];
	}
	var f = {};
	f.width = width;
	f.height = height;
	f.id = 'xml_'+xml_id;
	f.xml_id = xml_id;
	f.mq_id = array_mq_id[xml_id];
	f.movie =  flashname_scale_chart +'?chartWidth='+f.width+'&amp;chartHeight='+f.height+'&amp;ChartNoDataText=&amp;PBarLoadingText=&amp;XMLLoadingText='
	f.scal = "noscale";
	f.wmode= "transparent";
	f.flashvars = array_data_xml[xml_id];
	
	
	
	
	insertChart(f,'xml_'+xml_id, flashname_scale_chart, f.xml_id, array_mq_id[xml_id], f.width, f.height ,type_chart);
} 


function AdvInfoResize(event, id_resizer, type)
{


} 

function AdvInfoMove(event, xmlid)
{

}

function AdvActiv(xml_id, value, xml_mq, link, flashname)
{
	if (i=0){return;}
	window.adv_xml_id = xml_id;
	//deltaX=(getCookie('xml_'+xml_id+'_width'))?(getCookie('xml_'+xml_id+'_width')):"780";
	//deltaY=(getCookie('xml_'+xml_id+'_height'))?(getCookie('xml_'+xml_id+'_height')):"660";
	dialogX = (arrayWidthDialog[xml_id]?arrayWidthDialog[xml_id]:640);
	dialogY = (arrayHeightDialog[xml_id]?arrayHeightDialog[xml_id]:520);
	
	
	//dialogX=(getCookie('xml_'+xml_id+'_width'))?(getCookie('xml_'+xml_id+'_width')):640;
	//dialogY=(getCookie('xml_'+xml_id+'_height'))?(getCookie('xml_'+xml_id+'_height')):520;
	if(!window.isFirsth){
		dialogX= dialogX*1+80;
		dialogY= dialogY*1+80;
	}else{
		dialogX= dialogX*1+20;
		dialogY= dialogY*1+20;
	}
	id = "adv_xml_"+xml_id;
	if ($("#adv_xml_"+xml_id).css("display")=="none"){
		$("#adv_xml_"+xml_id).dialog({
			"width"    : dialogX,
			"height"   : dialogY,
			"minWidth" : "400",
			"minHeight": "400",
			open :function(event, ui) {  
				
			},
			
			resizeStart:function(event, ui) {  
				var xml_id = window.adv_xml_id;
				//getId("adv_xml_table_"+xml_id+'_content').style.visibility = 'hidden';
				$("#adv_xml_table_"+xml_id+"_content").css("visibility", 'hidden');
				
				//getId(id).style.border = 'dotted 3px #0000ff'; 
			},
		   
			resizeStop:function(event, ui) { 
				var xml_id = window.adv_xml_id;
				getId("adv_xml_table_"+xml_id+'_content').style.visibility = 'visible';
				var xml_id = window.adv_xml_id;
				getId("adv_xml_"+xml_id).style.border = ''; 
				var deltaX = ui.size.width-20;
				var deltaY = ui.size.height-80;
				value = getCookie('xml_'+xml_id);
				content_id = "adv_xml_div_"+xml_id+"_content";
				setCookie('xml_'+xml_id+'_width', deltaX);
				setCookie('xml_'+xml_id+'_height', deltaY);
					
				flashname = '';
				if (getCookie('xml_flash_'+xml_id))
				{
					flashname = getCookie('xml_flash_'+xml_id);
				}
				//debugger;
				ResizeScalarDin(xml_id);
				//downloadPage('ajax.php', 'mq_id='+value+'|&ajax=adv_xml&xmlid='+xml_id+'&chartWidth='+deltaX+(flashname?'&flashname='+flashname:'')+'&chartHeight='+deltaY, content_id, "", "getId('adv_xml_table_"+xml_id+"_content').style.display = ''; ", 0, 0, 5,0);
					
					
			},
			resize:function(event, ui) {  
				if(ui.size.width < 402) {
					ui.size.width = 402;
				}
				if(ui.size.height < 402) {
					ui.size.height = 402;
				}
			},
			close:function(event, ui) {  
				var xml_id = window.adv_xml_id;
				content_id = "adv_xml_div_"+xml_id+"_content";
				setCookie('xml_'+xml_id, '');
				getId(content_id).style.display = 'none';
				getId("adv_xml_"+xml_id).style.display = 'none';
				$("#adv_xml_"+xml_id).dialog("destroy");
				elem = $("#adv_xml_"+xml_id);//.remove();
				$("#adv_home").append(elem);
				
				downloadPage('ajax.php', 'mq_id=|&ajax=adv_xml&xmlid='+xml_id, content_id, "", " ", 0, 0, 0,0);
				
			}
		
		 });
		 }
		AdvInfo (xml_id, value, xml_mq, link, flashname);
/*	}else{
		
		
			$("#adv_xml_"+xml_id).dialog("open");
		
		
	}*/
}

function ToFullScreen (xml_id, xml_mq)
{
	getId(id).style.top = 0;
	getId(id).style.left = 0;
	width = document.getElementsByTagName('html')[0].offsetWidth - 16;
	height = document.getElementsByTagName('html')[0].offsetHeight - 26;
	getId(id).style.width = width; 
	getId(id).style.height = height;
	id = "adv_xml_"+xml_id;
	value = getCookie('xml_'+xml_id);
	content_id = "adv_xml_"+xml_id+"_content";
	downloadPage('ajax.php', 'mq_id='+value+'|'+xml_mq+'&ajax=adv_xml&xmlid='+xml_id+'&chartWidth='+parseInt(width)+'&chartHeight='+parseInt(height), content_id, "", " ", 0, 0, 5,1);
	return false;
}


function AdvInfo (xml_id, value, xml_mq, link, flashname)
{
	content_id = "adv_xml_div_"+xml_id+"_content";
	return_value = '';	
	
	if (flashname)
	{
		setCookie('xml_flash_'+xml_id, flashname);
	}else{
		if (getCookie('xml_flash_'+xml_id))
		{
			flashname = getCookie('xml_flash_'+xml_id);
		}
	}
	
	if (value == ''){
		getId("adv_xml_div_"+ xml_id + "_content").style.display = 'none';
		setCookie('xml_'+xml_id, ''); // очищаем кукисы
		getId(id).style.display = 'none';
		$("#adv_xml_"+xml_id+"").dialog("close");
		getId(id).startSize;
		return false;
	}else if(value == 'null')
	{
		if (getCookie('xml_'+xml_id)) // если в кукисах что то есть
		{
			value = getCookie('xml_'+xml_id);
		}else{
			value = array_mq_id[xml_id];
		}
		downloadPage('ajax.php', 'mq_id='+value+'&ajax=adv_xml&xmlid='
				+xml_id+(flashname?'&flashname='+flashname:'')
				+(arrayWidthDialog[xml_id]?'&chartWidth='+arrayWidthDialog[xml_id]:'')
				+(arrayHeightDialog[xml_id]?'&chartHeight='+arrayHeightDialog[xml_id]:'')
				//+(getCookie('xml_'+xml_id+'_width')?'&chartWidth='+getCookie('xml_'+xml_id+'_width'):'')
				//+(getCookie('xml_'+xml_id+'_height')?'&chartHeight='+getCookie('xml_'+xml_id+'_height'):'')
				, content_id, "", "getId('adv_xml_div_"+ xml_id + "_content').style.display = '';", 0, 0, 0,0);
		return false;
		//downloadPage('ajax.php', 'ajax=xml2&xmlid='+xml_id+"&mq_id=", content_id, '','', 0, 0,13,0,0,0);
	}
	
	if (getCookie('xml_'+xml_id)) // если в кукисах что то есть
	{
		
		value_cookies = getCookie('xml_'+xml_id);
		
		value_cookies_arr = value_cookies.split('|');
		temp_mq = xml_mq.split('|');
		for (var i = 0; i < value_cookies_arr.length; i++)
		{
		  if (value_cookies_arr[i] == value)
		  {
			value_cookies_arr.splice(i,1);
		  }
		}

		
		if (value_cookies_arr[0].indexOf(value+',') >= 0)
		{
			if (value_cookies_arr[0].indexOf(value) <= 0){
				value = (value_cookies_arr[0]?value_cookies_arr[0]:'')+(value?value:'')+(value_cookies_arr[1]?'|'+value_cookies_arr[1]:'');
			}else{
				if (value_cookies_arr[0]){
					value_cookies_arr[0] = value_cookies_arr[0].replace(value+',','');
					value_cookies_arr[0] = value_cookies_arr[0].replace(',,',',');
					value = (value_cookies_arr[0]?value_cookies_arr[0]:'')+(value_cookies_arr[1]?'|'+value_cookies_arr[1]:'');
				}
				
			}
		}else{
			
			if (value_cookies_arr[0].indexOf(value) <= 0){
				value = (value_cookies_arr[0]?value_cookies_arr[0]+',':'')+(value?value:'')+(value_cookies_arr[1]?'|'+value_cookies_arr[1]:'');
				//value = value_cookies_arr[0];
			}else{
				if (value_cookies_arr[0]){
					value_cookies_arr[0] = value_cookies_arr[0].replace(value,'');
					value_cookies_arr[0] = value_cookies_arr[0].replace(',,',',');
					value = (value_cookies_arr[0]?value_cookies_arr[0]:'')+(value_cookies_arr[1]?'|'+value_cookies_arr[1]:'');
				}
			}
		}
		
		
	//	setCookie('xml_'+xml_id, value);
	}else{
		value = value+(xml_mq?'|'+xml_mq:'');
		//setCookie('xml_'+xml_id, value);
	}
	
	value = value.replace(',|','|');
	
	setCookie('xml_'+xml_id, value);

	
	//width=(getCookie('xml_'+xml_id+'_width'))?(getCookie('xml_'+xml_id+'_width')):640;
	//height=(getCookie('xml_'+xml_id+'_height'))?(getCookie('xml_'+xml_id+'_height')):520;
	
	
	//alert(arrayWidthDialog[xml_id]);
	//value = value.replace(',','');
	//alert(value);
	downloadPage('ajax.php', 'mq_id='+value+'&ajax=adv_xml&xmlid='
			+xml_id+(flashname?'&flashname='+flashname:'')
			+(arrayWidthDialog[xml_id]?'&chartWidth='+arrayWidthDialog[xml_id]:'')
			+(arrayHeightDialog[xml_id]?'&chartHeight='+arrayHeightDialog[xml_id]:'')
			//+(getCookie('xml_'+xml_id+'_width')?'&chartWidth='+getCookie('xml_'+xml_id+'_width'):'')
			//+(getCookie('xml_'+xml_id+'_height')?'&chartHeight='+getCookie('xml_'+xml_id+'_height'):'')
			, content_id, "", "getId('adv_xml_div_"+ xml_id + "_content').style.display = '';", 0, 0, 0,0);
	return true;
}

function ShowHideValues(xml_id)
{
	if (getCookie('xml_values_'+xml_id))
	{
		type = getCookie('xml_values_'+xml_id);
		if (type == 1)
		{
			type = 0;
		}else{
			type = 1;
		}
	}else{
		type = 1;
	}
	
	value = getCookie('xml_'+xml_id);
	setCookie('xml_values_'+xml_id, type);
	//AdvInfo (xml_id, value, '', this, '');
	AdvInfo (xml_id, 'null', '', this, '');
}

function Point(x, y, top, left){
	this.x = parseInt(x);
	this.y = parseInt(y);
	this.startTop = parseInt(top);
	this.startLeft = parseInt(left);
}

/*----------------------------------------------------------конец-для всплывающего окна с графиком-------------------------------------------------------------------------------------*/

//для Региональная экономика (оперативная информация) и Региональная экономика (годы)
function ElemInfo(elem_id, defaultyear)
{
	setCookie('elemid', elem_id);
	year = '';
	if (getCookie('elemyear'))
	{
		year = getCookie('elemyear');
	}else{
		year = defaultyear;
	}
	m_q = elem_id+'|'+year;

	setCookie('xml_230', elem_id); // список
	setCookie('xml_209', m_q); // надпись
	setCookie('xml_266', m_q); // надпись у таблицы
	setCookie('xml_210', m_q); // комбобокс
	setCookie('xml_216', m_q); // диаграмма
	setCookie('xml_261', m_q); // диаграмма - все регионы
	setCookie('xml_217', m_q); // карта
	setCookie('xml_270', m_q); // таблица под картой
	setCookie('xml_271', m_q); // график под картой
	
	downloadPage('monitoring.php', 'mq_id='+m_q+'&nobody=1', 'inner_page', '', "", 0, 0, 5,1);
}

//для Региональная экономика (оперативная информация)
function OperRegionElemInfo (elem_id)
{
	setCookie('operelemid', elem_id);
	regionelemdate = '';
	if (getCookie('operregionelemdate'))
	{
		regionelemdate = getCookie('operregionelemdate');
	}else{
		regionelemdate = '';
	}
	m_q = elem_id+'|'+regionelemdate;
	setCookie('xml_2006',elem_id);''
	reloadxmls('2006,2002,2004,2005,1167,1168,1169,1170,1540',m_q);
}
//для Региональная экономика (оперативная информация)
function ChangeElemOperRegionDate (refresh_xml, curr_xml, regionelemdate, query_type)
{
	if (!regionelemdate){return;}
	elem_id = '';
	if (getCookie('operelemid'))
	{
		elem_id = getCookie('operelemid');
	}
	m_q = elem_id+'|'+regionelemdate;
	setCookie('operregionelemdate', regionelemdate);
	reloadxmls(refresh_xml, m_q);
}	

//для диаграммы и места в Финансовым менеджменте
function ChangeElemDateFinman (refresh_xml, elemdate)
{
	if (!elemdate){return;}
	elem_id = '';
	if (getCookie('finmanelem'))
	{
		elem_id = getCookie('finmanelem');
		
	}
	m_q = elem_id+'|'+elemdate;
	setCookie('finmanelemdate', elemdate);
	reloadxmls(refresh_xml, m_q);
}	

//для диаграммы в Финансовым менеджменте
function ChangeElemFinman (xmls,elem_id)
{
	setCookie('finmanelem', elem_id);
	elemdate = '';
	if (getCookie('finmanelemdate'))
	{
		elemdate = getCookie('finmanelemdate');
	}else{
		elemdate = '';
	}
	m_q = elem_id+'|'+elemdate;
	reloadxmls(xmls,m_q);
}

/*-------------------------------для диаграммы и карты в "Сводная таблица исполнения бюджетов субъектов РФ"-------------------------------*/
function ChangeRegionDiagr(value)
{
	setCookie('region_analitics_hid',value);
	if (getCookie('region_analitics_year'))
	{
		year = getCookie('region_analitics_year');
	}else{
		year = '';
	}
	value = year + '|' + value;
	
	reloadxmls('1176,1177,1178,1181,1216',value); 
}

function ChangeRegionDate(date)
{
	setCookie('region_analitics_year',date);
	if (getCookie('region_analitics_hid'))
	{
		hid = getCookie('region_analitics_hid');
	}else{
		hid = '10';
	}
	value = date + '|' + hid;
	reloadxmls('1171,1172,1174,1176,1177,1178,1181,1216,1539',value); 
}
/*-------------------------------конец-для диаграммы и карты в "Сводная таблица исполнения бюджетов субъектов РФ"-------------------------------*/


//Региональная экономика (годы) и Финансовый менеджмент место, карта, диаграмма
function ChangeElemDate (refresh_xml, curr_xml, fm_q, query_type)
{
	if (!fm_q){return;}
	year = fm_q.split('|')[1];
	ids = refresh_xml.split(',');
	elem_id = '';
	elem_id = fm_q.split('|')[0];
	m_q = elem_id+'|'+year;
	setCookie('elemyear', year);
	reloadxmls(refresh_xml, m_q);
}


function DiagrLimit(xml, typelimit)
{
	oldcookie = getCookie('xml_'+xml+'_limit');
	setCookie('xml_'+xml+'_limit', typelimit);
	if (getId('xml_'+xml))
	{
		downloadPage('ajax.php', 'ajax=xml2&xmlid='+xml, 'xml_'+xml, ' ', 1, 0, 0,13,0,0,1);
	}else if (getId('xml_'+oldcookie))
	{
		downloadPage('ajax.php', 'ajax=xml2&xmlid='+xml, 'xml_'+oldcookie, ' ', 1, 0, 0,13,0,0,1);
	}else{
		top.location.reload();
	}
}

//всплывающая подсказка
function ShowHideAdvHelp()
{
	if (getId('help_advanced').style.display == 'none'){
		getId('help_advanced').style.display ='';
		getId('help_link').innerHTML = 'скрыть';
	}else{
		getId('help_advanced').style.display = 'none';
		getId('help_link').innerHTML = 'подробнее';
	}
	getId('content_help').style.height = 'auto';
}

//для print_versions
function shver(id)
{
	if (getId('source_'+id).style.display == 'none'){
		getId('source_'+id).style.display ='';
		
	}else{
		getId('source_'+id).style.display = 'none';
	}
}

//для worldfinance.php и tovar.php
function FontSize(size)
{
	setCookie('font-size', size);
	size = parseInt(size);
	document.body.style.fontSize = size;
	if (getId('leftMenu'))
	{
		getId('leftMenu').style.fontSize = size;
	}
	if (getId('page_name'))
	{
		getId('page_name').style.fontSize = parseInt(size)+2;
	}
	save_user_settings();
}

function save_user_settings()
{
	downloadPage('ajax.php', 'ajax=save_user_settings', 'hidden_content', '', 0, 0, 0,0,0,0,1);
}



function Search()
{
	if (getId('search').value == '' || getId('search').value == '> Поиск'){
		alert('введите строку для поиска');
		return false;
	}else{
		return true;
	}
}

//для рейтинга по странам
function ReloadRatings (rating_id)
{
	if (rating_id)
	{
		if (getId('ratings'))
		{
			downloadPage('ajax.php', 'ajax=ratings&rating_id='+rating_id, 'ratings', '', '', 0, 0,13,0,0,1);
			setCookie('ratings',rating_id);
		}
	}
}

//для рейтинга по субъектам РФ
function ReloadRegionRatings (rating_id, pda_mode)
{
	if (rating_id)
	{
		if (pda_mode == undefined)
		{
			if (getId('region_ratings'))
			{
				downloadPage('ajax.php', 'ajax=ratings_region&rating_id='+rating_id, 'region_ratings', '', '', 0, 0,13,0,0,1);
				setCookie('region_ratings',rating_id);
			}
		}else{
			if (getId('region_ratings'))
			{
				downloadPage('ajax.php', 'ajax=ratings_region_pda&rating_id='+rating_id, 'region_ratings', '', '', 0, 0,13,0,0,1);
				setCookie('region_ratings',rating_id);
			}
		}
	}
}







//var isMSIE = navigator.userAgent.indexOf('MSIE') >= 0;


window.onresize = function() {
	if (!getId('div_reload')){return;}
    if (getId('div_reload').style.display == '') {
        getId('fillarea_bg_progress_window').style.zIndex = 0;
        getId('fillarea_bg_progress_window').style.top = document.getElementsByTagName('html')[0].scrollTop + 'px';
        getId('fillarea_bg_progress_window').style.left = document.getElementsByTagName('html')[0].scrollLeft + 'px';
        
        if (isMSIE) {
            height = getWindowHeight();
            width = getWindowWidth();
        }
        else {
            height = innerHeight;
            width = innerWidth;
        }
        getId('fillarea_bg_progress_window').style.width = width + 18 + 'px';
        getId('fillarea_bg_progress_window').style.height = height;
        
        var calcTop = document.getElementsByTagName('html')[0].scrollTop + (getWindowHeight() - getId('div_reload').offsetHeight) / 2
        var calcLeft = document.getElementsByTagName('html')[0].scrollLeft + (getWindowWidth() - getId('div_reload').offsetWidth) / 2
        getId('div_reload').style.top = calcTop;
        getId('div_reload').style.left = calcLeft;
    }
}

//ошибка у Silverlight таблиц
function onSilverlightError (sender, args)
{
    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    } 
    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;
    
    var errMsg = "Unhandled Error in Silverlight 2 Application " +  appSource + "\n" ;

    errMsg += "Code: "+ iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError")
    {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError")
    {           
        if (args.lineNumber != 0)
        {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " +  args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }

    throw new Error(errMsg);
}







//для слайдов
function DownloadSlidePage(id_presentation, param)
{
	setCookie('param_'+id_presentation, param);
	
	if (getId('slide_page'))
	{
		downloadPage('/slides/index.php', 'param='+param+'&id_presentation='+id_presentation+'&convert_to_utf=1', 'slide_page', '', "getId('slide_page').style.display = ''; getId('slide_page_top').style.height = 'auto';", 0, 0, 0,0,0);
	}
	
}



/* определим функцию обработки ошибок */
//window.onerror = onErrorHandler;

function onErrorHandler()
{
	return true;
}


/*----------------------------------------------------------------------------------------------------------*/



/*-таблица приложений с поиском---------------------------------------------------------------------------------------------------------------------*/

//поиск по спсику application
function SearchApplication(value,page_name)
{
	value = value.replace('"','');
	value = value.replace('\\','');
	clearTimeout(window.ApplicationTimeout);
	if (window.ApplicationSearchValue != value)
	{
		window.ApplicationSearchValue = value;
		window.applicationTimeout = setTimeout('UpdateApplicationTable("' + value + '","'+page_name+'");', 300);
	}
}


//обновление списка application при поиске
function UpdateApplicationTable(value, page_name)
{
	downloadPage('ajax.php', 'ajax=applicationtable&text='+value+'&page_name='+page_name, 'list_application_table', '', '', 0, 0,13,0,0,0);
}

function MRedirectRegion(regionId)
{
	ids = regionId.split(','); // все слои через запятую
	regionId = ids.pop();
	setCookie('xml_select_3004', regionId);
	reloadxmls('3002,3005,3007,3006', regionId);
	top.location.href='project_fb_mezh_budjet_subj.php';
}

function ReloadVersionsComboAndUpdateOndpFrame(id)
{	
	downloadPage('ajax.php', 'ajax=setondpcookie&xml_id=1057558&mq_id='+id, 'hidden_content', '', "ReloadVersionsComboAndUpdateOndpFrame2()", 0, 0,13,1,1,0);
}

function ReloadVersionsComboAndUpdateOndpFrame2()
{
	downloadPage('ajax.php', 'ajax=xml2&xmlid=1057558&mq_id='+getCookie('xml_1057538'), 'xml_1057558', '','UpdateOndpFrame()', 0, 0,13,0,0,1);
}

function UpdateOndpFrame()
{
	downloadPage('ajax.php', 'ajax=ondpframe&page='+page_id, 'div_ondp_frame', '', '', 0, 0,13,0,0,0);
}

function ExportOndp(id, ondp_id, page_id, type)
{
	downloadPage ('ajax.php', 'ajax=ondpexport&ondp='+ondp_id+'&id='+id+'&type='+type+'&page_id='+page_id, 'hidden_content', '', '', 0, 0,13,0,0,0);
}
/*----------------------------------------------------------------------------------------------------------------------*

/*красиво скрывает левое меню*/
function HideMenu(){
	
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf('chrome')==-1){
	//Вариант первый
	/*$("#left_block").attr("position","absolute");
	$("#left_block").parent().animate({"width": "toggle"}, "slow");
	$("#left_block").toggle("slow");	
	*/
	
	//Второй вариант
	/*$("#left_block").attr("position","absolute");
	$("#left_block").parent().animate({"width": "toggle"}, "slow");
	$("#left_block").animate({"width": "toggle"}, "slow");/**/
	
	//Вариант третий
		$("#left_block").attr("position","absolute");
		$("#left_block").parent().animate({"width": "toggle"}, "slow");
		if ($("#left_block").css("marginLeft") == "-250px"){
			$("#left_block").animate({"marginLeft": "0"}, "slow");
		}else{
			$("#left_block").animate({"marginLeft": "-250"}, "slow");
		}
	}else{
		//$(".menu_left").toggleClass("hide");
		$(".menu_left").toggle();
	}
	$("#hide_left_block").toggleClass("hide");
	$("#visible_left_block").toggleClass("hide");
	
	// Сохраняем фиксированные размеры окна с контентом
	if($("#hide_left_block").is(".hide")){
		$(".tdContent1").css("min-width", "1190px");
	}else{
		$(".tdContent1").css("min-width", "940px");
	}
}

/*для олапа*/
function openolap(url, width, height, name, resizeable, location, status, scroll, text)
{
	mywindow = window.open (url, name, "resizable="+resizeable+", location="+location+",status="+status+",scrollbars="+scroll+",width="+width+",height="+height+",fullscreen=no");
	var width = null;
    var height = null;
    width = document.getElementsByTagName('html')[0].offsetWidth;
    height = document.getElementsByTagName('html')[0].offsetHeight;
    add_to_log(6, text, 9);
} 

//поиск по спсику ОНДП
function SearchONDP(value)
{
	value = value.replace('"','');
	value = value.replace('\\','');
	clearTimeout(window.ApplicationTimeout);
	if (window.ApplicationSearchValue != value)
	{
		window.ApplicationSearchValue = value;
		window.applicationTimeout = setTimeout('UpdateONDPTable("' + value + '");', 300);
	}
}


//обновление списка ОНДП при поиске
function UpdateONDPTable(value)
{
	downloadPage('ajax.php', 'ajax=ondptable&text='+value, 'list_ondp_table', '', '', 0, 0,13,0,0,0);
}

function GotoHref(value)
{
	value.replace(' ',''); // убираем пробелы
	ids = value.split(','); // все слои через запятую
	
	countryId = ids.shift();
	countryId = ids.shift();
	//top.location.href = countryId;
	window.open(countryId); 
}



function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}


function onZoom(value)
{
	var a = '';
//alert('onZoom');
	for (var i=0; i<50; i++)
    {
    	a[i] = "'mlst_image_"+i+"'";
    }
	
//	document["flashmap"].SetMilestonesVisibility(a,true);
}

function clickWorldLocation (e)
{
	alert(e);
	/*if (e == 0) { //Россия
		setTimeout("callSetMilestonesVisibility(true,'101,102,103,104,105,106,107,108,109,110,111,112,113')", 0);
		setTimeout("callSetMilestonesVisibility(false,'1,2,3,4,5,6,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86')", 100);
	}else if (e == 1) //СЗФО
	{
		setTimeout("callSetMilestonesVisibility(false,'101,102,103,104,105,106,107,108,109,110,111,112,113')", 0);
		setTimeout("callSetMilestonesVisibility(true,'1,2,3,4,5,6,8,9,11,12')", 100);
	}else if (e == 2) //ЦФО
	{
		setTimeout("callSetMilestonesVisibility(false,'101,102,103,104,105,106,107,108,109,110,111,112,113')", 0);
		setTimeout("callSetMilestonesVisibility(true,'13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29')", 100);
	}else if (e == 3) //ЮФО
	{
		setTimeout("callSetMilestonesVisibility(false,'101,102,103,104,105,106,107,108,109,110,111,112,113')", 0);
		setTimeout("callSetMilestonesVisibility(true,'30,31,32,33,34,35,36,37,38,39,40,41,42,43')", 100);
	}else if (e == 4) //ПФО
	{
		setTimeout("callSetMilestonesVisibility(false,'101,102,103,104,105,106,107,108,109,110,111,112,113')", 0);
		setTimeout("callSetMilestonesVisibility(true,'44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61')", 100);
	}else if (e == 5) //УФО
	{
		setTimeout("callSetMilestonesVisibility(false,'101,102,103,104,105,106,107,108,109,110,111,112,113')", 0);
		setTimeout("callSetMilestonesVisibility(true,'62,63,64,65,66')", 100);
	}else if (e == 6) //СФО
	{
		setTimeout("callSetMilestonesVisibility(false,'101,102,103,104,105,106,107,108,109,110,111,112,113')", 0);
		setTimeout("callSetMilestonesVisibility(true,'67,68,69,70,71,72,73,74,75,76,77')", 100);
	}else if (e == 7) //ДВФО
	{
		setTimeout("callSetMilestonesVisibility(false,'101,102,103,104,105,106,107,108,109,110,111,112,113')", 0);
		setTimeout("callSetMilestonesVisibility(true,'78,79,80,81,82,83,84,85')", 100);
	}*/
}   

function callSetMilestonesVisibility(e,milestones) {
    var a = new Array();
    ids = milestones.split(','); // все слои через запятую
	
    for (var i=0; i<ids.length; i++)
    {
    	a[i] = 'mile'+ids[i];
    }
//    alert('Переданные индентификаторы: '+a);
    document["flashmap"].SetMilestonesVisibility(a, e);
}

function inArray(mas, element)
  {
    for (var i = 0; i < mas.length; i++)
    {
      if (mas[i] == element)
      {
        return true;
      }
    }
    return false;
  }
  
  
  function downloadNIR()
  {
//	alert(date+dep+filteract);
	var date = getId('select_1301498').value;
	var dep  = getId('select_1301548').value;
	var filteract = '';
	if (getId('filteract').value != 'Поиск') 
	{
		filteract = getId('filteract').value;
		setCookie ('nir_filteract',  filteract);
	//	alert(filteract);
	}	
	//setCookie("nir_date",date);
	
	downloadPage('ajax.php', 'ajax=NIR_METOD_FILES&nir_date='+date+'&nir_dep='+dep+'&nir_filteract='+filteract, 'NIR_METOD_FILES', '', '', 0, 0,13,1,1,0);
  }

