﻿// zamjenjuje staru cijenu novim, s tim da ostavlja naziv valute
function WebshopShowNewValue(object_name, new_value, is_price)
{
    if (is_price == true)
    {
        current_text = $(object_name).text();
        old_value = current_text.match(/[0-9.]+/g);
        new_value = current_text.replace(old_value, WebshopDecimalToPrice(new_value));
    }
    return $(object_name).fadeOut(100).text(new_value).fadeIn(100);
}

// formatira decimalni broj (123456.12) u cijenu (123.456,12)
function WebshopDecimalToPrice(n)
{
    var c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
    + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

// cijenu pretvara u decimalni broj
function WebshopPriceToDecimal(s)
{
    price = s.replace(/[^\d\,]/g, "");
    return price.replace(",", ".");
}

// klasicno dodavanje proizvoda u kosaricu klikom na Dodaj u kosaricu
function WebshopAddToCart(id, code, currency)
{
    $.post('/webshop/data/add_to_cart/', {shopping_cart_item_id: id}, function(response)
    {
        response_status = response[0];
        response_qty = response[1];

        $(".cart_response_product_code").html(code);
        $("#cart_response_" + response_status).css('top', '-500px').animate({top: '0px'}, 500).delay(3000).animate({top: '-500px'}, 300);

        if (response_status == 1)
        {
            $("#product_qty_"+id).text(response_qty);
    		$.getJSON('/webshop/data/cart_info/?currency=' + currency + '&' + ( new Date() * 1 ), function(data){
                WebshopShowNewValue("#cart_count", data.item_count, false);
                WebshopShowNewValue("#cart_sum", data.total_c, true);
    		});
        }
    }, "json");
}

// dodavanje proizvoda u kosaricu odabirom iz pull downa (html: <select id="products_field">). Lista se nalazi na detaljima grupe
function WebshopAddToCartPullDown(products_field, currency)
{
    var id = $(products_field).val();
    var code = $(products_field).text();

    $.post('/webshop/data/add_to_cart/', {shopping_cart_item_id: id}, function(response)
    {
        response_status = response[0];
        response_qty = response[1];

        $(".cart_response_product_code").html(code);
        $("#cart_response_" + response_status).css('top', '-500px').animate({top: '-25px'}, 500).animate({top: '-25px'}, 2000).animate({top: '-500px'}, 300);

        if (response_status == 1)
        {
    		$.getJSON('/webshop/data/cart_info/?currency=' + currency + '&' + ( new Date() * 1 ), function(data){
                WebshopShowNewValue("#cart_count", data.item_count, false);
                WebshopShowNewValue("#cart_sum", data.total_c, true);
    		});
        }
    }, "json");
}

// Izmjena cijena varijacija
function WebshopChangeProductPrice(products_field, prices_field)
{
	$(products_field).change(function(){
        var id = $(this).val();
        $(prices_field).find(prices_field+'_'+id).show().siblings().hide();
    });
}

// dodavanje proizvoda u kosaricu upisom kolicine za dodavanje (html: <input type="text" id="product_qty">)
function WebshopAddToCartEnterQty(product_qty_field, id, code, currency)
{
    var qty = parseInt($(product_qty_field).val());

    if (qty != 'undefined' && qty > 0)
    {
        $.post('/webshop/data/set_qty/', {shopping_cart_item_id: id, qty: qty}, function(response)
        {
            response_status = response[0];
            response_qty = response[1];

            $(".cart_response_product_code").html(code);
            $("#product_qty").val(response_qty);
            $("#cart_response_" + response_status).css('top', '-500px').animate({top: '-25px'}, 500).animate({top: '-25px'}, 2000).animate({top: '-500px'}, 300);

            if (response_status > 0)
            {
        		$.getJSON('/webshop/data/cart_info/?currency=' + currency + '&' + ( new Date() * 1 ), function(data){
                    WebshopShowNewValue("#cart_count", data.item_count, false);
                    WebshopShowNewValue("#cart_sum", data.total_c, true);
        		});
            }
        }, "json");
    }
}

// uredjivanje kosarice. Dodavanje, brisanje, promijena kolicine....
function WebshopSetQty(id, mode, code, currency){
    var message_duration = 2000;
    var product = $("#product_" + id);
    var qty;

    if (mode == 'delete')
    {
        qty = 0;
    }
    else
    {
        qty = parseInt(product.find("input[name=qty]").val());
        if (mode == 'plus')
        {
            qty += 1;
        }
        else if(mode == 'minus')
        {
            qty -= 1;
        }
    }

    if (qty != 'undefined')
    {
        $.post('/webshop/data/set_qty/', {shopping_cart_item_id: id, qty: qty}, function(response)
        {
            response_status = response[0];
            response_qty = response[1];

            // if not click remove, and qty is 0
            if (response_qty < 1 && mode != 'delete')
            {
                mode = 'delete';
            }

            $("#cart-info span[class='cart-info-" + mode + "-" + response_status + "']").css('display', 'block').siblings().css('display', 'none');

            position =  product.position().top - 40;
            $("#cart-info").animate({top: position + 'px'}, 500).animate({top: position + 'px'}, message_duration).animate({top: '-500px'}, 300)

            $.getJSON('/webshop/data/cart_info/?currency=' + currency + '&' + ( new Date() * 1 ), function(data){
                WebshopShowNewValue("#cart_count", data.item_count, false);
                WebshopShowNewValue("#cart_sum", data.total_c, true);
                WebshopShowNewValue("#sc_total_items", data.total_items_c, true);
                WebshopShowNewValue("#sc_total_vat", data.total_vat_c, true);
                WebshopShowNewValue("#sc_total", data.total_c, true);

                if (data.item_count < 1){
                    $("#cart-step, #cart-table, #promotioncode, #giftrecipient, #btns, #total").animate({top: '0px'}, message_duration).slideUp();
                    $("#empty_shopping_cart_message").animate({top: '0px'}, message_duration).slideDown();
                }

                if (data.num_promotion_codes < 1)
                {
                    $("#giftrecipient").animate({top: '0px'}, message_duration).slideUp();
                }
            });

            if (response_status > 0)
            {
                product.find("input[name='qty']").val(response_qty);
                product.find("span[class='qty']").text(response_qty);

                var total = product.find(".item-total").text();
                total_price_formated = total.match(/[0-9.]+/g);
                total_price = WebshopPriceToDecimal(total);
                product_price = WebshopPriceToDecimal(product.find(".item-price").text());
                total_price_new = WebshopDecimalToPrice(parseFloat(product_price * response_qty).toFixed(2));
                new_value = total.replace(total_price_formated, total_price_new);
                WebshopShowNewValue("#product_" + id + " .item-total", new_value, false);

                // hide deleted product
                if (response_qty < 1)
                {
                    product.animate({top: position+'px'}, message_duration).fadeOut();
                }
            }
            else
            {
                qty = product.find("span[class='qty']").text();
                product.find("input[name='qty']").val(qty);
            }
        }, "json");
    }
}

// Provjera kod za popust
function WebshopSetPromotionCode(promotion_code_field)
{
    var promotion_code = $(promotion_code_field).val();

    $.post('/webshop/data/set_promotion_code/', {promotion_code: promotion_code}, function(response)
    {
        response_status = response[0];
        if (response_status == 1)
        {
            $("#promotioncode_success").fadeIn().delay(3000).fadeOut();
            $("#promotioncode-code").text(promotion_code);
            $("#promotioncode-total").text(response[1]);
        }
        else
        {
            $("#promotioncode_error").fadeIn().delay(3000).fadeOut();
        }
    }, "json");
}

// Dodaje listu mailova za primanje promotivnih kodova
function WebshopSetGiftRecipients(id, gift_receipients_field)
{
    var receipients_emails = $(gift_receipients_field).val();

    $.post('/webshop/data/set_gift_recipients/', {shopping_cart_item_id: id, emails: receipients_emails}, function(response)
    {
        response_status = response[0];
        if (response_status == 1)
        {
            $("#giftrecipient_message_success").fadeIn().delay(3000).fadeOut();
            $("#giftrecipient_total").text(response[1]);
            $(gift_receipients_field).val(response[2]);
        }
        else
        {
            $("#giftrecipient_message_error").fadeIn().delay(3000).fadeOut();
        }
    }, "json");
}

// filtrira select polja kod napredne pretrage
function AdvancedSearchFilter(form_name, currenty_field_id, mode, form_data)
{
    // nemoj filtrirat ako je promjenjeno polje za sortiranje
    if (currenty_field_id == 'id_sort')
    {
        return false;
    }

    if (mode == 'form')
    {
        form_data = $("form[name='"+form_name+"'] select").serialize();
    }

    var num_values = 0;

    if (form_data != '')
    {
        if (currenty_field_id)
        {
            $("#"+currenty_field_id).after('<span class="form_reload"></span>');
        }

        $("form[name='"+form_name+"'] select[id!='"+currenty_field_id+"']").attr('disabled', 'disabled');
        $("select[name='sort']").removeAttr('disabled');
        $.get('ajax_filter/', form_data, function(response)
        {
    		for(select_field_name in response)
            {
                // brisi sve vrijednosti iz trenutnog polja
                $("select[name='"+select_field_name+"'] > option[value!='']").hide();

                num_values = 0;
                for (field_value in response[select_field_name])
                {
                    // prikazuje samo one vrijednosti za koje postoje proizvodi
                    $("select[name='"+select_field_name+"'] > option[value='"+field_value+"']").show();

                    num_values ++;
                }

                // brise disabled sa onih select lista za koje postoji barem jedna opcija
                if (num_values > 0)
                {
                    $("select[name='"+select_field_name+"']").removeAttr('disabled');
                }
            }
            $(".form_reload").remove();

        }, "json");
    }
}

// boji pozadine kategorija ovisno o njihovoj razini, te mice '-' iz naziva (tako da je moguce pretraziti kategorije po nazivu)
function ColorizeSelectOption(field, normal_color, normal_bg, first_color, first_bg, second_color, second_bg)
{
    $(field + " option").each(function(){
        var color = normal_bg;
        var weight = 'normal';
        var fontcolor = normal_color;

        var title = $(this).html();
        // boja prvu razinu
        if (title[0] != '-')
        {
            color = first_bg;
            weight = 'bold';
            fontcolor = first_color;
        }

        // boja drugu razinu
        if (title[0] == '-' && title[2] != '-')
        {
            color = second_bg ;
            weight = 'bold';
            fontcolor = second_color;
        }

        // mice znakove '- ' iz naziva kategorije
        title = title.replace(/- /g,'');
        $(this).html(title).css('background', color).css('font-weight', weight).css('color', fontcolor);
    });
}

function ToggleBox(element_identify)
{
    $(element_identify).animate({opacity: 'toggle'});
}


$(function(){
    // show/hide webshop step description
    $("#cart-step div").hover(function(){
        $(this).find("span").show();
    }, function(){
        $(this).find("span").hide();
    });
});
