Ext.override(Ext.grid.GridView, {
    onRowOver : function(e, t){
        var row;
        if((row = this.findRowIndex(t)) !== false){
            this.addRowClass(row, "x-grid3-row-over");
            this.grid.fireEvent('rowmouseover', this.grid, row);
        };
    },
    onRowOut : function(e, t){
        var row;
        if((row = this.findRowIndex(t)) !== false && !e.within(this.getRow(row), true)){
            this.removeRowClass(row, "x-grid3-row-over");
            this.grid.fireEvent('rowmouseout', this.grid, row);
        };
    }
});

var zObject = false;
var dwPhoto=null;
var photoStore = null;
var panoramStore = null;
var infoPanelToolBar = null;
var tname = '';	 		var ttext;	  		var tCount;
var webcam = false;
var youtube = 0;
var cityCode = 0;
var dopinfo = '';
Ext.namespace('chiz');


Ext.onReady(function(){
	Ext.QuickTips.init();
	Ext.get('waitButton').remove();
	Ext.get('startButton').show();
});

Ext.namespace('startMaprest');
startMaprest = function (){
    if(Ext.ToolTip) Ext.ToolTip.prototype.dismissDelay = 0;
	myGMap = new Ext.Panel({		
		border:true,
		width: 800,
		height: 400
	});
	chiz = function (){
		myGMap.el.mask('Подождите, пожалуйста...');
		if(tname=="") return;
		var mapParams = myGMap.getCurrentMapParams();
		SWx = mapParams.SWx; SWy = mapParams.SWy; NEx = mapParams.NEx; NEy = mapParams.NEy; zoom = mapParams.zoom;
		myGrid.getStore().baseParams['table_name'] = tname;
		myGrid.getStore().baseParams['SWx'] = SWx;
		myGrid.getStore().baseParams['SWy'] = SWy;
		myGrid.getStore().baseParams['NEx'] = NEx;
		myGrid.getStore().baseParams['NEy'] = NEy;
		if(zoom>6) myGMap.clasterType ="object";
		else myGMap.clasterType ="g_object";
		myGrid.getStore().baseParams['clasterType'] = myGMap.clasterType;
		myGMap.map.clearOverlays();
		myGrid.getStore().load();
		panoramStore.reload();
	};
	
	// Нажатие пункта меню
	function onItemClick(item){
		zObject = false;
		if(!item.dopuslug)
			myGrid.getStore().baseParams['dopuslug'] = '';
		tname = item.tname;
		ttext = item.text;
		chiz();
    };
	panoramStore = new Ext.data.JsonStore({
			root: 'photos',
			totalProperty: 'count',
			proxy         : new Ext.data.ScriptTagProxy({method:'GET', url: 'http://www.panoramio.com/map/get_panoramas.php'}),
			baseParams    : {
				order: 'popularity', set: 'public', from: 0, to: 40,
				minx: 0, miny: 0, maxx: 0, maxy: 0,	size: 'medium'
			},
			fields: ['upload_date', 'owner_name', 'photo_id', 'longitude', 'height', 'width',
				'photo_title', 'latitude', 'owner_url', 'owner_id', 'photo_file_url', 'photo_url']
	});
	
	panoramStore.on("load", function(){ 		
		myGMap.setPanoMarker(); 
		myGMap.el.unmask();
	});
		
	// Нажатие на маркера или на строку грида
	Ext.namespace('onRowClick');
	function onRowClick(t,ri,item){
		var selRec = myGrid.getSelectionModel().getSelected();
		var selCount = myGrid.getSelectionModel().getCount();					
		var id = selRec.get('id');
		var rieltor = selRec.get('rieltor');
		var oldMarker = myGMap.selMarker;
		myGMap.selMarker = id;
		if(oldMarker>-1) myGMap.mMarkerIcon(oldMarker);
		myGMap.chMarkerIcon(id);
		var annot = selRec.get('annot');
		var description = Ext.util.Format.nl2br(selRec.get('description'));
		var gen_description = selRec.get('gen_description');
		var date_create = selRec.get('date_create');	
		var fio = selRec.get('fio');	
		var email = selRec.get('email');	
		var company_name = selRec.get('company_name');	
		var site = selRec.get('site');	
		var adress = selRec.get('adress');	
		var tel = selRec.get('tel');
		var logo = selRec.get('logo');
		dopinfo = selRec.get('dopinfo');
		webcam = selRec.get('webcam')!=null;
		youtube = parseInt(selRec.get('youtube'));
		var statist = 0;

		/* ********************		Panoramio	BEGIN	**************** */
		var lat = parseFloat(selRec.get('lat'));
		var lng = parseFloat(selRec.get('lng'));

		if(dopinfo != ''){
			var clip = Ext.getCmp('dopInfobtn');
			clip.enable();
			clip.setIconClass('clipA');
		}else{
			var clip = Ext.getCmp('dopInfobtn');
			clip.disable();
			clip.setIconClass('clipP');			
		}
		Ext.getCmp('statButton').setTooltip('');
		Ext.Ajax.request({
			url:'action.php',
			params:{ action: 'yapogoda', lat: lat, lng: lng, id:id, tname:tname },
			success: function(res,opts){var p=Ext.decode(res.responseText); cityCode=p['kod']; statist=p['statistic'];},
			callback: function(){
				var ypB = Ext.getCmp('YaPogodaButton');
				var wB = Ext.getCmp('webcamButton');
				var ytB = Ext.getCmp('youtubeButton');
				var sB = Ext.getCmp('statButton');
				
				ypB.setIconClass('tbar-weatherA');
				if(webcam){ wB.setIconClass('tbar-webcamA'); wB.setTooltip('Изображение с вэб-камеры на выбранном объекте');}
				else { wB.setIconClass('tbar-webcamP'); wB.setTooltip('Изображение с вэб-камеры (если она установлена) на выбранном объекте');}
				if(youtube>0) ytB.setIconClass('tbar-youtubeA');
				else ytB.setIconClass('tbar-youtubeP');
				if(statist>0){ sB.setIconClass('tbar-statA'); sB.setTooltip(statist +' просмотров'); }
				else{ sB.setIconClass('tbar-statP'); sB.setTooltip('Статистика просмотров выбранного объекта'); }
				
			}
		});		
		
		panoramStore.baseParams['minx']= lng-0.185;//-0.37;
		panoramStore.baseParams['miny']= lat-0.185;
		panoramStore.baseParams['maxx']= lng+0.185;//+0.37;
		panoramStore.baseParams['maxy']= lat+0.185;
		panoramStore.load();		
		
		/* ********************		Panoramio END    **************** */
		photoStore.baseParams['tname']= tname;	
		photoStore.baseParams['id']=id;			
		photoStore.load({
			callback: function(){
				photoPanel.doLayout();
			}
		});
		infoPanelTpl.overwrite(Ext.getCmp('info_panel_tpl').body, {res_exist: true, annot: annot, description: description, gen_description: gen_description, date_create:date_create, fio: fio, email:email, company_name:company_name, site:site, tel:tel, logo:logo, adress:adress});

		if(item!='no_count') Ext.Ajax.request({
			url:'action.php',
			params:{
				action: 'counter',
				tname: tname,
				rieltor: rieltor,
				id: id
			}						
		});
    };
	
	var gridStore = new Ext.data.Store({
		url: 'action.php',
      baseParams:{
        action:"list",
		table_name: tname,
		SWx: '', 
		SWy: '', 
		NEx: '', 
		NEy: '',
		clasterType: 'g_object'
      }, 
	  remoteSort: true,
      reader: new Ext.data.JsonReader({
        root: 'records',
        totalProperty: 'totalcount',
        id:'id',		
        fields: ['id','description', 'gen_description', 'annot', 'webcam', 'youtube', 'filename', 'date_create', 'rieltor', 'fio', 'email', 'company_name', 'site', 'adress', 'tel', 'logo', 'type', 'lat', 'lng', 'dop', 'SWx', 'SWy', 'NEx','NEy', 'params', 'dopinfo']
      })
    });	
	
	gridStore.on("load", function(t,r,o){		
		var tCount = myGrid.getStore().getTotalCount();				
		if(tCount>0){
			if(myGMap.clasterType!=='g_object')searchPanelTpl.overwrite(Ext.getCmp('sixth_grid_tpl').body, {res_exist: true, object_type: ttext, total: tCount});
			else searchPanelTpl.overwrite(Ext.getCmp('sixth_grid_tpl').body, {res_exist: false});					
			myGMap.setMarkers({tname:tname});
		}else{
			searchPanelTpl.overwrite(Ext.getCmp('sixth_grid_tpl').body, {res_exist: false});					
		};
		
		if(photoStore!==null){
			photoStore.baseParams['id'] = 0;
			photoStore.load();
		}		
		
		var pB = Ext.getCmp('panoButton');
		var ypB = Ext.getCmp('YaPogodaButton');
		var wB = Ext.getCmp('webcamButton');
		var ytB = Ext.getCmp('youtubeButton');
		var sB = Ext.getCmp('statButton');
		var clip = Ext.getCmp('dopInfobtn');

		if(myGMap.selMarker>-1){
			var rec_num=-1;
			for(i=0;i<r.length;i++) if(r[i].get('id')==myGMap.selMarker) {rec_num = i; break;}
			if(rec_num!=-1){
				myGrid.getSelectionModel().selectRow(rec_num);
				myGrid.fireEvent('rowclick', myGrid, rec_num, 'no_count');
			}else{				
				cityCode = 0;
				ypB.setIconClass('tbar-weatherP');
				webcam = false;
				wB.setIconClass('tbar-webcamP'); wB.setTooltip('Изображение с вэб-камеры (если она установлена) на выбранном объекте');
				youtube = 0;
				ytB.setIconClass('tbar-youtubeP');
				sB.setIconClass('tbar-statP');
				sB.setTooltip('Статистика просмотров выбранного объекта');
				clip.disable();
				clip.setIconClass('clipP');
				infoPanelTpl.overwrite(Ext.getCmp('info_panel_tpl').body, {res_exist: false});
			}
		}
		
		
		if(myGMap.getCurrentMapParams().zoom>8){
			pB.setIconClass('tbar-panoA');
			pB.setTooltip('Нажмите, чтобы посмотреть фотографии с Panoramio окрестностей объекта. Чтобы убрать фотографии с карты нажмите повторно.');
		}else{
			pB.setIconClass('tbar-panoP');
			pB.setTooltip('Фотографии с Panoramio окрестностей выбранного объекта. Доступны при повышенных зумах карты');
		}
	});
	
	function render_annot(val){		
		return Ext.util.Format.nl2br(val);
	};
	myGrid = new Ext.grid.GridPanel({	
		frame:false,		
		margins:'0 5 0 5',
		flex:1,
		store: gridStore,		
		columns: [		
			{hidden:true, dataIndex: 'id'},
			{header: "Компания: ", dataIndex: 'company_name',width:150, renderer: render_annot},
			{header: "Аннотация: ", dataIndex: 'annot',width:300, renderer: render_annot}
		],
		viewConfig:{
			forceFit:true
		},
		listeners: {
			rowclick: onRowClick,
			rowmouseover: function(g, r){
				var rec = g.getStore().getAt(r);
				var rId = rec.get('id');
				if(myGMap.selMarker!==rId){
					myGMap.invMarkerIcon(rId);
				}
			},
			rowmouseout: function(g, r){
				var rec = g.getStore().getAt(r);
				var rId = rec.get('id');
				if(myGMap.selMarker!==rId){
					myGMap.mMarkerIcon(rId);
				}
			}
		}		
	});
	photoStore = new Ext.data.JsonStore({
        url: 'action.php',
        root: 'records',
		baseParams:{
			action:"photo",
			tname: 0,
			id: 0
		},		
        fields: ['file_name','file_large_name', 'description', 'annot', 'lat', 'lng', 'id', 'w', 'h']
    });
	photoStore.on("load", function(){
		if(gridStore.baseParams['clasterType']=="object"){
			// myGMap.map.clearOverlays();
			myGMap.setMarkers({tname:tname});
			if(myGMap.selMarker>-1) myGMap.chMarkerIcon(myGMap.selMarker);
			myGMap.setPhotoMarker();		
		}
	});
	
	var myGMapPanel = new Ext.Panel({
		region: 'center',
		border: false,
		width: 800,
		height: myHeight,
		bodyStyle:'padding:5 0 0 5',
		layout:'fit',
		items:[myGMap]
	});
	
	var quickLinkStore = new Ext.data.Store({
		url: 'action.php',
		baseParams: {action: "quickLink"},			
		reader: new Ext.data.JsonReader({
			root: 'records', 
			totalProperty: 'totalcount', 
			id: 'id',				
			fields: ['id', 'center', 'title', 'metaname', 'domen', 'metadescription']				
		}),
		remoteSort: true		
    });	
	quickLinkStore.load();
	var quickLink = new Ext.form.ComboBox({		
		store: quickLinkStore,		
		loadingText: 'Loading ... ',
		triggerAction:'all',
		mode: 'local',
		forceSelection: true,
		emptyText: 'Выберите субъект РФ',
		style: 'padding-right: 0px;',
		readOnly: false,
		editable: false,
		valueField: 'id',
		displayField: 'title',
		width: 150,
		listWidth: 200,
		minChars: 0,
		listeners:{
			select : function (c,r,i){
				var centerLatLng = r.get('center');				
				myGMap.map.setCenter(new GLatLng(eval(centerLatLng)[0],eval(centerLatLng)[1]), eval(centerLatLng)[2]);
			}
		}
	});
	var onCheckItemClick = function(){
		var dopVal = this.ownerCt.val.split(";");
		var strVal = [];
		if(this.checked){
			for(var i=0; i<dopVal.length; i++){
				if(dopVal[i]!==this.tname && dopVal[i]!=="") strVal[strVal.length] = dopVal[i];
			}
		}else{
			if(this.tname!=="") dopVal[dopVal.length] = this.tname;
			strVal = dopVal;
		}
		this.ownerCt.val = strVal.join(';');
		myGrid.getStore().baseParams['dopuslug'] = this.ownerCt.val;
		onItemClick({tname:this.ownerCt.tname, dopuslug: true});
	}

	var otdix = [
		{xtype: 'menumycheckitem', tname: 'bicycle_tour', iconCls1:'bike16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'excursion_tour', iconCls1:'bus16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'gliding', iconCls1:'delta16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'diving', iconCls1:'diving16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'eco_tour', iconCls1:'eco16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'fishing_tour', iconCls1:'fishing16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'pedestrian_tour', iconCls1:'hike16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'horse_tour', iconCls1:'horse16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'hunting_tour', iconCls1:'hunt16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'jipping', iconCls1:'jeep16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'mountain_tour', iconCls1:'mount16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'mount_ski_tour', iconCls1:'m-ski16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'pilgrim_tour', iconCls1:'pal16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'ski_tour', iconCls1:'ski16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'speleo_tour', iconCls1:'speleo16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'boating', iconCls1:'water16x16.png', handler: onCheckItemClick},
		{xtype: 'menumycheckitem', tname: 'yachts_tour', iconCls1:'yacht16x16.png', handler: onCheckItemClick}
	];
	var tBar = new Ext.Toolbar({
			items:[				
				{text: 'Отдых', 
					menu: {
						items: [
							{
								text: 'Санатории', tname: 'sanatorium', handler: onItemClick, iconCls:'san',
								menu:{ tname: 'sanatorium', items:otdix, val: '' }
							},
							{text: 'Дома отдыха', tname: 'rest_houses', handler: onItemClick, iconCls:'resthouse',
								menu:{ tname: 'rest_houses', items:otdix, val: '' }
							},
							{text: 'Коттеджи', tname: 'cottage', handler: onItemClick, iconCls:'house',
								menu:{ tname: 'cottage', items:otdix, val: '' }
							},
							{text: 'Турбазы', tname: 'camp_site', handler: onItemClick, iconCls:'camp',
								menu:{ tname: 'camp_site', items:otdix, val: '' }
							}
						]
					},
					handler: function(){return false;}
				},'-',	
				{text: 'Спорт/экстрим',
					menu: {
						items: [
							{text: 'Пеший туризм', tname: 'pedestrian_tour', handler: onItemClick, iconCls:'hike'},
							{text: 'Водный туризм', tname: 'boating', handler: onItemClick, iconCls:'water'},
							{text: 'Яхты и парусный спорт', tname: 'yachts_tour', handler: onItemClick, iconCls:'yacht'},
							{text: 'Горный туризм', tname: 'mountain_tour', handler: onItemClick, iconCls:'mount'},
							{text: 'Лыжный туризм', tname: 'ski_tour', handler: onItemClick, iconCls:'ski'},
							{text: 'Спелеотуризм', tname: 'speleo_tour', handler: onItemClick, iconCls:'speleo'},
							{text: 'Конный туризм', tname: 'horse_tour', handler: onItemClick, iconCls:'horse'},
							{text: 'Велосипедный туризм', tname: 'bicycle_tour', handler: onItemClick, iconCls:'bike'},
							{text: 'Дайвинг', tname: 'diving', handler: onItemClick, iconCls:'diving'},
							{text: 'Планеризм', tname: 'gliding', handler: onItemClick, iconCls:'delta'},
							{text: 'Джиппинг', tname: 'jipping', handler: onItemClick, iconCls:'jeep'}
						]
					},
					handler: function(){return false;}
				},'-',	
				{text: 'Рыболовство/охота', 
					menu: {
						items: [
							{text: 'Рыболовные туры', tname: 'fishing_tour', handler: onItemClick, iconCls:'fishing'},
							{text: 'Охотничьи туры', tname: 'hunting_tour', handler: onItemClick, iconCls:'hunt'}					                        
						]
					},
					handler: function(){return false;}
				},'-',	
				{text: 'Горнолыжные туры', tname: 'mount_ski_tour', handler: onItemClick, iconCls:'m-ski'},	'-',	
				{text: 'Экскурсии', tname: 'excursion_tour', handler: onItemClick, iconCls:'bus'},'-',	
				{text: 'Паломнические туры', tname: 'pilgrim_tour', handler: onItemClick, iconCls:'pal'},'-',					
				{text: 'Экотуризм', tname: 'eco_tour', handler: onItemClick, iconCls:'eco'}, 
				'-',					
				//{text:'Участники',handler: rieltorsWindow, disabled:true},
				{text:'Форум',handler: function(){ window.open('http://maprest.ru/smf/'); }, iconCls:'forum'},
				'-',
				{text:'О проекте' , 
					handler: function(){
						var w = new Ext.Window({
							width: 450,
							title: 'О проекте',
							html: '<div style="margin-left: 5px; margin-right: 5px; margin-top: 10px; margin-bottom: 10px;"><b>Размещение информации:</b><br>Размещение информации по объектам туризма бесплатно.<br>Информация от физических лиц к размещению не принимается.<br>По вопросам размещения информации и по другим вопросам просьба обращаться по адресу электронной почты: <a href="mailto:support@marq.ru">support@marq.ru</a><br><br><b>Реклама на сайте:</b><br>Размещение рекламы на сайте бесплатно.<br>На сайте размещается реклама, соответствующая тематике сайта.<br>К размещению принимаются баннеры в графических форматах размером 468х60 пкс.<br>Администрация сайта оставляет за собой право устанавливать периодичность показа размещаемых баннеров.<br></div>'
						});
						w.show();
					}
				}, '->', 'Быстрый переход: ',	quickLink
			]
		});
		
	
	var searchPanelTpl = new Ext.XTemplate(
		'<div style="height:40px; font-family: tahoma,verdana,helvetica; font-size: 11px;">',
			'<tpl if="res_exist == true">',
				'<p style="font-size: 13px;"><b>Категория объектов:</b> <i>{object_type}</i> <br /> <b>Всего найдено объектов:</b> <i>{total}</i></p>',
			'</tpl>',
			'<tpl if="res_exist == false">',
				'<p style="font-size: 11px;">Hет данных для отображения</p>',
			'</tpl>',
		'</div>'
	);
	
	var searchPanel =new Ext.Panel({	
		id: 'sixth_grid_tpl',
		margins:'5 5 5 5',
		items:[searchPanelTpl]
	});
	
    photoStore.load();
	
	var photoPanelTpl = new Ext.XTemplate(
		'<tpl for=".">',
            '<div class="thumb-wrap" id="{file_name}">',
		    '<div class="thumb"><img src="photos/preview/{file_name}" qtip="{description}" onMouseOver="photoOverOut({id}, true)" onMouseOut="photoOverOut({id}, false)" onClick="ObjectImageView(\'{file_large_name}\', \'{annot}\', \'{id}\',{w},{h})"></div>',
		    '<span>{annot}</span></div>',
        '</tpl>',
        '<div class="x-clear"></div>'
	);
	photoPanelTpl.compile();
	dwPhoto = new Ext.DataView({
				store: photoStore,
				tpl: photoPanelTpl,            
				overClass:'x-view-over',
				itemSelector:'div.thumb-wrap',
				emptyText: '',
				prepareData: function(data){
					data.annot = Ext.util.Format.ellipsis(data.annot, 20);					
					return data;
				}
			});
	var photoPanel = new Ext.Panel({
		id:'images-view',
		width: 320,
		margins:'5 5 5 5',	
		layout:'fit',
		items: [{			
			autoScroll:true,
			border:false,
			items: dwPhoto
		}]
	});
	
	var infoPanelTpl = new Ext.XTemplate(
		'<tpl if="res_exist == true">',
			'<div style="height: 200px;">',				
				'<table style="font-family: tahoma,verdana,helvetica; font-size: 11px;"  cellspacing="10%" cellpadding="10%">' ,
					'<tr>' ,
						'<td style="width: 600px;">' ,
							'<table style="font-family: tahoma,verdana,helvetica; font-size: 11px; cellpadding:3px;">' ,								
								'<tr>' ,
									'<td>{description}</td>' ,
								'</tr>' ,						
							'</table>' ,
						'</td>' ,
						'<td valign="top">' ,					
						'</td>' ,
					'</tr>' ,
				'</table><table style="font-family: tahoma,verdana,helvetica; font-size: 11px;" cellspacing="10%" cellpadding="10%">',	
					'<tr>',					
						'<td><img src="admin/logos/{logo}"></td>',
						'<td valign=top><p><b>Компания:</b> {company_name}</p>',						
						'<p><b>Адрес:</b> {adress} </p>',
						'<p><b>Телефон:</b> {tel} </p>',
						'<p><b>e-mail:</b> <a href="mailto:{email}"> {email} </a></p>',
						'<p><b>сайт:</b> <a href="{site}" target="_blank"> {site} </a></p></td>',
					'</tr>',
				'</table>',
			'</div>',
		'</tpl>',
		'<tpl if="res_exist == false">',
			'<div style="font-family: tahoma,verdana,helvetica; font-size: 11px;height: 200px;">Нет данных для отображения</div>',
		'</tpl>'	
	);
	
	var ytButtonHandler = function(){
		var videoStore = new Ext.data.JsonStore({
			url: 'action.php',
			root: 'records',
			totalProperty: 'total',
			baseParams:{
				action:"videoList",
				tname: 0,
				id: 0
			},
			fields: ['id', 'video_id', 'url', 'annot']
		});
		
		var videoPanelTpl = new Ext.XTemplate(
			'<tpl for=".">',
				'<div class="thumb-wrap" id="{video_id}">',
				'<tpl if="video_id==0">',
				'<div class="thumb"><img src="../images/no_foto.jpg" title=""></div>',
				'</tpl>',
				'<tpl if="video_id!=0">',
				'<div class="thumb"><img src="{url}" title=\'{annot}\'></div>',
				'<span>{video_id}</span>',
				'</tpl></div>',
			'</tpl>',
			'<div class="x-clear"></div>'
		);
		videoPanelTpl.compile();
		
		var videoPanel = new Ext.Panel({
			id:'videos-view',
			region: 'center',
			margins:'5 5 5 5',
			layout:'fit',
			items: {
				autoScroll:true,
				border:false,
				items: new Ext.DataView({
					id:'videoPanel_dataView',
					store: videoStore,
					tpl: videoPanelTpl,
					overClass:'x-view-over',
					singleSelect: true,
					itemSelector:'div.thumb-wrap',
					emptyText: '',
					prepareData: function(data){
						data.annot = Ext.util.Format.ellipsis(data.annot, 50);
						return data;
					},
					listeners:{
						click: function(t,i,n,e){
							var rec = t.getRecord(n);
							if(rec&&rec.get('id')){
								var video_id = rec.get('video_id');
								var annot = rec.get('annot');
								youtubeView(video_id, annot);
							}else Ext.Msg.alert('','Выберите видеоролик.');
						}
					}
				})
			}
		});
		
		videoWindow = new Ext.Window({
			id:'videoWindow',
			title: 'Список видео',
			x:0, y:0,
			height: 700,			
			width:150,
			closeable:true,
			resizable:false,
			border: false,				
			layout:'border',
			items: videoPanel,
			listeners:{
				move:onMove,
				close: function(){
					var win = Ext.getCmp('youtube-video');
					if(win) win.close();
				}
			}
		});					
		videoStore.baseParams["tname"] = tname;
		videoStore.baseParams["id"] = myGMap.selMarker;
		videoWindow.show();
		videoStore.reload();
	};
	
	infoPanelToolBar = new Ext.Toolbar({
		id:'infoPanelToolBar',
		items:[
			{
				xtype:'button'
				,id: 'panoButton'
				,iconCls: 'tbar-panoP'
				,handler: function(b,e){
					myGMap.PanoramEnable = !myGMap.PanoramEnable;
					chiz();
				}
				,tooltip:'Фотографии с Panoramio окрестностей выбранного объекта. Доступны при повышенных зумах карты'
			}
			,'&nbsp;&nbsp;'
			,{
				xtype:'button'
				,id: 'YaPogodaButton'
				,iconCls: 'tbar-weatherP'
				,handler: function(b,e){}
				,tooltip: 'Погода в районе выбранного объекта'
				,listeners:{
					mouseover: function(b,e){
						if(cityCode){
							YaPogodaPanel = new Ext.Panel({
								html:	'<a target="_blank" href="http://clck.yandex.ru/redir/dtype=stred/pid=7/cid=1228/'+
										'*http://weather.yandex.ru/index.xml?city='+cityCode+'">'+
										'<img src="http://info.weather.yandex.net/informer/200x100/'+cityCode+'.png" '+
										'border="0" alt="Яндекс.Погода"/><img width="1" height="1" '+
										'src="http://clck.yandex.ru/click/dtype=stred/pid=7/cid=1227/*http://img.yandex.ru/i/pix.gif" '+
										'alt="" border="0"/></a>'
							});
							var pos = b.getPosition();
							var YaPogodaWin = Ext.getCmp('YaPogodaWin');
							if(YaPogodaWin) YaPogodaWin.close();
							YaPogodaWin = new Ext.Window({
								id:'YaPogodaWin',
								width:215,
								height:135,
								title: 'Яндекс погода',
								resizable: false,
								items:YaPogodaPanel
							});
							YaPogodaWin.setPosition(pos[0], pos[1]-150);
							YaPogodaWin.show();
						}
					},
					mouseout: function(b,e){
						if(cityCode) setTimeout('Ext.getCmp("YaPogodaWin").close()', 2000);
					}				
				}
			}
			,'&nbsp;&nbsp;'
			,{
				xtype:'button'
				,id: 'webcamButton'
				,iconCls: 'tbar-webcamP'
				,tooltip: 'Изображение с вэб-камеры (если она установлена) на выбранном объекте'
				,handler: function(b,e){
					if(webcam){
						var selRec = myGrid.getSelectionModel().getSelected();
						Ext.Ajax.request({
							url:'action.php',
							params:{ action: 'imgsize', fileurl: selRec.get('webcam')},
							success: function(res,opts){
								var p=Ext.decode(res.responseText); 
								var w=parseInt(p['w']), h=parseInt(p['h']);
								if(w&&h) WebCamView(selRec.get('webcam'),w,h);
							}
						});
					}
				}
			}
			,'&nbsp;&nbsp;'
			,{					
				xtype:'button'
				,id: 'youtubeButton'
				,iconCls: 'tbar-youtubeP'
				,text: '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
				,tooltip: 'Посмотреть видео из YouTube'
				,handler: function(b,e){
					var win = Ext.getCmp('videoWindow');
					if(win) win.close();
					else if(youtube>0) ytButtonHandler();					
				}
			}
			,'&nbsp;&nbsp;'
			,{					
				xtype:'button'
				,id: 'statButton'
				,iconCls: 'tbar-statP'
				,tooltip: 'Статистика просмотров выбранного объекта'
				,handler: function(b,e){}
			},{					
				xtype:'button'
				// ,text: 'Доп. инфо'
				,id: 'dopInfobtn'
				,iconCls: 'clipP'
				,disabled: true
				,tooltip: 'Дополнительная информация об объекте'
				,handler: function(b,e){
					var dopInfoWin = Ext.getCmp('dopInfo');
					if(dopInfoWin) dopInfoWin.close();
					dopInfoWin = new Ext.Window({
						id:'dopInfo'
						,width:400
						,height:'auto'
						,title: 'Дополнительная информация'
						,layout:'fit'
						,html: '<div style="padding: 10px; background: white; height: 100%;"> ' + dopinfo + ' </div>'
					});
					dopInfoWin.show();
				}
			}
		]
	});
	
	
	var infoPanel =new Ext.Panel({	
		id: 'info_panel_tpl'
		//,title:'Описание'
		,tbar: infoPanelToolBar
		,margins:'5 5 5 0'
		,autoScroll: true
		,flex:1
		,items:[infoPanelTpl]
	});	
	
	var viewport = new Ext.Viewport({
		layout: 'border',
		border:false,	
		frame:false,
		items: [{
			region: 'north',
			xtype: 'panel',
			height:125,
			border:false,
			bodyStyle:'padding:5 5 0 5',
			items:[{
				border: false, bodyBorder: false,
				html: '<div style="float:left; width: 100%; height:90px; background: url(images/bgn.jpg);"><img src="images/header.jpg">'+
				'<div class="kroxus">разработка <a href="http://kroxus.ru" target="_blank">Kroxus Software</a>'+
				'<br><a href="http://top100.rambler.ru/home?id=1873405" target="_blank"><img src="http://top100-images.rambler.ru/top100/w9.gif" alt="Rambler\'s Top100" width="88" height="31" border="0" /></a>'+
				'</div></div>'
			}, tBar ]
		}, myGMapPanel, 
		{
			region: 'east',			
			width:481,
			border: false,
			xtype: 'panel',
			layout:'vbox',
			layoutConfig: {
				align : 'stretch',
				pack  : 'start'
			},
			items: [searchPanel, myGrid]
		},{
			region: 'south',
			xtype: 'panel',						
			height: 240,
			border: false,
			layout:'hbox',			
			layoutConfig: {
				align : 'stretch',
				pack  : 'start'
			},
			items: [ photoPanel, infoPanel,			
			{
				html:'<div style="width: 100%; height:70px; background:"><center>'+
					'<script language="JavaScript"> var loc = ""; alert(0);</script>'+
					'<script language="JavaScript1.4">try{ var loc = escape(top.location.href); }catch(e){;}</script>'+
					'<script language="JavaScript">document.write("<sc"+"ript language=\'JavaScript\' src=\'http://ad3.bannerbank.ru/bb.cgi?cmd=ad&hreftarget=_blank&pubid=162598348&pg=1&r=js&ssi=nofillers&vbn=456&num=1&w=468&h=60&&ref="+escape(document.referrer)+"&loc="+loc+"&nocache="+Math.round(Math.random()*999111)+"\'>\n</sc"+"ript>");</script>'+
					'<br></center>'+
					'<center><FONT SIZE=1><A HREF="http://go.bb.ru/enter.html" target = "_top" > Туристическая баннерная сеть</A></FONT></center></div>'+
					'<div style="width: 100%; height:70px; background:"><img src="images/banner.jpg"></div>'+
					'<div style="width: 100%; height:70px; background:"><img src="images/banner.jpg"></div>', 
				//title:'Место для рекламы',
				margins:'5 5 5 0',
				border:true,
				width:471
			}]			
		}]
	});	
	if(GMapApiEnable){
		var myHeight=document.body.offsetHeight-375;
		myGMap = new Ext.ux.GMapPanel({
			border:true,
			width: 'auto',
			height: myHeight,
			gMapStore: gridStore,
			gMapPhStore: photoStore,
			gMapPanoStore: panoramStore,
			PanoramEnable: false,
			grid: myGrid,
			callback: function(){
				chiz();
			},
			listeners: {
				resize: function(p, w, h){
					if(p.map){
						p.map.checkResize();						
					}
				}
			}
		});
		myGMapPanel.removeAll();
		myGMapPanel.add(myGMap);
	}
	
	searchPanelTpl.overwrite(Ext.getCmp('sixth_grid_tpl').body, {res_exist: false});
	infoPanelTpl.overwrite(Ext.getCmp('info_panel_tpl').body, {res_exist: false});
};

