var gallery_view = "../gallery/displayimage.php?pid=";
var album_view = "../gallery/thumbnails.php?album=";
var gallery_dir = "../gallery/albums/";
var pic_zoom = Gzoom;

function icon_dir(color){
	return 'images/marker_' + color + '.png';
}

function set_coord_cookie(){
	var coord_div=document.getElementById("drag_coordinates");
	if (coord_div){
		var marker_coord = coord_div.value;
		var marker_direction = document.getElementById("user4").value;
		setCookie ("coordinates",marker_coord);
		for (i=0;i<directions.length;i++){
			if (marker_direction==directions[i])
				setCookie ("direction",i);
		}
	}
}

var directions=["Не определено","сверху","с севера","с северо-востока","с востока","с юго-востока","с юга","с юго-запада","с запада","с северо-запада"]

function update_coordinates(){
	set_coord_cookie();
	$.post("../update_coordinates.php?pid=" + drag + '&' + add_hash(),function (data){
		var url = current_url();
		window.location.replace(url)																		
	})
}

function point_to_pixels(map,point){
	var prj = map.getCurrentMapType().getProjection();
	var pixels = prj.fromLatLngToPixel(point,pic_zoom);
	var center = prj.fromLatLngToPixel(Gcenter,pic_zoom);
	var dx = pixels.x - center.x + Math.floor(gwidth/2)
	var dy = center.y - pixels.y + Math.floor(gheight/2)
	return dx + ',' + dy
}

var sw_pic_coord;
var ne_pic_coord;
var pic_url;
var overlay;
var gmap;
var markerD; // required in infowindows

function add_draggable_marker(map,point,color,id){
	var icon = new GIcon();
	icon.image = icon_dir(color);
	icon.iconSize = new GSize(24, 40);		
	icon.iconAnchor = new GPoint(12, 52);
	markerD = new GMarker(point, {icon:icon, draggable: true}); 
	map.addOverlay(markerD);
	markerD.enableDragging();
	gmap = map;
	GEvent.addListener(markerD, "drag", function(){
		 var point = this.getPoint();
	//	 GLog.write( "Marker coords x="+point.lat() + " y="+point.lng())
		if (get(id).className == 'inpixels'){
				$("#" + id).val(point_to_pixels(gmap,point))
			}
		else {
			if (id != 'drag_coordinates'){ // for link picture only
	//			var px = point_to_pixels(map,markerD.getPoint())
	//			var px = point_to_pixels(map,new GLatLng(markerD.getPoint().lat(),markerD.getPoint().lng()))
				if (id=='drag_1')
					sw_pic_coord = point
				if (id=='drag_2')
					ne_pic_coord = point	
				var boundaries = new GLatLngBounds(sw_pic_coord,ne_pic_coord);
				if (overlay)
					map.removeOverlay(overlay)
				overlay = new GGroundOverlay(pic_url, boundaries);
				map.addOverlay(overlay);
				var overlays_div = map.getPane(G_MAP_OVERLAY_LAYER_PANE) 
				$(overlays_div).css({'opacity':0.5})
			}
			$("#" + id).val(point.toUrlValue())
		}
	});
}

var drag_started = false;

function manage_drag(side,pid){
//	link_picture(side,pid);
//	return

	if (!pid || drag_started)
		return
	drag_started = true;
	var url='read_picture.php?pid=' + pid + '&' + add_hash();
	$.get(url,function(result,status,xmlhttp){	   
		var pic = read_picture(xmlhttp);
		var coord = pic.coordinates;
		if (coord=="")
			coord="55.750957,37.617585"
		deleteCookie("coordinates");
		deleteCookie("direction");	
		Gcenter = latlng_from_text(coord);
		var map = eval(side+"_map");
		map.setCenter(Gcenter, Gzoom);		
		add_draggable_marker(map,Gcenter,'green','drag_coordinates') 
		hide_lines();
		drag_started = false;	
		if (drag_infodiv)
			return	
		var pic_file = 'normal_' + pic.file_name;
		var pwidth = pic.pwidth;
		var pheight = pic.pheight;
		if (pwidth<=540 && pheight<=540)
			pic_file = pic.file_name;
		if (pwidth>pheight){
			nwidth=300;
			nheight=300*(pheight/pwidth);
		}
		else {
			nheight=300;
			nwidth=300*(pwidth/pheight);
		}	
		var hash = huffman(' ' + pic.pid);
		var js = 'window.open(&quot;' + gallery_view + pic.pid + '&fullsize=' + hash + '&quot;,&quot;&quot;,&quot;width=' + pwidth + ', height=' + pheight + '&quot;)'
		var title1 = pic.title.replace(/\"/g,"'")
		var html1 = '<table><tr style="background-color:#f2f1ec"><td colspan=2><b>' + get_album_title(pic.aid) + '</b></td>' +
			'<td><img src="../gallery/images/icons/search.png" onmouseover="pic_infowin(&quot;' + pic.date + '&nbsp;'+ pic.title + '&quot;,&quot;' + pic.file_path + pic_file + '&quot;,' + pwidth + ',' + pheight + ')" onmouseout="close_infowin3()"/></td></tr>' + 
			'<tr><td colspan=3 width=' + 315 + ' height=' + 315 + ' bgcolor=#eeeeee align=center valign=middle>' +
			'<a><img src="' + gallery_dir + pic.file_path + pic_file +
			'" border=0 width="' + nwidth + '" height="' + nheight + ' alt="Документ загружается..." title="Посмотреть полноразмерное изображение" onclick="' + js + '"/></a></td></tr>' +
			'<tr><td colspan=3>Переместите зеленый маркер в точку съемки изображения</td></tr></table>' +
			'<form  action="#" onsubmit="update_coordinates(); return false;"><table><tr><td align=left>Координаты маркера: </td><td align=right><input type="text" style="width: 135px" id="drag_coordinates" value="' + pic.coordinates + '" maxlength=20 /></td></tr>' +
			'<tr><td align=left>Направление съемки: </td><td align=right><select id="user4">';
			for (i=0;i<directions.length;i++){
				html1 += '<option value="' + directions[i] + '" ';
				if (pic.direction==directions[i])
					html1 += 'selected="selected"'
				html1 += '>' + directions[i] + '</option>'
			}
			html1 += '</select></td></tr><tr><td align=left><a class="f" href="' + gallery_view + pic.pid + '"><b>Это изображение в галерее</b></a></td><td colspan=2 align=right><input type="submit" value="Сохранить" /></td></tr></table></form>';	
		var direction = "";
		if ((pic.direction != "Не определено") && (pic.direction!="")){
			direction = ' (вид ' + pic.direction + ')';
		}
		drag_infodiv = infowin(60+"%",75,350,pic.date + ' ' + pic.title + direction, html1);	
})
}

function link_picture(side,pid){
	var url='read_picture.php?pid='+pid;
	$.get(url,function(result,status,xmlhttp){
		var coord1 = getCookie ("coord1");
		var coord2 = getCookie ("coord2");
		var pixel1 = getCookie ("pixel1");
		var pixel2 = getCookie ("pixel2");			
		
		function show_overlay(){
			if (!coord1)
				return
		//	var bounds = maps[0].getBounds(); // map bounds
		//	var southWest = bounds.getSouthWest();
		//	var northEast = bounds.getNorthEast();	
			var boundaries = new GLatLngBounds(latlng_from_text(coord1),latlng_from_text(coord2));
			var path = pic.file_path;
			var file = pic.file_name;
			var prefix = set_prefix(file);
			var overlay = new GGroundOverlay(gallery_dir + path + prefix + file, boundaries);
			map.addOverlay(overlay);
			var overlays_div = map.getPane(G_MAP_OVERLAY_LAYER_PANE) 
			$(overlays_div).css({'opacity':0.5})
		}						   
		var pic = read_picture(xmlhttp);
		var coord = pic.coordinates;
		if (coord=="")
			coord="55.750957,37.617585"
		Gcenter = latlng_from_text(coord);
		var map = eval(side+"_map");
		map.setCenter(Gcenter, Gzoom);		
		add_draggable_marker(map,(coord1)?latlng_from_text(coord1):Gcenter,'red','drag_1')
		add_draggable_marker(map,(coord2)?latlng_from_text(coord2):Gcenter,'green','drag_2')
		hide_lines();
	//	show_overlay();
		show_picture(side,pid)
})
}

var gwidth;
var gheight;

function set_picture_cookie(){
	var coord_div1 = document.getElementById("drag_1");
	var coord_div2 = document.getElementById("drag_2");
	var pixel_div1 = document.getElementById("pic_1");
	var pixel_div2 = document.getElementById("pic_2");

	var coord1 = coord_div1.value; // markers latlng coordinates
	var coord2 = coord_div2.value;
	var pixel1 = pixel_div1.value;	// markers pixel coordinates
	var pixel2 = pixel_div2.value;
	setCookie ("coord1",coord1);
	setCookie ("coord2",coord2);
	setCookie ("pixel1",pixel1);
	setCookie ("pixel2",pixel2);
}

function reload_submitted(){
	var url=current_url();
	set_picture_cookie();
	window.location.replace(url)
}

function show_picture(side,pid){
	var url='read_picture.php?pid='+pid;
	$.get(url,function(result,status,xmlhttp){
		var pic = read_picture(xmlhttp);
		var w=win_num;
		var w_top=null
		var w_left=null
		if (getBodyScrollTop()>0)
			w_top=getBodyScrollTop()+70+'px';
		idm=infowin(600,w_top,540,'<a class="f1">'+ pic.title + '</a>','',2,540);
		var inner=get('info_inner'+w)
		$(inner).css({'padding-bottom':0,'height':500,'overflow':'hidden'})
		var caption = document.createElement('div');
		inner.appendChild(caption);
		
		var html = '<form  action="#" onsubmit="reload_submitted();return false;"><table><tr><td><img src="' + icon_dir("red") + '" height=16></td><td><input class="inpixels" type="text" style="width: 60px" id="pic_1" value="qq" maxlength=12/></td><td><input type="text" style="width:120px" id="drag_1" value="' + pic.coordinates + '" maxlength=19/></td><td align=right width=24><img src="' + icon_dir("green") + '" height=16></td><td><input class="inpixels" type="text" style="width:60px"  id="pic_2" value="pp" maxlength=12/></td><td><input type="text" style="width:120px" id="drag_2" value="' + pic.coordinates + '" maxlength=19 /></td><td align=right><input type="submit" value="Сохранить" /></td></tr></table>';
		$(caption).css({'height':26,'background-color':'#fff','padding-right':20,'margin-bottom':4, 'text-align':'center'}).html(html);
		
		var map_div = document.createElement('div');
		map_div.id 			= 'map' + w;
		inner.appendChild(map_div);
		$(map_div).css({'height':470,'border':'1px solid gray'});		
		map = new_map(map_div,'0020090',1);
		map.addControl(new GSmallZoomControl3D());
		
		delete_terms(map);
		
		var pwidth = gwidth = pic.pwidth;
		var pheight = gheight = pic.pheight;
	//	alert("pwidth="+pwidth+" pheight="+pheight)
		var path = pic.file_path;
		var file = pic.file_name;
		var prefix = set_prefix(file);
	//	$("img").load(function(){
	//		if (this.width == 256)
	//			this.style.display='none'
	//	});		
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var prj = map.getCurrentMapType().getProjection();
			
		var sw = prj.fromLatLngToPixel(southWest,pic_zoom);
		var ne = prj.fromLatLngToPixel(northEast,pic_zoom);
		var swd = map.fromLatLngToDivPixel(southWest);
		var ned = map.fromLatLngToDivPixel(northEast);
		sw.x -= Math.floor((pwidth-ned.x)/2);
		sw.y += Math.floor((pheight-swd.y)/2);
		ne.x = sw.x + pwidth;
		ne.y = sw.y - pheight;
		new_sw = prj.fromPixelToLatLng(new GPoint(sw.x,sw.y),pic_zoom);
		new_ne = prj.fromPixelToLatLng(new GPoint(ne.x,ne.y),pic_zoom);
		add_draggable_marker(map,new_sw,'red','pic_1') 
		add_draggable_marker(map,new_ne,'green','pic_2')
		$("#pic_1").val(point_to_pixels(map,new_sw))
		$("#pic_2").val(point_to_pixels(map,new_ne))
		var boundaries = new GLatLngBounds(new_sw, new_ne);
		pic_url = gallery_dir + path + prefix + file;
		var overlay = new GGroundOverlay(pic_url, boundaries);
		map.addOverlay(overlay);
		map.setZoom(10);
	//	GEvent.addListener(map, 'zoomend',function(){pic_zoom = map.getZoom()});
	//	map.setZoom(map.getZoom()-6);		
	})
}
