function showDiv (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 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);
	}
}



var crop_popup=function(href){
	general_popup(href,'CropWindow','auto',500,500);
}

// deletes comment if user can do it :)
function delete_comment(comm_id) {
	// CONFIRM REQUIRES ONE ARGUMENT
	var message = "Вы уверены, что хотите удалить этот комментарий?";

	                // CONFIRM IS BOOLEAN. THAT MEANS THAT
	                // IT RETURNS TRUE IF 'OK' IS CLICKED
	                // OTHERWISE IT RETURN FALSE
	var return_value = confirm(message);

	                // TEST TO SEE IF TRUE|FALSE RETURNED
	if (return_value == true) {
		            // YOUR 'OK' SCRIPT GOES HERE
		            $.post(
		                 '/',
		                  {
			                action:'deleter_2',
			                comment_id: comm_id
		                  },
		              function(resp)
		              {
		              	 if (resp == 1) {
		              	 	var comm_identifier = '#comment_' + comm_id;
		              	 	$(''+comm_identifier+'').hide();
		              	 	// recalculating number of comments to current article
		              	 	get_comments_number();
		              	 }
			             else alert('Не удалось удалить комментарий!');
		              }
	               );
	} 
}
			   
// Admin VIDEO
function add_video(id_news) {   
	if ($("#video_id").val() == '') alert('Вы не ввели код видео!');
	else { 
		$.post(
		'/',
		{
			action: 'add_video',
			id_news: id_news,
			text_video: $("#video_id").val()
		},
		function(resp){
			if (resp == 'ok') {
				$("#video_id").attr("value", "");
				alert('Вы успешно добавили видео!');				
			}
			else {
				alert('Вы не добавили видео. Обратитесь к администратору.');
			}
		}
	);
	}
}

// Admin Delete VIDEO
function del_video(id) {   
	if (id != '') { 
		$.post(
		'/',
		{
			action: 'del_video',
			id: id,
		},
		function(resp){
			if (resp == 'ok') {
				$("#video_id").attr("value", "");
				alert('Вы успешно удалили видео!');
				document.location.reload();
			}
			else {
				alert('Вы не удалили видео. Обратитесь к администратору.');
			}
		}
	);
	}
}

// generating select block
// we need function for setting selected value to current element
// curr - element which select user
function generateSelect() {
	// getting current link
    strHref = window.location.href;
    urlArr = new Array();
    nameArr = new Array();

    outputString = '<select name="section" style="width:144px; margin:5px 5px 0 0;" onchange="dropdown_top(this);">';
   	for (i=0; i<urlArr.length; i++)
      {
        myRegExp2 = urlArr[i];
        matchPos2 = strHref.search(myRegExp2);
        if (matchPos2 > -1)
          {
            outputString = outputString + '<option value="' + urlArr[i] + '" selected>'+ nameArr[i] +'</option>';
          }
        else outputString = outputString + '<option value="' + urlArr[i] + '">'+ nameArr[i] +'</option>';
       }
     outputString = outputString + '</select>';
     return outputString;

}

//функции для какртинок на странице новости
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();
					//first page other style
					$('#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', 'aspan2').attr('id', 'p_link_'+i).html(i).appendTo('#pic_pages')
					.click(function() {
					});
						$('<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 is used to check all page
// for right inputted data in form
// before sending to DB   
function prepare_send_db_IMG() { 
      // varialbe for sendingOK
      var sendingOK = 0;
      // checking if all input fields are filled
      // getting values of input fields
      var img_path_input = document.getElementById('file_id').value;
      if (img_path_input.length != 0) {
      	  // alert ('Все в порядке, данные готовы к отсылке в БД!');
          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 ('Формат файла недопустим!'); 
      	  	return false;
      	  }
        }
      else {
       	  alert ('Пожалуйста, укажите путь к загружаемому файлу!');
       	  return false;
       }
}


function get_name_subsec(sec, subsec) { 
//нужно вернуть названия подкатегорий
	var str = '';
	$.post('/', {
					action:'get_name_subsec',
					name_sec: sec, 
					name_subsec:subsec
		        },
		        function(resp) {
					
		            if (resp != 'err' && resp != '') {
						$(".name_subsec").css('font-weight', 'bold').html(resp);
					}
	});
	return str;
}	

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;
	//datastr = day + ", "+ date +" "+ month +" "+ year +" | "+ hours + ":" + mins;
	return datastr;
}
