function addEvent (obj, evType, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, true);
        return true;
    } else if (obj.attachEvent) {
        return obj.attachEvent("on" + evType, fn);
    } else {
        return false;
    }
}

function checkFlashVer() {
    // Check for Flash version 7+
    var hasReqestedVersion = DetectFlashVer(7, 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 7 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 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() {
    // Create popup window
    var windowXY = findWindowCenter(650, 500);
    var urlPath = "./window.php?src=videos";
    var winPop = open(urlPath, 'Video', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupVideoText() {
    // Create popup window
    var windowXY = findWindowCenter(550, 450);
    var urlPath = "./window.php?src=videotext";
    var winPop = open(urlPath, 'VideoText', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupAbout() {
    // Create popup window
    var windowXY = findWindowCenter(600, 560);
    var urlPath = "./window.php?src=about";
    var winPop = open(urlPath, 'About', windowXY + 'menubar=no,toolbar=yes,location=yes,scrollbars=yes,status=yes,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

function popupFAQ() {
    // Create popup window
    var windowXY = findWindowCenter(600, 560);
    var urlPath = "./window.php?src=faq";
    var winPop = open(urlPath, 'FAQ', windowXY + 'menubar=no,toolbar=yes,location=yes,scrollbars=yes,status=yes,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

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

function openFeedback(srcID, questionFlag) {
    // Optional argument
    if (!questionFlag) var questionFlag = 0;

    // Hide any open feedback item
    closeFeedback();
    // Hide selected button -- *button has to be visible for offset to work correctly* -- Hide later
    //$('#'+srcID+"_btn").css('visibility', 'hidden');
    // Show selected feedback
    $('#'+srcID).css('left', '-999px');
    $('#'+srcID).show();
    // Position feedback box
    positionFeedback(srcID, questionFlag);
}

function closeFeedback() {
    $('.feedback:visible').hide();
    $('.agbutton:hidden').css('visibility', 'visible');
}

function positionFeedback(srcID, questionFlag) {
    var siND = null;
    var fbID = "";

    // Find location of agent button
    var btnLoc = $('#'+srcID+"_btn").offset();
    // Find corner locations
    var btnTop = btnLoc.top;
    var btnLeft = btnLoc.left;
    var btnBot = btnTop + $('#'+srcID+"_btn").height();
    var btnRight = btnLeft + $('#'+srcID+"_btn").width();

    if (questionFlag == 1) {
        switch(srcID) {
            case 'penguin': {
                btnRight = 797;
                break;
            }
            case 'gecko': {
                btnRight = 541;
                break;
            }
        }
    }

    // Hide selected button
    $('#'+srcID+"_btn").css('visibility', 'hidden');

    // Get box and document dimensions
    var docHeight = $(document).height();
    var docWidth = $(document).width();
    var boxHeight = $('#'+srcID).height();
    var boxWidth = $('#'+srcID).width();
    var boxOffset = 10;

    // Determine box coordinates to make sure box appears within document bounds
    var boxTop = btnTop;
    var boxLeft = btnRight - boxWidth - boxOffset;
    if ((btnTop + boxHeight) > docHeight) {
        boxTop = docHeight - boxHeight - 5;
    }
    if (boxLeft + boxWidth > docWidth) {
        boxLeft = docWidth - boxWidth - 5;
    }

    // Position box
    $('#'+srcID).css('top', boxTop +'px');
    $('#'+srcID).css('left', boxLeft +'px');
}

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

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=\"336\" data=\"./flash/flv_player/flvplayer.swf?file=../../video/" + filename  + "&autostart=false&clicktext=" + playStr + "\" wmode=\"transparent\" allowScriptAccess=\"always\">";
    outputHTML += "<param name=\"movie\" value=\"./flash/flv_player/flvplayer.swf?file=../../video/" + filename + "&autostart=false&clicktext=" + playStr + "\" />";
    outputHTML += "<param name=\"wmode\" value=\"transparent\" />";
    outputHTML += "<param name=\"allowScriptAccess\" value=\"always\" />";
    outputHTML += "</object>";
    // Add new video item
    document.getElementById("videohome").innerHTML = outputHTML;
}

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

function createAgent(agentID, xmlPath) {
    if (DragItem['dragAgent' + agentID]) return;
    var agent = new FlashAgent(agentID, 'http://agents.cast.org/v5/', 'http://agents.cast.org/shared/', xmlPath);
    agent.setOnPlayStop( function() { agent.dragBox.hide(); } );
    agent.setSize(200,200);
    agent.createDragBox();
    agent.dragBox.clearOnHide = true;
    agent.dragBox.handleScroll = true;
    agent.dragBox.show();
}

function playAgent(agentType, sequenceID) {
    // Set agentID based on agentType
    switch(agentType) {
        case 'penguin': { agentID = 1; break;}
        case 'gecko':   { agentID = 2; break;}
        case 'dog':     { agentID = 3; break;}
        case 'giraffe': { agentID = 4; break;}
    }

    // Build path to xml call - actually calls a dynamic page
    // use '|' as delimeter to work around &'s getting lost
    xmlPath = "/agentxml.php?q=" + agentType + "|" + sequenceID;

    var agBox = FlashApplet.lookupNumber(agentID);
    if (agBox == null) {
        createAgent(agentID, xmlPath);
    } else {
        agBox.seqPath = xmlPath;
        agBox.dragBox.show();
        agBox.updateSettings();
    }
}

//------------------------------------------------------------------------------------------------
// Page updated warning message
function setPageUpdatedWarning() {
    $('a').each(function(i){
        if ( $(this).is('.boxagent') || $(this).is('.ignore_update') || ($(this).attr("target") == "_blank") ) {
            // Do nothing
        } else {
            // Add checkPageUpdated function call
            $(this).bind("click", function() { return checkPageUpdated(); });
        }
    });
}

function checkPageUpdated() {
    var haltLink = false;
    //var prevVal = document.forms[0].reflecttext_prev.value;
    //var currVal = document.forms[0].reflecttext.value;

    //alert(prevVal + "\n::\n" + currVal);
    //alert("EQ: " + prevVal == currVal);

    if ((slider_updated == 1) || (reflecttext_updated == 1)) {
        haltLink = true;
    }

    if (haltLink) {
        // Show warning box
        followConfirm = confirm("You have entered information without saving.\n\nAre you sure you leave this page without saving your changes?\n\nPress OK to continue without saving.\nPress CANCEL to return to the page so you may save your work.");
        return followConfirm;
    }
}

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

// 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;
}
