$(document).bind('ready', function() {
    rebuildCart();
    
    $('.cart-action').click(function() {
        cartRequest(this);
        return false;
    });
    
    $('.send-inquiry').click(function() {
        inquiryActions(this);
        return false;
    });
    
});

function showMessage(msg, title, button){
    var options = {
        'resizable': false,
        'title': title,
        'modal': true
    };
    $('<div>' + msg + '</div>').dialog(options);
}

var URL_getCartContent = '/shop/cart/get-cart';
var URL_cartContent = '/shop/cart/content';
var URL_processStepNext = '/shop/process/cashier';
var URL_processStepBack = '/shop/process/back';
var URL_processCancel = '/shop/process/cancel';
var URL_processPartialsTakeover = '/shop/process/partials/takeover';



//////////////////
//// Cart actions - takes href and sends xhr to cart handler
//
function cartRequest(trigger, sibling){
    var triggerParent = $(trigger).parent().parent().get(0);
    var quantity = '';
    if( $(triggerParent).find('input.add-to-cart-value').length ){
        var qnt = $(triggerParent).find('input.add-to-cart-value').val();
        quantity = '/quantity/' + qnt;
    }
    $.ajax({
        'url': $(trigger).attr('href') + quantity,
        'dataType': 'json',
        'async': false, // syncronous request - disable browser while sending
        'success': showCartMessage
    });
}

function showCartMessage(response){
    if(response.code == -1){
        //console.log(response);
    }
    if(response.message){
        showMessage(response.message, 'Košarica');
    }
    rebuildCart();
}

///////////
//// Rebuild cart bar and check if anything has left in cart
//
function rebuildCart(){
    $.ajax({
        'url': URL_cartContent,
        'dataType': 'json',
        'async': false, // syncronous request - disable browser while sending
        'success': function(response){
            buildCartBar(response);
            checkCart();
        }
    });
}

var CartContent = {};
///////////
//// (re)Build cart bar
//
function buildCartBar(response){
    CartContent = response;
    var cartContainer = $('#cart-bar');
    $(cartContainer).empty();
    if( response.itemSum) {
        var bar = $('#cart-bar-template').clone();
        $(bar).find('.cart-info .cart-quantity-sum').html(response.itemSum);
        $(bar).find('.cart-info .cart-price-sum').html(response.priceSum);
        $(bar).removeAttr('id','cart-bar-template');
    }
    else {
        var bar = $('#empty-cart-bar-template').clone();
        $(bar).removeAttr('id','empty-cart-bar-template');
    }
    $(bar).addClass('cart-bar');
    $(bar).show();
    $(cartContainer).append(bar);
}

var checkCartContent = false; // flag for checking
var showingOrderForm = false; // flag for checking cart after ordering start
///////////
//// Check if cart has anything in it, and close/cancel cart or order dialogs if not
///  @return bool true if cart is not empty
//
function checkCart(){
    if(! CartContent.priceSumFloat && checkCartContent){
        showMessage('Vaša košarica je prazna', 'Vaša košarica');
        if( showingOrderForm){
            orderCancel();
        }
        else {
            cartClose();
        }
        return false;
    }
    return true;
}

///////////
//// Begin (or continue) ordering process
//
function cartToCashier(){
    checkCartContent = true;
    showingOrderForm = true;
    if( checkCart() ){
        $.ajax({
            'url': URL_processStepNext,
            'dataType': 'json',
            'async': false, // syncronous request - disable browser while sending
            'success': function (response){
                    if(response.code == -1){
                        if(response.message){
                            showMessage(response.message, 'Narudžba');
                        }
                        return;
                    }
                    $('#cashier-dialog').html(response.form);
                    rebuildCart();
                    populateCart();
                    orderShow();
                }
        });
    }
}

///////////
//// Order cancel
//
function orderCancel(){
    $.ajax({
        'url': URL_processCancel,
        'dataType': 'json',
        'async': false, // syncronous request - disable browser while sending
        'success': function(response){
            if(response.code != -1){
            }
            if(response.message){
                showMessage(response.message, 'Narudžba');
            }
            orderClose();
        }
    });
    return false;
}

///////////
//// Close order dialog
//
function orderClose(){
    $('#cashier-dialog').dialog('close');
    checkCartContent = false;
    showingOrderForm = false;
    return false;
}

///////////
//// Show order dialog
//
function orderShow(){
    $('#cashier-dialog').dialog({
        'modal': true,
        'resizable': false,
        'title': 'Narudžba',
        'width': '740px'
    });
    return false;
}

///////////
//// Order confirm
//
function orderConfirm(){
    var form = $('#process-order-form');
    
    //$('#start_of_transaction').val($('#dummy-honey').html());
    $('#order_startup_timestamp').val($('#dummy-honey').html());
    
    var vals = $(form).find('input[type="text"], input[type="password"], input[type="hidden"], input[type="radio"]:checked, select, textarea');
    var checks = $(form).find('input[type="checkbox"]:checkbox');
    
    
    var dataTrunk = {};
    for(i=0; i<vals.length; i++){
        dataTrunk[ $(vals[i]).attr('name') ] = $(vals[i]).val();
    }
    for(i=0; i<checks.length; i++){
        dataTrunk[ $(checks[i]).attr('name') ] = 1;
    }
    
    orderClose(); // dissable further changes or multiple sending of form!
    $.ajax({
        'url': URL_processStepNext,
        'dataType': 'json',
        'type': 'post',
        'data': dataTrunk,
        'async': false, // syncronous request - disable browser while sending
        'success': _actionProcess
    });
    return false;
}

///////////
//// Return to the previous step
//
function orderStepBack(){
    orderClose(); // dissable further changes or multiple sending of form!
    $.ajax({
        'url': URL_processStepBack,
        'dataType': 'json',
        'async': false, // syncronous request - disable browser while sending
        'success': _actionProcess
    });
    return false;
}

function _actionProcess(response){
    if(response.code == -1){
        if(response.message){
            showMessage(response.message, 'Narudžba');
            return false;
        }
    }
    $('#cashier-dialog').html(response.form);
    rebuildCart();
    populateCart();
    orderShow();
    return true;
}


////////////
//// Cart actions from within the cart table container
//
function cartActions(trigger){
    $.ajax({
        'url': $(trigger).attr('href'),
        'dataType': 'json',
        'async': false, // syncronous request - disable browser while sending
        'success': function(response){
            populateCart();
            rebuildCart();
        }
    });
}

//////////////
//// Show cart dialog
//
function showCart(){
    checkCartContent = true;
    if( checkCart() ){
        populateCart();
        $('#cart-dialog').dialog({ title: 'Vaša košarica', width: 'auto', modal: true, resizable: false });
    }
}

////////////
//// Populate cart table containers
//
function populateCart(){
    $.ajax({
        url: URL_getCartContent,
        'async': false, // syncronous request - disable browser while sending
        success: function(response){
            $('.cashier-cart-container').html(response);
        }
    });
}

///////////
//// Close cart dialog
//
function cartClose(){
    checkCartContent = false;
    $('#cart-dialog').dialog('close');
}


////////////
//// inquiry actions
//
function inquiryActions(trigger){
    $.ajax({
        'url': $(trigger).attr('href'),
        'dataType': 'json',
        'async': false, // syncronous request - disable browser while sending
        'success': function(response){
            $('#inquiry-dialog').html(response);
            showInquiry();
        }
    });
}


function inquirySubmit(href){
    inquiryClose();
    
    var form = $('#inquiry-form');
    
    $('#request_startup_timestamp').val($('#dummy-honey').html());
    
    var vals = $(form).find('input[type="text"], input[type="password"], input[type="hidden"], input[type="radio"]:checked, select, textarea');
    var checks = $(form).find('input[type="checkbox"]:checkbox');
    
    var dataTrunk = {};
    for(i=0; i<vals.length; i++){
        dataTrunk[ $(vals[i]).attr('name') ] = $(vals[i]).val();
    }
    for(i=0; i<checks.length; i++){
        dataTrunk[ $(checks[i]).attr('name') ] = 1;
    }
    
    $.ajax({
        'url': href,
        'dataType': 'json',
        'data': dataTrunk,
        'type': 'post',
        'async': false, // syncronous request - disable browser while sending
        'success': function(response){
            $('#inquiry-dialog').html(response);
            showInquiry();
        }
    });
}

//////////////
//// Show inquiry dialog
//
function showInquiry(){
    $('#inquiry-dialog').dialog({ title: 'Upit o proizvodu', width: '600px', modal: true, resizable: false });
}

///////////
//// Close inquiry dialog
//
function inquiryClose(){
    $('#inquiry-dialog').dialog('close');
}
