/**
 * $Id$
 *
 * @todo incapsulate to object
 */
var pluralFormRub = ["рубль", "рубля", "рублей"];
var pluralFormModel = ["модель", "модели", "моделей"];
var priceByCover = {};

function updateCoverPrice()
{
    sizeId = $('#product_size_price').val();
    selectedSize = sizePrice[sizeId];

    if (selectedSize == undefined) {
        $(this).html(formatPrice(0));
    } else {
        $('#matt_height').text(selectedSize.height+' см');
        priceBase = parseInt(selectedSize.price);
        $('.cover_price').each(function (index) {
            coverId = $(this).attr('id').substr(12);
            currCover = coverFee[coverId];
            price = priceBase;
            if (currCover.type == 'percent') {
                price = price + Math.round(price * (parseInt(currCover.percent)/100));
            } else {
                for (i in currCover.fees) {
                    fee = currCover.fees[i];
                    //console.log('fee width: '+fee.width+', length:'+fee.length);
                    // @todo disable cover if there is no suitable size?
                    if (fee.width == selectedSize.width && fee.length == selectedSize.length) {
                        //console.log('fee found! '+fee.fee);
                        price = price + parseInt(fee.fee);
                        break;
                    }
                }
            //console.log('fixed fee: '+price);
            }
            priceByCover[''+coverId] = price;
            price = discountedPrice(price);
            //console.log('final: '+price);
            $(this).html(formatPrice(price));
        });
        setCoverPrice();
    }
}
function updateSimplePrice()
{
    sizeId = $('#product_size_price').val();
    //console.log('size id: '+sizeId);
    selectedSize = sizePrice[sizeId];
    if (selectedSize != undefined) {
        $('#matt_height').text(selectedSize.height+' см');
        price = selectedSize.price;
        if (discount > 0) {
            $('#current_price').html(formatPrice(discountedPrice(price))
                + (discount > 0 ? '<span>Скидка <b>'+discount+'%</b></span>' : ''));
            $('#old_current_price').html(formatPrice(price));
        } else {
            $('#current_price').html(formatPrice(price));
        }
    }
}

function setCoverPrice()
{
    id = $('input[name=cover]:checked').attr('id').substr(6);
    price = priceByCover[''+id];
    if (discount > 0) {
        $('#current_price').html(formatPrice(discountedPrice(price))
            + (discount > 0 ? '<span>Скидка <b>'+discount+'%</b></span>' : ''));
        $('#old_current_price').html(formatPrice(price));
    } else {
        $('#current_price').html(formatPrice(price));

    }
}


function updateMattBlocksList()
{
    mattSelect = $("#Product_mattress_block_id")
    selectedTypeId = mattSelect.val();
    mattSelect.children().remove();
    val = $("#Product_is_springless").val();
    mattSelect.append($("<option/>").attr({value: -1}).text("-Любой-"));
    for (i in mattBlockData) {
        if (val > 0) {
            bSelectedIsSprLess = val == 1;
            if (bSelectedIsSprLess != mattBlockData[i].is_springless) continue;
        }
        optDom  = $("<option/>").attr({value: mattBlockData[i].id}).text(mattBlockData[i].name);
        if (mattBlockData[i].id == selectedTypeId) {
            optDom.attr("selected", "selected");
        }
        mattSelect.append(optDom);
    }
}

function addToCart()
{
    var isMattress = $('.cover_price').length;
    sizeId = $('#product_size_price').val();
    //console.log('size id: '+sizeId);
    selectedSize = sizePrice[sizeId];
    if (selectedSize == undefined) {
        alert('Данный товар временно не доступен.');
        return;
    }
    url = '/cart/add/id/'+productId+'/w/'+selectedSize.width+'/l/'+selectedSize.length+'/h/'+selectedSize.height+'/qty/1';
    if (isMattress) {
        coverId = $('input[name=cover]:checked').attr('id').substr(6);
        url += '/cover/'+coverId;
    }

    document.location.href = url;
}

function formatPrice(price)
{
    price = parseFloat(price);
    return '<strong><b>'+price.toFixed(0)+'</b> '+pluralFormRub[pluralState(price)]+'</strong>';
}

function updateTwoSidedComfort()
{
    if ($("#Product_two_sided").is(":checked")) {
        $("#Product_comfort").removeAttr("disabled");
        $("#Product_comfort_bottom").removeAttr("disabled");
        $("#Product_comfort_both").attr("disabled", "disabled");
    } else {
        $("#Product_comfort").attr("disabled", "disabled");
        $("#Product_comfort_bottom").attr("disabled", "disabled");
        $("#Product_comfort_both").removeAttr("disabled");
    }
}

function updateSpringsType()
{
    if ($("#Product_is_springless").val() == 2) {
        $("#Product_mattress_block_id").removeAttr("disabled");
    } else {
        $("#Product_mattress_block_id").attr("disabled", "disabled");
    }
}

function doCount()
{
    $.getJSON("/products/count", $("#mattress-search-form").serializeArray(), function (data) {
        if (data.success) {
            $("#ms_search_result").html("<strong>"
                +data.count+"</strong> <span>"+pluralFormModel[pluralState(data.count)]+"</span>");
        } else {
            alert("FAILED!");
        }
    });
}


function pluralState(a)
{
    if (a%10==1 && a%100!=11) {
        return 0;
    } else if (a%10>=2 && a%10<=4 && (a%100<10 || a%100>=20)) {
        return 1;
    } else {
        return 2;
    }
}

function discountedPrice(price)
{
    return price - Math.round(price*discount/100);
}


function displayErrors(errors)
{
    errList = [];
    $.each(errors, function (i, err) {
        errList.push(err.desc);
    });
    $('#err-messages').html('<ul><li>'+errList.join('</li><li>')+'</li></ul>').fadeIn();
}

function scrollTop()
{
    $("html, body").animate({scrollTop: $("#yw0").offset().top}, 200);
}
