
    //<![CDATA[

    var plants = Array();
	var plants2 = Array(); //Заводы ЖБИ
	var office = Array();
	var adressPoint = null;
    var map = null;
    var geocoder = null;
    var gdir;
    var marker;

	function initialize() {
      if (GBrowserIsCompatible()) {
			//Инициализируем заводы
			plants[0] = new Plant('Бетонный завод № 1', 55.883682,37.626661, 
			           '(<a href="/contacts/medvedkovo/" target="_blank">Контакты</a>)', 
					   'Москва, ул. Вилюйская, 3',
					   'Адрес: Москва, ул. Вилюйская, 3<br><a href="/contacts/medvedkovo/">Подробнее</a>'); 
            plants[1] = new Plant('Бетонный завод № 2', 55.161018,37.427276,
                       '(<a href="/contacts/chehov/" target="_blank">Контакты</a>)',
					   'МО, г. Чехов, ул. Комсомольская, 20',
					   'Адрес: МО, г. Чехов, ул. Комсомольская, 20<br><a href="/contacts/chehov/">Подробнее</a>');
            plants[2] = new Plant('Бетонный завод № 4', 55.690431,37.950157,
                       '(<a href="/contacts/nekrasovka/" target="_blank">Контакты</a>)',
					   'Москва, пос. Некрасовка, ул. 2-я Вольская, 34 корп. 1',
					   'Адрес: Москва, пос. Некрасовка,<br> ул. 2-я Вольская, 34 корп. 1<br><a href="/contacts/nekrasovka/">Подробнее</a>');  
            plants[3] = new Plant('Бетонный завод № 5', 55.643227,37.380992,
                       '(<a href="/contacts/proizvodstvennaya/" target="_blank">Контакты</a>)',
					   'Москва, ул. Производственная, 17А',
					   'Адрес: Москва, ул. Производственная, 17А<br><a href="/contacts/proizvodstvennaya/">Подробнее</a>');  
            plants[4] = new Plant('Бетонный завод в Домодедово', 55.450735,37.766694,
                       '(<a href="/contacts/domodedovo/" target="_blank">Контакты</a>)',
					   'МО, г. Домодедово, ул. Промышленная, 11',
					   'Адрес: МО, г. Домодедово, ул. Промышленная, 11<br><a href="/contacts/domodedovo/">Подробнее</a>');
			plants[5] = new Plant('Головной завод', 55.687946,37.626189,
                       '(<a href="/contacts/golovnoi/" target="_blank">Контакты</a>)', 
					   'Москва, Варшавское шоссе, 37Г',
					   'Адрес: Москва, Варшавское шоссе, 37Г<br><a href="/contacts/golovnoi/">Подробнее</a>');

			plants2[0] = new Plant('Цех № 5', 55.772451,37.512753,
                       '(<a href="/contacts/ceh/" target="_blank">Контакты</a>)',
					   'Москва, ул. 1-ая Магистральная, 24',
					   'Адрес: Москва, ул. 1-ая Магистральная, 24<br><a href="/contacts/ceh/">Подробнее</a>');   
			plants2[1] = new Plant('Цех № 6', 55.88719,37.635019,
                       '(<a href="/contacts/ceh6/" target="_blank">Контакты</a>)',
					   'Москва, Чермянский пр-д, 3',
					   'Адрес: Москва, Чермянский пр-д, 3<br><a href="/contacts/ceh6/">Подробнее</a>'); 
			
			office[0] = new Plant('Управление комбината', 55.883682,37.626661, 
			           '(<a href="/contacts/upravlenie/" target="_blank">Контакты</a>)', 
					   'Москва, ул. Вилюйская, 3',
					   'Адрес: Москва, ул. Вилюйская, 3<br><a href="/contacts/upravlenie/">Подробнее</a>');  
    		//=====================
			
			map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			geocoder = new GClientGeocoder();
			gdir = new GDirections(map);
            GEvent.addListener(gdir, "load", onGDirectionsLoad);
            GEvent.addListener(gdir, "error", handleErrors);

    	    //Установка карты на Москву и МО
            map.setCenter(new GLatLng(55.747212, 37.633667), 9);            
		  }
    }
	
	function createMarker(point, html, markerOptions) {
		  var marker = new GMarker(point, markerOptions);
		  GEvent.addListener(marker, "click", function() {
			map.openInfoWindowHtml(point, html);
		  });
		  return marker;
	}

	function setPlants() {
		  //Определяем тип иконок для заводов

		  var plantIcon = new GIcon(G_DEFAULT_ICON);
		  plantIcon.image = "/images/gmapBetonIcon.png";
		  plantIcon.shadow = "/images/gmapZBIIconSH.png";//"http://www.google.com/mapfiles/shadow50.png";
		  plantIcon.iconSize = new GSize(21, 30);
		  plantIcon.shadowSize = new GSize(31, 29);
		  plantIcon.iconAnchor = new GPoint(9, 25);
		  plantIcon.infoWindowAnchor = new GPoint(9, 2);

          var ZBIIcon = new GIcon(G_DEFAULT_ICON);
		  ZBIIcon.image = "/images/gmapZBIIcon.png";
		  ZBIIcon.shadow = "/images/gmapZBIIconSH.png";//"http://www.google.com/mapfiles/shadow50.png";
		  ZBIIcon.iconSize = new GSize(24, 29);
		  ZBIIcon.shadowSize = new GSize(31, 31);
		  ZBIIcon.iconAnchor = new GPoint(9, 25);
		  ZBIIcon.infoWindowAnchor = new GPoint(9, 2);
		  
		  var OfficeIcon = new GIcon(G_DEFAULT_ICON);
		  OfficeIcon.image = "/images/gmapOfficeIcon.png";
		  OfficeIcon.shadow = "/images/gmapOfficeIconSH.png";//"http://www.google.com/mapfiles/shadow50.png";
		  OfficeIcon.iconSize = new GSize(28, 18);
		  OfficeIcon.shadowSize = new GSize(35, 17);
		  OfficeIcon.iconAnchor = new GPoint(9, 25);
		  OfficeIcon.infoWindowAnchor = new GPoint(9, 2);
		  
		  // Set up our GMarkerOptions object
          markerOptions = { icon:plantIcon };

		  for (var i = 0; i < plants.length; i++) {
		    var point = new GLatLng(plants[i].lat, plants[i].lng);
		    map.addOverlay(createMarker(point, '<br><b>' + plants[i].name + '</b><br>' + plants[i].html2, markerOptions));
  		  }
		  
		  // Set up our GMarkerOptions object
          markerOptions = { icon:ZBIIcon };
		  
		  for (var i = 0; i < plants2.length; i++) {
		    var point = new GLatLng(plants2[i].lat, plants2[i].lng);
		    map.addOverlay(createMarker(point, '<br><b>' + plants2[i].name + '</b><br>' + plants2[i].html2, markerOptions));
  		  }
		
     	  markerOptions = { icon:OfficeIcon };	
		  var point = new GLatLng(office[0].lat, office[0].lng);
   	      map.addOverlay(createMarker(point, '<br><b>' + office[0].name + '</b><br>' + office[0].html2, markerOptions));
	}
	
	function showPlant2(index, plantIndex, loop) {
		mapmain.style.display = '';
		try 
		{
			GUnload();	
		} catch (err) {}
		initialize();
		setPlants();
		if(plantIndex == 0)
		{
			latlng = new GLatLng(plants[index].lat, plants[index].lng);
			map.setCenter(latlng, loop); 
			map.openInfoWindow(latlng, '<br><b>' + plants[index].name + '</b><br>');
		} else if(plantIndex == 1) {
			latlng = new GLatLng(plants2[index].lat, plants2[index].lng);
			map.setCenter(new GLatLng(plants2[index].lat, plants2[index].lng), loop);  
			map.openInfoWindow(latlng, '<br><b>' + plants2[index].name + '</b><br>');
		} else if(plantIndex == 2) {
			latlng = new GLatLng(office[0].lat, office[0].lng);
			map.setCenter(new GLatLng(office[0].lat, office[0].lng), loop);    	
			map.openInfoWindow(latlng, '<br><b>' + office[index].name + '</b><br>');
		}		
		
	}
	
	function showPlant(index, plantIndex, loop) {
		if(plantIndex == 0)
		{
			latlng = new GLatLng(plants[index].lat, plants[index].lng);
			map.setCenter(latlng, loop); 
			map.openInfoWindow(latlng, '<br><b>' + plants[index].name + '</b><br>' + plants[index].html2);
		} else if(plantIndex == 1) {
			latlng = new GLatLng(plants2[index].lat, plants2[index].lng);
			map.setCenter(new GLatLng(plants2[index].lat, plants2[index].lng), loop);  
			map.openInfoWindow(latlng, '<br><b>' + plants2[index].name + '</b><br>' + plants2[index].html2);
		} else if(plantIndex == 2) {
			latlng = new GLatLng(office[0].lat, office[0].lng);
			map.setCenter(new GLatLng(office[0].lat, office[0].lng), loop);    	
			map.openInfoWindow(latlng, '<br><b>' + office[index].name + '</b><br>' + office[index].html2);
		}
	}

	function showMap(address) {
		try 
		{
			GUnload();	
		} catch (err) {}
		
		plantsList.innerHTML = '';
		distance.innerHTML = '';
		
		GMapWindow.style.display = '';
		
		deliveryAdress.innerHTML = '<b>Адрес доставки</b><img src="/images/cms/markerB.gif" /><br /><br />&nbsp;&nbsp;&nbsp;' + address;
				
		try
		{
			initialize();
			
			//Переводим адрес в Point
			geocoder.getLatLng(address, 
				function(point) {
					if (!point) {
						alert(address + "- адрес не найден. Проверьте правильность указанного адреса доставки.");
						try 
						{
							GUnload();
						} catch (err) {}
						mapmain.innerHTML = 'Адрес не найден. Проверьте правильность указанного адреса доставки.';
					} else {
						adressPoint = point;
						
						calcNearestPlants(adressPoint);
				
						showRoute(0, 0);
				
						showPlantsList(plants[0]);						
					}
				});
			//=====================================

		} catch (err) {
			alert('Сервис недоступен. Приносим свои извинения.');	
			GMapWindow.style.display = 'none';
		}
	}


	//Расчет ближайших заводов по производству бетона и ЖБИ
	function calcNearestPlants(adressPoint) {
		//Сортируем по дальности бетонные заводы 
		for (i = 0; i < plants.length; i++)
		{
			plants[i].distance = adressPoint.distanceFrom(new GLatLng(plants[i].lat, plants[i].lng));
		}
		//отсортировали по дальности маршрута
		plants=plants.sort(function (a,b) {return (a.distance - b.distance)}); 
		//======================================
		
		//Сортируем по дальности заводы ЖБИ
		for (i = 0; i < plants2.length; i++)
		{
			plants2[i].distance = adressPoint.distanceFrom(new GLatLng(plants2[i].lat, plants2[i].lng));
		}
		//отсортировали по дальности маршрута
		plants2=plants2.sort(function (a,b) {return (a.distance - b.distance)}); 
		//======================================					
	}
	
	function showPlantsList(selectedPlant)
	{
		plantsList.innerHTML = '<em>Доставка бетона:</em>';
		for (i = 0; i < plants.length; i++)
		{
			if(i==0) {			
				if(plants[i] == selectedPlant)
				{
					plantsList.innerHTML = plantsList.innerHTML + '<li style="padding:2px 0px 2px 0px;"><b><font color="#fe6634">' + plants[i].name + '</font></b>&nbsp;<font color="red"><b>*</b></font>&nbsp;' + plants[i].html + '<br><div style="padding-left:16px">' + plants[i].address + '</div></li>';
				} else {
					plantsList.innerHTML = plantsList.innerHTML + '<li style="padding:2px 0px 2px 0px;"><a href="javascript:showRoute(' + i + ', 0);">' + plants[i].name + '</a>&nbsp;<font color="red"><b>*</b></font></li>';
				}
			} else {
				if(plants[i] == selectedPlant)
				{
					plantsList.innerHTML = plantsList.innerHTML + '<li style="padding:2px 0px 2px 0px;"><b><font color="#fe6634">' + plants[i].name + '</font></b>&nbsp;' + plants[i].html + '<br><div style="padding-left:16px">' + plants[i].address + '</div></li>';	
				} else {
					plantsList.innerHTML = plantsList.innerHTML + '<li style="padding:2px 0px 2px 0px;"><a href="javascript:showRoute(' + i + ', 0);">' + plants[i].name + '</a></li>';	
				}
			}
		}			
	
		plantsList.innerHTML = plantsList.innerHTML + '<br><em>Доставка ЖБИ:</em>';
		for (i = 0; i < plants2.length; i++)
		{
			if(i==0) {			
				if(plants2[i] == selectedPlant)
				{
					plantsList.innerHTML = plantsList.innerHTML + '<li style="padding:2px 0px 2px 0px;"><b><font color="#fe6634">' + plants2[i].name + '</font></b>&nbsp;<font color="red"><b>*</b></font>&nbsp;' + plants[i].html + '<br><div style="padding-left:16px">' + plants[i].address + '</div></li>';
				} else {
					plantsList.innerHTML = plantsList.innerHTML + '<li style="padding:2px 0px 2px 0px;"><a href="javascript:showRoute(' + i + ', 1);">' + plants2[i].name + '</a>&nbsp;<font color="red"><b>*</b></font></li>';
				}
			} else {
				if(plants2[i] == selectedPlant)
				{	
					plantsList.innerHTML = plantsList.innerHTML + '<li style="padding:2px 0px 2px 0px;"><b><font color="#fe6634">' + plants2[i].name + '</font></b>&nbsp;' + plants[i].html + '<br><div style="padding-left:16px">' + plants[i].address + '</div></li>';	
				} else {
					plantsList.innerHTML = plantsList.innerHTML + '<li style="padding:2px 0px 2px 0px;"><a href="javascript:showRoute(' + i + ', 1);">' + plants2[i].name + '</a></li>';	
				}
			}
		}			
	}
	
	function showRoute(key, ifPlant2)
	{
		if (!ifPlant2)
		{
			gdir.loadFromWaypoints([plants[key].lat + "," + plants[key].lng, adressPoint.lat() + "," + adressPoint.lng()],
														{ "locale": "ru" });	
			showPlantsList(plants[key]);
		}
		else 
		{
			gdir.loadFromWaypoints([plants2[key].lat + "," + plants2[key].lng, adressPoint.lat() + "," + adressPoint.lng()],
														{ "locale": "ru" });	
			showPlantsList(plants2[key]);
		}
	}
	
    function onGDirectionsLoad() {
        for(i = 0; i < gdir.getNumRoutes(); i++)
        {
			route = gdir.getRoute(i);
			document.getElementById('distance').innerHTML = '<br>' + '<b>Расстояние:</b>&nbsp;<span style="color:#fe6634; font-weight:bold;">' + route.getDistance().html + '</span>';
        }
    }
    
    function handleErrors(){
       if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
         alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
       else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
         alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
       
       else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
         alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

       else if (gdir.getStatus().code == G_GEO_BAD_KEY)
         alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

       else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
         alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
        
       else alert("An unknown error occurred.");       
    }  
	
	function gmapClose()
	{
		document.getElementById('GMapWindow').style.display = 'none';	
	}
    
    function Plant(name, lat, lng, html, adress, html2)
    {
		this.name = name;
		this.lat = lat;
        this.lng = lng;
        this.html = html;
        this.distance = 1000000;
		this.address = adress;
		this.html2 = html2;
    }
    
    //]]>
