function ajaxFileUpload() {
    //starting setting some animation when the ajax starts and completes
    $("#loading")
            .ajaxStart(function() {
        $(this).show();
    })
            .ajaxComplete(function() {
        $(this).hide();
    });

    /*
     prepareing ajax file upload
     url: the url of script file handling the uploaded files
     fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
     dataType: it support json, xml
     secureuri:use secure protocol
     success: call back function when the ajax complete
     error: callback function when the ajax failed

     */
    $.ajaxFileUpload({
        url:'/shop/shop_upload.php',
        secureuri:false,
        fileElementId:'shop_image_file',
        maxSizeId:'maxsize',
        adddata:{'fast_register':$('#shop_image_fast_register:checked').val(), 'user_name':$('#shop_image_user_name').val(), 'user_email':$('#shop_image_user_email').val()},
        dataType: 'json',
        success: function (data, status) {
            if (data['error']== '1') {
                $('#shop_image_text_help').text(data['text']);
            } else {
                $('#shop_image_text_help').text("Файл успешно загружен.");
                // TODO обновление картинки
                $('#load_image').attr({'src':'/userfiles/shops/thumbs/' + data['filename']});
                $('#load_image').attr({'title':''});
                $('#load_image').attr({'alt':''});
                $('#load_image').unbind('click');
                $('#load_image').css({'cursor':'default'});
                $('#load_image').fitimage({ placeholder: "/images/blank.gif" });
                $('#shop_image').dialog('close');
                if (data['action'] == 'reload') document.location.reload();
            }
        },
        error: function (data, status, e) {
            $('#shop_image_text_help').text('Ошибка: ' + e);
        }
    });
    return false;
}

$(function() {
    $('.fit').fitimage({ placeholder: "/images/blank.gif" });
    $.get('/top10_aero.html', {}, function(data) {
        if (data.text != "") $('#top10_aero').addClass('infoblock').css('display', 'block').append(data.text);
    }, "json");
    $.get('/top10_news.html', {}, function(data) {
        if (data.text != "") $('#top10_news').addClass('infoblock').css('display', 'block').append(data.text);
    }, "json");
    
    var comment_dialog_height;
    var shop_dialog_height;
    var product_dialog_height;
    var change_price_dialog_height;
    var shop_image_dialog_height;
    /*
     * показ дополнительных цен (2)
     */
    //Раньше использовался метод one, но свое изжил.
    // вроде как нельзя сделать live-one
    $('.other_price').live('click', function() {
        my_obj = $(this);
        my_id = $(this).attr('id').replace(/^.*?(\d+)$/, '$1');
        $.post('/product/get_product_other_price.php', {'product':my_id, 'action':'get','price':my_obj.parent().children("span.price").text()},
                function(data) {
                    if (data) {
                        zz = my_obj.parent().parent().after(data);
                        $(my_obj).click(function() {
                            return false;
                        });
                        //TODO сделать плавное распахивание
                    }
                });
        //TODO заменить кружок на стрелочку вниз для наглядности
        return false;
    });
    /*конец 2*/


    /*
     * Изменение цены на товар (1)
     */
    $('.insert_new_price').live('click', function() {
        my_id = $(this).attr('id').replace(/^.*?(\d+)$/, '$1');
        $.post('/product/get_product.php', {id:my_id}, function(data) { // считываем название в заголовок

            if (user != "anonymous")
                change_price_dialog_height = 240;
            else
                change_price_dialog_height = 380;
            $('#shop_product_price').dialog('option', 'title', data.name + ", " + data.volume);
            $('#shop_product_price').load('/product/new_price.php', function() {
                $(this).dialog('open');
            });
        }, 'json');

        return false;
    });

    $('a.add_product').live("click", function() {
        $('#product_add').dialog('open').load("/product/add_product_dialog.php", function () {
            //TODO Более полная шапка окна здесь и в остальны диалогах.
            if (user != "anonymous")
                comment_dialog_height = 390;
            else
                comment_dialog_height = 530;
            $("#product_name").autocomplete("/product/get_product.php");
        });

    });
    $(".only_digit").live("keyup", function() {
        /**
         * преобразует запятую в точку в числовых полях
         */
        re = /\,/gi;
        $(this).val($(this).val().replace(re, "."));
    });


    $('#product_add').dialog({ //новый продукт в магазине
        bgiframe: true,
        autoOpen: false,
        height: product_dialog_height,
        width: 500,
        modal: true,
        resizable: false,
        zIndex: 10000,
        buttons: {
            'Добавить товар': function() {
                $('#product_text_help').text("");

                if ($('#product_name').val() == "") {
                    $('#product_text_help').text("Необходимо указать название товара");
                    $('#product_name').focus();
                    return (false);
                }
                if ($('#product_volume').val() == "") {
                    $('#product_text_help').text("Необходимо задать объем тары");
                    $('#product_volume').focus();
                    return (false);
                }
                if ($('#product_price2').val() == "") {
                    $('#product_text_help').text("Необходимо указать стоимость");
                    $('#product_price2').focus();
                    return (false);
                }
                if (isNaN($('#product_price2').val())) {
                    $('#product_text_help').text("Должны быть цифры (разделитель - точка)");
                    $('#product_price2').focus();
                    return (false);
                }
                if ($('#product_currency2').val() == "") {
                    $('#product_text_help').text("Укажите валюту");
                    $('#product_currency2').focus();
                    return (false);
                }
                if ($('#product_fast_register:checked').val() == 1 && $('#product_user_name').val() == "" && user == 'anonymous') {
                    $('#product_text_help').text("Для  быстрой регистрации необходимо заполнить поле «Ваше имя»");
                    $('#product_user_name').focus();
                    return (false);
                }
                if ($('#product_fast_register:checked').val() == 1 && $('#product_user_email').val() == "" && user == 'anonymous') {
                    $('#product_text_help').text("Для быстрой регистрации необходимо заполнить поле «Ваш e-mail»");
                    $('#product_user_email').focus();
                    return (false);
                }

                if (user == 'anonymous' && $('#product_user_email').val().length > 0 && $('#product_user_email').val().search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
                    $('#product_text_help').text("Необходимо указать реальный e-mail");
                    $('#product_user_email').focus();
                    return false;
                }
                if ($('#product_fast_register:checked').val() == 1 && $('#product_user_email').val() != "" && user == 'anonymous') {
                    if ($.ajax({type:"POST", async: false, url:'/register.php',
                        data:({'email':$('#product_user_email').val(),'action':'checkuser'})}).responseText == 0) {
                        $('#product_text_help').text("На сайте уже есть пользователь с таким e-mail");
                        return false;
                    }
                }
                $('#product_text_help').text('Ваша информация отправляется...');
                $.post('/product/product_add.php', {'fast_register':$('#product_fast_register:checked').val(), 'user_name':$('#product_user_name').val(), 'user_email':$('#product_user_email').val(), 'product_name':$('#product_name').val(), 'product_volume':$('#product_volume').val(), 'price':$('#product_price2').val(),'product_currency':$('#product_currency2').val(), 'action':'save'},

                        function(data) {
                            if (data['error'] == 0) {
                                if (data.text != "") {
                                    $('#price_list_header').after(data.text);
                                    if ($('#price_list').css('display') == 'none') $('#price_list').css('display', 'block');
                                }
                                $('#product_add').dialog('close');
                                if (data['action'] == 'reload') document.location.reload();
                            }
                            else $('#product_text_help').text(data['text']);
                        }, 'json');
            }
        }
    });

    $('#shop_product_price').dialog({
        bgiframe: true,
        autoOpen: false,
        height: change_price_dialog_height,
        width: 500,
        modal: true,
        resizable: false,
        zIndex: 10000,
        buttons: {
            'Сохранить': function() {

                if ($('#price_price').val() == "") {
                    $('#price_text_help').text("Необходимо указать стоимость");
                    $('#price_price').focus();
                    return (false);
                }
                if (isNaN($('#price_price').val())) {
                    $('#price_text_help').text("Должны быть цифры (разделитель - точка)");
                    $('#price_price').focus();
                    return (false);
                }
                if ($('#price_currency').val() == "") {
                    $('#price_text_help').text("Укажите валюту");
                    $('#price_currency').focus();
                    return (false);
                }
                if ($('#price_fast_register:checked').val() == 1 && $('#price_user_name').val() == "" && user == 'anonymous') {
                    $('#price_text_help').text("Для  быстрой регистрации необходимо заполнить поле «Ваше имя»");
                    $('#price_user_name').focus();
                    return (false);
                }
                if ($('#price_fast_register:checked').val() == 1 && $('#price_user_email').val() == "" && user == 'anonymous') {
                    $('#price_text_help').text("Для быстрой регистрации необходимо заполнить поле «Ваш e-mail»");
                    $('#price_user_email').focus();
                    return (false);
                }

                if (user == 'anonymous' && $('#price_user_email').val().length > 0 && $('#price_user_email').val().search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
                    $('#price_text_help').text("Необходимо указать реальный e-mail");
                    $('#price_user_email').focus();
                    return false;
                }
                if ($('#price_fast_register:checked').val() == 1 && $('#price_user_email').val() != "" && user == 'anonymous') {
                    if ($.ajax({type:"POST", async: false, url:'/register.php',
                        data:({'email':$('#price_user_email').val(),'action':'checkuser'})}).responseText == 0) {
                        $('#price_text_help').text("На сайте уже есть пользователь с таким e-mail");
                        return false;
                    }
                }
                $('#product_text_help').text('Ваша информация отправляется...');
                $.post('/product/product_new_price_save.php', {'fast_register':$('#price_fast_register:checked').val(), 'user_name':$('#price_user_name').val(), 'user_email':$('#price_user_email').val(), 'price':$('#price_price').val(),'product_currency':$('#price_currency').val(),'product':my_id, 'action':'save'},
                        function(data) {
                            if (data['error'] == "0") {
                                //TODO тоже делать серой - что это?
                                //TODO вставка цены в таблицу
                                // TODO сохранение валюты магазина (вдруг будут несколько записей вбивать)
                                $('#price_in_table_' + my_id).text($('#price_price').val() + " " + $('#price_currency').val()).attr("title", "Последнее уточнение цены: несколько секунд назад");
                                $('#shop_product_price').dialog('close');

                                //FIXME просто перегружать шапку, без страницы. несколько мест
                                if (data['action'] == 'reload') document.location.reload();


                            }
                            else $('#price_text_help').text(data['text']);
                        }, 'json');
            }
        }
    });
    /*
     * end 1
     */

    /*
     * 	Подтверждение цены
     */
    $('.confirm_price').live('click', function() {
        myid = $(this);
        $.post('/product/confirm_price.php', {action:'confirm_price',id:$(this).attr('id')}, function(data) {
            if (data['error'] == "0") {
                myid.click(function() {
                    return false;
                }).removeClass('tools').addClass('tools_disable').attr('title', 'Вы сможете нажать эту кнопку еще раз после перезагрузки страницы, но зачем?').attr('href', '');
            }
        }, 'json');
        return false;
    });

    /*end 3*/
    //диалог информации о магазине
    $('#shop_input').dialog({
        bgiframe: true,
        autoOpen: false,
        height: shop_dialog_height,
        width: 500,
        modal: true,
        resizable: false,
        zIndex: 10000,
        buttons: {
            'Сохранить': function() {
                if ($("#shop_name").val() == "" && $("#shop_site").val() == "" && $("#shop_phone").val() == "") {
                    $('#shop_text_help').text("Заполните хотя-бы одно поле");
                    return false;
                }
                if ($('#shop_fast_register:checked').val() == 1 && $('#shop_user_name').val() == "" && user == 'anonymous') {
                    $('#shop_text_help').text("Для  быстрой регистрации необходимо заполнить поле «Ваше имя»");
                    $('#shop_user_name').focus();
                    return (false);
                }
                if ($('#shop_fast_register:checked').val() == 1 && $('#shop_user_email').val() == "" && user == 'anonymous') {
                    $('#shop_text_help').text("Для быстрой регистрации необходимо заполнить поле «Ваш e-mail»");
                    $('#shop_user_email').focus();
                    return (false);
                }

                if (user == 'anonymous' && $('#shop_user_email').val().length > 0 && $('#shop_user_email').val().search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
                    $('#shop_text_help').text("Необходимо указать реальный e-mail");
                    $('#shop_user_email').focus();
                    return false;
                }
                if ($('#shop_fast_register:checked').val() == 1 && $('#shop_user_email').val() != "" && user == 'anonymous') {
                    if ($.ajax({type:"POST", async: false, url:'/register.php',
                        data:({'email':$('#shop_user_email').val(),'action':'checkuser'})}).responseText == 0) {
                        $('#shop_text_help').text("На сайте уже есть пользователь с таким e-mail");
                        return false;
                    }
                }
                $('#shop_text_help').text('Ваша информация отправляется...');
                $.post('/shop/shop_info.php', {'fast_register':$('#shop_fast_register:checked').val(), 'user_name':$('#shop_user_name').val(), 'user_email':$('#shop_user_email').val(),'name':$('#shop_name').val(),'site':$('#shop_site').val(),'phone':$('#shop_phone').val(),'action':'save'},
                        function(data) {
                            if (data['error'] == "0") {
                                $('#shop_input').dialog('close');
                                if (data['action'] == 'reload') document.location.reload();
                            } else {
                                $('#shop_text_help').text(data['text']);
                            }
                        }, "json");
            }
        }
    });

    $('#add_comment').dialog({
        //  open:function(){setTimeout("$('#coment_text').focus();",500);},
        bgiframe: true,
        autoOpen: false,
        //height: 320,
        height: comment_dialog_height,
        width: 500,
        modal: true,
        resizable: false,
        zIndex: 10000,
        buttons: {
            'Сохранить': function() {
                var error = 100;
                $('#comment_text_help').text("");
                if ($('#comment_text').val() == "") {
                    $('#comment_text_help').text("Необходимо заполнить поле «Содержание отзыва»");
                    $('#comment_text').focus();
                    return (false);
                }
                if ($('#comment_fast_register:checked').val() == 1 && $('#comment_user_name').val() == "" && user == 'anonymous') {
                    $('#comment_text_help').text("Для быстрой регистрации необходимо заполнить поле «Ваше имя»");
                    $('#comment_user_name').focus();
                    return (false);
                }
                if ($('#comment_fast_register:checked').val() == 1 && $('#comment_user_email').val() == "" && user == 'anonymous') {
                    $('#comment_text_help').text("Для быстрой регистрации необходимо заполнить поле «Ваш e-mail»");
                    $('#comment_user_email').focus();
                    return (false);
                }

                if (user == 'anonymous' && $('#comment_user_email').val().length > 0 && $('#comment_user_email').val().search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
                    $('#comment_text_help').text("Необходимо указать реальный e-mail");
                    $('#comment_user_email').focus();
                    return false;
                }
                if ($('#comment_fast_register:checked').val() == 1 && $('#comment_user_email').val() != "" && user == 'anonymous') {
                    if ($.ajax({type:"POST", async: false, url:'/register.php',
                        data:({'email':$('#comment_user_email').val(),'action':'checkuser'})}).responseText == 0) {
                        $('#comment_text_help').text("На сайте уже есть пользователь с таким e-mail");
                        return false;
                    }
                }
                $('#comment_text_help').text('Ваш отзыв отправляется...');
                $.post('/comment/add.php', {'fast_register':$('#comment_fast_register:checked').val(), 'user_name':$('#comment_user_name').val(), 'user_email':$('#comment_user_email').val(), 'text':$('#comment_text').val(),'action':'save'},
                        function(data) {
                            if (data['error'] == 0) {
                                $('#add_comment').dialog('close');
                                $.history.load("review");
                                $('#review_count').text(parseInt($('#review_count').text()) + 1);
                                if (data['action'] == 'reload') document.location.reload();
                            } else
                                $('#comment_text_help').text(data['text']);

                        }, "json");
            }
        }
    });

    $('#shop_image').dialog({
        bgiframe: true,
        autoOpen: false,
        height: shop_image_dialog_height,
        width: 500,
        modal: true,
        resizable: false,
        zIndex: 10000,
        buttons: {
            'Сохранить': function() {
                $('#shop_image_text_help').text('');
                if ($('#shop_image_file').val() == "") {
                    $('#shop_image_text_help').text("Необходимо указать имя файла");
                    $('#shop_image_file').focus();
                    return (false);
                }

                if ($('#shop_image_file').val().search(/^.*?\.(jpeg|jpg|png)$/gi) == -1) {
                    $('#shop_image_text_help').text("Формат файла должен быть jpeg или png");
                    $('#shop_image_file').focus();
                    return (false);
                }
                if ($('#shop_image_fast_register:checked').val() == 1 && $('#shop_image_user_name').val() == "" && user == 'anonymous') {
                    $('#shop_image_text_help').text("Для быстрой регистрации необходимо заполнить поле «Ваше имя»");
                    $('#shop_image_user_name').focus();
                    return (false);
                }
                if ($('#shop_image_fast_register:checked').val() == 1 && $('#shop_image_user_email').val() == "" && user == 'anonymous') {
                    $('#shop_image_text_help').text("Для быстрой регистрации необходимо заполнить поле «Ваш e-mail»");
                    $('#shop_image_user_email').focus();
                    return (false);
                }

                if (user == 'anonymous' && $('#shop_image_user_email').val().length > 0 && $('#shop_image_user_email').val().search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
                    $('#shop_image_text_help').text("Необходимо указать реальный e-mail");
                    $('#shop_image_user_email').focus();
                    return false;
                }
                if ($('#shop_image_fast_register:checked').val() == 1 && $('#shop_image_user_email').val() != "" && user == 'anonymous') {
                    if ($.ajax({type:"POST", async: false, url:'/register.php',
                        data:({'email':$('#shop_image_user_email').val(),'action':'checkuser'})}).responseText == 0) {
                        $('#shop_image_text_help').text("На сайте уже есть пользователь с таким e-mail");
                        return false;
                    }
                }
                $('#shop_image_text_help').text("Загружаем файл...");
                ajaxFileUpload();
            }
        }
    });


    $('#shop_input_key').click(function() {
        if (user != "anonymous")
            comment_dialog_height = 340;
        else
            comment_dialog_height = 480;
        $('#shop_input').dialog('open').load("/shop/info.php");
        return false;
    });


    $('#page_comment_key').click(function() {
        if (user != "anonymous")
            comment_dialog_height = 300;
        else
            comment_dialog_height = 440;
        $('#add_comment').dialog('open').load("/comment/add_dialog.php");
        return false;
    });

    //    $('#show_comment_key').click(function() {
    //        a = $('#shop_comment');
    //        //if(a.text()==""){
    //        a.load("/comment/get.php", {}, function () {
    //            a.toggle('blind', '', 500, '');
    //        });
    //        //}
    //        //else{ a.toggle('blind','',500,'');
    //        return false;
    //    });

    $('#load_image').click(function() {
        if (user != "anonymous")
            shop_image_dialog_height = 320;
        else
            shop_image_dialog_height = 460;
        $('#shop_image').dialog('open').load('/shop/image_load.php', function() {

        });
    });
});


function pageload(hash) {
        $("#page_show_price").tipsy('hide');
        $("#page_show_news").tipsy('hide');
        $("#page_show_review").tipsy('hide');
        if (hash) {
            hash2 = hash.replace("?show_all", "");
            if (hash == hash2)
                $("#info_zone").load(hash2+"?ajax=1");
            else
                $("#info_zone").load(hash+"&ajax=1");
            $("#page_show_" + hash2).tipsy('show');
        } else {
            $("#info_zone").load("price" + show_all+"ajax=1");
            $("#page_show_price").tipsy('show');
        }
    }

    $(document).ready(function() {
        $("._update").tipsy({title:'rel',trigger: 'manual',gravity:'s'});
        $.history.init(pageload);

        $("a._update").live("click", function() {
            var hash = this.href;
            hash = hash.replace(/^.*\/(.*)$/, '$1');
            $.history.load(hash);
            return false;
        });
    });
