function checkFlashVer() {
    // Check for Flash version 8+
    var hasReqestedVersion = DetectFlashVer(8, 0, 0);
    if (!hasReqestedVersion) {
        var userAction = confirm("Thank you for using the CAST UDL Book Builder.\n\n CAST UDL Book Builder uses Adobe Flash Player version 8 and above for some of its features.  This computer appears to be missing or using an older version of the Flash Player.\n\nClick OK to Download the Adobe Flash Player, or Cancel to Continue.");
        if (userAction == true) {
            // Create popup window to Adobe
            var currWinW = window.innerWidth;
            var currWinH = window.innerHeight;
            var windowXY = findWindowCenter(currWinW, currWinH);
            var urlPath = "http://www.adobe.com/go/getflashplayer";
            var winPop = open(urlPath, 'FlashPlayer', windowXY + ',scrollbars=yes,status=yes,resizable=yes,toolbar=yes,location=yes,menubar=yes');
            if (!winPop.opener) winPop.opener = self;
            winPop.focus();
        }
    }
}

function checkForOldSafari() {
    // Safari 3 - internal version number 523.x
    if ($.browser.safari  &&  parseInt($.browser.version) < 523 ) {
        alert("*** W A R N I N G *** W A R N I N G ***\n\nThe CAST UDL Book Builder uses a text editor that is not fully compatible with older versions of Safari, resulting in errors and possible loss of information.\n\nCAST recommends using another browser such as Firefox (available at http://www.mozilla.com).\n\n We are sorry for any inconvenience.");
    }
}

function findWindowCenter(winWidth, winHeight) {
    // Target the window to open in the center of the screen
    var screenWidth = screen.width;
    var screenHeight = screen.height;

    var windowX = (screenHeight - winHeight) / 2;
    var windowY = (screenWidth - winWidth) / 2;

    centerString = "width=" + winWidth + ",height=" + winHeight + ",top=" + windowX + ",left=" + windowY;

    return centerString;
}

function popupVideo(targetSrc) {
    // Create popup window
    var windowXY = findWindowCenter(650, 500);
    var urlPath = "./window.php?src=" + targetSrc;
    var winPop = open(urlPath, 'Video', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupAgent(bookid, pagenum, agentnum) {
    // Create popup window
    var windowXY = findWindowCenter(700, 490);
    var urlPath = "./edit_agent.php?book=" + bookid + "&page=" + pagenum + "&agent=" + agentnum;
    var winPop = open(urlPath, 'Agent', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupText(bookid, pagenum, slotnum) {
    // Create popup window
    var windowXY = findWindowCenter(700, 420);
    var urlPath = "./edit_text.php?book=" + bookid + "&page=" + pagenum + "&slot=" + slotnum;
    var winPop = open(urlPath, 'Text', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupImage(bookid, pagenum, slotnum) {
    // Create popup window
    var windowXY = findWindowCenter(700, 650);
    var urlPath = "./edit_image.php?book=" + bookid + "&page=" + pagenum + "&slot=" + slotnum;
    var winPop = open(urlPath, 'Image', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupAudio(bookid, pagenum, slotnum) {
    // Create popup window
    var windowXY = findWindowCenter(700, 475);
    var urlPath = "./edit_audio.php?book=" + bookid + "&page=" + pagenum+ "&slot=" + slotnum;
    var winPop = open(urlPath, 'Audio', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupTip(bookid, pagenum) {
    // Create popup window
    var windowXY = findWindowCenter(700, 410);
    var urlPath = "./edit_tip.php?book=" + bookid + "&page=" + pagenum;
    var winPop = open(urlPath, 'Tip', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupExtras(bookid, pagenum) {
    // Create popup window
    var windowXY = findWindowCenter(700, 410);
    var urlPath = "./edit_extras.php?book=" + bookid + "&page=" + pagenum;
    var winPop = open(urlPath, 'Extras', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupResponse(bookid, pagenum) {
    // Create popup window
    var windowXY = findWindowCenter(700, 410);
    var urlPath = "./edit_response.php?book=" + bookid + "&page=" + pagenum;
    var winPop = open(urlPath, 'Response', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupTOC(bookid, pagenum) {
    // Create popup window
    var windowXY = findWindowCenter(700, 410);
    var urlPath = "./edit_toc.php?book=" + bookid + "&page=" + pagenum;
    var winPop = open(urlPath, 'TOC', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupTOCTitle(bookid, pagenum) {
    // Create popup window
    var windowXY = findWindowCenter(700, 410);
    var urlPath = "./edit_toc_title.php?book=" + bookid;
    var winPop = open(urlPath, 'TOC', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupDownload(bookid) {
    // Create popup window
    var windowXY = findWindowCenter(700, 400);
    var urlPath = "./download.php?book=" + bookid;
    var winPop = open(urlPath, 'Download', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupView(bookid, pagenum, orientation) {
    // Create popup window
    if (orientation == "2") {
        var windowXY = findWindowCenter(690, 560);
    } else {
        var windowXY = findWindowCenter(545, 695);
    }
    var urlPath = "./view.php?op=view&book=" + bookid + "&page=" + pagenum;
    var winPop = open(urlPath, 'View', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupPrint(bookid) {
    // Create popup window
    var windowXY = findWindowCenter(700, 400);
    var urlPath = "./view.php?op=print&book=" + bookid;
    var winPop = open(urlPath, 'Print', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupGlossaryText(bookid, wordid) {
    // Create popup window
    var windowXY = findWindowCenter(700, 410);
    var urlPath = "./edit_glossary_text.php?book=" + bookid + "&word=" + wordid;
    var winPop = open(urlPath, 'GText', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupGlossaryImage(bookid, wordid) {
    // Create popup window
    var windowXY = findWindowCenter(700, 650);
    var urlPath = "./edit_glossary_image.php?book=" + bookid + "&word=" + wordid;
    var winPop = open(urlPath, 'GImage', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupGlossaryAudio(bookid, wordid) {
    // Create popup window
    var windowXY = findWindowCenter(700, 475);
    var urlPath = "./edit_glossary_audio.php?book=" + bookid + "&word=" + wordid;
    var winPop = open(urlPath, 'GAudio', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupGlossary(bookid, wordid) {
    // Create popup window
    if (wordid == null) { wordid = ""; }
    var windowXY = findWindowCenter(520, 500);
    var urlPath = "./view_glossary.php?book=" + bookid + "&word=" + wordid + "#curr";
    var winPop = open(urlPath, 'GView', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupInfo(page) {
    // Create popup window
    var windowXY = findWindowCenter(520, 500);
    var urlPath = "./view_info.php?page=" + page;
    var winPop = open(urlPath, 'Info', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupNotice() {
    // Create popup window
    var windowXY = findWindowCenter(650, 520);
    var urlPath = "./window.php?src=notice";
    var winPop = open(urlPath, 'Notice', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupAvatarImage(bookid, avatarid) {
    // Create popup window
    var windowXY = findWindowCenter(520, 500);
    var urlPath = "./edit_avatar.php?op=editimg&book=" + bookid + "&avatar=" + avatarid;
    var winPop = open(urlPath, 'AvatarImg', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function showVideo(num, filename) {
    // Determine "Click to Start" string
    switch(num) {
        case '1': {
            var playStr = "Click to Play 'Diversity of Learners'";
            break;
        }
        case '2': {
            var playStr = "Click to Play 'Universal Design and UDL'";
            break;
        }
        case '3': {
            var playStr = "Click to Play 'The Brain Research'";
            break;
        }
        case '4': {
            var playStr = "Click to Play 'Principles of UDL'";
            break;
        }
        default: {
            var playStr = "";
            break;
        }
    }

    // Build Flash OBJECT item
    var outputHTML = "";
    outputHTML += "<object type=\"application/x-shockwave-flash\" width=\"368\" height=\"356\" data=\"./flash/mediaplayer/player.swf?file=../../video/" + filename + "&autostart=true&fullscreen=true&backcolor=#EEEEEE\" wmode=\"transparent\" allowScriptAccess=\"always\" allowfullscreen=\"true\">";
    outputHTML += "<param name=\"movie\" value=\"./flash/mediaplayer/player.swf?file=../../video/" + filename + "&autostart=true&fullscreen=true&backcolor=#EEEEEE\" />";
    outputHTML += "<param name=\"wmode\" value=\"transparent\" />";
    outputHTML += "<param name=\"allowScriptAccess\" value=\"always\" />";
    outputHTML += "<param name=\"allowfullscreen\" value=\"true\" />";
    outputHTML += "</object>";
    // Add new video item
    document.getElementById("videohome").innerHTML = outputHTML;
}

function showAudio(filepath) {
    var outputHTML = "";
    outputHTML += "<object type=\"application/x-shockwave-flash\" width=\"240\" height=\"20\" data=\"./flash/mediaplayer/player.swf?file=" + filepath  + "&autostart=false&fullscreen=false&backcolor=#EEEEEE\" wmode=\"transparent\" allowScriptAccess=\"always\">";
    outputHTML += "<param name=\"movie\" value=\"./flash/mediaplayer/player.swf?file=" + filepath + "&autostart=false&fullscreen=false&backcolor=#EEEEEE\" />";
    outputHTML += "<param name=\"wmode\" value=\"transparent\" />";
    outputHTML += "<param name=\"allowScriptAccess\" value=\"always\" />";
    outputHTML += "<param name=\"allowfullscreen\" value=\"false\" />";
    outputHTML += "</object>";
    // Add new audio item
    document.write(outputHTML);
}

function showAgentAudio(filepath) {
    var outputHTML = "";
    outputHTML += "<object type=\"application/x-shockwave-flash\" width=\"185\" height=\"20\" data=\"./flash/mediaplayer/player.swf?file=" + filepath  + "&autostart=false&fullscreen=false&backcolor=#EEEEEE&skin=./flash/mediaplayer/simple.swf\" wmode=\"transparent\" allowScriptAccess=\"always\">";
    outputHTML += "<param name=\"movie\" value=\"./flash/mediaplayer/player.swf?file=" + filepath + "&autostart=false&fullscreen=false&backcolor=#EEEEEE&skin=./flash/mediaplayer/simple.swf\" />";
    outputHTML += "<param name=\"wmode\" value=\"transparent\" />";
    outputHTML += "<param name=\"allowScriptAccess\" value=\"always\" />";
    outputHTML += "<param name=\"allowfullscreen\" value=\"false\" />";
    outputHTML += "</object>";
    // Add new audio item
    $('#audioDiv').eq(0).html(outputHTML);
}

function imageSwap(Item,ImgSrc) {
    if (document.images) {
        Item.src = ImgSrc;
    }
}

function windowClose(editStyle, glossary) {
    if (!glossary) var glossary = false;
    var haltClose = false;
    var closeConfirm = false;

    if (editStyle == "text") {
        if (tinyMCE != false) {
            tinyMCE.triggerSave();
        }
        prevVal = document.forms[0].prev.value;
        currVal = document.forms[0].text.value;
        // Check to see if 'previous' value matches the current value
        if (prevVal != currVal) {
            haltClose = true;
        }
    }

    if (editStyle == "textopt") {
        prevVal = document.forms[0].prev.value;
        currVal = document.forms[0].text.value;
        prevCheck = document.forms[0].prevcheck.value;
        currCheck = document.forms[0].incitem.checked;

        // Check to see if 'previous' value matches the current value
        if ( (prevVal != currVal) || (prevCheck + "") !== (currCheck + "") ) {
            haltClose = true;
        }
    }

    if (editStyle == "image") {
        aprevVal = document.forms[0].altprev.value;
        acurrVal = document.forms[0].alt.value;
        cprevVal = document.forms[0].captionprev.value;
        ccurrVal = document.forms[0].caption.value;

        // Check to see if previous alt tag value matches the current value
        if (aprevVal != acurrVal) {
            haltClose = true;
        }

        // Check to see if previous caption value matches the current value
        if (cprevVal != ccurrVal) {
            haltClose = true;
        }

        // Check to see if 'change' flag is set
        if (document.imageedit.change.value == "1") {
            haltClose = true;
        }
    }

    if (editStyle == "avatarimg") {
        // Check to see if 'change' flag is set
        if (document.imageedit.change.value == "1") {
            haltClose = true;
        }
    }

    if (editStyle == "audio") {
        // Check to see if 'change' flag is set
        if (document.audioedit.change.value == "1") {
            haltClose = true;
        }
    }

    if (haltClose) {
        // Show warning box and
        closeConfirm = confirm("There are unsaved changes.\n\n  Are you sure you want to close the edit window?");
        if (closeConfirm) {
        // OK -- close window
            if (editStyle == "image") {
                // Call to remove any upload image and then close window
                var bookid = document.imageedit.book.value;
                if (!glossary) {
                    var pageid = document.imageedit.page.value;
                    var slotnum = document.imageedit.slot.value;
                    document.location.href = "./edit_image.php?op=cancel&book=" + bookid + "&page=" + pageid + "&slot=" + slotnum;
                } else {
                    var wordid = document.imageedit.word.value;
                    document.location.href = "./edit_glossary_image.php?op=cancel&book=" + bookid + "&word=" + wordid;
                }
                return;
            }
            if (editStyle == "audio") {
                // Call to remove any upload audio and then close window
                var bookid = document.audioedit.book.value;
                if (!glossary) {
                    var pageid = document.audioedit.page.value;
                    document.location.href = "./edit_audio.php?op=cancel&book=" + bookid + "&page=" + pageid;
                } else {
                    var wordid = document.audioedit.word.value;
                    document.location.href = "./edit_glossary_audio.php?op=cancel&book=" + bookid + "&word=" + wordid;
                }
                return;
            }
            // Simply close all other windows
            window.close();
            return;
        } else {
            // Cancel - do nothing
            return;
        }
    }

    // No changes made - close window
    window.close();
    return;
}

//------------------------------------------------------------------------------------------------

function createAgentBox(agentID, xmlPath, preview) {
    if (DragItem['dragAgent' + agentID]) return;
    var agent = new FlashAgent(agentID, 'http://agents.cast.org/v6/', 'http://agents.cast.org/shared/', xmlPath);

    if (preview == true) {
        agent.setOnReady( function() { enableAgentSave(); });
    }

    agent.setOnPlayStop( function() { agent.dragBox.hide(); } );
    agent.setSize(200,200);
    agent.createDragBox();
    agent.dragBox.clearOnHide = true;
    agent.dragBox.handleScroll = false;
    agent.dragBox.show();
}

function createAndPlay(agentID, xmlPath, preview) {
    //var xmlPath = sequenceFile[seqNum];
    var agBox = FlashApplet.lookupNumber(agentID);
    if (agBox == null) {
        createAgentBox(agentID, xmlPath, preview);
        //agBox = FlashApplet.lookupNumber(agentID);
    } else {
        agBox.seqPath = xmlPath;
        agBox.dragBox.show();
        agBox.updateSettings();
    }
}

function previewAgent() {
    // Make sure there is something else return
    var speechTxt = document.agentedit.text.value;
    if(speechTxt.trim() == "") {
        alert("Please provide something for the coach to say.");
        return;
    }

    speechTxt = speechTxt.nl2br();
    speechTxt = speechTxt.stripnl();

    // Write back speech to form element
    //document.agentedit.text.value = speechTxt;

    // Get agent num and speech text
    var saveItems = new Array();
    saveItems['bookId'] = document.agentedit.book.value;
    saveItems['agentNum'] = document.agentedit.agent.value;
    saveItems['agentTxt'] = speechTxt;

    // Save temp file and play
    storeSequence(saveItems);
}

function storeSequence(saveItems) {
    var http_request = false;

    $.post("./store.php", {bookId: saveItems['bookId'], agentNum: saveItems['agentNum'], agentTxt: saveItems['agentTxt']}, function(returnData) {
        storeReturn(returnData);
    });
}

function storeReturn(returnData) {
    // Check for any reports php errors
    returnSplit = returnData.split("|");
    if (returnSplit[0].trim() != "OK" ) {
        alert(returnData);
    } else {
        // Everything should be ok
        // Save cache id
        document.getElementById('agentcache').value = returnSplit[2].trim();
        // Create and play agent
        var xmlPath = returnSplit[1].trim();
        var agentNum = document.agentedit.agent.value;
        createAndPlay(agentNum, xmlPath, true);
    }
}

function enableAgentSave() {
    var isIE6 = ((navigator.userAgent.indexOf("MSIE 6.") != -1) && (navigator.userAgent.indexOf("Opera") == -1));
    var isIE7 = (navigator.userAgent.indexOf("MSIE 7.") != -1);

    // Enable save button
    document.getElementById('agentsave').disabled = "";

    // Turn save button image 'on'
    if (isIE6 || isIE7) {
        holdFilter = document.getElementById('agentsave').runtimeStyle.filter;
        newFilter = holdFilter.replace(/save_g.png/i, "save.png");
        document.getElementById('agentsave').runtimeStyle.filter = newFilter;
    } else {
        holdSrc = document.getElementById('agentsave').src;
        newSrc = holdSrc.replace(/save_g.png/i, "save.png");
        document.getElementById('agentsave').src = newSrc;
    }
}

function disableAgentSave() {
    var isIE6 = ((navigator.userAgent.indexOf("MSIE 6.") != -1) && (navigator.userAgent.indexOf("Opera") == -1));

    // Disable save button
    document.getElementById('agentsave').disabled = "disabled";

    // Turn save button image 'off' - grayed out state
    if (isIE6) {
        holdFilter = document.getElementById('agentsave').runtimeStyle.filter;
        newFilter = holdFilter.replace(/save.png/i, "save_g.png");
        document.getElementById('agentsave').runtimeStyle.filter = newFilter;
    } else {
        holdSrc = document.getElementById('agentsave').src;
        newSrc = holdSrc.replace(/save.png/i, "save_g.png");
        document.getElementById('agentsave').src = newSrc;
    }
}

//------------------------------------------------------------------------------------------------
function generateBook(bookID) {
    var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // Not loading XML as result - do not override
            //http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Error: Cannot create an XMLHTTP instance');
        return false;
    }
    http_request.onreadystatechange = function() { generateReturn(http_request); };

    // Send the request
    http_request.open("GET", "./generate.php?book=" + bookID);
    // Send the request
    http_request.send(null);
}

function generateReturn(http_request) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            returnData = http_request.responseText;
            // Check for any reports php errors
            returnSplit = returnData.split("|");
            if (returnSplit[0].trim() != "OK" ) {
                if (returnSplit[0].trim() == "INVALID") {
                    // Invalid download attempt -- reload page to show nothing
                    document.location.href = "./download.php";
                }

                //alert(returnData);
                //document.getElementById('statuslog').innerHTML = returnData;
            } else {
                // Everything should be ok
                // Reload download window with download ID
                var bookID = returnSplit[1].trim();
                var downID = returnSplit[2].trim();
                showDownLink(bookID, downID);
            }
        } else {
            alert('There was a problem with the request.');
        }
    }
}

function showDownLink(bookID, downID) {
    newURL = "./download.php?op=download&book=" + bookID + "&down=" + downID;
    document.location.href = newURL;
}

//------------------------------------------------------------------------------------------------
function scaleImages(preview) {
    var isIE6 = ((navigator.userAgent.indexOf("MSIE 6.") != -1) && (navigator.userAgent.indexOf("Opera") == -1));

    preview = (preview == true) ? preview : false;

    $('.scale').each(function() {
        if ($(this).children('img').length) {
            var childImg = $(this).children('img').eq(0);

            // Reset any scaling
            $(childImg).css('width', '');
            $(childImg).css('height', '');
            if (!preview) {
                $(childImg).css('position', "absolute");
                $(childImg).css('left', "-9999");
            }

            // Get image dimensions
            var imgW = $(childImg).attr('width');
            var imgH = $(childImg).attr('height');

            // Get box dimensions
            var boxW = $(this).width();
            var boxH = $(this).height();

            // Get caption height
            if ($(this).children('.imgcaption').length) {
                var capH = $(this).children('.imgcaption').eq(0).height();
                boxH = boxH - capH;
            }

            // Determine scale ratios
            var scaleW = boxW / imgW;
            var scaleH = boxH / imgH;

            //alert("Img:" + imgW + "::" + imgH + "\nBox:" + boxW + "::" + boxH + "\nScale:" + scaleW + "::" + scaleH);

            /* */
            // Move image into visible area
            if (!preview) {
                $(childImg).css('position', "relative");
                $(childImg).css('left', "0");
            }
            /* */

            if ((imgW < boxW) && (imgH < boxH)) {
                return;
            }

            if (!preview) {
                if (imgW <= boxW) {
                    $(this).css('height', "auto");
                    return;
                }

                if (imgW > boxW) {
                    var newScale = (imgW/boxW) * scaleW * 100;
                    $(childImg).css('width', newScale.toFixed(2) + "%")
                    $(childImg).css('height', "auto");
                    $(this).css('height', "auto");
                    return;
                }
            } else {
                if ((scaleW > scaleH)) {
                    var newScale = (imgW/boxW) * scaleH * 100;
                    $(childImg).css('width', newScale.toFixed(2) + "%")
                    $(childImg).css('height', "auto");
                } else {
                    $(childImg).css('width', "100%")
                    $(childImg).css('height', "auto");
                }
            }
        }
    });
}

function resizeCaptions() {
    $(".scale").each(function() {
        var imgWidth = $(this).children('img').eq(0).attr('width');
        if ($(this).children('.imgcaption').length) {
            var capLeft = parseInt($(this).children('.imgcaption').eq(0).css('paddingLeft'));
            var capRight = parseInt($(this).children('.imgcaption').eq(0).css('paddingRight'));
            //alert(imgWidth + ":" + capLeft +":"+ capRight);
            $(this).children('.imgcaption').eq(0).css('width', imgWidth-capLeft-capRight);
        }
    });
}

//------------------------------------------------------------------------------------------------

// Open the specified UDL Connection item
function openTip() {
    // Hide the tip button
    document.getElementById("tipbtn").style.display = "none";
    // Show the text content
    document.getElementById("tiptop").style.display = "block";
    document.getElementById("tiptxt").style.display = "block";
}

// Close the specified UDL Connection item
function closeTip() {
    // Hide agent item
    hideTipAgent();
    // Hide the text content
    document.getElementById("tiptop").style.display = "none";
    document.getElementById("tiptxt").style.display = "none";
    // Show the tip button
    document.getElementById("tipbtn").style.display = "block";
}

function showTipAgent() {
    // Hide listen button
    document.getElementById("tipagentbtn").style.display = "none";
    // Update agent settings (sequence file)
    var agTip = FlashApplet.lookupNumber(20);
    if (agTip == null) {
        createTipAgent();
        agTip = FlashApplet.lookupNumber(20);
    } else {
        agTip.seqPath = agentTip;
        agTip.updateSettings();
    }
    // Insert into agent container
    document.getElementById('tipagent').style.marginTop = "-40px";
    agTip.insertTag('tipagent');
    // Set hide on play end
    agTip.setOnPlayStop( function() { hideTipAgent(); } );
    // Start playing
    //agTip.playSequence('01');
}

function hideTipAgent() {
    if (document.getElementById("tipagent") == null) {
        return;
    }

    // Delete the children of DOM node for the audio item
    objNode = document.getElementById("tipagent");
    // Walk DOM tree backwards
    while(objNode.hasChildNodes()) {
        objNode.removeChild(objNode.lastChild);
    }

    // Resize the div
    document.getElementById('tipagent').style.marginTop = "0px";

    // Show Listen buttons
    document.getElementById("tipagentbtn").style.display = "block";
}

function createTipAgent() {
    // sequenceFile(s) -- defined in page template -- e.g. [app_root]/xml/create_page.xml
    sequenceFile = agentTip;
    // Create agent object
	var agent = new FlashAgent(20, 'http://agents.cast.org/v6/', 'http://agents.cast.org/shared/', sequenceFile);
	agent.autoplay = true;
	agent.setSize(160, 160);
}

//------------------------------------------------------------------------------------------------

function showAgent(idnum) {
    // Hide listen button
    $('.masterModal .agentbtn').hide();

    // Update agent settings (sequence file)
    var agChar = FlashApplet.lookupNumber(idnum);
    if (agChar == null) {
        createAgent(idnum);
        agChar = FlashApplet.lookupNumber(idnum);
    } else {
        agChar.seqPath = sequenceFile[idnum];
        agChar.updateSettings();
    }

    // Insert into agent container
    $('#agentDiv').eq(0).css("marginTop", "-40px");
    agChar.insertTag('agentDiv');
    // Set hide on play end
    agChar.setOnPlayStop( function() { hideAgent2(); } );
}

function hideAgent2() {
    if (document.getElementById('agentDiv') == null) {
        return;
    }

    // Delete the children of DOM node for the audio item
    objNode = document.getElementById('agentDiv');
    // Walk DOM tree backwards
    while(objNode.hasChildNodes()) {
        objNode.removeChild(objNode.lastChild);
    }

    // Resize the div
   $('.masterModal #agentDiv').eq(0).css("marginTop", "0px");

    // Show Listen buttons
    $('.masterModal .agentbtn').show();
}

function createAgent(idnum) {
    // Create agent object
	var agent = new FlashAgent(parseInt(idnum), 'http://agents.cast.org/v6/', 'http://agents.cast.org/shared/', sequenceFile[idnum]);
	agent.autoplay = true;
	agent.setSize(160, 160);
}

//------------------------------------------------------------------------------------------------

function checkBookInfo() {
    // Ignore book info validation for 'Cancel' press
    if (document.getElementById('btnpress').value == "cancel") { return true; }

    var errorMsg = "";

    // Book title
    if (document.book_info.infotitle.value.trim() == "") {
        errorMsg += " - Please provide a Book Title.\n";
    }

    // Credits
    if ( (document.book_info.infoauthor.value.trim() == "") &&
        (document.book_info.infoillustrator.value.trim() == "") &&
        (document.book_info.infooauthor.value.trim() == "") &&
        (document.book_info.infoadaptedby.value.trim() == "") ) {
        errorMsg += " - Please provide at least one book Credit.\n";
    }

    // Content Area
    if (document.book_info.infoarea.value == "") {
        errorMsg += " - Please make a Content Area selection.\n";
    }

    // Grade Level
    if (document.book_info.glP.checked == false &&
        document.book_info.glK.checked == false &&
        document.book_info.gl1.checked == false &&
        document.book_info.gl2.checked == false &&
        document.book_info.gl3.checked == false &&
        document.book_info.gl4.checked == false &&
        document.book_info.gl6.checked == false &&
        document.book_info.gl9.checked == false &&
        document.book_info.glO.checked == false ) {
        errorMsg += " - Please provide at least one Grade Level for your book.\n";
    }

    // Agent slot check
    var slot_array = new Array();
    slot_array['1'] = document.book_info.agent_slot_1.value;
    slot_array['2'] = document.book_info.agent_slot_2.value;
    slot_array['3'] = document.book_info.agent_slot_3.value;
    slot_array['4'] = document.book_info.agent_slot_4.value;
    slot_array['5'] = document.book_info.agent_slot_5.value;
    slot_array['6'] = document.book_info.agent_slot_6.value;
    slot_array['a'] = document.book_info.agent_slot_a.value;

    var slot_error = false;
    if (slot_array.count('1') > 1) { slot_error = true; }
    if (slot_array.count('2') > 1) { slot_error = true; }
    if (slot_array.count('3') > 1) { slot_error = true; }

    if ( (slot_array.count('1') == 0) || (slot_array.count('2') == 0) || (slot_array.count('3') == 0) ) {
       errorMsg += " - Please select three agents to use with this book.\n";
    }

    if (slot_error) {
       errorMsg += " - You may only use one coach per available slot.\n";
    }

    if (errorMsg != "") {
        alert("A few issues with your Book Information have been found:\n\n" + errorMsg + "\n");
        return false;
    }

    return true;
}


function agentSelUpate(agentId) {
    //var agentList = new Array('1','2','3','4','5','6','a');
    var agentList = new Array('1','2','3','4','a');

    eval("var setValue = document.book_info.agent_slot_" + agentId + ".value");

    // Loop through all agent selection items
    for (var i=0; i < agentList.length; i++) {
        // Skip matching selection element
        if (agentList[i] != agentId) {
            eval("var tmpValue = document.book_info.agent_slot_" + agentList[i] + ".value");
            // If match, set previous selection to '--'
            if (setValue == tmpValue) {
                eval("document.book_info.agent_slot_" + agentList[i] + ".selectedIndex = 0");
            }
        }
    }
}


function checkTermInfo() {
    // Ignore term validation for 'Cancel' press
    if (document.getElementById('btnpress').value == "cancel") {
        history.back();
        return false;
    }

    // Make sure we have a non-empty term (after trimming all whitespace)
    var word_term = "";
    word_term = document.glossary_term.glossterm.value;
    word_term = word_term.trim();

    if (word_term == "") {
        // Show error message
        alert("Please supply a glossary term.");
        return false;
    }

    return true;
}

function noenter(e) {
    var key;

    if(window.event) {
        //IE
        key = window.event.keyCode;
    } else {
        // Firefox
        key = e.which;
    }
    if(key == 13) {
        return false;
    } else {
        return true;
    }
}

//------------------------------------------------------------------------------------------------
// Remove 'fancy' word formatting
/*
function cleanString(input) {
    var replacements = {
        "\xa0": " ",
        "\xa9": "(c)",
        "\xae": "(r)",
        "\xb7": "*",
        "\u2018": "'",
        "\u2019": "'",
        "\u201c": '"',
        "\u201d": '"',
        "\u2026": "...",
        "\u2002": " ",
        "\u2003": " ",
        "\u2009": " ",
        "\u2013": "-",
        "\u2014": "--",
        "\u2122": "(tm)"};
    var regex = {};
    for (key in replacements) {
        regex[key] = new RegExp(key, 'g');
    }

    var output = input.replace(regex[key], replacements[key]);

    return output;
}

UTF8 = {
	encode: function(s){
		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
		);
		return s.join("");
	},
	decode: function(s){
		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
			((a = s[i][c](0)) & 0x80) &&
			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
		);
		return s.join("");
	}
};
*/

//------------------------------------------------------------------------------------------------
// String.trim() - simulate functionality via regex
String.prototype.trim = function() {
    // skip leading and trailing whitespace
    // and return everything in between
    var x = this;
    x = x.replace(/^\s*(.*)/, "$1");
    x = x.replace(/(.*?)\s*$/, "$1");
    return x;
}

// Array.in_array_minus(search_term) - Determine if item is contained within an array
// Snippet from:  http://andrew.hedges.name/experiments/javascript_optimization/in_array.html
// Further modifications found in comments at: http://code.mikebrittain.com/?p=8
Array.prototype.in_array_minus = function (search_term) {
   var i = this.length;
   do {
      if (this[i] === search_term) {
         return true;
      }
   } while (i--);
   return false;
}

// Based on in_array_minus - but it returns the key value
// Obviously this only works with contiguous non-associative arrays
Array.prototype.in_array_minus_key = function (search_term) {
   var i = this.length;
   do {
      if (this[i] === search_term) {
         return i;
      }
   } while (i--);
   return false;
}

// String.nl2br() - replace new-lines with <br />
String.prototype.nl2br = function() {
    var x = this;
    x = x.replace(/\n/gi, "<br />");
    return x;
}

// String.stripnl() - strip new-lines from text strings
String.prototype.stripnl = function() {
    var x = this;
    x = x.replace(/\n*/gi, "");
    x = x.replace(/\r*/gi, "");
    return x;
}

Array.prototype.count = function(element){
    var count = 0;

    // Works on string or mixed indexed arrays
    for (i in this) {
        if(this[i] == element){
            count += 1;
        }
    }
    /*
    // Only works for numeric indexed arrays
    for(var i = 0; i < this.length; i++){
        if(this[i] == element){
            count += 1;
        }
    }
    */
    return count;
}
