jQuery.preloadImages = function()
{
	for(var i = 0; i<arguments.length; i++)
		jQuery("<img>").attr("src", arguments[i]);
};


/*
* Инициализация при загрузке страницы
*/
$(function(){
	window.hidden = {15:1};
	$.ajax({
		type: "get",
		url: "/int/yachts/cache/yacht_list.txt?rand="+Math.floor(Math.random()*10001),
		dataType: "json",
		success: function(data){
			var dt=data[0]["dt"];
			var j=0;
			for(var i=1;i<data.length;i++)
			{
				if(dt<data[i].dt)
				{
					dt=data[i].dt;
					j=i;
				}
			}
			//window.map = new GMap(data[j].lat/100000,data[j].lng/100000,2); // центр карты устанавливаем на яхту, о которой есть самая свежая информация
			window.map = new GMap(data[5].lat/100000,data[5].lng/100000,2); // центр карты устанавливаем на яхту, о которой есть самая свежая информация
			window.map.showMarkers(data); // показываем маркеры всех яхт
			window.map.makeTimeControl(2012,0); // показываем ползунок для задания промежутка времени, начало отсчета 2010 год, 1 месяц (февраль, 0 - январь)
		}
	});


	/*
	* All map controls
	*/
	$("td.name").bind("click",function(){
		window.scrollBy(0,-window.pageYOffset+387); 
		if ($(this).parent().find(".checkbox span a").hasClass("unchecked")) {
			$(this).parent().find("input").attr("checked","checked").parent().find("span a").removeClass("unchecked");
		}	
		window.map.getBounds($(this).find("label").text());
	});


	$("td.checkbox a").click(function(){	
		if ($(this).hasClass("unchecked")) {
			$(this).parent().parent().find("input").attr("checked","").parent().find("span a").removeClass("unchecked");
			var yid = $(this).attr("href").replace("#","");
			if(yid)
				window.showYacht(yid);
		}	
		else
		{
			$(this).parent().parent().find("input").removeAttr("checked").parent().find("span a").addClass("unchecked");
			var yid = $(this).attr("href").replace("#","");
			if(yid)
				window.hideYacht(yid);
		}
	});


	// Tabs	
	$("#tabs .nav_tabs a").click(function(){
		$("#tabs .nav_tabs a").removeClass("active");
		$(this).addClass("active");
	})
	
	$("#tab1").click(function(){
		$("#hosts table").addClass("wide");
	});
	$("#tab2").click(function(){
		$("#hosts table").removeClass("wide");
	});


	$.preloadImages(
		"/int/yachts/img/yachts/a.gif",
		"/int/yachts/img/yachts/anastasia.gif",
		"/int/yachts/img/yachts/anna.gif",
		"/int/yachts/img/yachts/avangard.gif",
		"/int/yachts/img/yachts/dilbar.gif",
		"/int/yachts/img/yachts/ice.gif",
		"/int/yachts/img/yachts/legrandbleu.gif",
		"/int/yachts/img/yachts/pelorus.gif",
		"/int/yachts/img/yachts/predator.gif",
		"/int/yachts/img/yachts/queen-k.gif",
		"/int/yachts/img/yachts/solemar.gif",
		"/int/yachts/img/yachts/sussuro.gif",
		"/int/yachts/img/yachts/tripleseven.gif",
		"/int/yachts/img/yachts/eclipse.gif",
		"/int/yachts/img/yachts/luna.gif"
	);

});


window.showYacht = function(yid)
{
	if(window.map.markers[yid])
		window.map.markers[yid].setVisible(true);
	window.hidden[yid]=null;
}

window.hideYacht = function(yid)
{
	window.map.ib.close();
	window.map.removeRoots();
	if(window.map.markers[yid])
		window.map.markers[yid].setVisible(false);
	window.hidden[yid]=1;
}


/* 
* Обрабатывает перемещения ползунков при выборе периода отображения маршрутов яхт
*/
window.slider_callback = function(slider_component)
{		
	window.map.formPeriodQuery();	
	window.map.onPeriodChange();
}


// 2010-02-15 23:15:43 -> 15/02 23:15
window.formatDate = function(date)
{
	var arr=date.split(" ");
	var arr1=arr[0].split("-");
	var time=arr[1]?arr[1].substring(0,5):"";
	return arr1[2]+"/"+arr1[1]+" "+time;
}


window.arrows_data = [];


/*
* Карта с маркерами яхт
*/
function GMap(lat,lng,zoom)
{
	var myLatLng = new google.maps.LatLng(lat,lng);
    var myOptions = {
		zoom: zoom,
		center: myLatLng,
		mapTypeId: google.maps.MapTypeId.TERRAIN,
		scaleControl:true
    };
    this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);	

	this.yachts = {}; // список всех яхт (ID, название, владелец, координаты)
	this.markers = {}; // список маркеров яхт		
	this.bounds = {}; // "зоны обитания" яхт
	this.focus_yacht; // текущая яхта
	
	// данные о текущем маршруте
	this.roots={}; // хэш данных о перемещении яхт
	this.still =true; // неподвижная яхта
	this.gotbounds = false;
	this.lines = []; // маршрут: линии
	this.circles = []; // маршрут: точки
	this.winds = []; // маршрут: стрелки
	this.a_overlay = null; // слой, позволяюший спроецировать карту на плоскость и перевести координаты (широта, долгота) в пиксели

	this.mon_border_points = {}; // запоминаем границы между отрезками марштрутов (маршрут каждой яхты делится на отрезки помесячно)

	
	this.infowindow = new google.maps.InfoWindow({content: ""});

	this.ib_options = {
					content: ""
					,disableAutoPan: false
					,maxWidth: 0
					,pixelOffset: new google.maps.Size(-140, 0)                     
					,zIndex: null
					,boxStyle: { 
						background: "url('/int/yachts/img/tipbox_w.gif') no-repeat"
						,opacity: 1.00
						,width: "420px"
					}
					,closeBoxMargin: "0px 0px 2px 2px"
					,closeBoxURL: "/int/yachts/img/x.gif" // close.gif
					,infoBoxClearance: new google.maps.Size(1, 1)
					,isHidden: false
					,pane: "overlayMouseTarget" // floatPane
					,enableEventPropagation: false
				};
	this.ib = new InfoBox(this.ib_options); 
	this.picts = {5:"a",4:"anastasia",12:"anna",14:"avangard",6:"dilbar",8:"ice",7:"legrandbleu",1:"pelorus",10:"predator",11:"queen-k",13:"solemar",3:"sussuro",9:"tripleseven",2:"eclipse",16:"luna"};

	var me = this;


	/*
	* Обработчик события "смена зума"
	*/
	google.maps.event.addListener(me.map,"zoom_changed",function(event){me.onZoomChange(event);});


   /*
   *  Обрабатывает выбор одной яхты для слежения,
   *  запрашивает данные о географических границах маршрута яхты за выбранный период,
   *  меняет границы обображаемой области карты, так чтобы весь маршрут был видим,
   *  при этом меняется зум, а по событию "смена зума" запрашиваются данные о маршрутах 
   *  всех яхт для данного зума и данного промежутка времени.
   */
	this.getBounds = function(yacht)
	{
		me.user_event = "focus";
		me.focus_yacht=yacht;
		if(window.map.markers[me.focus_yacht])
			window.map.markers[me.focus_yacht].setVisible(true);
		me.formPeriodQuery();
		me.bmcount=me.start;
		me.mcount=me.start;
		me.getMonthBounds();
		if($(".baloon")) $("#baloon").removeClass("timetip");
	}


	// Показать яхту, которая не движется
	this.showStillYacht = function()
	{
		me.map.setZoom(15);
		me.map.setCenter(new google.maps.LatLng(me.yachts[me.focus_yacht].lat/100000,me.yachts[me.focus_yacht].lng/100000), 15);						
	}


	this.getMonthBounds = function()
	{		
		var year = 2012;
		var mon = me.bmcount+1<10? "0"+(me.bmcount+1) : me.bmcount+1;
		if (mon == "00"){
			mon = "12";
			year = "2010";
		};
		if (mon == "0-1"){
			mon = "11";
			year = "2010";
		};
		$.ajax({
			type: "get",
			url: "/int/yachts/cache/bounds_"+year+"_"+mon+".txt?rand="+Math.floor(Math.random()*10001),
			dataType: "json",
			success: function(data){				
				if(!me.bounds[me.focus_yacht])
					me.bounds=data;	
				else
				{
					for(ind in me.bounds)
					{
						if(data[ind])
						{
							me.bounds[ind]["max_lat"]=Math.max(me.bounds[ind]["max_lat"],data[ind]["max_lat"]);
							me.bounds[ind]["max_lng"]=Math.max(me.bounds[ind]["max_lng"],data[ind]["max_lng"]);
							me.bounds[ind]["min_lat"]=Math.min(me.bounds[ind]["min_lat"],data[ind]["min_lat"]);
							me.bounds[ind]["min_lng"]=Math.min(me.bounds[ind]["min_lng"],data[ind]["min_lng"]);
						}
					}
				}
				me.bmcount++;
				me.still = true;
				me.showArea();		
				if(me.bmcount>=me.end) 
				{
					if(me.still)					
						me.showStillYacht();
					me.gotbounds = true;
					return;
				}
				else me.getMonthBounds();
			}
		});
	}


	/*
	* Фиксируем границы карты по границам маршрута выбранной яхты11.03.2010
	*/
	this.showArea = function()
	{
		for(ind in me.bounds)
		{
			if(me.focus_yacht==ind)
			{
				var ne=new google.maps.LatLng(me.bounds[me.focus_yacht].max_lat/100000, me.bounds[me.focus_yacht].max_lng/100000); //ne max_lat, max_lng
				var sw=new google.maps.LatLng(me.bounds[me.focus_yacht].min_lat/100000,me.bounds[me.focus_yacht].min_lng/100000);  //sw min_lat, min_lng
				var bounds_obj= new google.maps.LatLngBounds(sw,ne);	
				me.map.fitBounds(bounds_obj);
				me.still = false;
			}
		}
	}


	/*
	*  По событию "смена зума" запрашиваются данные о маршрутах 
	*  всех яхт для данного зума и данного промежутка времени
	*/
	this.onZoomChange = function(event){
		if(me.bmcount>=me.end){
			me.getRoots();
			//me.ib.close();
			//me.ib.setContent(me.getBaloonHtml(me.yachts[me.focus_yacht]['id'], me.yachts[me.focus_yacht]['name'], me.yachts[me.focus_yacht]['owner']));
			//me.ib.open(me.map, me.markers[5]);
		}
	}
	

	/*
	*  По событию "смена периода" запрашиваются данные о маршрутах 
	*  всех яхт для данного зума и данного промежутка времени
	*/
	this.onPeriodChange = function()
	{
		me.formPeriodQuery();
		if(me.focus_yacht) 
			me.getRoots();
	}


	this.getRoots = function()
	{
		me.removeRoots();
		var today = new Date();
		var mon = today.getMonth();
		me.mcount = me.start;
		me.getMonthRoots();
	}


	this.getMonthRoots = function()
	{
		var year = 2012;
		//me.bmcount--;
		var mon = me.mcount<10? "0"+me.mcount : me.mcount;
		if (me.mcount == -2){
			mon = "11";
			year = "2010";
		};
		if (me.mcount == -1){
			mon = "12";
			year = "2010";
		};
		if (me.mcount == 0){
			mon = "01";
			year = "2012";
		};
		var z=me.map.getZoom();
		if(z>15) z=15;
		z=z<10?"0"+z:z;
		$.ajax({
			type: "get",
			url: "/int/yachts/cache/"+z+"_"+year+"_"+mon+".txt?rand="+Math.floor(Math.random()*10001),
			dataType: "json",
			success: function(data){	
				me.roots=data;
				me.quick_showRoots();
				me.mcount++;
				if(me.mcount>me.end)
				{					
					me.getArrowsWings();
					me.DrawLastCircles(z);
					return;
				}
				else 
					me.getMonthRoots();
			}
		});
	}


	/*
	* Определяет, маршруты каких яхт нужно отображать на карте
	*/
	this.getCloseYachts = function(yacht)
	{
		var yachts = {};
		yachts[me.focus_yacht]=me.focus_yacht;
		var bounds = new google.maps.LatLngBounds();

		if(me.bounds[me.focus_yacht])
		{
			var ne=new google.maps.LatLng(me.bounds[me.focus_yacht].max_lat/100000, me.bounds[me.focus_yacht].max_lng/100000); //ne max_lat, max_lng
			var sw=new google.maps.LatLng(me.bounds[me.focus_yacht].min_lat/100000,me.bounds[me.focus_yacht].min_lng/100000);  //sw min_lat, min_lng
			var fbounds = new google.maps.LatLngBounds(sw,ne);
		}
		for(ind in me.bounds)
		{				
			if(window.hidden[ind]==1) continue;
			if(ind!=me.focus_yacht && me.bounds[me.focus_yacht] && me.bounds[ind])
			{				
				ne=new google.maps.LatLng(me.bounds[ind].max_lat/100000, me.bounds[ind].max_lng/100000); //ne max_lat, max_lng
				sw=new google.maps.LatLng(me.bounds[ind].min_lat/100000,me.bounds[ind].min_lng/100000);  //sw min_lat, min_lng
				var bounds = new google.maps.LatLngBounds(sw,ne);
				if(bounds.intersects(fbounds))
					yachts[ind]=ind;
			}
		}
		return yachts;
	}

		
    this.quick_showRoots = function()
	{			
		/*
		"#FFCE0A" - желтый теплый (Абрамович, Sussurro, 3),
		"#007F0E" - темно-зеленый (Усманов, Dilbar, 6),
		"#FF192B" - красный (Анна, Рыболовлев, 12),
		"#404040" - черный (Керимов, Ice, 8),
		"#B200FF" - сиреневый (Абрамов, Triple Seven, 9),
		"#4A0037" - коричневый (Махмудов, Predator, 10),
		"#0026FF" - синий (Дерипаска, Queen K, 11),
		"#FFFFFF" - белый (Потанин, Анастасия, 4),
		"#FF00DC" - лиловый (Прохоров, Solemar ,13),
		"#00FFFF" - голубой (Миновалов, Avangard II, 14),
		"#FCFF21" - желтый холодный, (Швидлер, Le Grand Bleu, 7),
		"#4CFF00" - зеленый неон (Абрамович, Пелорус,1),
		"#FF6600" - рыжий  (Мельниченко, A, 5),
		"#FFE4FF" - розовый, запасной :-)
		*/
		var colors={3:"#FFCE0A",6:"#007F0E",12:"#FF192B",8:"#404040",9:"#B200FF",10:"#4A0037",11:"#0026FF",4:"#FFFFFF",13:"#FF00DC",14:"#00FFFF",7:"#FCFF21",2:"#FFE4FF",1:"#4CFF00",5:"#FF6600",16:"#FFE4FF"};
		
		var yachts=me.getCloseYachts();	
		
		var roots = {};
		var roots_exist = false;
		for(ind in yachts)
		{
            //var ind = me.focus_yacht;
			if(me.roots[ind])
			{
				if(!me.roots[ind]) continue;
				roots[ind]=me.roots[ind];
				roots_exist = true;
				for(j in roots[ind])
					roots[ind][j]["color"]=colors[ind];
			}
        }
		
		if(roots_exist)
			me.Draw(roots);	

		if(me.markers[me.focus_yacht] && me.user_event=="focus")
		{
			me.user_event=null;
			me.ib.close();
			me.ib.setContent(me.getBaloonHtml(me.focus_yacht,me.markers[me.focus_yacht].name,me.markers[me.focus_yacht].owner));
			me.ib.open(me.map, me.markers[me.focus_yacht]);
		}
	}

	
	/*
	* Отображает маркеры всех яхт на карте
	*/
	this.showMarkers = function(yachts)
	{	    
		this.markers = {};
		for(var i=0;i<yachts.length;i++)
		{
			if(window.hidden[yachts[i].id]) continue;	
				me.yachts[yachts[i].id] = yachts[i];
		}

		for(var ind in me.yachts)
		{			
			var latlng = new google.maps.LatLng(me.yachts[ind].lat/100000,me.yachts[ind].lng/100000);			 
			this.markers[ind] = new google.maps.Marker({
				position: latlng,
				icon: "/int/yachts/img/pipka.png",
				map: this.map,
				zIndex: 2,
				title:me.yachts[ind].name,
				id:ind,				
				name:me.yachts[ind].name, 
				owner:me.yachts[ind].owner,
				dt:me.yachts[ind].dt				
			});                
			
			google.maps.event.addListener(this.markers[ind], 'click', function() {				
				if($(".baloon")) $("#baloon").removeClass("timetip");
				me.ib.close();
				me.ib.setContent(me.getBaloonHtml(this.id,this.name,this.owner));
				me.ib.open(this.map,me.markers[this.id]);
				me.tm=setTimeout(me.enlargeBaloon,1);
			});
			me.ib.setContent(me.getOneBaloonHtml());
			me.ib.open(this.map,me.markers[2]);
			me.tm=setTimeout(me.enlargeBaloon,1);
		
		}
	}
	
	/*
	* Отображает ползунок и selects для выбора промежутка времени
	*/
	this.makeTimeControl = function(sy,sm)
	{
		var today = new Date();
		var mon = today.getMonth();
		if(mon < 10) mon = "0"+mon;
		
		var months = {"01":"январь","02":"февраль","03":"март","04":"апрель","05":"май","06":"июнь","07":"июль","08":"август","09":"сентябрь","10":"октябрь","11":"ноябрь","12":"декабрь"};

		var ey=2012;
		var em=12;
		/*
		var html="";
		for(var y=sy;y<=ey;y++)
		{		
			html+='<optgroup label="'+y+'">';
			var y2=(y+'').substring(2,4);
			for(var m=1;m<=12;m++)
			{
				if(y==sy && m<sm || y==ey && m>em) continue;
				var m2=m<10?'0'+m:m;
				html+='<option value="'+m2+'/'+y2+'">'+months[m2]+' / '+y2+'</option>';
				html+='\n';
			}
			html+='</optgroup>';
			html+='\n';
			var smy=(em<10?'0'+(em):(em))+'/'+(ey+'').substring(2,4);
			var emy=em<10?'0'+em:em+'/'+(ey+'').substring(2,4);
			$('#valueAA').html(html.replace('value="'+mon+'/10"','value="'+mon+'/10" selected="selected"'));
			$('#valueBB').html(html.replace('value="12/10"','value="12/10" selected="selected"'));
		}
		$('select#valueAA, select#valueBB').selectToUISlider({
			labels: 12
		});

		if(sm==em && sy == ey)
			$("#tcontrol").css("display","none");	

		this.sm=sm;
		this.sy=sy;
		this.em=em;
		this.ey=ey;
		*/		
		this.formPeriodQuery();
	}


	this.formPeriodQuery = function()
	{		
		//me.start=$('select#valueAA').get(0).selectedIndex+1;		
	    //me.end=$('select#valueBB').get(0).selectedIndex+1;
	    //me.start = 0;
	    //me.end = 1;
		var today = new Date();
		var em=today.getMonth();
		me.end = em+1;
		me.start = me.end - 2;
	}


	this.getBaloonHtml = function(ind,name,owner)
	{
		//var html = "<div class='baloon'>";
		html = "<img src='/int/yachts/img/yachts/"+me.picts[ind]+".gif'><br/>";
		html += "<span class='yname'>"+name+"</span><br/>";
		html += owner+"<br/>";
		html += "<a class='baloon_lnk' onclick='window.map.getBounds("+ind+");'>Показать маршрут</a><br/>";
		//html += "</div>";
		return html;
	}
	
	this.getOneBaloonHtml = function()
	{
		//var html = "<div class='baloon'>";
		html = "<img src='/int/yachts/img/yachts/"+me.picts[2]+".gif'><br/>";
		html += "<span class='yname'>Eclipse</span><br/>";
		html += "Роман Абрамович<br/>";
		html += "<a class='baloon_lnk' onclick='window.map.getBounds(2);'>Показать маршрут</a><br/>";
		//html += "</div>";
		return html;
	}
	



	/*
	* Удаляет маршруты с карты
	*/
	this.removeRoots = function()
	{	
		me.ib.close(); 				
		if(me.lines.length)
		{
			for(var i=0;i<me.lines.length;i++)
				me.lines[i].setMap(null);	
			me.lines = [];
		}

		if(me.circles.length)
		{			
			for(var i=0;i<me.circles.length;i++)
				me.circles[i].setMap(null);	
			me.circles = [];
		}	
		
		if(me.winds.length)
		{			
			for(var i=0;i<me.winds.length;i++)
				me.winds[i].setMap(null);	
			me.winds = [];
		}
		
		me.mon_border_points = {};
		window.arrows_data = [];
		window.winds_points = [];
	}


	this.Draw = function(roots)
	{
		var zoom = me.map.getZoom();	
		var roots = roots;
	
		for(ind in roots)
		{
			var name = me.yachts[ind].name;
			name = name.replace(' ','&nbsp;');
			var root=roots[ind];			
			var prev = null;
			var steps = 0;	
			for(i in root)
			{					
				var latlng = new google.maps.LatLng(root[i].lat/100000, root[i].lng/100000);
				
				if(prev) // середина отрезка
				{
					var p = new google.maps.LatLng(root[prev].lat/100000, root[prev].lng/100000);
					this.DrawLine(p,latlng,root[i].color,window.formatDate(i));	
					window.arrows_data[window.arrows_data.length]=[p,latlng,root[i].color,window.formatDate(prev)];
				}
				else if(prev==null && me.mon_border_points[ind]) // начало отрезка
				{					
					var steps = me.mon_border_points[ind][3];
					
					var p=me.mon_border_points[ind][0];
					var d=me.mon_border_points[ind][2];					
					this.DrawLine(p,latlng,root[i].color,d);	
					window.arrows_data[window.arrows_data.length]=[p,latlng,root[i].color,d];
				}

				//if(steps%2==0 || steps == 0) 
					this.DrawCircle(latlng,zoom,root[i].color,window.formatDate(i)+'\n'+name);
				
				steps++;
				prev = i;
			}
			
			me.mon_border_points[ind]=[latlng,root[i].color,window.formatDate(i),steps]; // запоминаем данные о точках на границах отрезков
		}
	}


	// Стрелки
	this.getArrowsWings = function()
	{
		window.winds_points = [];
		me.a_overlay = new AOverlay(me.map);
		me.tm=setTimeout(me.drawArrows,100);	
	}


	// Линии
	this.DrawLine = function(p1,p2,color,title)
	{
		me.lines[me.lines.length] = new google.maps.Polyline({
				path: [p1,p2],
				strokeColor: color, 
				strokeOpacity: 1.0,
				strokeWeight: 1,
				title: title,
				pos:p1
		});
		me.lines[me.lines.length-1].setMap(me.map);
	}

	// Toчки 
	this.DrawCircle = function(p,zoom,color,title)
	{		
		if(zoom>15) return;
		if(zoom>12)
			var radius = 3;
		else if(zoom>11)
			var radius = 25;
		else if(zoom>10)
			var radius = 30;
		else if(zoom>8)
			var radius = 100;
		else 
			var radius = 300;
		
		me.circles[me.circles.length] = new google.maps.Circle({center: p,fillColor:color,radius:radius,strokeColor:color,title:title});
		me.circles[me.circles.length-1].setMap(me.map);
		google.maps.event.addListener(me.circles[me.circles.length-1],"mousemove", function(event) {			
			me.ib.setContent(this.title);
			me.ib.setPosition(this.center);
			me.ib.setZIndex(1);			
			me.ib.open(me.map);
			me.tm=setTimeout(me.reduceTip,1);
						
		});
	}	


	// Завершающие точки маршрутов
	this.DrawLastCircles = function(zoom)
	{
		for(ind in me.mon_border_points)
		{				
			var name = me.yachts[ind].name;
			name = name.replace(' ','&nbsp;');
			var p=me.mon_border_points[ind][0];
			var color=me.mon_border_points[ind][1];
			var d=me.mon_border_points[ind][2];		
			this.DrawCircle(p,zoom,color,d+'\n'+name);
		}		
	}


	this.reduceTip = function()
	{
		if($(".baloon"))
		{
			clearTimeout(me.tm);
			$(".baloon").addClass("timetip");
		}
		else 
			me.tm=setTimeout(me.reduceTip,10);
	}


	this.enlargeBaloon = function()
	{
		if($(".baloon"))
		{
			clearTimeout(me.tm);
			$(".baloon").removeClass("timetip");
		}
		else 
			me.tm=setTimeout(me.enlargeBaloon,10);
	}


	this.drawArrows = function()
	{
		if(window.winds_points.length)
		{
			clearTimeout(me.tm);
			for(var i=0;i<window.winds_points.length;i++)
			{
				if(i%4!=0) continue;
				me.winds[me.winds.length] = new google.maps.Polyline({
					path: [window.winds_points[i][1],window.winds_points[i][0]],
					strokeColor: window.winds_points[i][3], 
					strokeOpacity: 1.0,
					strokeWeight: 1,
					title: window.winds_points[i][4],
					pos:window.winds_points[i][0]
				});
				me.winds[me.winds.length-1].setMap(me.map);
				me.winds[me.winds.length] = new google.maps.Polyline({
					path: [window.winds_points[i][2],window.winds_points[i][0]],
					strokeColor: window.winds_points[i][3], 
					strokeOpacity: 1.0,
					strokeWeight: 1,
					title: window.winds_points[i][4],
					pos:window.winds_points[i][0]
				});
				me.winds[me.winds.length-1].setMap(me.map);
			}
			me.a_overlay.setMap(null);
		}
		else 
			me.tm=setTimeout(me.drawArrows ,100);
	}

}


// Слой, необходимый для перевода широты и долготы в пиксельные координаты
function AOverlay(map)
{
	this.setMap(map);

	this.remove = function()
	{
		this.setMap(null);
	}
}

AOverlay.prototype = new google.maps.OverlayView();

AOverlay.prototype.draw = function()
{
	var projection = this.getProjection();
	for(var i=0;i<window.arrows_data.length;i++)
	{
		var s = projection.fromLatLngToDivPixel(window.arrows_data[i][0]);
		var e = projection.fromLatLngToDivPixel(window.arrows_data[i][1]);
		if(s == e) return null;
		var w = (e.x - s.x);
		var h = (e.y - s.y);
		var l = Math.sqrt(w*w+h*h);
		if(l<10) continue;
		var angle = Math.atan(h/w)*180/ Math.PI+90;
		if(w<0) angle +=180;	
		var hd1x = 6*Math.cos((angle-45)*Math.PI/180);
		var hd1y = 6*Math.sin((angle-45)*Math.PI/180);
		var hd2x = 6*Math.cos((angle+45)*Math.PI/180);
		var hd2y = 6*Math.sin((angle+45)*Math.PI/180);
		var ph1=projection.fromDivPixelToLatLng(new google.maps.Point(s.x+10*w/l-hd1x,s.y+10*h/l-hd1y));
		var ph2=projection.fromDivPixelToLatLng(new google.maps.Point(s.x+10*w/l+hd2x,s.y+10*h/l+hd2y));
		var p2=projection.fromDivPixelToLatLng(new google.maps.Point(s.x+10*w/l,s.y+10*h/l));
		window.winds_points[window.winds_points.length] = [p2,ph1,ph2,window.arrows_data[i][2],window.arrows_data[i][3]];
	}
}

AOverlay.prototype.onAdd = function(){}
