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 Lesson Builder.\n\n CAST UDL Lesson 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 checkForSafari() {
    // Check to see if the browser is Safari
    var agt=navigator.userAgent.toLowerCase();
    var is_safari = ((agt.indexOf('safari') != -1) && (agt.indexOf('mac') != -1)) ? true : false;

    if (is_safari) {
        alert("*** W A R N I N G *** W A R N I N G ***\n\nThe CAST UDL Lesson Builder uses a text editor that is not fully compatible with 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 findWindowRight(winWidth, winHeight) {
    // Window origin
    if (window.innerHeight) {
        originX = screenX + (window.outerWidth - window.innerWidth);
        originY = screenY + (window.outerHeight - window.innerHeight);
    } else {
        originX = screenLeft;
        originY = screenTop;
    }

    // Window width
    if (window.innerWidth) {
        theWidth=window.innerWidth;
    } else if (document.documentElement && document.documentElement.clientWidth) {
        theWidth=document.documentElement.clientWidth;
    } else if (document.body) {
        theWidth=document.body.clientWidth;
    }

    // Window height
    if (window.innerHeight) {
        theHeight=window.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        theHeight=document.documentElement.clientHeight;
    } else if (document.body) {
        theHeight=document.body.clientHeight;
    }

    // Target window to open on right side of browswer window
    var windowX = originY + (theHeight/2) - (winHeight/2);
    var windowY = originX + theWidth - winWidth;

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

    return locationString;
}

function popupRight(targetSrc) {
    // Create popup window
    var windowXY = findWindowRight(350, 300);
    var urlPath = "./window.php?src=" + targetSrc;
    var winPop = open(urlPath, 'MoreInfo', windowXY + ',scrollbars=yes,status=no,resizable=yes');
    if (!winPop.opener) winPop.opener = self;
    winPop.focus();
}

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 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 popupResources(targetSrc) {
    // Create popup window
    var windowXY = findWindowCenter(650, 520);
    var urlPath = "./window.php?src=" + targetSrc;
    var winPop = open(urlPath, 'Resources', 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=\"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 printPlan() {
    var errorMsg = "";
    var openCount = 0;
    // Check to see if any edit boxes are open
    var editList = new Array('eb_overview', 'eb_unitdesc', 'eb_lessondesc', 'eb_standards', 'eb_unitgoals', 'eb_lessongoals', 'eb_anticipatory', 'eb_introduce', 'eb_guided', 'eb_independent', 'eb_wrapup', 'eb_formative', 'eb_summative', 'eb_addresource', 'eb_editresource');
    for (var i=0; i < editList.length; i++ ) {
        if (document.getElementById(editList[i]) != null) {
            if (document.getElementById(editList[i]).style.display == "block") {
                openCount++;
            }
        }
    }

    if (openCount > 0) {
        alert("Please Save or Cancel any content you are editing before attempting to print.");
    } else {
        window.print();
    }
}

function editOpen(id) {
    // Hide the edit link
    document.getElementById('el_' + id).style.display = "none";
    // Hide the static content
    document.getElementById('es_' + id).style.display = "none";
    // Show the edit box
    document.getElementById('eb_' + id).style.display = "block";
}

function editClose(id) {
    // Hide the edit box
    document.getElementById('eb_' + id).style.display = "none";
    // Show the edit link
    document.getElementById('el_' + id).style.display = "inline";
    // Show the static content
    document.getElementById('es_' + id).style.display = "block";
}

function editContent(id) {
    // Reset fields
    editReset(id);
    // Open edit box
    editOpen(id);
}

function editCancel(id) {
    // Reset fields
    editReset(id);
    // Close edit box
    editClose(id);
}

function editReset(id) {
    //Reset form fields to match the static content - by using the static content to make the resets
    if (id == 'overview') {
        // Update title form field
        document.getElementById('overtitle').value = document.getElementById('es_title').innerHTML;
        // Update duration form field
        document.getElementById('overduration').value = document.getElementById('es_duration').innerHTML;
        // Update subject select box
        for (var i=0; i< subjectArray.length; i++ ) {
            if (subjectArray[i] == document.getElementById('es_subject').innerHTML) {
                document.getElementById('oversubject').selectedIndex = i;
            }
        }
        // Unset all checkboxes
        document.getElementById('glP').checked = false;
        document.getElementById('gl3').checked = false;
        document.getElementById('gl6').checked = false;
        document.getElementById('gl9').checked = false;
        // Update grade level checkboxes
        var gradeList = document.getElementById('es_grades').innerHTML.split(', ');
        for (var i=0; i< gradeList.length; i++ ) {
            if(gradeList[i] != "") {
                tempName = 'gl' + gradeList[i].substr(0,1);
                document.getElementById(tempName).checked = true;
            }
        }
    } else if (id == 'materials') {
        alert("MATERIALS NOT SUPPORTED YET!");
    } else {
        if (tinyMCE != false) {
            // Update edit box content (needed for Mozilla/Firefox)
            document.getElementById('mce_' + id).value = document.getElementById('es_' + id).innerHTML;
            tinyMCE.updateContent('mce_' + id);
        }
    }
}

function editSave(id, pid) {
    // Prepare save data
    var saveItems = new Array();
    saveItems['planid'] = pid;
    saveItems['section'] = id;

    try {
        if (id == 'overview') {
            // Check for subject
            var errorMsg = "";
            if (document.getElementById('es_subject').value == "") {
                errorMsg += " - Select a subject for the Lesson Plan.\n";
            }
            if (errorMsg != "" ) {
                errorMsg = "Please resolve the following issues with the new resource:\n" + errorMsg;
                alert(errorMsg);
                return false;
            }

            // Update static content
            document.getElementById('es_title').innerHTML = document.getElementById('overtitle').value;
            document.getElementById('es_duration').innerHTML = document.getElementById('overduration').value;
            document.getElementById('es_subject').innerHTML = subjectArray[document.getElementById('oversubject').value];
            var gradeText = "";
            gradeText += (document.getElementById('glP').checked) ? "Prek-K&ndash;2, " : "";
            gradeText += (document.getElementById('gl3').checked) ? "3&ndash;5, " : "";
            gradeText += (document.getElementById('gl6').checked) ? "6&ndash;8, " : "";
            gradeText += (document.getElementById('gl9').checked) ? "9&ndash;12, " : "";
            document.getElementById('es_grades').innerHTML = gradeText.substr(0, gradeText.length-2);
            // Add content pieces to save data
            saveItems['overtitle'] = document.getElementById('overtitle').value;
            saveItems['oversubject'] = document.getElementById('oversubject').value;
            saveItems['overduration'] = document.getElementById('overduration').value;
            saveItems['glP'] = document.getElementById('glP').checked;
            saveItems['gl3'] = document.getElementById('gl3').checked;
            saveItems['gl6'] = document.getElementById('gl6').checked;
            saveItems['gl9'] = document.getElementById('gl9').checked;
        } else if (id == 'materials') {
            alert("MATERIALS NOT SUPPORTED YET!");
        } else {
            if (tinyMCE != false) {
                // Force TinyMCE to update the form data
                tinyMCE.execInstanceCommand('mce_' + id, 'mceFocus');
                tinyMCE.triggerSave();
            }
            // Read saved content
            var newContent = document.getElementById('mce_' + id).value;
            newContent = newContent.trim();
            //alert(document.getElementById('mce_' + id).value);
            // Update the static content
            document.getElementById('es_' + id).innerHTML = newContent;
            // Add content pieces to save data
            saveItems['mce_' + id] = newContent;
        }

        // Close edit box
        editClose(id);

        // Send items back to be saved
        storeContent(saveItems);

        // Stop form submit
        return false;
    } catch(err) {
        //Handle errors here
        alert(err);
        // Stop form submit
        return false;
    }
}

function storeContent(saveItems) {
    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() { storeReturn(http_request); };

    // Specify use of POST to send data
    http_request.open("POST", "./store.php");

    // Serialize the save data with PHP compatible method
    var php = new PHP_Serializer();
    saveString = php.serialize(saveItems);

    // URL encode the serialized string for sending
    saveStringEnc = WebToolKit.url.encode(saveString);

    // Send items to be saved
    http_request.send("saveData=" + saveStringEnc);
}

function storeReturn(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("|");

            //alert("RETURN DATA:\n" + returnData);

            if (returnSplit[0].trim() != "OK" ) {
                if (returnSplit[0].trim() == "ERROR") {
                    switch(returnSplit[1].trim()) {
                        case "INVALID_SESSION": {
                            // Send them back to home page
                            document.location.href = "./";
                            break;
                        }
                        case "INVALID_PLAN": {
                            // Send them back to plan list
                            document.location.href = "./create.php";
                            break;
                        }
                        default: {
                            // Show error message
                            alert("Error:\n" + returnSplit[1].trim());
                            break;
                        }
                    }
                }
            } else {
                // Everything should be OK
            }
        } else {
            alert('There was a problem with the request.');
        }
    }
}

function resourceAddNew() {
    // Reset fields
    resourceAddReset();
    // Open edit box
    resourceAddOpen();
}

function resourceAddCancel() {
    // Reset fields
    resourceAddReset();
    // Close edit box
    resourceAddClose();
}

function resourceAddReset() {
    // Blank out the form fields
    document.getElementById('ef_addresource').reset();
    if (tinyMCE != false) {
        // Force TinyMCE to update
        tinyMCE.updateContent('mce_add_description');
    }
}

function resourceAddOpen() {
    // Hide the edit button
    document.getElementById('el_addresource').style.display = "none";
    // Show the edit box
    document.getElementById('eb_addresource').style.display = "block";
}

function resourceAddClose() {
    // Show the edit button
    document.getElementById('el_addresource').style.display = "block";
    // Hide the edit box
    document.getElementById('eb_addresource').style.display = "none";
}

function resourceAddSave() {
    if (tinyMCE != false) {
        // Force TinyMCE to update the form data
        tinyMCE.execInstanceCommand('mce_add_description', 'mceFocus');
        tinyMCE.triggerSave();
    }

    var errorMsg = "";

    // Check for subject
    if (document.getElementById('addsubject').value == "") {
        errorMsg += " - Select a subject for the Resource.\n";
    }
    // Check for category
    if (document.getElementById('addcategory').value == "") {
        errorMsg += " - Select a category for the Resource.\n";
    }

    if (errorMsg != "" ) {
        errorMsg = "Please resolve the following issues with the new Resource:\n" + errorMsg;
        alert(errorMsg);
        //return false;
    } else {
        // Submit form
        document.getElementById('ef_addresource').submit();
    }
}

function resourceAddSavePlan() {
    if (tinyMCE != false) {
        // Force TinyMCE to update the form data
        tinyMCE.execInstanceCommand('mce_add_description', 'mceFocus');
        tinyMCE.triggerSave();
    }

    var errorMsg = "";

    // Check for category
    if (document.getElementById('addcategory').value == "") {
        errorMsg += " - Select a category for the Resource.\n";
    }

    if (errorMsg != "" ) {
        errorMsg = "Please resolve the following issues with the new Resource:\n" + errorMsg;
        alert(errorMsg);
        //return false;
    } else {
        // Submit form
        document.getElementById('ef_addresource').submit();
    }
}

function resourceEditOpen() {
    // Show the edit box
    document.getElementById('eb_editresource').style.display = "block";
    // Hide the add button
    document.getElementById('el_addresource').style.display = "none";
}

function resourceEditClose() {
    // Hide the edit box
    document.getElementById('eb_editresource').style.display = "none";
    // Show the add button
    document.getElementById('el_addresource').style.display = "block";
}

function resourceEditCancel() {
    // Reset fields
    resourceEditReset();
    // Close edit box
    resourceEditClose();
}

function resourceEditReset() {
    // Blank out the form fields
    document.getElementById('ef_editresource').reset();
    if (tinyMCE != false) {
        // Force TinyMCE to update
        tinyMCE.updateContent('mce_edit_description');
    }
}

function resourceEdit(id, subjectid, categoryid) {
    // Open the edit box
    resourceEditOpen();
    // Copy the information to the edit box
    document.getElementById('editid').value = id;
    document.getElementById('editsubject').selectedIndex = subjectid;
    document.getElementById('editcategory').selectedIndex = categoryid;
    document.getElementById('edittitle').value = document.getElementById('restitle_' + id).innerHTML;
    document.getElementById('editurl').value = document.getElementById('resurl_' + id).innerHTML;
    document.getElementById('mce_edit_description').value = document.getElementById('resdesc_' + id).innerHTML;
    if (tinyMCE != false) {
        // Update MCE
        tinyMCE.updateContent('mce_edit_description');
    }
}

function resourceEditPlan(id, subjectid, categoryid) {
    // Open the edit box
    resourceEditOpen();
    // Copy the information to the edit box
    document.getElementById('editid').value = id;
    //document.getElementById('editsubject').selectedIndex = subjectid;
    document.getElementById('editcategory').selectedIndex = categoryid;
    document.getElementById('edittitle').value = document.getElementById('restitle_' + id).innerHTML;
    document.getElementById('editurl').value = document.getElementById('resurl_' + id).innerHTML;
    document.getElementById('mce_edit_description').value = document.getElementById('resdesc_' + id).innerHTML;
    if (tinyMCE != false) {
        // Update MCE
        tinyMCE.updateContent('mce_edit_description');
    }
}

function resourceEditSave() {
    if (tinyMCE != false) {
        // Force TinyMCE to update the form data
        tinyMCE.execInstanceCommand('mce_edit_description', 'mceFocus');
        tinyMCE.triggerSave();
    }

    var errorMsg = "";

    // Check for subject
    if (document.getElementById('editsubject').value == "") {
        errorMsg += " - Select a subject for the Resource.\n";
    }
    // Check for category
    if (document.getElementById('editcategory').value == "") {
        errorMsg += " - Select a category for the Resource.\n";
    }

    if (errorMsg != "" ) {
        errorMsg = "Please resolve the following issues with the Resource:\n" + errorMsg;
        alert(errorMsg);
        //return false;
    } else {
        // Submit form
        document.getElementById('ef_editresource').submit();
    }
}

function resourceEditSavePlan() {
    if (tinyMCE != false) {
        // Force TinyMCE to update the form data
        tinyMCE.execInstanceCommand('mce_edit_description', 'mceFocus');
        tinyMCE.triggerSave();
    }

    var errorMsg = "";

    // Check for category
    if (document.getElementById('editcategory').value == "") {
        errorMsg += " - Select a category for the Resource.\n";
    }

    if (errorMsg != "" ) {
        errorMsg = "Please resolve the following issues with the Resource:\n" + errorMsg;
        alert(errorMsg);
        //return false;
    } else {
        // Submit form
        document.getElementById('ef_editresource').submit();
    }
}

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

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