$(document).ready(
    function() {
        $("body").ready(setCart);
        // open link in a new window
        $("a.bb").click(function() {
            $.jqURL.loc(this.href, {w:805,h:800,wintype:'_blank'});
            return false;
        });
        $("a#imglink").click(function() {
            $.jqURL.loc(this.href, {w:640,h:480,wintype:'_blank'});
            return false;
        });
        $("button#allspec").click(function() {
            $.jqURL.loc("/?act=allspec");
        });
        // action in cart
        $("table#cart input:checkbox.m").bind("click", inCartAction);
        // add to cart
        $("table#list input:checkbox.add").bind("click", addToCart);
        // ajax global events
        $("#loading").bind("ajaxSend", function() {
            $(this).show();
        }).bind("ajaxComplete", function() {
            $(this).hide();
        });
        // validate form
        $("#orderForm").validate({
            errorPlacement: function(error, element) { error.appendTo( element.parent("td").next("td") ); },
            rules: {
                lastname: { required: true },
                firstname: { required: true },
                company: { required: true },
                position: { required: true },
                phone: { required: true },
                email: { required: true, email: true }
            },
            messages: {
                lastname: { required: "Введите фамилию" },
                firstname: { required: "Введите имя" },
                company: { required: "Ввидите название компании" },
                position: { required: "Введит вашу должность" },
                phone: { required: "Введите номер телефона" },
                email: "Введите правильный адрес электронной почты"
            }
        });
        // field mask
        $("#tphone").mask("(999) 999-99-99");
        // autocomplete
        $("#namesearch").autocomplete("/search/", {
		    width: 560,
    		selectFirst: false
    	});
});
function setCart() {
    $("table#list input:checkbox.add:checked").removeAttr("checked");
    // disable button
    $("div#amenu input:submit").attr("disabled", "disabled");
    getData();
}
function getData() {
    $.ajax({
        type: "POST",
        url: "/cart/",
        data: "a=get",
        dataType: "json",
        success: setData
    });
}
function setData(cart) {
    var m = (new Date).getMonth() + 1;
    var d = (new Date).getDay() + 1;

    m = d > 20 ? m + 2 : m + 1;

    $("span#quant").html(cart.quantity);
    $("span#total").html(cart.sum);

    var idx = 0;
    while (idx < cart.ids.length) {
        $("table#list input:checkbox[value='" + cart.ids[idx] + "']").attr("checked", "true");
        // or
        $("table#list input:checkbox[value='" + cart.ids[idx] + ";" + m + "']").attr("checked", "true");
        idx++;
    }

    if (cart.ids.length > 0) {
        $("div#amenu input:submit").removeAttr("disabled");
    }
}

function addToCart() {
    var checkbox = $(this);

    if (checkbox.is(":checked")) {
        $.ajax({
            type: "POST",
            url: "/cart/",
            data: "a=add&id=" + checkbox.attr("value"),
            success: calc(checkbox, "+", true)
        });

        $("div#amenu input:submit").removeAttr("disabled");
    }
    else {
        $.ajax({
            type: "POST",
            url: "/cart/",
            data: "a=rem&id=" + checkbox.attr("value"),
            success: calc(checkbox, "-", true)
        });
    }
}

function inCartAction() {
    var checkbox = $(this);
    var id = checkbox.attr("value").split(";");

    if (checkbox.is(":checked")) {
        // first checked checkbox: add to cart
        if (checkbox.parents("tr:first").find("input:checkbox:checked.m").size() == 1) {
            $.ajax({
                type: "POST",
                url: "/cart/",
                data: "a=add&id=" + id[0],
                success: calc(checkbox, "+", true)
            });
        }
        else {
            calc(checkbox, "+", false);
        }
    }
    else {
        // last checked checkbox: remove from cart
        if (checkbox.parents("tr:first").find("input:checkbox:checked.m").size() == 0) {
            $.ajax({
                type: "POST",
                url: "/cart/",
                data: "a=rem&id=" + id[0],
                success: calc(checkbox, "-", true)
            });
        }
        else {
            calc(checkbox, "-", false);
        }
    }
}

function calc(checkbox, action, qaction) {
    var cost  = checkbox.parents("tr:first").find("td:eq(5)").text();
    var total = $("span#total").text();
    var quant = parseInt($("span#quant").text());

    cost = cost.match(/(\d{1,3}) (\d{3})/);
    cost = parseInt(cost[1] + cost[2]);

    // check for total
    if (total != "0") {
        total = total.match(/(\d{1,3}) (\d{3})/);
        total = parseInt(total[1] + total[2]);
    }
    else {
        total = 0;
    }

    // calculate total
    if (action == "+") {
        total = total + cost;

        if (qaction) {
            quant = quant + 1;
        }
    }
    else if (action == "-") {
        total = total - cost;

        if (qaction) {
            quant = quant - 1;
        }
    }

    $("span#quant").html(quant);

    if (total == 0) {
        $("span#total").html(total);
    }
    else {
        total = total.toString().match(/(\d{1,3})(\d{3})/);
        $("span#total").html(total[1] + " " + total[2]);
    }
}
