/*
startList = function() {
  if (document.all&&document.getElementById)
  {
    navRoot = document.getElementById("nav");
      elements = navRoot.getElementsByTagName("li");
    for (i = 0; i<elements.length; i++)
      {
      elements[i].onmouseover = function() {
        this.className += " over";
      }
      elements[i].onmouseout = function() {
        this.className = this.className.replace(" over", "");
      }
    }
  }
}
window.onload = startList;
*/

function intval (mixed_var, base) {
    // Get the integer value of a variable using the optional base for the conversion  
    // 
    // version: 910.813
    // discuss at: http://phpjs.org/functions/intval
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: stensi
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Matteo
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: intval('Kevin van Zonneveld');
    // *     returns 1: 0
    // *     example 2: intval(4.2);
    // *     returns 2: 4
    // *     example 3: intval(42, 8);
    // *     returns 3: 42
    // *     example 4: intval('09');
    // *     returns 4: 9
    // *     example 5: intval('1e', 16);
    // *     returns 5: 30
    var tmp;

    var type = typeof( mixed_var );

    if (type === 'boolean') {
        return (mixed_var) ? 1 : 0;
    } else if (type === 'string') {
        tmp = parseInt(mixed_var, base || 10);
        return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
    } else if (type === 'number' && isFinite(mixed_var) ) {
        return Math.floor(mixed_var);
    } else {
        return 0;
    }
}

Array.max = function( array ){
    return Math.max.apply( Math, array );
}; 

var current_menu = 1;

function change_menu(num)
{
  $('#order_menu_' + current_menu).removeClass("selected");
  $('#order_menu_' + num).addClass("selected");
  current_menu = num;
}

function send_registration()
{
  var total = 7;
  var pre_total = check("USER_LAST_NAME", isCyr($('#USER_LAST_NAME').val())) + 
    check("USER_NAME", isCyr($('#USER_NAME').val())) + 
    check("USER_SECOND_NAME", isCyr($('#USER_SECOND_NAME').val())) + 
    check("USER_PERSONAL_PHONE", isPhone($('#USER_PERSONAL_PHONE').val())) + 
    check("USER_EMAIL", isEmail($('#USER_EMAIL').val())) + 
    check("USER_PASSWORD_reg", isPasswordLength($('#USER_PASSWORD_reg').val(), 6)) + 
    check("USER_CONFIRM_PASSWORD_reg", isConfirmPassword($('#USER_CONFIRM_PASSWORD_reg').val(), $('#USER_PASSWORD_reg').val())); 
    
  if (total == pre_total)
  {
    var queryString = $('#reg_form').formSerialize();
     $.getJSON("/registration.php",
       queryString,
       function(json){
         if (!json.errors)
         {
          $.nyroModalManual({
            bgColor: '#f7f9ea',
            content: json.content
          });
          $('#login_word').html(json.login_word);
          $('#private_box').hide();
         }
         else
         {
           $('#captcha_sid').val(json.captcha_sid);
           $('#captcha_img').attr('src', '/bitrix/tools/captcha.php?captcha_sid=' + json.captcha_sid);
           $('#captcha_word').val('');
         }
       }
     );
  }
}

function send_registration2()
{
  var total = 7;
  var pre_total = check("USER_LAST_NAME", isCyr($('#USER_LAST_NAME').val())) + 
    check("USER_NAME", isCyr($('#USER_NAME').val())) + 
    check("USER_SECOND_NAME", isCyr($('#USER_SECOND_NAME').val())) + 
    check("USER_PERSONAL_PHONE", isPhone($('#USER_PERSONAL_PHONE').val())) + 
    check("USER_EMAIL", isEmail($('#USER_EMAIL').val())) + 
    check("USER_PASSWORD_reg", isPasswordLength($('#USER_PASSWORD_reg').val(), 6)) + 
    check("USER_CONFIRM_PASSWORD_reg", isConfirmPassword($('#USER_CONFIRM_PASSWORD_reg').val(), $('#USER_PASSWORD_reg').val())); 
    
  if (total == pre_total)
  {
    var queryString = $('#reg_form').formSerialize();
     $.getJSON("/registration.php",
       queryString,
       function(json){
         if (!json.errors)
         {
          $.nyroModalManual({
            bgColor: '#f7f9ea',
            content: json.content
          });
          $('#login_word').html(json.login_word);
          $('#private_box').hide();
          $('#personal_data').html(json.personal_data);
          ur = 1;
          $('#ORDER_PROP_17').val(json.phone);
         }
         else
         {
           $('#captcha_sid').val(json.captcha_sid);
           $('#captcha_img').attr('src', '/bitrix/tools/captcha.php?captcha_sid=' + json.captcha_sid);
           $('#captcha_word').val('');
         }
       }
     );
  }
}

function check(id, result)
{
  var obj = $('#' + id + '_sign');
  var obj_tooltip = $('#' + id + '_tooltip');
  if (result)
  {
    obj.html('OK');
    obj.css('color', '#209330');
    obj_tooltip.hide();
  }
  else
  {
    obj.html('&nbsp;&nbsp;!');
    obj.css('color', '#f7544c');
    obj_tooltip.show();
  }
  obj.show();
  return result;
}

function isCyr(value)
{
  rexp = /^[ЁёА-Яа-яA-Za-z\s]+$/;
  return rexp.test(value); 
}

function isPhone(value)
{
  rexp = /^[0-9\-()+\s]+$/;
  return rexp.test(value); 
}

function isEmail(value)
{
  //rexp = /^[=_\.0-9A-Za-z+~-]+@(([-0-9A-Za-z_]+\.)+)([A-Za-z]{2,10}$)/
  rexp = /^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+(?:[a-zA-Z]{2,4}|museum|travel)$/
  return rexp.test(value); 
}

function isPasswordLength(value, length)
{
  if (value.length >= length) return true;
  else return false;
}

function isConfirmPassword(value1, value2)
{
  if (value1 == value2 && value1.length > 0) return true;
  else return false;
}

function get_order_data(user_id, action)
{
  //if ()
  $.getJSON("/order.php", "action=" + action + "&user_id=" + user_id, function (r) { $('#' + action).html(r.content); }  );
}

function get_book_info(id)
{
  $.getJSON("/book_info.php", "ID=" + id, function (r) { alert(r.content); } );
}

function toggle_private()
{
  $('#private_box').toggle();
}

function delete_from_basket(productId) {
    $.getJSON("/ajaxbasket.php", "ACTION=delete&ID=" + productId , function (r) {
        $('#book_item_' + productId).remove();
        $('#delivery_time').html(r.delivery_time);
        $('#basket_total').html(r.basket_total);
        $('#allSum').html(r.allSum);
        $('#discount').html(r.discount);
        $('#allSum_discount').html(r.allSum_discount);

        if (r.deny_ordering == true) {
            $("input[name=BasketOrder]").hide();
        } else {
            $("input[name=BasketOrder]").show();
        }
    });
}

function delete_from_delay(productId)
{
  $.getJSON("/ajaxbasket.php", "ACTION=delete&ID=" + productId , function (r) { if (r.delay_items > 0) $('#header_delay').hide(); else $('#header_delay').show(); $('#book_' + productId).remove(); $('#delivery_time').html(r.delivery_time); $('#basket_total').html(r.basket_total); $('#allSum').html(r.allSum); $('#discount').html(r.discount); $('#allSum_discount').html(r.allSum_discount); }  );
}

function send_to_delay(productId) {
    addToBasket(productId, 'new_delay_item');
    $('#book_item_' + productId).remove();

    $.getJSON("/ajaxbasket.php", "ACTION=delay&ID=" + productId, function (r) {
        if (r.delay_items > 0)
            $('#header_delay').hide();
        else
            $('#header_delay').show();

        $('#new_delay_item')
            .html(r.new_item)
            .addClass('delay_book')
            .attr('id', 'book_' + productId)
            .after('<div id="new_delay_item" style="margin:15px 0 0 10px;"></div>');

        $('#delivery_time').html(r.delivery_time);
        $('#basket_total').html(r.basket_total);
        $('#allSum').html(r.allSum);
        $('#discount').html(r.discount);
        $('#allSum_discount').html(r.allSum_discount);

        if (r.deny_ordering == true) {
            $("input[name=BasketOrder]").hide();
        } else {
            $("input[name=BasketOrder]").show();
        }
    });
}

function undelay(productId) {
    addToBasket(productId, 'new_item');
    $('#book_' + productId).remove();

    $.getJSON("/ajaxbasket.php", "ACTION=undelay&ID=" + productId, function (r) {
        if (r.delay_items > 0)
            $('#header_delay').hide();
        else
            $('#header_delay').show();

        $('#new_item')
            .html(r.new_item)
            .addClass('book-list')
            .attr('id', 'book_item_' + productId)
            .after('<tr id="new_item"></tr>');

        $('#delivery_time').html(r.delivery_time);
        $('#basket_total').html(r.basket_total);
        $('#allSum').html(r.allSum);
        $('#discount').html(r.discount);
        $('#allSum_discount').html(r.allSum_discount);

        if (r.deny_ordering == true) {
            $("input[name=BasketOrder]").hide();
        } else {
            $("input[name=BasketOrder]").show();
        }
    });
}

function start_search()
{
  $('#search_indicator').show();
  setTimeout('change_search_string()', 300);
}

var str = 1;

function change_search_string()
{
  var points = "";
  for (var i = 0; i < str; i++) points = points + ".";
  for (var i = str; i < 7; i++) points = points + "&nbsp;";
  str++;
  if (str == 8) str = 1;
  $('#search_indicator').html("Идет поиск" + points);
  setTimeout('change_search_string()', 400);
}

var timeout1;

function renew_basket(productId, quantity) {
    var parts = productId.split("_");

    $.getJSON("/ajaxbasket.php",
              "ACTION=renew&ID=" + productId + "&quantity=" + quantity,
              function (r) {
                $('#basket_total').html(r.basket_total);
                $('#allSum').html(r.allSum);
                $('#discount').html(r.discount);
                $('#allSum_discount').html(r.allSum_discount);
                $('#renew_image_' + productId).attr('src', '/i/beige/basket_renewed.jpg');

                $('#limit' + productId).html(r.delivery_message);
                $("#QUANTITY_" + parts[2]).val(r.quantity_limit);
                $('#limit' + productId).html(r.quantity_message);
                $('#delivery' + productId).html('Этот товар будет у Вас:<br />' + r.delivery_time);
                
                timeout1 = setTimeout("change_image('#renew_image_" + productId + "', '/i/beige/basket_renew.gif')", 2000);

                setTimeout('$("#limit' + productId + '").empty();', 10000);
  });
}

function change_image(id, image)
{
  $(id).attr('src', image);
  //clearTimeout(timeout1);
}

function renew_main_basket()
{
  $.getJSON("/ajaxbasket.php", "" , function (r) { $('#basket_total').html(r.basket_total); $('#allSum').html(r.allSum); $('#discount').html(r.discount); $('#allSum_discount').html(r.allSum_discount); }  );
}

function vote(productId)
{
  $.getJSON("/vote.php", "ID=" + productId + "&vote=" + current_vote , function (r) { $("#rating_back").hide(); $("#rating_thanks").fadeIn(2000); }  );
}

var current_vote = 0;

function check_voting()
{
  if (current_vote == 0)
  {
    return false;
  }
  else
  {
    $('#vote_radio').val(current_vote);
  }
}

function change_top(type)
{
  $.getJSON(
    "/ajax.php",
    "ACTION=change_top&TYPE=" + type,
    function (r) { 
      for (var i = 1; i < 6; i++)
      {
        $("#top_" + i).html(r.books[i]);
      }
      $("#top5_links").html(r.links);
    }
  );
}

function fill_profile(profile_id)
{
  var fields = new Array(22, 23, 24, 25, 26, 27, 28, 31, 17);
  for (var i = 0; i < fields.length; i++)
  {
    $('#ORDER_PROP_' + fields[i]).val('');
  }
  var el = document.getElementById('ORDER_PROP_20');
  el.selectedIndex = 0;
  if (profile_id > 0)
  {
    for (var i in profiles[profile_id])
    {
      $('#ORDER_PROP_' + i).val(profiles[profile_id][i]);
    }
  }
}


var order_delivery_id = 0;
var delivery_fields = new Array();
delivery_fields[1] = new Array(7, 8, 9, 10, 11, 12, 123, 13);
delivery_fields[5] = new Array(4, 8, 9, 10, 11, 12, 123, 13, 16, 17, 18);
delivery_fields[2] = new Array(12, 123, 13);
delivery_fields[3] = new Array(2, 14, 5, 8, 9, 10, 11, 12, 123, 13);
delivery_fields[4] = new Array(1, 3, 15, 6, 8, 9, 10, 11, 12, 123, 13);

var pay_systems = new Array();
pay_systems[1] = new Array(1, 3, 4, 5, 6);
pay_systems[2] = new Array(1, 2, 4, 5, 6);

function show_delivery_fields(delivery_id)
{
  order_delivery_id = delivery_id;
  $('#all_fields').show();
  $('#not_selected').hide();
  
  if (delivery_id == 2) {
    $('#self_text').show();
    if (total >= 1000)
    {
      $('#try_courier').show();
    }
    else
    {
      $('#try_courier').hide();
    }
  } else {
    $('#self_text').hide();
    $('#try_courier').hide();
  }

  if (delivery_id == 3) {
    $('#delivery_methods').fadeIn();
    $("#russianpost").attr("checked", "checked");
  } else {
    $('#delivery_methods').hide();
    $("#russianpost").removeAttr("checked");
  }

  if (delivery_id == 4) {
    $('#delivery_foreign_methods').fadeIn();
    $("#russianpost2").attr("checked", "checked");
  } else {
    $('#delivery_foreign_methods').hide();
    $("#russianpost2").removeAttr("checked");
  }
  
  for (var i = 1; i < 19; i++)
  {
    $('#delivery_' + i).hide();
  }
  
  for (var i in delivery_fields[delivery_id])
  {
    $('#delivery_' + delivery_fields[delivery_id][i]).show();
  }
  
  if (delivery_id == 1)
  {
    if (total >= 1000) delivery_price = 0; 
    else if (total >= 700) delivery_price = 90;
    else delivery_price = 140;
    extra_total = extra_total + delivery_price;
    $('#delivery_price_text').html(delivery_price + ' руб');
    $('#extra_total').html(extra_total);
    $('#happy_hours').fadeIn();
  }
  else
  {
    $('#extra_total').html(extra_total);
    $('#happy_hours').hide();
  }

  if (delivery_id == 2) $('#delivery_price_text').html('0 руб');
  
  if (
    delivery_id == 5 ||
    delivery_id == 3 ||
    delivery_id == 4
  ) $('#delivery_price_text').html('Цену на доставку вам сообщит оператор');
  
  if ((delivery_id == 3 || delivery_id == 4) && total > 3000)
  {
    $('#PAY_SYSTEM_ID_1').attr('disabled', true);
    $('#prepay').show();
  }
  else
  {
    $('#PAY_SYSTEM_ID_1').attr('disabled', false);
    $('#prepay').hide();
  }
}

function get_selected_pay_system()
{
  for (var i = 1; i < 10; i++)
  {
    if($('#PAY_SYSTEM_ID_' + i + ':checked').length > 0) return i;
  }
}

function get_selected_delivery_type()
{
  return intval($("input[name$='delivery_type']:checked").val());
}

function get_selected_delivery_method()
{
  return intval($("input[name$='delivery_method']:checked").val());
}

function show_pay_systems(delivery_id)
{
  if (
    delivery_id == 1 ||
    delivery_id == 3
  )
  {
    //$('#_pay_1').show();
    $('#desc_PAY_SYSTEM_ID_1').html('Наличный расчет');
  }
  else
  {
    //$('#_pay_1').hide();
    $('#desc_PAY_SYSTEM_ID_1').html('Наложенный платеж');
    //$('#PAY_SYSTEM_ID_1').attr('checked', false);
  }
    
  delivery_type = get_selected_delivery_type();
  delivery_method = get_selected_delivery_method();
  
  if (delivery_type == 4 || delivery_method == 6)
  {
    $('#PAY_SYSTEM_ID_1').attr('disabled', true);
    $('#PAY_SYSTEM_ID_1').attr('checked', false);
  }
  else
  {
    $('#PAY_SYSTEM_ID_1').attr('disabled', false);
  }
}

var max_discount = 0;

function recalculateSum()
{
  var pay_system = get_selected_pay_system();
  var delivery_type = get_selected_delivery_type();

  if (pay_system == 3 || pay_system == 4 || pay_system == 5 || pay_system == 6)
  {
    //discounts[1] = 5;  
  }
  else
  {
    discounts[1] = 0;
  }
  
  max_discount = Array.max(discounts);
  
  if (max_discount > 0)
  {
    var discount_value = intval(Math.ceil(total * max_discount / 100));
    extra_total = total - discount_value;
    $('#discount_percent').html(max_discount);
    $('#discount_value').html(discount_value);
    $('#extra_total').html(extra_total);
    $('#discount_row').show();
  }
  else
  {
    extra_total = total;
    $('#extra_total').html(extra_total);
    $('#discount_row').hide();
  }
}

function buy(id, sale)
{
  if (sale != true) sale = 0; else sale = 1;
  $.getJSON("/buy.php", "action=BUY&ID=" + id + "&sale=" + sale, function (r) { $('#in_basket_' + id).attr('src', '/i/in_basket.jpg').parent("a").attr('onclick', 'return false;').after("<br /><a href='/personal/cart/' style='font-size:12px;text-decoration:underline;'>Перейти в корзину</a>"); $('#basket_total').html(r.basket_total); $('#basket_total2').html(r.basket_total); }  );
}

//created by u4n
function preorderItem(id) {
    $.getJSON("/buy_pre.php", "action=preorder&id=" + id , function (r) {
        $("#addToBasket")
            .html("Просмотреть корзину &raquo;")
            .attr("href", "/personal/cart/")
            .removeAttr("onclick");

        var element = $("#addToBasket").parent().parent().get(0).tagName;
        $(element + " img:first").attr("src", "/img/soft/icon_show_basket.png")
            .attr("alt", "Просмотреть корзину")
            .attr("title", "Просмотреть корзину");

        $('#basket_total').html(r.basket_total);
        $('#basket_total2').html(r.basket_total);
    });
}

//created by u4n
function buyItem(id) {
    $.getJSON("/buy.php", "action=BUY&ID=" + id , function (r) {
        $("#addToBasket")
            .html("Просмотреть корзину &raquo;")
            .attr("href", "/personal/cart/")
            .removeAttr("onclick");

        var element = $("#addToBasket").parent().parent().get(0).tagName;
        $(element + " img:first").attr("src", "/img/soft/icon_show_basket.png")
            .attr("alt", "Просмотреть корзину")
            .attr("title", "Просмотреть корзину");

        $('#basket_total').html(r.basket_total);
        $('#basket_total2').html(r.basket_total);
    });
}

//created by u4n
function buyRecommendation(currentId, id) {
    $.getJSON("/buy.php", "action=BUY&ID=" + id , function (r) {
        $("#" + currentId)
            .html("Просмотреть корзину &raquo;")
            .attr("href", "/personal/cart/")
            .removeAttr("onclick");

        $('#basket_total').html(r.basket_total);
        $('#basket_total2').html(r.basket_total);
    });
}

//created by u4n
function addToWaitingList(userId, productId) {
    $(".addToWaitingList" + productId).html("Обработка запроса...");

    $.getJSON("/personal/waiting_list/index.php", "action=add_to_waiting_list&user_id=" + userId + "&id=" + productId, function(response) {

        if (response.reply == "OK") {
            $(".addToWaitingList" + productId)
                .html("Просмотреть лист ожидания &raquo;")
                .attr("href", "/personal/waiting_list/")
                .removeAttr("onclick");
        } else {
            $(".addToWaitingList" + productId).html("Сообщить о поступлении &raquo;");
        }
    });
}

// created by u4n
function addToUnregisteredWaitingList(userEmail, productId, offsetX, offsetY) {
    $("#waitingListWarning" + productId).html("Обработка запроса...");

    $.getJSON("/personal/waiting_list/index.php", "action=add_to_unregistered_waiting_list&user_email=" + userEmail + "&id=" + productId, function(response) {

        if (response.reply == "OK") {
            $("#waitingListWarning" + productId)
                .html("Товар добавлен")
                .css({"color": "#422207", "cursor": "default"});

            $("#wlForm").slideUp();
        } else {
            $("#waitingListWarning" + productId).html("Указан неверный E-mail. Укажите другой и повторите попытку.").css("color", "#c40000");

            $("#waitingListWarning" + productId)
                .aqTip('<p class="waitingDescription">' +
                       '<a href="#" onclick="switchAuthorize();" style="color: #431b01; text-decoration: underline;">Авторизуйтесь</a> или укажите E-mail адрес, на который хотите получать уведомление о поступлении:</p>' +
                       '<form id="unregisteredForm' + productId + '" method="post">' +
                       '<p><input type="text" id="unregisteredEmail' + productId + '" name="unregistered_email" value="" style="border: 1px solid #c39772; width: 250px;" /></p>' +
                       '<p style="padding: 5px 0; text-align: right;"><input type="submit" name="save" id="saveButton" value="Сохранить" /></p>' +
                       '</form>',
                       { marginX: offsetX, marginY: offsetY,
                       css: {
                           "background": "#fcf4d8",
                           "border": "1px solid #c39772",
                           "color": "#422207",
                           "cursor": "text",
                           "height": "100px",
                           "padding": "10px",
                           "text-align": "left",
                           "width": "250px",
                           "z-index": "10000"
                       }
                });

            $("#unregisteredForm" + productId).submit(function() {
                var email = $("#unregisteredEmail" + productId).val();

                addToUnregisteredWaitingList(email, productId, offsetX, offsetY);

                return false;
            });
        }
    });
}

//created by u4n
function switchAuthorize() {
    if ($("#private_box:hidden").attr("id") != undefined) {
        toggle_private();
    }
}

//created by u4n
function removeFromWaitingList(userId, productId) {
    $.getJSON("/personal/waiting_list/index.php", "action=remove_from_waiting_list&user_id=" + userId + "&id=" + productId, function(response) {

        if (response.reply == "OK") {
            $("#" + productId).slideUp("slow");
        }
    });
}

//created by u4n
function showWaitingListWarning(id) {
    if (id == null) {
        id = '';
    }

    $("#waitingListWarning" + id).empty().hide();

    $("#waitingListWarning" + id)
        .append('Эта функция доступна только для зарегистрированных пользователей. ' +
             '<a class="nyroModal" href="#reg">Зарегистрироваться.</a>')
        .addClass("waitingListAlert")
        .fadeIn('slow');

    $('.nyroModal').nyroModal();

    window.setTimeout('$("#waitingListWarning' + id + '").fadeOut();', 10000);
}

//created by u4n
function addInterviewComment() {
    $("#error").empty();

    var interviewId = $("input[name=interview_id]").val();
    var userName = $("input[name=user_name]").val();
    var comment = $("textarea[name=comment_text]").val();

    $.getJSON("/interviews/interview.php?action=add_comment",
              "interview_id=" + interviewId + "&user_name=" + encodeURIComponent(userName) + "&comment_text=" + encodeURIComponent(comment),
              function(response) {
                if (response.reply == "OK") {
                    location.reload();
                } else {
                    $("#error").text(response.error);
                }
    });
}

function check_address_fields()
{
  var error = 0;

  if (order_delivery_id == 1)
  {
    if ($('#subway').val() == "Нет метро") { error++; $('#delivery_7_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_7_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#street').val() == "") { error++; $('#delivery_8_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_8_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#house').val() == "") { error++; $('#delivery_9_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_9_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#user_phone').val() == "") { error++; $('#delivery_12_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_12_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");

    if ($('#email').val() == "" || isEmail($('#email').val()) != true) {
        error++;

        $('#delivery_13_error').html("<strong style='color:red;font-size:1em;'>Неверный E-mail</strong>");
    } else
        $('#delivery_13_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  }

  if (order_delivery_id == 5)
  {
    if ($('#m_city').val() == "0" && $('#m_region').val() == 0 && $('#m_city_text').val() == "") { error++; $('#delivery_4_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_4_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#street').val() == "") { error++; $('#delivery_8_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_8_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#house').val() == "") { error++; $('#delivery_9_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_9_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#user_phone').val() == "") { error++; $('#delivery_12_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_12_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");

    if ($('#email').val() == "" || isEmail($('#email').val()) != true) {
        error++;

        $('#delivery_13_error').html("<strong style='color:red;font-size:1em;'>Неверный E-mail</strong>");
    } else
        $('#delivery_13_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  }

  if (order_delivery_id == 2)
  {
    if ($('#user_phone').val() == "") { error++; $('#delivery_12_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_12_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");

    if ($('#email').val() == "" || isEmail($('#email').val()) != true) {
        error++;

        $('#delivery_13_error').html("<strong style='color:red;font-size:1em;'>Неверный E-mail</strong>");
    } else
        $('#delivery_13_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  }

  if (order_delivery_id == 3)
  {
    if ($('#region').val() == "") { error++; $('#delivery_2_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_2_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#r_city').val() == "Выберите город" && $('#r_city_text').val() == "")  { error++; $('#delivery_14_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_14_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#zip').val() == "")  { error++; $('#delivery_5_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_5_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#street').val() == "") { error++; $('#delivery_8_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_8_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#house').val() == "") { error++; $('#delivery_9_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_9_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#user_phone').val() == "") { error++; $('#delivery_12_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_12_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");

    if ($('#email').val() == "" || isEmail($('#email').val()) != true) {
        error++;

        $('#delivery_13_error').html("<strong style='color:red;font-size:1em;'>Неверный E-mail</strong>");
    } else
        $('#delivery_13_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  }

  if (order_delivery_id == 4)
  {
    if ($('#country').val() == "Выберите страну") { error++; $('#delivery_1_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_1_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#state').val() == "")  { error++; $('#delivery_3_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_3_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#city_text').val() == "")  { error++; $('#delivery_15_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_15_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#f_zip').val() == "")  { error++; $('#delivery_6_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_6_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#street').val() == "") { error++; $('#delivery_8_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_8_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#house').val() == "") { error++; $('#delivery_9_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_9_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    if ($('#user_phone').val() == "") { error++; $('#delivery_12_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#delivery_12_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");

    if ($('#email').val() == "" || isEmail($('#email').val()) != true) {
        error++;

        $('#delivery_13_error').html("<strong style='color:red;font-size:1em;'>Неверный E-mail</strong>");
    } else
        $('#delivery_13_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  }

  if (error == 0)
     return true;
  else
     return false;  
}

function check_order_fields()
{
  if (!document.getElementById('agree').checked)
  {
    $('#agree_error').show();
    return false;
  }
  else
  {
    $('#submit_btn').attr('disabled', true);
    $('#agree_error').hide();
    return true;
  }
}

function check_order_guest_fields()
{
  if (!document.getElementById('agree').checked)
  {
    $('#agree_error').show();
    return false;
  }
  else
  {
    $('#submit_btn').attr('disabled', true);
    $('#agree_error').hide();
    return true;
  }
}

function change_accord(index)
{
  $('#order').accordion('activate', index - 1);
  change_menu(index);
}

function change_accord2(index)
{
  if (document.getElementById('jury_check') && document.getElementById('jury_check').checked)
    person_type = 2;
  else
    person_type = 1;
    
  if (index == 4)
  {
    for (var i = 1; i < 7; i++)
    {
      $('#PAY_SYSTEM_ID_' + i).hide();
      $('#desc_PAY_SYSTEM_ID_' + i).hide();
    }
    for (var i in pay_systems[person_type])
    {
      $('#PAY_SYSTEM_ID_' + pay_systems[person_type][i]).show();
      $('#desc_PAY_SYSTEM_ID_' + pay_systems[person_type][i]).show();
    }    
  }
  
  var selected_pay_system = get_selected_pay_system();
  
  if (index > 1)
  {
    if (document.getElementById('jury_check') && document.getElementById('jury_check').checked)
    {
      if (check_juri_fields())
      {
        if (index > 2)
        {
          if (order_delivery_id > 0)
          {
            if (index > 3)
            {
              if (check_address_fields())
              {
                if (index > 4)
                {
                  if (selected_pay_system > 0)
                  {
                    change_accord(index);
                  }
                }
                else
                {
                  change_accord(index);
                }
              }
            }
            else
            {
              change_accord(index);
            }
          }
          else
          {
            $('#not_selected').show();
          }
        }
        else
        {
          change_accord(index);
        }
      }
    }
    else
    {
      if (index > 2)
      {
        if (order_delivery_id > 0)
        {
          if (index > 3)
          {
            if (check_address_fields()) 
            {
              if (index > 4)
              {
                if (selected_pay_system > 0)
                {
                  change_accord(index);
                }
              }
              else
              {
                change_accord(index);
              }
            }
          }
          else
          {
            change_accord(index);
          }
        }
        else
        {
          $('#not_selected').show();
        }
      }
      else
      {
        change_accord(index);
      }
    }
  
  }
  else
  {
    change_accord(index);
  }
}

function change_accord3(index)
{
  if (document.getElementById('jury_check') && document.getElementById('jury_check').checked)
    person_type = 2;
  else
    person_type = 1;
    
  if (index == 4)
  {
    for (var i = 1; i < 7; i++)
    {
      $('#PAY_SYSTEM_ID_' + i).hide();
      $('#desc_PAY_SYSTEM_ID_' + i).hide();
    }
    for (var i in pay_systems[person_type])
    {
      $('#PAY_SYSTEM_ID_' + pay_systems[person_type][i]).show();
      $('#desc_PAY_SYSTEM_ID_' + pay_systems[person_type][i]).show();
    }    
  }

  if ($('#USER_LAST_NAME').val() == "") $('#user_last_name_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); else $('#user_last_name_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#USER_NAME').val() == "") $('#user_name_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); else $('#user_name_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if (index > 1)
  {
    if ($('#USER_LAST_NAME').val() != "" && $('#USER_NAME').val() != "")
    {
      if (document.getElementById('jury_check') && document.getElementById('jury_check').checked)
      {
        if (check_juri_fields())
        {
          if (index > 2)
          {
            if (order_delivery_id > 0)
            {
              if (index > 3)
              {
                if (check_address_fields()) change_accord(index);
              }
              else
              {
                change_accord(index);
              }
            }
            else
            {
              $('#not_selected').show();
            }
          }
          else
          {
            change_accord(index);
          }
        }
      }
      else
      {
        if (index > 2)
        {
          if (order_delivery_id > 0)
          {
            if (index > 3)
            {
              if (check_address_fields()) change_accord(index);
            }
            else
            {
              change_accord(index);
            }
          }
          else
          {
            $('#not_selected').show();
          }
        }
        else
        {
          change_accord(index);
        }
      }
    }
    else
    {
      //if ($('#USER_LAST_NAME').val() == "") $('#user_last_name_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); else $('#user_last_name_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
      //if ($('#USER_NAME').val() == "") $('#user_name_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); else $('#user_name_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
    }
  }
  else
  {
    change_accord(index);
  }
}

function check_order_reg()
{
  var error = 0;

  if ($('#USER_LAST_NAME').val() == "") { error++; $('#user_last_name_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#user_last_name_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#USER_NAME').val() == "") { error++; $('#user_name_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#user_name_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#USER_PERSONAL_PHONE').val() == "") { error++; $('#user_personal_phone_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#user_personal_phone_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");

    if ($('#USER_EMAIL').val() == "" || isEmail($('#USER_EMAIL').val()) != true) {
        error++;

        $('#user_email_error').html("<strong style='color:red;font-size:1em;'>Неверный E-mail</strong>");
    } else
        $('#user_email_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");

  if ($('#USER_PASSWORD_reg').val() == "") { error++; $('#user_password_reg_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#user_password_reg_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#USER_CONFIRM_PASSWORD_reg').val() == "")
  {
    error++;
    $('#user_confirm_password_reg_error').html("<strong style='color:red;font-size:1em;'>!</strong>");
  }
  else
  {
    if ($('#USER_CONFIRM_PASSWORD_reg').val() != $('#USER_PASSWORD_reg').val())
    {
      error++;
      $('#user_confirm_password_reg_error').html("<strong style='color:red;font-size:1em;'>!</strong>");
    }
    else $('#user_confirm_password_reg_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  }
  if ($('#captcha_word').val() == "") { error++; $('#captcha_word_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#captcha_word_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if (!document.getElementById('agree').checked)
  {
    $('#agree_error').show();
    error++;
  }
  else
  {
    $('#agree_error').hide();
  }
  if (error == 0) return true; else return false;
}

function check_juri_fields()
{
  var error = 0;

  if ($('#ORDER_PROP_10').val() == "") { error++; $('#juri_1_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#juri_1_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#ORDER_PROP_8').val() == "") { error++; $('#juri_2_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#juri_2_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#ORDER_PROP_11').val() == "") { error++; $('#juri_3_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#juri_3_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#ORDER_PROP_15').val() == "") { error++; $('#juri_5_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#juri_5_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#ORDER_PROP_16').val() == "") { error++; $('#juri_6_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#juri_6_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#ORDER_PROP_39').val() == "") { error++; $('#juri_7_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#juri_7_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#ORDER_PROP_40').val() == "") { error++; $('#juri_8_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#juri_8_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#ORDER_PROP_41').val() == "") { error++; $('#juri_9_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#juri_9_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");
  if ($('#ORDER_PROP_42').val() == "") { error++; $('#juri_10_error').html("<strong style='color:red;font-size:1em;'>!</strong>"); } else $('#juri_10_error').html("<strong style='color:green;font-size:1em;'>OK</strong>");

  if (error == 0) return true; else return false;
}


function show_profiles(type)
{
  var firstProfile = 0;

  str = "";
  for (var i in user_profiles[type])
  {
    profile_id = user_profiles[type][i];

    if (firstProfile == 0) {
        firstProfile = profile_id;
    }

    str += "<input style='border: 0; width: auto;' onclick='fill_in_profile(" + profile_id + ");' type='radio' name='USER_PROFILE' value='" + profile_id + "'";

    if (firstProfile == profile_id && firstProfile != 0) {
        str += " checked='checked'";
    }

    str += " />";

    for (var j in profiles[profile_id])
    {
      if (j != 37) str += profiles[profile_id][j] + ", ";
      
    }
    str = str.substr(0, str.length - 2);
    str += "<br />";
  }

  str += "<input style='border: 0; width: auto;' onclick='fill_in_profile(0);' type='radio' name='USER_PROFILE' value='0'";

  if (firstProfile == 0) {
    str += " checked='checked'";
  }

  str += " /> Новый адрес";

  $('#u_profiles').empty().html(str);

  fill_in_profile(firstProfile);
}

function fill_in_profile(profile_id)
{
  var d_fields = new Array();
  d_fields[20] = 'subway';
  d_fields[26] = 'street';
  d_fields[27] = 'house';
  d_fields[28] = 'building';
  d_fields[31] = 'flat';
  d_fields[17] = 'user_phone';
  
  if (order_delivery_id == 5) d_fields[24] = 'm_city_text';
  if (order_delivery_id == 3) d_fields[24] = 'r_city_text';
  if (order_delivery_id == 4) d_fields[24] = 'city_text';

  d_fields[22] = 'country';

  if (order_delivery_id == 3) d_fields[23] = 'region';
  if (order_delivery_id == 4) d_fields[23] = 'state';
  
  if (order_delivery_id == 3) d_fields[25] = 'zip';
  if (order_delivery_id == 4) d_fields[25] = 'f_zip';
  
  if (profile_id == 0)
  {
    for (var i in d_fields)
    {
      $('#' + d_fields[i]).val('');
    }    
  }
  else
  {
    for (var i in d_fields)
    {
      $('#' + d_fields[i]).val('');
      $('#' + d_fields[i]).val(profiles[profile_id][i]);
    }
  }

    $("#choosen_profile").val(profile_id);
}

function toggle_events(num)
{
  if (num == 12)
  {
    $('#fragment12').show();
    $('#fragment14').hide();
    $('#fragment15').hide();
  }
  if (num == 14)
  {
    $('#fragment12').hide();
    $('#fragment14').show();
    $('#fragment15').hide();
  }
  if (num == 15)
  {
    $('#fragment12').hide();
    $('#fragment14').hide();
    $('#fragment15').show();
  }
}

function toggle_soft(num)
{
  if (num == 1)
  {
    $('#fragment1').show();
    $('#fragment2').hide();
    $('#fragment3').hide();
  }
  if (num == 2)
  {
    $('#fragment1').hide();
    $('#fragment2').show();
    $('#fragment3').hide();
  }
  if (num == 3)
  {
    $('#fragment1').hide();
    $('#fragment2').hide();
    $('#fragment3').show();
  }
}

function get_russianpost(zip, rp, total, weight, rd, pay_system)
{
  if (rp.get(0).checked && rd.get(0).checked)
  {
    if (pay_system.get(0).checked) pay = 1; else pay = 0;
    $('#delivery_price_text').hide();
    $('#loading').show();
    $.getJSON("/russianpost.php", "zip=" + zip + "&total=" + total + "&total_weight=" + weight + "&PAY_SYSTEM_ID=" + pay, function (r) {
      extra_total = extra_total + r.price;
      $('#delivery_price_text').html(r.price + ' пїЅпїЅпїЅ').show();
      $('#extra_total').html(extra_total);
      $('#loading').hide();
    }  );    
  }
  
}

function get_delivery_price(form, total, weight)
{
  form.find("input[name=PAY_SYSTEM_ID]").each(
    function() {
      if ($(this).get(0).checked) pay_system = $(this).val();
    }
  );

  form.find("input[name=delivery_type]").each(
    function() {
      if ($(this).get(0).checked) delivery_type = $(this).val();
    }
  );

  form.find("input[name=delivery_method]").each(
    function() {
      if ($(this).get(0).checked) delivery_method = $(this).val();
    }
  );
  
  if (delivery_type == 1)
  {
    if (total >= 1000) delivery_price = 0; 
    else if (total >= 700) delivery_price = 90;
    else delivery_price = 140;
    extra_total = extra_total + delivery_price;
    $('#delivery_price_text').html(delivery_price + ' руб').show();
    $('#extra_total').html(extra_total);
  }

  if (delivery_type == 3 && delivery_method == 2)
  {
    if (pay_system == 1) pay = 1; else pay = 0;
    zip = form.find("#zip").val();
    $('#delivery_price_text').hide();
    $('#loading').show();
    $.getJSON("/russianpost.php", "foreign=0&avia=0&zip=" + zip + "&total=" + total + "&total_weight=" + weight + "&PAY_SYSTEM_ID=" + pay, function (r) {
        extra_total = extra_total + r.price;
        $('#delivery_price_text').html(r.price + ' руб').show();
        $('#extra_total').html(extra_total);
        $('#loading').hide();
      }
    );    
  }

  if (delivery_type == 4 && delivery_method == 2)
  {
    $('#delivery_price_text').hide();
    $('#loading').show();
    $.getJSON("/russianpost.php", "foreign=1&avia=0&total_weight=" + weight, function (r) {
        extra_total = extra_total + r.price;
        $('#delivery_price_text').html(r.price + ' руб').show();
        $('#extra_total').html(extra_total);
        $('#loading').hide();
      }
    );    
  }

  if (delivery_type == 3 && delivery_method == 6)
  {
    zip = form.find("#zip").val();
    $('#delivery_price_text').hide();
    $('#loading').show();
    $.getJSON("/ems.php", "foreign=0&zip=" + zip + "&total_weight=" + weight, function (r) {
        extra_total = extra_total + r.price;
        $('#delivery_price_text').html(r.price + ' руб').show();
        $('#extra_total').html(extra_total);
        $('#loading').hide();
      }
    );    
  }

  if (delivery_type == 4 && delivery_method == 6)
  {
    country = form.find("#country").val();
    $('#delivery_price_text').hide();
    $('#loading').show();
    $.getJSON("/ems.php", "foreign=1&country=" + country + "&total_weight=" + weight, function (r) {
        extra_total = extra_total + r.price;
        $('#delivery_price_text').html(r.price + ' руб').show();
        $('#extra_total').html(extra_total);
        $('#loading').hide();
      }
    );    
  }

  if (delivery_type == 4 && delivery_method == 9)
  {
    $('#delivery_price_text').hide();
    $('#loading').show();
    $.getJSON("/russianpost.php", "foreign=1&avia=1&total_weight=" + weight, function (r) {
        extra_total = extra_total + r.price;
        $('#delivery_price_text').html(r.price + ' руб').show();
        $('#extra_total').html(extra_total);
        $('#loading').hide();
      }
    );    
  }
  
  if (delivery_type == 5)
  {
    $('#delivery_price_text').hide();
    $('#loading').show();
    
    if (total >= 3000)
    {
      $('#delivery_price_text').html('0 руб').show();
      $('#extra_total').html(extra_total);
      $('#loading').hide();
    }
    else
    {
      $.getJSON("/moscowregion.php", "m_city=" + $('#m_city').val() + "&m_region=" + $('#m_region').val(), function (r) {
          extra_total = extra_total + r.price;
          $('#delivery_price_text').html(r.price + ' руб').show();
          $('#extra_total').html(extra_total);
          $('#loading').hide();
        }
      );    
    }
  }
}

function activate(id)
{
  $('#' + id).attr('src', '/i/new_menu/test/' + id + '_active.jpg');
  $('#' + id).parent().prev().attr('src', '/i/new_menu/mega_other_active.png');
  $('#' + id).parent().next().attr('src', '/i/new_menu/left_active.png');
}

function deactivate(id)
{
  $('#' + id).attr('src', '/i/new_menu/test/' + id + '_inactive.jpg');
  $('#' + id).parent().prev().attr('src', '/i/new_menu/other_active.png');
  $('#' + id).parent().next().attr('src', '/i/new_menu/other_active.png');
}

function defineMenu() {
    if ($(".elementSelected").attr("id") == "menuTabBooks") {
        $(".elementSelected").append('<a href="/books/"><img src="/img/menu/books_hover.png" width="100" height="37" alt="" title="" /></a>');
    } else if ($(".elementSelected").attr("id") == "menuTabStudy") {
        $(".elementSelected").append('<a href="/studybooks/"><img src="/img/menu/studybooks_hover.png" width="131" height="37" alt="" title="" /></a>');
    } else if ($(".elementSelected").attr("id") == "menuTabChild") {
        $(".elementSelected").append('<a href="/children/"><img src="/img/menu/children_hover.png" width="108" height="37" alt="" title="" /></a>');
    } else if ($(".elementSelected").attr("id") == "menuTabSoft") {
        $(".elementSelected").append('<a href="/soft/"><img src="/img/menu/soft_hover.png" width="105" height="37" alt="" title="" /></a>');
    } else if ($(".elementSelected").attr("id") == "menuTabGames") {
        $(".elementSelected").append('<a href="/games/"><img src="/img/menu/games_hover.png" width="108" height="37" alt="" title="" /></a>');
    } else if ($(".elementSelected").attr("id") == "menuTabVideo") {
        $(".elementSelected").append('<a href="/dvd/"><img src="/img/menu/video_hover.png" width="108" height="37" alt="" title="" /></a>');
    } else if ($(".elementSelected").attr("id") == "menuTabMusic") {
        $(".elementSelected").append('<a href="/music/"><img src="/img/menu/music_hover.png" width="123" height="37" alt="" title="" /></a>');
    }

    $(".elementSelected").pngFix();

    $("#menuTabBooks:not(.elementSelected)").hover(function() {
        $(this)
        .append('<a href="/books/">' +
                '<img src="/img/menu/books_hover.png" width="100" height="37" alt="" title="" />' +
        '</a>')
        .css({ "cursor": "pointer", "z-index": "1000" })
        .pngFix();
        
        absolutizeMenu();
    },
    function() {
        $(this).empty();
    }).css({"position": "absolute"});

    $("#menuTabStudy:not(.elementSelected)").hover(function() {
        $(this)
        .append('<a href="/studybooks/">' +
                '<img src="/img/menu/studybooks_hover.png" width="131" height="37" alt="" title="" />' +
        '</a>')
        .css({ "cursor": "pointer", "z-index": "1000" })
        .pngFix();
        
        absolutizeMenu();
    },
    function() {
        $(this).empty();
    }).css({"position": "absolute"});

    $("#menuTabChild:not(.elementSelected)").hover(function() {
        $(this)
        .append('<a href="/children/">' +
                '<img src="/img/menu/children_hover.png" width="108" height="37" alt="" title="" />' +
        '</a>')
        .css({ "cursor": "pointer", "z-index": "1000" })
        .pngFix();
        
        absolutizeMenu();
    },
    function() {
        $(this).empty();
    }).css({"position": "absolute"});

    $("#menuTabSoft:not(.elementSelected)").hover(function() {
        $(this)
        .append('<a href="/soft/">' +
                '<img src="/img/menu/soft_hover.png" width="105" height="37" alt="" title="" />' +
        '</a>')
        .css({ "cursor": "pointer", "z-index": "1000" })
        .pngFix();
        
        absolutizeMenu();
    },
    function() {
        $(this).empty();
    }).css({"position": "absolute"});
    
    $("#menuTabGames:not(.elementSelected)").hover(function() {
        $(this)
        .append('<a href="/games/">' +
                '<img src="/img/menu/games_hover.png" width="108" height="37" alt="" title="" />' +
        '</a>')
        .css({ "cursor": "pointer", "z-index": "1000" })
        .pngFix();
        
        absolutizeMenu();
    },
    function() {
        $(this).empty();
    }).css({"position": "absolute"});

    $("#menuTabVideo:not(.elementSelected)").hover(function() {
        $(this)
        .append('<a href="/dvd/">' +
                '<img src="/img/menu/video_hover.png" width="108" height="37" alt="" title="" />' +
        '</a>')
        .css({ "cursor": "pointer", "z-index": "1000" })
        .pngFix();
        
        absolutizeMenu();
    },
    function() {
        $(this).empty();
    }).css({"position": "absolute"});

    $("#menuTabMusic:not(.elementSelected)").hover(function() {
        $(this)
        .append('<a href="/music/">' +
                '<img src="/img/menu/music_hover.png" width="123" height="37" alt="" title="" />' +
        '</a>')
        .css({ "cursor": "pointer", "z-index": "1000" })
        .pngFix();
        
        absolutizeMenu();
    },
    function() {
        $(this).empty();
    }).css({"position": "absolute"});

    $("#currentTopic").pngFix();    

    function absolutizeMenu() {
        $('#menuTabBooks').css({"border": "0", "position": "absolute"});
        $('#menuTabStudy').css({"border": "0", "position": "absolute"});
        $('#menuTabChild').css({"border": "0", "position": "absolute"});
        $('#menuTabSoft').css({"border": "0", "position": "absolute"});
        $('#menuTabGames').css({"border": "0", "position": "absolute"});
        $('#menuTabVideo').css({"border": "0", "position": "absolute"});
        $('#menuTabMusic').css({"border": "0", "position": "absolute"});
    }
}

function preloadImages() {
    if (document.images) {
        if (!document.p) {
            document.p = new Array();
        }
    }

    var i, j = document.p.length, a = preloadImages.arguments;

    for (i = 0; i < a.length; i++) {
        if (a[i].indexOf("#") != 0) {
            document.p[j] = new Image;
            document.p[j++].src = a[i];
        }
    }
}

function toggle_juri_fields(checked)
{
  if (checked)
  {
    $('#juri_fields').show();
  }
  else
  {
    $('#juri_fields').hide();
  }
}

$(document).ready(function(){
    defineMenu();

    preloadImages('/img/menu/books_hover.png',
                  '/img/menu/children_hover.png',
                  '/img/menu/studybooks_hover.png',
                  '/img/menu/soft_hover.png',
                  '/img/menu/games_hover.png',
                  '/img/menu/video_hover.png',
                  '/img/menu/music_hover.png');
});

function show_pay_fields()
{
  var pay_system = get_selected_pay_system();
  if (pay_system == 7)
  {
    $('#boom_fields').show();
  }
  else
  {
    $('#boom_fields').hide();
  }
}

function get_regions(country_id)
{
		if (country_id == 0) {
			$("#state").html(
				'<option value="0">Выберите регион</option>'
			);
			
			$("#city_text").html(
				'<option value="0">Выберите город</option>'
			);
			
			return;
		}
		
		$("#state").attr("disabled", "disabled");
		$("#city_text").attr("disabled", "disabled");
		
		$.post("/get_regions.php",
				{country: country_id},
				function(response) {
					$("#state").removeAttr("disabled");
					$("#city_text").removeAttr("disabled");
					
					if (response.regions != null) {
						$("#state").html(
							'<option value="0">Выберите регион</option>' +
							getOptions(response.regions)
						);
						
						$("#city_text").html(
							'<option value="0">Выберите город</option>'
						);
					}
		}, "json");
}

function get_cities(region_id)
{
		if (region_id == 0) {
			$("#city_text").html(
				'<option value="0">Выберите город</option>'
			);
			
			return;
		}
		
		$("#city_text").attr("disabled", "disabled");
		
		$.post("/get_cities.php",
				{region: region_id},
				function(response) {
					$("#city_text").removeAttr("disabled");
					
					if (response.cities != null) {
						$("#city_text").html(
							'<option value="0">Выберите город</option>' +
							getOptions(response.cities)
						);
					}
		}, "json");
}

function getOptions(list) {
	var output = "";

	for (i in list) {
		output += '<option value="' + list[i].index + '"';
		
		if (list[i].selected) {
			output += ' selected="selected"';
		}
		
		output += '>' + list[i].label + '</option>';
	}
	
	return output;
}

function update_preorder(id, quantity)
{
    $.getJSON("/ajaxbasket2.php",
              "ID=" + id + "&quantity=" + quantity,
              function (r) {
                $('#renew_image_' + id).attr('src', '/i/beige/basket_renewed.jpg');
                $('#pre_total').html(r.total);
                
                total = r.total;
                weight = r.weight;
                
                recalculateSum();
                get_delivery_price($('#order'), total, weight);

                timeout1 = setTimeout("change_image('#renew_image_" + id + "', '/i/beige/basket_renew.gif')", 2000);
  });
  
}