$(document).ready(page_setup);

// Set up the jquery bindings to elements of the page
function page_setup() {
    // Register the showing/hiding of divs
    $("div[class='product_name'] > a").click(toggleDistribution);
    $("a[class='product_salessheets_link']").click(toggleSalesSheets);   
    $("a[class='product_information_link']").click(toggleProductInformation);   
    $("input[class='product_filter']").keyup(filterProducts);
    // unblock when ajax activity stops 
    $().ajaxStop($.unblockUI); 
}

// Show or hide sales sheet information
function toggleSalesSheets(e) {
    e.preventDefault();
    var principal_id = $(this).parents("[class$='principal']").attr('id');
    
    $("div#" + principal_id).children("[class='principal_products']").slideUp();
    $("div#" + principal_id).children("[class='principal_salessheets']").slideToggle();    
}

// Show or hide product information
function toggleProductInformation(e) {
    e.preventDefault();
    var principal_id = $(this).parents("[class$='principal']").attr('id');
    
    $("div#" + principal_id).children("[class='principal_salessheets']").slideUp();
    $("div#" + principal_id).children("[class='principal_products']").slideToggle();    
}

// Show or hide distribution divs
function toggleDistribution(e) {
    // Stop the normal link click
    e.preventDefault();
    productID = $(this).attr("id").substr(8);
    distributorDiv = '#distributors' + productID;
    
    // Check if the div is being displayed
    if($(distributorDiv).css('display') == 'none') {
        $(distributorDiv).slideDown("slow");
    }
    // Slide up in this case
    else {
        $(distributorDiv).slideUp("slow"); 
    }
}

// Filter the product information
function filterProducts(e) {
    var name = $(this).attr('id');
    var principal_id = $(this).parents("[class$='principal']").attr('id');
    
    $("div#product_data_" + principal_id).block( { message: '<p><img src="/images/busy.gif" /> Just a moment...</p>' } );
    
    // Post to the fetch products form
    $.post('/principal/fetchProducts', { principal_id: principal_id, product_name: '%' + $(this).attr('value') + '%' },
            function  (data) {
                // Replace the products
                $("div#product_data_" + principal_id).replaceWith(data);
                // Rebind the distributors sliders
                $("div[class='product_name'] > a").click(toggleDistribution);
            });
 }
