var routeId = 0;
var busCount = 0;
var refreshRateBuses = 30;

var tileOverlay;
var tileLayer;
var copyright;
var copyrightCollection;
var marker;
var camIcon;
var data;
var list;
var i;
var canAuto = true;
var uaVers;
var h;

var url;

var busMarkers = new Array();
var stationMarkers = new Array();

var timeouts = new Array();
var timeoutsState = new Array();

$(document).ready(function()
{
	$("#sm_trans").addClass('highlit');
	$('#tran_input_field').bind('keyup', function() {
		list = "";

		$.getJSON(siteRoot + 'backend/transport_executeSmallList.php?jsoncallback=?', {routeFilter: $('#tran_input_container input')[0].value},
		function(response) {
			data = eval(response);
			for(i in data)
			{
				if (data[i].name)
				{      
					list += " <a style='cursor:pointer; cursor:hand;' onclick='displayRoute("+data[i].id+")'>";
					busCount = parseInt(data[i].n);
					if (!busCount) busCount = 0;
					if (busCount > 1)
					{
						list += " <img src='http://www.doroga.tv/images/bus_green.gif' alt='" + busCount + "'>";
					}
					else
					{
						list += " <img src='http://www.doroga.tv/images/bus_no.gif' alt='" + busCount + "'>";
					}
					list += data[i].name + "</a><br>";
				}
			}
			$('#search_results').html(list);
		});
	});

	$.getJSON(siteRoot + "backend/transport_executeSmallList.php?jsoncallback=?", {}, function(response){
		data = eval(response);
		list = "";
		for(i in data)
		{
			if (data[i].name)
			{
				list += " <a style='cursor:pointer; cursor:hand;' onclick='displayRoute("+data[i].id+")'>";
				busCount = parseInt(data[i].n);
				if (!busCount) busCount = 0;
				if (busCount > 1)      
				{
					list += " <img src='http://www.doroga.tv/images/bus_green.gif' alt='" + busCount + "'>";
				}
				else
				{
					list += " <img src='http://www.doroga.tv/images/bus_no.gif' alt='" + busCount + "'>";
				}
				list += data[i].name + "</a><br>";
			}
		}
		$('#search_results').html(list);
	});
	
	uaVers='' // uaVers может не определиться в Опере, так что, переменную приходится инициализировать, чтобы не было ошибок
	if (window.navigator.userAgent.indexOf ("MSIE") >= 0)
	{
		ua = 'Explorer';
		uaVers=window.navigator.userAgent.substr(window.navigator.userAgent.indexOf("MSIE")+5,3);
		if (uaVers.indexOf("7") == -1)
		{
			canAuto = false;
		}
	}  
  
	if (canAuto)
	{
		h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
		$("#map_container").height(h - 170);
		$("#search_results").height(h - 380);

		$(window).resize(function(){
			h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
			$("#map_container").height(h - 170);
			$("#search_results").height(h - 380);
		});
	}
});

function updateBuses(routeID)
{
  routeId = routeID;
  
  $.getJSON(siteRoot + 'backend/transport_executeBuses.php?jsoncallback=?', {routeId: routeID}, function(response)
  {
    var newBusMarkers = new Array();  
    
    data = eval(response);
    for(i in data)
    {
      if(data[i].Longtitude)
      {
        var camIcon = new GIcon(G_DEFAULT_ICON);
        camIcon.image = "http://www.doroga.tv/images/dirs/r0.gif";
        
        if(data[i].AverageSpeed5min>10)
          camIcon.image = "g";
        else if (data[i].AverageSpeed5min>0)
          camIcon.image = "y";
        else
          camIcon.image = "r";
          
        camIcon.image += (Math.round((data[i].Bearing)/45)*45)%360;
        
        camIcon.image = "http://www.doroga.tv/images/dirs/" + camIcon.image;
        camIcon.image += ".gif";        
        camIcon.shadow = "";
        camIcon.iconSize = new GSize(24, 24);
        camIcon.iconAnchor = new GPoint(12, 12);
        marker = new GMarker(new GLatLng(parseFloat(data[i].Latitude), parseFloat(data[i].Longtitude)), {title: data[i].ObjectName + " [" + data[i].LastUpdated + "]", icon: camIcon});
        //marker.CameraId = data[i].CameraId;
        newBusMarkers[newBusMarkers.length] = marker;
        delete marker;
      }
    }
    
    for(i=0; i<busMarkers.length; i++)
    {
      map.removeOverlay(busMarkers[i]);
    }    
    
    busMarkers.length = 0;
    for(i=0; i<newBusMarkers.length; i++)
    {
      busMarkers[busMarkers.length] = newBusMarkers[i];
      map.addOverlay(busMarkers[i]);
    }
    
    delete newBusMarkers;
  });  
}
function getHumanReadableTime(time)
{
	//time += 10;
	var min_o, sec_o;
	if(time >= 60)
	{
		var min = Math.ceil(time/60);
		var sec = time%60;

		if(min < 10) {
			min_o = "0"+Math.floor(min).toString();
		} else {
			min_o = Math.floor(min).toString();
		}
		
		if(sec < 10) {
			sec_o = "0"+Math.floor(sec).toString();
		} else {
			sec_o = Math.floor(sec).toString();
		}
		var res = Math.floor(min)+" м "+Math.floor(sec)+" с"; 
	} else {
		if(time < 10) {
			sec_o = "0"+Math.floor(time).toString();
		} else {
			sec_o = Math.floor(time).toString();
		}
		var res = Math.floor(time) + " с";
	}
	return res;
}
getBusArrivals = function (obj, nextobj, marker, reopen)
{

	var name = obj.Name;
	if(typeof nextobj != 'undefined') var nextname = "<br /><small>в сторону ост. " + nextobj.Name + "</small>";
	else var nextname = "";
	$.ajax({
		url: siteRoot + 'backend/transport_busArrivals.php?jsoncallback=?',
		data: 'station_id='+marker.Id,
		dataType: 'json',
		cache: false,
		success: function(resp) {
			genPredictionHtml = function () {
				var html;
				
				for(ind in resp){
					if(resp[ind].T < 1 && resp[ind].T >= 3600) delete resp[ind];
				}
				var count = resp.length;
				if(count%2 != 0) count--;
				if(count <= 30 ) var limit = count;
				else limit = 30;
				
				if(count >=24) limit_col = 3
				else if(count > 9 && count < 24) limit_col = 2
				else if(count <=9 ) limit_col = 1;

				var k=0;
				var item;
				var legend = '<tr><td colspan="2"><small>Время до прибытия транспорта</small></td></tr>';
				var main_tbl = document.createElement('table');
				main_tbl.id = 'main_tbl';
				main_tbl.width = '100%';
  				html = '<tr><td colspan="2"><b>'+name+'</b>'+nextname+'</td></tr>';
				
				if(resp.length > 0) main_tbl.innerHTML += legend;
				html +='<tr><td valign="top"><table>';

				for(ind=0;ind<count;ind++)
				{
					item = resp[ind];
					if(item.T > 0)
					{
						html += '<tr><td><a style="font-weight: bold;" title="Посмотреть маршрут" onclick="displayRoute('+item.RouteId+');return false;" href="#">' + item.TrackName + '</a></td><td>' + getHumanReadableTime(item.T) + '</td></tr>';
						k++;
						
						if( limit_col>2 && k==Math.floor(limit/limit_col) || k==Math.floor(limit/limit_col)+Math.floor(limit/limit_col) || (limit_col ==2 && (k==Math.floor(limit/limit_col) )) ) html += '</table></td><td valign="top"><table>'
					}

					if(k == limit) break;
				}
				if(k==0) html += 'Нет данных для прогноза';
	            html += '</table></td></tr></table>';
	            
	            main_tbl.innerHTML = html;
				var tr = document.createElement('tr');
				var a = document.createElement('a');
				
				a.onclick = function() {
					$(map.getInfoWindow().getContentContainers()).html(createDivRefresh());
					getBusArrivals(obj,nextobj,marker,false);
					return false;
				};
				a.href='#';
				a.innerHTML = 'обновить прогноз';
				a.style.color = '#0099CC';
				a.style.textDecoration = 'underline';
				tr.appendChild(a);
				main_tbl.appendChild(tr);

	            marker.openInfoWindowHtml(main_tbl);
	            
				displayRouteBaloon = function () {
					displayRoute(item.RouteId,marker.Id);
					//genPredictionHtml(obj, nextobj, marker, false);
					//getBusArrivals(obj, nextobj, marker, true);
					//marker.openInfoWindow();
				}

    			delete div,html,k,item,resp,legend,limit,count;
			}
			
			genPredictionHtml();

			return true;
		}
	});
}
createDivRefresh = function() {
	var div = document.createElement('div');
	div.setAttribute('id','stopinfo');
	div.appendChild(document.createTextNode('Обновление информации ...'));
	return div;
}
createMarker = function (obj,nextobj) {

	var marker = new GMarker(new GLatLng(parseFloat(obj.Latitude), parseFloat(obj.Longtitude)), {title: obj.Name, icon:camIcon});
	marker.Id = obj.Id;

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(createDivRefresh());
		getBusArrivals(obj,nextobj,marker,true);
	});
	return marker;
}
function displayRoute(routeID)
{
	routeId = routeID;

	if(GBrowserIsCompatible())
	{
		//map.clearOverlays();
		copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, "Doroga.TV");
		copyrightCollection = new GCopyrightCollection('2008');
		copyrightCollection.addCopyright(copyright);
		tilelayer = new GTileLayer(copyrightCollection, 11, 16);
		tilelayer.getTileUrl = TransportGetTileUrl;
		tilelayer.getOpacity = function() {return 1.0; };
		tileOverlay = new GTileLayerOverlay(tilelayer);
		map.addOverlay(tileOverlay);
		camIcon = new GIcon(G_DEFAULT_ICON);
		camIcon.image = "http://www.doroga.tv/images/jams_icon_single_blue_circle_trans.gif";
		camIcon.shadow = "";
		camIcon.iconSize = new GSize(13, 13);
		camIcon.iconAnchor = new GPoint(7, 7);

		$.getJSON(siteRoot + 'backend/transport_executeStations2.php?jsoncallback=?', {routeId: routeID}, function(response)
		{
			var newStationMarkers = new Array();

			data = eval(response);
			for(ind=0;ind<data.length;ind++)
			{
				if(data[ind].Longtitude)
				{
					marker = createMarker(data[ind],data[ind+1]);

					newStationMarkers[newStationMarkers.length] = marker;
					delete marker;
				}
			}

			for(i=0; i<stationMarkers.length; i++)
			{
				map.removeOverlay(stationMarkers[i]);
			}    

			stationMarkers.length = 0;
			for(i=0; i<newStationMarkers.length; i++)
			{
				stationMarkers[stationMarkers.length] = newStationMarkers[i];
				map.addOverlay(stationMarkers[i]);
			}

			delete newStationMarkers;
		});

		$.getJSON(siteRoot + 'backend/transport_executeCenter.php?jsoncallback=?', {routeId: routeID}, function(response)
		{
			var bounds = new GLatLngBounds(new GLatLng(parseFloat(response[0].MnLatitude),parseFloat(response[0].MnLongtitude)), new GLatLng(parseFloat(response[0].MxLatitude),parseFloat(response[0].MxLongtitude)) );
			map.setZoom( map.getBoundsZoomLevel(bounds) );
			map.panTo(new GLatLng(parseFloat(response[0].CLatitude), parseFloat(response[0].CLongtitude)));
		});    
	}

	for(i=0;i<timeouts.length;i++)
	{
		clearTimeout(timeouts[i]);
		timeoutsState[i] = -1;
	}

	updateBuses(routeId);
	timeouts[timeouts.length] = setTimeout("Refresh()", refreshRateBuses*1000);
	timeoutsState[timeoutsState.length] = routeId;
}

function Refresh()
{
	updateBuses(routeId);

	for(i=0;i<timeouts.length;i++)
	{
		if (timeoutsState[i] != routeId) {
			timeoutsState[i] = -1;
			clearTimeout(timeouts[i]);
		} else {
			timeouts[i] = setTimeout("Refresh()", refreshRateBuses*1000);
		}
	}  
}

function TransportGetTileUrl(point, zoom)
{
	return siteRoot + "makeTraficImgRoute.php?x="+point.x+"&y=" + point.y + "&Level="+zoom+"&RouteID="+routeId+"&pin="+getCookie('dtv_session');
}

function wait()
{
	setTimeout("doNothing();", 1000);
}

function doNothing()
{
	a = 1;
}
