function preloader(){
	var i = 0;imageObj = new Image();images = new Array();
	images[0]="/static/images/ajax1.gif";
	images[1]="/static/images/ajax2.gif";
	for(i=0; i<=images.lenght; i++)imageObj.src=images[i];
	
	CreateCityList();
}
function gid(idName) {
	return document.getElementById(idName);
}

function replace(search, replace, subject){
	var ra = replace instanceof Array,
		sa = subject instanceof Array,
		l = (search = [].concat(search)).length,
		replace = [].concat(replace),
		i = (subject = [].concat(subject)).length;
	while(j = 0, i--)
		while(subject[i] = subject[i].split(search[j]).join(ra ? replace[j] || "" : replace[0]), ++j < l);
	return sa ? subject : subject[0];
}

function padZero(n) {
	n = "00" + n;
	return n.substring(n.length - 2);
}

var update_datetime_on_page_months = new Array ("января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря");
var update_datetime_on_page_u = false;
var ServerTime = false;
var TimerTime = 0;
function update_datetime_on_page() {
	if (ServerTime == false) {
		ServerTime = new Date(document.getElementById('serverTime').innerHTML);
	}
	TimerTime+=1000;
	var Now = new Date();
	Now.setTime(ServerTime.getTime()+TimerTime);
	if (update_datetime_on_page_u == false) update_datetime_on_page_u = true;
	else update_datetime_on_page_u = false;
	var t;
	if (update_datetime_on_page_u) t = ':';
	else t = ' ';
	gid('suTime').innerHTML = padZero(Now.getHours())+t+padZero(Now.getMinutes());
	gid('suDate').innerHTML = Now.getDate()+' '+update_datetime_on_page_months[Now.getMonth()];
}
var update_datetime_on_page_t = window.setInterval("update_datetime_on_page();", 1000);


var preInputArray = new Array();
function preInputClick(n){
	preInputMove(n);
	preInputArray[ n ]['click'] = 1;
}
function preInputMove(n){
	if( typeof preInputArray[ n ] == 'undefined' ) {
		i = gid( 'preInput_' + n );
		preInputArray[ n ] = new Array();
		preInputArray[ n ]['value'] = i.value;
		preInputArray[ n ]['color'] = i.style.color;
		preInputArray[ n ]['style'] = i.style.fontStyle;
		i.value = '';
		i.style.color = '#234';
		i.style.fontStyle = 'normal';
	}
}
function preInputOut(n){
	i = gid( 'preInput_' + n );
	if( typeof preInputArray[ n ] != 'undefined' && i.value == '' && typeof preInputArray[ n ]['click'] == 'undefined' ) {
		i.value = preInputArray[ n ]['value'];
		i.style.color = preInputArray[ n ]['color'];
		i.style.fontStyle = preInputArray[ n ]['style'];
		preInputArray[ n ] = undefined;
	}
}

function CreateCityList(){
	var text;
	 text = '<ul>';
	 
	 text += '<li><a href="/msk/">Москва</a></li>';
	 text += '<li><a href="/spb/">Санкт-Петербург</a></li>';
	 text += '<li><a href="/ekb/">Екатеринбург</a></li>';
	 text += '<li><a href="/prm/">Пермь</a></li>';
	 text += '<li><a href="/volgograd/">Волгоград</a></li>';
	 text += '<li><a href="/izh/">Ижевск</a></li>';
	 text += '<li><a href="/kzn/">Казань</a></li>';
	 text += '<li><a href="/kaliningrad/">Калининград</a></li>';
	 text += '<li><a href="/krasnodar/">Краснодар</a></li>';
	 text += '<li><a href="/krasnoyarsk/">Красноярск</a></li>';
	 text += '<li><a href="/murmansk/">Мурманск</a></li>';
	 text += '<li><a href="/nnovgorod/">Нижний Новгород</a></li>';
	 text += '<li><a href="/nsk/">Новосибирск</a></li>';
	 text += '<li><a href="/omsk/">Омск</a></li>';
	 text += '<li><a href="/rnd/">Ростов-на-Дону</a></li>';
	 text += '<li><a href="/samara/">Самара</a></li>';
	 text += '<li><a href="/saratov/">Саратов</a></li>';
	 text += '<li><a href="/sochi/">Сочи</a></li>';
	 text += '<li><a href="/ufa/">Уфа</a></li>';
	 text += '<li><a href="/chelyabinsk/">Челябинск</a></li>';

	 text += '</ul>';
	 gid("changecityd").innerHTML = text;
}

function UpdateCaptcha(){
	gid('captchaIMG').src = '/captcha.php?r=' + Math.random();
}

function isArray(o) {
	return Object.prototype.toString.call(o) == '[object Array]';
}

function isObject(o) {
	return Object.prototype.toString.call(o) == '[object Object]';
}

var _AjaxStyles = Array();
var _AjaxRunning = Array();
var _AjaxXML = Array();

function Ajax(url, locked, ajaxID, ajaxType, resultID){
	
	url = url.replace(/&amp;/g, '&');
	sep = ( url.indexOf('?') + 1 ) ? '&' : '?';
	url = url + sep + 'rj=' + Math.random();
	
	if ( locked ) {
		
		if ( typeof _AjaxRunning[resultID] != 'undefined' && _AjaxRunning[resultID] == true )
			return;
		_AjaxRunning[resultID] = true;
		
	}
	
	ExecFunction = arguments[5] || false;
	ArrayPost = arguments[6] || false;
	
	sendData = new Array();
	
	if ( isArray(ArrayPost) || isObject(ArrayPost) ) {
		
		for ( var k in ArrayPost ) {
			push = k + '=' + encodeURIComponent( ArrayPost[ k ] );
			sendData.push( push );
		};
		
	} else {
		
		for ( var i = 6; i < arguments.length; i++ ) {
			
			elem = gid( arguments[i] );
			
			if ( elem ) {
				if ( elem.type == 'checkbox' )
					value = ( elem.checked != false ) ? 1 : 0;
				else value = elem.value;
			}
			else value = 0;
			
			push = arguments[i] + '=' + encodeURIComponent( value );
			sendData.push( push );
			
		}
		
	}
	
	sendData = sendData.join('&');
	
	
	_AjaxXML[resultID] = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try {
		_AjaxXML[resultID] = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			_AjaxXML[resultID] = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e2) {
			_AjaxXML[resultID] = false;
		}
	}
	@end @*/
	if (!_AjaxXML[resultID] && typeof XMLHttpRequest != 'undefined') {
		_AjaxXML[resultID] = new XMLHttpRequest();
	}
	
	if ( sendData != false ) {
		_AjaxXML[resultID].open("POST", url, true);
		_AjaxXML[resultID].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	} else {
		_AjaxXML[resultID].open("GET", url, true);
	}
	
	_AjaxXML[resultID].onreadystatechange = function(){AjaxComplete(ajaxID, resultID, ExecFunction);};
	
	if ( sendData != false ) {
		_AjaxXML[resultID].send( sendData );
	} else {
		_AjaxXML[resultID].send( null );
	}
	
	if ( ajaxID != false )
		AjaxInsertImage( ajaxID, ajaxType );
	
}

function AjaxInsertImage (id, type) {
	type = ( type == 'small' ) ? 2 : 1;
	elem = gid( id );
	elem.innerHTML = '';
	if ( typeof _AjaxStyles[id] == 'undefined' ) {
		_AjaxStyles[id] = Array();
		_AjaxStyles[id]['va'] = elem.style.verticalAlign;
		_AjaxStyles[id]['back'] = elem.style.background;
		_AjaxStyles[id]['bcol'] = elem.style.backgroundColor;
		_AjaxStyles[id]['disp'] = elem.style.display;
		_AjaxStyles[id]['w'] = elem.style.width;
		_AjaxStyles[id]['h'] = elem.style.height;
		_AjaxStyles[id]['m'] = elem.style.margin;
	}
	elem.style.verticalAlign = 'middle';
	elem.style.background = "#fff url('/static/images/ajax" + type + ".gif') center center no-repeat";
	elem.style.display = 'inline-block';
	elem.style.width = '40px';
	elem.style.height = ( type == 1 ) ? '25px' : '15px';
	elem.style.margin = '0px 5px';
}

function AjaxRemoveImage (id) {
	elem = gid( id );
	elem.innerHTML = '';
	elem.style.verticalAlign = _AjaxStyles[id]['va'];
	elem.style.background = _AjaxStyles[id]['back'];
	elem.style.backgroundColor = _AjaxStyles[id]['bcol'];
	elem.style.display = _AjaxStyles[id]['disp'];
	elem.style.width = _AjaxStyles[id]['w'];
	elem.style.height = _AjaxStyles[id]['h'];
	elem.style.margin = _AjaxStyles[id]['m'];
	delete _AjaxStyles[id];
}

function AjaxComplete(ajaxID, resultID, ExecFunction) {
	
	debug = true;
	
	if ( typeof _AjaxXML[resultID] != 'undefined' && _AjaxXML[resultID].readyState == 4 ) {
		
		if ( ajaxID != false )
			AjaxRemoveImage( ajaxID );
		_AjaxRunning[resultID] = false;
		
		if ( _AjaxXML[resultID].status == 200 ) {
			
			r = gid( resultID );
			
			var Response = json_parse( _AjaxXML[resultID].responseText );
			if ( Response == false ) {
				
				if ( r ) {
				if ( debug )
					r.innerHTML = _AjaxXML[resultID].responseText;
				else
					r.innerHTML = '<span class="error">'
					+ 'Ajax error: Сбой при передаче</span>';
				}
				
			} else {
				
				redirect = Response[0] || false;
				
				if ( redirect != false ) location.replace( redirect );
				
				insertHTML = Response[2] || false;
				
				if ( r ) {
					var IE='\v'=='v';
					if ( IE ) {
						var el = document.createElement('div');
						el.innerHTML=insertHTML;
						r.innerHTML = '';
						r.appendChild(el);
					}
					else r.innerHTML = insertHTML;
				}
				
				if ( Response[2].indexOf('<script') != -1 ) {
					collection = r.getElementsByTagName("SCRIPT");
					for( i = 0; i < collection.length; i++ ){
						eval( collection[ i ].innerHTML );
					}
				}
				
				if ( ExecFunction != false ) ExecFunction( Response[1] );
				
			}
			
		} else {
			
			if ( gid( resultID ) ) {
				gid( resultID ).innerHTML = '<span class="error">'
					+ 'Ajax error: ' + _AjaxXML[resultID].status + '. ' + _AjaxXML[resultID].statusText
					+ '</span>';
			}
			
		}
	
		delete _AjaxXML[resultID];
		
	}
	
}

function AjaxError(data, name, aname) {
	gid( aname ).innerHTML = '';
	info = data[name] || false;
	if ( info != false ) {
		gid( aname ).innerHTML = info;
		return false;
	} else return true;
}



// Places ==============================
var tmr_ShowPlace;
var tmr_AnimePlace;
var tmr_ClosePlace;
var id_ShowPlace = false;
var bOpenedPlace = false;
var bClosePlace = false;

function DelayPlace(id){
	bClosePlace = false;
	
	clearTimeout(tmr_ClosePlace);
	
	if ( id == id_ShowPlace ) return;
	
	clearTimeout(tmr_AnimePlace);
	
	bOpenedPlace = false;
	if ( id_ShowPlace != false ) ClosePlace();
	
	bOpenedPlace = true;
	id_ShowPlace = id;
	tmr_ShowPlace = setTimeout("ShowPlace()", 500);
}
function ShowPlace(){
	if ( bClosePlace == true ) {
		ClosePlace();
		return;
	}
	bOpenedPlace = false;
	
	elem = gid('pl_' + id_ShowPlace);
	if ( !elem ) {
		ClosePlace();
		return;
	}
	img = elem.getElementsByTagName('img')[0];

	elem.style.display='block';
	img.style.width = 120 + 'px';
	
	AnimePlace();
}
function dClosePlace(){
	if ( bOpenedPlace == true ) {
		bClosePlace = true;
		return;
	}
	tmr_ClosePlace = setTimeout("ClosePlace()", 100);
}
function ClosePlace(){
	if ( id_ShowPlace != false ) {
		elem = gid('pl_' + id_ShowPlace);
		if ( elem ) {
			img = elem.getElementsByTagName('img')[0];
			elem.style.display='none';
			elem.style.width = '120px';
			img.style.width = 120 + 'px';
			elem.style.left = 0;
			elem.style.top = 0;
		}
		
		clearTimeout(tmr_ShowPlace);
		clearTimeout(tmr_AnimePlace);
		clearTimeout(tmr_ClosePlace);
		id_ShowPlace = false;
		bOpenedPlace = false;
		bClosePlace = false;
	}
}
function AnimePlace(){
	elem = gid( 'pl_'+ id_ShowPlace );
	if ( !elem ) {
		ClosePlace();
		return;
	}
	img = elem.getElementsByTagName('img')[0];
	
	i = img.width + 10;
	j = img.height;
	elem.style.width = i + 'px';
	img.style.width = i + 'px';

	elem.style.left = -((i - 120) / 2) + 'px';
	elem.style.top = -((j - 90) / 2) + 'px';
	
	if ( i < 150 )
		tmr_AnimePlace = setTimeout("AnimePlace()", 20);
	else {
		img.style.width = 'auto';
		img.style.height = 'auto';
		bOpenedPlace = false;
		bClosePlace = false;
	}
}



function ClearHtml(name) {
	gid(name).innerHTML = '&nbsp;';
}

function Districts(id) {
	Ajax('/ajax.php?action=districts&id='+id,true,'aDistricts','small','Districts',false);
}
function Metro(id) {
	Ajax('/ajax.php?action=metro&id='+id,true,'aMetro','small','Metro',false);
}
function PlaceSub(id, sid, name) {
	Ajax('/ajax.php?action=placesub&id='+id+'&sid='+sid,true,'aPlaceSub_'+name,'small','PlaceSub_'+name,false);
}

function detectIE6(){
	var browser = navigator.appName;
	
	if (browser == "Microsoft Internet Explorer"){
		
		var b_version = navigator.appVersion;
		var re = /\MSIE\s+(\d\.\d\b)/;
		var res = b_version.match(re);
		if (res[1] <= 6) return true;
		
	}
	
	return false;
}

var Places = {
	city: false,
	section: false,
	start: 0,
	sort: 'rating',
	order: 0,
	vsort: 0,
	sub: new Array(),
	addSub: function(name, variable){
		if ( this.sub[ name ] != variable ) {
			this.sub[ name ] = variable;
			this.reload();
		}
	},
	reload: function(){
		this.start = 0;
		ClosePlace();
		Ajax(this.geturl(), false, 'aFilter', 'normal', 'AllPlaces', false);
	},
	load: function(Flag, Start){
		this.start = Start;
		var url = this.geturl() + '&loadpage=1';
		Ajax(url, true, 'amore_'+Flag, 'small', 'more_'+Flag, false);
	},
	geturl: function(){
		var subs = new Array();
		for( var key in this.sub )
			subs.push( '&' + key + '=' + encodeURIComponent(this.sub[key]) );
		var substr = subs.join('');
		
		return '/ajax.php?action=places&city=' + this.city +
			'&section=' + this.section + '&start=' + this.start +
			'&sort=' + this.sort + '&order=' + this.order +
			'&vsort=' + this.vsort + substr;
	},
	setSort: function(name){
		if ( this.sort == name ) {
			this.order = ( this.order == 1 ) ? 0 : 1;
		} else {
			this.sort = name;
			this.order = ( name == 'name' || name == 'check' ) ? 1 : 0;
		}
		this.vsort = 1;
		this.reload();
	},
	clear: function(name){
		if ( typeof this.sub[ name ] != 'undefined' ) {
			delete this.sub[ name ];
			if ( name == 'name' ) gid('preInput_filtr').value = '';
			this.reload();
		}
	},
	clearSort: function(){
		if ( this.sort == 'rating' && this.order == 0 ) return;
		this.sort = 'rating';
		this.order = 0;
		this.vsort = 0;
		this.reload();
	}
}


function RatingVote(vote, sub, id) {
	Ajax('/ajax.php?action=rating&id='+id+'&vote='+vote+'&sub='+sub,true,'aRating','small','aRating',false);
}

function igoVote(modul, id) {
	Ajax('/ajax.php?action=igo&modul='+modul+'&id='+id,true,'iGoForm','small','iGoForm');
}

function myplaceVote(id) {
	Ajax('/ajax.php?action=myplace&id='+id,true,'myplaceForm','small','myplaceForm');
}

function LoadDesc(elem, id) {
	var func = function(){ResetNavBox(elem);};
	Ajax('/ajax.php?action=desc&id='+id,false,'aNavBox','small','navBox',func);
}

function LoadUserBox(elem, box, id) {
	var func = function(){ResetNavBox(elem);};
	Ajax('/ajax.php?action=userbox&box='+box+'&id='+id,false,'aNavBox','small','navBox',func);
}

function delUplace(id) {
	Ajax('/ajax.php?action=deluplace&id='+id,true,'aUplace'+id,'small','aUplace'+id);
}

function userAction(type,id) {
	Ajax('/ajax.php?action=useraction&type='+type+'&id='+id,true,'aUmodify'+id,'normal','Umodify'+id);
}

function AddFriend(id) {
	Ajax('/ajax.php?action=addfriend&id='+id,true,'aUserMenu','small','aUserMenu');
}

function RemoveFriend(id) {
	Ajax('/ajax.php?action=useraction&type=remove&id='+id,true,'aUserMenu','small','aUserMenu');
}

function NewMessage(id,aid) {
	Ajax('/ajax.php?action=newmessage&id='+id,true,aid,'small','aUserMenu');
}

function NewMessageSend(id) {
	Ajax('/ajax.php?action=newmessage&id='+id,true,'aNewMsgSend','small','aUserMenu',false,'newMessage','newMsgSubject');
}

function MessageDelete(id) {
	Ajax('/ajax.php?action=messagedelete&id='+id,true,'aMsgRead'+id,'normal','MsgRead'+id);
}

function MessageRead(id) {
	var func = function(){gid('MsgReadSpan'+id).className='box'};
	Ajax('/ajax.php?action=newmessage&id='+id+'&re=1',true,'aMsgRead'+id,'small','aUserMenu',func);
}

function LoadModDesc(id) {
	var vars = {
		'id': id,
		'cid': gid('modDescCID').value,
		'modul': gid('modDescModul').value
	};
	Ajax('/ajax.php?action=modifydesc',false,'aNavBox','small','DescEdit',false,vars);
}

function SaveModDesc() {
	var vars = {
		'id': gid('modDescID').value,
		'cid': gid('modDescCID').value,
		'modul': gid('modDescModul').value,
		'newname': gid('newNameDesc').value,
		'newdesc': gid('newDescDesc').value,
		'submitsave': 1
	};
	Ajax('/ajax.php?action=modifydesc',true,'aSubmitModDesc','small','DescEdit',false,vars);
}

function DelModDesc() {
	var vars = {
		'id': gid('modDescID').value,
		'cid': gid('modDescCID').value,
		'modul': gid('modDescModul').value,
		'submitdelete': 1
	};
	Ajax('/ajax.php?action=modifydesc',true,'aNavBox','small','DescEdit',false,vars);
}

function modSaveSubs(id) {
	
	var checks = document.getElementsByName('sub_'+id);
	var c = checks.length;
	var a = [];
	
	for( var i=0; i < c; i++ ) {
		
		if ( checks[i].type == 'checkbox' && checks[i].checked != false )
			a.push( checks[i].value );
		
	}
	
	a = a.join(',');
	
	var vars = {
		'namesub': id,
		'newsubs': gid('newsubs_'+id).value,
		'vars': a
	};
	Ajax('?action=savesubs',true,'amodSubs'+id,'small','modSubs'+id,false,vars);
	
}

function LoadEventsOnDesc(elem, City, Sec, Vi, Place) {
	var func = function(){ResetNavBox(elem);};
	Ajax('/ajax.php?action=events&city='+City+'&section='+Sec+'&view='+Vi+'&place='+Place,false,'aNavBox','small','navBox',func);
}

function DelMetro(id) {
	Ajax('?action=delmetro&idmetro='+id,false,'aMetro','small','Metro',false);
}

function ResetNavBox(elem) {
	var li = elem.parentNode;
	var list = li.parentNode.childNodes;
	for(var i=0; i < list.length; i++)
		if ( 1 == list[i].nodeType && list[i].id != 'aNavBox' )
			list[i].className = 'tab';
	li.className = 'seltab';
}



function commentReply(elem, user) {
	
	var r = false;
	var comment = elem.parentNode.parentNode;
	var list = comment.childNodes;
	for(var i=0; i < list.length; i++)
		if ( 1 == list[i].nodeType && list[i].className == 't' )
			 r = list[i].textContent||list[i].innerText;
	
	if ( r != false ) bbField[0].Insert('quote', user, r);
	
}

function LoadComments(modul, id, all) {
	Ajax('/ajax.php?action=getcomments&modul='+modul+'&id='+id+'&allcomments='+all,true,'aComments','small','Comments',false);
}

function ModifyComment(id) {
	Ajax('/ajax.php?action=modcomment&id='+id,true,'aComment_'+id,'small','Comment_'+id,false);
}

function ModifyCommentEdit(id) {
	var vars = {
		'edittext': gid('commentText_'+id).value
	};
	Ajax('/ajax.php?action=modcomment&id='+id,true,'aComment_'+id,'small','Comment_'+id,false,vars);
}

function DeleteComment(id) {
	Ajax('/ajax.php?action=delcomment&id='+id,true,'aComment_'+id,'small','Comment_'+id,false);
}

function NewCommentSend(modul, id) {
	var vars = {
		'edittext': gid('commentText').value
	};
	Ajax('/ajax.php?action=newcomment&id='+id+'&modul='+modul,true,'aNewComment','small','NewComment',false,vars);
}

function GuestComment(modul, id) {
	var vars = {
		'captcha': gid('captcha').value,
		'login': gid('GuestCommentLogin').value,
		'edittext': gid('GuestCommentMsg').value
	};
	Ajax('/ajax.php?action=newcomment&id='+id+'&modul='+modul,true,'aNewComment','small','NewComment',false,vars);
}

images_pl_array = new Array();
images_pl_temp = new Array();
images_pl_current = 0;
images_pl_preload = 3;
function DelPhoto(id) {
	Ajax('/ajax.php?action=delphoto&id='+id,true,'aModifyPhoto_'+id,'small','aModifyPhoto_'+id,false);
}
function DelVideo(id) {
	Ajax('/ajax.php?action=delvideo&id='+id,true,'aModifyVideo_'+id,'small','aModifyVideo_'+id,false);
}
function SaveVideoName(id) {
	var vars = {
		'newname': gid('newVideoName_'+id).value
	};
	Ajax('/ajax.php?action=savevideoname&id='+id,true,'aNameVideo_'+id,'small','aNameVideo_'+id,false,vars);
}
function LoadPhotos(modul, id, all) {
	Ajax('/ajax.php?action=getphotos&modul='+modul+'&id='+id+'&allphotos='+all,true,'aPhotos','small','Photos',false);
}
function nextImage() {
	images_pl_current++;
	if (images_pl_current>=images_pl_array.length) images_pl_current=0;
	images_pl_show();
}
function selectImage(sel) {
	// Style
	gid('openImage').style.display = 'block';
	images_pl_current = sel; images_pl_show();
}
function images_pl_show() {
	// Show
	if (typeof images_pl_array[images_pl_current] == 'undefined') return false;
	if (typeof  document.body == "undefined") return false;
	file = images_pl_array[images_pl_current];
	eval("document.getElementById('openImageBig').src=('"+file+"')");
	// Preload
	count = images_pl_array.length;
	for (i=images_pl_current+1; i <= images_pl_current+images_pl_preload; i++) {
	    if (i>=count) l = i - count;
	    else l = i;
	    if(typeof images_pl_temp[l] != 'object') {
			images_pl_temp[l]=new Image();
			images_pl_temp[l].src=images_pl_array[l];
	    }
	}
}


var videoPlayer = false;
var videoArray = new Array();
function videoPlay(i) {
	var video = videoArray[i];
	
	gid('playerDiv').style.display = "block";
	videoPlayer.addParam('allowfullscreen','true');
	videoPlayer.addParam('allowscriptaccess','always');
	videoPlayer.addParam('flashvars','file='+video['video']+'&image='+video['image']);
	videoPlayer.write('player');
	
	gid('videoname').innerHTML = video['name'];
}


function PagesLoad(Flag, Start, City, Sec) {
	Ajax('/ajax.php?action=getpages&city='+City+'&section='+Sec+'&start='+Start,true,'amore_'+Flag,'small','more_'+Flag,false);
}

function NewsLoad(Flag, Start, City, Date, Place) {
	Ajax('/ajax.php?action=getnews&city='+City+'&date='+Date+'&place='+Place+'&start='+Start,true,'amore_'+Flag,'small','more_'+Flag,false);
}

function EventsLoad(Flag, Start, City, Sec, Vi, Place) {
	Ajax('/ajax.php?action=events&city='+City+'&section='+Sec+'&view='+Vi+'&start='+Start+'&place='+Place,true,'amore_'+Flag,'small','more_'+Flag,false);
}

function LoadExtended(id, date) {
	Ajax('/ajax.php?action=extended&id='+id+'&date='+date,true,'aSeanses','small','Seanses',false);
}

function LoadSimple(id, date) {
	Ajax('/ajax.php?action=simple&id='+id+'&date='+date,true,'aSeanses','small','Seanses',false);
}


function PickID (id, mode) {
	var nameb = ( mode == true ) ? 'newbegin' : 'begin';
	var namee = ( mode == true ) ? 'newending' : 'ending';
	
	var dates = $( "#"+nameb+id+", #"+namee+id ).datepicker({
		dateFormat: 'yy-mm-dd',
		onSelect: function( selectedDate ) {
			var i = this.id == nameb+id ? 1 : -1;
			var option = this.id == nameb+id ? "minDate" : "maxDate",
				instance = $( this ).data( "datepicker" );
				date = $.datepicker.parseDate(
					instance.settings.dateFormat ||
					$.datepicker._defaults.dateFormat,
					selectedDate, instance.settings );
				date.setDate(date.getDate() + i);
			dates.not( this ).datepicker( "option", option, date );
		}
	});
}

function AddDateInEvent (id) {
	gid('NewDateInEvent'+id).innerHTML = ''+
	'<tr><td>с&nbsp;</td><td>'+
	'<input type="text" id="newbegin'+id+'" class="input" style="width:70px;" value="" maxlength="10" />'+
	'</td><td>по&nbsp;</td><td>'+
	'<input type="text" id="newending'+id+'" class="input" style="width:70px;" value="" maxlength="10" />'+
	'</td><td>Время: '+
	'<input type="text" id="newseans'+id+'" class="input" value="" maxlength="512" /> '+
	'<input type="submit" value="Сохранить" /> '+
	'<a href="#" onclick="DelNewDateInEvent('+id+');return false;"><img src="/static/images/delete.jpg" title="Удалить" /></a> '+
	'<span id="aaddDate'+id+'">&nbsp;</span>'+
	'</td></tr>';
	PickID (id, true);
}
function DelNewDateInEvent (id) {
	gid('NewDateInEvent'+id).innerHTML = ''+
	'<tr><td>'+
	'<a href="#" onclick="AddDateInEvent('+id+');return false;">Добавить дату</a>'+
	'</td></tr>';
}
function DelDateInEvent (id) {
	Ajax('?action=deldate&id='+id,true,'amodDate'+id,'small','adelDate'+id,false);
}
function SaveDateInEvent (id, mod) {
	var nd = ( mod == true ) ? 1 : 0;
	var name = ( mod == true ) ? 'new' : '';
	var vars = {
		'begin': gid(name+'begin'+id).value,
		'ending': gid(name+'ending'+id).value,
		'seans': gid(name+'seans'+id).value
	};
	var aid = ( mod == true ) ? 'aaddDate' : 'amodDate';
	var rid = ( mod == true ) ? 'modDates' : 'amodDate'+id;
	Ajax('?action=savedate&id='+id+'&newdate='+nd,mod,aid+id,'small',rid,false,vars);
}


var modDates = {
	city: false,
	event: false,
	type: false,
	lastname: false,
	place_id: false,
	selected: false,
	arr: new Array(),
	curmem: false,
	
	Init: function(city, event){
		this.city = city;
		this.event = event;
	},
	
	Get: function(){
		evt = arguments[0] || false;
		evt = (evt) ? evt : (window.event) ? event : false;
		if ( evt != false )
		if ( evt.keyCode == 38 ) {
			var c = this.arr.length;
			if ( c > 0 ) {
				var cur = this.curmem;
				if ( cur === false ) cur=c-1; else cur--;
				if ( cur < 0 ) cur=c-1;
				this.Mem(cur);
			}
			return;
		} else if ( evt.keyCode == 40 ) {
			var c = this.arr.length;
			if ( c > 0 ) {
				var cur = this.curmem;
				if ( cur === false ) cur=0; else cur++;
				if ( cur >= c ) cur=0;
				this.Mem(cur);
			}
			return;
		} else if ( evt.keyCode == 13 ) {
			var c = this.arr.length;
			if ( c > 0 && this.curmem != false ) {
				this.Sel(this.curmem);
				return;
			}
		}
		
		val = gid('newNamePE');
		if ( val.value == this.lastname ) return;
		if ( val.value.length < 2 ) return;
		
		this.lastname = val.value;
		this.type = gid('newTypePE').value;
		this.Clear();
		var vars = {
			'city': this.city,
			'type': this.type,
			'name': this.lastname
		};
		Ajax('/ajax.php?action=placesinevent',false,'anewNamePE','small','anewNamePE',this.Show,vars);
	},
	
	Show: function(arr){
		var count = arr.length;
		var x = gid('newNamePEx');
		var html = '';
		
		for( var i=0; i<count; i++ ) {
			a = arr[i];
			modDates.arr[i] = a['id'];
			html += '<div class="elem"><a href="#" onclick="modDates.Sel('+i+');return false;" onmouseover="modDates.Mem('+i+');">'+a['rus_name']+'</a></div>';
		}
		
		x.innerHTML = html;
		x.style.display = 'inline';
	},
	
	Mem: function(e){
		var list = gid('newNamePEx').childNodes;
		if ( this.curmem !== false ) {
			list[this.curmem].style.backgroundColor = '#fff';
		}
		list[e].style.backgroundColor = '#cfc';
		this.curmem = e;
	},
	
	Sel: function(e){
		var x = gid('newNamePEx');
		var list = x.childNodes;
		this.place_id = modDates.arr[e];
		this.selected = true;
		
		val = gid('newNamePE');
		val.value = list[e].childNodes[0].innerHTML;
		this.lastname = val.value;
		val.style.backgroundColor = '#cfc';
		
		x.style.display = 'none';
	},
	
	Send: function(){
		if ( this.selected == false ) {
			gid('anewNamePE').innerHTML = '<span class="error">Выберите заведение</span>';
		} else {
			Ajax('?action=newplace&place='+this.place_id,true,'anewNamePE','small','modDates',false);
		}
	},
	
	Clear: function(){
		this.selected = false;
		this.place_id = false;
		this.arr = new Array();
		this.curmem = false;
		e = gid('newNamePE');
		e.style.backgroundColor = '#fcc';
	}
}



var bbField = new Array();

function bbCods (Name, Field){

this.Panel = '' +
'<span title="Жирный" onclick="bbField[' + Field + '].Insert(\'b\', 0);"><b>B</b></span>' +
'<span title="Курсив" onclick="bbField[' + Field + '].Insert(\'i\', 0);"><i>i</i></span>' +
'<span title="Подчеркивание" onclick="bbField[' + Field + '].Insert(\'u\', 0);"><u>u</u></span>' +
'<span title="Вставить ссылку: [url] http://www.idemvgorod.ru/ [/url]" onclick="bbField[' + Field + '].Insert(\'url\', 0);">URL</span>' +
'<span title="По левому краю" onclick="bbField[' + Field + '].Insert(\'left\', 0);"><span class="left">&nbsp;</span></span>' +
'<span title="По центру" onclick="bbField[' + Field + '].Insert(\'center\', 0);"><span class="center">&nbsp;</span></span>' +
'<span title="По правому краю" onclick="bbField[' + Field + '].Insert(\'right\', 0);"><span class="right">&nbsp;</span></span>' +
'<select title="[size=12] Text [/size] - размер в пикселях" onchange="bbField[' + Field + '].Insert(\'size\', this);">' +
'	<option selected value="0">Размер</option>' +
'	<option style="font-size:6px;" value="6">6</option>' +
'	<option style="font-size:8px;" value="8">8</option>' +
'	<option style="font-size:10px;" value="10">10</option>' +
'	<option style="font-size:12px;" value="12">12</option>' +
'	<option style="font-size:14px;" value="14">14</option>' +
'	<option style="font-size:18px;" value="18">18</option>' +
'	<option style="font-size:22px;" value="22">22</option>' +
'	<option style="font-size:26px;" value="26">26</option>' +
'	<option style="font-size:32px;" value="32">32</option>' +
'</select>' +
'<select title="[color=Green] Text [/color] или [color=#00FF00] Text [/color]" onchange="bbField[' + Field + '].Insert(\'color\', this);">' +
'	<option selected value="0">Цвет шрифта</option>' +
'	<option style="background-color:#00ffff;color:#000;" value="#00ffff">Морская волна</option>' +
'	<option style="background-color:#808080;color:#fff;" value="#808080">Серый</option>' +
'	<option style="background-color:#000080;color:#fff;" value="#000080">Темно-синий</option>' +
'	<option style="background-color:#c0c0c0;color:#000;" value="#c0c0c0">Серебрянный</option>' +
'	<option style="background-color:#000000;color:#fff;" value="#000000">Черный</option>' +
'	<option style="background-color:#008000;color:#fff;" value="#008000">Зеленый</option>' +
'	<option style="background-color:#808000;color:#fff;" value="#808000">Оливковый</option>' +
'	<option style="background-color:#008080;color:#fff;" value="#008080">Бирюзовый</option>' +
'	<option style="background-color:#0000ff;color:#fff;" value="#0000ff">Синий</option>' +
'	<option style="background-color:#00ff00;color:#000;" value="#00ff00">Лайм</option>' +
'	<option style="background-color:#800080;color:#fff;" value="#800080">Пурпурный</option>' +
'	<option style="background-color:#ffffff;color:#000;" value="#ffffff">Белый</option>' +
'	<option style="background-color:#ff00ff;color:#000;" value="#ff00ff">Фуксия</option>' +
'	<option style="background-color:#800000;color:#fff;" value="#800000">Темно-бордовый</option>' +
'	<option style="background-color:#ff0000;color:#fff;" value="#ff0000">Красный</option>' +
'	<option style="background-color:#ffff00;color:#000;" value="#ffff00">Желтый</option>' +
'</select>' +
'<span title="Цитата: [quote=User] Message [/quote]" onclick="bbField[' + Field + '].Insert(\'quote\', \'\');">Quote</span>' +
'';

	var ShowImage = arguments[2] || false;
	
	if ( ShowImage ) {
		
		this.Panel = this.Panel + '<span title="Загруженная картинка: [img] id [/img], '
		+ 'где id это - размер и номер загруженной картинки в текущий фотоальбом. '
		+ 'Пример: m3075r. Первая буква это размер: l - 640x0, x - 250x0, m - 150x0, s - 150x113, '
		+ 't - 100x75, u - 50x67. Ноль означает - любая высота. Буква r - означает '
		+ 'выравнивание по правому краю, без буквы - по левому." onclick="bbField['
		+ Field + '].Insert(\'img\', 0);">Рисунок</span>';
		
	}
	
	this.TextAreaName = Name;
	this.Res = document.getElementById(Name);
	this.Field = Field;
	
	elem = document.createElement('div');
	elem.innerHTML = this.Panel;
	elem.className = 'bbpanel';
	this.Res.parentNode.insertBefore(elem, this.Res);
	
	var thisobj = this;
	this.ierng = false;
	this.IE='\v'=='v';
	if ( this.IE ) {
		
		this.Res.onmouseup = function(){thisobj.ierng = document.selection.createRange().duplicate();};
	}
	
	this.Insert = function(tag, mod){
		
		if ( tag=='b' || tag=='i' || tag=='u' || tag=='url' || tag=='left' || tag=='center' || tag=='right' || tag=='img' ) {
			this._SimplyInsert(tag);
		}
		else if ( tag == 'color' || tag == 'size' || tag == 'quote' ) {
			inText = arguments[2] || false;
			this._ExpertInsert(tag, mod, inText);
		}

	}

	this._SimplyInsert = function(tag){
		var left = '[' + tag + ']';
		var right = '[/' + tag + ']';
		this.FindSelected(left, right);
	}
	this._ExpertInsert = function(tag, mod, inText){
		if (mod.value == 0) return;
		var modt = ( mod.value ) ? mod.value : mod;
		
		var left = '[' + tag + '=' + modt + ']';
		var right = '[/' + tag + ']';
		this.FindSelected(left, right, inText);

		if ( mod.options )
		mod.options[0].selected = 'true';
	}
	
	this.FindSelected = function(left, right){
		this.Res.focus();
		inText = arguments[2] || false;
		
		if ( this.IE ) {
			
			if ( this.ierng == false ) {
				
				this.ierng = document.selection.createRange().duplicate();
				
			}
			
			var l = this.ierng.text.length;
			
			if ( inText != false ) {
				
				this.ierng.text = left + inText + right;
				
			} else {
			
				this.ierng.text = left + this.ierng.text + right;
				this.ierng.moveEnd("character", -right.length);
				this.ierng.moveStart("character", -l);
				
				this.ierng.select();
			
			}
			
		} else if (window.attachEvent && navigator.userAgent.indexOf('Opera') === -1){
			
			var rng = document.selection.createRange();
			
			if ( inText != false ) {
				
				rng.text = left + inText + right;
				
			} else {
			
				rng.text = left + rng.text + right;
				rng.select();
			
			}
			
		} else if (typeof(this.Res.selectionStart)=="number"){

			var scroll = this.Res.scrollTop;
			var start = this.Res.selectionStart;
			var end = this.Res.selectionEnd;
			
			if ( inText != false ) {
				
				this.Res.value = this.Res.value.substr(0,start) +
				left + inText + right +
				this.Res.value.substr(end);
				
			} else {
			
				this.Res.value = this.Res.value.substr(0,start) +
				left + this.Res.value.substr(start,end-start) + right +
				this.Res.value.substr(end);
	
				start = start + left.length;
				end = end + left.length;
				this.Res.setSelectionRange(start,end);
			
			}
			
			if (scroll >= 0) this.Res.scrollTop = scroll;
			
		}
		
	}
}


var json_parse = (function () {

// This function creates a JSON parse function that uses a state machine rather
// than the dangerous eval function to parse a JSON text.

    var state,      // The state of the parser, one of
                    // 'go'         The starting state
                    // 'ok'         The final, accepting state
                    // 'firstokey'  Ready for the first key of the object or
                    //              the closing of an empty object
                    // 'okey'       Ready for the next key of the object
                    // 'colon'      Ready for the colon
                    // 'ovalue'     Ready for the value half of a key/value pair
                    // 'ocomma'     Ready for a comma or closing }
                    // 'firstavalue' Ready for the first value of an array or
                    //              an empty array
                    // 'avalue'     Ready for the next value of an array
                    // 'acomma'     Ready for a comma or closing ]
        stack,      // The stack, for controlling nesting.
        container,  // The current container object or array
        key,        // The current key
        value,      // The current value
        escapes = { // Escapement translation table
            '\\': '\\',
            '"': '"',
            '/': '/',
            't': '\t',
            'n': '\n',
            'r': '\r',
            'f': '\f',
            'b': '\b'
        },
        string = {   // The actions for string tokens
            go: function () {
                state = 'ok';
            },
            firstokey: function () {
                key = value;
                state = 'colon';
            },
            okey: function () {
                key = value;
                state = 'colon';
            },
            ovalue: function () {
                state = 'ocomma';
            },
            firstavalue: function () {
                state = 'acomma';
            },
            avalue: function () {
                state = 'acomma';
            }
        },
        number = {   // The actions for number tokens
            go: function () {
                state = 'ok';
            },
            ovalue: function () {
                state = 'ocomma';
            },
            firstavalue: function () {
                state = 'acomma';
            },
            avalue: function () {
                state = 'acomma';
            }
        },
        action = {

// The action table describes the behavior of the machine. It contains an
// object for each token. Each object contains a method that is called when
// a token is matched in a state. An object will lack a method for illegal
// states.

            '{': {
                go: function () {
                    stack.push({state: 'ok'});
                    container = {};
                    state = 'firstokey';
                },
                ovalue: function () {
                    stack.push({container: container, state: 'ocomma', key: key});
                    container = {};
                    state = 'firstokey';
                },
                firstavalue: function () {
                    stack.push({container: container, state: 'acomma'});
                    container = {};
                    state = 'firstokey';
                },
                avalue: function () {
                    stack.push({container: container, state: 'acomma'});
                    container = {};
                    state = 'firstokey';
                }
            },
            '}': {
                firstokey: function () {
                    var pop = stack.pop();
                    value = container;
                    container = pop.container;
                    key = pop.key;
                    state = pop.state;
                },
                ocomma: function () {
                    var pop = stack.pop();
                    container[key] = value;
                    value = container;
                    container = pop.container;
                    key = pop.key;
                    state = pop.state;
                }
            },
            '[': {
                go: function () {
                    stack.push({state: 'ok'});
                    container = [];
                    state = 'firstavalue';
                },
                ovalue: function () {
                    stack.push({container: container, state: 'ocomma', key: key});
                    container = [];
                    state = 'firstavalue';
                },
                firstavalue: function () {
                    stack.push({container: container, state: 'acomma'});
                    container = [];
                    state = 'firstavalue';
                },
                avalue: function () {
                    stack.push({container: container, state: 'acomma'});
                    container = [];
                    state = 'firstavalue';
                }
            },
            ']': {
                firstavalue: function () {
                    var pop = stack.pop();
                    value = container;
                    container = pop.container;
                    key = pop.key;
                    state = pop.state;
                },
                acomma: function () {
                    var pop = stack.pop();
                    container.push(value);
                    value = container;
                    container = pop.container;
                    key = pop.key;
                    state = pop.state;
                }
            },
            ':': {
                colon: function () {
                    if (Object.hasOwnProperty.call(container, key)) {
                        throw new SyntaxError('Duplicate key "' + key + '"');
                    }
                    state = 'ovalue';
                }
            },
            ',': {
                ocomma: function () {
                    container[key] = value;
                    state = 'okey';
                },
                acomma: function () {
                    container.push(value);
                    state = 'avalue';
                }
            },
            'true': {
                go: function () {
                    value = true;
                    state = 'ok';
                },
                ovalue: function () {
                    value = true;
                    state = 'ocomma';
                },
                firstavalue: function () {
                    value = true;
                    state = 'acomma';
                },
                avalue: function () {
                    value = true;
                    state = 'acomma';
                }
            },
            'false': {
                go: function () {
                    value = false;
                    state = 'ok';
                },
                ovalue: function () {
                    value = false;
                    state = 'ocomma';
                },
                firstavalue: function () {
                    value = false;
                    state = 'acomma';
                },
                avalue: function () {
                    value = false;
                    state = 'acomma';
                }
            },
            'null': {
                go: function () {
                    value = null;
                    state = 'ok';
                },
                ovalue: function () {
                    value = null;
                    state = 'ocomma';
                },
                firstavalue: function () {
                    value = null;
                    state = 'acomma';
                },
                avalue: function () {
                    value = null;
                    state = 'acomma';
                }
            }
        };

    function debackslashify(text) {

// Remove and replace any backslash escapement.

        return text.replace(/\\(?:u(.{4})|([^u]))/g, function (a, b, c) {
            return b ? String.fromCharCode(parseInt(b, 16)) : escapes[c];
        });
    }

    return function (source, reviver) {

// A regular expression is used to extract tokens from the JSON text.
// The extraction process is cautious.

        var r,          // The result of the exec method.
            tx = /^[\x20\t\n\r]*(?:([,:\[\]{}]|true|false|null)|(-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)|"((?:[^\r\n\t\\\"]|\\(?:["\\\/trnfb]|u[0-9a-fA-F]{4}))*)")/;

// Set the starting state.

        state = 'go';

// The stack records the container, key, and state for each object or array
// that contains another object or array while processing nested structures.

        stack = [];

// If any error occurs, we will catch it and ultimately throw a syntax error.

        try {

// For each token...

            for (;;) {
                r = tx.exec(source);
                if (!r) {
                    break;
                }

// r is the result array from matching the tokenizing regular expression.
//  r[0] contains everything that matched, including any initial whitespace.
//  r[1] contains any punctuation that was matched, or true, false, or null.
//  r[2] contains a matched number, still in string form.
//  r[3] contains a matched string, without quotes but with ecapement.

                if (r[1]) {

// Token: Execute the action for this state and token.

                    action[r[1]][state]();

                } else if (r[2]) {

// Number token: Convert the number string into a number value and execute
// the action for this state and number.

                    value = +r[2];
                    number[state]();
                } else {

// String token: Replace the escapement sequences and execute the action for
// this state and string.

                    value = debackslashify(r[3]);
                    string[state]();
                }

// Remove the token from the string. The loop will continue as long as there
// are tokens. This is a slow process, but it allows the use of ^ matching,
// which assures that no illegal tokens slip through.

                source = source.slice(r[0].length);
            }

// If we find a state/token combination that is illegal, then the action will
// cause an error. We handle the error by simply changing the state.

        } catch (e) {
            state = e;
        }

// The parsing is finished. If we are not in the final 'ok' state, or if the
// remaining source contains anything except whitespace, then we did not have
//a well-formed JSON text.

        if (state !== 'ok' || /[^\x20\t\n\r]/.test(source)) {
            return false;
        }

// If there is a reviver function, we recursively walk the new structure,
// passing each name/value pair to the reviver function for possible
// transformation, starting with a temporary root object that holds the current
// value in an empty key. If there is not a reviver function, we simply return
// that value.

        return typeof reviver === 'function' ? (function walk(holder, key) {
            var k, v, value = holder[key];
            if (value && typeof value === 'object') {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = walk(value, k);
                        if (v !== undefined) {
                            value[k] = v;
                        } else {
                            delete value[k];
                        }
                    }
                }
            }
            return reviver.call(holder, key, value);
        }({'': value}, '')) : value;
    };
}());
