
defaultIcon 	= new Image();
defaultIcon.src	= "/images/map_ico.png";
var icon		= "/images/map_ico.png";



$(function() {
 	var mapController = {
 		currentType 			:	type,											//Тип выводимого контента (Тематика вкладок)
 		currentLang 			:	lang,											//Текущий язык контента
 		reqPath					: 	"/" + lang + "/map.html?xhr=1&type=" + type,	//Путь для XHR-запроса
 		GMap					:	null,											//Объект Google-карты
 		defaultIcon				: 	null,											//Иконка точки карты по-умоолчанию
 		clickedItem				:   0,												//Щёлкнутая ссылка окна по-умолчанию
 		defWinHeight			:	0,												//Высота окна ссылок сразу после загрузки сиситемы
 		collapsedContentHeight	:	60,												//Высота контента выбранной ссылки
 		start_latitude			:	30.315785,										//Координаты Петербурга
 		start_longitude			:	59.939039,
 		start_zoom				:	10,												//Стартовое увеличение карты
 		defautWindowHeight		: 	660,		
 		
 		
 		/**
 	 	* mapController::onLoadInit()
 	 	* Инициализация виджета. Определние своиств и событий для ссылок
 	 	* @access public 
 	 	* @return void
 	 	*/	
 		onLoadInit	: 	function(mapObj){
			/**
			* Только если API карт загрузилось и броузер нужного типа
			*/
			if (typeof("GBrowserIsCompatible") != "undefined" && GBrowserIsCompatible()) 
			{			    		
				var map = new GMap2(document.getElementById("map"));				
				if(type == "offices" || type == "events"){
					var position = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));	
				}
				else{
					var position = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10));				
				}						
				
				//Если запускаем с виджета гл. страницы - то не выводим контролы
				if(frontpage === true){
					var customUI = map.getDefaultUI();
					customUI.controls.scalecontrol 			= false;
					customUI.maptypes.normal  				= true;
					customUI.maptypes.satellite   			= false;										
					customUI.maptypes.hybrid    			= false;							
					customUI.maptypes.physical     			= false;	
					customUI.controls.smallzoomcontrol3d    = false;
					customUI.controls.menumaptypecontrol    = false;															
					map.setUI(customUI);
				}
				else{
					map.addControl(new GLargeMapControl3D(), position);   								
				}
				
				var startpoint = new GLatLng(parseFloat(start_longitude), parseFloat(start_latitude));
				map.setCenter(startpoint, start_zoom);								
		    }	
		    else{
		    	return;	
		    } 			
 			 			 			 			
 			this.GMap = map;
 			this.setDefaultIcon();
 			this.requestWIndowContent();
 			 			
 			var that = this;
 			$(".current").click(function(){ 				
 				that.scrollWindow();
 				return false;	
 			});
 			
 			
 			if(setToPoint.length > 0 ){
 				this.setPointToMap();	 				
 			}
	 	},
	 	
	 	/**
	 	* mapController::setPointToMap()
	 	* Установка точки в координату с всплывшем балуном
	 	* @access public
	 	* @return void
	 	*/
	 	setPointToMap: function(){
 			var posArr 	= setToPoint.split(",");
 			var lat 	= parseFloat(posArr[0]);
 			var lng 	= parseFloat(posArr[1]); 			
 			var point 	= new GLatLng(lat,lng);
 			var marker  = new GMarker(point);			 			
			this.GMap.setCenter(point, 15);
			this.GMap.addOverlay(marker);  	
			this.GMap.openInfoWindow(this.GMap.getCenter(), titleToPoint);					  
	 	},
	 	

 		/**
 	 	* mapController::setDefaultIcon()
 	 	* Установка иконки по-умолчанию
 	 	* @access public 
 	 	* @return void
 	 	*/		 	
	 	setDefaultIcon: function(){
			this.defaultIcon = new GIcon();
		    this.defaultIcon.iconAnchor = new GPoint(16, 16);
		    this.defaultIcon.infoWindowAnchor = new GPoint(16, 0);
		    this.defaultIcon.iconSize = new GSize(32, 32);
		    //this.defaultIcon.shadow = "images/shadow.png";
		    this.defaultIcon.shadowSize = new GSize(59, 32);			 		 		
	 	},
 	
 		/**
 	 	* mapController::requestWIndowContent
 	 	* Запрос контента окна
 	 	* @access public 
 	 	* @return void
 	 	*/		 	 		
 		requestWIndowContent: function(){
 			var that = this; 			
 			this.windowLoader(true);
			$.ajax({
				type	: 	"POST",
				url		: 	that.reqPath,
				cache	: 	false,
				data	: 	"op=rqwincontent",
				success	: 	function(msg){			     	
				   	$("#object_list").html(msg);
				   	that.addLinksEvents();
				   	that.windowLoader(false);
				   	that.defWinHeight = $("#object_list").height();
				   	that.correctWIndowHeight();
			   	}
			}); 			
 		},
 		
 		/**
 		* mapController::correctWIndowHeight()
 		* Корректировка высоты окна в зависимости от высоты поступившего контента
 		* @access public
 		* @return void
 		*/
 		correctWIndowHeight: function(){
 			var contentHeight = $("#offices_list").height() + 40;
 			this.defWinHeight = contentHeight;
 			if(this.defWinHeight > this.defautWindowHeight)  this.defWinHeight = this.defautWindowHeight;
			$("#object_list").animate({ 
				height: contentHeight + "px"
			}, 200);
 			
 		},
 		 	
 		/**
 	 	* mapController::requestWIndowContent
 	 	* Запрос контента окна
 	 	* @access public 
 	 	* @return void
 	 	*/	 		
 		windowLoader: function(show){
 			if(show === true) 		$("#object_list").addClass("preloader_big"); 
 			else if(show === false)	$("#object_list").removeClass("preloader_big"); 
 			else return;
 				
 			return;
 		},
 		
 		
 		/**
 	 	* mapController::addLinksEvents()
 	 	* Добавление обработчика onClick на ссылки загруженного контента
 	 	* @access public 
 	 	* @return void
 	 	*/	 		 		
 		addLinksEvents: function(){
 			var that = this;
			$("#offices_list a").each(function(index){
				var id 	= $(this).attr("clk");
				id 		= parseInt(id);
				if(id > 0 && !isNaN(id)){
					$(this).click(function(){
						that.requestMapPoints(id); 
						that.clickedItem = id;
						return false;	//Чтобы ссылку заблокировать 	
					});					
				}
			});
 		},
 		
		/**
 	 	* mapController::requestMapPoints()
 	 	* Запрос на получение точек карты
 	 	* @access public 
 	 	* @param int objID Значение аттрибута clk ссылки, которую обраюатываем
 	 	* @return void
 	 	*/	 		 		  		
 		requestMapPoints: function(objID){
 			this.hideWindowContents(true);	
 			this.windowLoader(true);
 			var that = this;	 			
			$.getJSON(this.reqPath + "&op=pointsdata&lang=" + this.currentLang + "&id=" + objID, function(data){	
				that.hideWindowContents(false);	
 				that.windowLoader(false);		
 				that.GMap.clearOverlays();						
		    	$.each(data.mpoints, function(i,item){
		    		that.showSingleMapPoint(item);	
		        });
		        that.expandOrCollapseList();
		        that.scrollWindow();	
		        that.zoomToDefault();			                
        	}); 			
 		},
 		
 		zoomToDefault: function()
 		{
 			var startpoint = new GLatLng(parseFloat(this.start_longitude), parseFloat(this.start_latitude));
 			this.GMap.setCenter(startpoint, this.start_zoom);	
 		},

		/**
 	 	* mapController::showSingleMapPoint()
 	 	* Отображение еденичной точки при помощи GoogleMap.API
 	 	* @access public
 	 	* @param object pointData Объект с данными, получеными из JSON-ответа с backend-а 
 	 	* @return void
 	 	*/	 		 		  		 		
 		showSingleMapPoint: function(pointData){
 			if(typeof(pointData) != "object") return;
 			var posArr 	= pointData.position.split(",");
 			var lat 	= parseFloat(posArr[0]);
 			var lng 	= parseFloat(posArr[1]);
 			
 			var point 	= new GLatLng(lat,lng);
 			var marker  = new GMarker(point);

	        GEvent.addListener(marker, "click", function() {
	          marker.openInfoWindowHtml("<table class='baloon_table' cellpadding='0' cellspacing='0'><tr><td>" + pointData.baloon_content + "</td></tr></table>");
	        }); 			
 			
			//this.GMap.setCenter(point, 14);
			this.GMap.addOverlay(marker);  			 			
 		},
 		
 		
 		/**
 	 	* mapController::hideWindowContents()
 	 	* Скрытие полезного контента окна (применяется при его свёртке) 
 	 	* @access public
 	 	* @param boolean hide true/false Скрывать/Не скрывать 
 	 	* @return void
 	 	*/			 		
 		hideWindowContents: function(hide){
			if(hide === true) 		$("#offices_list").addClass("hidden");
			else if(hide === false)	$("#offices_list").removeClass("hidden");
			else					return;			 		
	 		return;	
 		},
 		
 		/**
 	 	* mapController::scrollWindow()
 	 	* Сворачивание/Разворачивание окна с контентом ссылок
 	 	* @access public
 	 	* @return void
 	 	*/			 		 		
 		scrollWindow: function(){		
 			if($("#object_list").height() >= this.defWinHeight){
	 		  	if(this.clickedItem != 0){		 		  		
	 		  		this.expandOrCollapseList(false);	   		 		  			 		  			
				  	$("#object_list").animate({ 
				    	height: this.collapsedContentHeight + "px"
				  	}, 500);
			  	}
			  	else{
			  		this.expandOrCollapseList(false);
				  	$("#object_list").animate({ 
				    	height: "0px"
				  	}, 500);		  			  	
			  	} 		
			  	
			  	$(".current span").removeClass("arrow_up");
			  	$(".current span").addClass("arrow_down");
			  	
			  			
 			}
 			else{
 				var that = this;
 				this.expandOrCollapseList(true);
 				$("#object_list").animate({ 
				  	height: this.defWinHeight +"px"
				}, 500, function(){															
				});
				
				$(".current span").removeClass("arrow_down");
				$(".current span").addClass("arrow_up");
 			}
 		},
 
 
 		/**
 	 	* mapController::expandOrCollapseList()
 	 	* Сворачивание/развоворачивание полезного контента непосредственно при свёртке окна.
 	 	* Может быть неполным 	 	
 	 	* Метод должен вызываться ДО СВОРАЧИВАНИЯ ОКНА ОБЯЗАТЕЛЬНО!!!
 	 	* @access public
 	 	* @param boolean expand Раздвигать?
 	 	* @return void
 	 	*/	 		
 		expandOrCollapseList: function(expand){ 			
 			if(this.clickedItem == 0){
 				this.hideWindowContents(!expand);		
 			}
 			else{
	 			var that = this;
				$("#offices_list li").each(function(index){
					if($(this).children("a").attr("clk") != that.clickedItem){
						if(expand !== true) $(this).addClass("hidden");
						else 				$(this).removeClass("hidden");						
					}	
				});	 	
				if(expand !== true) $("a[clk|=" + that.clickedItem + "]").css({"font-weight" : "bold", "font-size" : "14px"});	
				else 				$("a[clk|=" + that.clickedItem + "]").css({"font-size" : "12px"});										
				/**
				* Вычисление высоты, до какой мы будем скроллить окно (убирание)
				*/					
				this.collapsedContentHeight = $("a[clk|=" + that.clickedItem + "]").height();	
				this.collapsedContentHeight = parseInt(this.collapsedContentHeight) + 40;							 				
 			}	
 		}
 	}	
 
    mapController.onLoadInit();    	    	
});
