// comments
function voteForCom(cid,rate)
{	
	$.post("/ajax/cvote/", { commentid: cid, rate: rate },
		  function(data){
		  	if(data && data.length<300 && data.length>0)
		  	{
		    	$("#cvote"+cid).html(data);
		  	}
		  });
	return false;
}

function voteForOtzyv(cid,rate)
{	
	$.post("/ajax/ovote/", { commentid: cid, rate: rate },
		  function(data){
		  	if(data && data.length<300 && data.length>0)
		  	{
		    	$("#ovote"+cid).html(data);
		  	}
		  });
	return false;
}

function deleteMDate(block, id) 
{
	if (id == 0)
	{
		$("#"+block).fadeOut(500);
	}
	else
	{
		$.post("/ajax/deletemdate/", 
		{id: id},
			function(data){
				if(data == 'error') return;
				$("#"+block).fadeOut(500);
			});
	}
}
function addFriend(userid)
{
  $('#a_addfriend').hide();
  $('#a_statusfriend').html('Отправка запроса...').show();
  $.post("/ajax/newfriend/", { 'userid':userid },
		  function(data){
		  	if(data && data.length<300 && data.length>0)
		  	{
          if(data=='accepted' || data=='already')
          {
		    	  $('#a_statusfriend').html('Добавлен в друзья');
          }
          if(data=='waiting')
          {
		    	  $('#a_statusfriend').html('Заявка отправлена');
          }
          if(data=='error')
          {
		    	  $('#a_statusfriend').html('Ошибка');
          }
		  	}
		  });
 return false;
}

function acceptFriend(userid)
{
  $.post("/ajax/acceptfriend", { 'userid':userid } ,function(data){
    if(data=='ok')
	 	{
      $('#info-box-buttons').hide();
      $('#info-box-status').show();  
    }
    else
    { 
      alert('Произошла ошибка. Обновите страницу и попробуйте снова.');
    }
  });
  return false;
}


function declineFriend(userid)
{
  $.post("/ajax/declinefriend", { 'userid':userid } );
  $('#info-mail-box').load('/ajax/infomailbox/');
  return false;
}

function closeInfoBox()
{
  $('#info-mail-box').load('/ajax/infomailbox/');
  return false;
}

var current_comment_form=0;
function addComment(parentid,guestmode,doctype)
{
	text = document.getElementById('comment_tex_'+parentid).value;
	if(text.length==0) return;
	//text = encodeURIComponent(text);
	
	$("#comment_button_"+parentid).attr("disabled","disabled");
	$("#comment_tex_"+parentid).attr("disabled","disabled");
	$("#comment_span_"+parentid).html("Идёт добавление комментария...");
	
	var cap=0;
	var guestname = '';
	var gmode = 0;
	if(guestmode)
	{
		cap = $('#cap_'+parentid).val();
		guestname = $('#guestname_'+parentid).val();
		gmode = 1;
	}

	// отправляем коммент, получаем массив - статус (0 если неудача, или id добавленного коммента если удача) и ветку
	$.post("/ajax/newcomment/", 
		{doctype:doctype, parentid: parentid, tex: text, guestmode: gmode, cap:cap, guestname: guestname},
  		function(data){
  			if(data=='captcha')
  			{
  				$("#comment_span_"+parentid).html("Неправильно указан код с картинки");
  			}
  			else
  			{ 				
  				data = eval(data);
					
					if(data.id)
	  			{  			
            $('#com_div_'+parentid).hide();
            
		  			var cont = $("#comment_node_"+parentid);
		  			if(cont.attr("rel")=='rootnode') {
		  				$("#comment_node_"+parentid).html(data.html);
						}
		  			else {
		  				$("#comment_node_"+parentid).replaceWith(data.html);
						}
		  			
		    		$('#comment_tex_'+parentid).val("");
		    		$("#comment_span_"+parentid).html("");
						document.location.href='#com'+data.id;
	  			}
	  			else  				
	  			{
  					$("#comment_span_"+parentid).html("При добавлении комментария произошла ошибка");
  				}
	  		}  			
			$("#comment_tex_"+parentid).removeAttr("disabled");
			$("#comment_button_"+parentid).removeAttr("disabled");			
  		});
	return false;
}


function showCommentForm(parentid)
{
	if(current_comment_form) {$("#comments_form_"+current_comment_form).hide();}
	
	$("#comments_form_"+parentid).show();
	current_comment_form=parentid;
}


function expandComments(parentid,that)
{
	$("#comments_subtree_"+parentid+" div").html('<br>Идёт загрузка ветки комментариев...');
	$("#comments_subtree_"+parentid).load("/ajax/commentsubtree", {parentid: parentid});
}


function simpleDeleteComment(id)
{
	$.post("/ajax/deletecomment2", 
		{id: id},
  		function(data){
  			if(data=='error') return;
				$("#del_com_"+id).replaceWith('<small class="red">Комментарий был удалён</small>');
  		});
}

function deleteComment(id,parentid,childcount)
{
	var question = 'Вы уверены в том что хотите удалить этот комментарий?';
	if(childcount%10==1 && childcount%100!=11) question = 'Вместе с этим комментарием удалится и один ответ на него. Все равно удалить?';
	else if(childcount>0) question = 'Вместе с этим комментарием удалятся и '+childcount+' вложенных. Удалить всю ветку?';
	if(!confirm(question)) return;
	
	// отправляем запрос, получаем массив - статус (0 если неудача, или parentid если удалили) и ветку родителя
	$.post("/ajax/deletecomment", 
		{id: id, parentid: parentid},
  		function(data){
  			if(data=='error') return;
  			
			// все нормально - удалился, подгружаем ветку
			var cont = $("#comment_node_"+parentid);
 			if(cont.attr("rel")=='rootnode')
  				$("#comment_node_"+parentid).html(data);
  			else
  				$("#comment_node_"+parentid).replaceWith(data);
  		});
}

// ajax-проверки:
function ajaxCheckLoginInn()
{
	var str = $('#login_id_inn').val();
	if(str.length==0) 
	{
		$('#login_error_inn').html("Введите логин");
		$('#login_id_inn').get(0).focus();
		return false;
	}
	$('#login_error_inn').html("идёт проверка...");
	$.get("/check/signup/login", { login: str },
		function(data){
		  if(data=='ok') 
		  	  $('#login_error_inn').html("Логин свободен");
		  else
			  $('#login_error_inn').html(data);
	});
	return false;
}

// ajax-проверки:
function ajaxCheckLogin()
{
	var str = $('#login_id').val();
	if(str.length==0) 
	{
		$('#login_error').html("Введите логин");
		$('#login_id').get(0).focus();
		return false;
	}
	$('#login_error').html("идёт проверка...");
	$.get("/check/signup/login", { login: str },
		function(data){
		  if(data=='ok') 
		  	  $('#login_error').html("Логин свободен");
		  else
			  $('#login_error').html(data);
	});
	return false;
}


// ajax-загрузка селекта
function loadSelect(url, key, output_id)
{
	var box = $('#'+output_id);
	box.html('<option value="0">идёт загрузка...');
	var str='';
	$.getJSON(url, { key: key },
		function(data){
		  for(obj in data)
		  {
		  	str+='<option value="'+data[obj]['id']+'">'+data[obj]['title'];
		  }
		  box.html(str);
		  box.get(0).disabled=false;
	});
}

// util
function selectBoxes(className)
{
	$('.'+className).each(
		function()
		{
			this.checked=true;
		}
	);
	return false;
}

// news filter
function newsFilter()
{
	var countryurl = $('#news_country').val();
	var newstype = $('#news_type').val();
	if(countryurl=='0' && newstype=='0') lnk = '/news';
	if(countryurl!='0' && newstype=='0') lnk = '/news/'+countryurl;
	if(countryurl=='0' && newstype!='0') lnk = '/news/'+newstype;
	if(countryurl!='0' && newstype!='0') lnk = '/news/'+countryurl+'/'+newstype;
	document.location.href = lnk;
	return false;
}

// hotels select
function showHotel(city_url,country_url)
{
	var hotel = $('#hotels_'+city_url).val();
	if(hotel=='0') document.location.href = '/hotels/'+country_url+'/'+city_url;
	else document.location.href = '/hotel/'+hotel;
}

// new-spo
function countryCity(country_id, block_id) 
{
	for(var i = 1; i <= 5; i++)
	{
		loadSelect('/load/cities',country_id,'city_id_'+block_id+'_'+i);
	}
}

// tour
function countryCityHotelsLoad(country_id)
{
	if(country_id)
	{
		loadSelect('/load/cities',country_id,'city_id');
		loadSelect('/load/cityhotels',0,'hotel_id');
	}
}

// my-page
function countryCityHotels(country_id)
{
	if(country_id==idblr)
	{
		loadSelect('/load/oblast',country_id,'city_id');
		loadSelect('/load/oblastestates',0,'hotel_id');
	}
	else
	{
		loadSelect('/load/cities',country_id,'city_id');
		loadSelect('/load/cityhotels',0,'hotel_id');
	}
}

// touralbums
function countryCityHotels2(country_id)
{
	if(country_id==idblr)
	{
		$('#s3ta_city').html('По областям:');
		$('#s3ta_hotel').html('По усадьбам:');
		loadSelect('/load/oblast',country_id,'city_id');
		loadSelect('/load/oblastestates',0,'hotel_id');
	}
	else
	{
		$('#s3ta_city').html('По городам:');
		$('#s3ta_hotel').html('По отелям:');
		loadSelect('/load/cities',country_id,'city_id');
		loadSelect('/load/cityhotels',0,'hotel_id');
	}
}

function cityHotels(country_id,city_id)
{
	if(country_id==idblr)
		loadSelect('/load/oblastestates',city_id,'hotel_id');
	else
		loadSelect('/load/cityhotels',city_id,'hotel_id');
}

var booking = '<input type="hidden" name="url" value="http://www.booking.com/searchresults.html" /><input type="hidden" name="aid" value="332431" /><input type="hidden" name="error_url" value="http://www.booking.com/?aid=332431;" /><input type="hidden" name="label" value="" /><input type="hidden" name="lang" value="ru" /><input type="hidden" name="ifl" value="" /><input type="hidden" name="aid" value="332431" /><input type="hidden" name="lang" value="ru" /><input type="hidden" name="sid" value="654299d518cb8583304a76af33f00b0b" /><input type="hidden" name="si" value="ai,co,ci,re" />';

// site search
function update_search()
{
	var s_string = $("input[name=q]").val();
	$("input[name=ss]").val(s_string);
}

function search_toggle(that)
{
	if(that.id=='s_news')
	{
		$('#s_what').val('news');
		that.className='act';
		$('#s_tours').removeClass('act');
		$('#s_spos').removeClass('act');
		$('#s_trips').removeClass('act');
		
		$('.hs').attr('action','/reservation/results');
		$('#booksearch').html(booking);
	}
	
	if(that.id=='s_spos') 
	{
		$('#s_what').val('spos');
		that.className='spo act';
		$('#s_tours').removeClass('act');
		$('#s_news').removeClass('act');
		$('#s_trips').removeClass('act');
	}
	if(that.id=='s_trips') 
	{
		$('#s_what').val('trips');
		that.className='trip act';
		$('#s_tours').removeClass('act');
		$('#s_news').removeClass('act');
		$('#s_spos').removeClass('act');
	}
	if(that.id=='s_tours') 
	{
		$('#s_what').val('tours');
		that.className='act';
		$('#s_news').removeClass('act');
		$('#s_spos').removeClass('act');
		$('#s_trips').removeClass('act');
	}
		//alert(that.className='act');
	return false;
}


// messaging
function showMessageBox()
{
	$('#sm_box').slideDown();
	return false;
}

function resetMessageBox()
{
	$('#sm_sent').hide();
	$('#sm_sending').hide();
	$('#sm_button').show();
	document.getElementById('sm_text').value='';
//	document.getElementById('sm_subject').value='';
}

function sendMes()
{
	text = document.getElementById('sm_text').value;
	//subject = document.getElementById('sm_subject').value;
	recipient = document.getElementById('sm_recipient').value;
	
	if(text.length=='') {alert('Введите текст сообщения');document.getElementById('sm_text').focus();return false;}
	
	$('#sm_button').hide();
	$('#sm_sending').show();
	
	$.post('/mail/send',
		{ 'subject':'', 'text':text, 'recipient':recipient }, 
		function(data){
			data = eval(data);
			if(data.status=='ok')
			{
				$('#sm_sending').hide();
				$('#sm_sent').show();
			}
			// other cases
	});

	return false;
}


function sendAdminMes()
{
	text = document.getElementById('sm_text').value;
	recipient = document.getElementById('sm_recipient').value;
	
	if(text.length=='') {alert('Введите текст сообщения');document.getElementById('sm_text').focus();return false;}
	
	$('#sm_button').hide();
	$('#sm_sending').show();
	
	$.post('/adm/mail/send',
		{ 'subject':'', 'text':text, 'recipient':recipient }, 
		function(data){
			data = eval(data);
			if(data.status=='ok')
			{
				$('#sm_sending').hide();
				$('#sm_sent').show();
			}
			// other cases
	});

	return false;
}


function sendMes2()
{
	$('#sm_sent').hide();
	
	text = document.getElementById('sm_text').value;
	recipient = document.getElementById('sm_recipient').value;
	
	if(text.length=='') {alert('Введите текст сообщения');document.getElementById('sm_text').focus();return false;}
	
	$('#sm_button').hide();
	$('#sm_sending').show();
	
	$.post('/mail/send',
		{ 'subject':'', 'text':text, 'recipient':recipient }, 
		function(data){
			data = eval(data);
			if(data.status=='ok')
			{
				$('#sm_sending').hide();
				$('#sm_button').show();
				$('#sm_sent').show();
			 document.getElementById('sm_text').value='';
			}
			// other cases
	});

	return false;
}

function sendMes2new()
{
	$('#sm_sent').hide();
	
	subject = document.getElementById('sm_subject').value;
	text = document.getElementById('sm_text').value;
	recipient = document.getElementById('sm_recipient').value;
	recipienttype = document.getElementById('sm_recipienttype').value;
	
	if(text.length=='') {alert('Введите текст сообщения');document.getElementById('sm_text').focus();return false;}
	
	$('#sm_button').hide();
	$('#sm_sending').show();
	
	$.post('/mailnew/send',
		{ 'subject':subject, 'text':text, 'recipient':recipient, 'recipienttype':recipienttype }, 
		function(data){
			data = eval(data);
			if(data.status=='ok')
			{
				$('#sm_sending').hide();
				$('#sm_button').show();
				$('#sm_sent').show();
			 document.getElementById('sm_text').value='';
			}
			// other cases
	});

	return false;
}

function sendMes3()
{
	$('#sm_sent').hide();	
	
  text = document.getElementById('sm_text').value;
	
	if(text.length=='') {alert('Введите текст сообщения');document.getElementById('sm_text').focus();return false;}
	
	$('#sm_button').hide();
	$('#sm_sending').show();
	
	return true;
}

// favourites 
function add2favourites(docid,that)
{
	$.post("/favourites/add", { documentid: docid },
  function(data){
		data = eval(data);
	
		if(data.status=='ok' || data.status=='already') $(that).remove();
		if(data.status=='ok') $('#bloknot_count').html(data.count);
	 
	  if(data.status=='ok') alert('Новая запись добавлена в блокнот.');
		if(data.status=='user') alert('Зарегистрируйтесь на сайте чтобы пользоваться блокнотом.');
		if(data.status=='alredy') alert('Такая запись уже есть в вашем блокноте.');
  });	
	return false;
}

function removeFromFavourites(docid,that)
{
	$.post("/favourites/remove", { documentid: docid },
  function(data){
		data = eval(data);
	
		if(data.status=='ok') $(that).slideUp();
		if(data.status=='ok') $('#bloknot_count').html(data.count);
	 
	  if(data.status=='ok') alert('Запись удалена из блокнота.');
		if(data.status=='user') alert('Войдите на сайт чтобы пользоваться блокнотом.');
  });	
	return false;
}


// rating
function voteForDoc(docid,rate)
{	
	$.post("/ajax/vote/", { documentid: docid, rate: rate },
		  function(data){
		  	if(data && data.length<100 && data.length>0)
		  	{
		  		if(data=='ip') {alert('С одного IP можно голосовать за один альбом не чаще чем раз в час. Попробуйте позже.');return;}
		  		data = eval(data);
					$("#stars_for_"+docid+" span").attr('class',data.xx);
		    	//$("#rating"+docid).html(data.rating);
		    	//$("#votes"+docid).html(data.votes + ' '+plural_form(parseInt(data.votes),'голос','голоса','голосов'));
		    	$("#voted"+docid).show();
		  	}
		  });
}

function clearStars(objid)
{
	$('#rating_for_'+objid+' .star').removeClass('star_on');
	$('input[@name=rating_'+objid+']').val('');
}

// linked
function showLinkedMore()
{
	$('#linked_more').slideDown();
	$('#linked_more_block').slideUp();
	
	$('.linked_more').each(
		function(i)
		{
			this.src=this.alt;
			this.alt='';
		}
	);
	
	return false;
}


// invite
function invite()
{
	email = $('#invite_email').val();
	if(email=='') 
	{
		$('#invite_message').addClass('error');
		return false;
	}
	$('#invite_message').removeClass('error');
	
	$('#invite_who1').html(email);
	$('#invite_who2').html(email);
	
	$('#invite_form').hide();
	$('#invite_sending').show();
	
	$.post('/my/invite',
		{ email:email }, 
		function(data){
			if(data=='ok')
			{
				$('#invite_email').val('');
				$('#invite_sending').hide();
				$('#invite_sent').show();
			}
			else
			{
				$('#invite_sending').hide();
				$('#invite_message').addClass('error').html('Адрес e-mail задан неверно.');
				$('#invite_form').show();
			}
	});
	
	return false;
}


function inviteReset()
{
	$('#invite_message').removeClass('error');
	$('#invite_message').html('Введите e-mail, чтобы отправить приглашение');
	$('#invite_sent').hide();
	$('#invite_form').show();
	return false;
}


function ajaxRemind()
{
	var email = $('#pr_email').val();
	if(email=='') 
	{
		$('#pr_message').html('Введите e-mail');
		return false;
	}
	$('#pr_message').html('');
	
	$('#pr_form').hide();
	$('#pr_sending').show();
	
	$.post('/ajax/remind',
		{ email:email }, 
		function(data){
			if(data=='ok')
			{
				$('#pr_email').val('');
				$('#pr_sending').hide();
				$('#pr_sent').show();
			}
			else
			{
				$('#pr_sending').hide();
				$('#pr_message').html(data);
				$('#pr_form').show();
			}
	});
	
	return false;
}


$(document).ready(function(){
	if(need_map==1)
	{
	 	$('#karta .region').bind("mouseover", function(e){
	        $(this).addClass('hover');
	    });    
	  $('#karta .region').bind("mouseout", function(e){
	        $(this).removeClass('hover');
	    });    
		$('#karta .region').bind("click", function(e){
	       var rid = $(this).get(0).title;
			   $('#overlay').show();
			   $('#loading').show();
					$('#karta #popup').load("load/region/"+rid, function(){
					   	 $('#loading').hide();
						 $('.popup_container').show(); 
						 	$('#karta .pop_close').bind("click", function(e){
									$('#overlay').hide()
									$('.popup_container').hide()
									return false;
							});
					 });
	    });   
	}
});


function GetPopup(popup_id, overlay_id, show, where_url)
{
	document.location.href='#top';
	
	var popup = document.getElementById(popup_id);
	var overlay = document.getElementById(overlay_id);
	
	if (where_url)
		$("#where").val(where_url);
	
	if (show)
	{
		overlay.style.display = "block";
		popup.style.display = "block";
	}
	else
	{
		popup.style.display = "none";
		overlay.style.display = "none";
	}
}


//function ChangeTab(id)
function ChangeTab(tabBlockId, id)
{
	var tabs = document.getElementById(tabBlockId).getElementsByTagName('div');
	var this_tab = document.getElementById(id);
	
	for (i=0; i<tabs.length; i++)
	{
		var curTab = $(tabs[i]);
		var tabWidth = curTab.css("width");
		var index = tabWidth.indexOf('p');
		tabWidth = tabWidth.substr(0, index);
		
		if (tabs[i] != this_tab)
		{
			switch (tabs[i].className)
			{
				case 'tab first active_first':	
					tabs[i].className = 'tab first';
					curTab.width(tabWidth - 5);
					break;
				case 'tab last active_last':	
					tabs[i].className = 'tab last';
					curTab.width(tabWidth - 5);
					break;
				case 'tab active':	
					tabs[i].className = 'tab';
					curTab.width(tabWidth - 10);
					break;
			}
			document.getElementById(tabs[i].id+'_body').style.display = 'none';
		}
		else
		{
			switch (tabs[i].className)
			{
				case 'tab first hover_first':	
					tabs[i].className = 'tab first active_first';
					curTab.width(tabWidth*1 + 5);
					break;
				case 'tab last hover_last':	
					tabs[i].className = 'tab last active_last';
					curTab.width(tabWidth*1 + 5);
					break;
				case 'tab hover':	
					tabs[i].className = 'tab active';
					curTab.width(tabWidth*1 + 10);
					break;
			}
			document.getElementById(tabs[i].id+'_body').style.display = 'block';
		}
	}
}

function ChangeLeftTabs(id_this, id_other) {
    var this_tab = document.getElementById(id_this);
    var other_tab = document.getElementById(id_other);

    if (this_tab.className.indexOf('rol') != -1) {
        other_tab.className = 'info_tab ' + other_tab.id;
        document.getElementById(id_other + '_body').style.display = 'none';
        this_tab.className = 'info_tab ' + this_tab.id + ' ' + this_tab.id + '_activ';
        document.getElementById(id_this + '_body').style.display = 'block';
    }
}

function ChangeBlueTab(obj, body_id)
{
	var tabs = document.getElementById('blue_tabs').getElementsByTagName('div');
	var this_tab = obj;
	var bodies = document.getElementById('blue_bodies').getElementsByTagName('div');
	var this_body =  document.getElementById(body_id);
	
	if (this_tab.className != 'blue_tab act')
	{
		for (var i=0; i<tabs.length; i++)
		{
			switch (tabs[i].className)
			{
				case 'blue_tab act':	
					tabs[i].className = 'blue_tab';
					break;
				case 'blue_tab':
					if (tabs[i] == this_tab) tabs[i].className = 'blue_tab act';
					break;
				case 'blue_tab hov':
					if (tabs[i] == this_tab) tabs[i].className = 'blue_tab act';
					break;
			}
		}
		for (var i=0; i<bodies.length; i++)
		{
			if (bodies[i].className == 'blue_body')
				if (bodies[i] == this_body)
					bodies[i].style.display = 'block';
				else
					bodies[i].style.display = 'none';
		}
	}
				 
}

function ChangeBg(obj)
{
	switch (obj.className)
	{
		case 'blue_tab':
			obj.className += ' hov';
			obj.onmouseout = function() {
				if (obj.className != 'blue_tab act')
					obj.className = 'blue_tab';	
			}
			break;
		case 'tab spo':
			obj.className += ' hover';
			obj.onmouseout = function() {
				if (obj.className != 'tab spo active')
					obj.className = 'tab spo';	
			}
			break;
		case 'tab fell':
			obj.className += ' hover';
			obj.onmouseout = function() {
				if (obj.className != 'tab fell active')
					obj.className = 'tab fell';	
			}
			break;
		case 'tab':
			obj.className += ' hover';
			obj.onmouseout = function() {
				if (obj.className != 'tab active')
					obj.className = 'tab';	
			}
			break;
		case 'tab first':
			obj.className += ' hover_first';
			obj.onmouseout = function() {
				if (obj.className != 'tab first active_first')
					obj.className = 'tab first';	
			}
			break;
		case 'tab last':
			obj.className += ' hover_last';
			obj.onmouseout = function() {
				if (obj.className != 'tab last active_last')
					obj.className = 'tab last';	
			}
			break;
	}
}

function QuickSearch(obj, id)
{
	var block = document.getElementById(id);
	
	if (block.style.display == 'none')
	{
		block.style.display = 'block';
		obj.className += ' qs';
	}
	else
	{
		block.style.display = 'none';
		obj.className = 'detailed_search';
	}
}

function addMData() 
{
	$('#mdate_'+mdate).show();
	mdate++;
	if (mdate == 11)
		$('#addMDate').hide();
}

// var spo = [2, 2, 2, 2, 2, 2]; - declaration moved to processing file
function addCity(position)
{
	var ps = position-1;
	$('#c_'+position+'_'+spo[ps]).show();
	spo[ps]++;
	if(spo[ps] == 6)
		$('#add_'+position).hide();
}

// var country_pos = 2; - declaration moved to processing file
function addCountry()
{
	$('#cc_'+country_pos).show();
	country_pos++;
	if (country_pos == 7)
		$('#addCountry').hide();
}

/* Add to Favorite Functions */
function getBrowserInfo() 
{
 var t,v = undefined;
 if (window.opera) t = 'Opera';
 else if (document.all) 
 {
  t = 'IE';
  var nv = navigator.appVersion;
  var s = nv.indexOf('MSIE')+5;
  v = nv.substring(s,s+1);
 }
 else if (navigator.appName) t = 'Netscape';
 return {type:t,version:v};
}
 
function bookmark(a, url, title) 
{
 var b = getBrowserInfo();
 if (b.type == 'IE' && b.version >= 4) window.external.AddFavorite(url,title);
 else if (b.type == 'Opera') 
 {
  a.href = url;
  a.rel = "sidebar";
  a.title = url+','+title;
  return true;
 }
 else if (b.type == "Netscape") window.sidebar.addPanel(title,url,"");
 else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
 return false;
}
/* End Add to Favorite Functions */

/* Login Popup Functions */
var ua = navigator.userAgent.toLowerCase();
var isOpera = (ua.indexOf('opera') > -1);
var isIE = (!isOpera && ua.indexOf('msie') > -1);

function GetViewportHeight() {
    return ((document.compatMode || isIE) && !isOpera) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight : document.body.clientHeight : (document.parentWindow || document.defaultView).innerHeight;
}

function getDocumentHeight() {
    return Math.max(document.compatMode != 'CSS1Compat' ? document.body.scrollHeight : document.documentElement.scrollHeight, GetViewportHeight());
}

function getLoginPopup() {
	var overlay = $("#main-overlay");
	var popup = $("#login-popup");
	
	overlay.height(getDocumentHeight() + "px").show();
    overlay.click(function() {
		closeLoginPopup();
    });
	
	popup.css({
        top: document.documentElement.scrollTop == 0 ? document.body.scrollTop + 100 : document.documentElement.scrollTop + 100,
		marginLeft: -270
    }).show();
}

function closeLoginPopup() {
	$("#main-overlay, #login-popup").hide();
}
/* End Login Popup Functions */

$(document).ready(function() {
	var ddlCurVal = $(".customSelect .curVal");
	var ddlList = ddlCurVal.parent().find("ul");
	ddlCurVal.click(function() {
		if (ddlCurVal.hasClass("opened")) {
			ddlList.hide();
			ddlCurVal.removeClass("opened");
		}
		else {
			ddlList.show();
			ddlCurVal.addClass("opened");
		}
	});
	$(".customSelect ul a").click(function() {
		$(".customSelect ul a").removeClass("act");
		ddlCurVal.text($(this).text()).removeClass("opened");
		ddlList.hide();
		$(this).addClass("act");
	});
	var sell = document.getElementById("cityDdl");
	if (sell != null) {
		AddEvent(document, 'click', function(event){
			var event = event || window.event;
			var t = event.target || event.srcElement;
			
			if (t!=sell && !isChildNode(sell, t)) {
				ddlList.hide();
				ddlCurVal.removeClass("opened");
			}
		});
	}		
});

function isChildNode(elem, sell) {
	for (var childItem in elem.childNodes) {
		if (elem.childNodes[childItem].nodeType == 1) {
			if (elem.childNodes[childItem] == sell)
				return true;
			else if (isChildNode(elem.childNodes[childItem], sell))
				return true;
		}
	}
	return false;
}

function AddEvent(obj, type, fn) {
	if (obj.addEventListener)
		obj.addEventListener(type, fn, false);
	else if (obj.attachEvent)
		obj.attachEvent( "on"+type, fn );
}