(function($) {
    $.extend({
        add2cart: function(source_id, target_id, callback) {

            var source = $('#' + source_id );
            var target = $('#' + target_id );

            var shadow = $('#' + source_id + '_shadow');
            if( !shadow.attr('id') ) {
                $('body').prepend('<div id="'+source.attr('id')+'_shadow" style="display: none; background-color: #808080; border: solid 1px darkgray; position: static; top: 0px; z-index: 100000;">&nbsp;</div>');
                shadow = $('#'+source.attr('id')+'_shadow');
            }

            if( !shadow ) {
                alert('Cannot create the shadow div');
            }

            shadow.width(source.outerWidth()).height(source.outerHeight()).css('top', source.offset().top).css('left', source.offset().left).css('opacity', 0.5).fadeIn("200");
            shadow.css('position', 'absolute');

            shadow.animate( {
                width: target.innerWidth(),
                height: target.innerHeight(),
                top: target.offset().top,
                left: target.offset().left
            }, {
                duration: 600,
                complete: callback
            } )
            .animate( {
                opacity: 0
            }, {
                duration: 200,
                complete: function() {
                    shadow.remove()
                    }
            } );
        }
    });
})(jQuery); 

function isUnsignedInteger(s){
    return (s.toString().search(/^[0-9]+$/) == 0);
}

function isUnsignedFloat(s){
    return (s.toString().search(/^[0-9]+(,|.)?[0-9]*$/) == 0);
}


function getErrorText(key){
    var errorDict = {
        "bad_format" : "Neteisingas formatas. \u012evedami gali būti tik teigiami skaičiai.<br/>",
        "bad_format_cart" : "Neteisingas formatas. Gali b\u016bti įvedami tik teigiami skaičiai.<br/>Kiekis automatiškai pakoreguotas.<br/>",
        "cart_empty" : "Laukelis negali b\u016bti tuščias.<br/>",
        "bad_data" : "Neteisingai \u012fvesti duomenys.<br/>Prašome įvesti korektiškus duomenis.<br/>"
    };
    if (key in errorDict){
        return errorDict[key];
    } else {
        return "N\u0117ra reikšmės žodyne.";
    }
}

function hideError(fieldid){
    $("#skaiciuokle_klaida").html("");
    if (fieldid != ""){
        if ($("#"+fieldid).hasClass("error")){
            $("#"+fieldid).removeClass("error");
        }
    }
    if( $("#addtocart_btn").hasClass("noclick")){
        $("#addtocart_btn").removeClass("noclick");
    }
}

function showError(fieldid, errorKey, changeOnlyVal, value){
    if (fieldid != ""){
        if (value != ""){
            $("#"+fieldid).val(value);
        }
        if (!changeOnlyVal) {
            $("#"+fieldid).addClass("error")
        }
    }
    $("#skaiciuokle_klaida").html(getErrorText(errorKey));
    $("#addtocart_btn").addClass("noclick");
}

function enableAddToCart(){
    if( $("#addtocart_btn").hasClass("noclick")){
        $("#addtocart_btn").removeClass("noclick");
    }
}

function parseFloat2(str){
    return parseFloat(str.replace(",", "."));
}

function calculatePackagesAmount(){
    var product_size_type = $("#product_size_type_inp").val();
    var length;
    var width;
    var need_amount;
    var square_meters;
    var amount;
    var product_price;
    var product_sum_price;
    var product_amount;
    var product_units;
    switch(product_size_type){
        case '1':
        case '2':
        case '3':{
            break;
        }
        case '4':{
            length_ = $("#product_length_inp").val();
            width = $("#product_width_inp").val();
            need_amount = $("#product_need_amount_inp").val();
            length_ = parseFloat2(length_);
            width = parseFloat2(width);
            if (need_amount != "") {
                need_amount = parseFloat2(need_amount);
                if (length_ && width && need_amount){
                    square_meters = width*length_;
                    amount = need_amount/square_meters;
                    amount = Math.ceil(amount);
                    $("#product_cart_amount_inp").val(amount);
                    product_price = $("#product_price_inp").val();
                    product_price = parseFloat2(product_price);
                    product_sum_price = amount*product_price;
                    product_sum_price = product_sum_price.toFixed(2);
                    $("#product_sum_price_inp").val(product_sum_price);
                } else {
                    showError("product_need_amount_inp", "bad_format", false, "");
                }
                
            } else {
                hideError("product_need_amount_inp");
            }
            break;
        }
        case '5':{
            product_amount = $("#product_amount_inp").val();
            need_amount = $("#product_need_amount_inp").val();
            product_amount = parseFloat2(product_amount);
            if (need_amount != "") {
                need_amount = parseFloat2(need_amount);
                if (need_amount){
                    amount = need_amount/product_amount;
                    amount = Math.ceil(amount);
                    $("#product_cart_amount_inp").val(amount);
                    product_price = $("#product_price_inp").val();
                    product_price = parseFloat2(product_price);
                    product_sum_price = amount*product_price*product_amount;
                    product_sum_price = product_sum_price.toFixed(2);
                    $("#product_sum_price_inp").val(product_sum_price);
                } else {
                    showError("product_need_amount_inp", "bad_format", false, "");
                }
            } else {
                hideError("product_need_amount_inp");
            }
            break;
        }
        case '6':{
            product_units = $("#product_units_inp").val();
            need_amount = $("#product_need_amount_inp").val();
            product_units = parseInt(product_units);
            if (need_amount != "") {
                need_amount = parseInt(need_amount);
                if (need_amount){
                    amount = need_amount/product_units;
                    amount = Math.ceil(amount);
                    $("#product_cart_amount_inp").val(amount);
                    product_price = $("#product_price_inp").val();
                    product_price = parseFloat2(product_price);
                    product_sum_price = amount*product_price*product_units;
                    product_sum_price = product_sum_price.toFixed(2);
                    $("#product_sum_price_inp").val(product_sum_price);
                } else {
                    showError("product_need_amount_inp", "bad_format", false, "");
                }
            } else {
                hideError("product_need_amount_inp");
            }
            break;
        }
        case '7':{
            product_amount = $("#product_amount_inp").val();
            need_amount = $("#product_need_amount_inp").val();
            product_amount = parseFloat2(product_amount);
            if (need_amount != "") {
                need_amount = parseFloat2(need_amount);
                if (need_amount){
                    amount = need_amount/product_amount;
                    amount = Math.ceil(amount);
                    $("#product_cart_amount_inp").val(amount);
                    product_price = $("#product_price_inp").val();
                    product_price = parseFloat2(product_price);
                    product_sum_price = amount*product_price*product_amount;
                    product_sum_price = product_sum_price.toFixed(2);
                    $("#product_sum_price_inp").val(product_sum_price);
                } else {
                    showError("product_need_amount_inp", "bad_format", false, "");
                }
            } else {
                hideError("product_need_amount_inp");
            }
            break;
        }
    }
}

function calculateNeedAmount(){
    var product_size_type = $("#product_size_type_inp").val();
    var length;
    var width;
    var cart_amount;
    var square_meters;
    var amount;
    var product_price;
    var product_sum_price;
    var product_amount;
    var product_units;
    switch(product_size_type){
        case '1':
        case '2':
        case '3':{
            cart_amount = $("#product_cart_amount_inp").val();
            if (cart_amount != "") {
                cart_amount = parseInt(cart_amount);
                if (cart_amount){
                    product_price = $("#product_price_inp").val();
                    product_price = parseFloat2(product_price);
                    product_sum_price = cart_amount*product_price;
                    product_sum_price = product_sum_price.toFixed(2);
                    $("#product_sum_price_inp").val(product_sum_price);
                } else {
                    showError("product_cart_amount_inp", "bad_format_cart", true, "1");
                }

            } else {
                showError("product_cart_amount_inp", "cart_empty", true, "1");
            }
            break;
        }
        case '4':{
            length_ = $("#product_length_inp").val();
            width = $("#product_width_inp").val();
            cart_amount = $("#product_cart_amount_inp").val();
            length_ = parseFloat2(length_);
            width = parseFloat2(width);
            if (cart_amount != "") {
                cart_amount = parseInt(cart_amount);
                if (length_ && width && cart_amount){
                    square_meters = width*length_;
                    amount = cart_amount*square_meters;
                    amount = amount.toFixed(4);
                    $("#product_need_amount_inp").val(amount);
                    product_price = $("#product_price_inp").val();
                    product_price = parseFloat2(product_price);
                    product_sum_price = cart_amount*product_price;
                    product_sum_price = product_sum_price.toFixed(2);
                    $("#product_sum_price_inp").val(product_sum_price);
                } else {
                    alert("Kabum");
                    showError("product_cart_amount_inp", "bad_format_cart", true, "1");
                }
            } else {
                showError("product_cart_amount_inp", "cart_empty", true, "1");
            }
            break;
        }
        case '5':{
            product_amount = $("#product_amount_inp").val();
            cart_amount = $("#product_cart_amount_inp").val();
            product_amount = parseFloat2(product_amount);
            if (cart_amount != "") {
                cart_amount = parseInt(cart_amount);
                if (cart_amount){
                    amount = cart_amount*product_amount;
                    amount = amount.toFixed(4);
                    $("#product_need_amount_inp").val(amount);
                    product_price = $("#product_price_inp").val();
                    product_price = parseFloat2(product_price);
                    product_sum_price = cart_amount*product_price*product_amount;
                    product_sum_price = product_sum_price.toFixed(2);
                    $("#product_sum_price_inp").val(product_sum_price);
                } else {
                    showError("product_cart_amount_inp", "bad_format_cart", true, "1");
                }
            } else {
                showError("product_cart_amount_inp", "cart_empty", true, "1");
            }
            break;
        }
        case '6':{
            product_units = $("#product_units_inp").val();
            cart_amount = $("#product_cart_amount_inp").val();
            product_units = parseInt(product_units);
            if (cart_amount != "") {
                cart_amount = parseInt(cart_amount);
                if (cart_amount){
                    amount = cart_amount*product_units;
                    amount = amount.toFixed(0);
                    $("#product_need_amount_inp").val(amount);
                    product_price = $("#product_price_inp").val();
                    product_price = parseFloat2(product_price);
                    product_sum_price = amount*product_price;
                    product_sum_price = product_sum_price.toFixed(2);
                    $("#product_sum_price_inp").val(product_sum_price);
                } else {
                    showError("product_cart_amount_inp", "bad_format_cart", true, "1");
                }
            } else {
                showError("product_cart_amount_inp", "cart_empty", true, "1");
            }
            break;
        }
        case '7':{
            product_amount = $("#product_amount_inp").val();
            cart_amount = $("#product_cart_amount_inp").val();
            product_amount = parseFloat2(product_amount);
            if (cart_amount != "") {
                cart_amount = parseInt(cart_amount);
                if (cart_amount){
                    amount = cart_amount*product_amount;
                    amount = amount.toFixed(4);
                    $("#product_need_amount_inp").val(amount);
                    product_price = $("#product_price_inp").val();
                    product_price = parseFloat2(product_price);
                    product_sum_price = amount*product_price;
                    product_sum_price = product_sum_price.toFixed(2);
                    $("#product_sum_price_inp").val(product_sum_price);
                } else {
                    showError("product_cart_amount_inp", "bad_format_cart", true, "1");
                }
            } else {
                showError("product_cart_amount_inp", "cart_empty", true, "1");
            }
            break;
        }
    }
}

function calculatorStart(){
    var default_amount = 1;
    var product_size_type = $("#product_size_type_inp").val();
    var product_price;
    var amount;
    var product_sum_price;
    var product_amount;
    var product_units;
    switch(product_size_type){
        case '1':
        case '2':
        case '3':{
            product_price = $("#product_price_inp").val();
            product_price = parseFloat2(product_price);
            $("#product_cart_amount_inp").val(default_amount);
            amount = default_amount;
            product_sum_price = amount*product_price;
            product_sum_price = product_sum_price.toFixed(2);
            $("#product_sum_price_inp").val(product_sum_price);
            break;
        }
        case '4':{
            product_price = $("#product_price_inp").val();
            product_price = parseFloat2(product_price);
            $("#product_cart_amount_inp").val(default_amount);
            amount = default_amount;
            product_sum_price = amount*product_price;
            product_sum_price = product_sum_price.toFixed(2);
            $("#product_sum_price_inp").val(product_sum_price);
            break;
        }
        case '5':{
            product_price = $("#product_price_inp").val();
            product_price = parseFloat2(product_price);
            product_amount = $("#product_amount_inp").val();
            product_amount = parseFloat2(product_amount);
            $("#product_cart_amount_inp").val(default_amount);
            amount = default_amount;
            product_sum_price = amount*product_price*product_amount;
            product_sum_price = product_sum_price.toFixed(2);
            $("#product_sum_price_inp").val(product_sum_price);
            break;
        }
        case '6':{
            product_price = $("#product_price_inp").val();
            product_price = parseFloat2(product_price);
            product_units = $("#product_units_inp").val();
            product_units = parseFloat2(product_units);
            $("#product_cart_amount_inp").val(default_amount);
            amount = default_amount;
            product_sum_price = amount*product_price*product_units;
            product_sum_price = product_sum_price.toFixed(2);
            $("#product_sum_price_inp").val(product_sum_price);
            break;
        }
        case '7':{
            product_price = $("#product_price_inp").val();
            product_price = parseFloat2(product_price);
            product_amount = $("#product_amount_inp").val();
            product_amount = parseFloat2(product_amount);
            $("#product_cart_amount_inp").val(default_amount);
            amount = default_amount;
            product_sum_price = amount*product_price*product_amount;
            product_sum_price = product_sum_price.toFixed(2);
            $("#product_sum_price_inp").val(product_sum_price);
            break;
        }
    }
}

function addToCart(){
    var amount = $("#product_cart_amount_inp").val();
    var product_id = $("#product_id_inp").val();
    var url = $("#addtocart_btn").attr("href");
    url = url.split('?');
    var query = '';
    if (url.length >= 2) {
        query = url[1];
        url = url[0];
        var postdata = {};
        query = query.split("&");
        for(var i in query){
            var param = query[i];
            param = param.split("=");
            postdata[param[0]] = param[1];
        }
        postdata['amount'] = amount;
        postdata['product_id'] = product_id;
        postdata['ajax'] = 1;
        var poststr = jQuery.param(postdata);
        $.post( url,
            poststr,
            function(data){
                if (data != "1") {
                    alert("Prek\u0117s pridėti į krepšelį nepavyko.");
                } else {
                   $.add2cart(  "addtocart_cntn",
                        "cart_outer_cntn",
                        function(){
                            var postarray = {};
                            postarray['id'] = postdata['id'];
                            postarray['returnid'] = postdata['returnid'];
                            postarray['action'] = "cart_short";
                            poststr = jQuery.param(postarray);
                            $.post( url,
                                poststr,
                                function(data){
                                    $("#cart_outer_cntn").html(data);
                                }
                            );
                        });
                }
        });
    }
}

$(document).ready(function(){
    calculatorStart();
    calculateNeedAmount();

    $("#product_need_amount_inp").change(function(){
        var value = $(this).val();
        if (isUnsignedFloat(value)){
            hideError("product_need_amount_inp");
            hideError("product_cart_amount_inp");
            calculatePackagesAmount();
        } else if (value != "" ){
            showError("product_need_amount_inp", "bad_format", false, "");
        }
    });

    $("#skaiciuokle_count").click(function(){
        return false;
    });

    $("#product_cart_amount_inp").change(function(){
        var value = $(this).val();
        var hasError = false;
        if (isUnsignedInteger(value)){
            hideError("product_need_amount_inp");
            hideError("product_cart_amount_inp");
            calculateNeedAmount();
        } else if (value != "") {
            hasError = true;
            showError("product_cart_amount_inp", "bad_format_cart", true, "1");
        } else {
            hasError = true;
            showError("product_cart_amount_inp", "cart_empty", true, "1");
        }
        value = $(this).val();
        if (isUnsignedInteger(value) && hasError){
            calculateNeedAmount();
            enableAddToCart();
        }
    });

    $("#addtocart_btn").click(function(){
        if ($(this).hasClass("noclick")){
            showError("", "bad_data", false, "");
        } else {
            addToCart();
        }
        return false;
    });
    
});

