var is_saving = false;
var recursive = 0;
// Обработчик переходов по истории
var siteListener = function(newLocation) {
    var target = $.base64.decode(newLocation).split('-')
    switch (target[0]) {
        case 'c':
                $("ul.menu ul:visible").css("display", "none");
                if(parseInt(target[2])){
                    recursive = 1;
                    menu_click(target[2]);
                }
                recursive = 0;
                $("ul.menu").find("a[product_id = " + target[1] + "]").click();
                break;
        case 'nd':
                get_news_detail(target[1], target[2], target[3], false);
                break;
        case 'ind':
                get_important_news_detail(target[1], false);
                break;
        case 's':
                get_shareholders_page(target[1], false);
                break;                      
        case 'n':
                get_news(false);
                break;  
        case 'na':
                $.ajax({
                    async: false,
                    type: "post",
                    url: script_path + "news/news_header/",
                    success: function(data){
                        $("#text").css("background","none");
                        $("#text").html("").css("height", "auto");
                        $("#text").html(data);
                    }
                });
                get_ajax_news(target[1], false);
                break;  
        case 'b':
                get_brand_content(target[1], false);
                break; 
        default:
                $("ul.menu").find("a[product_id = " + 1 + "]").click();
                break;
    }
}
//Инициализация модуля перехода по ajax ссылкам
window.dhtmlHistory.create({
    toJSON: function(o) {
        return JSON.stringify(o);
    },
    fromJSON: function(s) {
        return JSON.parse(s);
    }
});
window.onload = function() {   
    var hash = window.location.hash.split('#');
    
	dhtmlHistory.initialize();

	dhtmlHistory.addListener(siteListener);

	historyStorage.reset();
	//window.location.hash = '';
    siteListener(hash[1]);
};
jQuery(document).ready(function() {
	//Глобальная переменная для XMLHttpRequest
	xmlhttprequest_id = null;

	//TinyMCE
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",   //(n.b. no trailing comma, this will be critical as you experiment later)
		plugins : "style, advimage, advlink, searchreplace, print, contextmenu, paste, fullscreen, nonbreaking, xhtmlxtras, visualchars, media, table, images",
		theme_advanced_buttons1 : "images, pastetext, pasteword, |, nonbreaking,charmap, |, image, link, unlink, anchor, media, |, cleanup, removeformat, |, fullscreen, print, code, formatselect",
		theme_advanced_buttons2 : "bold, italic, underline, strikethrough, sub, sup, |, bullist, numlist, outdent, indent, |, justifyleft, justifycenter, justifyright, justifyfull, |, styleprops, styleselect",
		theme_advanced_buttons3 : "tablecontrols",
		editor_selector : "mceEditor",
		relative_urls : false,
		remove_script_host : true
	});
    
	//jQuery Tools scrollable
	$(".scrollable").scrollable({
		next: ".prev",
		prev: ".next"
	});

	//Litebox
	$('[rel=lightbox]').lightBox({
		txtImage: "Изображение",
		txtOf: "из"
	});

	//Получаем статус
	$.post(script_path + "main/get_status",
		function(data){
			if(data)
				$("#exitIcon").show();
			else
				$("a.fileLink").css("margin-left","0px");
		},
		"html");

	//jqDock
	// set up the options to be used for jqDock...
	var dockOptions =
	{
		align: 'middle' // horizontal menu, with expansion UP/DOWN from the middle
		,
		size: 36 // set the maximum minor axis (horizontal) image dimension to 36px
		,
		labels: 'tl' // add labels (override the 'tc' default)
	};
	// ...and apply...
	$('#dock1, #dock2').jqDock(dockOptions);

	$(".jqDock").live("mouseover", function(){
		$(".next, .prev").css("z-index", "0");
	//$(".next, .prev, #searchForm").hide();
	});
	$(".jqDock").live("mouseout", function(){
		$(".next, .prev").css("z-index", "10");
	//$(".next, .prev,  #searchForm").show();
	});

	$("ul.menu li a.menuItem").bind("click", function(){
		mainMenu = $(this);
		$("ul.submenu li a, ul.menu li a").each(function(){
			$(this).css("background", "#fff");
			$(this).css("color", "#595A5C");
		});
        //Проставляем родителю верхнему и самому элементу цветовое выделение
        mainMenu.parents("li:last").find("a:visible").eq(0).css("background", "#E7E8E9").css("color", "#009444");
        mainMenu.parents("li:first").find("a:visible").eq(0).css("background", "#E7E8E9").css("color", "#009444");

        //Скрываем пункты меню, если кликнули другой корневой пункт меню
        if($(this).parent("li").parent("ul").hasClass("menu")){
            $("ul.menu").find("ul:first").slideUp();
        }

		if(mainMenu.parent().find("ul:first").css("display") == "none"){
			mainMenu.parent().find("ul:first").slideDown();
			mainMenu.parent().css("padding-bottom", "0px");
		}else{
			mainMenu.parent().find("ul:first").slideUp();
			mainMenu.parent().css("padding-bottom", "3px");
		}
		if(xmlhttprequest_id != null){
			xmlhttprequest_id.abort();
		}
		if(mainMenu.attr("content") != 'none')
		{
			$("#text").html("").css("height", "50px");
			$("#text").css("background","url(" + script_path + "system/application/views/" + "images/loader.gif) no-repeat center top");
            var content_id = mainMenu.attr("content")
            var product_parent_id = mainMenu.attr("product_parent_id");
            if(!recursive){
                get_content(content_id, product_parent_id, true);
            }
		}

		if(mainMenu.attr("url") == 'shareholders')
		{
			$("#text").html("").css("height", "50px");
			$("#text").css("background","url(" + script_path + "system/application/views/" + "images/loader.gif) no-repeat center top");
			get_shareholders_page(mainMenu.attr("owner_id"), true);
		}

		if(mainMenu.attr("url") == 'news')
		{
			$("#text").html("").css("height", "50px");
			$("#text").css("background","url(" + script_path + "system/application/views/" + "images/loader.gif) no-repeat center top");
			get_news(true);            
		}
	});

	//Закругленные уголки
	$("#flower").corner("round");

	//Появление кнопки админа
	$("#admIcon").hover(function(){
		$("#admIcon > a").css('visibility', 'visible');
	},
	function(){
		$("#admIcon > a").css('visibility', 'hidden');
	});

	//Открытие окна логина для админа
	$("#dialog").dialog("destroy");

	$("#admAuth").dialog({
		autoOpen: false,
		//height: 300,
		width: 300,
		modal: true,
		dialogClass: 'admAuth',
		buttons: {
			'Авторизация': function() {
				var dialogVar = $(this);
				$("#errorMessage").html();
				var login = $.trim($("#login").val());
				var pass =  $.trim($("#pass").val());
				$.post(script_path + "auth/logon",
				{
					'login': login,
					'pass': pass
				},
				function(data){
					if(data.length > 0){
						$("#errorMessage").html(data);
					}else{
						$("#admIcon").hide();
						$("#exitIcon").show();
						$("input#login").val("");
						$("input#pass").val("");
						dialogVar.dialog('close');
						window.location.reload();
					}
				},
				"html");
			},
			'Отмена':
			function() {
				$("input#login").val();
				$("input#pass").val();
				$(this).dialog('close');
			}
		},
		close: function() {
			$("input#login").val("");
			$("input#pass").val("");
		}
	});

	$("#admIcon > a").bind("click", function(){
		$('#admAuth').dialog('open');
	});

	//Открытие окна добавления контента
	$("#addContent").dialog({
		autoOpen: false,
		//height: 300,
		width: 890,
		modal: true,
		resizable: false,
		dialogClass: 'addContent',
		position: 'top',
		buttons: {
			'Опубликовать': function() {
				current_dialog = $(this);
				contentText = tinyMCE.get('contentText');
				contentText.setProgressState(1);
				$.post(script_path + "main/set_content",
				{
					'content_text': contentText.getContent(),
					'id': menu_item_id
				},
				function(data){
					contentText.setProgressState(0);
					$("#text").html("").html(contentText.getContent());
					current_dialog.dialog('close');
				},
				"html");
				tinyMCE.execCommand('mceRemoveControl', false, 'contentText');
				$("#addContent").empty();
			},
			'Отмена':
			function() {
				tinyMCE.execCommand('mceRemoveControl', false, 'contentText');
				$("#addContent").empty();
				$(this).dialog('close');
			}
		},
		close: function() {
			tinyMCE.execCommand('mceRemoveControl', false, 'contentText');
			$("#addContent").empty();
		}
	});

	$(".addContentButton").bind("click", function(){
		menu_item_id = $(this).attr("content");
		jQuery.ajaxSetup({
			async: false
		});
		$.post(script_path + "main/get_form",
		{
			'form_name': 'add_content'
		},
		function(data){
			$("#addContent").html(data);
		},
		"html");
		$('#ui-dialog-title-addContent').html("Добавление контента");
		$('#addContent').dialog('open');
		tinyMCE.execCommand('mceAddControl', false, 'contentText');
	});

	//Открытие окна редактирования контента
	$("#editContent").dialog({
		autoOpen: false,
		//height: 300,
		width: 890,
		modal: true,
		resizable: false,
		dialogClass: 'editContent',
		position: 'top',
		buttons: {
			'Редактировать': function() {
				current_dialog = $(this);
				contentText = tinyMCE.get('editContentText');
				contentText.setProgressState(1);
				$.post(script_path + "main/set_content",
				{
					'content_text': contentText.getContent(),
					'id': menu_item_id
				},
				function(data){
					contentText.setProgressState(0);
					$("#text").html("").html(contentText.getContent());
					current_dialog.dialog('close');
				},
				"html");
				tinyMCE.execCommand('mceRemoveControl', false, 'editContentText');
				$("#editContent").empty();
			},
			'Отмена':
			function() {
				tinyMCE.execCommand('mceRemoveControl', false, 'editContentText');
				$("#editContent").empty();
				$(this).dialog('close');
			}
		},
		close: function() {
			tinyMCE.execCommand('mceRemoveControl', false, 'editContentText');
			$("#editContent").empty();
		}
	});

	$(".editContentButton").bind("click", function(){
		menu_item_id = $(this).attr("content");
		jQuery.ajaxSetup({
			async: false
		});
		$.post(script_path + "main/get_form",
		{
			'form_name': 'edit_content'
		},
		function(data){
			$("#editContent").html(data);
		},
		"html");
		$.post(script_path + "main/get_content",
		{
			'id': menu_item_id
		},
		function(data){
			$("#editContentText").val(data);
		},
		"html");
		$('#ui-dialog-title-addContent').html("Редактирование контента");
		$('#editContent').dialog('open');
		tinyMCE.execCommand('mceAddControl', false, 'editContentText');
	});


	//Открытие окна заливки файлов
	$("#uploadFilesContainer").dialog({
		autoOpen: false,
		//height: 300,
		width: 990,
		modal: true,
		resizable: false,
		dialogClass: 'uploadFiles',
		buttons: {
			'Загрузить': function() {
				current_dialog = $(this);
				$("#filesUpload").submit();
			},
			'Отмена':
			function() {
				$("div.formError").remove();
				$(this).dialog('close');
			}
		},
		close: function() {
			$("div.formError").remove();
		}
	});

	$(".uploadFilesButton").live("click", function(){
		owner_id = $(this).attr("content");
		jQuery.ajaxSetup({
			async: false
		});
		$.post(script_path + "main/get_form",
		{
			'form_name': 'upload_files'
		},
		function(data){
			$("#uploadFilesContainer").html(data);
		},
		"html");
		$.post(script_path + "shareholders/get_info",
		{
			'table_name': 'co_shareholders_info'
		},
		function(data){
			for(i=0;i<data.length;i++)
			{
				$("<option>" + data[i].name + "</option>").appendTo("form#filesUpload select.infoTypes").attr("id", data[i].id).attr("value", data[i].id);
			}
		},
		"json");
		$("input.ownerId").val(owner_id);
		$('#ui-dialog-title-uploadFilesContainer').html("Добавление файлов");
		$('#uploadFilesContainer').dialog('open');
	});

	//Открытие окна подтверждения удаления файла
	$("#deleteFileConfirmContainer").dialog({
		autoOpen: false,
		//height: 300,
		width: 300,
		modal: true,
		resizable: false,
		dialogClass: 'deleteFile',
		buttons: {
			'Удалить':
			function() {
				current_dialog = $(this);
				$.post(script_path + "shareholders/delete_file",
				{
					'file_id': file_id,
					'file_name': file_name
				},
				function(data){
					current_dialog.dialog('close');
					$("li[file_id =" + file_id + "]").fadeOut();
				},
				"html");
			},
			'Отмена':
			function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});

	//Событие клика по кнопке удаления файла
	$(".deleteFilesButton").live("click", function(){
		file_id = $(this).attr("file_id");
		file_name = $(this).attr("file_name");
		$('#deleteFileConfirmContainer').dialog('open');
	});

	//AJAX пагинация
	$('.ajax_pag a, .backLink a').live("click", function(event){
		// получаем содержимое ссылки
		var link = $(this).attr('href');
		// отменяем действие по умолчанию
		event.preventDefault();
        // посылаем ajax-запрос по полученной ссылке
        get_ajax_news(link, true);		
	});

	$(".newsDetailLink a, a.newsSearch").live("click", function(event){
		var current_link = $(this);
		var link = $(this).attr('href');
		var backlink = $(this).attr('offset');
		event.preventDefault();
		get_news_detail(link, current_link, backlink, true);
	});

	$(".importantNewsDetailLink").live("click", function(event){
		var link = $(this).attr('href');
		var backlink = $(this).attr('offset');
		event.preventDefault();
        get_important_news_detail(link, true);
	});

	//Открытие окна добавления новости
	$("#addNews").dialog({
		autoOpen: false,
		//height: 300,
		width: 890,
		modal: true,
		resizable: false,
		dialogClass: 'addNews',
		position: 'top',
		buttons: {
			'Опубликовать': function() {
				current_dialog = $(this);
				newsHeader = $("#newsHeader").val();
				newsBriefly = tinyMCE.get('newsBriefly');
				newsText = tinyMCE.get('newsText');
				newsDate = $("#newsDate").val();

				if($("#newsImportant").is(":checked"))
				{
					newsImportant = 1;
				}
				else
				{
					newsImportant = 0;
				}

				newsBriefly.setProgressState(1);
				newsText.setProgressState(1);
				$.post(script_path + "news/add_news",
				{
					'newsHeader': newsHeader,
					'newsBriefly': newsBriefly.getContent(),
					'newsText': newsText.getContent(),
					'newsImportant': newsImportant,
					'newsDate': newsDate
				},
				function(data){
					newsBriefly.setProgressState(0);
					newsText.setProgressState(0);
					current_dialog.dialog('close');
				},
				"html");
				tinyMCE.execCommand('mceRemoveControl', false, 'newsBriefly');
				tinyMCE.execCommand('mceRemoveControl', false, 'newsText');
				$("#addNews").empty();
			},
			'Отмена':
			function() {
				tinyMCE.execCommand('mceRemoveControl', false, 'newsBriefly');
				tinyMCE.execCommand('mceRemoveControl', false, 'newsText');
				$("#addNews").empty();
				$(this).dialog('close');
			}
		},
		close: function() {
			tinyMCE.execCommand('mceRemoveControl', false, 'newsHeader');
			tinyMCE.execCommand('mceRemoveControl', false, 'newsBriefly');
			tinyMCE.execCommand('mceRemoveControl', false, 'newsText');
			$("#addNews").empty();
		}
	});

	$(".addNewsButton").bind("click", function(){
		menu_item_id = $(this).attr("content");
		jQuery.ajaxSetup({
			async: false
		});
		$.post(script_path + "main/get_form",
		{
			'form_name': 'add_news'
		},
		function(data){
			$("#addNews").html(data);
		},
		"html");
		$('#ui-dialog-title-addNews').html("Добавление новости");
		$('#addNews').dialog('open');
		tinyMCE.execCommand('mceAddControl', false, 'newsBriefly');
		tinyMCE.execCommand('mceAddControl', false, 'newsText');
	});

	//Открытие окна подтверждения удаления новости
	$("#deleteNewsConfirmContainer").dialog({
		autoOpen: false,
		//height: 300,
		width: 300,
		modal: true,
		resizable: false,
		dialogClass: 'deleteFile',
		buttons: {
			'Удалить':
			function() {
				current_dialog = $(this);
				$.post(script_path + "news/delete_news",
				{
					'news_id': news_id
				},
				function(data){
					current_dialog.dialog('close');
					$("div[news_id = " + news_id + "]").fadeOut();
				},
				"html");
			},
			'Отмена':
			function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});

	//Событие на клик по кнопке удаления новости
	$(".deleteNewsButton").live("click", function(){
		news_id = $(this).attr("news_id");
		$('#deleteNewsConfirmContainer').dialog('open');
	});

	//Открытие окна редактирования новости
	$("#editNews").dialog({
		autoOpen: false,
		//height: 300,
		width: 890,
		modal: true,
		resizable: false,
		dialogClass: 'editNews',
		position: 'top',
		buttons: {
			'Редактировать': function() {
				current_dialog = $(this);
				newsHeader = $("#editNewsHeader").val();
				newsBriefly = tinyMCE.get('editNewsBriefly');
				newsText = tinyMCE.get('editNewsText');
				newsDate = $("#editNewsDate").val();
				if($("#editNewsImportant").is(":checked"))
				{
					newsImportant = 1;
				}
				else
				{
					newsImportant = 0;
				}

				newsBriefly.setProgressState(1);
				newsText.setProgressState(1);

				$.post(script_path + "news/edit_news",
				{
					'newsId': news_id,
					'newsHeader': newsHeader,
					'newsBriefly': newsBriefly.getContent(),
					'newsText': newsText.getContent(),
					'newsImportant': newsImportant,
					'newsDate': newsDate
				},
				function(data){
					newsBriefly.setProgressState(0);
					newsText.setProgressState(0);
					$("div[news_id = " + news_id + "] div.newsTextHeader").html("").html(newsHeader);
					$("div[news_id = " + news_id + "] div.newsTextBriefly").html("").html(newsBriefly.getContent());
					current_dialog.dialog('close');
				},
				"html");
				tinyMCE.execCommand('mceRemoveControl', false, 'editNewsText');
				tinyMCE.execCommand('mceRemoveControl', false, 'editNewsBriefly');
				$("#editNews").empty();
			},
			'Отмена':
			function() {
				tinyMCE.execCommand('mceRemoveControl', false, 'editNewsText');
				tinyMCE.execCommand('mceRemoveControl', false, 'editNewsBriefly');
				$("#editNews").empty();
				$(this).dialog('close');
			}
		},
		close: function() {
			tinyMCE.execCommand('mceRemoveControl', false, 'editNewsText');
			tinyMCE.execCommand('mceRemoveControl', false, 'editNewsBriefly');
			$("#editContent").empty();
		}
	});

	//Событие на клик по кнопке редактирования новости
	$(".editNewsButton").live("click", function(){
		news_id = $(this).attr("news_id");
		jQuery.ajaxSetup({
			async: false
		});
		$.post(script_path + "main/get_form",
		{
			'form_name': 'edit_news'
		},
		function(data){
			$("#editNews").html(data);
		},
		"html");
		$.post(script_path + "news/get_current_news",
		{
			'news_id': news_id
		},
		function(data){
			$("#editNewsHeader").val(data.header);
			$("#editNewsBriefly").val(data.briefly);
			$("#editNewsText").val(data.text);
			$("#editNewsDate").val(data.date);
			if(data.important == 1)
				$("#editNewsImportant").attr("checked", "true");
		},
		"json");
		$('#ui-dialog-title-editNews').html("Редактирование новости");
		$('#editNews').dialog('open');
		tinyMCE.execCommand('mceAddControl', false, 'editNewsText');
		tinyMCE.execCommand('mceAddControl', false, 'editNewsBriefly');
	});

	//Открытие окна подтверждения удаления новости с главной
	$("#deleteNewsFromMainConfirmContainer").dialog({
		autoOpen: false,
		//height: 300,
		width: 300,
		modal: true,
		resizable: false,
		dialogClass: 'deleteImportantNews',
		buttons: {
			'Удалить':
			function() {
				current_dialog = $(this);
				$.post(script_path + "news/delete_news_from_main",
				{
					'news_id': news_id
				},
				function(data){
					current_dialog.dialog('close');
					$("div[last_news_id = " + news_id + "]").fadeOut();
				},
				"html");
			},
			'Отмена':
			function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});

	//Событие клика по кнопке удаления новости с главной
	$(".deleteNewsFromMain").live("click", function(){
		news_id = $(this).attr("news_id");
		$('#deleteNewsFromMainConfirmContainer').dialog('open');
	});

	//Логаут
	$("#exitIcon").bind("click", function(){
		$.post(script_path + "auth/logoff",
		{
			},
			function(data){
				$("#admIcon").show();
				$("#exitIcon").hide();
				$("a.fileLink").css("margin-left","0px");
				window.location.reload();
			});
	});

	//Добавление контента при клике на карусель
	$(".carouselLink").bind("click", function(){
		var brand = $(this).attr("product_id");
        get_brand_content(brand, true);
	});

	//Рекурсивное открытие пунктов меню
	$(".fullDescriptionLink, .rightDeals, #messagesLink, #actionsLink").live("click", function() {
		var current_link = $(this);
		var product_id = $(this).attr("product_id");
		var product_parent_id = $(this).attr("product_parent_id");

		$("ul.menu ul:visible").css("display", "none");

		var li = $("ul.menu").find("a[product_id = " + product_id + "]");
        if(parseInt(product_parent_id)){
            recursive = 1;
            menu_click(product_parent_id);
        }
        recursive = 0;
		li.click();

		if (current_link.hasClass("search")) {
			$("#text").append("<a href='javascript:void(0)' class = 'searchBack'>Назад к результатам поиска</a>");
		}
	});

	//При возврате к результатам поиска
	$(".searchBack").live("click", function(){
		jQuery.ajaxSetup({
			async: false
		});
		$.post(script_path + "main/get_search_query",
		{},
			function(data){
				search_query = data;
			},
			"html"
			);
		window.location = script_path + "main/search?searchInput=" + search_query;
	});

    //Кнопка задать вопрос
    $("#feedbackLink").live('click', function(){
        $.post(script_path + "main/get_view",
            {
                view_name : 'feedback'
            },
            function(data){
                $("#feedbackContainer").html(data);
                initialiaze_feedback();
            },
            "html"
        );
    });
    
    //Кнопка редактирование спецпредложений
    $(".dealsControlEdit, .dealsControlAdd").live("click", function(){
        $.ajax({
            async: false,
            type: "POST",
            url: script_path + "main/get_deal",
            data: {
                deal_id : $(this).attr("deal_id")
            },
            dataType: "html",
            success: function(data){
                $("#dealsEditContainer").html(data);
            }
        });
        $("#dealsEditContainer").dialog({
            autoOpen: true,
            //height: 300,
            width: 640,
            modal: true,
            resizable: false,
            title: "Редактирование спецпредложений",
            dialogClass: 'dealsControlEditWindow',
            buttons: {  
                'Сохранить':
                    function() {
                        $("#editDealForm").submit();
                        $(this).dialog('close');
                    },
                'Закрыть':
                    function() {
                        $(this).dialog('close');
                    }
            }
        });
    });
    
    //Кнопка удаления спецпредложений
    $(".dealsControlDelete").live('click', function(){
        if(confirm("Удалить спецпредложение?")){
            var deal = $(this);
            $.post(script_path + "main/delete_deal",
                {
                    deal_id : deal.attr("deal_id")
                },
                function(data){
                    deal.closest(".dealContainer").fadeOut("fast");
                },
                "html"
            );
        }
    });
});

/*
 * Окно с формой обратной связи
 */
function initialiaze_feedback(){
    var x = getCheckDigits();
    var y = getCheckDigits();
    $("#xDigit").html(x);
    $("#yDigit").html(y);
    $("#feedbackContainer").dialog({
        width: 420,
        modal: true,
        resizable: false,
        dialogClass: 'feedbackDialog',
        buttons: {
            'Отправить':
                function() {
                    if(is_saving){
                        alert("Подождите, идет отправка сообщения!");
                    }
                    var is_saving = true;
                    var error = '';
                    var username = $("#feedbackContainer input[name=username]");
                    var email = $("#feedbackContainer input[name=email]");
                    var message = $("#feedbackContainer textarea[name=message]");
                    var check = $("#feedbackContainer input[name=check]");
                    //Убираем подсветку об ошибках
                    $("#feedbackContainer input").removeClass("errorField");
                    if(username.val() == ""){
                        error += "Введите свое имя, пожалуйста \n ";
                        username.addClass("errorField");
                    }
                    if(email.val() == ""){
                        error += "Введите свой адрес электронной почты, пожалуйста \n";
                        email.addClass("errorField");
                    }
                    if(message.val() == ""){
                        error += "Введите сообщение, пожалуйста \n";
                        message.addClass("errorField");
                    }
                    if((x + y != parseInt(check.val()))){
                        error += "Неверно введена контрольная сумма \n";
                        check.addClass("errorField");
                    }

                    if(error){
                        alert(error);
                        is_saving = false;
                        return;
                    }
                    else{
                        $("#feedbackContainer input").removeClass("errorField");
                    }
                    $.post(script_path + "main/set_feedback",
                        {
                            username: username.val(),
                            email: email.val(),
                            message: message.val()
                        },
                        function(data){
                            is_saving = false;
                            $("#feedbackContainer").html("Сообщение успешно отправлено.");
                            $(".feedbackDialog .ui-dialog-buttonset .ui-button:first").hide();
                            $(".feedbackDialog .ui-dialog-buttonset .ui-button").eq(1).find('span').html('Закрыть');
                        },
                    "html");

                },
            'Отмена':
                function() {
                    is_saving = false;
                    $(this).dialog('close');
                }
        },
        close: function() {
            is_saving = false;
        }
    });
}

function getCheckDigits(){
    return Math.floor(Math.random() * (10- 0+ 1)) + 0;
}

function menu_click(product_id) {
	var li = $("ul.menu").find("a[product_id = " + product_id + "]");
	var product_parent_id = li.attr("product_parent_id");    
	li.click();

	if (product_parent_id != 0) {
		menu_click(product_parent_id);
	}
}

function get_content(content_id, product_parent_id, set_history){
    jQuery.ajaxSetup({
        async: false
    });
    xmlhttprequest_id = $.post(script_path + "main/get_content",
        {
            'id': content_id
        },
        function(data){
            $("#text").css("background","none");
            $("#text").html("").css("height", "auto");
            $("#text").html(data);
            $('[rel=lightbox]').lightBox({
                txtImage: "Изображение",
                txtOf: "из"
            });
            //Сохраняем клик в историю
            if(!recursive && set_history){
                addHistoryEvent($.base64.encode('c-' + content_id + '-' + product_parent_id)); 
            }            
        },
        "html"        
    );
}

function get_news_detail(link, current_link, backlink, set_history){
    $.get(link,
		{},
        function(data){
            $('#newsContainer').remove();
            $('#text').html("");
            $('#text').append(data);
            if(current_link.hasClass("newsSearch")){
                $('.backLink').html("<a href='javascript:void(0)' class = 'searchBack'>Назад к результатам поиска</a>");
            }
            else{
                $('.backLink').html("<a href='" + script_path + "news/index/" + backlink + "' offset = '" + backlink + "'>Назад</a>");
            }
            //Сохраняем клик в историю
            if(!recursive && set_history){
                addHistoryEvent($.base64.encode('nd-' + link + '-' + current_link + '-' + backlink));
            }
        },
        "html"
    );
}

function get_shareholders_page(owner_id, set_history){
    xmlhttprequest_id = $.post(script_path + "shareholders/index/" + owner_id,
        function(data){
            $("#text").css("background","none");
            $("#text").html("").css("height", "auto");
            $("#text").html(data);
            //Сохраняем клик в историю
            if(!recursive && set_history){
                addHistoryEvent($.base64.encode('s-' + owner_id));
            }
        },
        "html"
    );
}

function get_important_news_detail(link, set_history){
    $.get(link,
        {},
        function(data){
            $('#text').html(data);
            //$('.backLink').html("<a href='" + script_path + "news/index/" + backlink + "' offset = '" + backlink + "'>Назад</a>");
            //Сохраняем клик в историю
            if(!recursive && set_history){
                addHistoryEvent($.base64.encode('ind-' + link));
            }
        },
        "html"
    );
}

function get_news(set_history){    
    $.ajax({
        async: false,
        type: "post",
        url: script_path + "news/news_header/",
        success: function(data){
            $("#text").css("background","none");
            $("#text").html("").css("height", "auto");
            $("#text").html(data);
        }
    });
    
    $.post(script_path + "news/index/",
        function(data){
            $("#text").append(data);

            $('[rel=lightbox]').lightBox({
                txtImage: "Изображение",
                txtOf: "из"
            });
            //Сохраняем клик в историю
            if(!recursive && set_history){
                addHistoryEvent($.base64.encode('n-'));
            }
        },
        "html"
    );
}

function get_ajax_news(link, set_history){
    $.get(
        link,
        function(data){
            $('#newsContainer').remove();
            $('#text').append(data);
            //Сохраняем клик в историю
            if(!recursive && set_history){
                addHistoryEvent($.base64.encode('na-' + link));
            }
        },
        "html"
    );
}
            
function get_brand_content(brand, set_history){
    if(xmlhttprequest_id != null){
        xmlhttprequest_id.abort();
    }
    xmlhttprequest_id = $.post(script_path + "main/get_brand_content",
        {
            'brand': brand
        },
        function(data){
            $("#text").html("<table id='brandTable'></table>");
            for(i=0;i<data.length;i++)
            {
                $("#brandTable").append("<tr>");
                if(data[i].image != undefined)
                    $("#brandTable tr:last").append("<td class='brandImage'><img src='" + data[i].image + "' /></td>");
                else
                    $("#brandTable tr:last").append("<td class='brandImage'></td>");
                if(data[i].page_content != undefined && data[i].page_content != '')
                    $("#brandTable tr:last").append("<td><p>" + data[i].page_content + "</p><a class = 'fullDescriptionLink' product_id = '" + data[i].id + "' product_parent_id = '" + data[i].parent_id + "' href='javascript: void(0);'>Подробнее</a></td>");
                $("#brandTable").append("</tr>");                
            }
        },
        "json"
    );
    //Сохраняем клик в историю
    if(!recursive && set_history){
        addHistoryEvent($.base64.encode('b-' + brand));
    }
}

// Добавление запроса в историю браузера
function addHistoryEvent(title) {
	dhtmlHistory.add(title);
}
