function need_to_show_picker()
{
	var picker 		= document.getElementById("search_date_picker");
	var selector 	= document.getElementById("search_type_selector");
	var show_table = new Array("none","block","block");

	if (picker) {
		picker.style.display = show_table[selector.selectedIndex];
	}
}

function ShowMail(user, domain1, domain2) {
	var email = user+'&#64;'+domain1+'&#46;'+domain2;
	if (ShowMail.arguments[3]) name = ShowMail.arguments[3];
	else name = email;
	document.writeln('<a href="mailto:'+email+'">'+name+'</a>');
}

function SendLink(link_name) {
	window.open("/send/?link="+link_name, "SendLink", "scrollbars=0, resizable=1, width=370, height=230").focus();
}


function MM_findObj(n, d) {
  	var p,i,x;
	if(!d) d=document;
	if((p=n.indexOf("?"))>0&&parent.frames.length) {
	    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) x=d.all[n];
	for (i=0;!x&&i<d.forms.length;i++)
		x=d.forms[i][n];
  	for(i=0;!x&&d.layers&&i<d.layers.length;i++)
		x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById)
		x=d.getElementById(n);
	return x;
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}


	function addBookmark()
	{
	  if (window.external)
	    external.AddFavorite("http://www.dobavkam.net", "Dobavkam.NET - Скажем добавкам нет!")
	  else
    	alert("Браузер не поддерживает эту возможность.");
	}


function openImage(image, ev) {
    var ev = window.event || ev;
    if (ev == undefined) {
        if (image) window.open("/popup.php?img="+image, "popupimage", "scrollbars=0,resizable=0,width=100,height=100,location=0,menubar=0,status=0,toolbar=0").focus();
        return false;
    }
    var obj = ev.srcElement || ev.target;
    if (obj.tagName == 'IMG') obj = obj.parentNode;
    return hs.expand(obj);
}

function preload() {
	b=preload.arguments;
	preload_images = new Array();
	for(i=0; i<b.length; i++) {
		preload_image = new Image;
		preload_image.src=b[i];
		preload_images[i]=preload_image;
	}
}



function menu_sw(x,name,turn) {
	td2=x.parentElement;
	tr=td2.parentElement;
	td1=tr.children(0);
	img=td1.children(0);
	img.src='/images/smenu/'+name+'_ico'+turn+'.gif';
}

function mout(myId,ext){
		s = document.getElementById('img'+myId).src;
		l = s.length;
		s = s.substr(0,l-5);

		document.getElementById('img'+myId).src = s+'.' + ext;

}
function mout_menu(myId){
	document.getElementById('smenu'+myId).style.backgroundColor = '#489442';
}
function mover_menu(myId){
	document.getElementById('smenu'+myId).style.backgroundColor = '#6DA968';
}
//____________________________________________________________________________

function menu_show(id){
	if (document.getElementById('submenu'+id).style.display == 'block') {
		document.getElementById('submenu'+id).style.display = 'none';
		document.getElementById('arr'+id).src = 'images/arr.gif';
	}
	else {
		document.getElementById('submenu'+id).style.display = 'block';
		document.getElementById('arr'+id).src = 'images/arr_act.gif';
	}

}
function rusoft() {
  window.open('http://www.rusoft.ru');
}

// --------------------------------------------------
// ---- Отображение галереи на странице объекта -----
// --------------------------------------------------
var i=0;
var timer;
// --- Клик на кнопку Вперед/Назад
function showGallery(count, mode, rotate){
	i = parseInt(i) + parseInt(mode);
	if (rotate) {
		if (i>=count) i=0;
		if (i<0) i=count-1;
	} else {
		if (i>=count) i=count-1;
		if (i<0) i=0;
	}
	if (i>=0 && (i-1)<count) {
		if (document.getElementById('object_image') && par[i]) {
			document.getElementById('object_image').innerHTML = par[i];
			document.getElementById('object_alt').innerHTML = alt[i];
		}
	}

	changeImageArrows(count);
	return false;
}
function changeImageArrows(count){
	if (i==0) document.getElementById('link_prev').innerHTML = '<span class="ol_previous" style="background: none">Предыдущая</span>';
	else document.getElementById('link_prev').innerHTML = '<a href="javascript:void();" class="ol_previous" onclick="showGallery(' + count + ',-1); return false;" id="prev">Предыдущая</a>';

	if ((i+1)>=count) document.getElementById('link_next').innerHTML = '<span class="ol_next" style="background: none">Следующая</span>';
	else document.getElementById('link_next').innerHTML = '<a href="javascript:void();" onclick="showGallery(' + count + ',1); return false;" class="ol_next" id="next">Следующая</a>';
}
// --- Клие на превью
function SelectImage(type, image, bigimage, width, height, num, count){
	if (this.timer) stopGallery();
	showGallery(count, num-this.i, false);
}
// --- Клик на кнопку Play
function playGallery(count, timeout){
	// Надо вызывать функцию showGallery с какой-то задержкой
	this.timer = window.setInterval("showGallery("+count+", 1, true)", timeout);
	document.getElementById('play').src = '/images/controls_stop_active.gif';
	document.getElementById('play_link').onclick = function(){stopGallery(count); return false;};
}
// --- Клик на кнопку Stop
function stopGallery(count){
	window.clearInterval(this.timer);
	document.getElementById('play').src = '/images/controls_play_active.gif';
	document.getElementById('play_link').onclick = function(){playGallery(count); return false;};
}

function ShowMiddleImage(imagepath, largeimagepath, alt, page, pos) {
	this.i = pos;
	document.getElementById('object_alt').innerHTML = alt;
	var image = '';
	if (largeimagepath) {
		image += '<a href="' + largeimagepath + '" onclick="openImage(\'' + largeimagepath + '\'); return false">';
	}
	image += '<img src="' + imagepath + '" border="0">';
	if (largeimagepath) {
		image += '</a>';
	}
	document.getElementById('object_image').innerHTML = image;
	document.getElementById('return_link').onclick = function() {ShowSmallImage(page); return false};
	document.getElementById('small_photo_div'+page).style.display = 'none';
	document.getElementById('middle_photo_div').style.display = 'block';
}

function ShowSmallImage(page) {
	document.getElementById('small_photo_div'+page).style.display = 'block';
	document.getElementById('middle_photo_div').style.display = 'none';
}

var _page = 1;
// Переход на заданную страницу галереи
function gotoPage(page) {
	document.getElementById('small_photo_div'+page).style.display = 'block';
	document.getElementById('small_photo_div'+_page).style.display = 'none';
	_page = page;
}
// --------------------------------------------------

function showMaterialsDiv(divId)
{
    document.getElementById('materials_'+divId).style.display = 'block';
    var oldId = parseInt(document.getElementById('old_mat_hidden').innerHTML);
    document.getElementById('old_mat_hidden').innerHTML = divId;
    document.getElementById('materials_'+oldId).style.display = 'none';
}

function validateFeedBack()
{
    string = "Заполните, пожалуйста, следующие поля:\r\n";
    var name = document.getElementById('fbname').value;
    var strerror = '';
    var strerror2 = '';
    if(trim(name) == '')
        strerror = "ФИО\r\n";

    var question = document.getElementById('fbtext').value;
    if(trim(question) == '')
	strerror2 = "Текст вопроса\r\n";


    if(strerror == '' && strerror2 == '')
	return true
        alert(string+strerror+strerror2);
    return false;

}

function trim(string)
{
    return string.replace(/(^\s+)|(\s+$)/g, "");
}

function switch_member_tab(num)
{
    switch(parseInt(num)) {
        case 1:
            document.getElementById('1tb').style.display = '';
            document.getElementById('2tb').style.display = 'none';
            document.getElementById('3tb').style.display = 'none';
            document.getElementById('rutab').className = 'active';
            document.getElementById('entab').className = '';
            document.getElementById('frtab').className = '';
            break;
        case 2:
            document.getElementById('1tb').style.display = 'none';
            document.getElementById('2tb').style.display = '';
            document.getElementById('3tb').style.display = 'none';
            document.getElementById('rutab').className = '';
            document.getElementById('entab').className = 'active';
            document.getElementById('frtab').className = '';
            break;
        case 3:
            document.getElementById('1tb').style.display = 'none';
            document.getElementById('2tb').style.display = 'none';
            document.getElementById('3tb').style.display = '';
            document.getElementById('rutab').className = '';
            document.getElementById('entab').className = '';
            document.getElementById('frtab').className = 'active';
            break;
        return true;
    }
}

function delpublication(id){
    if(confirm('Подтвердите удаление публикации.\n(Восстановить публикацию будет невозможно!)'))
        window.location = "/mempage/delpubl/" + id;
    return true;
}

function del_mcontent(id){
    if(confirm('Подтвердите удаление страницы.\n(Восстановить страницу будет невозможно!)'))
        window.location = "/mempage/delcont/" + id;
    return true;
}

function del_mbanner(id){
    if(confirm('Подтвердите удаление баннера.\n(Восстановить баннер будет невозможно!)'))
        window.location = "/mempage/delban/" + id;
    return true;
}

function hideshow(el_id) {
    var disp = document.getElementById(el_id).style.display;
    if (disp == 'none')
        document.getElementById(el_id).style.display = '';
    else
        document.getElementById(el_id).style.display = 'none';
}

function activateform(div_id) {
    document.getElementById(div_id).style.display = '';
    if(window['curform'] != null && window['curform'] != div_id)
        document.getElementById(window['curform']).style.display = 'none';
    window['curform'] = div_id;
}

function getStatusByNum() {
    if (trim(document.getElementById('snumsearch').value) != '')
        window.location = "/ru/feedback/getmsgstate/?num=" + document.getElementById('snumsearch').value;
}
function getStatusByMail() {
    if (trim(document.getElementById('mailsearch').value) != '')
        window.location = "/ru/feedback/getmsgstate/?mail=" + document.getElementById('mailsearch').value;
}
function switchTemplate(_id) {
    currentText = document.getElementById('ta_answer').value;
    document.getElementById('template_' + currentTemplate).value = currentText;
    document.getElementById('ta_answer').value = document.getElementById('template_' + _id).value;
    currentTemplate = document.getElementById('template_options').value;
    return true;
}

var req = null;
//classname

function sendRequest(url, dataString, responseFunction) {
    try
    {
        req=new ActiveXObject('Msxml2.XMLHTTP');
    }
    catch (e)
    {
    	try
    	{
            req=new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch (e)
        {
            if(window.XMLHttpRequest)
            {
               req=new XMLHttpRequest();
            }
        }
    }
	if (req)
	{
		req.open("GET", url, true);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
		req.setRequestHeader("Accept-Language", "ru, en");
		req.setRequestHeader("Accept-Charset", "cp1251");
		if(req.overrideMimeType)
		{
			req.setRequestHeader('Connection', 'close');
		}
		req.onreadystatechange = responseFunction;
		req.send(dataString);
	}
}


function requestResponse(start, end)
{
	if (req.readyState == 4)
	{
		if (req.status == 200)
		{
			document.getElementById('newsCountResults').style.display = 'block';
			response = req.responseText;
			records = response.split("#");

			if (records[0] > 0){
				document.getElementById('chamberLink').href = '/search/?type=chamber_news&start='+start+'&end='+end;
				document.getElementById('chamberCount').innerHTML = records[0];
			}
			toggleParagraphs('chamber', records[0]);

			if (records[1] > 0){
				document.getElementById('regionLink').href = '/search/?type=region_news&start='+start+'&end='+end;
				document.getElementById('regionCount').innerHTML = records[1];
			}
			toggleParagraphs('region', records[1]);
		}
		else {
			var message = 'There was a problem retrieving the XML data: ' + req.statusText;
		}
	}
}
function toggleParagraphs(what, count)
{
	nothing = document.getElementById(what+'NothingFound');
	results = document.getElementById(what+'Par');
	if (count == 0)
	{
		nothing.style.display = "block";
		results.style.display = "none";
	} else {
		nothing.style.display = "none";
		results.style.display = "block";
	}
}
function startDeadMachine()
{
	if(document.getElementById('start_cal').value && document.getElementById('end_cal').value)
		sendRequest(
			'/countOfNews/?start='+document.getElementById('start_cal').value+'&'+'end='+document.getElementById('end_cal').value,
			'',
			function (){requestResponse(document.getElementById('start_cal').value, document.getElementById('end_cal').value)}
		);
}

//blog rating
var xmlHttp;
var blogId;
var commId;

function GetXmlHttpObject()
{
    var objXMLHttp=null
    if (window.XMLHttpRequest)
    {
        objXMLHttp=new XMLHttpRequest()
    }
    else if (window.ActiveXObject)
    {
        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
    }

    return objXMLHttp
}

function stateChangedBlog()
{
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    {
        var xmldoc = xmlHttp.responseXML;
        //alert (xmlHttp.responseText);
        if (xmldoc.getElementsByTagName ('content').item (0).firstChild.data.length != 0) {
            var obj = document.getElementById ('blog_rating_'+blogId);
            obj.innerHTML = xmldoc.getElementsByTagName ('content').item (0).firstChild.data;
            var child = obj.parentNode.childNodes;
            var num = 0;
            for (var i=0; i<child.length; i++) {
                if (child[i].className == 'mines')
                {
                    child[i].src = '/images/rate_btn_mines.gif';
                    child[i].style.cursor = 'default';
                    num++;
                }
                else if (child[i].className == 'pluse')
                {
                    child[i].src = '/images/rate_btn_pluse.gif';
                    child[i].style.cursor = 'default';
                    num++;
                }
                if (num == 2) break;
            }
        }
    }
}

function rateBlog (rate, id, path)
{
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request")
        return
    }
    var url = path;
	blogId = id;

    url=url+"?id="+id;
    url=url+"&rate="+rate;
    url=url+"&sid="+Math.random();

    xmlHttp.onreadystatechange=stateChangedBlog;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


function stateChangedComment()
{
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    {
        var xmldoc = xmlHttp.responseXML;
        //alert (xmlHttp.responseText);
        if (xmldoc.getElementsByTagName ('content').item (0).firstChild.data.length != 0) {
            var obj = document.getElementById ('comment_rating_'+commId);
            obj.innerHTML = xmldoc.getElementsByTagName ('content').item (0).firstChild.data;
            var child = obj.parentNode.childNodes;
            var num = 0;
            for (var i=0; i<child.length; i++) {
                if (child[i].className == 'mines')
                {
                    child[i].src = '/images/rate_btn_mines.gif';
                    child[i].style.cursor = 'default';
                    num++;
                }
                else if (child[i].className == 'pluse')
                {
                    child[i].src = '/images/rate_btn_pluse.gif';
                    child[i].style.cursor = 'default';
                    num++;
                }
                if (num == 2) break;
            }
        }
    }
}

function rateComment (rate, id, path)
{
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request")
        return
    }
    var url = path;
	commId = id;

    url=url+"?id="+id;
    url=url+"&rate="+rate;
    url=url+"&sid="+Math.random();

    xmlHttp.onreadystatechange=stateChangedComment;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}


//HELP
function helpBox() {
	var help = document.getElementById('helpBox');
	if (help.style.display == 'none') {
		help.style.display = 'block';
	}
	else { help.style.display = 'none'; }
}

function help() {
	var help = document.getElementById('help');
	if (help.style.display == 'none') {
		help.style.display = 'block';
	}
	else { help.style.display = 'none'; }
}

function AddToFavorite() {
    var title =  document.title;
    var url = location.href;

    if (window.sidebar) { // Firefox
        window.sidebar.addPanel(title, url, "");
    }
    else if(window.opera && window.print) { // Opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    }
    else if(document.all) { // IE
        window.external.AddFavorite(url, title);
    }
}

function mousePageXY(e, id)
{
	var x = 0, y = 0;
	if (!e) e = window.event;

	if (e.pageX || e.pageY)	{
		x = e.pageX;
		y = e.pageY;
	}
	else if (e.clientX || e.clientY){
		x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
		y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
	}

	document.getElementById('dropNoReg_'+id).style.top = y+'px';
	document.getElementById('dropNoReg_'+id).style.left = x+'px';
}

function feedbackHiddenText() {
	$('.feedbackAnswer a.more, .feedbackQuestion a.more').toggle(
		function () {
			$(this).parent().find('.hiddenText').css('display', 'inline');
			$(this).text('свернуть');
		},
		function () {
			$(this).parent().find('.hiddenText').css('display', 'none');
			$(this).text('развернуть');
		}
	);
}

// file input
function fileInput() {
	var file = $('div.elemBox.file input[type="file"]');

	file.change(function () {
		var inputText = $(this).parent().parent().next().children('input[type="text"]');
		var fileVal = $(this).val();
		inputText.attr('value', fileVal);
	});
}

// placeholder
function placeholder() {
	if (!$.browser.webkit) {
		$('input[placeholder], textarea[placeholder]').blur(function(){

			if ($(this).val() == '') {
				$(this).val($(this).attr('placeholder'));
				$(this).addClass('m-placeholder');
			}

		}).focus(function(){

			$(this).removeClass('m-placeholder');
			if ($(this).val() == $(this).attr('placeholder')) {
				$(this).val('');
			}

		}).each(function(){

			if ( ($(this).val() == '') || ($(this).val() == $(this).attr('placeholder')) ) {
				$(this).val( $(this).attr('placeholder') );
				$(this).addClass('m-placeholder');
			}

			var form = $(this).closest('FORM');
			if (form.length) {
				form.submit(function(){
					if ($(this).val() == $(this).attr('placeholder')) {
						$(this).val('');
					}
				});
			}
		});
	}
}

// gallery list
function galleryList() {
	function secondClass() {
		var $set = $.Deferred();
		$('.galleryList li:nth-child(3n)').prev('li').addClass('center');
		$set.resolve();
		return $set;
	}

	var $ok = secondClass();

	$ok.done(function(){
		// после того, как выполниться secondClass(), делаем это
		$('.galleryList li:nth-child(3n)').after('<li class="cl"></li>');
	});
}

// add hover class
function hover() {
	$('.mainMenu > li').hover(
		function () {
			$(this).addClass('hover');
		},
		function () {
			$(this).removeClass('hover');
		}
	);
}

// add last class
function lastClass() {
	$('.list.control li').last().addClass('last');
	$('.list.blog li').last().addClass('last');
	$('.list.recent li').last().addClass('last');

	var $actual = $('.list.actual');
	$actual.each(function () {
		$(this).children('li').last().addClass('last');
	});
}

// add first class
function firstClass() {
	$('.footer .site li').first().addClass('first');
}

// main themes
function mainThemesSwitch() {
	$('dl.mainThemes dt').hover(
		function(){
			$(this).siblings().removeClass('select').end().next('dd').andSelf().addClass('select');
		},
		function(){}
	);
}

// show calendar
function showCalenadr() {
	$('.calendar a.day').click(function () {
		$(this).parents('td').siblings('td').removeClass('select').end().parents('tr').siblings('tr').children('td').removeClass('select');
		$(this).parents('td').toggleClass('select');

		return false;
	});
    
    $('body').click(function(){
        $('.calendar td.select').toggleClass('select');
    });
    
    $('.eventBox').click(function(evt){
        evt.stopPropagation();
    });
}

// footer height
function footerHeight() {
	$(window).load(function () {
		var $footH = $('.footInsede').outerHeight();

		$('.footer').css({ 'height': $footH, 'marginTop': -($footH + 25) });
		$('.clearFooter').css('height', $footH + 25);
	});
}

showCalendarMonth = function(month, year, type) {
    jQuery.ajax({
        type: 'POST',
		url: '/?q=getCalendarHtml&month='+month+'&year='+year+'&type='+type,
        dataType: 'json',

        timeout: 50000,

//        beforeSend: function() {
//            $('#calendar_html').html('<img src="./images/ajax_load.gif" />');
//        },

        success: function(data) {
            if (typeof data.calendar_nav != 'undefined') {
                $('#calendar_nav').html(data.calendar_nav);
            }

            if (typeof data.calendar_html != 'undefined') {
                $('#calendar_html').html(data.calendar_html);
            }

            showCalenadr();
        },

        error: function(request, status, errorT) {
            //		alert('XMLHttpRequest='+request.responseText+'textStatus='+status+'errorThrown='+errorT);
            alert ('Произошел сбой. Запрос не может быть выполнен. Повторите попытку позже.');
        }
    });
};

function langSelct() {
	$('.langBox .now, .sorting .now').click(function () {
		$(this).parent().toggleClass('show');
	});
}

// drop menu height
function menuHeight() {
	var $menuH = $('.mainMenu ul').outerHeight();
	$('.mainMenu').css('paddingBottom', $menuH + 10);
}

function evenClass() {
	$('.memberInfo tr:even').addClass('even');
}

// select auth form
function selectAuthForm() {
	$('.authBtn a').click(function () {
		var $name = $(this).attr('name');

		$('.authBox').removeClass('select');
		$('.authBox.' + $name).addClass('select');

		return false;
	});
}

// insert to blog
function insertToBlog() {
	$('.insertToBlog').click(function () {
		$(this).next('.insertContent').toggleClass('show');
		return false;
	});
}

// show more text
function showMore() {
	$('.showMore').toggle(
		function () {
			$(this).parent('.moreBox').prev('p').children('.hiddenText').addClass('show');
			$(this).html('- <span>свернуть</span>');
			return false;
		},
		function () {
			$(this).parent('.moreBox').prev('p').children('.hiddenText').removeClass('show');
			$(this).html('+ <span>развернуть</span>');
			return false;
		}
	);
	
	$('.moreBox.showMoreHidden a.more').toggle(
		function () {
			$(this).parent('.moreBox').siblings('.commentFixText').addClass('auto');
			$(this).html('- <span>свернуть</span>');
			return false;
		},
		function () {
			$(this).parent('.moreBox').siblings('.commentFixText').removeClass('auto');
			$(this).html('+ <span>развернуть</span>');
			return false;
		}
	);
}
function hotLine() {
	$('.hotLine tr:odd').addClass('odd');
}

function tabSwitch() {
	$('dl.tabs dt').click(function(){
		$(this).siblings().removeClass('select').end().next('dd').andSelf().addClass('select');
	});	
}
