
function selectTab(selected, i) {
    $('#tabs').tabs('enable', i);
    $('#tabs').tabs('option', 'selected', i);
    $('#tabs').tabs('disable', selected);
}

function prevStep() {
    var selected = $('#tabs').tabs('option', 'selected');
    selectTab(selected, selected-1);
}

function nextStep() {
    var selected = $('#tabs').tabs('option', 'selected');
    if(selected == 0) {
        selectTab(selected, selected+1);
    } else if(selected == 1) {
        // WYSYLKA/DOSTAWA
        if($('input[name=\'carrier_radio\']:checked').val() !== undefined) {
            $.blockUI();
            $.ajax({
                url: 'login',
                cache: false,
                type: 'POST',
                dataType: 'json',
                data: ({ajax: true}),
                success: function(result){
                    $.unblockUI()
                    if(result.login != undefined && result.login) {
                        selectTab(selected, selected+2);
                        $('#tabs-3 .form-container').html(result.html);
                    } else {
                        selectTab(selected, selected+1);
                        $('#tabs-3 .form-container').html(result.html);
                    }
                }
            });
        } else {
            $('.tab_title_content').effect("pulsate", {}, 400);
        }
    } else if(selected == 2) {
        // WALIDACJA FORMULARZA LOGOWANIA

        // Wyciaganie danych z formularza
        var formFields = [];
        $('#tabs-3 .form-container input').each(function(){
            if(this.type == 'checkbox')
                formFields.push({'f_name': this.name, 'f_val': $('#'+this.name).attr('checked')});
            else
                formFields.push({'f_name': this.name, 'f_val': this.value});
        });
        // Wysylanie pol formularza
        $.blockUI();
        $.ajax({
            url: 'login',
            cache: false,
            type: 'POST',
            dataType: 'json',
            data: ({submit:'true', fields:$.toJSON(formFields, true), ajax: true}),
            success: function(result){
                $.unblockUI()
                $('#tabs-3 .form-container').html(result.html);
                changeInvoiceFields()
                if(result.login) {
                    selectTab(selected, selected+1);
                }
            }
        });
    } else if(selected == 3) {
        // WALIDACJA FORMULARZA ZAMOWIENIA

        // Wyciaganie danych z formularza
        var formFields = [];
        $('#tabs-4 .form-container input').each(function(){
            if(this.type == 'checkbox')
                formFields.push({'f_name': this.name, 'f_val': $('#'+this.name).attr('checked')});
            else
                formFields.push({'f_name': this.name, 'f_val': this.value});
        });
        // Wysylanie pol formularza
        $.blockUI();
        $.ajax({
            url: 'order/get_form',
            cache: false,
            type: 'POST',
            dataType: 'json',
            data: ({submit:'true', fields:$.toJSON(formFields, true)}),
            success: function(result){
                $.unblockUI()
                $('#tabs-4 .form-container').html(result.html);
                changeInvoiceFields()
                if(result.errors != 0) {
                    selectTab(selected, selected+1);
                    // Pobieranie podsumowania
                    $.blockUI();
                    $.ajax({
                        url: 'order/summary',
                        cache: false,
                        type: 'POST',
                        dataType: 'json',
                        data: ({
                            carrier_id: $('input[name=\'carrier_radio\']:checked').val(),
                            payment_id: $('input[name=\'payment_radio\']:checked').val()
                        }),
                        success: function(result){
                            $.unblockUI()
                            // Uzupelnienie odpowiednich danych podsumowania
                            $('#count_prod').html(result.count_prod);
                            $('#sum_prod').html(result.sum_prod);
                            $('#sum_carr').html(result.sum_carr);
                            $('#main_sum').html(result.main_sum);
                        }
                    });
                }
            }
        });
    } else if(selected == 4) {
        var formFields = [];
        $('#tabs-4 .form-container input').each(function(){
            if(this.type == 'checkbox')
                formFields.push({'f_name': this.name, 'f_val': $('#'+this.name).attr('checked')});
            else
                formFields.push({'f_name': this.name, 'f_val': this.value});
        });
        $.blockUI();
        $.ajax({
            url: 'order/final_step',
            cache: false,
            type: 'POST',
            data: ({
                submit: 'true',
                carrier_id: $('input[name=\'carrier_radio\']:checked').val(),
                payment_id: $('input[name=\'payment_radio\']:checked').val(),
                fields: $.toJSON(formFields, true)
            }),
            success: function(result){
                $.unblockUI()
                if(result == 'count_error') {
                    // Blad ilosci produktow koszyku
                    $("#order_failed_dialog").dialog({
                        modal: true,
                        close: function() {
                            window.location.reload();
                        },
                        buttons: {
                            ok: function() {
                                $(this).dialog('close');
                            }
                        }
                    });
                } else if(result == 'carrier_error') {
                    // Blad w wyborze wysylki/platnosci
                    $("#order_failed_dialog").dialog({
                        modal: true,
                        close: function() {
                            changePayments();
                            selectTab(selected, 1);
                        },
                        buttons: {
                            ok: function() {
                                $(this).dialog('close');
                            }
                        }

                    });
                } else {
                    // Brak bledow podczas dodawania zamowienia
                    $("#order_success_dialog").dialog({
                        modal: true,
                        close: function() {
                            window.location.reload();
                        },
                        buttons: {
                            ok: function() {
                                $(this).dialog('close');
                            }
                        }
                    });
                }
            }
        });
    }
}

/**
 * Sprawdź dostępność produktu (opierajac sie na cechach)
 */
function checkAvailable() {
    // Czy dostepny
    var avail = true;
    // Petla po wszyskich selektach  wariantami
    $('#features>.select').each(function(index) {
        if($('#features>.select>select:eq('+index+')').val().indexOf('#') != -1) {
            $('#add_to_basket').hide();
            $('#ask_available').show();
            avail = false;
        }
    });
    if(avail) {
        // Wszystkie cechy sa dostepne
        $('#add_to_basket').show();
        $('#ask_available').hide();
    }
}

/**
 * Dodaj do koszyka
 */
function addToBasket(id, price){
    var f_array = [];
    $('#features>.select').each(function(index){
        f_array.push({
            id: $('#features>.select>select:eq('+index+')').attr("id"),
            val: $('#features>.select>select:eq('+index+')').val()
        });
    });
    $("#add_to_basket_dialog").dialog({
        modal: true,
        open: function() {
            setTimeout("$(\"#add_to_basket_dialog\").dialog('close')", 1000);
        }
    });
    $("#add_to_basket_dialog").dialog('open');
    $.blockUI();
    $.ajax({
        url: 'cart/add_product',
        cache: false,
        type: 'POST',
        data: ({id:id, price:price, features:$.toJSON(f_array)}),
        success: function(html){
            $.unblockUI();
            $('#cart_box').replaceWith(html);
            $('#cart_box').effect("pulsate", {}, 400);
        }
    });
}

function editBasketProduct(th, index){
    $.blockUI(); 
    $.ajax({
        url: 'cart/edit_product',
        cache: false,
        type: 'POST',
        dataType: 'json',
        data: ({index:index, value:$(th).val()}),
        success: function(result){
            $.unblockUI();
            $('#cart_box').replaceWith(result.cart_box);
            $('#product_'+index+'>.price_sum').html(result.price_sum);
            $('#main_summary_price').html($('#cart_summary').html());
            $('#cart_box').effect("pulsate", {}, 400);
            changePayments();
        }
    });
}

function removeFromBasket(index){
    $.blockUI(); 
    $('#product_'+index).hide('drop', {}, 500);
    $.ajax({
        url: 'cart/remove_product',
        cache: false,
        type: 'POST',
        data: ({index:index}),
        success: function(html){
            $.unblockUI();
            $('#cart_box').replaceWith(html);
            $('#main_summary_price').html($('#cart_summary').html());
            $('#cart_box').effect("pulsate", {}, 400);
            changePayments();
        }
    });
}

function changeCarriers(th){
    $.blockUI();
    $.ajax({
        url: 'order/get_carriers',
        cache: false,
        type: 'POST',
        data: ({payment_id:$(th).val()}),
        success: function(html){
            $.unblockUI();
            $('#carriers').html(html);
        }
    });
}

function changePayments(){
    $.blockUI();
    $.ajax({
        url: 'order/get_payments',
        cache: false,
        type: 'POST',
        success: function(html){
            $.unblockUI();
            $('#payments').html(html);
            $('#carriers').html('');
        }
    });
}

function getOrderForm(){
    $.ajax({
        url: 'order/get_form',
        cache: false,
        type: 'POST',
        dataType: 'json',
        success: function(result){
            $('#tabs-4 .form-container').html(result.html);
            changeInvoiceFields()
        }
    });
}

function changeInvoiceFields(){
    if($('#invoice').attr('checked')) {
       $('#invaddr_name').parent().show();
       $('#invaddr_street').parent().show();
       $('#invaddr_postcode').parent().show();
       $('#invaddr_city').parent().show();
       $('#nip').parent().show();
    } else {
       $('#invaddr_name').parent().hide();
       $('#invaddr_street').parent().hide();
       $('#invaddr_postcode').parent().hide();
       $('#invaddr_city').parent().hide();
       $('#nip').parent().hide();
    }
}

