function Dump(d,l) {
    if (l == null) l = 1;
    var s = '';
    if (typeof(d) == "object") {
//	    var nlev = 0;
        s += " {\n";
        for (var k in d) {
            for (var i=0; i<l; i++) s += "  ";
            s += k+": " + Dump(d[k],l+1);
//						if( nlev++ > 5 ) break;
        }
        for (var i=0; i<l-1; i++) s += "  ";
        s += "}\n"
    } else {
        s += "" + d + "\n";
    }
    return s;
}

/*
Я не программист. Поэтому тут ничего интересного нет.
I am not a programmer. Nothing interestig here.

But if you can write some better jscript welcome. :)
*/

function udata() {}
udata.prototype = {
	map: null,
	point: [null, null],
	time1: "",
	nType: 0,
	nDays: 0,
	ua: "",
	nSost: 1,
	id: 0,
	allid: [],
	aIcons: {oStMark: {}, oFnMark: {}, oFind1: {}, oFind2: {}},
	arrMarkers: {},
	oActivePoint: [0, 0],
	adrList: ["/adr/src/", "/adr/dest/"],
	adrListGo: ["/adr/gettown/?q=", "/adr/getpoint/?q="],
	loadMap: function () {
		if (GBrowserIsCompatible()) {
			this.map = new GMap2(document.getElementById("idmap"));
			this.map.setCenter(new GLatLng(55.99, 37.19), 13);
			this.map.addControl(new GSmallMapControl());
			this.map.addControl(new GMapTypeControl());
			GEvent.addListener(this.map, "click", function(marker, point) {
				oDot.onMapClick(marker, point);
});
			this.arrGSize = [new GSize(32,32), new GSize(56,32), new GSize(12, 20), new GSize(22, 20)];
			this.arrGPoint = [new GPoint(10,32), new GPoint(19,0), new GPoint(6, 20), new GPoint(5, 1)];

			for(var i in this.aIcons) this.aIcons[i] = new GIcon();
			this.makeNewIcon(this.aIcons.oStMark, {image: '/pic/gicon/grn-pushpin.png', shadow: '/pic/gicon/pushpin_shadow.png', iconSize: this.arrGSize[0], shadowSize: this.arrGSize[1], iconAnchor: this.arrGPoint[0], infoWindowAnchor: this.arrGPoint[1]});
			this.makeNewIcon(this.aIcons.oFnMark, {image: '/pic/gicon/gold-pushpin.png', shadow: '/pic/gicon/pushpin_shadow.png', iconSize: this.arrGSize[0], shadowSize: this.arrGSize[1], iconAnchor: this.arrGPoint[0], infoWindowAnchor: this.arrGPoint[1]});
			this.makeNewIcon(this.aIcons.oFind1, {image: '/pic/gicon/mm_20_red.png', shadow: '/pic/gicon/mm_20_shadow.png', iconSize: this.arrGSize[2], shadowSize: this.arrGSize[3], iconAnchor: this.arrGPoint[2], infoWindowAnchor: this.arrGPoint[3]});
			this.makeNewIcon(this.aIcons.oFind2, {image: '/pic/gicon/mm_20_green.png', shadow: '/pic/gicon/mm_20_shadow.png', iconSize: this.arrGSize[2], shadowSize: this.arrGSize[3], iconAnchor: this.arrGPoint[2], infoWindowAnchor: this.arrGPoint[3]});

//	var marker_subgurim_32657_ = new GMarker(new GLatLng(41.438303,-75.618196),{clickable:true,icon:icon_subgurim_32658_});
		}
//		this.ua = navigator.userAgent + " " + screen.width + "x" + screen.height + "x" + screen.colorDepth;
	},

	onMapClick: function(marker, point) {
		if( this.nSost < 3 ) {
			var nId = this.nSost - 1;
			if( !this.point[nId] ) {
				this.point[nId] = new GMarker(point, {draggable: true}); // , icon: this.aIcons.oFind2
				this.map.addOverlay(this.point[nId]);
				this.nSost++;
				this.showReg(this.nSost); /* onclik="this.showReg(1); return(false);"*/
			}
			else {
				if( point ) this.point[nId].setLatLng(point);
			}
		}
	},

	makeNewIcon: function(oNew, oAttr) {
		for(var i in oAttr) oNew[i] = oAttr[i];
	},

	showWind: function(b) {
		if( b ) $('#shinfo').show();
		else $('#shinfo').hide();
		return false;
	},

	showDopInfo: function(id) {
		var oLocal = this;
		$.getJSON('/find/getinfo/?id='+id, function(json) {
			$('#shinfo').empty();
//			if( json.err.errno != 0 ) $('#shinfo').html("Error: "+json.err.errmsg);
//			else {
				$('#shinfo').html(json.info + ((json.err.errno!=0)?"<p>Error: "+json.err.errmsg+"</p>":""));
//			}
			oLocal.showWind(true);
		});
	},

	showInfoData: function(adr, bAdd) {
		var oLocal = this;
		$.getJSON(adr, function(json) {
			if( !bAdd ) $('#shinfo').empty();
			$('#shinfo').html($('#shinfo').html()+json.info + ((json.err.errno!=0)?"<p>Error: "+json.err.errmsg+"</p>":""));
			oLocal.showWind(true);
			if( typeof json.contact != "undefined" ) $("#idudat").html(json.contact);
		});
	},

	getGeoData: function(adr, oParam) {
		var oLocal = this;
		var s = "";
		if( typeof oParam != "undefined" )
			for(var i in oParam) s += "&"+i+"="+encodeURI(oParam[i]);
		if( s != "" ) adr += "?"+s.substr(1);
		$.getJSON(adr, function(json) {
			if( json.err.errno != 0 ) $("#idres").text("Error: "+json.err.errmsg);
			else {
				if( typeof json.act != "undefined" ) {
					eval(json.act);
				}
			}
		});
		return(false);
	},

	clearResult: function() {
//		if( this.arrMarkers.length > 0 ) {
//			alert("clearResult()");
			for(var i in this.arrMarkers) {
				this.map.removeOverlay(this.arrMarkers[i][0]);
				delete this.arrMarkers[i][0];
				this.map.removeOverlay(this.arrMarkers[i][1]);
				delete this.arrMarkers[i][1];
				delete this.arrMarkers[i];
			}
//			for(var i=this.arrMarkers.length; i>=0; i--) delete this.arrMarkers[i];
//			this.arrMarkers.length = 0;
			this.arrMarkers = {};
//		}
		this.oActivePoint = [0, 0];
	},

	makeResult: function(oRes) {
		this.clearResult();
		var sRet = "";
		var nId;
		for(var i in oRes) {
//			alert("makeResult(): add " + oRes[i].id);
//			this.arrMarkers[this.arrMarkers.length] = 
			this.arrMarkers[oRes[i].id] = [];
			this.arrMarkers[oRes[i].id][0] = 
				new GMarker(new GLatLng(oRes[i].p1.lat, oRes[i].p1.lon), {draggable: true, icon: this.aIcons.oFind1});
			this.map.addOverlay(this.arrMarkers[oRes[i].id][0]);
			nId = oRes[i].id;
			GEvent.addListener(this.arrMarkers[oRes[i].id][0],'click',function(id1){return function(){$( "#ast_"+id1).click();}}(nId)); // alert("start "+id1); 
//			this.arrMarkers[this.arrMarkers.length] = 
			this.arrMarkers[oRes[i].id][1] = 
				new GMarker(new GLatLng(oRes[i].p2.lat, oRes[i].p2.lon), {draggable: true, icon: this.aIcons.oFind2});
//			this.map.addOverlay(this.arrMarkers[this.arrMarkers.length-1]);
			this.map.addOverlay(this.arrMarkers[oRes[i].id][1]);
			GEvent.addListener(this.arrMarkers[oRes[i].id][1],'click',function(id1){return function(){$( "#afn_"+id1).click();}}(nId));
			var oLatLon = new GLatLng(oRes[i].p2.lat, oRes[i].p2.lon);
			sRet += "<tr><td class=\"tdr1\">"+oRes[i].t1+"<span class=\"time2\">"+((oRes[i].gdist.length>0)?" ("+oRes[i].gdist+")":"")+" "+this.point[1].getLatLng().distanceFrom(oLatLon).toFixed(0)+" m</span></td><td class=\"tdr1\">"+oRes[i].anc+"</td></tr>";
//			alert(oRes[i].anc);
		}
		if( sRet.length > 0 ) {
			sRet = "<table border=\"0\" cellspacing=\"0\">"+sRet+"</table>";
		}
		return sRet;
	},

	goToPoint: function(id, bStart) {
		this.showWind(false);
//		alert("goToPoint()");
//		alert(typeof(this.arrMarkers[74]));
		if( this.oActivePoint[0] != 0 ) {
			this.arrMarkers[this.oActivePoint[0]][this.oActivePoint[1]].setImage("/pic/gicon/"+((this.oActivePoint[1]==0)?"mm_20_red.png":"mm_20_green.png"));
		}
		if( typeof(this.arrMarkers[id]) != "undefined" ) {
			var omark = this.arrMarkers[id][bStart?0:1];
			var ogo = omark.getLatLng();
			if( !this.isPointVisible(ogo) )
				this.map.panTo(ogo);
			this.oActivePoint[0] = id;
			this.oActivePoint[1] = bStart?0:1;
			omark.setImage("/pic/gicon/mm_20_yellow.png");
		}
		return false;
	},

	testData: function () {
		var sret = "";
		$('#idtime select').each(function() {
			if( $(this).attr("name") == "hour" ) {
				var n1 = $(this).attr("selectedIndex");
				var n2 = $(this).children(); // filter("option");
//				alert("hour: "+$(this).attr("value")+" : "+n1+" = "+$(n2[n1]).text());
//				sret = $(this).attr("value")+sret;
				sret = $(n2[n1]).text()+sret;
			}
			if( $(this).attr("name") == "minute" ) {
				var n1 = $(this).attr("selectedIndex");
				var n2 = $(this).children(); // filter("option");
//				alert("minute: "+$(this).attr("value"));
				sret = sret+"."+$(n2[n1]).text();
//				sret = sret+"."+$(this).attr("value");
			}
		});
		this.time1 = sret;
		var nDays = 0;
		$('#cbday input').each(function() {
			var s1 = $(this).attr("name");
			var a1 = [1,2,4,8,16,32,64,128];
			if( s1.match(/d\d+/i) ) {
				if( $(this).attr("checked") ) {
					nDays += a1[s1.substr(1)-1]
				}
			}
		});
		this.nDays = nDays;
		if( this.nDays > 0 ) $('#idbut').show();
		else $('#idbut').hide();
		this.nType = $('#idrole select').attr("value");
//		alert("time = " + sret + " ; days = " + this.nDays+" this.nType = "+this.nType); // $(this).attr("name")+" : "+$(this).attr("value") + " = " + 
	},

	isPointVisible: function(oLatLon) {
		return this.map.getBounds().containsLatLng(oLatLon)
	},

	setListVal:  function (sList, sVal) {
		var nSel = 0;
		var bStop = false;
//		alert("setListVal( "+sList+", "+sVal+" )");
		$(sList+" option").each(function(){
			if( bStop ) return;
			var sOpVal = $(this).attr('value');
			sOpVal = sOpVal.replace(/^\s*(.*?)\s*$/, "$1");
			if( sOpVal.length == 0 ) sOpVal = $(this).text();
			if( sOpVal )
				if( sOpVal == sVal ) {
					$(sList).attr('selectedIndex', nSel);
					bStop = true;
				}
			nSel++;
		});
	},

	getPoints:  function () {
		var oLocal = this;
		$("#idres").text("Loading ...");
		$.getJSON('/find/getpoint/', function(json) {
			$("#idres").empty();
			if( json.err.errno != 0 ) $("#idres").text("Error: "+json.err.errmsg);
			else {
				var sprint = "";
				if( json.contact ) $("#idudat").html(json.contact);
				if( json.retmsg ) sprint += json.retmsg;
//				alert(Dump(json));
				if( json.pnt.length > 0 ) {
					for(var j in json.pnt) {
						if( json.pnt[j].p1 && json.pnt[j].p1.lat && json.pnt[j].p1.lon ) {
							oLocal.nSost = 1;
							oLocal.onMapClick(null, new GLatLng(json.pnt[j].p1.lat, json.pnt[j].p1.lon));
						}
						else continue;
						if( json.pnt[j].p2 && json.pnt[j].p2.lat && json.pnt[j].p2.lon ) {
							oLocal.onMapClick(null, new GLatLng(json.pnt[j].p2.lat, json.pnt[j].p2.lon));
						}
						else continue;
						if( json.pnt[j].ty ) {
							oLocal.setListVal("#idrole select", json.pnt[j].ty);
						}
						if( json.pnt[j].t1 ) {
							var a1 = json.pnt[j].t1.split(".");
							oLocal.setListVal("#idtime select[@name=\"hour\"]", 1*a1[0]);
							oLocal.setListVal("#idtime select[@name=\"minute\"]", 1*a1[1]);
						}
						if( json.pnt[j].d ) {
							for(var k=1, n1=1; k<8; k++, n1*=2)
								if( (n1 & json.pnt[j].d) )
									$("#cbday input[@name=\"d"+k+"\"]").attr('checked', true);
						}
						oLocal.id = json.pnt[j].id;
						
						break;
					}
					oLocal.testData();
				}
			}
		});
	},

	selRow: function (oRow) {
//		alert("selRow()"+$(oRow).html());
		$(oRow).siblings().children("td").removeClass("trr1");
		$(oRow).children("td").addClass("trr1");
	},

	setMapPos: function (lat, lon, scale) {
		this.map.setCenter(new GLatLng(lat, lon), scale);
		return false;
	},

	gotoPointName:  function (sAdr) {
//		$("#idres").text(sAdr);
		var oLocal = this;
		$.getJSON(sAdr, function(json) {
			if( json.err.errno != 0 ) $("#idres").text("Error: "+json.err.errmsg);
			else {
				$("#idres").text("");
				if( json.pnt.length == 1 )
					oLocal.setMapPos(json.pnt[0].lat, json.pnt[0].lon, 14);
//					oLocal.map.setCenter(new GLatLng(json.pnt[0].lat, json.pnt[0].lon), 13);
				else {
					var s1 = "";
					if( json.info ) s1 += json.info;
					for(i in json.pnt ) s1 += "<p>"+json.pnt[i].info+"</p>";
					$('#shinfo').html(s1);
					oLocal.showWind(true);
				}
			}
		});
	},

	clearLogo: function() {
		$("#idmap div a").each(function() {
			if( $(this).attr('href').indexOf('google.com') > 0 ) {
				$(this).parent().hide();
			}
		});
	},

	makePointReq: function(sAdr) {
		$("#idres").text("Make request ...");
		this.showWind(false);
		var oLocal = this;
		var sreq = "p1="+this.point[0].getLatLng().toUrlValue()+"&p2="+this.point[1].getLatLng().toUrlValue();
		sreq += "&t1="+this.time1+"&ty="+this.nType+"&d="+this.nDays+"&id="+this.id;
		$.getJSON(sAdr+'?'+sreq, function(json) {
			$("#idres").text("Calculate ...");
//			$("#idres").empty();
			if( json.err.errno != 0 ) $("#idres").text("Error: "+json.err.errmsg);
			else {
				if( json.contact ) $("#idudat").html(json.contact);
				if( json.newid && (json.newid != 0) ) oLocal.id = json.newid;
				var sprint = "";
				if( json.retmsg ) sprint += json.retmsg;
				oLocal.clearResult();
				if( json.pnt.length > 0 ) {
					sprint += oLocal.makeResult(json.pnt);
				}
				$("#idres").html(sprint)
			}
		});
	},

	showReg: function (nReg) {
//		if( this.nSost < nReg ) nReg = this.nSost;
		$('.order li').each(function() {
			$(this).hide();
		});
		$('.order li#v0'+nReg).show();
		this.nSost = nReg;
		if( nReg > 1 ) $('.order li#v0'+(nReg-1)+' div .next').show();
		if( nReg < 3 )
			if( this.point[nReg-1] && !this.isPointVisible(this.point[nReg-1].getLatLng()) ) this.map.setCenter(this.point[nReg-1].getLatLng());
	}
}
oDot = new udata;

$(document).ready(function(){
	if( $('#idmap').length > 0 ) {
		oDot.loadMap();
		oDot.showReg(1);
	}
	$('.order li').each( function() {
		var sAdd = "";
		if( $(this).attr("id") != "v01" ) sAdd += "<a href='' class='prev'><img src=\"/pic/default/go1.gif\" width=16 height=16 border=0 alt=\"\"></a>";
		else sAdd += "<img src=\"/pic/1.gif\" width=16 height=1 border=0 alt=\"\">";
		if( sAdd != "" ) sAdd += " ";
		if( $(this).attr("id") != "v04" ) sAdd += "<a href='' class='next'><img src=\"/pic/default/go2.gif\" width=16 height=16 border=0 alt=\"\"></a>";
		sAdd = "<div class=\"numb\">"+sAdd+"</div>";
		$(this).append(sAdd);
	});
	$('.order li div .next').hide();
	$('.order li div .next').click( function() { oDot.showReg($(this).parent().parent().attr("id").substr(2)*1+1); return false;} );
	$('.order li div .prev').click( function() { oDot.showReg($(this).parent().parent().attr("id").substr(2)*1-1); return false;} );
	$('#cbday input').change( function() { oDot.testData();} );
	$('#idrole select').change( function() { oDot.testData();} );
	$('#idtime select').change( function() { oDot.testData();} );
	$("#idres").ajaxError(function(request, settings){
//			alert();
		$(this).html("<p>Error requesting page " + settings.responseText + "</p>");
	});
	$('input[@name=find]').click( function() {
		oDot.makePointReq('/find/getres/');
	});
	$('input[@name=go1]').click( function() {
		oDot.gotoPointName(oDot.adrListGo[0]+encodeURI($('#idnear1').val()));
	});

	$('input[@name=go2]').click( function() {
		oDot.gotoPointName(oDot.adrListGo[1]+encodeURI($('#idnear2').val()));
	});

	$('input[@name=setcity]').click(function() {
		oDot.getGeoData('/adr/setsity/', {'city': $('input[@name=city]').val()});
	});

	$('#setsity').submit(function() {
		return oDot.getGeoData('/adr/setsity/', {'city': $('input[@name=city]').val()});
	});
//	setTimeout('oDot.clearLogo()', 5000);
	

function liFormat (row, i, num) {
	var result = row[0]; //  + '<!-- <p class=qnt>' + row[1] + '</p> -->'
	return result;
}

function selectItem(li) {
	if( li == null ) return; // var sValue = 'А ничего не выбрано!';
	if( !!li.extra ) var sValue = li.extra[2];
	else var sValue = li.selectValue;
	if( sValue.length > 0 )
		oDot.gotoPointName(oDot.adrListGo[oDot.nSost-1]+sValue); // encodeURI($('#idnear2').val())
//	alert("Выбрана запись с ID: " + sValue);
}

$('#idnear1').autocomplete(oDot.adrList[0], {
	delay:10,
	minChars:3,
	matchSubset:1,
	autoFill:false,
	matchContains:1,
	cacheLength:0,
	selectFirst:false,
	formatItem:liFormat,
	maxItemsToShow:10,
	onItemSelect:selectItem
});

$('#idnear2').autocomplete(oDot.adrList[1], {
	delay:10,
	minChars:3,
	matchSubset:1,
	autoFill:false,
	matchContains:1,
	cacheLength:0,
	selectFirst:false,
	formatItem:liFormat,
	maxItemsToShow:10,
	onItemSelect:selectItem
});

});

