/* this allows us to pass in HTML tags to autocomplete. Without this they get escaped */
$["ui"]["autocomplete"].prototype["_renderItem"] = function(ul, item) {
    return $("<li></li>")
        .data("item.autocomplete", item)
        .append($("<a></a>").html(item.label))
        .appendTo(ul);
};

$(function() {
    $("#tab-common").click(function() {
        $('#search-box').removeClass();
        $('#type').val('');
        $('#for').val('');
        return false;
    });
    $("#tab-type").click(function() {
        $('#search-box').removeClass().addClass('search-type');
        $('#type').val('type');
        $('#for').val('');
        return false;
    });
    $("#tab-device").click(function() {
        $('#search-box').removeClass().addClass('search-device');
        $('#type').val('device');
        $('#for').val('');
        return false;
    });
    $("#tab-model").click(function() {
        $('#search-box').removeClass().addClass('search-model');
        $('#type').val('model');
        $('#for').val('');
        return false;
    });
/*
    $(".buy a").click(function() {
        var id = $(this).parents(".item").attr("id").replace("item_", "");
//        addToCart(id, prompt('Количество позиций?', 1));

//        $(".buy .qty").hide();
//        $(".buy a").show();

//        $(this).hide();
//        $("#qty_" + id).show();
        $("#qty_" + id).select().focus();
        return false;
    });
*/
/*
    $(".buy input.qty").change(function() {
        var id = $(this).attr("id").replace("qty_", "");
        addToCart(id, $(this).val(), true);
    });
*/
    $(".buy input.qty").focus(function() {
        $(this).data("__init_val", $(this).val());
    });

    $(".buy input.qty").blur(function() {
        if ($(this).val() == 0) $(this).val("");
        if ($(this).data("__init_val") != $(this).val()) {
//            $(this).change();
            var id = $(this).attr("id").replace("qty_", "");
            addToCart(id, $(this).val(), true);
        }
    });


    function keyboardHandler(e) {
        var t  = $(e.currentTarget);
        var li = t.parent("td").parent("tr");
        switch (e.which) {
            case 13: // enter
                t.get(0).blur();
                $("#for").focus().select();
                e.preventDefault(); // prevent for submitting
                break;
            case 40: // down
                t.get(0).blur();
                if (li.next().find(".buy input.qty").length) {
                    li.next().find(".buy input.qty").get(0).focus();
                    li.next().find(".buy input.qty").get(0).select();
                } else {
                    t.get(0).focus();
                    t.get(0).select();
                }
                break;
            case 27: // esc
                t.val(t.data("__init_val"));
                //"t.select();
                $("#for").focus();
                break;
            case 38: // up
                t.get(0).blur();
                if (li.prev().find(".buy input.qty").length) {
                    li.prev().find(".buy input.qty").get(0).focus();
                    li.prev().find(".buy input.qty").get(0).select();
                } else {
                    t.get(0).focus();
                    t.get(0).select();
                }
                break;
            case 8:   // backspace
            case 9:   // tab
            case 16:  // shift
            case 17:  // control
            case 33:  // page up
            case 34:  // page down
            case 35:  // end
            case 36:  // home
            case 37:  // left
            case 39:  // right
            case 46:  // del
                break;
            default:
//                $("#item").append(e.which);
                if (!(e.which >= 48 && e.which <= 57) && !(e.which >= 96 && e.which <= 105)) {
                    e.preventDefault();
                }
        }
    }

    // we must bind keypress for Opera
    $(".buy input.qty").bind("keydown keypress", keyboardHandler);

//    $("#for").focus(function() { $(this).select(); });
    // webkit specific
//    $("#for").mouseup(function(e) { e.preventDefault(); });

    $("#for").focus();
    // hack for Google Chrome and Opera
    var forValue = $("#for").val();
    $("#for").val('').val(forValue);

/*
    $("#for").autocomplete({
        source: "/autocomplete/index/",
        minLength: 2,
        select: function() {
            $("#search-box").submit();
        }
    });
*/
    function split(val) {
        return val.split(/,\s*/);
    }
    function extractLast(term) {
        return split(term).pop();
    }
/*
    $("#for").autocomplete({
        source: function(request, response) {
            $.getJSON("/autocomplete/index/", {
//                term: extractLast(request.term)
                term: request.term
            }, response);
        },
        search: function(event, ui) {
            // custom minLength
//            var term = extractLast(this.value);
//            if (term.length < 2) return false;
        },
        focus: function(event, ui) {
            this.value = ui.item.value;
            return false;
        },
        select: function(event, ui) {
//            var terms = split(this.value);
//            terms.pop();
//            terms.push(ui.item.value);
//            terms.push("");
//            this.value = terms.join(", ");
            this.value = ui.item.value + ", ";
            return false;
        }
    });
*/

    $(".catalog6 > ul > li > a").click(function() {
        var myLink = $(this);
        var myList = myLink.next("ul");
        $(".catalog6 > ul > li > ul").not(myList).hide();
        $(".catalog6 > ul > li > a").not(myLink).removeClass("opened");
        if (myLink.hasClass("opened")) {
            myList.fadeOut("normal");
            myLink.removeClass("opened");
        } else {
            myList.fadeIn("normal");
            myLink.addClass("opened");
        }
        return false;
    });

    $("#results .name a").click(showItem);

    $("#btn-cart").click(function() {
        $(this).toggleClass("active");
        $("#cart").toggle("normal");
        if ($(this).hasClass("active")) {
            $.cookie('showCart', 'show', {path: '/'});
        } else {
            $.cookie('showCart', null, {path: '/'});
        }
//        return false;
    });

    cartButtons();
/*
    if ($.cookie('showCart') == 'show') {
        $("#btn-cart").addClass("active");
        $("#cart").show();
    }
*/
    $("#hint a").click(function() {
        $("#for").focus().val($(this).html());
        return false;
    });
});


function addToCart(itemId, qty, set)
{
    qty = (qty) ? Math.abs(parseInt(qty, 10)) : 0;
//    openCart();
    $("#cart").load("/cart/add/" + itemId, { "qty": qty, "set": set ? 1 : 0 }, function() {
        var cnt = $("#cart .count").attr("id").replace("count_", "");
        $("#btn-cart strong").html(cnt == 0 ? "" : "(" + cnt + ")");
        $("#item_" + itemId).fadeOut().fadeIn();
        $("#cart_" + itemId).fadeOut().fadeIn();
        $("#btn-cart").fadeOut().fadeIn();
    });
}

function cartButtons()
{
    $("#cart .del .delete").live("click", function() {
        var id = $(this).parent("li").parent("ul").attr("id").replace("cart_", "");
        $("#cart").load($(this).attr("href"), {}, function() {
            var cnt = $("#cart .count").attr("id").replace("count_", "");
            $("#btn-cart strong").html(cnt == 0 ? "" : "(" + cnt + ")");
            $("#qty_" + id).val("");
        });
        return false;
    });

    $("#clear").live("click", function() {
        $("#cart").load($(this).attr("href"), {}, function() {
            $("#btn-cart strong").html("");
            $(".buy input.qty").val("");
        });
        return false;
    });

    $("#cart .name a").live("click", showItem);

    $("#coupon").live("click", function() {
        setCoupon();
    });
}

function openCart()
{
    $("#btn-cart").addClass("active");
    $("#cart").show("normal");
    $.cookie('showCart', 'show', {path: '/'});
    return false;
}

function showItem(e)
{
    var li = $(e.currentTarget).parent("span").parent("td").parent("tr");
    if (li.hasClass("active")) {
        li.removeClass("active");
    } else {
        if (!li.find(".product-item").html()) {
            li.find(".product-item").html('<img src="/images/loader.gif" alt="loading" />');
            li.find(".product-item").load($(e.currentTarget).attr("href"),  {"ajax": 1});
        }
        $(".items tr.active").removeClass("active");
        li.addClass("active");
    }
    return false;
}

function changeClient(sel)
{
    var val  = sel.options[sel.selectedIndex].value;
    document.location = '/cart/order/0/client/' + val;
}

function setCoupon()
{
    var coupon = prompt('Введите номер купона:');
    if (!coupon) return;
    $("#cart").load("/cart/coupon/" + coupon, {}, function() {
        $("#btn-cart").fadeOut().fadeIn();
    });
}

function changeCurrency(list)
{
    var currency = list.options[list.selectedIndex].value;
    $.cookie('currency', currency, { path: '/', expires: 365 });

    document.location.reload();
}

