var pxInEm = 14;

function tableHover(target)
{
	
	var elNode;
	if (target)
	{
		if (typeof(target) == 'string')
		{
			if (!(elNode = document.getElementById(target)))
				return false;
		}
		else
		{
			elNode = target;
		}
	}
	else
		elNode = document;
		
	var Tables = elNode.getElementsByTagName('table');
	var Trs = [];
	
	for (var i = 0; i < Tables.length; i++)
	{
		if (matchClass(Tables[i],'nohover') || Tables[i].getElementsByTagName('table').length > 0 || Tables[i].getElementsByTagName('tr').length < 3)
			continue;
		
		Trs = Tables[i].getElementsByTagName('tr');
		for (var j = 0; j < Trs.length; j++)
		{
			if (!matchClass(Trs[j],'nohover'))
			{
				Trs[j].onmouseover = function (){addClass(this,'hovered');};
				Trs[j].onmouseout = function () {removeClass(this,'hovered');};
			}		
		}				  
	}

}

/** common **/

function $(element)
{
	return document.getElementById(element);
}



function createRequest()
{
	var hRequest;
	if (window.XMLHttpRequest)
	{
		hRequest = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		var XMLHTTP_IDS = new Array(
			'MSXML2.XMLHTTP.5.0',
			'MSXML2.XMLHTTP.4.0',
			'MSXML2.XMLHTTP.3.0',
			'MSXML2.XMLHTTP',
			'Microsoft.XMLHTTP' );
		var success = false;
		for (var i = 0; i < XMLHTTP_IDS.length && !success; i++)	
		{
			try
			{
				hRequest = new ActiveXObject(XMLHTTP_IDS[i]);
				if (hRequest)
					success = true;
			}
			catch (e) {}
		}
		
	}
	return hRequest ? hRequest : false;
}

function evalScripts(str)
{
	var aMatches = str.match(/<script[^>]+>((.|\r\n|\n|\r)*?)<\/script>/igm);
	if (aMatches)
	{
		for (var i = 0; i < aMatches.length; i++)
		{
			aMatches[i] = aMatches[i].replace(/(\t)+/ig,' ').replace(/<\/?script[^>]*?>/ig,'').replace(/(<!\[CDATA\[|\]\]>)/ig,'');
			//document.getElementById('debugDiv').innerHTML += aMatches[i] + '<br /><br />';
			window.eval(aMatches[i]);
		}
		
	}
}

function encodeUTF(sValue) { 
  
		var
			text = "",
			Ucode,
			ExitValue,
			s;
  
		for(var i = 0; i < sValue.length; i++) { 
  
			s = sValue.charAt(i);
			Ucode = s.charCodeAt(0);
		
			var Acode = Ucode;
		
			if(Ucode > 1039 && Ucode < 1104) { 
		
				Acode -= 848;
				ExitValue = "%" + Acode.toString(16);          
			
			}
			else if(Ucode == 1025) {
		
				Acode = 168; 
				ExitValue = "%" + Acode.toString(16);          
				
			}
			else if(Ucode == 1105) {
		
				Acode = 184;
				ExitValue = "%" + Acode.toString(16);          
				
			} 
			else if(Ucode == 32) {
      
				Acode = 32;
				ExitValue = "%" + Acode.toString(16);          
		
			} 
			else if(Ucode == 10){
		
				Acode = 10;
				ExitValue = "%0A";
			}
			else {
		
				ExitValue = s;          
			
			}
     
			text = text + ExitValue; 

		}      
		
		return text; 
	
	}



/** main show/hide **/

function ShowSection(url,sectionId,dTitle)
{
	/*if (pagesSummary[sectionId] != -1) 
	{
		if (pagesSummary[sectionId] == url)
		{
			HideSection(sectionId);
			return;
		}
		else if (sectionId == url)
		{
			url = sectionId;
		}
	}*/
	
	var permaLink = $('permalink_' + sectionId);
	
	if (pagesSummary[sectionId] != -1) 
	{
		if (sectionId == url && pagesSummary[sectionId] == url)
		{
			HideSection(sectionId);
			//permaLink.getElementsByTagName('a')[0].href = '#';
			//addClass(permaLink,'hidden');
			return;
		}
		else if (pagesSummary[sectionId] == url)
		{
			url = sectionId;
		}
	}
	var hRequest = createRequest();
	if (!hRequest)
		return false;
		
	var oNode = $(sectionId);
	
//	permaLink.getElementsByTagName('a')[0].href = url;
//	removeClass(permaLink,'hidden');
	
	var ourDiv = $(sectionId + '_content');
	if (isMSIE)
	{
		ourDiv.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=50)';
	}
	
	addClass(oNode,'loading');
	
	
	
	var currentHeight = oNode.getElementsByTagName('td')[0].offsetHeight > ourDiv.offsetHeight ? oNode.getElementsByTagName('td')[0].offsetHeight : ourDiv.offsetHeight;
	var neededHeight = Math.max(currentHeight,60);
	
	var HeightTween = new Tween(ourDiv, 'height', Math.linearTween, currentHeight, neededHeight, Math.abs(currentHeight-neededHeight)/60, 'px');
		
	removeClass(oNode,'hidden');
	if ($(sectionId + '_navigation'))
		addClass($(sectionId + '_navigation'),'currentLink');
		
	showMiniMapItem(sectionId);
	
	hRequest.onreadystatechange = function () {DisplaySection(hRequest,sectionId,url,dTitle);};
	hRequest.open('GET',url + (url.match(/\?/) ? '&' : '?') + 'ajax=on',true);
	hRequest.send(null);

}
function HideSection(sectionId)
{
	
	var oNode = $(sectionId);
	var ourDiv = $(sectionId + '_content');
	addClass(oNode,'loading');
	var currentHeight = oNode.getElementsByTagName('td')[0].offsetHeight > ourDiv.offsetHeight ? oNode.getElementsByTagName('td')[0].offsetHeight : ourDiv.offsetHeight;
	
	
	var HeightTween = new Tween(ourDiv, 'height', Math.linearTween, currentHeight,22, currentHeight/60, 'px');
	HeightTween.onMotionFinished = function()
	{
		removeClass(oNode,'loading');
		//oNode.getElementsByTagName('td')[0].innerHTML = '';
		//ourDiv.innerHTML = '';
//		menuMeasurer.innerHTML = contentMeasurer.innerHTML = '';
//		evalScripts(oNode.innerHTML);
		addClass(document.getElementById(sectionId),'hidden');
		if (document.getElementById(sectionId + '_navigation'))
			removeClass(document.getElementById(sectionId + '_navigation'),'currentLink');
		miniMapScroll();
		if (checkOneOpen() === false)
			hideMiniMap();
	}
	
	hideMiniMapItem(sectionId);
	pagesSummary[sectionId] = -1;
	
	miniMapScroll();
	
	
	
}

function checkOneOpen()
{
	if (!pagesSummary)
		return -1;
	for (var i in pagesSummary)
	{
		if (typeof (pagesSummary[i]) != 'function' && pagesSummary[i] != -1)
			return true;
	}
	return false;
}

function DisplaySection(hRequest,sectionId,url,dTitle)
{
	if (!hRequest || !$(sectionId))
	{
		document.location = url;
		return false;
	}
	
	if (hRequest && hRequest.readyState == 4) 
	{
		if (hRequest.status == 200)
		{
			var oNode = $(sectionId);
			var rsDump=hRequest.responseText;
			rsDump=rsDump.replace(/\r?\n/g, '');
			
			//var matches = hRequest.responseText.match(/<ajax-content>((.|\n|\r\n|\r)*?)<\/ajax-content>/ig);
			var matches = rsDump.match(/<ajax-content>(.*?)<\/ajax-content>/ig);
			var menuMeasurer = $('mainLeftMenuMeasurer');
			var contentMeasurer = $('mainContentMeasurer');
			
			var ourDiv = $(sectionId + '_content');
			if (isMSIE)
			{
				ourDiv.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=50)';
			}
			
			//addClass(oNode,'loading');
			
			
			menuMeasurer.innerHTML = matches[0].replace(/<\/?ajax-content>/ig,'');
			contentMeasurer.innerHTML = matches[1].replace(/<\/?ajax-content>/ig,'');
		
			var neededHeight = Math.max(menuMeasurer.offsetHeight,contentMeasurer.offsetHeight);
			var currentHeight = oNode.getElementsByTagName('td')[0].offsetHeight > ourDiv.offsetHeight ? oNode.getElementsByTagName('td')[0].offsetHeight : ourDiv.offsetHeight;
			
			var HeightTween = new Tween(ourDiv, 'height', Math.linearTween, currentHeight, neededHeight, Math.abs(currentHeight-neededHeight)/60, 'px');
			HeightTween.onMotionFinished = function()
			{
				removeClass(oNode,'loading');
				oNode.getElementsByTagName('td')[0].innerHTML = menuMeasurer.innerHTML;
				ourDiv.innerHTML = contentMeasurer.innerHTML;
				if (!isMSIE)
					ourDiv.style.height = 'auto';
				else
				{
					ourDiv.runtimeStyle.filter = '';
					ourDiv.style.height = '90%';
				}
				menuMeasurer.innerHTML = contentMeasurer.innerHTML = '';
				evalScripts(oNode.innerHTML);
				tableHover(oNode);
			}
			
			removeClass(oNode,'hidden');
			if ($(sectionId + '_navigation'))
				addClass($(sectionId + '_navigation'),'currentLink');
				
			showMiniMapItem(sectionId);
			
			/*if (dTitle)
				document.title = dTitle;*/
			pagesSummary[sectionId] = url;
			miniMapScroll();
		
			showMiniMap();
		}
	}
	
}

function sendForm(form)
{
	if (!form)
		return false;
	var params = collectFormParams(form);
	params += '&ajax=on';
	
	
	var neededParent = null;
	var startNode = form;
	while (!neededParent && startNode.parentNode)
	{
		if (matchClass(startNode.parentNode,'contentHolder'))
			neededParent = startNode.parentNode;
		startNode = startNode.parentNode;
	}
	var sectionId = neededParent.id.replace(/_content/i,'');
	
	//alert(pagesSummary[sectionId]);
	//alert(params);
	
	var hRequest = createRequest();
	if (!hRequest)
		return false;
		
	hRequest.onreadystatechange = function () {DisplaySection(hRequest,sectionId,form.action ? form.action : form.getAttribute('action'));};
	
	hRequest.open('POST', form.action ? form.action : form.getAttribute('action'), true);
	hRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	hRequest.setRequestHeader("Content-length", params.length);
	hRequest.setRequestHeader("Connection", "close");
	hRequest.send(params);
	
	//hRequest.open('GET',form.action ? form.action : form.getAttribute('action') + params,true);
	//hRequest.send(null);
	
	
}

function collectFormParams(form)
{
	if (!form)
		return false;
		
	var readyParams = '';
	
		
	var inputs = form.getElementsByTagName('input');
	for (var i = 0; i < inputs.length; i++)
	{
		readyParams += (readyParams.length > 0 ? '&' : '') + inputs[i].name + '=' + encodeUTF(inputs[i].value);
	}
	return readyParams;
	
}


/** issue parameters **/
function ShowIssueParameters(sender,url,sectionId)
{
	if (!$(sectionId))
		return false;
	if (!matchClass($(sectionId).parentNode,'hidden'))
		HideIssueParameters(sectionId);
	else
	{
		var hRequest = createRequest();
		if (!hRequest)
			return false;
			
		hRequest.onreadystatechange = function () {DisplayIssueParameters(hRequest,sectionId,sender);};
		hRequest.open('GET',url + (url.match(/\?/) ? '&' : '?') + 'ajax=on',true);
		hRequest.send(null);
	}
}
function HideIssueParameters(sectionId)
{
	if ($(sectionId))
		addClass($(sectionId).parentNode,'hidden');
}
function DisplayIssueParameters(hRequest,sectionId)
{
	if (!hRequest || !$(sectionId))
	{
//		document.location = url;
		return false;
	}
	
	if (hRequest && hRequest.readyState == 4) 
	{
		if (hRequest.status == 200)
		{
			var oNode = $(sectionId);
			var matches = hRequest.responseText.match(/<ajax-content>((.|\n|\r\n|\r)*?)<\/ajax-content>/igm);
			oNode.innerHTML = matches[1];
			evalScripts(oNode.innerHTML);
			removeClass(oNode.parentNode,'hidden');
		}
	}
			
}



function CloseAll()
{
	if (pagesSummary)
	{
		for (var i in pagesSummary)
		{
			if (typeof (pagesSummary[i]) != 'function' && pagesSummary != -1)
			{
				HideSection(i);
			}
		}
	}
	
	//document.title = rootTitle ? rootTitle : 'Мосфинагентство';
}

function showCouponPeriods(sender)
{
	while (sender.parentNode)
	{
		if (sender.parentNode.nodeName.toLowerCase() == 'table')
		{
			var trs = sender.parentNode.getElementsByTagName('tr');
			for (var i = 0; i < trs.length; i++)
			{
				if (matchClass(trs[i],'couponPeriods') && !matchClass(trs[i],'currentCoupon'))
				{
					switchClass(trs[i],'hidden','visible');
				}
			}
			return false;
		}
		
		sender = sender.parentNode;
	}
	return false;
}

function selectRow(sender)
{
	if (sender.nodeName.toLowerCase() == 'tr')
	{
		if (!matchClass(sender,'selectedRow'))
			addClass(sender,'selectedRow');
		else
			removeClass(sender,'selectedRow');
	}
	else if (sender.parentNode)
		selectRow(sender.parentNode);
	else
		return false;
}











function putContents(hRequest,target)
{

	if (!target || !document.getElementById(target) || !hRequest)
		return false;

	if (hRequest && hRequest.readyState == 4) {
            if (hRequest.status == 200) {
            	var oNode = document.getElementById(target);
                oNode.innerHTML = hRequest.responseText;
            }
        }
}




function parseAjaxContentTo(hRequest,target,url)
{

	if (!target || !document.getElementById(target) || !hRequest)
		return false;

	if (hRequest && hRequest.readyState == 4) {
            if (hRequest.status == 200) {
            	var oNode = document.getElementById(target);
				
				var matches = hRequest.responseText.match(/<ajax-content>((.|\n|\r\n|\r)*?)<\/ajax-content>/igm);
//				alert(hRequest.responseText);
//				document.getElementById('debugDiv').innerHTML = hRequest.responseText;
				if (oNode.nodeName.toLowerCase() == 'tr')
				{
					oNode.getElementsByTagName('td')[0].innerHTML = matches[0];
					oNode.getElementsByTagName('td')[1].innerHTML = matches[1];
	//				alert(oNode.getElementsByTagName('td')[1].getElementsByTagName('div')[0].id);
					removeClass(oNode,'hidden');
					if (document.getElementById(target + '_navigation'))
						addClass(document.getElementById(target + '_navigation'),'currentLink');
					evalScripts(oNode.innerHTML);
				}
				else if (oNode.nodeName.toLowerCase() == 'div')
				{
					if (!oNode.innerHTML.match(/\S/))
					{
						oNode.innerHTML = matches[1];
						evalScripts(oNode.innerHTML);
					}
					removeClass(oNode.parentNode,'hidden');
				}
				
				pagesSummary[target] = url;
            }
        }
}



function ShowContent(url,sId,dTitle,loadAll)
{
	//alert(pagesSummary['/ru/moscow/']);
	if (pagesSummary[sId] != -1)
	{
		if (pagesSummary[sId] == url)
		{
			HideContent(sId);
			return;
		}
	}
	
	var hRequest = createRequest();
	if (!hRequest)
		return false;
	
	hRequest.onreadystatechange = function () {parseAjaxContentTo(hRequest,sId,url);};
	hRequest.open('GET',url + (url.match(/\?/) ? '&' : '?') + 'ajax=on',true);
	hRequest.send(null);
	
	//document.title = dTitle;
	
}

/**
rate graphs
**/
function switchRateGraph(switchId)
{
	var oneChecked = false;
	for (var i in rateGraphs)
	{
		if (typeof(rateGraphs[i]) != 'function')
		{
			if (rateGraphs[i] != -1 && i != switchId)
				oneChecked = true;
		}
	}
	if (oneChecked)
	{
		if (rateGraphs[switchId] != -1)
		{
			$('img_'+switchId).style.display = 'none';
			rateGraphs[switchId] = -1;
			$(switchId).checked = '';
		}
		else
		{
			$('img_' + switchId).style.display = 'inline';
			rateGraphs[switchId] = 1;
			$(switchId).checked = true;
		}
		return true;
	}
	else
	{
		$(switchId).checked = true;
		rateGraphs[switchId] = 1;
		return false;
	}
}
function addRateGraph(switchId)
{
	$(switchId).checked = true;
	rateGraphs[switchId] = 1;
	$('img_' + switchId).style.display = 'inline';
}


var  m = document.uniqueID /*IE*/
        && document.compatMode  /*>=IE6*/
        && !window.XMLHttpRequest /*<=IE6*/
        && document.execCommand ;

        try{
                if(!!m){
                        m("BackgroundImageCache", false, true) /* = IE6 only */
                }

        }catch(oh){};