
    var Shell = {};
    Shell.onePanelState = false; // для маленького разрешения - на некоторых страницах возможно единовременно открыть только либо правую, либо левую панель
    Shell.currentState = {};
    Shell.currentState.leftPanel = true;
    Shell.currentState.rightPanel = true;
    Shell.hideLeftPanel = function() {
        $('#menu_left_exp').hide();
        $('#menu_left_col').show();
        $('#content_center').css('margin-left', 0);
        onResize();
        Shell.currentState.leftPanel = false;
    }
    Shell.showLeftPanel = function() {
        $('#menu_left_exp').show();
        $('#menu_left_col').hide();
        $('#content_center').css('margin-left', '250px');
        onResize();
        Shell.currentState.leftPanel = true;
        
        if (Shell.onePanelState) Shell.hideRightPanel();
    }
    Shell.hideRightPanel = function() {
        $('#menu_right_exp').hide();
        $('#menu_right_col').show();
        $('#content_center').css('margin-right','7px');
        onResize();
        Shell.currentState.rightPanel = false;
    }
    Shell.showRightPanel = function() {
        $('#menu_right_exp').show();
        $('#menu_right_col').hide();
        $('#content_center').css('margin-right','250px');
        onResize();
        Shell.currentState.rightPanel = true;
        
        if (Shell.onePanelState) Shell.hideLeftPanel();
    }
    Shell.toggleLeftPanel = function() {
        if (Shell.currentState.leftPanel) {
            Shell.hideLeftPanel();
        } else {
            Shell.showLeftPanel();
        }
    }

	var contentHeight=0; //keeps current content div's height
	var hintTimeout;
	var numsteps=1;

	var map;
	
	var GMbeganload = false;
	var GMready = false;
	
	var HBounds = new Array();

	HBounds[3]=[-74,85];
	HBounds[4]=[-81,82];
	HBounds[5]=[-83,85];
	HBounds[6]=[-84,85];
	
	
 	var allowedBounds = true;
  	  	
  	function genNewBounds(curZoom) {
  		if (curZoom<3 || curZoom>6) {
			var southBound = HBounds[6][0];
			var northBound = HBounds[6][1];
		} else {
			var southBound = HBounds[curZoom][0];
			var northBound = HBounds[curZoom][1];
		}
		// The allowed region which the whole map must be within
		allowedBounds = new GLatLngBounds(new GLatLng(southBound,-179), new GLatLng(northBound,-180));
        
  	};
	
	// If the map position is out of range, move it back
    function checkBounds() {
    	// Perform the check and return if OK
        if (allowedBounds.contains(map.getCenter())) {
          return;
        }
        // It`s not OK, so find the nearest allowed point and move there
        var C = map.getCenter();
        var X = C.lng();
        var Y = C.lat();

        var AmaxX = allowedBounds.getNorthEast().lng();
        var AmaxY = allowedBounds.getNorthEast().lat();
        var AminX = allowedBounds.getSouthWest().lng();
        var AminY = allowedBounds.getSouthWest().lat();

        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}
        
        map.panTo(new GLatLng(Y,X));
	}
    
	function beginGMload() {
		GMbeganload=true;
		var GMscript = document.createElement("script");
  			GMscript.src = "http://www.google.com/jsapi?key="+GMkey+"&callback=loadMaps";
  			GMscript.type = "text/javascript";
  			$('body').after(GMscript);
	}
		
	function loadMaps() {
		google.load("maps", "2", {"callback" : mapsLoaded});
	}
	
	function mapsLoaded() {	
			
		/* Проверка на совместимость с используемым браузером*/
		if (GBrowserIsCompatible()) {
			
			/* Создание объекта карты, googlemap - имя, по которому находится объект карты, описываемый ниже*/
			map = new google.maps.Map2(document.getElementById("googlemaps"));
				
			map.setCenter(new GLatLng(59.92,30.34), 3, G_PHYSICAL_MAP);
						
			GMready=true;
				
			$('#map_controls').show();	
				
			GEvent.addListener(map, "dblclick", function(){
				zoom=map.getZoom();
				newzoom=zoom+1;
				
				if (newzoom<=15) {
					$('#scroller').removeClass('zoom'+zoom);
					$('#scroller').addClass('zoom'+newzoom);
					if (newzoom>=8) $('#map_switcher').show();
				}
			});
			
			map.enableDragging()
			
			map.enableContinuousZoom();
			//map.enableScrollWheelZoom();
					
			GEvent.addListener(map, "dragend", function() {
        		//alert(map.getBounds());
        		checkBounds();
      		});
      		
      		var curZoom = map.getZoom();
      		genNewBounds(curZoom);
      		      			
      		GEvent.addListener(map, "zoomend", function(oldZoom,curZoom) {
      			genNewBounds(curZoom);		
      		});
      		
		}
						
	}

	
	/*$.datepicker.setDefaults({showOn: 'both', buttonImageOnly: false,
	buttonImage: gl_addr + '/image/calendar.gif', buttonText: 'Calendar'});*/
	
	Planetoid.ifr_count = Math.floor(Math.random()*1000);
	Planetoid.flood_timeout = false;
	Planetoid.flood = false;
	
	function setNewHeight(new_height) {
		
		document.getElementById(Planetoid.new_ifr).style.height=new_height+'px';
		
		onResize();
						
	}
	
	function setNewDynamicHeight(obj) {
		Planetoid.fr_obj = obj;
		if($('#'+Planetoid.new_ifr).height()<obj.height()){
			document.getElementById(Planetoid.new_ifr).style.height=obj.height()+'px';
			setTimeout(function(){setNewDynamicHeight(Planetoid.fr_obj)},300);
		}
		onResize();
						
	}
	
	function showNewIfr(new_height) {
		
		document.getElementById('content').style.height='';
		
		document.getElementById(Planetoid.new_ifr).style.position='static';
		
		$('.plifr_old').remove();
		
		setNewHeight(new_height);
		
	}
	
	//Выполняется при смене #хэша - производит подгрузку данных в "контент"
	function callback(hash,divId) {
            
            if ((hash == 'main' || hash.substr(0, 4) == 'help') && Planetoid.getClientWidth() < 1200) {
                Shell.onePanelState = true;
                if (Shell.currentState.rightPanel) Shell.hideLeftPanel(); 
            }
            else {
                Shell.onePanelState = false;
                Shell.showLeftPanel();
            }
            
			Planetoid.old_ifr = 'plifr'+Planetoid.ifr_count;
			
			$('#'+Planetoid.old_ifr).addClass('plifr_old');

			Planetoid.ifr_count+=1;
			Planetoid.new_ifr = 'plifr'+Planetoid.ifr_count;
			
			if ($('#'+Planetoid.old_ifr).get(0))
				$('#content').css('height',$('#'+Planetoid.old_ifr).height()+'px');
			
			$('#place_add_toolbar,#map_show_toolbar').hide();
					
			if(!$.browser.msie) $('#'+Planetoid.old_ifr).css('opacity','0.5');
			
				$('#content_loading').show();
			
			
			//$('#'+Planetoid.old_ifr).css('position','absolute').css('left','0').css('background-color','transparent');
			
			$('#content').prepend('<iframe id="'+Planetoid.new_ifr+'" name="'+Planetoid.new_ifr+'" src="'+gl_addr+'content.php?p='+hash+'&_='+Math.random()+'&w='+Planetoid.getClientWidth()+'" style="position:absolute;left:-9999px;background-color:transparent;" allowtransparency="true" frameborder="0" class="plifr" scrolling="no"></iframe>');
			
	}
	
	// Planetoid.numsteps = 0;
	
	function refreshPostMenuPosition() {
		$postEditMenu = $('.plifr').contents().find('#post-edit-menu');
		
		if ($(window).scrollTop() < 125) newY = 0;
		else newY = $(window).scrollTop() - 125;
		$postEditMenu.css({top: newY});
		$(window).scroll(function(){
			if ($(window).scrollTop() < 125) newY = 0;
			else newY = $(window).scrollTop() - 125;
			$postEditMenu.css({top: newY});
		});
	}
	
	//Преходилка. Производит подгрузку данных в зависимости от #хэша и прописывает "переход" в "хистори"
	function goTo(url,divId) {
		
            var splitUrl = url.split('#',2);
			var hrefa;
			var tourfl=0;
            
			if (Planetoid.flood) return false;
		
			if (!divId) divId='#content';
			
			contentHeight = $(divId).height();
			
			//Иначе результаты автокомплита не исчезают при изменении контента
			$('.ac_results').hide();
			
			//Очищает маршруты с карты
			if(map)map.clearOverlays();
			
			if (splitUrl.length==1) {
				var url_parts = url.split('/');
				
				var static_url='';
				for (x in url_parts) {
					if (x>2) static_url+=url_parts[x]+'/';
				}


				if (!static_url) hrefa = 'main';
				else hrefa = static_url;
				
			} else {
				hrefa = splitUrl[1];
				var url0=hrefa.split('/',1);
				if (url0=='toursearch' || url0=='tours') tourfl=1;
			}
			$.history.load(hrefa,divId);
			
			updateNew();
			//return false;
		
			
			/*numsteps++;
		
			if ((document.getElementById('right_info').style.display=='none' && (numsteps>=3 && tourfl==0)) || 
		    	(document.getElementById('right_info').style.display!='none' && (numsteps>=4 || tourfl==1))) {
		   	 		hintTimeout=clearTimeout(hintTimeout);
		   			hintTimeout=setTimeout(function(){
						$('#tour_search').toggle();
						$('#right_info').toggle();
						$(this).toggleClass('open_closed');
					},2000);
				numsteps=1;
			} */
			
			
			Planetoid.flood = true;
				
			Planetoid.flood_timeout = clearTimeout(Planetoid.flood_timeout);	
			
			Planetoid.flood_timeout = setTimeout(function(){Planetoid.flood = false;},700)
		
	}
	
	//Байндит события на линки "history"
	function bindHistoryLinks() {
		/* Отвязываем все события, чтобы при подгрузке новых ссылок
		** на них не байндились по 10 раз клики
		** (можно в принципе сделать при каждой новой подгрузке байнд только на новые ссылки
		** например на $('#content a[@rel="history"]') - но что, если ссылка появилась вне "контента"?)
		*/
		$("a[rel='history'], a[rel='sub_history'], a[rel='sub_sub_history']").unbind();
		
		//Вешаем на клик "переходилку"
		$("a[rel='history']").click(function(){
   			goTo($(this).attr('href'));
   			return false;
  	 	});
  	 	
  	 	$("a[rel='sub_history']").click(function(){
  	 		if($(this).hasClass('tab'))selectTab($(this).parent());
  	 		else if($(this).hasClass('sub_tab'))selectSubTab($(this));
  	 		
  	 		if(browserType()!='ie6')goTo($(this).attr('href'),'.sub_content');
  	 		else goTo($(this).attr('href'));
   			return false;
  	 	});
  	 	
  	 	$("a[rel='sub_sub_history']").click(function(){
  	 		if(browserType()!='ie6')goTo($(this).attr('href'),'.sub_sub_content');
  	 		else goTo($(this).attr('href'));
   			return false;
  	 	});
  	 	
	}
	
	function updateNew() {
	
		t2=setTimeout(function(){
				$("a[rel='history'], a[rel='sub_history']").bind('click',abortAjax2);
			},100);
	
		var postData = {
			sessid: getCookie(PHPSESSID),
			ajax: 'main',
			hash: location.hash,
			updateNew: true
		};
		
		//Отменяет AJAX-запрос	
		var abortAjax2 = function() {
			ajaxManager2.abort();
		}
		
		var ajaxManager2 = $.manageAjax({
			manageType: 'abortOld',
			maxReq: 1
		});
		
		ajaxManager2.add({
			type: "POST",
			url: gl_addr + "ajax.php",
			data: postData,
			success: function(retHTML){
				if (retHTML) {
					if (retHTML.messages>0) $('#newMes').html('(<span id="newMesNum">'+retHTML.messages+'</span>)');
					else $('#newMes').html('');
					
					if (retHTML.friends>0) $('#newFr').html('(<span id="newFrNum">'+retHTML.friends+'</span>)');
					else $('#newFr').html('');
					
					if (retHTML.pictures>0) {
						$('#newPic').html('(<span id="newPicNum">'+retHTML.pictures+'</span>)');
						$('#shell_photos_link').attr('href',gl_addr+'#photos/person=/new');
					} else {
						$('#newPic').html('');
						$('#shell_photos_link').attr('href',gl_addr+'#photos');
					}
	
					if (retHTML.trips>0) $('#newTr').html('(<span id="newTrNum">'+retHTML.trips+'</span>)');
					else $('#newTr').html('');

					
					if (retHTML.hints || retHTML.widgets) {
						
						$('#hint_cloud_0').hide();
						
						var i=0, num, numhints=0, numwidgets=0;
						if (retHTML.hints) numhints=retHTML.hints.length;
						if (retHTML.widgets) numwidgets=retHTML.widgets.length;
						
						while(i<numhints && i<3) {
							num=i*1+1;
							if (retHTML.hints[i]) {
								$('#hint_cloud_'+num).show();
								$('#hint_title_'+num).html(retHTML.hints[i].title);
								
								$('#hint_title_'+num).addClass('hint_title');
								$('#hint_title_'+num).removeClass('hint_widget_title');
								
								$('#hint_txt_'+num).html(retHTML.hints[i].txt);
							} else $('#hint_cloud_'+num).hide();
							
							i++;
						}
						var numprev=i;
						while(i<numwidgets+numprev && i<3) {
							num=i*1+1;
							if (retHTML.widgets[i]) {
								$('#hint_cloud_'+num).show();
								$('#hint_title_'+num).html(retHTML.widgets[i].title);
								
								$('#hint_title_'+num).removeClass('hint_title');
								$('#hint_title_'+num).addClass('hint_widget_title');
								
								$('#hint_txt_'+num).html(retHTML.widgets[i].txt);
							} else $('#hint_cloud_'+num).hide();		
							
							i++;				
						}
						
						
					} else {
						$('.hint_cloud').hide();
						$('#hint_cloud_0').show();
					}

				}
				
				$("a[rel='history'], a[rel='sub_history']").unbind('click',abortAjax2);		
			},
			dataType: "json"
		});
	}
	
	




	$(document).ready(function() {
		
		//Инициализируем "хисторю"
 		$.history.init(callback);
				
 		//Байндим события на линки "history"
   		bindHistoryLinks();
   		
   		//Проверяем новые сообщения. Если есть - записываем их число в #newMes
   		updateNew();
   		
   		var showDef=true;
   		$('#toggleAllPanels').click(function(){
   			if (showDef) {
   				$('#wrapper, #navigation, #extra').slideUp('slow');
   				$(this).html('Развернуть всё');
   				showDef=false;
   			} else {
   				$('#wrapper, #navigation, #extra').slideDown('slow');
   				$(this).html('Свернуть всё');
   				showDef=true;
   			}
   		});
   		
   		//Прячет результаты автокомплита
   		$(document).click(function(){
   			$('.ac_results').hide();
   		});
   		
	});
