var my_action = '/cgi-bin/mebelus/mebelus.pl';
var order_action = '/cgi-bin/order0001.cgi';
var re_order = true;
var cupe_mode = true;

callJS = function(jsStr) { 
  return eval(jsStr)
}

open_gtshow = function(page, id)
{
 window.open('/mebelus/'+page+'?id='+id+'','gtview',
 'width=760,height=700,scrollbars=yes,resizable=yes');
}

open_gtselect = function(page)
{
 var gt=document.all('gt').options[document.all('gt').selectedIndex].value;
 window.open('/mebelus/'+page+'?id='+gt+'','gtview',
 'width=760,height=700,scrollbars=yes,resizable=yes');
}

// отрабатывает когда пользователь выбирает понравившийся ламинат
function opener_change(tid, image, title) {
    if (re_order) {
        $('div#order-wood').text( title );
    }
    
    $('#lam_id').val(tid);
    $('#lam_img').attr('src', image);
    $('#laminat').hide();
}

open_lamselect = function(page, id) {
    if ($(page).is(':hidden')) {
        $(page).html('<p>Загрузка... пожалуйста, подождите!</p>');
        $(page).show();
        $.get('/cgi-bin/mebelus/mebelus.pl', { 'action' : 'show_sl', 'id' : id }, function(data){
            $(page).html(data);
            initLytebox();
        });
    }
    else {
        $(page).hide();
    }
}


function reset_images(index)
{
    document.all('k_t').value='';
    document.all('k_t_img').src='/images/choose_companion.gif';
    document.all('m_t').value='';
    document.all('m_t_img').src='/images/choose_obivka.gif';
    $('#hp').val( $('#gt option:selected').attr('mebelus:price') );
    if (index > 0)
       {
    document.getElementById('cloth1').style.display = 'block';
    document.getElementById('cloth2').style.display = 'block';
       }
      else
       {
    document.getElementById('cloth1').style.display = 'none';
    document.getElementById('cloth2').style.display = 'none';
       }
}

reloadPrices = function(var_id, gab_id)
    {
     if (var_id != null)
        {
         $("#select_place").html('<img src="/images/ajax-loader.gif">');
         $("#table_place").html('<img src="/images/ajax-loader.gif">');
         $.get(''+my_action+'', { action: "up_pr", id: var_id, size: gab_id, place: "select" },
               function(data){
                  $("#select_place").html(data);
               });
         $.get(''+my_action+'', { action: "up_pr", id: var_id, size: gab_id, place: "table" },
               function(data){
                  $("#table_place").html(data);
               });
        }
    }

function buildCupeParam() {
    var txt = 'Габариты: ';
    var size_txt = '';
    $('.size-select option:selected').each(function(){
        if ( size_txt ) {
            size_txt = size_txt + 'x';
        }
        
        size_txt = size_txt + $(this).val(); 
    });

    txt = txt + size_txt + '; Комплектация: ' + $('.'+$('.cmpl-radio:checked').attr('id')).text();
    txt = txt + '; Дополнительные элементы: ';
    
    
    var is_add = 0;
    $('.ae-check:checked').each(function(){
        txt = txt + $('.'+$(this).attr('id')).text()+' ('+ $('.cnt_'+$(this).attr('id')).val() +'шт.)'+'; ';
        is_add = 1;
    });
    
    if ( !is_add ) {
        txt = txt + 'нет;'
    }
    
    txt = txt + ' Цвет профиля: ' + $('.'+$('.prof-check:checked').attr('id')).text();

    return txt;
}

// отправка заказа
function reorderSubmit() {
    if (re_order) {
        
        // формируем строку с названием
        var submit_string = $('div#order-title').text();
        if ($('div#order-wood').text() != '') {
            submit_string = submit_string + ', материал: ' + $('div#order-wood').text(); 
        }

        if ($('div#order-baset').text() != '') {
            submit_string = submit_string + ', обивка: ' + $('div#order-baset').text(); 
        }

        if ($('div#order-compt').text() != '') {
            submit_string = submit_string + ', компаньен: ' + $('div#order-compt').text(); 
        }

        var this_price = $('div#order-price').text();
        var cupe_price = recountCupeTotalPrice(); 
        if ( cupe_price ) {
            this_price = cupe_price;
            submit_string = submit_string + ', ' + buildCupeParam();
        }
        else {
            if ($('div#order-size').text() != '') {
                submit_string = submit_string + ', габариты: ' + $('div#order-size').text(); 
            }
        }
        
        // урл для окошка заказа
        var url = order_action + '?type=add&price=' + this_price + "&goods=" + submit_string;

        $.post( 
            url, {
                'type': 'add',
                'price': this_price,
                'goods': submit_string
            },
            function(data) {
                $.get( 
                    order_action, {
                        'type': 'basket2'
                    },
                    function(data) {
                        $('#basket-win').html( data );
                        alert('Товар добавлен в корзину!');
                        window.location = "http://www.mebelur.ru/order/";
                    }
                );
            }
        );
        
        return false;
    }
    
    return true;
}

function recountCupeTotalPrice() {
    var base_price = parseInt( $('.total-price').attr('rel') );
    var total = base_price;

    $('.add-to-price:checked').each(function(){
        var add = parseInt( $(this).attr('rel') );
        var count_field = $(this).attr('ext:count');
        var count = 1;
        if ( count_field ) {
            count = parseInt( $( '#' + count_field ).val() );
            if ( count < 1 ) {
                count = 1;
                $( '#' + count_field ).val( count );
            }
        }
        total = total + count * add;
    });

    $('.size-select option:selected').each(function(){
        var add = parseInt( $(this).attr('rel') );
        total = total + add;
    });
    
    $('.total-price').text( total );
    return total;
}

function updateHandlers() {
    $('#window-select .txt3').click(function(){
        return false;
    });

    $('.btn-select').click(function(){
        if ( ob.is('.cl-main') ) {
            $('#m_t').val( $(this).attr('mebelus:tid') );
            $('div#order-baset').text( $(this).attr('mebelus:title') );
            $('#m_t_img').attr('src', $(this).attr('mebelus:link'));
        }
        if ( ob.is('.cl-second') ) {
            $('#k_t').val( $(this).attr('mebelus:tid') );
            $('div#order-compt').text( $(this).attr('mebelus:title') );
            $('#k_t_img').attr('src', $(this).attr('mebelus:link'));
        }
        return false;
    });
}

$(document).ready(function(){
    // перехватываем ошибки запроса
    $('#laminat, #basket-win').ajaxError(function(){
        $("#laminat").html('<p>Error</p>');
    });
    
    // если нужна интеграция с корзиной реактора - связываем обработчики
    if (re_order) {
        // размер и цена по умолчанию
        $('div#order-size').text( $('.order-size:checked').attr('order:size') );
        $('div#order-price').text( $('.order-size:checked').attr('order:price') );
        
        // изменение габарита
        $('.order-size').click(function(){
            $('div#order-size').text( $(this).attr('order:size') );
            $('div#order-price').text( $(this).attr('order:price') );
            $('div#size-id').text( $(this).attr('size:id') );
        });
        
        // отправка заказа
        $('#order-submit').click(function(){
            return reorderSubmit();
        });
    }
    
    if ( cupe_mode ) {
        $('.basket-catch').click(function(){
            recountCupeTotalPrice();
        });
        $('.size-select').change(function(){
            recountCupeTotalPrice();
        });
        $('.additional-count').bind('focusout', function(){
            recountCupeTotalPrice();
        });
    }

    $('.table-cell').hover(function(){
        $(this).addClass('active-cell');
    }, function(){
        $(this).removeClass('active-cell');
    });
    
    $('.cl').click(function(){
        ob = $(this);
        var vid = $(this).attr('mebelus:vid'); 
        var tid = $('div#size-id').text();
        window.open( '/mebelus/fview.shtml?id='+vid+'&tid='+tid, 'fview', 'width=1000,height=700,scrollbars=yes,resizable=yes' );
    });

});

