function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
$(document).ready(function() {
    //Ajax setup
    $.ajaxSetup({
        cache: false,
        type: 'POST',
        dataType: 'html',
        beforeSend: function(xhr, settings) {
            if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            }
        }
    });
});
$(document).ready(function() {	
	var next_rotator_item = 1;
	var rotator_items = $("#RotatorItems div.RotatorItem").length;
	var is_auto = false;
    
	$("#MainRotatorLink").click(function(){return false;});
	
    function AnimateRotator(obj){
		if (!obj.hasClass('Active')) {
			var old_selected_objects = $(".RotatorItem.Active");
			$(".RotatorItem.Active > .RotatorItemText").slideUp(400, function(){
				old_selected_objects.removeClass("Active");
			});
			obj.addClass("Active");
			obj.children(".RotatorItemText").slideDown(400);
			next_rotator_item = (next_rotator_item + 1) % rotator_items;
			if (!is_auto) {
				clearInterval(intervalID);
			}
			$("#MainRotatorImage").attr('src', obj.attr('image'));
            $("#MainRotatorLink").attr('href', obj.attr('imagehref'));
            if (obj.attr('imagehref') == '#') {
                $("#MainRotatorLink").click(function(){return false;});
            }
            else {
                $("#MainRotatorLink").unbind('click');
            }
            
		}
		return false;
	}
	$(document.body).click(function(){
		$(".ButtonSelectPopup:visible").hide();
	});
	
	$(".RotatorItem").click(function(){
		AnimateRotator($(this));
	});
	if ($("#RotatorItems div.RotatorItem").length > 1) {
		// Start rotator cycle
		var intervalID = setInterval(
			function(){
				is_auto = true;
				AnimateRotator($("#RotatorItems div.RotatorItem:eq("+next_rotator_item+")"));
				is_auto = false;
			},
			10000
		);
	}
	
	$("span.ButtonMenu > i > a").click(function(){
		$(".ButtonSelectPopup").show();
		return false;
	});
	
	$("#ClosePopup").click(function(){
		$("#HideBlock, #PopupWindow").hide();
		return false;
	});
	$("#FormSelectorLink, #AllFormList > li > a, .FormCustomLink").click(function(){
		$(".ButtonSelectPopup").hide();
		$("#HideBlock").show();
		var form_type = $(this).attr("type");
        var form_name = $(this).html();
		data = {draw_form: form_type};
		if ($(this).attr("type") == 'question') {
			data['catid'] = $(".DoctorInfo[catid]:eq(0)").attr("catid");
		}
		$.ajax({
			url: '/forms/',
			type: "GET",
			data: data,
			dataType: 'html',
			error:function(){
				alert('error');
				$("#HideBlock").hide();
			},
			success: function(html){
				$("#FormContent").html(html);
				if (form_type == 'doctor_question') {
					$("#id_catid").val($("#CategoryItemId").attr('itemid'));
				}
				if (form_type == 'doctor_question' && $("#DoctorItemId").attr('itemid') > 0) {
					$("#id_doctor").val($("#DoctorItemId").attr('itemid'));
				}
				if (form_type == 'category_question' && $("#CategoryItemId").attr('itemid') > 0) {
					$("#id_category").val($("#CategoryItemId").attr('itemid'));
				}
				if (form_type == 'program' && $("#ProgramItemId").attr('itemid') > 0) {
					$("#id_program").val($("#ProgramItemId").attr('itemid'));
				}
                $("#PopupWindow h1:eq(0)").html(form_name);
				$("#PopupWindow").show();
				
			}
		});
		return false;
	});
	
	$("#AskQuestionButton").click(function(){
		if ($(this).hasClass("NotClickable")) {
			return false;
		}
		var this_obj = $(this);
        this_obj.addClass("NotClickable");
		data = $('#FormContent > form').serializeArray();
		$.ajax({
			url: "/forms/",
			type: "POST",
			dataType: 'json',
			data: data,
			error: function(){
				this_obj.removeClass("NotClickable");
				alert("Во время отправки письма произошла ошибка.\nВозможно вы указали неверный адрес элекстронной почты.");
			},
			success: function(obj){
				this_obj.removeClass("NotClickable");
				$('#FormContent span.errors').remove();
				if (obj.errors) {
					for (var item in obj.errors) {
						tag = '<span class="errors">'+obj.errors[item]+'</span>';
						if (item == 'captcha') {
							item = 'captcha_0';
						}
						$("#FormContent #id_"+item).parent().append(tag);
					}
					$("#FormContent a[href=#refresh]").click();
					return false;
				}
				if (obj.message) {
					alert(obj.message);
				}
				$("#ClosePopup").click();
			}
		});
		return false;
	});
});
