var getId = function (id, doc) {
	if((id)&&((typeof id == "string")||(id instanceof String) ) ){
		if (!doc) { doc = document; }
		var ele = doc.getElementById(id);
		// workaround bug in IE and Opera 8.2 where
		// getElementById returns wrong element
		if (ele && (ele.id != id) && doc.all) {
			ele = null;
			// get all matching elements with this id
			eles = doc.all[id];
			if (eles) {
				// if more than 1, choose first
 				// with the correct id
				if (eles.length) {
					for (var i=0; i < eles.length; i++) {
						if (eles[i].id == id) {
							ele = eles[i];
							break;
						}
					}
				} // return 1 and only element
				else { ele = eles; }
			}
		}return ele;
	}return id; // assume it's a node
}


// Значения по умолчанию
var mapElement  = 'map';
var geoElement  = 'address';
var frmElement  = 'queryform';
var btnSuffix   = '_button';
var hdnSuffix   = '_hidden';

// Определение глобальных переменных
var map = null;
var center = null;
var geocoder = null;
var places = null;
var response = false;
var loс = '';
var lastquery = '';
var is_print = false;

// Пользовательские данные
var user_markers = new Array();
var user_markers_text = new Array();
var user_markers_count = 0;
var user_markers_event = null;
var user_markers_last = null;

var user_path = new Array();
var user_path_text = new Array();
var user_path_count = 0;
var user_path_event = null;
var user_path_last = null;

var pathPoly = [];
var pathLine = [];

function mapLoad()
{
	if (GBrowserIsCompatible() || arguments.length > 1) {
		if (v_size)
			mapSize(v_size, 'noCenter');

		map = new GMap2(document.getElementById(mapElement));

//		var extLargeMapControl = new ExtLargeMapControl();		
//		map.addControl(extLargeMapControl);

//		var mc = new GLargeMapControl();
		var mc = new GLargeMapControl3D();
		var mt = new GMapTypeControl();

		map.addControl(mc);
		map.addControl(mt);

	
		geocoder = new GClientGeocoder();

 // Add selectable terrain map
 map.addMapType(G_PHYSICAL_MAP);
 //var hControl = new GHierarchicalMapTypeControl();
 //hControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
 //map.addControl(hControl);
		
		
		mapInit();

		if (!response)
			map.setCenter(new GLatLng(0, 0), parseInt(v_zoom));
	}
	else
	{
		$('#'+mapElement).load('/response/browser/');
	}
	
		map.addControl(new MoreControl());	
}

function mapInit()
{
	response = false;

	var address = $('#'+geoElement+hdnSuffix).val();

	if (!address)
		return false;

	if (map && geocoder)
	{
		if (v_lat && v_lng && v_zoom && v_type)
		{
			point = new GLatLng(v_lat, v_lng);

			var t = null;

			if (v_type == 'h')
			{
				t = G_HYBRID_MAP;
			}

			if (v_type == 'k')
			{
				t = G_SATELLITE_MAP;
			}

			if (t)
			{
				map.setMapType(t);
			}

			map.setCenter(point);
			map.setZoom(v_zoom);

			response = true;
		}
		else
		{
			geocoder.setBaseCountryCode('ru');
			geocoder.getLatLng(address, function (point) {
				if (point)
				{
					if (overlays_set_center)
					{
						point = new GLatLng(overlays_set_center.latitude, overlays_set_center.longitude);
					}

					map.setCenter(point, parseInt(v_zoom));
					response = true;
				}
			});
		}
	}
	else
	{
		noMap();
		return false;
	}

}

function mapSearch()
{
	response = false;

	if ($.trim($('#'+geoElement).val()) == '')
	{
		noAddress();
		return false;
	}

	if ($.trim($('#'+geoElement).val()) == lastquery)
	{
		return false;
	}

	var address = $.trim($('#'+geoElement).val());

	lastquery = $.trim($('#'+geoElement).val());

	mapGetCache($.trim(address));
}

function mapGetCache(query)
{
	mapLoaderShow();

	$.get("/response/cache/", { query: query, place: v_place }, function (data){
		if ($.trim(data))
		{
			mapAddresses(eval('('+data+')'));
		}
		else
		{
			geocoder.getLocations($.trim($('#'+geoElement+hdnSuffix).val()+' '+query), function (data) {
				mapAddresses(data);
				if (response)
				{
					mapSaveCache(query, data);
				}
			});
		}
	});
}

function mapSaveCache(query, data)
{
	$.post("/response/cache/", { query: query, place: v_place, data: JSON.stringify(data) });
}

function mapAddresses(res)
{
	if (!res || res.Status.code != 200) {
		if (res.Status.code == 620)
		{
			noAttempts();
			mapLoaderHide();
			return false;
		}

		noResult();
		mapLoaderHide();
		return false;
	}

	if (res.Placemark.length > 1)
	{
		places = res;
		$('#additional').slideUp('slow');
		var data = '';
		for (i=0; i<res.Placemark.length; i++)
		{
			data += (i+1)+'. <a href="#" onclick="return mapShowPlace(places.Placemark['+i+'])">'+mapGetAddressString(res.Placemark[i])+'</a><br />';
		}
		$('#additional .data').html(data);
		$('#additional').slideDown('slow');
	}
	else
	{
		$('#additional').slideUp('slow');
	}

	place = res.Placemark[0];

	mapLoaderHide();

	mapShowPlace(place);

	response = true;
}

function mapShowPlace(place)
{
	point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

	var prefix = $.trim($('#'+geoElement+hdnSuffix).val());

	if (prefix)
		prefix += ', ';

	var address = mapGetAddressString(place);
	if (!address)
	{
		address = $('#'+geoElement).val();
	}

	map.clearOverlays();

	marker = new GMarker(point);
	map.panTo(point);
	map.addOverlay(marker);
	marker.openInfoWindowHtml(prefix+address);

	return false;
}

function mapGetAddressString(obj)
{
//	alert(JSON.stringify(obj));

	if (!obj)
		return false;
	else 
		return jsonPath(obj, "$..ThoroughfareName", {resultType:"VALUE"});
}

function mapSize(n)
{
	v_size = n;

	if (arguments.length == 1)
	{
		center = map.getCenter();
	}
	$('#'+mapElement).removeClass();
	$('#'+mapElement).addClass('map-size-'+n);

	$('#queryform, #queryform_brand').removeClass();
	$('#queryform, #queryform_brand').addClass('map-size-'+n);

	if (arguments.length == 1)
	{
		map.checkResize();
		map.panTo(center);
	}

	$('.mapsize a').removeClass('active');
	$('#msl_'+n).addClass('active');

	return false;
}

function mapLoaderShow()
{

	$('#'+geoElement+btnSuffix+', #'+geoElement).attr('disabled', 'disabled');
	$('#'+geoElement).val('Пожалуйста подождите...');

};

function mapLoaderHide()
{

	$('#'+geoElement+btnSuffix+', #'+geoElement).attr('disabled', false);
	$('#'+geoElement).val(lastquery);

};

function mapEnterprise()
{
	if (!map)
	{
		return false;
	}

	if (overlays_count > 0 || polyline_count > 0)
	{
		map.clearOverlays();
	}

	if (overlays_count > 0)
	{
		var ep = null;
		var em = null;

		for (i in overlays)
		{
			ep = new GLatLng(overlays[i].latitude, overlays[i].longitude);

			overlays[i].data = new GMarker(ep);
			overlays[i].data.bindInfoWindowHtml(overlays[i].name);
			map.addOverlay(overlays[i].data);
		}
	}

	if (polyline_count > 0)
	{
		var ep = null;
		var em = null;

		for (i in polyline)
		{
			ep = new GLatLng(polyline[i].latitude, polyline[i].longitude);

			polyline[i].data = new GMarker(ep);
			polyline[i].data.bindInfoWindowHtml(polyline[i].name);

			if (!v_hp)
			{
				map.addOverlay(polyline[i].data);
			}
		}

		drawPath(polyline, false);

		$('#user_sh').show();
	}
}

// Функции с префиксом 'no' обрабатывают пустые запросы и т.п.
function noMap()
{
	alert('Нет карты или не возможен поиск');
}

function noAddress()
{
	alert('Не введен адрес');
}

function noResult()
{
	alert('Адрес не найден, пожалуйста, уточните Ваш запрос');
}

function noAttempts()
{
	alert('Приносим свои извинения, достигнут лимит поисковых запросов. Осуществлять поиск можно будет завтра');
}

function printVersion()
{
	is_print = !is_print;

	if (is_print)
	{
//		$('body').attr('id', 'print-version');
		$('body').addClass('print-version');
	}
	else
	{
//		$('body').attr('id', '');
		$('body').removeClass('print-version');
	}

	return false;
}


function pushPoint()
{
	if (map)
	{

		if (user_path_event != null)
		{
			GEvent.removeListener(user_path_event);
		}

		user_markers_event = GEvent.addListener(map, "click", function(overlay, latlng) {

			if (user_path_count == 0 && user_markers_count == 0)
			{
				$('#user_link').hide();
			}

			$('#user_button').show();
			$('#user_get').hide();

			user_markers_count++;
			user_markers_text[user_markers_count] = '';

			var marker = new GMarker(latlng, {draggable: true, title: user_markers_count});

			GEvent.addListener(marker, "dragstart", function() {
				marker.closeInfoWindow();
			});

			GEvent.addListener(marker, "dragend", function() {
				var myHtml = '<p style="margin: 0 0 5px 0">Текст метки:</p><p style="margin: 0"><textarea style="width:250px;height:80px" id="ta'+marker.getTitle()+'">'+user_markers_text[marker.getTitle()]+'</textarea></p>';
				marker.openInfoWindowHtml(myHtml);
			});

			GEvent.addListener(marker, "click", function() {
				var myHtml = '<p style="margin: 0 0 5px 0">Текст метки:</p><p style="margin: 0"><textarea style="width:250px;height:80px" id="ta'+marker.getTitle()+'">'+user_markers_text[marker.getTitle()]+'</textarea></p>';
				marker.openInfoWindowHtml(myHtml);
			});

			GEvent.addListener(marker, "infowindowbeforeclose", function() {
				user_markers_text[marker.getTitle()] = $('#ta'+marker.getTitle()).val();
				GEvent.removeListener(user_markers_event);
			});

			map.addOverlay(marker);

			var myHtml = '<p style="margin: 0 0 5px 0">Текст метки:</p><p style="margin: 0"><textarea style="width:250px;height:80px" id="ta'+user_markers_count+'"></textarea></p>';
			marker.openInfoWindowHtml(myHtml);

			user_markers[user_markers_count] = marker;
			user_markers_last = marker;

		});
	}

	return false;
}


function drawPath(obj, is_marker)
{
	pathPoly.length = 0;

	var j = 0;

	for(i in obj)
	{
		if (pathLine[j])
		{
			map.removeOverlay(pathLine[j]);
		}

		if (is_marker)
		{
			pathPoly.push(obj[i].getPoint());
		}
		else
		{
			pathPoly.push(obj[i].data.getPoint());
		}

		pathLine[j] = new GPolyline(pathPoly, '#FF0000', 3, 1);

		map.addOverlay(pathLine[j]);

		j++;
	}
}

function showHidePath()
{
	map.clearOverlays();

	v_hp = !v_hp;

	if (!v_hp)
	{
		for (i in polyline)
		{
			map.addOverlay(polyline[i].data);
		}

		drawPath(polyline, false);

		$('#user_showhide').html('Скрыть точки на маршруте');
	}
	else
	{
		drawPath(polyline, false);
		$('#user_showhide').html('Показать точки на маршруте');
	}

	return false;
}

function pushPath()
{
	if (map)
	{

		if (user_markers_event != null)
		{
			GEvent.removeListener(user_markers_event);
		}

		user_path_event = GEvent.addListener(map, "click", function(overlay, latlng) {

			if (user_path_count == 0 && user_markers_count == 0)
			{
				$('#user_link').hide();
			}

			$('#user_button').show();
			$('#user_get').hide();

			user_path_count++;
			user_path_text[user_path_count] = '';

			var marker = new GMarker(latlng, {draggable: true, title: user_path_count});

			GEvent.addListener(marker, "dragstart", function() {
				user_path_last.closeInfoWindow();
				marker.closeInfoWindow();
			});

			GEvent.addListener(marker, "dragend", function() {
				drawPath(user_path, true);
			});

			GEvent.addListener(marker, "click", function() {
				var myHtml = '<p style="margin: 0 0 5px 0">Текст метки:</p><p style="margin: 0"><textarea style="width:250px;height:80px" id="ta'+marker.getTitle()+'">'+user_path_text[marker.getTitle()]+'</textarea></p>';
				marker.openInfoWindowHtml(myHtml);
			});

			GEvent.addListener(marker, "infowindowbeforeclose", function() {
				user_path_text[marker.getTitle()] = $('#ta'+marker.getTitle()).val();
			});

			map.addOverlay(marker);

			var myHtml = '<p style="margin: 0 0 5px 0">Текст метки:</p><p style="margin: 0"><textarea style="width:250px;height:80px" id="ta'+user_path_count+'"></textarea></p>';
			marker.openInfoWindowHtml(myHtml);

			user_path[user_path_count] = marker;
			user_path_last = marker;

			drawPath(user_path, true);

		});
	}

	return false;
}

function saveLink()
{
	var point = map.getCenter();
	var url = 'http://map.rzn.info/';

	if (v_place != '')
	{
		url += v_place+'/';
	}

	url += '?lng='+point.lng()+'&lat='+point.lat()+'&zoom='+map.getZoom()+'&size='+v_size;

	var type = map.getCurrentMapType().getUrlArg();
	url += '&type='+type;

	if (v_hp)
	{
		url += '&hp=1';
	}

	if (user_path_count < 1 && user_markers_count < 1)
	{
		$('#resulturl').val(url);
		$('#user_link').show();
		return false;
	}

	if (user_markers_last != null)
	{
		user_markers_last.closeInfoWindow();
	}

	if (user_path_last != null)
	{
		user_path_last.closeInfoWindow();
	}

	var data = 'polyline_count = '+user_path_count+'; ';

	for(i in user_path)
	{
		var point = user_path[i].getPoint();
		var text = user_path_text[i].substr(0, 250);

		while (text.indexOf('"') >= 0)
		{
			text = text.replace('"', "&quot;");
		}

		data += 'polyline['+i+'] = {name:"'+text+'", longitude:'+point.lng()+', latitude:'+point.lat()+', url:"url", data: null}; ';
	}

	data += 'overlays_count = '+user_markers_count+'; ';

	for(i in user_markers)
	{
		var point = user_markers[i].getPoint();
		var text = user_markers_text[i].substr(0, 250);

		while (text.indexOf('"') >= 0)
		{
			text = text.replace('"', "&quot;");
		}

		data += 'overlays['+i+'] = {name:"'+text+'", longitude:'+point.lng()+', latitude:'+point.lat()+', url:"url", data: null}; ';
	}

	data += '';

	var point = map.getCenter();

	$('#resulturl').val('Подождите');

	$.post("/response/saveuserdata/", {data: data, url: url}, function(data){
		$('#resulturl').val(data);
		$('#user_link').show();
	});


	//url += '&data=true';

}
























var timer;
var chosen = [];
 
/* Array of GLayers
 * The 'name' property is not being used here
*/
var layers = [
 { name: "Pano", obj: new GLayer("com.panoramio.all") },
 { name: "Tube", obj: new GLayer("com.youtube.all") },
 { name: "Wiki", obj: new GLayer("org.wikipedia.ru") },
 { name: "Kam", obj: new GLayer("ru.webcams.travel") }
];


function hideAll() {

 var boxes = document.getElementsByName("mark");
 for(var i = 0; i < boxes.length; i++) {
  if(boxes[i].checked) {
   boxes[i].checked = false;
   switchLayer(false, layers[i].obj);
   chosen.push(i);
  }
 }
}


function checkChecked() {

 /* Returns true if a checkbox is still checked
 *  otherwise false
 */
 var boxes = document.getElementsByName("mark");
 for(var i = 0; i < boxes.length; i++) {
  if(boxes[i].checked) return true;
 }
 return false;
}

function switchLayer(checked, layer) {

 /* Function was originally borrowed from Esa:
 *  http://esa.ilmari.googlepages.com/dropdownmenu.htm
 */
 var layerbox = document.getElementById("box");
 var boxlink = document.getElementById("boxlink");
 var button = document.getElementById("more_inner");

 if(checked) {
   map.addOverlay(layer);
   // Reset chosen array
   chosen.length = 0;
   /* Highlight the link and
   *  make the button font bold.
   */
   boxlink.className ="highlight";
   layerbox.className ="highlight";
   button.className ="highlight";
 }
 else {
   map.removeOverlay(layer);
   /*  Reset the link and the button
    * if all checkboxes were unchecked.
   */
   if(!checkChecked()) {
    boxlink.blur();
    boxlink.className ="";
    layerbox.className ="";
    button.className ="";
   }
 }
}

function showLayerbox() {

 if(window.timer) clearTimeout(timer);
 document.getElementById("box").style.display = "block";
 var button = document.getElementById("more_inner");
 button.style.borderBottomWidth = "4px";
 button.style.borderBottomColor = "white";
}


function setClose() {

 var layerbox = document.getElementById("box");
 var button = document.getElementById("more_inner");
 var bottomColor = checkChecked() ? "#6495ed" : "#c0c0c0";

 timer = window.setTimeout(function() {
  layerbox.style.display = "none";
  button.style.borderBottomWidth = "1px";
  button.style.borderBottomColor = bottomColor;
 }, 400);
}


function toggleLayers() {

 if(chosen.length > 0 ) {
   /* Make an independent copy of chosen array since switchLayer()
   *  resets the chosen array, which may not be useful here.
   */
   var copy = chosen.slice();
   for(var i = 0; i < copy.length; i++) {
    var index = parseInt(copy[i]);
    switchLayer(true, layers[index].obj);
    document.getElementsByName("mark")[index].checked = true;
   }
 }
 else {
  hideAll();
 }
}


function MoreControl() {};
MoreControl.prototype = new GControl();
MoreControl.prototype.initialize = function(map) {

 //var more = document.getElementById("outer_more");
 //var more = $("#outer_more");
 var more = getId("outer_more")
 
 var buttonDiv = document.createElement("div");
 //var buttonDiv = $("<div></div>");
 buttonDiv.id = "morebutton";
 buttonDiv.title = "Показать/скрыть слои";
 buttonDiv.style.border = "1px solid black";
 buttonDiv.style.width = "86px";
 var textDiv = document.createElement("div");
 textDiv.id = "more_inner";
 textDiv.appendChild(document.createTextNode("Ещё..."));
 buttonDiv.appendChild(textDiv);

 
 // Register Event handlers
 more.onmouseover = showLayerbox;
 more.onmouseout = setClose;
 buttonDiv.onclick = toggleLayers;

 // Insert the button just after outer_more div
 
 //more.insertBefore(buttonDiv, document.getElementById("box").parentNode);
 more.insertBefore(buttonDiv, getId("box").parentNode);
 
 // Remove the whole div from its location and reinsert it to the map
 map.getContainer().appendChild(more);
 return more;
}


MoreControl.prototype.getDefaultPosition = function() {
 return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(278, 7));
}


function showAddress(address) {

 var geocoder = new GClientGeocoder();
 geocoder.getLatLng(address, function(point) {

  if(!point) {
   alert(address + " not found.");
  }
  else {
   map.setCenter(point, 14);
  }
 });
}













// Назначение глобальных событий
$(document).ready(function() {
	$(window).unload(GUnload);

	$('#'+frmElement).submit(function() {
		mapSearch();
		return false;
	});

	
	setTimeout("mapLoad()",600);
//	mapLoad();
setTimeout("mapEnterprise()",600);
//	mapEnterprise();
});
