var win_num=0;
var win_index=5;
var	drag_win_left = "20px";
var	drag_win_top = "75px";
var	drag_win_width = "540px";

function startdrag(t, e,option) {  
     if (e.preventDefault) e.preventDefault(); //line for IE compatibility  
     e.cancelBubble = true;  
     window.document.onmousemoveOld = window.document.onmousemove;  
     window.document.onmouseupOld = window.document.onmouseup;  
     window.document.onmousemove=dodrag;  
     window.document.onmouseup=(option)? stop_drag1 : stop_drag;  // in case of infowin without top left new window is opened in a position of the old one, infowin2 - uses given top and left
     window.document.draged = t;  
     t.dragX = e.clientX;  
     t.dragY = e.clientY;
	 win_index++;
	 t.style.zIndex=win_index;
	 $(t).find(".return").css({'visibility':'visible'}).width(16) // opening of return menu in mapwin1
     return false;  
	 } 
	 
function dodrag(e) {        
     if (!e) e = event; //	line for IE compatibility  
     t = window.document.draged; 
	 if ((e.clientX>window_width) ||(e.clientY<header_bottom+title_height)|| (e.clientY>window_height-50))
	 	stop_drag()	 
	 var nleft=(t.offsetLeft + e.clientX - t.dragX);
	 if (nleft<0)
	 	nleft=0;
	 var ntop=(t.offsetTop + e.clientY - t.dragY);
	 if (ntop<header_bottom+title_height)
	 	ntop=header_bottom+title_height;
     $(t).css({'left' : nleft,'top' : ntop});  
     t.dragX = e.clientX;  
     t.dragY = e.clientY;
     return false;  
	 }  
function stop_drag() {  //	restore event-handlers
//	t = window.document.draged;
    window.document.onmousemove=window.document.onmousemoveOld;  
    window.document.onmouseup=window.document.onmouseupOld;  
	}

function stop_drag1() {  //	restore event-handlers
	t = window.document.draged;
	drag_win_left=t.style.left;
	drag_win_top=t.style.top;
	stop_drag()
  //  window.document.onmousemove=window.document.onmousemoveOld;  
   // window.document.onmouseup=window.document.onmouseupOld;  
	}

function start_resize(t, e) {  
     if (e.preventDefault) e.preventDefault(); //line for IE compatibility  
     e.cancelBubble = true;  
     window.document.onmousemoveOld = window.document.onmousemove;  
     window.document.onmouseupOld = window.document.onmouseup;  
     window.document.onmousemove=do_resize;  
     window.document.onmouseup=stop_drag;  
     window.document.resized = t;  
     t.startX = e.clientX;  
     t.startY = e.clientY;
	 win_index++;
	 t.style.zIndex=win_index;
	 $(t).find(".return").css({'visibility':'visible'}).width(16) // opening of return menu in mapwin1
     return false;  
} 
	 
function do_resize(e) {        
	if (!e) e = event; //	line for IE compatibility  
	t = window.document.resized;
	var delta_x = e.clientX - t.startX;
	var delta_y = e.clientY - t.startY;
	t.startX = e.clientX;  
	t.startY = e.clientY; 
	var nwidth = Math.max(200,$(t).width() + delta_x); 
	var nheight = Math.max(200,$(t).height() + delta_y);
	$(t).width(nwidth).height(nheight)	
	$(t).children().each(function(){
		var prefix = this.id.substr(5,1);		
		if (prefix == "h") // info_header						 
			$(this).width($(this).width() + delta_x);
		if (prefix == "f") // info_footer
			$(this).css({'left' : $(this).position().left + delta_x, 'top': $(this).position().top + delta_y})
//								$(this).css({'left' : $(this).position().left + delta_x, 'top': $(this).position().top + delta_y})		

		if (prefix == "i") {// info_inner
			$(this).width($(this).width() + delta_x).height($(this).height() + delta_y)
			try{maps[0].checkResize()}catch(e){}
//								try{maps[this.num].checkResize()}catch(e){}
			$(this).children().each(function(){
				if (this.id.substr(0,3) == 'map'){
					$(this).width($(this).width() + delta_x).height($(this).height() + delta_y)
					try{maps[0].checkResize()}catch(e){}						 
					}
				})
		}
	});
	if (nwidth <= 200 || nheight <= 200)
		stop_drag()
     return false;  
}  
		
function create_infodiv(w_left,w_top,w_width){	
	var infodiv = document.createElement('div');
	infodiv.id      = "info_div"+ win_num;
	infodiv.win     = win_num;
	win_num++;
	$(infodiv).appendTo('body').css({'top':w_top,'left':w_left,'background-color':'#fffaec','width':w_width,'position':'absolute','border':'1px solid #666','font-size':'8pt','z-index':win_index});
	$(infodiv).addClass('info_')
	return infodiv
}

function create_infoheader(infodiv,html){
	var infoheader = document.createElement('div');
	infoheader.id      = "info_header"+ infodiv.win;
	$(infoheader).appendTo(infodiv).css({'top':infodiv.style.top,'left':infodiv.style.left,'width':$(infodiv).width()-16,'min-height':'20px','padding':'0 0 0 16px','margin':0,'background-color':'#3a2823','color':'#fff'}).html(html)
	$(infoheader).addClass('info_')
	return infoheader
}

function create_infoinner(infodiv,html){
	var infoinner = document.createElement('div');
	infoinner.id      = "info_inner"+ infodiv.win;
	$(infoinner).appendTo(infodiv).css({'left':infodiv.style.left,'width':$(infodiv).width()-24,'padding':'10px','margin':0}).html(html)
	return infoinner
}
/*
function close_infowin(id){	
	try{
		if (id==search_win_id){
			document.getElementById("map_searcher").style.visibility='hidden';
			get(id).style.visibility='hidden';
			search_win_id="";
			GEvent.removeListener(adr_listener);
			GEvent.removeListener(left_cursor_listener);
			GEvent.removeListener(right_cursor_listener);
			}
	}catch(e){};
	try{
//	document.getElementById(id).style.visibility='hidden';
	$("#"+id).remove()
	if (drag_infodiv == id && window.markerD){ // removing overlay with big red marker
		right_map.removeOverlay(markerD);
		drag_infodiv='';
		drag=null;
		hide_lines(1); // unhiding
		}
	}catch(e){};
}
*/
function close_infowin(id){	
try{
	if (id==search_win_id){
		document.getElementById("map_searcher").style.visibility='hidden';
		get(id).style.visibility='hidden';
		search_win_id="";
		GEvent.removeListener(adr_listener);
		GEvent.removeListener(left_cursor_listener);
		GEvent.removeListener(right_cursor_listener);
		}
	else {
	//	document.getElementById(id).style.visibility='hidden';
		$("#"+id).remove()
		if (drag_infodiv == id){ // removing overlay with big red marker
			drag_infodiv = '';
			drag = null;
			hide_lines(1); // unhiding
			right_map.removeOverlay(markerD);	
		}
		if ($("#"+id).hasClass("left_pid"))
			left_pid = null
		if ($("#"+id).hasClass("right_pid"))
			right_pid = null	
	}
}
catch(e){};
}

function infowin(w_left, w_top, w_width, w_header, w_html,option,w_height){ // draggable non-fixed heght with header and close option
	if(!w_left)
		w_left=drag_win_left
	if(!w_top)
		w_top=drag_win_top	
	return infowin2(w_left, w_top, w_width,(option) ? w_height : false, w_header, w_html,(option) ? option : 1)
}

function close_infowin2(id){
	if (arguments.length){ // removing one
		if ($("#"+id).hasClass('closeby')){
			empty_closeby[get(id).closeby_num] = true;
		}
		$("#"+id).remove();		
	}
	else // removing all
		$(".infowin2").remove()
}

function infowin2(w_left, w_top, w_width, w_height, w_header, w_html,option){ // draggable fixed/non-fixed heght infowindow with header and close option
																			// option == 1 means fixing currently opened dragged infowin position for next infowins	
	var infodiv = create_infodiv(w_left,w_top,w_width);
	$(infodiv).addClass('shadow infowin2').css({'left':w_left});
	var ind = (w_height)?'2':''; // if height is set - fixed height
	var w_num = infodiv.win;
	var h_html='<div onmousedown="startdrag(this.parentNode.parentNode, event' + ((option==1)?',1':'') +');" >'+
			'<table width="100%"><tr><td  style="cursor:move"><b><a id="hdrh' + w_num + '"></a></b></td>' +
	//		'<td id="hdr5' + w_num + '" width="16px" align="right"></td>' + 
			'<td id="hdr2' + w_num + '" class="return" width="0px" align="right"></td>' + 
			'<td id="hdr4' + w_num + '" width="0px" align="right"></td>' + 
	//		'<td id="hdr3' + w_num + '" width="16px" align="right"></td>' + 
			
			'<td id="hdr1' + w_num + '" width="0px" align="right"></td>' + // extra cells for menu
  			'<td id="hdr0' + w_num + '" width="16px" align="right">' +
			'<img src="../images/close.png" hspace="0" vspace="0" border="0" onclick="close_infowin'+ind+'(&quot;info_div' + w_num + '&quot;);" id="info_close' + w_num + '" title="Закрыть окно" /></td></tr></table></div>';	
	var infoheader=create_infoheader(infodiv,h_html);
	$("#hdrh" + w_num).html(w_header)
	$(infoheader).addClass('topround')
	var infoinner = create_infoinner(infodiv,w_html);
	if (w_height){
		$(infodiv).height(w_height)
		$(infoinner).height(w_height-60)
	//	infodiv.style.height		=	w_height;
	//	infoinner.style.height		=	w_height - 60 //parseInt(w_height)-60+"px";
		infoinner.style.overflow	=	'auto';	
	}
	infoinner.style.paddingBottom	= "10px";	
	infoinner.onclick=function(){
			win_index++;
			this.parentNode.style.zIndex=win_index;
		}	
	if (option == 2){ // resizable
		var infofooter = document.createElement('img');
		infofooter.id = "info_footer"+ w_num;
		$(infofooter).appendTo(infodiv).css({'top': $(infodiv).height() - 18,'left': $(infodiv).width() - 18, 'cursor':'se-resize','position':'absolute'})
		infofooter.src	= "../images/resize.png"
		infofooter.onmousedown = function(e){start_resize(this.parentNode,e)}
	}
	if (option == 3) // fading out - show users
		$(infodiv).hide().fadeIn(500).delay(3000).fadeOut(2500);
	return infodiv.id
}

function close_infowin3(){
	$(".infowin3").remove()
}

function infowin3(w_left, w_top, w_width, w_header, w_html, w_height){ // fixed poition with header and no close option - animated map
	if (!w_height)
		w_height = 320
	close_infowin3();
	var infodiv = create_infodiv(w_left,w_top,w_width);
	var infoheader=create_infoheader(infodiv,"<b>"+w_header+"</b>");
	$(infoheader).addClass('topround').css({'padding-top':4})
	//infoheader.style.paddingTop = "4px";
	create_infoinner(infodiv,w_html);
	$(infodiv).addClass('shadow infowin3').css({'background':'#8a7873','color':'#fff','height':0,'width':w_width,'overflow':'hidden','border-bottom-width':16,"border-color":'#3a2823','opacity': 0}).animate({opacity:1},1000).animate({height:w_height,borderBottomWidth:1},3000)
	//$(infodiv).addClass('shadow infowin3').css({'background':'#fffaec','height':0,'width':w_width,'overflow':'hidden','border-bottom-width':16,"border-color":'#3a2823','opacity': 0}).animate({opacity:0.8},1000).animate({height:w_height,borderBottomWidth:1,opacity:1},3000)
	return infodiv.id
}

function close_infowin4(){
	$(".infowin4").remove()
}

function infowin4(w_width, w_html,mode){ // positioned from cursor, no header, no close option - menu preview pictures. With mode - on top of cursor
	close_infowin4();
	var w_left=window_width/2;
	var w_top=getBodyScrollTop()+110;
	try {w_left=cursor_xy.x;w_top=cursor_xy.y;}catch(e){return};
	if (w_left>window_width-w_width)
		w_left-=w_width;
	if (mode)
		w_top -= 350;
	var infodiv = create_infodiv(w_left,w_top+60,w_width)
	var infoinner = create_infoinner(infodiv,w_html);
	infoinner.style.padding	    = "0px"
	$(infodiv).addClass('shadow5 infowin4').css({'padding':'5px'}).hide().fadeIn(1000)	
}

var cursor_xy = new Object();
cursor_xy.x = 0;
cursor_xy.y = 0;
//window.document.onmousemove=function(e){try{cursor_xy=mousePageXY(e);}catch(e){}};

window.document.onmousemove = function (pos) {cursor_xy.x=pos.pageX;cursor_xy.y=pos.pageY}

function animated_pic(title,html,pwidth,pheight){
	var ratio=pwidth/pheight;
	n_w=n_h=540;
	(ratio>1) ? n_h=parseInt(n_h/ratio) : 0;
	(ratio<1) ? n_w=parseInt(n_w*ratio) : 0;
	var x=100, y=100;
	try {x=cursor_xy.x;y=cursor_xy.y;}catch(e){};
	var offset=getBodyScrollTop();
	w_top=offset+50;
	if (offset>40)
		w_top-=5;
	w_left=10;
	if (x<n_w+30 && y<n_h+30+getBodyScrollTop())
		w_left=x+30
	infowin3(w_left, w_top, n_w+20, title, html, n_h+50)	
	/*	
	close_infowin3();
	var infodiv = create_infodiv(w_left,w_top,n_w+20);
	var infoheader=create_infoheader(infodiv,"<b>"+title+"</b>");
	$(infoheader).css({'padding-top' : '4px','max-width' : n_w+20+'px'});
	create_infoinner(infodiv,html);
	$(infodiv).addClass('shadow infowin3').css({'background':'#fffaec','height':'0px','overflow':'hidden','border-bottom-width':'16px',"border-color":'#3a2823'}).hide().fadeIn(1000).animate({height:n_h+50,borderBottomWidth:1},3000)
	*/
}

function animated_pic1(title,html){
	var x=100, y=100;
	try {x=cursor_xy.x;y=cursor_xy.y;}catch(e){};
	var offset=getBodyScrollTop();
	w_top=offset+50;
	if (offset>40)
		w_top-=5;
	w_left = (x < 500)? 510 : 10;
	//w_left = 300;
	close_infowin3();
	var infodiv = create_infodiv(w_left,w_top,540);
	$(infodiv).hide();
	var infoheader=create_infoheader(infodiv,"<b>"+title+"</b>");
	$(infoheader).css({'padding-top' : 4,'max-width' : 540});
	create_infoinner(infodiv,html);
	var height = $(infodiv).height();
	$(infodiv).addClass('shadow infowin3').css({'background':'#fffaec',"border-color":'#3a2823'}).fadeIn(1000)
}

function expand_thumb(title,img,prefix){ // expanding picture, postion defined by cursor, no header, no close option
	var normal=(img.src).replace("thumb_",prefix);	
	html='<img id="pic'+win_num+'" src="'+normal+'" alt="'+title+'" title="'+title+'"/>'
	animated_pic(title,html,img.width,img.height)
}

function expand_oldmos_thumb(title,img){ // expanding picture, postion defined by cursor, no header, no close option
	var normal=(img.src).replace("th_","500_");	
	html='<img id="pic'+win_num+'" src="'+normal+'" alt="'+title+'" title="'+title+'" align="middle"/>'
	animated_pic1(title,html)
}

function expand_panoramio_thumb(title,img){ // expanding picture, postion defined by cursor, no header, no close option
	var normal=(img.src).replace("square","medium");	
	html='<img id="pic'+win_num+'" src="'+normal+'" alt="'+title+'" title="'+title+'" align="middle"/>'
	animated_pic1(title,html)
}

function pic_infowin(title,html, pwidth, pheight){ // html = path+file.jpg
	html='<img id="pic'+win_num+'" src="../gallery/albums/'+html+'" alt="'+title+'" title="'+title+'"/>'
	animated_pic(title,html,pwidth,pheight)
}

var map_win_number=0;
var map_win = Array();

function mapwin(w_left, w_top, w_width, w_header, w_html, map_code){ // draggable resizable pop-up window with mapster frame
	var lat_url="&lat=" + Gcenter.lat().toString().substring(0,9);
	var lng_url="&lng=" + Gcenter.lng().toString().substring(0,9);	
	var html = "<html><title>" + w_header + "</title><div id=\"info_map\" style=\"width:540px;height:540px;overflow:hidden; position:absolute; border:1px solid #666\"></div></html>";
	var url="http://retromap.ru/mapster.php?right=" + map_code + "&header=0&demo=1"+lat_url+lng_url;
	var specs="width=540, height=540, resizable=1, left=";
	specs += 40+map_win_number*30;
	specs += ",top=";
	specs += 75+map_win_number*30;
	map_win[map_win_number]=window.open(url,"", specs);
	map_win[map_win_number].focus();
	map_win_number++;
}
                                                                                
function hdr_html(map_div){
	var mcode = map_div.mcode
	var m_width = parseInt(map_div.style.width); 
	var f_size = (m_width < 400)?'<small>':'';
	var f_size_c = (m_width < 400)?'</small>':'';	
	return '<a class="f" style="color:#fff" href="../mapster.php?right='+mcode+map_zoom(mcode)+'" '+map_pic_html(mcode,0)+'>' + f_size + map_list[mcode].name + f_size_c + '</a>'
}

function mapwin1(map_div_id,option){ // map_div - defines position, size, id and mcode for initial map
									// map_div.mcode - defines window header
									// map_div.win - # of infowindow already opened for this div
									// option 0 - return to initial position
									// option 1 - on initial position defined by map_div_id with return, list and expand menu
									// option 2 - on possible dragged and resized position
	var map_div = get(map_div_id);
	var mcode = map_div.mcode;
	var w = win_num; // win_num - refers to infowindow
	var dv = (option == 2) ? $("#info_div"+map_div.win) : $(map_div);
	infowin2(dv.offset().left,dv.offset().top,dv.width(),dv.height(),hdr_html(map_div),'',2);
	if (option == 0 || option == 1)
		$("#hdr2" + w).css({'visibility':'hidden'}).width(0) // hiding return menu icon	
	if (option == 0 || option == 2) // closing previous
		close_infowin2("info_div"+map_div.win)
	$("#info_div" +w).removeClass('shadow');
	$("#info_header" +w).removeClass('topround');
	$("#hdr4" + w).width(16).html('<a title="Показать список карт" onclick="show_map_list(&quot;250px&quot;,&quot;65px&quot;,3,&quot;' + map_div_id + '&quot;)"><img src="../images/map_list2.png" border=0 height=12></a>');
	$("#hdr2" + w).html('<a onclick="mapwin1(&quot;' + map_div_id + '&quot;,0)" title="Вернуть на исходное место"><img src="../images/min_screen.png" border=0 height=12></a>')	
	$("#hdr1" + w).width(16).html('<a href="../mapster.php?right=' + mcode + '" title="Развернуть карту"><img src="../images/full_screen1.png" border=0 height=12></a>')
	$("#hdr0" + w).css({'display':'none'}) // close is not required
	map_div.win = w	
	var inner = get("info_inner"+w)	
	$(inner).css({'left' : '0','padding-top' : '26px'}) // because inner is not absolute
	var map = new_map(inner,mcode,1);
	map.mcode = mcode;
	map.id = map_div.nmap;
	maps[map_div.nmap] = map; // required for sync drag
	//GLog.write("map.id="+map.id)
	map.addControl(new GSmallZoomControl3D());
	delete_terms(map);
	GEvent.addListener(map, 'drag', function() {panMaps(this)});
	GEvent.addListener(map, 'zoomend', function() {panMaps(this)});
	return map
}
