var map;

var TrafficUrl = 'makeTraficImg.php';
var TilesUrl = 'getTraficImg.php';

var displayedObjects = {}; 
var selectedCamera = null;
var DTVcopy, DTVBaseLayer, DTVMap, DTVTrafficLayer;
var DTrafLayer,OSMlayer;

var satProj = G_SATELLITE_MAP.getProjection();	
var normalProj = G_NORMAL_MAP.getProjection();


function DTVMapTypeControl() { }
DTVMapTypeControl.prototype = new GControl();

DTVMapTypeControl.prototype.initialize = function(map) {
	var gmt_container = document.createElement("div");
	gmt_container.setAttribute('id','gmt_container');

	var gmt_l = document.createElement("div");
	gmt_l.setAttribute('id','gmt_l');
	
	var gmt_c = document.createElement("div");
	gmt_c.setAttribute('id','gmt_c');
	
	var gmt_r = document.createElement("div");
	gmt_r.setAttribute('id','gmt_r');

	var span1 = document.createElement("span");
	var a1 = document.createElement("a");
	a1.setAttribute('href','info: Тип карты DorogaTV');
	a1.appendChild(document.createTextNode("DorogaTV"));
	
	var span2 = document.createElement("span");
	var a2 = document.createElement("a");
	a2.setAttribute('href','info: Тип карты схема');
	a2.appendChild(document.createTextNode("Карта"));
	
	var span3 = document.createElement("span");
	var a3 = document.createElement("a");
	a3.setAttribute('href','info: Тип карты спутник');
	a3.appendChild(document.createTextNode("Спутник"));	
	
	a1.onclick = function() {
		map.setMapType(DTVNew);
		return false;
	}
	a2.onclick = function() {
		map.setMapType(DTVMap);
		return false;
	}
	a3.onclick = function() {
		map.setMapType(DTVSat);
		return false;
	}
    span1.appendChild(a1);
    span2.appendChild(a2);
    span3.appendChild(a3);
	
	gmt_c.appendChild(span1);
	gmt_c.appendChild(span2);
	gmt_c.appendChild(span3);
	
	gmt_container.appendChild(gmt_l);
	gmt_container.appendChild(gmt_c);
	gmt_container.appendChild(gmt_r);
	
	map.getContainer().appendChild(gmt_container);
	
	return gmt_container;
}

DTVMapTypeControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 10));
}

function clg(text) {
	if(typeof console != 'undefined' && typeof console.log == 'function' ) console.log(text);
}

setCenterCookies = function () {
	setCookie("centerlat", map.getCenter().lat(), "Mon, 01-Jan-2100 00:00:00 GMT", "/");
	setCookie("centerlng", map.getCenter().lng(), "Mon, 01-Jan-2100 00:00:00 GMT", "/");
	setCookie("zoom", map.getZoom(), "Mon, 01-Jan-2100 00:00:00 GMT", "/");
}
setMapHashParams = function() {
	//clg('Изменены координаты');
	setCenterCookies();
	DTVLocation.changeHash('c', map.getCenter().toUrlValue(8) );
	DTVLocation.changeHash('z', map.getZoom());
}
mapTypesToNumber = {
	'DorogaTV': 2,
	'Карта': 1,
	'Спутник': 0
}

function createMapType(mName,layers,minRes,maxRes)
{
	return new GMapType(layers, normalProj, mName, {maxResolution:maxRes, minResolution:minRes, errorMessage:'Error!'}); 
	
}
function addCustomMapType(mName,layers,minRes,maxRes)
{
	var cMap = createMapType(mName,layers,minRes,maxRes);
	map.addMapType(cMap);
	return cMap;
}

function showBBox()
{
	var sqrt = new GPolygon([new GLatLng(maxLat,minLon),new GLatLng(minLat,minLon),new GLatLng(minLat,maxLon),new GLatLng(maxLat,maxLon),new GLatLng(maxLat,minLon)], "#ff0000", 2, .5, 1, 0, {clickable: true});
	map.addOverlay(sqrt);
}

$(document).ready(function(){
	
	if(GBrowserIsCompatible()) {
		map = new GMap2($("#map_container").get(0));
		
		var customUI = map.getDefaultUI();
		customUI.zoom.scrollwheel = true;
		customUI.zoom.doubleclick = true;
		customUI.controls.maptypecontrol = false;
		customUI.controls.smallzoomcontrol3d = false;
		map.setUI(customUI);
		
		map.removeMapType(G_NORMAL_MAP);
		map.removeMapType(G_SATELLITE_MAP);
		map.removeMapType(G_PHYSICAL_MAP);

		DTVcopy = new GCopyrightCollection("DTV");
		DTVcopy.getCopyright = function(a,b) { return { prefix: "DTV(c)", copyrightTexts:["DorogaTV, ИП Дурандин А.В., Google"]}; }

		DTrafLayer = new GTileLayer(DTVcopy);
		DTrafLayer.getOpacity = function() { return 1.0; }
		DTrafLayer.getTileUrl = function (point,zoom) {
			var tilePoint = new GPoint();
			tilePoint.x = Math.floor((point.x+0.5) * 256);
			tilePoint.y = Math.floor((point.y+0.5) * 256);
			latlng = map.getCurrentMapType().getProjection().fromPixelToLatLng(tilePoint, zoom);
			if ((latlng.x < maxLon) && (latlng.x > minLon) && (latlng.y < maxLat) && (latlng.y > minLat)) {
				if ((zoom >= minZoom) && (zoom <= maxZoom)) {
					return siteRoot + TrafficUrl + "?x="+point.x+"&y=" + point.y + "&Level="+zoom+"&pin="+getCookie('dtv_session');
				}
			}
		}

		var GNormalLayer = G_NORMAL_MAP.getTileLayers()[0];
		var GSatLayer = G_SATELLITE_MAP.getTileLayers()[0];
		var GLabelsLayer = G_HYBRID_MAP.getTileLayers()[1];
		var GPhysicalLayer = G_PHYSICAL_MAP.getTileLayers()[0];

		OSMlayer = new GTileLayer(DTVcopy);
		OSMlayer.getOpacity = function() { return 1.0; }
		OSMlayer.getTileUrl = function (point, zoom) {
			return 'http://c.tile.openstreetmap.org/'+zoom+"/"+point.x+"/"+point.y+".png"
		};
		
		DTVlayer = new GTileLayer(DTVcopy);
		DTVlayer.getOpacity = function() { return 1.0; }
		DTVlayer.getTileUrl = function (point, zoom) {
			var tilePoint = new GPoint();
			tilePoint.x = Math.floor((point.x+0.5) * 256);
			tilePoint.y = Math.floor((point.y+0.5) * 256);
			var latlng = map.getCurrentMapType().getProjection().fromPixelToLatLng(tilePoint, zoom);
			
			if ((latlng.x < maxLon) && (latlng.x > minLon) && (latlng.y < maxLat) && (latlng.y > minLat)) {
				if ((zoom >= minZoom) && (zoom <= maxZoom)) {
					if(jamsTrafficType == 2) return siteRoot + TilesUrl + "?x="+point.x+"&y=" + point.y + "&Level="+zoom+"&pin="+getCookie('dtv_session');
					else if(jamsTrafficType == 1) return siteRoot + TrafficUrl + "?x="+point.x+"&y=" + point.y + "&Level="+zoom+"&pin="+getCookie('dtv_session');
				} else {
					return 'http://c.tile.openstreetmap.org/'+zoom+"/"+point.x+"/"+point.y+".png"
				}
			} else {
				return 'http://c.tile.openstreetmap.org/'+zoom+"/"+point.x+"/"+point.y+".png"
			}
		};
		
		//DTVMap = addCustomMapType('Карта', [ GNormalLayer,DTrafLayer ], 1,20);
        if(jamsTrafficType == 2) {
			// Используем DTVLayer
			DTVNew = createMapType('DorogaTV', [ DTVlayer ], 1,17);
		} else { 
			// Используем OSMlayer,DTrafLayer
			DTVNew = createMapType('DorogaTV', [ OSMlayer,DTrafLayer ], 1,18);		
		}
		
		DTVMap = createMapType('Карта', [ GNormalLayer,DTrafLayer ], 1,20);
		DTVSat = createMapType('Спутник', [ GSatLayer,DTrafLayer,GLabelsLayer ], 1,18);
		
    	//var mapControl = new GHierarchicalMapTypeControl();
		
		setCenter();
        GEvent.addListener(map, "zoomend", setMapHashParams );
        GEvent.addListener(map, "dragend", setMapHashParams );
        //GEvent.addListener(map, "move", setMapHashParams);
		
		/*
		GEvent.addListener(map, "maptypechanged", function(ls) {
			DTVLocation.changeHash('map', mapTypesToNumber[map.getCurrentMapType().getName(true)] );
		});
		*/
		
		/*
		//map.setMapType(DTVNew);
		mapType = DTVLocation.getValue('map'); 
		var varMapType;
		if(mapType !== null ) {
			varMapType = mapType;
		} else {
			varMapType = serviceMap;
		}
        */
		switch(serviceMap) {
			case 1:
				if(jamsTrafficType > 1 ) map.setMapType(DTVNew);
				else map.setMapType(DTVMap);
			break;

			case 0:
				map.setMapType(DTVSat);
			break;
			
			case 1:
				map.setMapType(DTVMap);
			break;
		}
		
		map.addControl(new DTVMapTypeControl());
		map.removeControl(new GMapTypeControl());
		
    	/*
    	mapControl.clearRelationships();
	    mapControl.addRelationship(GSatLayer, DTrafLayer, "Пробки", false);
	    mapControl.addRelationship(GSatLayer, GLabelsLayer, "Подписи", false);
	    mapControl.addRelationship(OSMlayer, DTrafLayer, "Пробки", true);
	    map.addControl(mapControl);
	    */
	    
	}
});

function RefreshJams()
{
	return false;
	
	if (totalUpdateTime >= 20)
	{
		return;
	}

	if(GBrowserIsCompatible())
	{ 
		if(typeof DTVlayer != 'undefined' ) {
			delete DTVlayer;
		}
		
		DTVBaseLayer = new GTileLayer(DTVcopy, 11, 16);
		DTVBaseLayer.getTileUrl = DTVTrafficTileUrl;
		DTVBaseLayer.getOpacity = function() {return 1.0; };    

		if(typeof trafficLayer != 'undefined' )
		{
			map.removeOverlay(DTVTrafficLayer);
			delete trafficLayer;
		}
		
		DTVTrafficLayer = new GTileLayerOverlay(DTVlayer);
		map.addOverlay(DTVTrafficLayer);
	}

	setTimeout("RefreshJams();", RefreshRateJams*1000);  
}
