$(document).ready(function() {

    var ammo_select = $("select#product");
    if (ammo_select)
    {
        $("select#product").change(function() {
            //alert($(this).val());
            $.getJSON("/ammosearch_select", {id: $(this).val(), ajax: 'true'}, function(j) {
                //alert('fetched');
                var coptions = '';
                var loptions = '';
                if (j.caliber) {
                    for (var i = 0; i < j.caliber.length; i++) {
                        coptions += '<option value="' + j.caliber[i].optionValue + '">' + j.caliber[i].optionDisplay + '</option>';
                    }
                    if (coptions) {
                        $("select#caliber").attr('disabled', false);
                        $("select#caliber").html(coptions);
                    }
                }
                else {
                    $("select#caliber").attr('disabled', true);
                }
                if (j.productline || j.bullettype) {
                    if (j.productline) {
                        loptions += '<optgroup label="Product Line">';
                        for (var i = 0; i < j.productline.length; i++) {
                            loptions += '<option value="' + j.productline[i].optionValue + '">' + j.productline[i].optionDisplay + '</option>';
                        }
                        loptions += '</optgroup>';
                    }
                    if (j.bullettype) {
                        loptions += '<optgroup label="Bullet Type">';
                        for (var i = 0; i < j.bullettype.length; i++) {
                            loptions += '<option value="' + j.bullettype[i].optionValue + '">' + j.bullettype[i].optionDisplay + '</option>';
                        }
                        loptions += '</optgroup>';
                    }
                    if (loptions) {
                        loptions = "<option value=''>-- Select One --</option>" + loptions;
                        $("select#line").attr('disabled', false);
                        $("select#line").html(loptions);
                    }
                }
                else {
                    $("select#line").attr('disabled', true);
                }
            })
        })
        $("select#product").change();
    }
})

