$(function() {
    
    function html_rating_stars(rating) {
        var html = "";
        var fullStars = Math.floor(rating);
        var halfStar = (rating > fullStars);
        
        for (var i=0; i < fullStars; i++) {
            html += "&#9679;";
        };
        
        if (halfStar) { html += "&#9675;"; }
        
        return html;
    }
    
    function create_row(wine) {
        var html = "";
        html += "<div class='itemEntryRow'>";
        html += "<div class='itemEntryCell ColumnName'><strong><a href='" + wine.url + "'target='_blank'>" + wine.name + "</a></strong></div>";
        html += "<div><input type='hidden' name='wines[" + wine.id + "][name]' value='"+ wine.name +"' /></div>";
        html += "<div class='itemEntryCell ColumnVintage'>" + wine.vintage + "</div>";
        html += "<div class='itemEntryCell ColumnType'>" + wine.description + "</div>";
        html += "<div class='itemEntryCell ColumnPlatter'>" + html_rating_stars(wine.platter) + "</div>";
        html += "<div class='itemEntryCell ColumnML'>" + wine.ml + "</div>";
        html += "<div class='itemEntryCell ColumnPrice'>" + wine.price +"</div>";
        html += "<div class='itemEntryCell ColumnDisplayPrice'>" + "R " + wine.price.toFixed(2) + "</div>";
        html += "<div class='itemEntryCell ColumnQuantity'><select " + (wine.available ? "" : "disabled") + " name='wines[" + wine.id + "][quantity]'></select></div>";
        html += "<div class='itemEntryCell ColumnAvailability'>" + (wine.available ? "Available" : "Not Available") + "</div>";
        html += "<div class='itemEntryCell ColumnTotal'><input name='wines[" + wine.id + "][subtotal]' class='subtotal' type='text' readonly='readonly' /></div>";
        html += "<br style='clear:both; height:1px; overflow:hidden;' />"
        return html;
    }
    
    
    function get_order_total() {
        var total = 0.0;
        $("input.subtotal").each( function(i,e) {
            total += (e.value == "") ? 0.0 : parseFloat( e.value );
        });
        return total;
    }
    
    // Update the various 'total' fields
    function update_total() {
        $("input.total").val( "R " + get_order_total().toFixed(2) );
    }
    
    function add_quantity_selectors(sizes) {
        var e = "<option selected='selected' value='0'>0</option>";
        $(sizes).each( function (i, size) {
           e += "<option value='"+size+"'>"+size+"</option>";
        });
        
        $("div.itemEntryRow div.ColumnQuantity select").append(e);
    }
    
    // add wines first
    $(WHITES).each( function(i, wine) {
        $("div.wines.whites").append( create_row(wine) );
    });
    $(ROSES).each( function(i, wine) {
        $("div.wines.roses").append( create_row(wine) );
    });
    $(REDS).each( function(i, wine) {
        $("div.wines.reds").append( create_row(wine) );
    });
    
    // inject the quantity selectors before we attach the event listeners
    add_quantity_selectors([1,2,3,4,5,6,9,12,18,24,30,36,42,48,54,60]);
    
    // Bind an update event to each select element
    $("div.itemEntryRow").each( function(i,e) {
        var price = $("div.ColumnPrice", e).text();
        
        $("select", e).change( function() {
            var bottle_count = $(this)[0].value;
            
            // Display the subtotal if there are 1 or more bottles selected
            if (bottle_count == 0) {
                $("input.subtotal", e).val("");
            } else {
                $("input.subtotal", e).val( (bottle_count * price).toFixed(2) );
            }
            
            update_total();
        });
    });
    
    // custom validator to ensure that the total order value is not 0.00
    jQuery.validator.addMethod("notZero", function(value, element) {
        return get_order_total() != 0.00;
    }, "You cannot place an order for zero value. Please choose some wines before continuing.");
    
    // add odd/even row classes
    $("div.itemEntryRow:even").addClass("even");
    $("div.itemEntryRow:odd").addClass("odd");
    
    // add click handlers for member status, to show the correct form fields
    $("a.memberYes").click( function() { 
        $("#orderDetailsFieldsHolder").html( $("#orderDetailsMember").html() );
        $("#orderDetailsHolder").removeClass("hidden");
        return false;
    });
    
    $("a.memberNo").click( function() { 
        $("#orderDetailsFieldsHolder").html( $("#orderDetailsDefault").html() );
        $("#orderDetailsHolder").removeClass("hidden");
        return false;
    });
    
    // i <3 javascript
    $("#orderForm").validate();
    
    update_total();
    
});

