var num_photo = 0;
var num_file = 0;

function Check_Register_Form()
{
	id_name = $('#id_name').val();
	id_desc = $('#id_desc').val();
	id_address = $('#id_address').val();
	id_phone = $('#id_phone').val();
	
	if(id_name == '')
	{
		alert('Не заполнено Название организации');
		return false;
	}
	if(id_desc == '')
	{
		alert('Не заполнено Описание деятельности');
		return false;
	}
	if(id_address == '')
	{
		alert('Не заполнен Адрес');
		return false;
	}
	if(id_phone == '')
	{
		alert('Не заполнено Телефоны');
		return false;
	}
	return true;
}

function Register_Add_Photo()
{
	if(num_photo == 20)
	{
		alert('Более 20 фотографий добавить нельзя.');
		return false;
	}
	num_photo++;
	$('#photos').append('<p>'+num_photo+'.&nbsp;<input type="file" name="photo['+num_photo+']" /></p>');
}

function deletePhoto(id_photo)
{
	$.ajax({
	   type: "GET",
	   url: "/my-page-delete-photo?id="+id_photo,
	   data: "ajax=1",
	   success: function(data){
	     if(data == 1)
	     {
	     	$('#photos_'+id_photo).empty();
	     }
	   }
	 });
}

function Register_Add_File()
{
	if(num_file == 10)
	{
		alert('Более 10 файлов добавить нельзя.');
		return false;
	}
	num_file++;
	$('#files').append('<p>'+num_file+'.&nbsp;<input type="file" name="file['+num_file+']" /></p>');
}

function Register_Add_File2()
{
	if(num_file == 10)
	{
		alert('Более 10 файлов добавить нельзя.');
		return false;
	}
	num_file++;
	$('#files').append('<p>'+num_file+'.&nbsp;<input type="file" name="file['+num_file+']" />');
	$('#files').append('Название: <input type="text" name="file_title['+num_file+']" value="" /></p>');
	
}

function deleteFile(id)
{
	$.ajax({
	   type: "GET",
	   url: "/my-page-delete-file?id="+id,
	   data: "ajax=1",
	   success: function(data){
	     if(data == 1)
	     {
	     	$('#files_'+id).empty();
	     }
	   }
	 });
}

function submitOnEnter(event, formElem)
{
	if((event.keyCode == 0xA)||(event.keyCode == 0xD))    
	{
		document.login.submit();
	}
}

function checkAddTender()
{
	id_cat = $('#id_cat').val();
	
	title = $('#title').val();
	
	var oFCKeditor = FCKeditorAPI.GetInstance($('#descr').attr('name')) ;
	descr = oFCKeditor.GetXHTML( true );
	
	tender_start_year = $('#tender_start_year').val();
	tender_start_month = $('#tender_start_month').val();
	tender_start_day = $('#tender_start_day').val();
	
	tender_finish_year = $('#tender_finish_year').val();
	tender_finish_month = $('#tender_finish_month').val();
	tender_finish_day = $('#tender_finish_day').val();
	
	$.post("/check-create-edit-tender", 
	{
		ajax: '1',
		id_cat: id_cat,
		title: title,
		descr: descr,
		tender_start_year: tender_start_year,
		tender_start_month: tender_start_month,
		tender_start_day: tender_start_day,
		tender_finish_year: tender_finish_year,
		tender_finish_month: tender_finish_month,
		tender_finish_day: tender_finish_day
	 },
		function(data){
			data = data.split('|');
     		o_error = 0;
     		for(var i in data)
     		{
     			if(data[i] != '')
     			{
     				o_error = 1;
     				$('#'+data[i]).addClass("red");
     			}
     		}
     		if(o_error == 0)
			{
				document.tender.submit();
			}
			else
			{
				return false;
			}
     	});
}

function checkAddCatalog()
{
    id_parent_cat = $('#id_parent_cat').val();
	title = $('#title').val();
    
    var oFCKeditor = FCKeditorAPI.GetInstance($('#descr').attr('name')) ;
	descr = oFCKeditor.GetXHTML( true );
    
    $.post("/save-create-catalog", 
	{
		ajax: '1',
		id_parent_cat: id_parent_cat,
		title: title,
		descr: descr
	 },
		function(data){
            if(data == '0')
            {
                alert('Заполните все обязательные поля формы.');
                return false;
            }
            else
            {
                document.offer.submit();
                return false;
            }
     	});
}

function checkAddOffer()
{
	id_cat = $('#id_cat').val();
	id_parent_cat = $('#id_parent_cat').val();
	
	title = $('#title').val();
	//descr = $('#descr').val();
	
	var oFCKeditor = FCKeditorAPI.GetInstance($('#descr').attr('name')) ;
	descr = oFCKeditor.GetXHTML( true );
	
	offer_start_year = $('#offer_start_year').val();
	offer_start_month = $('#offer_start_month').val();
	offer_start_day = $('#offer_start_day').val();
	
	offer_finish_year = $('#offer_finish_year').val();
	offer_finish_month = $('#offer_finish_month').val();
	offer_finish_day = $('#offer_finish_day').val();
	
	$.post("/check-create-edit-offer", 
	{
		ajax: '1',
		id_cat: id_cat,
		id_parent_cat: id_parent_cat,
		title: title,
		descr: descr,
		offer_start_year: offer_start_year,
		offer_start_month: offer_start_month,
		offer_start_day: offer_start_day,
		offer_finish_year: offer_finish_year,
		offer_finish_month: offer_finish_month,
		offer_finish_day: offer_finish_day
	 },
		function(data){
			data = data.split('|');
     		o_error = 0;
     		for(var i in data)
     		{
     			if(data[i] != '')
     			{
     				o_error = 1;
     				$('#'+data[i]).addClass("red");
     			}
     		}
     		if(o_error == 0)
			{
				document.offer.submit();
			}
			else
			{
				return false;
			}
     	});
}

function checkAddNews()
{
	title = $('#title').val();
	var oFCKeditor = FCKeditorAPI.GetInstance($('#text').attr('name')) ;
	text = oFCKeditor.GetXHTML( true );
	$.post("/check-create-edit-news", 
	{
		ajax: '1',
		title: title,
		text: text
	 },
		function(data){
			data = data.split('|');
     		o_error = 0;
     		for(var i in data)
     		{
     			if(data[i] != '')
     			{
     				o_error = 1;
     				$('#'+data[i]).addClass("red");
     			}
     		}
     		if(o_error == 0)
			{
				document.news.submit();
			}
			else
			{
				return false;
			}
     	});
}

$(document).ready(
	function(){
		$('dl.noscript').removeClass('noscript');

		$.fn.wait = function(time, type){
			
			time = time || 100;
			type = type || 'fx';
			
			return this.queue(type, function() {
	            var self = this;
	            setTimeout(function() {
	                $(self).dequeue();
	            }, time);
	        });
		};

	}
);
/*
$(function(){
	$('dl.tabs dt').click(function(){
		$(this)
			.siblings().removeClass('selected').end()
			.next('dd').andSelf().addClass('selected');
	});
});
*/
$(function(){
	$('.table-list tr').hover(
			function(){
				$(this).addClass('hover');
			},
			function(){
				$(this).removeClass('hover');
			}
	);
});

function commentArea()
{
	$('#comment-area').toggle();
}

function commentSubmit(id_news)
{
	var oFCKeditor = FCKeditorAPI.GetInstance($('#textarea').attr('name')) ;

	user_text = oFCKeditor.GetXHTML( true );
	
	$.post("/news-post-comment", 
	{
		ajax: '1',
		id_news: id_news,
		text: user_text
	 },
		function(data){
			data = data.split('|');
			status = data[0];
			data = data[1];
			if(status == 0)
			{
				$('#errors_out').html(data);
				$('#errors_out').show();
			}
			else if(status == 1)
			{
				$('#no-comment').hide();
				$('#comments-list').append(data);
				$('#comment-area').toggle();
				oFCKeditor.SetData('');
			}
     	});
}

var num_file = 0;
function Tenders_Add_File()
{
	if(num_file == 10)
	{
		alert('Более 10 файлов добавить нельзя.');
		return false;
	}
	num_file++;
	$('#files').append('<b>Файл '+num_file+':</b><br /><br />Введите название файла:&nbsp;<input type="text" name="file_title['+num_file+']" /><br />');
	$('#files').append('Выберите файл:&nbsp;<input type="file" name="file['+num_file+']" /><br /><br />');
}

function DeleteTender(id)
{
	$.ajax({
	   type: "GET",
	   url: "/delete-tender-file",
	   data: "ajax=1&id="+id,
	   success: function(data){
	     if(data == 1)
	     {
	     	$('#file_have_'+id).empty();
	     }
	   }
	 });
}

$(function(){
	$('#new-users, #leaders').accordion({
		active: false,
		autoHeight: false,
		event: 'mouseover'
	});
        
        var no_clicked = true;
        
        $('.users_out_block_left').click(function() {
            $('#s1').removeAttr('checked');
            $('#s2').attr('checked', 'checked');
            $('#jackdaw2').show();
            $('#jackdaw1').hide();
           $('.users_out_block_right').removeClass('block-orange');
           $('.users_out_block_left').addClass('block-blue');
           no_clicked = false;
        });
        
        $('.users_out_block_right').click(function() {
            $('#s2').removeAttr('checked');
            $('#s1').attr('checked', 'checked');
            $('#jackdaw1').show();
            $('#jackdaw2').hide();
           $('.users_out_block_left').removeClass('block-blue');
           $('.users_out_block_right').addClass('block-orange');
           no_clicked = false;
        });
        
        
            $(".users_out_block_left").hover(
              function () {
                if(no_clicked) {
                    $(this).addClass("block-blue");
                }
              },
              function () {
                  if(no_clicked) {
                      $(this).removeClass("block-blue");
                  }
              }
            );

            $(".users_out_block_right").hover(
              function () {
                  if(no_clicked) {
                      $(this).addClass("block-orange");
                  }
              },
              function () {
                  if(no_clicked) {
                    $(this).removeClass("block-orange");
                  }
              }
            );
});

function sendMailTo()
{
	var u_name = $('#u_name').val();
	var u_email = $('#u_email').val();
	var u_phone = $('#u_phone').val();
	var u_text = $('#u_text').val();
	
	u_text = str_replace('&', 'and', u_text);
	
	$.ajax({
	   type: "POST",
	   url: "/send-mail-to",
	   data: "ajax=1&u_name="+u_name+"&u_text="+u_text+"&u_email="+u_email+"&u_phone="+u_phone,
	   success: function(data){
	     if(data == 1)
	     {
	     	$('#send_mail').toggle();
	     	alert('Ваше сообщение успешно отправлено.');
	     }
	     else
	     {
	     	alert('Ошибка при отправке сообщения. Обратитесь к администратору портала.');
	     }
	   }
	 });
}

function AddCatalogNewPhoto()
{
    $('#new_photo').append('<br/><br/><input type="file" name="photo[]" />');
}

function OpenCatalog(id)
{
    $('#openwindow').remove();
    $.ajax({
	   type: "POST",
	   url: "/catalog-one?id="+id,
	   data: "ajax=1",
	   success: function(data){
           $('body').append('<div id="openwindow">'+data+'</div>');
           
            for(var i=0; i<catalog_arr.length; i++) 
            {
              if(catalog_arr[i] == id)
              {
                  if(catalog_arr[i+1] != undefined)
                  {
                      $('#catalog_next').html('<a href="javascript:void(0);" onclick="OpenCatalog('+catalog_arr[i+1]+');return false;" class="one-button">Далее &raquo;</a>');
                  }
                  if(catalog_arr[i-1] != undefined)
                  {
                      $('#catalog_prev').html('<a href="javascript:void(0);" onclick="OpenCatalog('+catalog_arr[i-1]+');return false;" class="one-button">&laquo; Назад</a>');
                  }
              }
            }
	   }
	 });
    
}

function changePhoto(img_o)
{
    old_src = $('#catalog_main_photo').attr('src');
    new_src = $(img_o).attr('src');
    new_src = new_src.split('_');
    $('#catalog_main_photo').attr('src', new_src[0]+'_2.jpg');
    old_src = old_src.split('_');
    //$(img_o).attr('src', old_src[0]+'_1.jpg');
}

function checkCatalogOrder()
{
    o_fio = $('#o_fio').val();
    o_phone = $('#o_phone').val();
    if(o_fio == '')
    {
        alert('Вы не заполнили поле "ФИО"');
        return false;
    }
    if(o_phone == '')
    {
        alert('Вы не заполнили поле "Телефон"');
        return false;
    }
    return true;
}

function str_replace ( search, replace, subject ) {	// Replace all occurrences of the search string with the replacement string
	// 
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Gabriel Paderni

	if(!(replace instanceof Array)){
		replace=new Array(replace);
		if(search instanceof Array){//If search	is an array and replace	is a string, then this replacement string is used for every value of search
			while(search.length>replace.length){
				replace[replace.length]=replace[0];
			}
		}
	}

	if(!(search instanceof Array))search=new Array(search);
	while(search.length>replace.length){//If replace	has fewer values than search , then an empty string is used for the rest of replacement values
		replace[replace.length]='';
	}

	if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
		for(k in subject){
			subject[k]=str_replace(search,replace,subject[k]);
		}
		return subject;
	}

	for(var k=0; k<search.length; k++){
		var i = subject.indexOf(search[k]);
		while(i>-1){
			subject = subject.replace(search[k], replace[k]);
			i = subject.indexOf(search[k],i);
		}
	}

	return subject;

}

