$(document).ready(page_setup);

// Set up the jquery bindings to elements of the page
function page_setup() {
    // Register the showing/hiding of divs
    $("a[class='location_contact_link']").click(toggleContact);
    $("a[class='location_association_link']").click(toggleAssociations);
    $("a[class='contact_name_link']").click(toggleContactBio);
    $("div[id^='associations_']").jqm();
    $("div#modal_dia").jqm();

    // Cycle the images
    $('div.location_image').cycle({
      fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
    });
    
    // unblock when ajax activity stops 
    $().ajaxStop($.unblockUI); 
}

// Show or hide contact divs
function toggleContact(e) {
    // Stop the normal link click
    e.preventDefault();
    
    locationId = $(this).parents("[class='location']").attr("id");
    contactDiv = '#contacts_' + locationId;
    associationDiv = '#associations_' + locationId;
    
    $(associationDiv).slideUp("slow");    
    $(contactDiv).slideToggle("slow");
}

// Show or hide the association divs
function toggleAssociations(e) {
    // Stop the normal link click
    e.preventDefault();
    locationId = $(this).parents("[class='location']").attr("id");
    associationDiv = '#associations_' + locationId;
    $(associationDiv).jqmShow();
}

// Show or hide the contact modal
function toggleContactBio(e) {
    e.preventDefault();
    
    $.blockUI({ message: '<p><img src="/images/busy.gif" /> Just a moment...</p>' })
    
    // Empty the main modal
    $("div[class='modal_main']").empty();
    var contact_id = $(this).parents("[class='contact']").attr("id").substring(8);
    
    // Post to the fetch products form
    $.post('/location/fetchContactBio', { contact_id: contact_id },
            function  (data) {
                // Replace the products
                $("div[class='modal_main']").append(data);
                // Add the handler to hide the bio
                $("div.contact_modal_back a").click(hideBio);
                $("div#modal_dia").jqmShow();
            });
}

function hideBio(e) {
  $("div#modal_dia").jqmHide();
}