//  вариант - jQuery  walks - new/ver. e2.jQuery.object
//  служебные функции и определения

 var B ;	// хеш "входных" данных ( например - текстов )
 var A ;	// хеш данных "оглавлений" и прогулок
// var C ;	// хеш "оперативных/служебных" данных 
// var L ;	// хеш данных "link" файла
 var LinksExt = new Array(); // хеш данных внешних "link" связей
 var Sled = new Array();
 var test = 0 ;	// 1 / 0  - вкл/выкл режим test
 var tst = 0 ;  // 1 / 0  - вкл/выкл режим протоколирования
 var i = 0 ; 
 var j = -1 ; 
 var flagGoTo = -7 ;   // если установленно 0 и больше - значит надо открыть Точку j=flagGoTo;
 var sizePict = 340 ; // размер текущей картинки
 var regim = 'tems' ; // режим запроса		j
 var param = "prnt=1000" ; //  исходные значения
 var name0 = "Россия" ; //  исходные значения
 var browType = "norm" ; // тип броузера  norm/mie
 var BigPict = '';	// флаг Большой картинки
 var YesMap = 0 ; // счетчик координат в описателе >0 - можно показывать карту
 var MapSumm = new Array(0,0,0,0) ;  // крайние координаты - для определения центра

var clickLinkColor = '#999999' ; //  цвет выделения текущей картинки Link

  // Защита от alert() в бесконечном цикле 
	window.alert=function(x){if(!confirm(x)){window.alert=null;}};

	var widthScrn = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth ;
	var heightScrn = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight ;

	var sUrl  = "/cgi-bin/album/album_ogle.pl?" ;

	var win_x = 0 ; var win_y = 0 ;
	var browserName = navigator.appName;
	if (browserName == "Microsoft Internet Explorer") 
	{ win_x = 0 ; win_y = 0 ; browType = "mie" ; browserName == "MIE"; }


	var Maps = {} ; // карты 
	var map;  // текущая карта - глобальная переменная
function maps_load() {	// определяем текущую карту 
		map = new YMaps.Map(outMaps);
		map.setCenter(new YMaps.GeoPoint(37.61, 55.75), 12);
	//    map.setCenter(new YMaps.GeoPoint(params[0], params[1]), params[2]);
		
		map.addControl(new YMaps.TypeControl());
		map.addControl(new YMaps.Zoom());
		map.addControl(new YMaps.ScaleLine());
		map.enableScrollZoom();
	//	map.addControl(new YMaps.MiniMap());  // почему-то не работает :(
	testText( "<br><b> maps_load:</b> oK! <br>" );
}

function NewMaps(name, param){ 	this.name = param ; }
	
//   создание нового Следа	
//  вообще-то надо проверять наличие данных перед их присвоением
function NewSled(regims, params, name, dsc){		
		this.regims = regims ;
		this.params = params ;
		this.name =  name ;
		this.dsc =  dsc ;
	testText("<hr><br><b> NewSled:</b> <b></b><br><b> NewSled:</b> regims=<b>"+regims+"</b><br>");  
	testText("<b> NewSled:</b> params=<b>"+params+"</b><br><b> NewSled:</b> name=<b>"+name+"</b><br>");  
	testText("<b> NewSled:</b> dsc=<b>"+dsc+"</b><br><b> NewSled:</b> end <b></b><br>");  
} ;

// управление следами
var SledLine = function( regims, params, name, dsc ){  	
		var enden = -1 ;	//   метка повторного захода
			for (var j=0; j<Sled.length; j++) {               //   
				if ( params == Sled[j].params   )  {   // проверяем наличие в Следе захода с такими параметрами..  Будет ошибка при постраничном просмотре...
					enden = j ;   // ??  нужен ли enden - ведь есть значение счетчика!!  - vrode NuGeN  :)
					break;
				}
			}
	 		if ( enden == -1 )	{   //  если наличие в Следе захода с такими параметрами не найдено 
				Sled.push( new NewSled( regims, params, name, dsc ) ) ;   //  добавляем новый След
			} else { Sled.length = enden+1 ; }   //   иначе обрезаем Следы до найденного
		testText ("SledLine:: regims="+regims+", params="+ params+", dsc="+ dsc+" <br>");
		templSledLine(params);
		if(params.indexOf('tema')>=0){
			params=params.replace('tema=','');
			params=params.replace('.rus','');
			params=params.replace('/'+dsc,';'+dsc);
		//	params+=';'+dsc;
		}
		if(Sled.length>1) { document.location.hash='#'+params ; }	// показываем в адресе заход на тек. положение
		else if(Sled.length=1) { document.location.hash='#'+params; }  //  для первого следа - правильнее .hash=''
		testText ("SledLine::"+Sled.length+" location.hash="+document.location.hash+" <br>");
		return ;
	//	return( templSledLine(params) );
}	;  // function SledLine

function outSledLine(ll){  //   обработка захода с указанием адреса ( тема, прогулка )
	var tek=Sled.length;
	testText( "<hr><br><b> outSledLine:</b>tek="+tek+" Распечатка <b>tems </b><br>" );  
	if(tek>0){ tek--;}
	testHash(ll) ;
	if( ll.tems[0].name ) {
		testText ( "<br><b> outSledLine:</b> ( Sled["+tek+"].name="+ ll.tems[0].name+" )<br>" ) ;
		Sled[tek].name = ll.tems[0].name ;
		templSledLine( Sled[tek].params );
		testHash(Sled) ;
	} else { testText ( "<br><b> outSledLine:</b> ( ll.tems[0].name - eRRor )<br>" ) ;}
	testText ( "<b> outSledLine: end</b> <br>" ) ;
	
}
	
// показываем страницу картинки с подложкой   - регулируем их размеры  выше	 
function showPictShow(){
	if ( PictShow.style.visibility != 'visible' )  { 
			ClosePictShow.style.visibility = 'visible'; 
			ClosePictShow.style.zIndex = 5 ;
			PictShow.style.visibility = 'visible' ; 
			PictShow.style.zIndex = 7 ;
	}
}

// показываем страницу картинки с подложкой GT - регулируем их размеры  выше	 
	function GTshowPictShow(){
		if ( GTPictShow.style.visibility != 'visible' )  { 
			GTClosePictShow.style.visibility = 'visible'; 
			GTClosePictShow.style.zIndex = 6 ;
			GTPictShow.style.visibility = 'visible' ; 
			GTPictShow.style.zIndex = 8 ;
		}
	}
	
	function closePictShow(){			// закрыть окно картинки
		ClosePictShow.style.visibility = 'hidden'; 
		ClosePictShow.style.zIndex = -10 ;
		PictShow.style.visibility = 'hidden' ; 
		PictShow.style.zIndex = -10 ;
	}  ;

	function GTclosePictShow(){			// закрыть окно картинки  GT goto
		GTClosePictShow.style.visibility = 'hidden'; 
		GTClosePictShow.style.zIndex = -10 ;
		GTPictShow.style.visibility = 'hidden' ; 
		GTPictShow.style.zIndex = -10 ;
	}  ;
		
	function testHash(X){		 //  !!!  попытка выводить содержимое Хеша
	  if ( tst > 0 ) {
		var out ;
		testText( "<pre>" ) ;
		for(i in X) {
			if( typeof(X[i]) == "object" ) {  // == 'object'
				for(j in X[i]) {
					if ( typeof(X[i][j]) == "object"  ) {
						for( n in X[i][j] ) {
							out = X[i][j][n]  ;	
							out = filtrTag( out ) ;
							testText( "<nobr>H_:_<b>"+i+":"+j+":"+n+"=</b>"+out+"</nobr><br>" ) ;
						} ;
					} else { 
						if( X[i][j] ) {
							 out = X[i][j]  ;	out = filtrTag( out ) ;
							 testText( "<nobr>H_._<b>"+i+":"+j+"=</b>"+out+"</nobr><br>" ) ; 
						}
					}
				}
			} else {
				if( X[i] ) {
					 out =  X[i]  ; 		out = filtrTag( out ) ;
					 testText( "<nobr>H_ _<b>" + i + "=</b>" + out + "</nobr><br>" ) ;
				}
			}
		}
		testText( " H end</pre><br>" ) ;
	  }
	} ;	   //  TeST  !!!!!!!

	function testText(X){		 //  собираем отладочную информацию
	//	alert ( "test = "+tst );
		if ( tst > 0 ) {
			outTest.innerHTML +=  X  ; 
		}
	} ;	   //  TeST  !!!!!!!!!
	
    function screenSize() {
		widthScrn = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth ;
		heightScrn = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight ;
		widthScrn -= win_x ; heightScrn -= win_y ;
		test_s.innerHTML= browserName+":ScrnSize: "+widthScrn+" х "+ heightScrn + " ( "+sizePict+" )" ;
	} ;
 
	function filtrUndef(msg){			// фильтр на undefined
		msg = ( (msg !== undefined) && (msg != 'undefined' ) ) ? msg : '' ; 	
		return(msg);
	}  ;
	
	function filtrTag(msg){			// замена <> в тегах
		if ( msg.indexOf('<') >= 0 ) {
			msg = msg.replace( /</g, "&#060" ) ; 	
			msg = msg.replace( />/g, "&#062" ) ; 	
		}
		return(msg);
	}  ;

	function filtrTitle(msg){			// замена кода &#146; в тегах
		if ( msg.indexOf('&#') >= 0 ) {
			msg = msg.replace( /&#146;/g, " " ) ; 	
			msg = msg.replace( /  /g, " " ) ; 	
		}
		return(msg);
	}  ;
	
 function doResize() {
	screenSize() ;
	if (  ( widthScrn > 1050 ) && ( heightScrn > 850 ) ) { 
		if( (sizePict != 640) && ( A !== undefined ) ){
			PictShowPictTek.src  = "/" + A.desc.pic_path + "/"+ A.tema[A.TekJ].pict_b;
		}
		sizePict = 640 ;
	}
	else { 
		if( (sizePict != 340) && ( A !== undefined ) ){
			PictShowPictTek.src  = "/" + A.desc.pic_path + "/"+ A.tema[A.TekJ].pict_m;
		}
		sizePict = 340 ;
	}
	CtrlForm.style.width = ( widthScrn-2 ) + 'px';

	TemsZona.style.width = ( widthScrn-8 ) + 'px';
	TemsZona.style.height = ( heightScrn-51 ) + 'px';

	PictShow.style.width = ( widthScrn-9 ) + 'px';
	PictShow.style.height = ( heightScrn-48 ) + 'px';
	ClosePictShow.style.width = ( widthScrn-11 ) + 'px';
	ClosePictShow.style.height = ( heightScrn-22 ) + 'px';
	closeMaps.style.width = ( widthScrn-11 ) + 'px';
	closeMaps.style.height = ( heightScrn-22 ) + 'px';
	PictBigShow.style.width = ( widthScrn-12 ) + 'px';
	PictBigShow.style.height = ( heightScrn-12 ) + 'px';

	GTPictShow.style.width = ( widthScrn-9 ) + 'px';
	GTPictShow.style.height = ( heightScrn-48 ) + 'px';
	GTClosePictShow.style.width = ( widthScrn-11 ) + 'px';
	GTClosePictShow.style.height = ( heightScrn-22 ) + 'px';
	
	sled.style.width =  ( widthScrn-27) + 'px'; 

	cntPsPict.style.width =  ( sizePict-0) + 'px'; // контейнер картинки на странице картинки 
	cntPsPict.style.height =  ( sizePict-0) + 'px'; // контейнер картинки на странице картинки 
	GTcntPsPict.style.width =  ( sizePict-0) + 'px'; // контейнер картинки на странице картинки 
	GTcntPsPict.style.height =  ( sizePict-0) + 'px'; // контейнер картинки на странице картинки 

	cntCtrlPictA.style.width = ( widthScrn-sizePict-30 ) + 'px';  //  контейнер управления на странице картинки 

	PictShowNameTek.style.width = ( widthScrn-sizePict-50 ) + 'px';  //
	PictShowTextTek.style.width = ( widthScrn-sizePict-60 ) + 'px';  //
	PictShowTextTek.style.height = ( sizePict-168 ) + 'px';  //
	PictShowResmTek.style.width = ( widthScrn-sizePict-50 ) + 'px';  //
	PictShowResmTek.style.top = ( sizePict - 4 ) + 'px';  //
	PictShowLink.style.top = ( sizePict-1+15 ) + 'px';  //
	PictShowLink.style.width = ( widthScrn-22 ) + 'px';  //
	PictBig.style.left = ( sizePict-1+9 ) + 'px';  //

	PictMaps.style.left = ( sizePict-1+9 ) + 'px';  //

	
	GTPictNewGoTo.style.width = ( widthScrn-sizePict-50 ) + 'px';  //
	GTPictShowNameTek.style.width = ( widthScrn-sizePict-50 ) + 'px';  //
	GTPictShowTextTek.style.width = ( widthScrn-sizePict-60 ) + 'px';  //
	GTPictShowTextTek.style.height = ( sizePict-168 ) + 'px';  //
	GTPictShowResmTek.style.width = ( widthScrn-sizePict-50 ) + 'px';  //
	GTPictShowResmTek.style.top = ( sizePict - 4 ) + 'px';  //
	GTclosePictRet.style.top = ( sizePict-1+25 ) + 'px';  //
	GTclosePictRet.style.width = ( widthScrn-sizePict-50 ) + 'px';  //
	
	outMaps.style.width = ( widthScrn-27 ) + 'px';
	outMaps.style.height = ( heightScrn-64 ) + 'px';
	outTest.style.width = ( widthScrn-40 ) + 'px';
	outTest.style.height = ( heightScrn-70 ) + 'px';
	outText.style.width = ( widthScrn-110 ) + 'px';
	outText.style.height = ( heightScrn-64 ) + 'px';
	outGBook.style.width = ( widthScrn-151 ) + 'px';
	outEdt.style.width = ( widthScrn-151 ) + 'px';
	GBook.style.width = ( widthScrn-77 ) + 'px';
	GBook.style.height = ( heightScrn-77 ) + 'px';
	showLoad.style.width = ( widthScrn-20 ) + 'px';
	showLoad.style.height = ( heightScrn-20 ) + 'px';

	var botBlock_bottom = ( heightScrn > ( sizePict + 240 ) ) ? 2 : ( heightScrn + 44 ) ;
	botBlock.style.bottom = botBlock_bottom + 'px';  //
	botBlock.style.width = ( widthScrn-30 ) + 'px';
	
	//map.redraw();
}	


    function doTest() {		//   показ отладочной информации
		ShowLoad(0) ;

		if ( $("#outTest").css("display") != 'block' )  
			 {	$("#outTest").slideDown(300) ;  }  // fadeIn/slideDown  outTest.style.zIndex =  9 ; 
		else { 	$("#outTest").slideUp(300) ; }  // fadeOut/slideUp  outTest.style.zIndex = -10 ; 
	}  ;


    function doText( file ) {  //  показ текстового файла html-верстка
		if ( $("#outText").css("display") != 'block' )  
			{	
				testText( "<b>doText</b> :"+file+"<br>" ) ;
				ShowLoad(1) ;
				
				var Url  = sUrl + "file" + '(file=' + file +')' ;	//  формирование строки запроса
				testText("<b>запрос файла:</b>"+ Url ) ; 					//  ТЕСТОВЫЙ вывод
				$("#tText").load(Url);	  //  обращение к серверу
				$("#outText").fadeIn(300) ;   // fadeIn/slideDown  outText.style.zIndex =  9 ; 
				ShowLoad(0) ;

			}
		else { 	$("#outText").fadeOut(300) ;    }	// fadeOut/slideUp outText.style.zIndex = -10 ; 
	} ;

    function ShowLoad(j) {  //  - крутим картинку - идет загрузка
		if ( j == 1 )  
			 {	$("#showLoad").fadeIn(600) ;  }  // fadeIn/slideDown  outTest.style.zIndex =  9 ; 
	//		 {	$("#showLoad").fadeTo("slow", 0.33) ;  }  // fadeIn/slideDown  outTest.style.zIndex =  9 ; 
			 
		else {
				$("#showLoad").fadeOut(600) ;   // fadeOut/slideUp  outTest.style.zIndex = -10 ; 
	//			$("#showLoad").fadeTo("slow", 0.0) ;   // fadeOut/slideUp  outTest.style.zIndex = -10 ; 
				var Url  = sUrl + "file" + '(file=' + '/stdt/botblock.htxt' +')' ;	//  формирование строки запроса
				$("#botBlock").load(Url);	
			 }
	}  ;	

	
// -------------------------------------------------- walks_setings ---------------------
 
function doSet() {
		if ( $("#outSet").css("display") != 'block' )  
			 {	$("#outSet").fadeIn(300) ;  }  // fadeIn/slideDown 
		else { 	$("#outSet").fadeOut(300) ; }  // fadeOut/slideUp  
}

// -------------------------------------------------- gBook ---------------------


	var gbUrl  = "/cgi-bin/gb/gba_db.pl?" ;
	var GB = new Array();
	var step=0;
	var page=1;
	var liMsg=11;
		
    function loadGBook() {		//   показ Гостевой Книги
		ShowLoad(1) ;
	
		$('#doAddGBook').click( function(){ 	// alert('AddGBook');
		
		//	GBAdd.action="/cgi-bin/gb/test_post.pl";
			GBAdd.action="/cgi-bin/gb/gba_db.pl";
			GBAdd.innerHTML='';  // шаблон - добавить сообщение в гостевую книгу
			$("#GBAdd").append('добавьте своё сообщение с гостевую книгу<hr>');
			$("#GBAdd").append('<br>Ваше имя: <input name="msg_autor" type="text" size="22" class="msg_autor" value="" >');
			$("#GBAdd").append('Ваш eMail: <input name="msg_email" type="text" size="33" class="msg_autor" value="" >');
			$("#GBAdd").append('<br><br>Ваше сообщение: <br><textarea name="msg_text" cols="77" rows="7" class="msg_text" ></textarea>');
			$("#GBAdd").append('<br><br><input type="submit" id="sendAddBook" value=" отправить " class="bttn_brd" >');
			$("#GBAdd").append('<a class="close_bttn_brd" title="outEdt" style="left:111px;" >закрыть</a>');

			$("#outEdt").slideDown(300) ; 
		} );

		$("#GBAdd").ajaxForm(function(data) { 
			//alert('Спасибо за комментарий!\n'); } 
			doPage(1); //alert("Change");
			$("#outEdt").slideUp(300) ; 
		});
		
		$('#pagesKol').val( liMsg );
		$('#pagesKol').change( function() {
			liMsg=$('#pagesKol').val();
			step=0;
			doPage(1); //alert("Change");
		});

		$('.page').live("mouseover", function() {
			$(this).css('color', '#ff0000' );
		});
		$('.page').live("mouseout", function() {
			$(this).css('color', '' );
		});

		$('.msg_kod').live( "click", function(){ 
	//		alert('kod!!!['+this.title+']!!!');
			var Url  = gbUrl + 'kod='+this.title ;	//  формирование строки запроса
			testText( "<b> doPage::запрос:</b> "+Url+"<br>" ) ; 		//  ТЕСТОВЫЙ вывод
			jQuery.getJSON( Url, function(json) { outEdtGB(json); });	//  обращение к серверу
		});

		$('a.page').live( "click", function(){ 
			doPage(this.text); 
		} );
		doPage(1);	
	}

function doPage(pg){
	page=pg;
	$('.page').css('font-size', '' );
	$('.page').css('cursor', '' );
	$('#pg'+page).css('cursor', 'default' );
	$('#pg'+page).css('font-size', '19px' );
//	testText( "<br>Page- "+page+" <br>" );

	var Url  = gbUrl + 'lims='+liMsg+'&page='+page ;	//  формирование строки запроса
	testText( "<b> doPage::запрос:</b> "+Url+"<br>" ) ; 		//  ТЕСТОВЫЙ вывод
	jQuery.getJSON( Url, function(json) { outGB(json); });	//  обращение к серверу
	outGBook.innerHTML ='';
}

function outGB(o){
	testText( "<b>outGB</b><br>" );
	GB=0; GB=o; o=0;
	if( step==0 ) { 
		templPagesGB(); 
		$('#pg1').css('cursor', 'default' );
		$('#pg1').css('font-size', '19px' );
	} 
	step++;
	if ( GB.gbook )  {	
		outGBook.innerHTML='';
	//	testHash(GB.gbook);	
		for (var jn=0; jn<GB.gbook.length; jn++) { 
			outGBook.innerHTML += templStrGB(jn)+"<br>";
		}
	}
	ShowLoad(0) ;
}

function doGBook() {		//   показ Гостевой Книги
	ShowLoad(0) ;

		if ( $("#GBook").css("display") != 'block' )  {
			if( page == 1 ){ loadGBook(); }
			$('#GBook').css('cursor', 'default' );
			$("#GBook").slideDown(300) ;  
		 }  // fadeIn/slideDown  outTest.style.zIndex =  9 ; 
		else { 	$("#GBook").slideUp(300) ; }  // fadeOut/slideUp  outTest.style.zIndex = -10 ; 
}  ;


function outEdtGB(o){	// оформляем элемент Показа/Редактора записи Гостевой
	testText( "<b>outEdtGB</b><br>" );
	GB=o; o=0;
//	outEdt.innerHTML = '<div class="close_bttn_X" title="outEdt"  ></div>' ;     
//	outEdt.innerHTML += templEdtGB(0)+"<br>";
	j=0;
	//	GBAdd.action="/cgi-bin/gb/test_post.pl";
		GBAdd.action="/cgi-bin/gb/gba_db.pl";
		GBAdd.innerHTML='';  // шаблон - Редактор записи в гостевую книгу
		$("#GBAdd").append('<b>изменить сообщение из гостевой книги...</b><hr>');
		$("#GBAdd").append('<input type="text" name="msg_autor" value="'+filtrUndef( GB.gbook[j].msg_autor )+'" size="33" class="msg_autor" >') ;
		$("#GBAdd").append(' <span class="msg_date">'+' '+filtrUndef( GB.gbook[j].r_date )+'</span>'+' ') ;
		$("#GBAdd").append('<span class="msg_date">'+filtrUndef( GB.gbook[j].r_time )+' '+'</span>') ;
		$("#GBAdd").append('<input type="text" size="33"  class="msg_email" name="msg_email" value="'+filtrUndef( GB.gbook[j].msg_email )+'" >') ;
		$("#GBAdd").append('<br>') ;
		$("#GBAdd").append('<textarea cols="103" rows="7" class="msg_text" name="msg_text" >'+filtrUndef( GB.gbook[j].msg_text)+'</textarea>') ;
		$("#GBAdd").append('<br>') ;
		$("#GBAdd").append('<textarea cols="103" rows="7" class="msg_text" name="msg_repl" >'+filtrUndef( GB.gbook[j].msg_repl)+'</textarea>') ;
		$("#GBAdd").append('<br><br>') ;
		$("#GBAdd").append('<span class="msg_kod" >'+' ('+GB.gbook[j].kod+')'+'</span>') ;
		$("#GBAdd").append('<input type="hidden" name="msg_kod" value="'+ GB.gbook[j].msg_kod +'" >') ;
		$("#GBAdd").append('<br><input type="submit" id="sendAddBook" value=" отправить " class="bttn_brd" >');
		$("#GBAdd").append('<a class="close_bttn_brd" title="outEdt" style="left:111px;" >закрыть</a>') ; 
		
		$("#outEdt").slideDown(300) ; 	
}
	
//  оформляем "постраничность" Гостевой
var templPagesGB = function(){	
	var ps=GB.MsgOpen/GB.MsgList;
	pagesBook.innerHTML ='';
	//	testText('<span class="msg_date">'+GB.MsgOpen+' / '+GB.MsgList+' = '+ps+'  '+'</span>') ;
	ps=Math.ceil(ps) ; 
	//	testText('<span class="msg_autor">'+' [ '+ps+' ] '+'</span>'+'<br/>') ;
	for( var p=1; p<=ps; p++ ){
		pagesBook.innerHTML += '[ <a id="pg'+p+'" class="page">'+p+'</a> ] ' ;
	}
}

 	function filtrBR(msg){			// замена <> в тегах
		if ( msg.indexOf('(br)') >= 0 ) {
			msg = msg.replace( /\(br\)/ig, "<br/>" ) ; 	
			msg = msg.replace( /\(b\)/ig, "<b>" ) ; 	
			msg = msg.replace( /\(\/b\)/ig, "</b>" ) ; 	
		}
		return(msg);
	}  ;


