var map, marker, icon, exml, directions, image_path, cs;
var curCity = 'Москва';
var cityCodes = [];
function goOffice(p) {
	if (directions!==undefined) directions.clear();
	var n = getOffice(p);
	//document.getElementById("infoDrive").innerHTML = "<h4>в "+fbOficeName[n]+" ФОРА-БАНКа</h4>";
	var directionsPanel = document.getElementById("infoDrive");
	var route = (["Указанная Вами точка начала пути "+cs+" Фора-Банка@"+p.lat()+","+p.lng(), nameparse(exml.side_bar_list[n])+"@"+exml.gmarkers[n].getLatLng().lat()+","+exml.gmarkers[n].getLatLng().lng()]);
  	directions = new GDirections(map, directionsPanel);
	GEvent.addListener(directions, "load", onGDirectionsLoad);
	directions.loadFromWaypoints(route ,{locale: "ru"});
}
function nameparse(s) {
	var n = s.indexOf("$$$");
	return s.substr(0,n);
}
function onGDirectionsLoad(){
	if (directions!==undefined) {
		directions.getMarker(1).getIcon().image = image_path+"/end.png";
		directions.getMarker(1).getIcon().iconSize = new GSize(76, 28);
        directions.getMarker(1).getIcon().iconAnchor = new GPoint(-20, 40);
		directions.getMarker(0).hide();
		marker.setLatLng(directions.getMarker(0).getLatLng());
	}
}

function getOffice(p) {
	var n = 0;
	var q = p.distanceFrom(exml.gmarkers[0].getLatLng());
	for (i=1;i<exml.gmarkers.length-1;i++) {
		if (q > p.distanceFrom(exml.gmarkers[i].getLatLng()))	{
			q = p.distanceFrom(exml.gmarkers[i].getLatLng());
			n = i;
		}
	}

	return n;
}

function addCityCode(code){
	cityCodes.push(code);
}

function selectCity(cityCode, cGLatLng, cZoom, cMapType){
	if(cityCode == 'all'){
		for (i=0;i<cityCodes.length;i++) {
			$('.'+cityCodes[i]).css('display', 'block');
		}
		map.setCenter(new GLatLng(55.74342553434736, 37.62695074081421), 7);
		map.setMapType(G_NORMAL_MAP);
	}
	else{
		for (i=0;i<cityCodes.length;i++) {
			if (cityCodes[i] == cityCode)
				$('.'+cityCodes[i]).css('display', 'block');
			else
				$('.'+cityCodes[i]).css('display', 'none');
		}
		map.setCenter(cGLatLng, cZoom, cMapType);
	}
}

function variant(kml_path, img_path, cmo_mode) {
//var cont = setGoogleMap();
//document.getElementById("map_container").innerHTML =cont;
    image_path=img_path;
    //geoXml = new GGeoXml("http://forateka.ru/demo/offices.kml?p="+Math.random());
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(55.74342553434736, 37.62695074081421), 10);
    map.addMapType(G_SATELLITE_MAP);
    map.addControl(new GHierarchicalMapTypeControl());
	map.addControl(new GLargeMapControl());
	map.disableDoubleClickZoom();
	GEvent.addListener (map, "dblclick",
							function(overlay, point) {
								if (!overlay) {
									testDrive(point);
								}
							}
					    );

    icon = new GIcon();
	icon.image = image_path+"/auto.png";
    icon.iconSize = new GSize(40, 46);
    icon.shadowSize = new GSize(32, 32);
    icon.iconAnchor = new GPoint(10, 10);
    icon.infoWindowAnchor = new GPoint(5, 1);

    var cc;
    if (cmo_mode=='offices') {
      cc = new GLatLng(57.5, 47.3025);
      cs = 'в ближайший офис';
    } else {
      cc = new GLatLng(57.1, 42.60);
      cs = 'к ближайшему банкомату';
    }

 	marker = new GMarker(cc, {icon: icon, draggable: true});
    GEvent.addListener(marker, "dragstart", function() {
		map.closeInfoWindow();
	  });
	GEvent.addListener(marker, "click", function() {
		alert("Для прокладки автомобильного маршрута "+cs+" Фора-Банка передвиньте автомобиль в точку, из которой Вы планируете поездку. Вы можете найти маршрут только в пределах Московской области и приграничных к ней районах.");
	  });

	GEvent.addListener(marker, "dragend", function(point) {
		testDrive(point);
	});
    map.addOverlay(marker);

    exml = new EGeoXml("exml", map, kml_path, {sidebarid:"officesList",iwwidth:550,sbaseicon:icon,titlestyle:'class="mw"', descstyle:'class = "description"'});
    exml.parse();

    GEvent.addListener(map, "maptypechanged", saveMapType);
    //GEvent.addListener(map, "click", function(overlay, point) {alert(point.lat()+'  '+point.lng());});
}

function testDrive(p) {
		if (pointInPolygon(p)) {
			goOffice(p);
		} else {
			alert("Прокладка автомобильного маршрута из заданной точки начала пути в настоящее время не доступна. Задайте начальную точку ближе к Москве.");
		}
}
function pointInPolygon(p) {
	var x = p.lat();
	var y = p.lng();
	var poly = exml.gpolygons[0];
	var polySides = poly.getVertexCount();
	//alert(polySides);
	//alert(poly.getVertex(0));
	//alert(poly.getVertex(0).lng());
	var i, j=polySides-1 ;
  	var  oddNodes=false
	for (i=0; i<polySides; i++) {
	if (poly.getVertex(i).lng()<y && poly.getVertex(j).lng()>=y ||  poly.getVertex(j).lng()<y && poly.getVertex(i).lng()>=y) {
	  if (poly.getVertex(i).lat()+(y-poly.getVertex(i).lng())/(poly.getVertex(j).lng()-poly.getVertex(i).lng())*(poly.getVertex(j).lat()-poly.getVertex(i).lat())<x) {
		oddNodes=!oddNodes; }}
	j=i;
	}
	return oddNodes;
}

function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
            ((expires) ? "; expires=" + expires.toGMTString() : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "")
    document.cookie = curCookie
}

function getCookie(name) {
    var prefix = name + "="
    var cookieStartIndex = document.cookie.indexOf(prefix)
    if (cookieStartIndex == -1)
            return null
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
    if (cookieEndIndex == -1)
            cookieEndIndex = document.cookie.length
    return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

function saveMapType() {
    var cmt = map.getCurrentMapType().getName();
    var ndt = new Date();
    ndt.setDate(ndt.getDate() + 100);
    setCookie(escape(curCity)+"MapType", cmt, ndt);
}

function getMapType(selCity) {
    curCity = selCity;
    var mts = '';
    var mt = G_NORMAL_MAP;
    mts = getCookie(escape(selCity)+"MapType");
    switch(mts) {
        case 'Спутник':
            mt = G_SATELLITE_MAP;
            break;
        case 'Гибрид':
            mt = G_HYBRID_MAP;
            break;
        default:
            mt = G_NORMAL_MAP;
    }
    return mt;
}