var routeId = 0;
var refreshRateBuses = 30; // sec

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

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

var routeId;
var stopIcon;
var routesOverlay = new Array();

function route_clicked(event) {
    var id = $(this).attr('id');
    var arr = id.split('_',2);
    if(arr.length == 2) {
        displayRoute(arr[1]);
    }
}

function update_routes(data) {
    var list = $('#routes_list');
    $(list).empty();
    $(list).hide();
    for(var i in data) {
        var rt = data[i];
        if (!rt.name) continue;
        var li = document.createElement('li');
        $(li).attr('id', 'route_'+rt.id);
        $(li).addClass('clickhover');
        $(li).html(rt.name);
        $(li).bind('click', route_clicked);
        var busCount = parseInt(rt.n);
        if (busCount >= 1) {
            $(li).addClass('gps_bus');
            $(li).attr('title','Транспортных средств: '+busCount);
        }
        $(list).append(li);
    }
    $(list).fadeIn( 500 );
    $('#routes').click();
    var route = DTVLocation.getValue('route');
    if(route > 0) $("#route_"+route).trigger("click");//displayRoute(route);
    
}

function delayed_route_filter(delay) {
    if(delayed_route_filter.timer_id) {
        window.clearTimeout(delayed_route_filter.timer_id);
        delete delayed_route_filter.timer_id;
    }
    delayed_route_filter.timer_id = window.setTimeout(function() {
        var filter = $('#route_filter').val();
        $('#routes_list').stop(true, true);
        //$('#routes_list').find('li:contains("'+filter+'")').show().parent().find('li').not(':contains("'+filter+'")').slideUp(200);

        var query = filter.toLowerCase();
        $('#routes_list').find("li").each(function() {
          var item = $(this);
          if (item.text().toLowerCase().indexOf(query) >= 0) item.show();
          else item.hide();
        });

        $("#routes[class!=active]").trigger('click');
    }, delay);
}

$(document).ready(function() {

    stopIcon = createStopIcon(); 

    $('#route_filter').bind('click', function(e) {
        e.stopPropagation();
        if($(this).val().indexOf('поиск') > -1) $(this).val('');
    }).bind('mouseenter', function() {
        if($(this).val().indexOf('поиск') > -1) $(this).val('');
        $(this).focus();
    }).bind('onvalidate', function() {
        if($(this).val()=='') $(this).val('поиск');
    }).bind('keyup', function(event) {
        delayed_route_filter(300); // ms
	});

	$.ajax({
        url:backend + "backend/transport_executeSmallList.php?jsoncallback=?",
        dataType: 'json',
        success: update_routes,
        complete: function() {
            var apikey = 'hr1UbNqaBzKlbGKoT4P0';
            if(typeof AdGeo != 'undefined') adgeo_obj = new AdGeo(map,apikey,14,17);
        }
    });

});

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

        var data = eval(response);
        var i;
        for(i in data) {
            if(data[i].Longtitude) {
                var icon = new GIcon(G_DEFAULT_ICON);
                icon.image = "http://www.doroga.tv/img/dirs/r0.gif";

                if(data[i].AverageSpeed5min>10) {
                    icon.image = "g";
                } else if (data[i].AverageSpeed5min>0) {
                    icon.image = "y";
                } else {
                    icon.image = "r";
                }

                icon.image += (Math.round((data[i].Bearing)/45)*45)%360;

                icon.image = "http://www.doroga.tv/img/dirs/" + icon.image;
                icon.image += ".gif";
                icon.shadow = "";
                icon.iconSize = new GSize(24, 24);
                icon.iconAnchor = new GPoint(12, 12);
                var bus_pos = new GLatLng(parseFloat(data[i].Latitude), parseFloat(data[i].Longtitude));
                var marker_opts = {
                    title: data[i].ObjectName + " [" + data[i].LastUpdated + "]",
                    icon: icon,
                    zIndexProcess: function(){return 200;}
                };
                marker = new GMarker(bus_pos, marker_opts);
                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, res;
	if(time >= 60)
	{
		var min = parseInt(time/60);
		var sec = Math.ceil(time%60);

		if(min < 10) {
			min_o = "0"+min.toString();
		} else {
			min_o = min.toString();
		}

		if(sec < 10) {
			sec_o = "0"+sec.toString();
		} else {
			sec_o = sec.toString();
		}
		res = min_o+" м "+sec_o+" с";
	} else {
		if(time < 10) {
			sec_o = "0"+Math.ceil(time).toString();
		} else {
			sec_o = Math.ceil(time).toString();
		}
		res = "~ " + sec_o + " с";
	}
	return res;
}
function getBusArrivals(obj, nextobj, marker, reopen) {
	var name = obj.Name;
	if(typeof nextobj != 'undefined') var nextname = "<br /><small>в сторону ост. " + nextobj.Name + "</small>";
	else var nextname = "";
	$.ajax({
		url: backend + 'backend/transport_busArrivals.php?jsoncallback=?',
		data: { use_jams: region.arrival_with_jams, station_id: marker.Id },
		dataType: 'json',
		cache: false,
		success: function(resp) {
            var T=0;
			var t1 = 0; // lower index bound
			var t2 = resp.length-1; // upper index bound
            for(var ind=0; ind<resp.length; ind++) {
                T = parseFloat(resp[ind].T);
                if(T <= 0) {
					t1 = ind+1;
					continue;
				}
				if(T >= 3600) {
                    t2 = ind;
                    break;
                }
            }

            var count = t2 - t1;

            var timetable_container = document.createElement('div');
            timetable_container.setAttribute('id', 'timetable_container');
            timetable_container.setAttribute('width','100%');

            var header = document.createElement('h4');
            header.setAttribute('style', 'margin: 0px; padding: 0px;');
            header.innerHTML = name;
            timetable_container.appendChild(header);

            var subheader = document.createElement('p');
            subheader.innerHTML = nextname.substr(13, nextname.length - 21); // trim damn html markup
            timetable_container.appendChild(subheader);
			
			var ul;
			var li;
            if (count == 0) {
				ul = document.createElement('ul');
				ul.setAttribute('class', 'timetable');
				li = document.createElement('li');
				li.innerHTML = 'Нет данных для прогноза';
				ul.appendChild(li);
				timetable_container.appendChild(ul);
			} else {
				var bus;
				var a;
				var span;
				var columns;
				if (count>=24) {
					columns = 3;
				} else if (count>9 && count<24) {
					columns = 2;
				} else {
					columns = 1;
				}
				var rowspercol = (count - count%columns) / columns;
				var col=0;
				for(col; col<columns; col++) {
					ul = document.createElement('ul');
					ul.setAttribute('class', 'timetable');
					for(ind=t1+col*rowspercol; ind<(col+1)*rowspercol && ind<t2; ind++) {
						bus = resp[ind];
						li = document.createElement('li');
						a = document.createElement('a');
						a.setAttribute('class', 'route_link');
						a.setAttribute('title', 'Посмотреть маршрут');
						a.setAttribute('onclick', 'displayRoute('+bus.RouteId+',1);return false;');
						a.setAttribute('href', '#');
						a.innerHTML = bus.TrackName;
						li.appendChild(a);
						span = document.createElement('span');
						span.setAttribute('class', 'bus_time');
						span.innerHTML = getHumanReadableTime(bus.T);
						li.appendChild(span);
						ul.appendChild(li);
					}
					timetable_container.appendChild(ul);
				}
            } 
            a = document.createElement('a');
			a.setAttribute('class', 'refresh_link');
            a.onclick = function() {
                $(map.getInfoWindow().getContentContainers()).html(createDivRefresh());
                getBusArrivals(obj,nextobj,marker,false);
                return false;
            };
            a.setAttribute('href','#');
            a.innerHTML = 'обновить прогноз';
            timetable_container.appendChild(a);

            marker.openInfoWindowHtml(timetable_container);

            delete timetable_container, a, span, li, ul, bus, ind, count;

			return true;
		}
	});
}

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

createMarkerBusstop = function(obj, nextobj) {
    var lat = parseFloat(obj.Latitude);
    var lon = parseFloat(obj.Longtitude);
    var marker_opts = {
        title: obj.Name,
        icon: stopIcon,
        zIndexProcess: function() {return 100;}
    };
    var marker = new GMarker(new GLatLng(lat, lon), marker_opts);
    marker.Id = obj.Id;
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(createDivRefresh());
        getBusArrivals(obj, nextobj, marker, true);
    });
    return marker;
}

function displayRoute(routeID,trigger) {
    routeId = routeID; // store selected route in global variable, needed for tiles
	if(trigger == 1) $('#route_'+routeID).trigger('click');
    
    if(GBrowserIsCompatible()) {
		var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, "Doroga.TV");
		var copyrightCollection = new GCopyrightCollection('2008');
		copyrightCollection.addCopyright(copyright);
		var tilelayer = new GTileLayer(copyrightCollection, 11, 16);
		tilelayer.getTileUrl = TransportGetTileUrl;
		tilelayer.getOpacity = function() { return 1.0; };
		var tileOverlay = new GTileLayerOverlay(tilelayer);
		map.addOverlay(tileOverlay);

               
        /*var camIcon = new GIcon(G_DEFAULT_ICON);
		//camIcon.image = "http://www.doroga.tv/images/jams_icon_single_blue_circle_trans.gif";
        camIcon.image = "/img/point.gif";
		camIcon.shadow = "";
		camIcon.iconSize = new GSize(22, 21);
		camIcon.iconAnchor = new GPoint(10, 20);*/


		$.ajax({
            url: backend + 'backend/transport_executeStations2.php?jsoncallback=?',
            data: {routeId: routeID},
            dataType: 'json',
            success: function(data) {
                var newStationMarkers = new Array();
    
                var ind;
                for(ind=0; ind<data.length; ind++) {
                    if(data[ind].Longtitude) {
                        marker = createMarkerBusstop(data[ind], data[ind+1]);

                        newStationMarkers[newStationMarkers.length] = marker;
                        delete marker;
                    }
                }
                var i;
                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(backend + 'backend/transport_executeCenter.php?jsoncallback=?', {routeId: routeID}, function(response) {
            var sw = new GLatLng(parseFloat(response[0].MnLatitude),parseFloat(response[0].MnLongtitude));
            var ne = new GLatLng(parseFloat(response[0].MxLatitude),parseFloat(response[0].MxLongtitude));
			var bounds = new GLatLngBounds(sw, ne);
			map.setZoom( map.getBoundsZoomLevel(bounds) );
			map.panTo( bounds.getCenter() );
		});
        DTVLocation.changeHash('route',routeID);
	}

    var i;
	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) {
    var url = backend + "makeTraficImgRoute.php?x="+point.x+"&y="+point.y+"&Level="+zoom+"&RouteID="+routeId+"&pin="+pin;
	return url;
}