﻿/////////////////////////////////////////////////////////////////////////////////
// The code in this file *IS* available immediately and is not dependent on 
//  the DOM being ready
/////////////////////////////////////////////////////////////////////////////////

// console.log() Shortcut
function c(message){try{console.log(message);}catch(e){alert(message);}}

var UserProfile;

// Cookie names
var EMAIL_COOKIE = "eEmail";
var PASSWORD_COOKIE = "ePassword";

// Used to determine success/failure from AJAX calls
var AJAX_SUCCESS = "SUCCESS";

// Used to determine whether we're modifying an existing bundle or creating a new one
var CREATE_NEW_BUNDLE = "CREATE_NEW";

// Used to allow events to determine which popup the event originated from
var TYPE_CUSTOM_BUNDLE = "CUSTOM_BUNDLE";
var TYPE_BUNDLE = "BUNDLE";
var TYPE_PDF = "PDF";

// Text for login/logout link in header
var LOGIN_LINK_TEXT = "Login";
var LOGOUT_LINK_TEXT = "Log out";

// Path to preview images
var IMAGE_PREVIEW_PATH = "/professional/in_office/images/previews/";


/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// General functions
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Gets the Action Tag and loads it into img#action_tag
function getActionTag(actionTag) {
    var randomNumber=Math.floor(Math.random()*10000001);
    document.action_tag.src = "http://switch.atdmt.com/action/" + actionTag + "/" + randomNumber;
}

/////////////////////////////////////////////////////////////////////////////////
// Gets the Dart Tag and loads it into iframe#dart_tag
// This is for an action like logging in/out (as opposed to a PDF/BUNDLE download)
function getDartTagForAction(dartId) {
    var randomNumber=Math.floor(Math.random()*10000001);
    document.dart_tag.src = "http://fls.doubleclick.net/activityi;src=2143263;type=asthm361;cat=prhcp" + dartId + ";ord=1;num=" + randomNumber + "?";
}

/////////////////////////////////////////////////////////////////////////////////
// Gets the Dart Tag and loads it into iframe#dart_tag
// This is for a PDF or a Bundle (as opposed to an action like logging in or out)
function getDartTagForPdfOrBundle(dartId) {
    var randomNumber=Math.floor(Math.random()*10000001);
    document.dart_tag.src = "http://fls.doubleclick.net/activityi;src=2143263;type=akcpr672;cat=prhcp" + dartId + ";ord=1;num=" + randomNumber + "?";
}

/////////////////////////////////////////////////////////////////////////////////
// Adds function to string object to trim() string and replace duplicate spaces
// with a single space
function trimAndRemoveDuplicateSpaces(string) {
    return $.trim(string.replace(/\s+/g," "));
}

/////////////////////////////////////////////////////////////////////////////////
// Shortcut - return a PDF object by pdfID
function getPdfByID(pdfID)
{
    return pdfData.getItemByID(pdfID);
}

/////////////////////////////////////////////////////////////////////////////////
// Update practice name if available - otherwise clear it
function updatePracticeName(){
    var practiceName = "";
    if (isLoggedIn()) {
        practiceName = UserProfile.firstName + " " + UserProfile.lastName ;
    }
    $("span#practiceName").text(practiceName);
}





/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Bundle functions
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Reads the contents from the div#popupBundleSave and puts them into a 
// JSON object which is sent back to the server 
// RETURNS: error from server, if any
function updateCustomBundle(li, bundleID, userID, name, description, pdfIDs){

    var updatedBundle = 
        {
            "bundleID" : bundleID, 
            "userID" : userID, 
            "name" : name, 
            "description" : description,
            "pdfIDs" : pdfIDs
        };

    // If bundle is not changing, don't do anything
    var originalBundle = Bundles.getBundleByID(bundleID);
    if (Bundles.areIdentical(originalBundle, updatedBundle)){
        return;
    }

    // Send request
    var bm = new BundleManager();
    var result = bm.update(updatedBundle);
    if (ajaxSuccess(result)) {
        closePopups();
        
        // Extrace rows affected from result
        var returnValue = extractAjaxResult(result);
        if (returnValue == 1) {
        
            // Update item in global bundle object
            var bundle = Bundles.getBundleByID(bundleID);
            bundle.name = name;
            bundle.description = description;
            bundle.pdfIDs = pdfIDs;
            
            // Update displayed bundle details
            updateCustomBundleDetails(li, name, description);
            
            // Update buttonstates
            setAddButtonState();
        }
        
    } else {
        return result;
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Reads the contents from the div#popupBundleSave and puts them into a 
// JSON object which is sent back to the server 
// RETURNS: error from server, if any
function saveCustomBundle(userID, name, description, pdfIDs){

    var newBundle = 
        {
            "userID" : userID, 
            "name" : name, 
            "description" : description,
            "pdfIDs" : pdfIDs
        };
    
    // Send request
    var bm = new BundleManager();
    var result = bm.save(newBundle);
    if (ajaxSuccess(result)) {
        closePopups();
        
        // Add bundleID
        newBundle.bundleID = extractAjaxResult(result);

        // Add new bundle to Bundle object
        Bundles.add(newBundle);
        
        // Add bundle to product list
        cloneCustomBundleTemplate(newBundle.bundleID, newBundle.name, newBundle.description);

        // Set cart button states
        setAddButtonState();
        
        // Make custom bundle edit and delete links active
        wireCustomBundleLinks();
        
    } else {
        return result;
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Get user's custom bundles and add them to bundle object
function getCustomBundles(userID){
    var bm = new BundleManager();
    var result = bm.getBundles({"id":userID});
    if (ajaxSuccess(result)) {
    
        // Extract result from return value
        result = extractAjaxResult(result);

        // eval() will create a local variable "ajaxResult" with a JSON object 
        // containing this user's custom bundles
        try {
            eval(result);
        } catch (e) {
            alert("Failed to load custom bundles: " + e);
        }

        // Make sure everything went ok
        if (ajaxResult) {
            
            // Loop through items in the bundle JSON object and add them to the product list
            for(var i=0; i<ajaxResult.items.length; i++){
                
                // Get current bundle 
                var bundle = ajaxResult.items[i];
                
                // Check to see if this bundleID already exists
                // If so, remove the old one before adding this one
                if (Bundles.getBundleByID(bundle.bundleID)) {
                    // Remove from Bundles object
                    Bundles.remove(bundle.bundleID);
                    
                    // Remove the listitem from the product list
                    var li = $("div#productsList").find("input[value=" + bundle.bundleID + "]").parent("li");
                    li.remove();
                }
                
                // Add it to the beginning of items() array
                Bundles.addToBeginning(bundle);
                
                // Add bundle to product list
                cloneCustomBundleTemplate(bundle.bundleID, bundle.name, bundle.description);
            }
            
            // Set cart button states
            setAddButtonState();
            
            // Make custom bundle edit and delete links active
            wireCustomBundleLinks();
        }
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Make custom bundle edit and delete links active
function wireCustomBundleLinks(){
    
    $("a.bundleEdit").unbind("click").bind("click", function(){
        // Find the bundleID
        var bundleID = $(this).parents("li").find("input.hidID").val();
        showModifyBundlePopup(bundleID);
        return false;
    });

    $("a.bundleDelete").unbind("click").bind("click", function(){
        // Find the bundleID
        var bundleID = $(this).parents("li").find("input.hidID").val();
        showDeleteCustomBundlePopup(bundleID);
        return false;
    });
}

/////////////////////////////////////////////////////////////////////////////////
// Shows the modify bundle popup for the custom bundle passed in
function showModifyBundlePopup(bundleID){

    var popup = $("div#popupBundleModify");
    
    var form = setupValidationForm({
        form: "form#formBundleModify",
        errorClass: "error",
        errorContainer: "div#bundleModifyErrorHeader, div#bundleModifyServerErrors",
        serverErrorContainer: "div#bundleModifyServerErrors",
        rules: {
            modifyBundleName: "required",
            modifyBundleDesc: { maxlength: 128 },
            modifyBundleItems: { listNotEmpty: popup.find("ul.items") }
        },
        messages: {
            modifyBundleName: "Please enter a bundle name.",
            modifyBundleDesc: { maxlength: "Please limit your description to 128 characters." },
            modifyBundleItems: "There are no PDFs below."
        }
    });

    // Show modify bundle popup
    popup

        // Cancel button
        .find("input#popupBtnBundleModifyCancel").unbind("click").click(function(){
            closePopups();
            return false;
        }).end()

        // Save button
        .find("input#popupBtnBundleModify").unbind("click").click(function(){
            if (form.valid()) {
                var popup = $("div#popupBundleModify");
                var bundleID = popup.find("option:selected").val();
                var selectedBundleName = popup.find("option:selected").text();
                var name = popup.find("input#modifyBundleName").val();
                
                // Get rid of extraneous spaces so "Bundle Name" != " Bundle     Name  "
                name = trimAndRemoveDuplicateSpaces(name);
                
                var description = popup.find("textarea#modifyBundleDesc").val();
                var pdfIDs = "";
                    popup.find("ul.items")
                        .find("li:visible")
                        .find("input.hidID")
                        .each(function(i){
                            pdfIDs = pdfIDs + ((i>0) ? "," : "") + $(this).val();
                        });
                var errorMessage;

                // Make sure we're not overwriting another bundle (but allow updating selected bundle)
                var bundle = Bundles.getBundleByName(name);
                if (bundle && 
                    (selectedBundleName != name)) {
                    // Found a duplicate bundle name - confirm before replacing
                    showDuplicateBundlePopup(bundle.bundleID, UserProfile.userID, name, description, pdfIDs);
                } else { 
                    // Didn't find a duplicate name - go ahead and save the bundle
                    if (bundleID == CREATE_NEW_BUNDLE) {
                        errorMessage = saveCustomBundle(UserProfile.userID, name, description, pdfIDs);
                    } else {
                        // Get listitem containing bundle
                        var li = $("div#productsList").find("input[value=" + bundleID + "]").parent("li");
                        // Perform update
                        errorMessage = updateCustomBundle(li, bundleID, UserProfile.userID, name, description, pdfIDs);
                    }

                    if (errorMessage) {
                        // If there was an error, display it
                        popup
                            .find("div#bundleModifyServerErrors").show()
                            .find("p.serverMessage")
                            .html(errorMessage)
                            .show();
                    } else {
                        // No error - just close popup
                        closePopups();
                    }
                }
            }
            return false;
        }).end()
        
        // Remove any items in dropdown after the first two
        .find("option:gt(1)").remove().end();

    // Manually submit when user presses enter in <INPUT />
    registerInputClick(popup, popup.find("input#popupBtnBundleModify"));
    
    showPopup(popup, true, populateModifyBundlePopup, bundleID);
}

/////////////////////////////////////////////////////////////////////////////////
// Populates the modify bundle popup
function populateModifyBundlePopup(popup, bundleID){

    // Add bundle names to dropdown
    var bundleIDs = Bundles.getBundleIDs();
    for (var i=0; i<bundleIDs.length; i++){
        
        var bundle = Bundles.getBundleByID(bundleIDs[i]);
        
        if(bundle.userID == UserProfile.userID){
            popup.find("option:last-child")
                .after("<option value=\"" + bundle.bundleID + "\">" + bundle.name + "</option>");
        }
    }
    
    // Wire up a change event for the selectbox
    popup.find("select").unbind("change").change(function(){
       
        // Get pdfs for chosen bundle
        var bundleID = $(this).val();
        switch (bundleID){
            case "":
                // "Select Bundle" - ignore
                break;
            case CREATE_NEW_BUNDLE:
                // New bundle
                // Clear out name, description
                popup.find("input#modifyBundleName").val("");
                popup.find("textarea#modifyBundleDesc").val("");
                break;
            default:
                // Get bundle info
                var bundle = Bundles.getBundleByID(bundleID);
                var pdfIDs = bundle.pdfIDs.split(",");
                
                // Populate fields
                popup.find("input#modifyBundleName").val(bundle.name);
                popup.find("textarea#modifyBundleDesc").val(bundle.description);
                
                // Populate the popup list with pdfIDs
                var template = $("li#popupBundleModifyTemplate");
                populatePopupList(pdfIDs, template);
                break;
        }
        return false;
    });
    
    // Select bundle that was passed in
    popup.find("option[value=" + bundleID + "]").attr("selected", "selected").end();
    
    // Manually fire the "change" event to populate the form
    popup.find("select").trigger("change");
}

/////////////////////////////////////////////////////////////////////////////////
// Displays a confirmation dialog and deletes the custom bundle passed in
function showDeleteCustomBundlePopup(bundleID){

    // Get listitem containing bundle
    var li = $("div#productsList").find("input[value=" + bundleID + "]").parent("li");
	
    var popup = $("div#popupBundleDelete")

        // Wire up edit button
        .find("input#popupBtnDeleteEdit").unbind("click").click(function(){
            showModifyBundlePopup(bundleID);
            return false;
        }).end()
		
	    // Wire up delete button
        .find("input#popupBtnDeleteBundle").unbind("click").click(function(){
            var bm = new BundleManager();
            var result = bm.deleteBundle({"bundleID" : bundleID, "userID" : UserProfile.userID});
            if (ajaxSuccess(result)) {
                // Remove the listitem from the product list
                li.remove();

                // Remove from Bundles object
                Bundles.remove(bundleID);
            } else {
                // There was a problem deleting the bundle
                alert("Your request could not be completed:\n\n" + result);
            }

	        closePopups();
            return false;
        }).end()
	
        // Wire up cancel button
        .find("input#popupBtnDeleteCancel").unbind("click").click(function(){
	        closePopups();
            return false;
        }).end();
        
    displayPopupAsModal(popup);
}

/////////////////////////////////////////////////////////////////////////////////
// Removes the users custom bundles from both the display and the items() array.
// Called when the user logs out.
function removeCustomBundles(){
    		                
    // Remove all visible LIs with the TYPE_CUSTOM_BUNDLE type (this user's custom bundles)
    $("div#productsList").find("li:visible input.hidType[value=" + TYPE_CUSTOM_BUNDLE + "]").parent("li").remove();
    
    // Remove this user's custom bundles
    Bundles.removeByUserID(UserProfile.userID);
}











/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// General Popup functions
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Close all popups
function closePopups(){
    // Hide popups
    $.modal.close();
}

/////////////////////////////////////////////////////////////////////////////////
// Takes the pdfIDs passed in and populates them into copies of the template
// and appends the new copy to the list containing the template
function populatePopupList(pdfIDs, template) {

    // Clear visible items out of UL (leaving template)
    template.parent("ul").children().remove(":visible");
    
    // Add each item in the chosen bundle to the list
    for (var i=0;i<pdfIDs.length;i++){
    
        // Get current PDF
        var pdf = getPdfByID(pdfIDs[i]);
        
        // Make copy of template for the new cart item
        template.clone().removeAttr("id")
        
            // Update hidID
            .find("input.hidID").val(pdf.pdfID).end()

            // Update thumbnail (won't always be found)
            .find("img.thumbnail").attr("src", pdf.thumbnailUrl).end()

            // Add itemName
            .find("a.itemName").text(pdf.name).end()
            
            // Add pdfSize
            .find("span.pdfSize").text(pdf.pdfSize).end()

            // Register an onclick event to the remove button
            .find("img.popupRemove").click(function() {
                $(this).parents("li").remove();
                return false;
            }).end()

            // Point the download link to the PDF
            .find("a.itemName").attr("href", pdf.url).attr("target", "_blank").end()
            
            // Action tag
            .find("a.itemName").click(function(){
                // Get pdfID
                var id = $(this).parents("li").find("input.hidID").val();

                // If there's an action tag, get it
                var actionTag = getPdfByID(id).actionTagDownload;
                if (actionTag){ getActionTag(actionTag); }
                
                // If there's a dart id, get it
                var dartId = getPdfByID(id).dartIdDownload;
                if (dartId){ getDartTagForPdfOrBundle(dartId); }
                
            }).end()
            
            // Copy new item into list
            .appendTo(template.parent()).show();
    }
}












/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Cart functions
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Adds an item to the outbox
function addItemToCart(id, type){

    var pdfIDs = new Array();
    
    switch (type){
        case TYPE_PDF:
            // PDF - just set pdfIDs[0] to the id
            pdfIDs[0] = id;

            // If the PDF isn't already in the cart, try getting action and dart tags
            if (!Cart.exists(id)) {
            
                var actionTag = getPdfByID(id).actionTagOutbox;
                if (actionTag){ getActionTag(actionTag); }
            
                var dartId = getPdfByID(id).dartIdOutbox;
                if (dartId){ getDartTagForPdfOrBundle(dartId); }
            }
            break;
        
        case TYPE_BUNDLE:
        case TYPE_CUSTOM_BUNDLE:
            // Bundle - set pdfIDs to an array of all the pdfIDs
            var bundle = Bundles.getBundleByID(id);
            pdfIDs = bundle.pdfIDs.split(",");
            
            // If there's an action tag, get it
            var actionTag = Bundles.getBundleByID(id).actionTagOutbox;
            if (actionTag){ getActionTag(actionTag); }
            
            // If there's dart id, get it
            var dartId = Bundles.getBundleByID(id).dartIdOutbox;
            if (dartId){ getDartTagForPdfOrBundle(dartId); }
            
            break;
    }
    
    // Add PDF(s) to cart
    for(var i=0;i<pdfIDs.length;i++){
        Cart.add(pdfIDs[i]);
    }

    // Set cart button states
    setAddButtonState();

    // Auto-scroll to the bottom of the list
    var cartItems = document.getElementById("cartItems");
    cartItems.scrollTop = cartItems.scrollHeight;
}

/////////////////////////////////////////////////////////////////////////////////
// Adds a PDF to the cart
function addPdfToCart(pdfID) {

    // Get pdf data
    var pdf = getPdfByID(pdfID);
    
    // Make copy of template for the new cart item
    var template = $("div#cartItems li#itemTemplate");
    
    // Don't allow duplicates to be added to cart
    var cartItems = $("div#cartItems li:visible").find("input.hidID[value=" + pdfID +"]");
    if(cartItems.length > 0) { return; }

    template.clone().removeAttr("id")
    
        // Update hidID
        .find("input.hidID").val(pdfID).end()

        // Update image, alt tags
        .find("img.cartImage")
            .attr("src", pdf.thumbnailUrl)
            .attr("alt", pdf.name)
            .attr("title", pdf.name).end()

        // Add itemName
        .find("p.itemName").text(pdf.name).end()
        
        // Add pdfSize
        .find("p.pdfSize > span").text(pdf.pdfSize).end()

        // Point the download link to the PDF
        .find("a.cartDownload").attr("href", pdf.url).attr("target", "_blank").end()

        // Action tag
        .find("a.cartDownload").click(function(){
            // Get pdfID
            var id = $(this).parents("li").find("input.hidID").val();

            // If there's an action tag, get it
            var actionTag = getPdfByID(id).actionTagDownload;
            if (actionTag){ getActionTag(actionTag); }
            
            // If there's a dart id, get it
            var dartId = getPdfByID(id).dartIdDownload;
            if (dartId){ getDartTagForPdfOrBundle(dartId); }
            
        }).end()
        
        // Register an onclick event to the remove button
        .find("a.cartRemove").click(function() {
            // Get LI and item id            
            var li = $(this).parents("li");
            var id = li.find("input.hidID").val();
            li.remove();

            // Remove item from Cart object
            Cart.remove(id);

            setAddButtonState();
            return false;
        }).end()

        // Copy new item into cart and display     
        .appendTo(template.parent()).show();
}

/////////////////////////////////////////////////////////////////////////////////
// Sets the state of the add buttons in the productList.
// For pdfs it will show the check mark if the pdf exists in the cart, or the 
// add button if it doesnt.  For bundles it will show the check mark if all the
// pdfs that comprise the bundle are in the cart.  Otherwise it will show the 
// add button.
function setAddButtonState(){

    // PDFs
    // For each visible listitem in the product list with a hidType = PDF,
    // see if it's in the cart and show the appropriate image
    $("div#productsList li:visible input.hidType[value=" + TYPE_PDF + "]").parent("li")
        .each(function(){
            var li = $(this);
            var id = li.find("input.hidID").val();
            
            // Show/hide appropriate images
            if (Cart.exists(id)){
                li.find("img.cartCheck").show().end()
                    .find("img.cartButton").hide();          
            } else {
                li.find("img.cartCheck").hide().end()
                    .find("img.cartButton").show();
            }
        });
    
    // Non-PDFs
    // For each visible listitem in the product list with a hidType != PDF (i,e, bundle),
    // see if ALL of its PDFs are in the cart and show the appropriate image
    $("div#productsList li:visible input.hidType[value!=" + TYPE_PDF + "]").parent("li")
        .each(function(){
            var li = $(this);
            var id = li.find("input.hidID").val();
            var pdfIDs = Bundles.getBundleByID(id).pdfIDs.split(",");

            // See if ALL of the PDFs in this bundle are in the cart
            var containsAllPdfs = true;
            for(i in pdfIDs){
                var pdfID = pdfIDs[i];
                if (!Cart.exists(pdfID)) {
                    containsAllPdfs = false;
                    break;
                }
            }
            
            // Show/hide appropriate images
            if(containsAllPdfs){
                li.find("img.cartCheck").show().end()
                    .find("img.cartButton").hide();          
            } else {
                li.find("img.cartCheck").hide().end()
                    .find("img.cartButton").show();
            }
        });        
}











/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Product list
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Wire up links in product list items
function wireProductListLinks(){
    // Get listitems
    var products = $("div#productsList ul li:visible");
    
    // Loop through products and wire up links
    products.each( function(i, n){
        // Get listitem
        li = $(n);
        
        // Wire up clickable items
        wireProductTemplateLinks(li);
    });
}

/////////////////////////////////////////////////////////////////////////////////
// Add item to the beginning of the product list
function cloneCustomBundleTemplate(id, name, description) {

    var template = $("li#productCustomTemplate");
    
    // Make copy of template for the new cart item
    var clone = template.clone().removeAttr("id")

        // Update hidID
        .find("input.hidID").val(id).end()

        // Copy new item into cart and display     
        .prependTo($("div#productsList ul"));
        
        // Wire up clickable items
        wireProductTemplateLinks(clone);
        
    // Add details to new template clone 
    updateCustomBundleDetails(clone, name, description);
    
    clone.show();
}

/////////////////////////////////////////////////////////////////////////////////
// Wires the links for a new product template
// li - product listitem (as jQuery object)
function wireProductTemplateLinks(li){

    // Get id and type
    var id = li.find("input.hidID").val();
    var type = li.find("input.hidType").val();
    
    li 
        // Show preview when clicking on the image
        .find("div.itemImage img").unbind("click").click(function(){
            showPreviewPopup(id, type);
            return false;
        }).end()

        // Show preview when clicking on the link
        .find("a.itemNameLink").unbind("click").click(function(){
            showPreviewPopup(id, type);
            return false;
        }).end()

        // Add to cart
        .find("img.cartButton").unbind("click").click(function(){
            // Extract item id and type
            var li = $(this).parents("li");
            var id = li.find("input.hidID").val();
            var type = li.find("input.hidType").val();
            
            // Add to cart
            addItemToCart(id, type);
            return false;
        }).end();
}

/////////////////////////////////////////////////////////////////////////////////
// Passed a listitem custom bundle template, this function will update all the 
// displayed information
function updateCustomBundleDetails(li, name, description){
    li
        // Set image attributes
        .find("div.itemImage img")
            .attr("alt", name)
            .attr("title", name).end()

        // Populate itemName link
        .find("a.itemNameLink").text(name).end()

        // Populate itemDescription
        .find("p.itemDescription").text(description).end();
}











/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// AJAX utilities
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Returns boolean indicating whether 'result' is the AJAX success string
function ajaxSuccess(result){
    try {
        if (result.substring(0, AJAX_SUCCESS.length) == AJAX_SUCCESS){
            return true;
        } else {
            return false;
        }
    } catch (e) {
        return false;
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Extracts the value returned from our custom AJAX calls
function extractAjaxResult(result){
    return result.substring(AJAX_SUCCESS.length);
}











/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Profile Popups
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Shows profile popup
function showProfilePopup(skipActionTag){
    if (!skipActionTag) {
        getActionTag("DIHAZ_PUL81007_Pro_Profile_lnk");
        getDartTagForAction("978");
    }
    
    var popup = $("div#popupProfile");
    showPopup(popup, true, populateProfilePopup);
}

/////////////////////////////////////////////////////////////////////////////////
// Populates the profile popup
function populateProfilePopup(popup){
    popup
        // Populate from UserProfile
        .find("span.profileFirstName").text(UserProfile.firstName).end()
        .find("span.profileLastName").text(UserProfile.lastName).end()
        .find("span.profileEmail").text(UserProfile.email).end()
        .find("span.profilePracticeName").text(UserProfile.practiceName).end()
        .find("span.profileAddress1").text(UserProfile.address1).end()
        .find("span.profileAddress2").text(UserProfile.address2).end()
        .find("span.profileCity").text(UserProfile.city).end()
        .find("span.profileState").text(UserProfile.state).end()
        .find("span.profileZip").text(UserProfile.zip).end()
        
        // set click handler for profile edit
        .find("a#popupLnkShowProfileEdit").unbind("click").click(function(){
            showProfileEditPopup();
            return false;
        });
}

/////////////////////////////////////////////////////////////////////////////////
// Shows profile edit popup
function showProfileEditPopup(){
    var popup = $("div#popupProfileEdit");
    showPopup(popup, true, populateProfileEditPopup);
}

/////////////////////////////////////////////////////////////////////////////////
// Populates the profile popup
function populateProfileEditPopup(popup){

    var form = setupValidationForm({
        form: "form#formProfileEdit",
        errorClass: "error",
        errorContainer: "div#profileEditErrorHeader, div#profileEditServerErrors",
        serverErrorContainer: "div#profileEditServerErrors",
        rules: {
            profileFirstName: "required",
            profileLastName: "required",
            profileEmail: { required: true, email: true },
            profilePassword: { minlength: 5, maxlength: 8, strongPassword: true },
            profilePasswordConfirm: { equalTo: "#profilePassword" }
//            profilePracticeName: "required",
//            profileAddress1: "required",
//            profileAddress2: "required",
//            profileCity: "required",
//            profileState: "required",
//            profileZip: "required",
        },
        messages: {
            profileFirstName: "Please enter your first name.",
            profileLastName: "Please enter your last name.",
            profileEmail: "Please enter a valid e-mail address.",
            profilePassword: { minlength: "Passwords must be between 5-8 characters.", 
                               maxlength: "Passwords must be between 5-8 characters.", 
                               strongPassword: "Please enter a valid password." },
            profilePasswordConfirmprofilePasswordConfirm: "Passwords must match."
//            profilePracticeName: "Please enter your practice name.",
//            profileAddress1: "Please enter your address.",
//            profileAddress2: "Please enter your address.",
//            profileCity: "Please enter your city.",
//            profileState: "Please enter your state.",
//            profileZip: "Please enter your zip code.",
        }
    });
    
    popup
        // Populate from UserProfile
        .find("input#profileFirstName").val(UserProfile.firstName).end()
        .find("input#profileLastName").val(UserProfile.lastName).end()
        .find("input#profileEmail").val(UserProfile.email).end()
        .find("input#profilePassword").val('').end()
        .find("input#profilePasswordConfirm").val('').end()
        .find("input#profilePracticeName").val(UserProfile.practiceName).end()
        .find("input#profileAddress1").val(UserProfile.address1).end()
        .find("input#profileAddress2").val(UserProfile.address2).end()
        .find("input#profileCity").val(UserProfile.city).end()
        .find("input#profileState").val(UserProfile.state).end()
        .find("input#profileZip").val(UserProfile.zip).end()
        
        // Save button 
        // - update global profile object from popup
        // - send request to save the profile data
        .find("input#popupBtnProfileEditSave").unbind("click").click(function(){
            if (form.valid()) {
                var newProfile = {};
                newProfile.userID =         UserProfile.userID;
                newProfile.firstName =      popup.find("input#profileFirstName").val();
                newProfile.lastName =       popup.find("input#profileLastName").val();
                newProfile.email =          popup.find("input#profileEmail").val();
                newProfile.practiceName =   popup.find("input#profilePracticeName").val();
                newProfile.address1 =       popup.find("input#profileAddress1").val();
                newProfile.address2 =       popup.find("input#profileAddress2").val();
                newProfile.city =           popup.find("input#profileCity").val();
                newProfile.state =          popup.find("input#profileState").val();
                newProfile.zip =            popup.find("input#profileZip").val();
                // Make sure to trim() password
                newProfile.password = $.trim(popup.find("input#profilePassword").val());

                // Send update request - revert changes on error
                var um = new UserManager();
                var result = um.updateProfile(newProfile);
                if (ajaxSuccess(result)) {
                
                    // Get ePassword from result
                    var newEpassword = extractAjaxResult(result);
                    
                    // Get eEmail/ePassword from UserProfile
                    newProfile.eEmail =        UserProfile.eEmail;
                    newProfile.ePassword =     newEpassword;
                    
                    // Use updated UserObject
                    UserProfile = newProfile;

                    // Save cookie with new ePassword
                    saveLoginCookies();
                    
                    // Update practice name 
                    updatePracticeName();

                    // Show profile popup
                    showProfilePopup(true);
                    
                } else {
                    // Got an error - display it
                    popup
                        .find("div#profileEditServerErrors").show()
                        .find("p.serverMessage")
                        .html(result)
                        .show();
                }
            }
            return false;
        }).end()
        
        // Add event to cancel button
        .find("input#popupBtnProfileEditCancel").unbind("click").click(function(){
            showProfilePopup(true);
            return false;
        }).end();
        
    // Manually submit when user presses enter in <INPUT />
    registerInputClick(popup, popup.find("input#popupBtnProfileEditSave"));
}









/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Recommendation Popups
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Shows the Email Recommendations popup
function showEmailRecommendationPopup(){
    
    var popup = $("div#popupEmailSend");

    // Make sure user selected something
    var numItemsSelected = $("div#cartItems")
        .find("li:visible")
        .find("input.hidID").length;

    if (numItemsSelected == 0) {
        alert("Your outbox is empty.");
    } else {
        showLoginOptionalPopup(popup, populateEmailSendPopup);
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Populates the email recommendation popup with data from the cart.
// This popup does not require the user to be logged in but does display user 
// information if available.
function populateEmailSendPopup(popup){
    
    getDartTagForAction("777");

    // Get user's name if the user is logged in
    var emailName = "";
    if (isLoggedIn()) {
        emailName = UserProfile.firstName + " " + UserProfile.lastName;
    }

    var form = setupValidationForm({
        form: "form#formEmailSend",
        errorClass: "error",
        errorContainer: "div#emailSendErrorHeader, div#emailSendServerErrors",
        serverErrorContainer: "div#emailSendServerErrors",
        rules: {
            emailName: "required",
            emailRecipientName: "required",
            emailRecipientEmail: { required: true, email: true },
            emailSendItems: { listNotEmpty: popup.find("ul.items") }
        },
        messages: {
            emailName: "Please enter your name.",
            emailRecipientName: "Please enter the recipient's name.",
            emailRecipientEmail: "Please enter a valid e-mail address.",
            emailSendItems: "There are no PDFs below."
        }
    });

    popup
        // Add name from profile
        .find("input.emailName").val(emailName).end()

        // Clear out other fields
        .find("input.emailRecipientName").val("").end()
        .find("input.emailRecipientEmail").val("").end()
        
        // Add cancel button handler
        .find("input#popupBtnEmailCancel").unbind("click").click(function(){
            closePopups();
            return false;
        }).end()
        
        // Add send button handler
        .find("input#popupBtnEmailSend").unbind("click").click(function(){
            if (form.valid()) {
                var name = popup.find("input.emailName").val();
                var recipientName = popup.find("input.emailRecipientName").val();
                var recipientEmail = popup.find("input.emailRecipientEmail").val();
                var pdfIDs = "";
                    popup.find("ul.items")
                        .find("li:visible")
                        .find("input.hidID")
                        .each(function(i){
                            pdfIDs = pdfIDs + ((i>0) ? "," : "") + $(this).val();
                        });
                
                var errorMessage = emailRecommendation(name, recipientName, recipientEmail, pdfIDs);
                if (errorMessage) {
                    // If there was an error, display it
                    popup
                        .find("div#emailSendServerErrors").show()
                        .find("p.serverMessage")
                        .html(errorMessage)
                        .show();
                } else {
               
                    // Remove from the Cart object
                    Cart.empty();
                
                    // Clear visible items out of cart UL (leaving template)
                    $("div#cartItems ul").children().remove("li:visible");

                    // Update check marks
                    setAddButtonState();
    
                    // Otherwise just show confirmation
                    showEmailConfirmation();
                }
            }
            return false;
        }).end();

    // Manually submit when user presses enter in <INPUT />
    registerInputClick(popup, popup.find("input#popupBtnEmailSend"));
    
    // Populate the popup list with pdfIDs from the cart
    var template = $("li#emailSendTemplate");
    populatePopupList(Cart.getIDs(), template);
}

/////////////////////////////////////////////////////////////////////////////////
// Sends an email recommendation back to the server in a JSON object
// RETURNS: error from server, if any
function emailRecommendation(name, recipientName, recipientEmail, pdfIDs){

    var recommendation = 
        {
            "userID" : (isLoggedIn() ? UserProfile.userID : ""), 
            "name" : name, 
            "recipientName" : recipientName, 
            "recipientEmail" : recipientEmail, 
            "pdfIDs" : pdfIDs
        };
    
    // Send request
    var em = new EmailManager();
    var result = em.save(recommendation);
    if (!ajaxSuccess(result)) {
        // Return any error
        return result;
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Shows the Email Confirmation popup 
function showEmailConfirmation() {
    
    getActionTag("DIHAZ_PUL81007_Pro_EmailOK");
    getDartTagForAction("592");
    
    var popup = $("div#popupEmailConfirm")
        .find("input#popupBtnCloseEmailConfirm").unbind("click").click(function(){
            closePopups();
            return false;
        }).end();
        
    showPopup(popup, false);   
}











/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Save Bundle Popup
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Shows the Save Bundle popup
function showSaveBundlePopup(){
    
    // Make sure user selected something
    var numItemsSelected = $("div#cartItems")
        .find("li:visible")
        .find("input.hidID").length;
    
    // Just display an error message if the outbox is empty
    if (numItemsSelected == 0){
        alert("Your outbox is empty.");
        return;
    }
    
    var popup = $("div#popupBundleSave");
    
    var form = setupValidationForm({
        form: "form#formBundleSave",
        errorClass: "error",
        errorContainer: "div#bundleSaveErrorHeader, div#bundleSaveServerErrors",
        serverErrorContainer: "div#bundleSaveServerErrors",
        rules: {
            saveBundleName: "required",
            saveBundleDesc: { maxlength: 128 },
            saveBundleItems: { listNotEmpty: popup.find("ul.items") }
        },
        messages: {
            saveBundleName: "Please enter a bundle name.",
            saveBundleDesc: { maxlength: "Please limit your description to 128 characters." },
            saveBundleItems: "There are no PDFs below."
        }
    });

    // Show save bundle popup
    popup
        // Clear out previous input
        .find("input:text:visible").val("").end()
        .find("textarea").val("").end()
        
        // Cancel button
        .find("input#popupBtnBundleSaveCancel").unbind("click").click(function(){
            closePopups();
            return false;
        }).end()
        
        // Save button
        .find("input#popupBtnBundleSave").unbind("click").click(function(){
            if (form.valid()) {
                var popup = $("div#popupBundleSave");
                var bundleID = popup.find("option:selected").val();
                var selectedBundleName = popup.find("option:selected").text();
                var name = popup.find("input#saveBundleName").val();
                
                // Get rid of extraneous spaces so "Bundle Name" != " Bundle     Name  "
                name = trimAndRemoveDuplicateSpaces(name);
                
                var description = popup.find("textarea#saveBundleDesc").val();
                var pdfIDs = "";
                    popup.find("ul.items")
                        .find("li:visible")
                        .find("input.hidID")
                        .each(function(i){
                            pdfIDs = pdfIDs + ((i>0) ? "," : "") + $(this).val();
                        });
                var errorMessage;
                
                // Make sure the new bundle's name doesn't already exist
                var bundle = Bundles.getBundleByName(name);
                if (bundle && 
                    (selectedBundleName != name)) {
                    // Found a duplicate bundle name - confirm before replacing
    	            showDuplicateBundlePopup(bundle.bundleID, UserProfile.userID, name, description, pdfIDs);
    	        } else { 
                    // Didn't find a duplicate name - go ahead and save the bundle
                    if (bundleID == CREATE_NEW_BUNDLE) {
                        errorMessage = saveCustomBundle(UserProfile.userID, name, description, pdfIDs);
                    } else {
                        // Get listitem containing bundle
                        var li = $("div#productsList").find("input[value=" + bundleID + "]").parent("li");
                        // Perform update
                        errorMessage = updateCustomBundle(li, bundleID, UserProfile.userID, name, description, pdfIDs);
                    }
                    if (errorMessage) {
                        // If there was an error, display it
                        popup
                            .find("div#bundleSaveServerErrors").show()
                            .find("p.serverMessage")
                            .html(errorMessage)
                            .show();
                    } else {
                        // No error
                        getActionTag("DIHAZ_PUL81007_Pro_SaveBundle_Complete");
                        getDartTagForAction("905");
                        closePopups();
                    }    
                }
            }
            return false;
        }).end()

        // Remove any items in dropdown after the first one
        .find("option:gt(0)").remove().end();

    // Manually submit when user presses enter in <INPUT />
    registerInputClick(popup, popup.find("input#popupBtnBundleSave"));
    
    showPopup(popup, true, populateSaveBundlePopup);
}

/////////////////////////////////////////////////////////////////////////////////
// Populates the Save Bundle popup - called from showSaveBundlePopup()
function populateSaveBundlePopup(popup){

    getDartTagForAction("882");
    
    // Add bundle names to dropdown
    var bundleIDs = Bundles.getBundleIDs();
    for (var i=0; i<bundleIDs.length; i++){
        
        var bundle = Bundles.getBundleByID(bundleIDs[i]);
        
        if(bundle.userID == UserProfile.userID){
            popup.find("option:last-child")
                .after("<option value=\"" + bundle.bundleID + "\">" + bundle.name + "</option>");
        }
    }
    
    // Wire up a change event for the selectbox
    popup.find("select").unbind("change").change(function(){
       
        // Get pdfs for chosen bundle
        var bundleID = $(this).val();
        switch (bundleID){
            case "":
                // "Select Bundle" - ignore
                break;
            case CREATE_NEW_BUNDLE:
                // New bundle
                // Clear out name, description
                popup.find("input#saveBundleName").val("");
                popup.find("textarea#modifyBundleDesc").val("");
                break;
            default:
                // Get bundle info
                var bundle = Bundles.getBundleByID(bundleID);
                var pdfIDs = bundle.pdfIDs.split(",");
                
                // Populate fields
                popup.find("input#saveBundleName").val(bundle.name);
                popup.find("textarea#saveBundleDesc").val(bundle.description);
                break;
        }
        return false;
    });

    // Populate the popup list with pdfIDs from the cart
    var template = $("li#popupBundleSaveTemplate");
    populatePopupList(Cart.getIDs(), template);
}













/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Duplicate Bundle Popup
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Shows the Dupliacte Bundle popup
function showDuplicateBundlePopup(bundleID, userID, name, description, pdfIDs){
    // Found a duplicate bundle name - confirm before replacing
    var popup = $("div#popupBundleDuplicate")
    
        // Wire up replace button
        .find("input#popupBtnBundleReplace").unbind("click").click(function(){
            closePopups();
            
            // Get listitem containing bundle
            var li = $("div#productsList").find("input[value=" + bundleID + "]").parent("li");
            
            var errorMessage = updateCustomBundle(li, bundleID, userID, name, description, pdfIDs);
            if (errorMessage) {
                alert("Your request could not be completed:\n\n" + errorMessage);
            }
            return false;
        }).end()

        // Wire up cancel button
        .find("input#popupBtnBundleReplaceCancel").unbind("click").click(function(){
            closePopups();
            return false;
        }).end();
    
    displayPopupAsModal(popup);
}












/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Preview Popups
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////
// Shows the preview popup 
function showPreviewPopup(id, type){
    switch(type){
        case TYPE_PDF:
            showPdfPreview(id);
            break;
            
        case TYPE_BUNDLE:
        case TYPE_CUSTOM_BUNDLE:
            showBundlePreview(id, type);
            break;
    }
}

/////////////////////////////////////////////////////////////////////////////////
// Populates and shows the pdf preview popup 
function showPdfPreview(pdfID){

    var popup = $("div#popupPDFPreview")
    
        // Update hidID so we can identify the PDF later
        .find("input.hidID").val(pdfID).end();
        
    showPdfPreviewData(popup, getPdfByID(pdfID));
    
    // Get image for this ID
    var image = $("input[class=hidType][value=" + TYPE_PDF + "]")
        .parent("li")
        .find("input[class=hidID][value=" + pdfID + "]")
        .parent("li")
        .find("div.itemImage img");

    // Scroll page to top when showing preview to simplify aligning arrow
    window.scrollTo(0,0);
    
    // Move arrow to image
    var popupTopMargin = parseInt(popup.css("margin-top"));
    var newTop = image.offset().top - popupTopMargin;
    var arrowImage = popup.find("div.itemArrow");
    arrowImage.css( { top:newTop } );
    
    showPopup(popup, false);
}

/////////////////////////////////////////////////////////////////////////////////
// Populates and shows the bundle preview popup 
function showBundlePreview(bundleID, type){
    
    var bundle = Bundles.getBundleByID(bundleID);
    var pdfIDs = bundle.pdfIDs.split(",");

    var popup = $("div#popupBundlePreview")
    
        // Update hidID so we can identify the bundle later
        .find("input.hidID").val(bundle.bundleID).end()
        
        // Update hidType so we can identify the bundle type later
        .find("input.hidType").val(type).end()
        
        // Remove the existing list entries from previous bundle previews
        .find("ul.items li:visible").remove().end()
    
        // Update bundle name
        .find("span.bundleName").text(bundle.name).end();
    
    // Add bundle pdfs to popup
    for(var i=0;i<pdfIDs.length;i++){
        pdf = getPdfByID(pdfIDs[i]);
        
        var li = clonePreviewPdfListEntryTemplate(popup, pdf);
        
        // preselects the first pdf.
        if(i==0){
            selectPreviewPdfListEntry(li);
            showPdfPreviewData(popup, pdf);
        }
    }
    
    // Get image for this ID
    var image = $("input[class=hidType][value!=" + TYPE_PDF + "]")
        .parent("li")
        .find("input[class=hidID][value=" + bundleID + "]")
        .parent("li")
        .find("div.itemImage img");

    // Scroll page to top when showing preview to simplify aligning arrow
    window.scrollTo(0,0);
    
    // Move arrow to image
    var popupTopMargin = parseInt(popup.css("margin-top"));
    var newTop = image.offset().top - popupTopMargin;
    var arrowImage = popup.find("div.itemArrow");
    arrowImage.css( { top:newTop } );

    showPopup(popup, false);
}

/////////////////////////////////////////////////////////////////////////////////
// Reproduces pdf preview entries in the listing on the bundle preview page.  
function clonePreviewPdfListEntryTemplate(popup, pdf){
    var template = $("li#previewPdfListEntryTemplate");
    var clone = template.clone();
    clone.removeAttr("id")
        .find("p.previewListPdfName").text(pdf.name).end()

        // Update hidID
        .find("input.hidID").val(pdf.pdfID).end()
        
        // Set thumbnail
        .find("img.thumbnail").attr("src", pdf.thumbnailUrl).end()
        
        .click(function(){
            selectPreviewPdfListEntry($(this));               
            showPdfPreviewData(popup, pdf);
            return false;
        })
        
        .appendTo(template.parent()).show();
        
    return clone;
}

/////////////////////////////////////////////////////////////////////////////////
// Populates a preview popup with pdf data.  This is used
// by both the pdf preview popup and the bundle preview popup.
function showPdfPreviewData(popup, pdf){

    var imageFile = pdf.previewPrefix + "-page";
    var pages = Number(pdf.numPages);
    var curPage = 1;
    
    var previewImage = popup.find("img.pagePreview")
        .attr("alt", pdf.name)
        .attr("title", pdf.name);
    
    var pageDisplay = popup.find("span.previewCurPage");
    
    popup
        .find("span.pdfName").text(pdf.name).end()
        .find("span.previewMaxPage").text(pages).end()
    
        // Binds the previous button to cycle to the previous page
        .find("img.prevPageBtn").unbind("click").click(function(){
            if(curPage > 1){
                curPage --;
                previewImage.attr("src", IMAGE_PREVIEW_PATH + imageFile + curPage + ".jpg");
                pageDisplay.text(curPage);
                
                // Show/hide prev/next as appropriate
                if (curPage == 1){
                    popup.find("img.prevPageBtn").addClass("hideButton");
                }
                popup.find("img.nextPageBtn").removeClass("hideButton");
            }
            return false;
        }).end()
        
        // Binds the next button to cycle to the next page
        .find("img.nextPageBtn").unbind("click").click(function(){
            if(curPage < pages){
                curPage ++;
                previewImage.attr("src", IMAGE_PREVIEW_PATH + imageFile + curPage + ".jpg");
                pageDisplay.text(curPage);
                
                // Show/hide prev/next as appropriate
                if (curPage == pages){
                    popup.find("img.nextPageBtn").addClass("hideButton");
                } 
                popup.find("img.prevPageBtn").removeClass("hideButton");
            }
            return false;
        }).end()   
        
        // Point the download link to the PDF
        .find("a.pdfDownload").attr("href", pdf.url).attr("target", "_blank").end()
        
        // Action tag
        .find("a.pdfDownload").unbind("click").click(function(){
            var type = $(this).parents("div.inside").find("input.hidType").val();
            var id;

            // Get pdfID - different for bundle/pdf preview
            if (type == TYPE_PDF) {
                id = $(this).parents("div.inside").find("input.hidID").val();
            } else {
                id = $(this).parents("div.inside").find("ul.items li.on input.hidID").val();
            }

            // If there's an action tag, get it
            var actionTag = getPdfByID(id).actionTagDownload;
            if (actionTag){ getActionTag(actionTag); }
            
            // If there's a dart id, get it
            var dartId = getPdfByID(id).dartIdDownload;
            if (dartId){ getDartTagForPdfOrBundle(dartId); }
        }).end()
        
        // Binds the "add to outbox" button to send the currently previewed pdf to the outbox
        .find("input.previewAddToOutbox").unbind("click").click(function(){
            // Extract item id and type
            var popup = $(this).parents("div.popup");
            var id = popup.find("input.hidID").val();
            var type = popup.find("input.hidType").val();
            
            addItemToCart(id, type);
            closePopups();
            return false;
        }).end();
    
    // Set initial prev/next state
    popup.find("img.prevPageBtn").addClass("hideButton");
    if (pages == 1) { 
        popup.find("img.nextPageBtn").addClass("hideButton");
    } else {
        popup.find("img.nextPageBtn").removeClass("hideButton");
    }

    previewImage.attr("src", IMAGE_PREVIEW_PATH + imageFile + curPage + ".jpg");
    pageDisplay.text(curPage);
}

/////////////////////////////////////////////////////////////////////////////////
// Changes the visible state of the clicked item in the  pdf listing in the 
// bundles preview popup.  Highlights the selected and unhighlights the 
// previously selected.
function selectPreviewPdfListEntry(li){

    var pdfID, pdf;

    // Find active listitem
    li.parent().find("li.on").each(function(i, n){ 
        var activeLi = $(n);
        pdfID = activeLi.find("input.hidID").val();
        pdf = getPdfByID(pdfID);
        // Set normal thumbnail
        activeLi.find("img.thumbnail").attr("src", pdf.thumbnailUrl);
        // Remove "on" class
        activeLi.attr("class", "")
    });

    pdfID = li.find("input.hidID").val();
    pdf = getPdfByID(pdfID);
    // Set selected thumbnail
    li.find("img.thumbnail").attr("src", pdf.thumbnailSelectedUrl);
    // Add "on" class
    li.attr("class", "on");
    
    return;
}



/////////////////////////////////////////////////////////////////////////////////
// Shows the help popup
function showHelpPopup(){
    
    getDartTagForAction("924");
    
    var popup = $("div#popupHelp")
        
        // Hide all questions
        .find(".answer").hide().end()
        
        // Add style to alternating rows
        .find("ul.questions > li:even").addClass("even").end()
        
        .find('p.question').unbind("click").click(function() {
            // Find parent LI
            var li = $(this).parent("li");
            
            // Find answer
            var answer = li.find(".answer");
            
            // Show/hide
            answer.slideToggle("fast");

            return false;
        }).end();
        
    displayPopupAsModal(popup);
}

/////////////////////////////////////////////////////////////////////////////////
// Closes the AKCPro popup window
function closeAKCPro(){    

    if (window.opener && !window.opener.closed)
    {
    	if (confirm("Click 'OK' to close the current window and return to the HCP site.  Click 'Cancel' to keep the current window open."))
    	{
            window.opener.document.location.href = "/professional/patients-caregivers/asthmakidcare-pro.aspx";
            window.close();
        }    
    }
    else
    {
        document.location.href = "/professional/patients-caregivers/asthmakidcare-pro.aspx";
    }    
}


