//setTimeout(function(){$('.flash_error').fadeOut('fast')},100000);
//setTimeout(function(){$('.flash_message').fadeOut('fast')},100000);

function add_reply(parent){
$("#addcomment").clone().addClass("reply_form").appendTo($("#reply_"+parent).closest("#reply_block"));
var $cancel = $(".reply_form").find(".cancel_reply");
$cancel.show();
document.getElementById("parent_comment").value=parent;
}

function cancel_reply(){
var $form = $('.reply_form');
$form.remove();
}

function order(value){
var value = $(value).val();
var link = window.location.href;
	$.ajax({
		type: "POST",
		url: link,
		data: {
			'order': value
		},
		success: function(data) {
			window.location.assign(window.location.href);
		}
	})
}

function sort(value){
var value = $(value).val();
var link = window.location.href;
	$.ajax({
		type: "POST",
		url: link,
		data: {
			'sort': value
		},
		success: function(data) {
			window.location.assign(window.location.href);
		}
	})
}

jQuery(function($) {

	/* Автозаполнитель поиска */
	$( ".fn-search.nimble" ).autocomplete({
		serviceUrl: '/ajax/live_search/get'+nimble.url_suffix+'?model='+nimble.model,
		minChars: 1,
		noCache: false,
		onSelect: function(suggestion) {
			$( "#fn-search" ).submit();
		},
		formatResult: function(suggestion, currentValue) {
			var reEscape = new RegExp( '(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join( '|\\' ) + ')', 'g' );
			var pattern = '(' + currentValue.replace( reEscape, '\\$1' ) + ')';
			return "<div>" + (suggestion.thumb_image ? "<img align=absmiddle src='" + suggestion.thumb_image + "'> " : '') + "<a href='" + suggestion.url + "'>" + suggestion.value.replace( new RegExp( pattern, 'gi' ), '<strong>$1<\/strong>' ) + "</a></div>";
		}
	});

});

$(document).ready(function() {

function check_certificate() {
	  	var form = $('#check-certificate');
		$('#subButton').on('click', function(){     
	  	if(form.length > 0){
		  	form.submit(function(event) {
			  	event.preventDefault();
				$.ajax({
				   url: '/ajax/demand/check_certificate'+nimble.url_suffix,
				   type: 'POST',
				   dataType: 'json',
				   data: form.serialize(),
				})
				.done(function(data) {
						//form[0].reset();
						//alert(JSON.stringify(data));
						$('#check-certificate-result').empty();
						var certificates = $("#check-certificate-result");
						if(data.suggestions.length > 0){
						$.each(data.suggestions, function(i,items){
							//alert(item[1].certificateName);
							certificates.append('<span><h3>'+items.fio+'</h3></span>');
							$.each(items.certificates, function(i,item){
							certificates.append('<li>'+item.certificateName+' (<strong>'+item.certificateNumber+'</strong>)'+' <a href="https://1c.ru/check-certificate/printcopy/'+item.typeGuid+'/'+item.certificateShortNumber+'/'+items.guid+'"><i class="fa fa-print"></i></a>'+' <a href="https://1c.ru/check-certificate/qrcode/'+item.typeGuid+'/'+item.certificateShortNumber+'/'+items.guid+'"><i class="fa fa-qrcode"></i></a>'+'</li>');
							});
						});
						}else{
							certificates.append('<h3>Сертификаты не найдены</h3><br>Данные появляются на следующий рабочий день, после получения автоматического письма.<br><br><strong>Полезная информация для подготовки к сдаче экзаменов 1С. Курс по подготовке. Описание сертификатов 1С и многое другое.</strong><ul><li>Обзорный курс для начинающих &quot;Старт в 1С&quot; - <a href="https://1c-study.ru/">https://1c-study.ru/</a></li><li>Комплект &quot;Три онлайн-курса для начинающих программистов, подготовка к тестированию &quot;1С:Профессионал&quot; по платформе &quot;1С:Предприятие 8&quot; - <a href="http://edu.1c.ru/start/">http://edu.1c.ru/start/</a></li><li>Онлайн-курс &quot;Подготовка к экзамену 1С:Специалист по платформе&quot; - <a href="http://edu.1c.ru/spec/">http://edu.1c.ru/spec/</a></li></ul><br><ul><li>Расписание экзаменов - <a href="http://1c.ru/spec/default.jsp">http://1c.ru/spec/default.jsp</a></li><li>1С:Профессионал - <a href="http://1c.ru/prof/prof.htm">http://1c.ru/prof/prof.htm</a></li><li>1С:Специалист &ndash; &nbsp;<a href="http://1c.ru/spec/texts/ekz_1c_spec.htm">http://1c.ru/spec/texts/ekz_1c_spec.htm</a></li><li>1С:Эксперт - <a href="http://1c.ru/rus/partners/training/expert.htm">http://1c.ru/rus/partners/training/expert.htm</a></li></ul>');
						}
						
				});
		  	});
	  	}
		});
	};
	
check_certificate();


function check_study_certificate() {
	  	var form = $('#check-study-certificate');
		$('#subButton').on('click', function(){     
	  	if(form.length > 0){

		  	form.submit(function(event) {
			  	event.preventDefault();
				$.ajax({
				   url: '/ajax/demand/check_study_certificate'+nimble.url_suffix,
				   type: 'POST',
				   dataType: 'json',
				   data: form.serialize(),
				})
				.done(function(data) {
						//form[0].reset();
						//alert(JSON.stringify(data));
						$('#check-study-certificate-result').empty();
						var certificates = $("#check-study-certificate-result");
						if(data.certificates.length > 0){
						certificates.append('<span><h3>'+data.fio+'</h3></span>');
							$.each(data.certificates, function(i,item){
							certificates.append('<li>'+item.Curs+' <a href="/account/get_study_certificate/?login='+item.login+'"><i class="fa fa-print"></i></a>'+'</li>');
							});
						}else{
							certificates.append('<h3>Удостоверения не найдены</h3>');
						}
						
				});
		  	});
	  	}
		});
	};
	
	check_study_certificate();
	
function check_uc1_certificate() {
	  	var form = $('#check-uc1-certificate');
		$('#subButton').on('click', function(){     
	  	if(form.length > 0){

		  	form.submit(function(event) {
			  	event.preventDefault();
				$.ajax({
				   url: '/ajax/demand/check_uc1_certificate'+nimble.url_suffix,
				   type: 'POST',
				   dataType: 'json',
				   data: form.serialize(),
				})
				.done(function(data) {
						//form[0].reset();
						//alert(JSON.stringify(data));
						$('#check-uc1-certificate-result').empty();
						var certificates = $("#check-uc1-certificate-result");
						if(data.certificates.length > 0){
						certificates.append('<span><h3>'+data.fio+'</h3></span>');
							$.each(data.certificates, function(i,item){
							certificates.append('<li>'+item.certificateTypeFullName+' (<strong>'+item.certificateNumber+'</strong>)'+' <a href="/account/get_study_certificate/?certificateNumber='+item.certificateNumber+'"><i class="fa fa-print"></i></a>'+'</li>');
							});
						}else{
							certificates.append('<h3>Удостоверения не найдены</h3>');
						}
						
				});
		  	});
	  	}
		});
	};
	
	check_uc1_certificate();

});

function update_komplekt_downloaded(val,demand_id) {
	if(val.is(':checked')){
        val = 1;
    } else {
        val = 0;
    }
    $.ajax({
        type: 'POST',
        url: '/ajax/demand/komplekt_downloaded'+nimble.url_suffix,
        data:{'komplekt_downloaded': val, 'demand_id': demand_id},
        success: function(data) {
			//window.location.assign(window.location.href);
		}
    });
}


function update_passport_show_all(val,token) {
    $.ajax({
        type: 'POST',
        url: '/ajax/edit_passport/show_all'+nimble.url_suffix,
        data:{'show_all': val, 'token': token},
        success: function(data) {
			window.location.assign(window.location.href);
		}
    });
}

function update_passport_show_email(val,token) {
    $.ajax({
        type: 'POST',
        url: '/ajax/edit_passport/show_email'+nimble.url_suffix,
        data:{'show_email': val, 'token': token},
        success: function(data) {
			window.location.assign(window.location.href);
		}
    });
}

function update_passport_show_phone(val,token) {
    $.ajax({
        type: 'POST',
        url: '/ajax/edit_passport/show_phone'+nimble.url_suffix,
        data:{'show_phone': val, 'token': token},
        success: function(data) {
			window.location.assign(window.location.href);
		}
    });
}

function update_passport_in_rate(val,token){
    $.ajax({
        type: 'POST',
        url: '/ajax/edit_passport/in_rate'+nimble.url_suffix,
        data:{'in_rate': val, 'token': token},
        success: function(data) {
			window.location.assign(window.location.href);
		}
    });	
}

function change_certificate_sort(val,token) {
   var el = $(val);
   $.ajax({
	   url: '/ajax/edit_passport/change_certificate_sort'+nimble.url_suffix, 
	   method: 'POST', 
	   data: {'sort': el.data('value'), 'token': token},
	   success: function(data) {
			window.location.assign(window.location.href);
		}
});
}

function validDate(date){ // date в формате 31.12.2014
  var d_arr = date.split('.');
  var d = new Date(d_arr[2]+'/'+d_arr[1]+'/'+d_arr[0]+''); // дата в формате 2014/12/31
  if (d_arr[2]!=d.getFullYear() || d_arr[1]!=(d.getMonth() + 1) || d_arr[0]!=d.getDate()) {
    return false; // неккоректная дата
  };
  return true;
}


//ajax формы
$(document).ready(function() {
	
$('#ajax_form').one('submit', function() {
    $(this).find('input[name="submit"]').attr('disabled','disabled');
});

function checkout_form() {
	  	var form = $('#ajax_form');
		$("#ajax_form").on('submit', function(e) {
		e.preventDefault();
		$(form).find('input[name="submit"]').attr('disabled','disabled');
		var formData = new FormData($(this)[0]);
		$.ajax({
            url: $(this).attr('action'),
            type: "POST",
            cache: false,
            async: false,
			cache: false,
			contentType: false,
			processData: false,
            data: formData,
            success: function(data) {
			var jsonData = JSON.parse(data);
			if (jsonData.success == "1")
            {
                location.href = jsonData.url;
            }else{
				$(form).find('input[name="submit"]').removeAttr('disabled');
				alert(jsonData.message);
			}
            },
            error: function(data) { // Данные не отправлены
				$(form).find('input[name="submit"]').removeAttr('disabled');
                alert('Что-то пошло не так...Попробуйте еще раз.');
				//$(form).find('input[name="submit"]').removeAttr('disabled');
            }
          });
		});
	};
	
checkout_form();

$('#ajax_save_form').one('submit', function() {
    $(this).find('button[name="submit"]').attr('disabled','disabled');
});

function save_form() {
	  	var form = $('#ajax_save_form');
		$("#ajax_save_form").on('submit', function(e) {
		e.preventDefault();
		$(form).find('button[name="submit"]').attr('disabled','disabled');
		var formData = new FormData($(this)[0]);
		$.ajax({
            url: $(this).attr('action'),
            type: "POST",
            async: false,
			cache: false,
			contentType: false,
			processData: false,
            data: formData,
            success: function(data) {
			var jsonData = JSON.parse(data);
			if (jsonData.success == "1")
            {
                location.href = jsonData.url;
            }else{
				$(form).find('button[name="submit"]').removeAttr('disabled');
				alert(jsonData.message);
			}
            },
            error: function(data) { // Данные не отправлены
				$(form).find('button[name="submit"]').removeAttr('disabled');
                alert('Что-то пошло не так...Попробуйте еще раз.');
				//$(form).find('input[name="submit"]').removeAttr('disabled');
            }
          });
		});
	};
	
save_form();


$('#ajax_external_reg_form').one('submit', function() {
    $(this).find('input[name="submit"]').attr('disabled','disabled');
});

function external_reg_form() {
	  	var form = $('#ajax_external_reg_form');
		$("#ajax_external_reg_form").on('submit', function(e) {
		e.preventDefault();
		$(form).find('input[name="submit"]').attr('disabled','disabled');
		$.ajax({
            url: $(this).attr('action'),
            type: "POST",
            cache: false,
            data: $(this).serialize(),
            success: function(data) {
			var jsonData = JSON.parse(data);
			if (jsonData.success == "1")
            {
                location.href = jsonData.url;
            }else{
				$(form).find('input[name="submit"]').removeAttr('disabled');
				alert(jsonData.message);
			}
            },
            error: function(data) { // Данные не отправлены
				$(form).find('input[name="submit"]').removeAttr('disabled');
                alert('Что-то пошло не так...Попробуйте еще раз.');
				//$(form).find('input[name="submit"]').removeAttr('disabled');
            }
          });
		});
	};
	
external_reg_form();

$('#ajax_login_form').one('submit', function() {
    $(this).find('button[name="submit"]').attr('disabled','disabled');
});

function login_form() {
	  	var form = $('#ajax_login_form');
		$("#ajax_login_form").on('submit', function(e) {
		e.preventDefault();
		$(form).find('button[name="submit"]').attr('disabled','disabled');
		$.ajax({
            url: $(this).attr('action'),
            type: "POST",
            cache: false,
            data: $(this).serialize(),
            success: function(data) {
			var jsonData = JSON.parse(data);
			if (jsonData.success == "1")
            {
                location.href = jsonData.url;
            }else{
				$(form).find('button[name="submit"]').removeAttr('disabled');
				alert(jsonData.message);
			}
            },
            error: function(data) { // Данные не отправлены
				$(form).find('button[name="submit"]').removeAttr('disabled');
                alert('Что-то пошло не так...Попробуйте еще раз.');
				//$(form).find('input[name="submit"]').removeAttr('disabled');
            }
          });
		});
	};
	
login_form();

$('#ajax_send_friend_form').one('submit', function() {
    $(this).find('button[name="submit"]').attr('disabled','disabled');
});

function send_friend_form() {
	  	var form = $('#ajax_send_friend_form');
		$("#ajax_send_friend_form").on('submit', function(e) {
		e.preventDefault();
		$(form).find('button[name="submit"]').attr('disabled','disabled');
		$.ajax({
            url: $(this).attr('action'),
            type: "POST",
            cache: false,
            data: $(this).serialize(),
            success: function(data) {
			var jsonData = JSON.parse(data);
			if (jsonData.success == "1")
            {
                location.href = jsonData.url;
            }else{
				$(form).find('button[name="submit"]').removeAttr('disabled');
				alert(jsonData.message);
			}
            },
            error: function(data) { // Данные не отправлены
				$(form).find('button[name="submit"]').removeAttr('disabled');
                alert('Что-то пошло не так...Попробуйте еще раз.');
				//$(form).find('input[name="submit"]').removeAttr('disabled');
            }
          });
		});
	};
	
send_friend_form();

});