//for ADMIN
function add_exhibition() {
	var title = $("#e_title").val();
	var title_en = $("#e_title_en").val();
	var date1 = $("#date1").val();
	var date2 = $("#date2").val();
	var lead = $("#e_lead").val();
	var country_id = $("#country_id").val();
	var city = $("#city").val();
	var content = $("#my_textarea_id").val();
	var place = $("#e_place").val();
	var organizatory = $("#e_organizatory").val();
	var vid = $("#e_vid").val();
	var grupe = $("#e_grupe").val();
	
	if (title != '' && date1 != '' && date2 != '' && lead != '' && country_id != '' && city != '' && content != '' && place != '' && title_en != '') {
		$.post('/',{
			action:'add_exhibition',
			title: title,
			title_en: title_en,
			date1: date1,
			date2: date2,
			lead: lead,
			country_id: country_id,
			city: city,
			content: content,
			place: place,
			o: organizatory,
			vid: vid,
			grupe: grupe			
		},
		function(resp){
			if (resp == 'err_date') alert('Проверьте даты начала и конца выставки!');
			if (resp == 'err1') alert('Такая выставка уже добавлена!');
			if (resp != 'err_date' && resp != 'err' && resp != 'err1') core_redirect('/admin/exhibition/' + resp);
		});
	}
	else {
		alert('Вы не заполнили все необходимые поля!');	
	}
}

function edit_exhibition() {
	var title = $("#e_title").val();
	var title_en = $("#e_title_en").val();
	var date1 = $("#date1").val();
	var date2 = $("#date2").val();
	var lead = $("#e_lead").val();
	var country_id = $("#country_id").val();
	var city = $("#city").val();
	var content = $("#my_textarea_id").val();
	var id = $("#e_id").val();
	var place = $("#e_place").val();
	var organizatory = $("#e_organizatory").val();
	var vid = $("#e_vid").val();
	var grupe = $("#e_grupe").val();
	var alias = $("#e_alias").val();
	
	if (title != '' && date1 != '' && date2 != '' && lead != '' && country_id != '' && city != '' && content != '' && title_en != '' && place != '' && alias != '') {
		$.post('/',{ 
			action:'edit_exhibition',
			title: title,
			title_en: title_en,
			date1: date1,
			date2: date2,
			lead: lead,
			country_id: country_id,
			city: city,
			content: content,
			id: id,
			place: place,
			o: organizatory,
			vid: vid,
			grupe: grupe,
			alias: alias
		},
		function(resp){
			if (resp == 'err_date') alert('Проверьте даты начала и конца выставки!');
			if (resp == 'ok') core_redirect('/admin/exhibition/' + id);
		});
	}
	else {
		alert('Вы не заполнили все необходимые поля!');	
	}
}

//REGISTRATION
function registration () {
	//checking data
	var name = $("#inp_name").val();
	var email = $("#inp_email").val();
	var s;	

	if($("#inp_mw_01:checked").length != 0) s = 0;
	if($("#inp_mw_02:checked").length != 0) s = 1;

	if (s != 1) s = 0; //0-man; 1-woman

	if (name == '') {
		$("#reg_err_name").css('display', 'block');
		$("#inp_name").focus();
		return false;
	}
	else {
		$("#reg_err_name").css('display', 'none');
	}
	
	if (!checkmail(email)) { 
		$("#reg_err_email").css('display', 'block');
		$("#inp_email").focus();
		return false;
	}
	else { 
		$("#reg_err_email").css('display', 'none');
	}	
	
//выполняем регистрацию
	$.post('/',{
		action:'registration_user',
		email:email,
		name:name,
		s:s
	},
	function(resp){
		resp=eval('('+resp+')');
		if(resp.ok=='yes') {
			alert('On your E-mail sent a letter with a new password.');
			core_redirect('/');
		}
		else if(resp.error=='email'){
			$("#inp_email").focus();
			$("#inp_email").empty();
			$("#err").html('Please type your email address in the format yourname@example.com!').appendTo($('#err'));
		}
		else if(resp.error=='pass'){
			$("#inp_pas").focus();
			$("#inp_pas").empty();
			$("#err").html('Please type your password.!').appendTo($('#err'));
		}
		else{
			alert(resp.error||resp);
		}
	}
	);
}

function select_star(star) {
	$('#star option[value='+star+']').attr('selected','selected');
}
//Проверка на корректность адреса электронной почты
function checkmail(email) {
	var template = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z])+$/;
   	email = drop_spaces(email); 
    if (template.test(email)) {
        return true;
    }
    return false;	
}
//Удаление всех пробелов
function drop_spaces(str) {
    var newstr = trim(str); 
    return newstr.replace(/(\s)+/g, ""); 
}

//Аналог функции trim() из PHP
function trim(str) {
    var newstr = str.replace(/^\s*(.+?)\s*$/, "$1");
    if (newstr == " ") {
        return "";
    }
    return newstr;
}

function redirectOnPhotoCountry() {
	var alias = $("select#country_id").val();
	core_redirect('/photos/' + alias);
}

function redirectOnHotelCountry() {
	var alias = $("select#country_id").val();
	core_redirect('/hotel/' + alias);
}

function redirectOnRestaurantCountry() {
	var alias = $("select#country_id").val();
	core_redirect('/restaurant/' + alias);
}

function redirectOnTurCountry() {
	var alias = $("select#country_id").val();
	core_redirect('/turfirmy/' + alias);
}

function redirectOnExhibitionCountry() {
	var alias = $("select#country_id").val();
	core_redirect('/exhibition/' + alias);
}

function selectCountry(id) { 
	$("#country_id [value='"+id+"']").attr("selected", "selected");
}

function showAllCountry(t) {
	$.post(
		'/',
		{
			action:'show_all_country',
			type_sec: t
		},
		function(resp){
			//очищаем select
			$("#country_id").empty();
			var sel = $("#country_id");
			resp1=eval('('+resp+')');
			$("<option></option>")  // создаем требуемый элемент
			.attr("value", "")     // устанавливаем значение одного из его атрибутов
			.html("select country ...") // записываем в него текст
			.appendTo(sel);
			for(var key in resp1) {
				$("<option></option>")  // создаем требуемый элемент
				.attr("value", key)     // устанавливаем значение одного из его атрибутов
				.html(resp1[key]) // записываем в него текст
				.appendTo(sel);       // прикрепляем к уже существующему элементу
			}
		}
	);
};

function selectCountryFromURL(tip){
	//tip = alias - значит нужно выбрать по алиасу
	//tip = id - нужно вернуть ID country
	$.post(
		'/',
		{
			action:'get_country',
			tip: tip,
			url: location.href // get url
		},
		function(resp){
			selectOneCountry(resp);
		}
	);
}

function selectOneCountry(ctr_id) {
	$("#country_id option[value='"+ctr_id+"']").attr('selected', 'selected');
}

function selectOneVid(id_vid) { 
	$("#vid_"+id_vid).attr("selected","selected");	
}

function selCountryOne(alias_country, area) {
	$("#id_"+area).attr("selected","selected");
	$.post(
		'/',
		{
			action:'show_country',
			cont:area			
		},
		function(resp){
			$("#id_country").empty();
			var sel = $("#id_country");
			resp1=eval('('+resp+')');

			for(var key in resp1) {
				if (key == alias_country) {
					$("<option></option>")  // создаем требуемый элемент
					.attr("value", key)
					.attr("selected", "selected")// устанавливаем значение одного из его атрибутов
					.html(resp1[key]) // записываем в него текст
					.appendTo(sel);       // прикрепляем к уже существующему элементу
				}
				else  {
					$("<option></option>")  // создаем требуемый элемент
					.attr("value", key)     // устанавливаем значение одного из его атрибутов
					.html(resp1[key]) // записываем в него текст
					.appendTo(sel);       // прикрепляем к уже существующему элементу
				}
			}
		}
	);
}

function selCountry() {
	var cont = $("#id_area").val();
	$.post(
		'/',
		{
			action:'show_country',
			cont:cont			
		},
		function(resp){
			$("#id_country").empty();
			var sel = $("#id_country");
			resp1=eval('('+resp+')');

			for(var key in resp1) {
				$("<option></option>")  // создаем требуемый элемент
				.attr("value", key)     // устанавливаем значение одного из его атрибутов
				.html(resp1[key]) // записываем в него текст
				.appendTo(sel);       // прикрепляем к уже существующему элементу
			}
		}
	);
}

function getGroupItems(opts) {
  jQuery.each(imageList, function(i, val) { 
    opts.itemArray.push(val);
 });
}


function editPos(pos){ 
	$(document).ready(function() {
		$("#gallery a").fancybox({
			overlayShow: true,
			overlayOpacity: 0.5,
			itemLoadCallback: getGroupItems,
			itemNum: pos-1
		});
	});
}


function showDiv_bt (id, id_bt, title1_bt, title2_bt) {
	//id - id div который нужно показать или скрыть
	//id_bt - id bt, которую нужно как-то изменить	
	//title1_bt - текст, если див скрыт
	//title2_bt - текст, если див показан
	
	if (document.getElementById(id).style.display == 'block') {
		document.getElementById(id).style.display = 'none';
		$("#" + id_bt).attr('value', title2_bt);
	}
	else {
		document.getElementById(id).style.display = 'block';
		$("#" + id_bt).attr('value', title1_bt);
	}
}

function showDivMenu (id) {
	//id - id div который нужно показать или скрыть	
	if (document.getElementById(id).style.display == 'block') {
		document.getElementById(id).style.display = 'none';
	}
	else {
		document.getElementById(id).style.display = 'block';
	}
}

function hidenDivMenu () {
	document.getElementById('menu1').style.display = 'none';
	document.getElementById('menu2').style.display = 'none';
	document.getElementById('menu3').style.display = 'none';
}


//Adminka - delete tag
function delTag (id_tag) {
	var message = "Вы уверены, что хотите удалить этот тег?";
	var return_value = confirm(message);
    if (return_value == true) {
	$.post(
		'/',
		{
			action:'del_tag_admin',
			id_tag:id_tag
		},
	function(resp){
			if (resp == 'ok') {
				$("#tr_tag_"+id_tag).hide();
			}
			else {
				alert('Запись не может быть удалена. Обратитесь к разработчику сайта.');
			}
		}
	);
	}
}

function yesTag (id_tag) {
	$.post(
		'/',
		{
			action:'yes_tag_admin',
			id_tag:id_tag
		},
	function(resp){
			if (resp == 'ok') {
				$("#tr_tag_"+id_tag).hide();
			}
			else {
				alert('Тег не может быть подтвержден. Обратитесь к разработчику сайта.');
			}
		}
	);
}

function cl_cnt_news(){
	$.post(
		'/',
		{
			action:'cnt_author_news'
		},
	function(resp){
			if (resp == 'ok') {
				alert('Авторские новости пересчитали!!!');
			}
			else {
				alert('Авторские новости НЕ  пересчитали!!!');
			}
		}
	);
}

function do_query(){
	var message = "Вы уверены, что хотите выполнить этот "+ $("#text_do").val() +"запрос?";
    var return_value = confirm(message);
    if (return_value == true) {
		$.post(
			'/',
			{
				action:'do_query',
				q: $("#text_do").val()
			},
		function(resp){
				if (resp == 'ok') {
					alert('Все прошло хорошо!!!');
				}
				if (resp == 'err') {
					alert('Такой запрос не выполню!!!');
				}
		}
		);
	}
}

var crop_popup=function(href){
	general_popup(href,'CropWindow','auto',500,500);
}

//For tags
function get_tags(somebody) {
  	  $.post(
		  '/',
		  {
			  action:'get_tags',
			  subscriber:somebody
		  },
		function(resp){
			var str_tags;
			str_tags ='';
			// starting processing ajax response
		  	resp1=eval('('+resp+')');
		  	// alert(resp1[]);
			$("#tags_place").empty();
		  	for(var key in resp1) {
				// getting font-size
				str_arr = key.split("_");
				// and new key
				key_new = str_arr[0];
				font_size = str_arr[1];
				// for showing custom tags (author, editors, all)
				// default value
				tag_prefix = '3';
				// author value
				if (somebody == 'author') tag_prefix = '1';
				// editor value
				if (somebody == 'editor') tag_prefix = '2';
				// str_tags = str_tags + key_new + '#' + resp1[key] + '__';
				//font_size -число шрифта
				if (tag_prefix == 3) str_tags = str_tags + '<a href="'+ '/tags/' + key_new + '" class="tsize'+font_size+'">' + resp1[key] + '</a>  ';
				else str_tags = str_tags + '<a href="'+ '/tags/' + key_new + '?tt=' + tag_prefix + '" class="tsize'+font_size+'">' + resp1[key] + '</a>  ';
			}
			$(".tegs").html(str_tags);
		}
	  );

  }

function delete_comment(comm_id, t) {
	var message = "Вы уверены, что хотите удалить этот комментарий?";
        var return_value = confirm(message);
        if (return_value == true) {
		$.post(
			'/',
		        {
				action:'deleter_2',
			        comment_id: comm_id,
					t:t
		        },
		        function(resp) {
		        	if (resp == 1) {
		              		var comm_identifier = '#comment_' + comm_id;
		              	 	$(''+comm_identifier+'').hide();
		              	 	get_comments_number();
		              	 }
			         else alert('Не удалось удалить комментарий!');			         
		       }
	              );
	 }    	   
}

function delete_ip(comm_id) {
	var message = "Вы уверены, что хотите заблокировать этот IP?";
        var return_value = confirm(message);
        if (return_value == true) {
		$.post(
			'/',
		        {
				action:'deleter_ip',
			        comment_id: comm_id
		        },
		        function(resp) {
		        	if (resp == 1) document.location.reload();
			         else alert('Не удалось заблокировать IP!');			         
		       }
	              );
	 }    	   
}

//функции для какртинок на странице новости
function showPicForNews(id_pic) {
	if(id_pic == 'first'){
		$('.pic_news').hide();
		$('.pic_news:first').show();
		$('#p_1').hide();
		$('<span></span>').attr('id','id_1').html('1').appendTo('#pic_pages');
	}
	if(id_pic == 'last'){
		$('.pic_news').hide();
		$('.pic_news:last').show();
	}
}

function showPages (news_id) {
	$.post(
		'/',
		{
			action:'show_pages_for_pic',
			news_id:news_id
		},
		function(resp){
			resp=eval('('+resp+')');
			len = resp.length;
			if (len > 1) {
				$('<span></span>').attr('class', 'aspan2').attr('title', 'Начало').html('&lt;&lt;').appendTo('#pic_pages').click(function() {
					$('.pic_news').hide();
					$('.pic_news:first').show();
					$('#p_link_1').hide();
					$('#p_1').show();
					$('<span></span>').attr('id','id_1').html('1').appendTo('#pic_pages');
				});

				$('<span></span>').html('&nbsp;&nbsp;&nbsp;').appendTo('#pic_pages');

				$('<span></span>').attr('class', 'aspan2').html('&lt;').appendTo('#pic_pages').click(function() {
					$('.pic_news').hide();
					$('.pic_news:first').show();
					//first page other style
					$('#p_1').hide();
					$('<span></span>').attr('id','id_1').html('1').appendTo('#pic_pages');
				});
				$('<span></span>').html('&nbsp;&nbsp;&nbsp;').appendTo('#pic_pages');

				//pages
				for (i=1; i<=len; i++) {
					//$('<span></span>').attr('class', 'span3').attr('id', 'p_'+resp[i-1]).html(i).appendTo('#pic_pages');
					$('<span></span>').attr('class', 'aspan2').attr('id', 'p_link_'+i).html(i).appendTo('#pic_pages')
					.click(function() {
							//$('#p_link_'+resp[i-1]).hide();
							//$('<span></span>').attr('class', 'span').attr('id', 'p_'+resp[i-1]).html(i).appendTo('#pic_pages');
					});
					//if (i+1 < len)
						$('<span></span>').html('|').appendTo('#pic_pages');
				}
				$('<span></span>').html('&nbsp;&nbsp;&nbsp;').appendTo('#pic_pages');
			}
		}
	);

}

var cur_mod='';
function change_mod(mod){
	document.getElementById('mod_'+cur_mod).className='';
	document.getElementById('mod_'+mod).className='active';
	document.search_form.mod.value=mod;
	cur_mod=mod;
}

function searchsubmit(){
	if(document.search_form.query.value==''){
		return false;
	}
	return true;
}

function prepare_send_db_IMG() { 
      var sendingOK = 0;
      var img_path_input = document.getElementById('file_id').value;
      if (img_path_input.length != 0) {
      	  if (img_path_input.indexOf(".jpg")!=-1 || img_path_input.indexOf(".JPG")!=-1 
				|| img_path_input.indexOf(".gif")!=-1 || img_path_input.indexOf(".GIF")!=-1
				|| img_path_input.indexOf(".jpeg")!=-1 || img_path_input.indexOf(".JPEG")!=-1
				|| img_path_input.indexOf(".png")!=-1 || img_path_input.indexOf(".PNG")!=-1)
          {
          	sendingOK=1;
            return true;
          }
      	  else 
      	  {
      	  	alert ('File format is not valid!'); 
      	  	return false;
      	  }
        }
      else {
       	  alert ('Please choose the file!');
       	  return false;
       }
}

function getRussianDateTime() {
	dayarray=new Array("Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота")
	montharray=new Array ("января","февраля","марта","апреля","мая","июня","июля","августа","сентября", "октября","ноября","декабря")
	ndata=new Date();
	day=dayarray[ndata.getDay()];
	month=montharray[ndata.getMonth()];
	date=ndata.getDate();
	year=ndata.getFullYear();
	hours = ndata.getHours();
	mins = ndata.getMinutes();
	secs = ndata.getSeconds();
	if (hours < 10) {hours = "0" + hours }
	if (mins < 10) {mins = "0" + mins }
	if (secs < 10) {secs = "0" + secs }
	//datastr = day + ", "+ date +" "+ month +" "+ year +", "+ hours + ":" + mins;
	datastr = date +" "+ month +" "+ year  +", "+ hours + ":" + mins;
	return datastr;
}

function addNewHotel(id_user, id_news) {
	var err_title = 'err';
	var err_star = 'err';
	var err_content = 'err';
	var err_rules = 'err';
	var err_country = 'err';
	var err_city = 'err';	
	
	//title
	if ($("#title").val() == '') $("#err_title").html('Ошибка заполнения заголовка');
	else { err_title = 'ok'; $("#err_title").html('');}

	//star
	if ($("#star").val() == '') $("#err_star").html('Такого количества звезд нет');
	else { err_star = 'ok'; $("#err_star").html('');}
	
	//country
	if ($("#country_id").val() == '') $("#err_country").html('Вы не выбрали страну');
	else { err_country = 'ok'; $("#err_country").html('');}
	
	if ($("#city").val() == '') $("#err_city").text('Ошибка заполнения города');
	else { err_city = 'ok'; $("#err_city").html(''); }
	//content
	if ($("#content").val() == '') $("#err_content").html('Ошибка заполнения');
	else { err_content = 'ok'; $("#err_content").html('');}
	//проверяем стоит ли отметка соглашение с правилами
	if ($("#rules:checked").length == 0) $("#err_rules").text("Вы не согласились с правилами публикации");
	else err_rules = 'ok';

	if (err_title == 'ok' && err_star == 'ok' && err_content == 'ok' && err_rules == 'ok' && err_country == 'ok' && err_city == 'ok') {
		$.post('/', {
					action:'addNewHotel',
					id_user: id_user,
					title: $("#title").val(),
					star: $("#star").val(),
					content: $("#content").val(),
					country_id: $("#country_id").val(),
					city:$("#city").val(),
					url: $("#url").val()
		        },
		        function(resp) {					
					resp1=eval('('+resp+')');
					for(var key in resp1) {
						if (key == 'alias_country') var a_c = resp1[key];
						if (key == 'alias_hotel') var a_h = resp1[key];
						if (key == 'alias_city') var a_city = resp1[key];
					}
					if (resp != 'err') { 
						core_redirect('/hotel/' +a_c+'/'+a_city+'/'+a_h );
					}
					if (resp == 'err') { 
						alert('Вы не можете добавить гостиницу. Спросите причину у администратора сайта.');
					}						
				}
		);
	}
}

//EDIT hotel
function editNewHotel(id_user, id_hotel) {
	var err_title = 'err';
	var err_star = 'err';
	var err_content = 'err';
	var err_rules = 'err';
	var err_country = 'err';
	var url_v, t, int_str, url, country_id;
	var err_city = 'err';
	
	//title
	if ($("#title").val() == '') $("#err_title").html('Ошибка заполнения заголовка');
	else { err_title = 'ok'; $("#err_title").html('');}

	//star
	if ($("#star").val() == '') $("#err_star").html('Такого количества звезд нет');
	else { err_star = 'ok'; $("#err_star").html('');}
	
	//country
	if ($("#country_id").val() == '') $("#err_country").html('Вы не выбрали страну');
	else { err_country = 'ok'; $("#err_country").html('');}
	
	if ($("#city").val() == '') $("#err_city").text('Ошибка заполнения города');
	else { err_city = 'ok'; $("#err_city").html(''); }
	//content
	if ($("#content").val() == '') $("#err_content").html('Ошибка заполнения');
	else { err_content = 'ok'; $("#err_content").html('');}
	//проверяем стоит ли отметка соглашение с правилами
	if ($("#rules:checked").length == 0) $("#err_rules").text("Вы не согласились с правилами публикации");
	else err_rules = 'ok';

	if (err_title == 'ok' && err_star == 'ok' && err_content == 'ok' && err_rules == 'ok' && err_country == 'ok' && err_city == 'ok') {
		$.post('/', {
					action:'editHotel',
					id_user: id_user,
					id_hotel: id_hotel,
					title: $("#title").val(),
					star: $("#star").val(),
					content: $("#content").val(),
					country_id:$("#country_id").val(),
					city:$("#city").val()
		        },
		        function(resp) {
					resp1=eval('('+resp+')');
					for(var key in resp1) {
						if (key == 'alias_country') var a_c = resp1[key];
						if (key == 'alias_hotel') var a_h = resp1[key];
						if (key == 'alias_city') var a_city = resp1[key];
					}
					if (resp != 'err') { 
						core_redirect('/hotel/' +a_c+'/'+a_city+'/'+a_h );
					}
					if (resp == 'err') { 
						alert('Вы не можете редактировать гостиницу. Спросите причину у администратора сайта.');
					}										
				}
		);
	}
}

function addNewRestaurant(id_user, id_news) { 
	var err_title = 'err';
	var err_vid = 'err';
	var err_content = 'err';
	var err_rules = 'err';
	var err_country = 'err';
	var err_time = 'err';
	var err_address = 'err';
	var err_phone = 'err';
	var err_city = 'err';
	
	//проверим заполнение полей
	//title
	if ($("#title").val() == '') $("#err_title").html('Error filling in the title');
	else { err_title = 'ok'; $("#err_title").html('');}
	
	//address
	if ($("#address").val() == '') $("#err_address").html('Error filling');
	else { err_address = 'ok'; $("#err_address").html('');}
	
	//phone
	if ($("#phone").val() == '') $("#err_phone").html('Error filling');
	else { err_phone = 'ok'; $("#err_phone").html('');}
	
	//time
	if ($("#time").val() == '') $("#err_time").html('Error filling');
	else { err_time = 'ok'; $("#err_time").html('');}

	//vid
	if ($("#vid").val() == '') $("#err_vid").html('Error filling');
	else { err_vid = 'ok'; $("#err_vid").html('');}
	
	//country
	if ($("#country_id").val() == '') $("#err_country").html('Error filling');
	else { err_country = 'ok'; $("#err_country").html('');}
	
	if ($("#city").val() == '') $("#err_city").text('You don`t write city');
	else { err_city = 'ok'; $("#err_city").html(''); }
	//content
	if ($("#content").val() == '') $("#err_content").html('Error filling');
	else { err_content = 'ok'; $("#err_content").html('');}
	//проверяем стоит ли отметка соглашение с правилами
	if ($("#rules:checked").length == 0) $("#err_rules").text("You do not agree with the rules of publishing");
	else err_rules = 'ok';

	if (err_title == 'ok' && err_vid == 'ok' && err_address == 'ok' && err_city == 'ok' && err_time == 'ok' && err_phone == 'ok' && err_content == 'ok' && err_rules == 'ok' && err_country == 'ok') {
		$.post('/', {
					action:'addNewRestaurant',
					id_user: id_user,
					title: $("#title").val(),
					vid: $("#vid").val(),
					content: $("#content").val(),
					country_id: $("#country_id").val(),
					address: $("#address").val(),
					time: $("#time").val(),
					phone: $("#phone").val(),
					url: $("#url").val(),
					city: $("#city").val()
		        },
		        function(resp) {					
					resp1=eval('('+resp+')');
					for(var key in resp1) {
						if (key == 'alias_country') var a_c = resp1[key];
						if (key == 'alias_restaurant') var a_r = resp1[key];
						if (key == 'alias_city') var a_city = resp1[key];
					}
					if (resp != 'err') { 
						core_redirect('/restaurant/' +a_c+'/'+a_city+'/'+a_r );
					}
					if (resp == 'err') { 
						alert('You can not add a restaurant. Ask the reason for administrator.');
					}					
				}
		);
	}
}
//EDIT Restaurant
function editRestaurant(id_user, id_news) {
	var err_title = 'err';
	var err_vid = 'err';
	var err_content = 'err';
	var err_rules = 'err';
	var err_country = 'err';
	var err_time = 'err';
	var err_address = 'err';
	var err_phone = 'err';
	var err_city = 'err';
	
	//проверим заполнение полей
	//title
	if ($("#title").val() == '') $("#err_title").html('Error filling in the title');
	else { err_title = 'ok'; $("#err_title").html('');}
	
	//address
	if ($("#address").val() == '') $("#err_address").html('Error filling');
	else { err_address = 'ok'; $("#err_address").html('');}
	
	//phone
	if ($("#phone").val() == '') $("#err_phone").html('Error filling');
	else { err_phone = 'ok'; $("#err_phone").html('');}
	
	//time
	if ($("#time").val() == '') $("#err_time").html('Error filling');
	else { err_time = 'ok'; $("#err_time").html('');}

	//vid
	if ($("#vid").val() == '') $("#err_vid").html('Error filling');
	else { err_vid = 'ok'; $("#err_vid").html('');}
	
	//country
	if ($("#country_id").val() == '') $("#err_country").html('Error filling');
	else { err_country = 'ok'; $("#err_country").html('');}

	//content
	if ($("#content").val() == '') $("#err_content").html('Error filling');
	else { err_content = 'ok'; $("#err_content").html('');}
	
	if ($("#city").val() == '') $("#err_city").text('You don`t write city');
	else { err_city = 'ok'; $("#err_city").html(''); }
	//проверяем стоит ли отметка соглашение с правилами
	if ($("#rules:checked").length == 0) $("#err_rules").text("You do not agree with the rules of publishing");
	else err_rules = 'ok';

	if (err_title == 'ok' && err_vid == 'ok' && err_address == 'ok' && err_city == 'ok' && err_time == 'ok' && err_phone == 'ok' && err_content == 'ok' && err_rules == 'ok' && err_country == 'ok') {
		$.post('/', {
					action:'editRestaurant',
					id_r: id_news,
					id_user: id_user,
					title: $("#title").val(),
					vid: $("#vid").val(),
					content: $("#content").val(),
					country_id: $("#country_id").val(),
					address: $("#address").val(),
					time: $("#time").val(),
					phone: $("#phone").val(),
					city: $("#city").val(),
					url: $("#url").val()
		        },
		        function(resp) {					
					resp1=eval('('+resp+')');
					for(var key in resp1) {
						if (key == 'alias_country') var a_c = resp1[key];
						if (key == 'alias_restaurant') var a_r = resp1[key];
						if (key == 'alias_city') var a_city = resp1[key];
					}
					if (resp != 'err') { 
						core_redirect('/restaurant/' +a_c+'/'+a_city+'/'+a_r );
					}
					if (resp == 'err') { 
						alert('You can not edit a restaurant. Ask the reason for administrator.');
					}					
				}
		);
	}
}

//ADD new tur firma
function addNewTur(id_user, id_tur) {
	var err_title = 'err';
	var err_content = 'err';
	var err_rules = 'err';
	var err_country = 'err';
	var err_city = 'err';

	if ($("#title").val() == '') $("#err_title").text('Ошибка заполнения заголовка');
	else { err_title = 'ok'; $("#err_title").html(''); }
	
	if ($("#country_id").val() == '') $("#err_country").html('Вы не выбрали страну');
	else { err_country = 'ok'; $("#err_country").html('');}
	
	if ($("#city").val() == '') $("#err_city").text('Ошибка заполнения города');
	else { err_city = 'ok'; $("#err_city").html(''); }

	if ($("#content").val() == '') $("#err_content").text('Ошибка заполнения описания');
	else { err_content = 'ok'; $("#err_content").html(''); }
	//проверяем стоит ли отметка соглашение с правилами
	if ($("#rules:checked").length == 0) $("#err_rules").text("Вы не согласились с правилами публикации");
	else err_rules = 'ok';

	if (err_title == 'ok' && err_content == 'ok' && err_rules == 'ok' && err_country == 'ok' && err_city == 'ok')  {
		$.post('/', {
					action:'addNewTur',
					id_user: id_user,
					title: $("#title").val(),
					content: $("#content").val(),
					country_id: $("#country_id").val(),
					city: $("#city").val(),
					phone: $("#phone").val(),
					icq: $("#icq").val(),
					skype: $("#skype").val(),
					url: $("#url").val()
		        },
		        function(resp) {					
					resp1=eval('('+resp+')');
					for(var key in resp1) {
						if (key == 'alias_country') var a_c = resp1[key];
						if (key == 'alias_city') var a_city = resp1[key];
						if (key == 'alias_tur') var a_t = resp1[key];
					}
					core_redirect('/turfirmy/' + a_c + '/' + a_city + '/' + a_t);						
				}
		);
	}
}

//ADD new tur firma
function editTur(id_user, id_tur) {
	var err_title = 'err';
	var err_content = 'err';
	var err_rules = 'err';
	var err_country = 'err';
	var err_city = 'err';
	
	if ($("#title").val() == '') $("#err_title").text('Error');
	else { err_title = 'ok'; $("#err_title").html(''); }
	
	if ($("#country_id").val() == '') $("#err_country").html('You don`t select country');
	else { err_country = 'ok'; $("#err_country").html('');}

	if ($("#city").val() == '') $("#err_city").text('You don`t write city');
	else { err_city = 'ok'; $("#err_city").html(''); }

	if ($("#content").val() == '') $("#err_content").text('You don`t write text');
	else { err_content = 'ok'; $("#err_content").html(''); }

	if ($("#rules:checked").length == 0) $("#err_rules").text("Error");
	else err_rules = 'ok';

	if (err_title == 'ok' && err_content == 'ok' && err_rules == 'ok' && err_country == 'ok') {
		$.post('/', {
					action:'editTur',
					id_user: id_user,
					title: $("#title").val(),
					content: $("#content").val(),
					country_id: $("#country_id").val(),
					city: $("#city").val(),
					phone: $("#phone").val(),
					icq: $("#icq").val(),
					skype: $("#skype").val(),
					url: $("#url").val(),
					vid: $("#vid_id").val(),
					id_tur: $("#id_tur").val()
		        },
		        function(resp) {					
					resp1=eval('('+resp+')');
					for(var key in resp1) {
						if (key == 'alias_country') var a_c = resp1[key];
						if (key == 'alias_city') var a_city = resp1[key];
						if (key == 'alias_tur') var a_t = resp1[key];
					}
					core_redirect('/turfirmy/' +a_c+'/'+a_city+'/'+a_t );						
				}
		);
	}
}

//Добавление новой записи
function addNewItem(id_user, id_news) {
	var err_title = 'err';
	var err_tags = 'err';
	var err_content = 'err';
	var err_rules = 'err';
	var post = 0;
	
	if($("#check_01:checked").length != 0) post = $("#check_01").val();
	if($("#check_02:checked").length != 0) post = $("#check_02").val();
	if($("#check_03:checked").length != 0) post = $("#check_03").val();
	if($("#check_00:checked").length != 0) post = $("#check_00").val();

	//проверим заполнение полей
	//title
	if ($("#title").val() == '') $("#err_title").html('Error filling in the title');
	else { err_title = 'ok'; $("#err_title").html('');}

	//tags
	if ($("#tags").val() == '') $("#err_tags").html('Error filling in the tags');
	else { err_tags = 'ok'; $("#err_tags").html('');}

	//content
	if ($("#content").val() == '') $("#err_content").html('Error filling');
	else { err_content = 'ok'; $("#err_content").html('');}
	//проверяем стоит ли отметка соглашение с правилами
		if ($("#rules:checked").length == 0) {
			$("#err_rules").text("You do not agree with the rules of publishing");
		}
		else {
			err_rules = 'ok';
		}

	if (err_title == 'ok' && err_tags == 'ok' && err_content == 'ok' && err_rules == 'ok') {
		$.post('/', {
					action:'addNewItem',
					id_user: id_user,
					title: $("#title").val(),
					tags: $("#tags").val(),
					content: $("#content").val(),
					post_com: post
		        },
		        function(resp) {					
					if (resp != 'err') { 
						core_redirect('/article/' + resp);
					}
					else {
						alert('You can not add an article. Ask the reason for administrator.');
					}					
				}
		);
	}
}

//EDIT news
function editNewItem(id_user, id_news) {
	var err_title = 'err';
	var err_tags = 'err';
	var err_content = 'err';
	var err_url = 'err';
	var err_rules = 'err';
	var post = 0;
	var url_v, t, int_str, url;
	
	if($("#check_01:checked").length != 0) post = $("#check_01").val();
	if($("#check_02:checked").length != 0) post = $("#check_02").val();
	if($("#check_03:checked").length != 0) post = $("#check_03").val();
	if($("#check_00:checked").length != 0) post = $("#check_00").val();
	//проверим заполнение полей
	//title
	if ($("#title").val() == '') $("#err_title").html('Error filling in the title');
	else { err_title = 'ok'; $("#err_title").html('');}
	//tags
	if ($("#tags").val() == '') $("#err_tags").html('Error filling in the tags');
	else { err_tags = 'ok'; $("#err_tags").html('');}
	//content
	if ($("#content").val() == '') $("#err_content").html('Error filling');
	else { err_content = 'ok'; $("#err_content").html('');}
	//проверяем стоит ли отметка соглашение с правилами
		if ($("#rules:checked").length == 0) {
			$("#err_rules").text("You do not agree with the rules of publishing");
		}
		else {
			err_rules = 'ok';
		}
		
	var sec = $("#id_section").val();
	if (err_title == 'ok' && err_tags == 'ok' && err_content == 'ok' && err_rules == 'ok') {
		$.post('/', {
					action:'editNewItem',
					id_user: id_user,
					id_news: id_news,
					title: $("#title").val(),
					tags: $("#tags").val(),
					content: $("#content").val(),					
					post_com: post
		        },
		        function(resp) {
					
					if (resp != 'err') { 						
						core_redirect('/article/' + resp);
					}
					else {
						alert('You can not edit an article. Ask the reason for administrator.');
					}					
				}
		);
	}
}

function pastItem (i) { 
	$.post('/',{
		action:'pastItem'
	},
	function(resp){
		if (resp != 'err' && i==1)
			core_redirect('/author/'+resp+'?add=1');
	}
	);
}

function pastPhoto (i) { 
	$.post('/',{
		action:'pastPhoto'
	},
	function(resp){ 
		if (resp != 'err' && i==1) { 
			core_redirect('/author/'+resp+'?add_photo=1');
		}
	}
	);
}
function pastHotel (i) { 
	$.post('/',{
		action:'pastHotel'
	},
	function(resp){ 
		if (resp != 'err' && i==1) { 
			core_redirect('/author/'+resp+'?add_hotel=1');
		}
	}
	);
}
function pastRestaurant (i) { 
	$.post('/',{
		action:'pastRestaurant'
	},
	function(resp){ 
		if (resp != 'err' && i==1) { 
			core_redirect('/author/'+resp+'?add_restaurant=1');
		}
	}
	);
}
function pastTur (i) { 
	$.post('/',{
		action:'pastTur'
	},
	function(resp){ 
		if (resp != 'err' && i==1) { 
			core_redirect('/author/'+resp+'?add_tur=1');
		}
	}
	);
}
function pastExhibition (i) { 
	$.post('/',{
		action:'pastExhibition'
	},
	function(resp){ 
		if (resp != 'err' && i==1) { 
			core_redirect('/author/'+resp+'?add_exhibition=1');
		}
	}
	);
}
function chselitem(val, id) {
		$('#o'+val).attr('selected','selected');	
}

function del_from_fav_ath(id_user, id) {
	$.post('/', {
		action:'del_from_fav_ath',
		id_1: id_user,
		id_2: id				
	},
	function(resp) {					
		if (resp == 'ok') {
			document.location.reload();
		}
		else {
			alert('You can not remove the author. Ask the reason for administrator');
		}
					
	}
	);
}

<!-- Profile -->
function show_hint_Div (t) {
	if (t=='ok') {
		$("#pf_info").hide();
		$("#pf_red_pas").hide();
		$("#pf_red_info").show();
	}
	if (t=='no') {
		$("#pf_red_info").hide();
		$("#pf_info").show();
	}
	if (t=='pas') {
		$("#pf_info").hide();
		$("#pf_red_info").hide();
		$("#pf_red_pas").show();
	}
	if (t=='no_pas') {
		$("#id_user_old_pas").attr("value",'');
		$("#id_user_pas1").attr("value",'');
		$("#id_user_pas2").attr("value",'');
		$("#pf_red_pas").hide();
		$("#pf_info").show();
	}
}

function change_pas(id_user) {
	var err_old_pas = 'err';
	var err_pas1 = 'err';
	var err_pas2 = 'err';
	
	//проверим заполнение полей
	//old pas
	if ($("#id_user_old_pas").val() != '') err_old_pas = 'ok'; 

	//pas 1
	if ($("#id_user_pas1").val() != '') err_pas1 = 'ok'; 
	
	//pas 2
	if ($("#id_user_pas2").val() != '') err_pas2 = 'ok'; 
	
	if (err_old_pas == 'err' || err_pas1 == 'err' || err_pas2 == 'err') alert('Fields are not fill!');
	else {
		//проверяем совпадают ли новые пароли
		if ($("#id_user_pas1").val() != $("#id_user_pas2").val()) {
			alert('New passwords do not match!');
		}
		else {
			$.post(
			'/',
			{
				action: 'change_password',
				old_pas: $("#id_user_old_pas").val(),
				new_pas: $("#id_user_pas2").val(),
				id_user: id_user
			},
			function(resp){
				if (resp == 'err_old') {
					alert('You entered an invalid old password!');	
				}
				if (resp == 'ok') {
					alert('You have successfully changed the password!');
					$("#id_user_old_pas").attr("value",'');
					$("#id_user_pas1").attr("value",'');
					$("#id_user_pas2").attr("value",'');
					$("#pf_red_pas").hide();
					$("#pf_info").show();
				}
				if (resp == 'err') {
					alert('Unable to change password! Please contact the site administrator.');	
				}
			}
			);
		}
	}
}

function change_info(id_user) {
	var post1 = 0;
	var post2 = 0;
	var post3 = 0;
	var post4 = 0;
	var birth = '1955-05-05';
	
	if($("#id_ch_user_name:checked").length != 0) post1 = 1;
	if($("#id_ch_user_icq:checked").length != 0) post2 = 1;
	if($("#id_ch_user_skype:checked").length != 0) post3 = 1;
	if($("#id_ch_user_phone:checked").length != 0) post4 = 1;
	
	if ($("#id_year").val() != '' && $("#id_year").val() > 1910 && $("#id_year").val() < 2005) {
		var year = $("#id_year").val();
		$("#err_prof").html('');
	}
	else {
		if ($("#id_year").val() != '') {
			$("#err_prof").html('Date of birth - an error filling!');	
			return false;
		}
		else $("#err_prof").html('');
	}
	var day = $("select#id_day").val();
	var month = $("select#id_month").val();
	if (day > 29 && month == 2) {
		$("#err_prof").html('Date of birth - an error filling!');
		return false;
	}
	
	if (day < 10) day = '0'+day;
	if (month < 10) month = '0'+month;
	
	if ($("#id_year").val() != '' && $("#id_year").val() > 1910 && $("#id_year").val() < 2005) {
		birth = year+'-'+month+'-'+day;
	}
	
	//проверим заполнение полей
	$.post(
			'/',
			{
				action: 'change_info',
				ch_user_name: post1,
				ch_user_icq: post2,
				ch_user_skype: post3,
				ch_user_phone: post4,
				user_name: $("#id_user_name").val(),
				user_icq: $("#id_user_icq").val(),
				user_skype: $("#id_user_skype").val(),
				user_phone: $("#id_user_phone").val(),
				user_info: $("#id_user_info").val(),
				id_user: id_user,
				birth:birth,
				country:$("#id_user_country").val(),
				region:$("#id_user_region").val()
			},
			function(resp){
				if (resp == 'ok') {
					alert('You have successfully changed the data in your profile!');
					$("#pf_red_info").hide();
					$("#pf_info").show();
					document.location.reload();
				}
				if (resp == 'err') {
					alert('Unable to change the data! Please contact the site administrator.');	
				}
			}
		); 
}

function check_birth (d, m) {
	$("#id_day_"+d).attr("selected","selected");
	$("#id_month_"+m).attr("selected","selected");
}
//add comment
function add_comment(type)  { 
         	var message_text = document.getElementById("commentText").value;
         	var url = window.location;
         	var email = document.getElementById("radio_02").checked;
         	$('#add_comm_but').attr('disabled','disabled');
			url = "'" + url + "'";
			var a;
			if (type == 'news') a = 'insert_comment_to_db1'; 
			if (type == 'article') a = 'insert_comment_to_db2';
			if (type == 'photo') a = 'insert_comment_to_db3';
			//проверим заполнение полей
			if (message_text != '') {
     			$.post(
				'/',
				{
					action: a,
					text: message_text,
					e: email,
					type: type,
					url: url
                 },
             	function(resp) { 
                  	if (resp == 1) {
                  		$(document).ready(function() {
                  			document.getElementById('commentText').value = '';
                  		}
                  		);
                       	window.location=url+'#view_comm';
                  		window.location.reload();
                  	}
					
					if (resp == 2) alert('We have not this item!');
					if (resp == 3) alert('We have not this user!');
					if (resp == 3) alert('We can not to add your coment! Please to write E-mail admin.');
              	});
                $('#add_comm_but').attr('disabled','');
			}
			else {
				alert('You did not write a comment!');	
				$('#add_comm_but').attr('disabled','');
			}
	}

// checking length of element
function checkLenItem(field_id, field_to_write_id, max_field_len) {
           var str = document.getElementById(field_id).value;
           var len = max_field_len - str.length;
           if (len<0)
           {
                 document.getElementById(field_id).value = str.substr(0,max_field_len);
                 len = 0;
           }
           document.getElementById(field_to_write_id).innerHTML = len;
} 

function addExhibition(id_user) {
	var title = $("#title").val();
	var s_day = $("#id_start_day").val();
	var s_month = $("#id_start_month").val();
	var s_year = $("#id_start_year").val();
	var e_day = $("#id_end_day").val();
	var e_month = $("#id_end_month").val();
	var e_year = $("#id_end_year").val();	
	var lead = $("#e_lead").val();
	var country_id = $("#country_id").val();
	var city = $("#city").val();
	var content = $("#my_textarea_id").val();
	var place = $("#e_place").val();
	var organizatory = $("#e_organizatory").val();
	var vid = $("#e_vid").val();
	var grupe = $("#e_grupe").val();
	var err_rules = 'err';
	
	if ($("#rules:checked").length == 0) {
		$("#err_rules").text("You do not agree with the rules of publishing");
	}
	else {
		err_rules = 'ok';
	}
	if (s_year < 2010 || e_year < 2011) alert('Check the start and end dates of the exhibition!');
	if (title != '' && s_day != '' && s_month != '' && s_year != '' && e_day != '' && e_month != '' && e_year != '' && lead != '' && country_id != '' && city != '' && err_rules == 'ok' && id_user != '' && id_user != 0) {
		$.post('/',{
			action:'add_new_exhibition',
			title: title,
			s_day: s_day,
			s_month: s_month, 
			s_year: s_year,
			e_day: e_day,
			e_month: e_month, 
			e_year: e_year,	
			lead: lead,
			country_id: country_id,
			city: city,
			content: content,
			place: place,
			o: organizatory,
			vid: vid,
			grupe: grupe,
			id_user: id_user
		},
		function(resp){
			if (resp == 'err_date') alert('Check the start and end dates of the exhibition!');
			if (resp == 'err1') alert('This exhibition has already been added!');
			if (resp != 'err_date' && resp != 'err' && resp != 'err1') core_redirect('/exhibition');
		});
	}
	else {
		alert('You did not complete all the required fields!');	
	}
}

function add_new_article() {
	var err_title;
	var err_content;
	var err_name;
	var err_mail;
	var title, content, uname, umail, uid;
	title = $("#title").val();
	content = $("#content").val();
	if (title == '') {
		$("#err_title").text("Error filling in the title");
		err_title = 'err';
	}
	else {
		$("#err_title").text("");
		err_title = 'ok';	
	}
	
	if (content == '') {
		$("#err_content").text("Error filling in the content");
		err_content = 'err';
	}
	else {
		$("#err_content").text("");
		err_content = 'ok';	
	}
	
	//check login or not
	$.post('/',{
			action:'check_login_user'
	},
	function(resp){ 
		if (resp == 'err') {
				uname = $("#uname").val();
				if (uname == '') {
					$("#err_uname").text("Error filling in the name");
					err_name = 'err';
				}
				else {
					$("#err_uname").text("");
					err_name = 'ok';	
				}
				
				umail = $("#umail").val();
				if (umail == '' || !checkmail(umail)) {
					$("#err_umail").text("Error filling in the E-mail");
					err_mail = 'err';
				}
				else {
					$("#err_umail").text("");
					err_mail = 'ok';	
				}
				//proveryaem dobavlen li takoj polzovatel
				if (err_name == 'ok' && err_mail == 'ok') {
					$.post('/',{
						action:'check_user',
						mail: umail
					},
					function(resp1){
						if (resp1 != 'err') {
							uid = resp1;
							err_name = 'ok';
							err_mail = 'ok';
							if (err_name == 'ok' && err_mail == 'ok' && err_title == 'ok' && err_content == 'ok') {
								//type = 0 - user to added, but not login
								$.post('/',{
									action:'add_country_content',
									url:'##'+window.location+'##',
									user_id:uid,
									title:title,
									content:content
								},
								function(resp3){
									document.location.reload();
								});
							}
						}
						else {
							//regestriruem polzovatelya
							$.post('/',{
								action:'registration_user',
								email:umail,
								name:uname,
								s:1
							},
							function(resp2){
								resp2=eval('('+resp2+')');
								if(resp2.ok=='yes') {
									uid = resp2.id;
									err_name = 'ok';
									err_mail = 'ok';
									if (err_name == 'ok' && err_mail == 'ok' && err_title == 'ok' && err_content == 'ok') {
										//type = 1 - registred, and to add content
										$.post('/',{
											action:'add_country_content',
											url:'##'+window.location+'##',
											user_id:uid,
											title:title,
											content:content
										},
										function(resp3){
											document.location.reload();
										});
									}
								}
								else{
									alert('Error: you can not to add content on this web page.');
									//alert(resp2.error||resp2);
									err_name = 'err';
									err_mail = 'err';
								}
							});							
						}
					});
				}
			}
			else {
				err_name = 'ok';
				err_mail = 'ok';
				uid=resp;
				if (err_name == 'ok' && err_mail == 'ok' && err_title == 'ok' && err_content == 'ok') {
					//type = 2 - user logined
					$.post('/',{
						action:'add_country_content',
						url: '##'+window.location+'##',
						user_id:uid,
						title:title,
						content:content
					},
					function(resp3){
						document.location.reload();
					});
				}
			}
	});
}
