/* Returns a cross browser compatible height or width value for the window */
function getDimension(dim){
    if (dim === "height"){
       if (window.innerHeight){
          return window.innerHeight;
       }
       else if (document.documentElement.clientHeight){
          return document.documentElement.clientHeight;
       }
       else if (document.body.clientHeight){
          return document.body.clientHeight;
       }
    }
    else if (dim === "width"){
       if (window.innerWidth){
          return window.innerWidth;
       }
       else if (document.documentElement.clientWidth){
          return document.documentElement.clientWidth;
       }
       else if (document.body.clientWidth){
          return document.body.clientWidth;
       }
    }
    return undefined;
}

function SlideSorter(pId, styleStr, cId){
    
    // private instance variables
    var objRef = this;
    var parentId = pId;
    var contentMarginStyle = styleStr;
    var contentId = cId;
    var fullScreenMargins = "0.5em 0 0.5em 0.5em";
    var slides = undefined;
    var modSlides = [];
    var bodyContent = $("#bodyContent *");
    var pickedupId = "";
    var mouseOffsetX = 0;
    var mouseOffsetY = 0;
    var panelKeys = {"slidePanel" : "divEditPanel"};
    var orientation = "vertical";
    var locked = false;
    var panelId = "divEditPanel";
    var slideIndex = 0;
    var panelDivisions = [];
    var moveposition = 0;
    var slidePickedUp = 0;
    var prevOrientation = orientation;
    
    this.setParentId = function(pid){
       parentId = pid;
    };
    this.setSlides = function(s){
       slides = s;
       modSlides = s;
    };
    
    this.getParentId = function(){
       return parentId;
    };
    this.getSlides = function(){
       return slides;
    };
    
    // Window resize handler
    var windResize = function(ev){
        $("#" + contentId).css("height", getDimension("height") - 100);
        //$("#divEditPanel").css("top", window.innerHeight - 175).css("width", window.innerWidth - 350);
    };
    
    // 
    var enlargeSlidePic = function(e){
        $("#slidePanelTable td .rew").css("border-width", "2px");
        var ta = "rq" + e.target.id.substring(6).toString();
        document.getElementById(ta).style.borderWidth = "5px";
    };
    
    // 
    var gotoSlide = function(event){

        if (orientation === "grid"){
            orientation = "vertical";
            createSorter(null);
        }

        $("#slidePanelTable td .rew").css("border-color", "#000000").css("background-color", "#FFFFFF");
        slideIndex = event.target.id.substring(6) - 1;
        $("#rq" + (slideIndex + 1).toString()).css("border-color", "blue").css("background-color", "#FFFF70");
        //var ta = "rq" + (slideIndex + 1).toString();
        //document.getElementById(ta).style.borderColor = "blue";
        //document.getElementById(ta).style.backgroundColor = "#FFFF70";
        $("#bodyContent *").hide();
        slides[slideIndex][4].show();
    };

    var remove = function(){
        $("#slidePanel, #" + panelId).remove();
        $("#" + contentId).css("margin", contentMarginStyle).css("position", "relative").css("top", "auto").css("right", "auto").css("left", "auto").css("overflow-y", "auto").css("height", "auto");
        $("#bodyContent *, #col1hidelink, div#column-one, div#p-personal, div#p-cactions, div#footer").show();
    };

    // These methods allow the slide sorter to be picked up and moved around
    var move = function(e){
        //alert(e.screenY - mouseOffsetY);
        $("#" + pickedupId).css("left", (e.screenX - mouseOffsetX) + "px");
        $("#" + pickedupId).css("top", (e.screenY - mouseOffsetY) + "px");
    };

    var moveP = function(e){
        var val;

        if (orientation === "vertical"){
           $("#" + pickedupId).css("left", (150) + "px");
           $("#" + pickedupId).css("top", (e.screenY - 200) + "px");
        }
        else{
           $("#" + pickedupId).css("left", (e.screenX - parseInt($("#divEditPanel").css("left"), 10)) + "px");
           $("#" + pickedupId).css("top", (0) + "px");
        }
        $(".pods").hide();

        if (orientation === "vertical"){
           val = e.screenY + $("#sidp").get(0).scrollTop;
        }
        else{
           val = e.screenX + $("#sidp").get(0).scrollLeft;
        }
        for (var i = 0; i < panelDivisions.length; i++){
           if (val > panelDivisions[i].top && val < panelDivisions[i].bottom){
               $("#bb" + i).show();
               moveposition = i - 1;
               break;
           }
        }
    };
    var pickup = function(e){
        pickedupId = panelKeys[e.target.id];
        $("#" + e.target.id).unbind("mousedown", pickup);
        slidePickedUp = parseInt(e.target.id.substring(4), 10) - 1;
        if (e.target.id.substring(0, 4) === "hand"){
           $(document).bind("mousemove", moveP);
           $(document).bind("keydown", maindrop);
           $("#" + pickedupId).css("position", "absolute").css("width", "175px");
        }
        else{
           //$("#" + e.target.id).bind("mouseup", drop);
           $(document).bind("mouseup", drop);
           $(document).bind("mousemove", move);
           $("#" + pickedupId).unbind("mousedown", pickup);
        }
        if (!$("#" + "divEditPanel").css("left")){
            $("#" + pickedupId).css("left", 105);
            $("#" + pickedupId).css("top", 105);
        }
        mouseOffsetX = e.screenX - parseInt($("#" + pickedupId).css("left"));
        mouseOffsetY = e.screenY - parseInt($("#" + pickedupId).css("top"));
        if (!mouseOffsetX || !mouseOffsetY){
            mouseOffsetX = 185;
            mouseOffsetY = 105;
        }
    };
    var maindrop = function(e){
        $(document).unbind("keydown", maindrop);
        $(document).unbind("mousemove", moveP);
        $(".pods").hide();
        
        //$("#" + pickedupId).unbind("mouseup", dropIN);
        $("#" + pickedupId).bind("mousedown", pickup);
        moveSlide(moveposition, pickedupId);
        
        $("#slidePanelTable td .rew").css("border-color", "#000000").css("background-color", "#FFFFFF");
        $("#rq" + (slideIndex + 1).toString()).css("border-color", "blue").css("background-color", "#FFFF70");
        //var ta = "rq" + (slideIndex + 1).toString();
        //document.getElementById(ta).style.borderColor = "blue";
        //document.getElementById(ta).style.backgroundColor = "#FFFF70";
        //$("#" + pickedupId).css("position", "relative").css("left", 0).css("top", 0).css("width", "auto");
    };
    var drop = function(e){
        //pickedupId = panelKeys[e.target.id];
        pickedupId = "divEditPanel";
        $(document).unbind("mousemove", move);
        //$("#" + pickedupId).unbind("mouseup", drop);
        $(document).unbind("mouseup", drop);
        $("#" + pickedupId).bind("mousedown", pickup);
    };

    var moveSlide = function(position, id){
        var moveIndex = parseInt(id.substring(2), 10) - 1, temp, ta;
        
        //if (Math.abs((moveIndex + 1) - (position + 1)) < 2) position = moveIndex;
        //alert((moveIndex + 1) + " " + (position + 1));
        
        if (moveIndex > position) position++;
        
        if (position < 0) position = 0;
        if (position >= modSlides.length) position = (modSlides.length - 1);
        if (slideIndex === moveIndex){
           slideIndex = position;
        }

        $("#" + pickedupId).css("position", "relative").css("left", 0).css("top", 0).css("width", "auto");
        $(".hyts").attr("innerHTML", "");
        temp = modSlides[moveIndex];
        modSlides.splice(moveIndex, 1);
        modSlides.splice(position, 0, temp);
        attachClones(modSlides);
    };

    var attachClones = function(sli){
        var a, b, clon, par, arr = [], oarr = [], rset = [], i;

        // Add the mini slide previews to the page
        for (i = 0; i < sli.length; i++){
            clon = sli[i][4].clone(false);
            clon.appendTo("#slideP" + (i + 1).toString());
            clon.show().css("cursor", "pointer").bind("mouseover", enlargeSlidePic).bind("click", gotoSlide).attr("id", "slideP" + (i + 1).toString());
            clon.find("*").show().attr("id", "slideP" + (i + 1).toString()).css("cursor", "pointer").bind("mouseover", enlargeSlidePic).bind("click", gotoSlide);
            clon.find("img").attr("width", "35").attr("height", "30");
        }
    };

    var createGridView = function(){
        
        var slidearea = "", i = 0, y = 1;
        
        slidearea += '<tr>';
        
        for (i = 1; i < slides.length + 1; i++){
           if ((y % 7) === 0) slidearea += '</tr><tr>';
           
           if (i != 1) y++;
           
           slidearea +=   '<td>' +
                            '<div id="rq' + i + '" class="rew" style="border-style:solid;border-width:3px;border-color:#000000;">' +
                              '<div class="handles" id="hand' + i + '" style="cursor:pointer;width:100%;height:15px;background-color:#484848;">' +
                              '</div>' +
                              '<div class="hyts" id = "slideP' + i + '" style = "overflow: hidden;font-size: 0.4em;text-align: center;width: 100%; height: 100px;margin-bottom:2em;">' +
                              '</div>' +
                            '</div>' +
                          '</td>';
        }
        slidearea += '</tr>';
        
        return slidearea;
    };
    
    var createMiniSlides = function(){

        var slidearea = "", topC = 0, bottomC = 100, i = 0;
        panelDivisions = [];

        if (orientation === "vertical"){
            slidearea += '<tr>' +
                           '<td class="pods" id="bb' + i + '" style="display:none;height:1px;width:100%;background-color:#000000;">' +
                           '</td>' +
                         '</tr>';
            panelDivisions.push({top:topC, bottom:bottomC});
            topC += 135;
            bottomC += 135;
        }
        else{
            slidearea += '<td>' +
                           '<td class="pods" id="bb' + i + '" style="display:none;height:100%;width:1px;background-color:#000000;">' +
                           '</td>' +
                         '</td>';
            panelDivisions.push({top:topC, bottom:bottomC});
            topC += 180;
            bottomC += 180;
        }

        for (i = 1; i < slides.length + 1; i++){
            if (orientation === "vertical"){
                   slidearea += '<tr id="sp' + i + '">' +
                                  '<td>' +
                                    '<div id="rq' + i + '" class="rew" style="border-style:solid;border-width:3px;border-color:#000000;">' +
                                      '<div class="handles" id="hand' + i + '" style="cursor:pointer;width:100%;height:15px;background-color:#484848;">' +
                                      '</div>' +
                                      '<div class="hyts" id = "slideP' + i + '" style = "overflow: hidden;font-size: 0.4em;text-align: center;width: 100%; height: 100px;margin-bottom:2em;">' +
                                      '</div>' +
                                    '</div>' +
                                  '</td>' +
                                '</tr>' +
                                '<tr>' +
                                  '<td class="pods" id="bb' + i + '" style="display:none;height:1px;width:100%;background-color:#000000;">' +
                                  '</td>' +
                                '</tr>';
                   panelDivisions.push({top:topC, bottom:bottomC});
                   topC += 135;
                   bottomC += 135;
             }
             else{
                   slidearea += '<td><div id="rq' + i + '" class="rew" style="border-style:solid;border-width:3px;border-color:#000000;"><div class="handles" id="hand' + i + '" style="cursor:pointer;width:100%;height:15px;background-color:#484848;"></div><div class="hyts" id = "slideP' + i + '"' + 
                   'style = "overflow: hidden;font-size: 0.4em;text-align: center;width: 175px; height: 100px;margin-bottom:2em;">' +
                   '</div></div></td>' +
                   '<td>' +
                   '<td class="pods" id="bb' + i + '" style="display:none;height:100%;width:1px;background-color:#000000;">' +
                   '</td>' +
                   '</td>';
                   panelDivisions.push({top:topC, bottom:bottomC});
                   topC += 180;
                   bottomC += 180;
             }
             panelKeys["hand" + i] = ("rq" + i);
        }
        
        if (orientation === "horizontal") slidearea += "</tr>";
        
        return slidearea;
    };
    
    var createSorter = function(e){
        
        var id = "slidePanel", slidePane = "", i = 1;
        
        if ($("#globalWrapper *").is("#" + panelId)){
            $("#" + panelId).remove();

            if (!e){
                orientation = orientation;
            }
            else if (e.target.id === "con86"){
               if (orientation === "vertical"){
                  orientation = "horizontal";
               }
               else if (orientation === "horizontal"){
                  orientation = "vertical";
               }
               else if (orientation === "grid"){
                  orientation = prevOrientation;
               }
            }
            else if (e.target.id === "con85"){
               if (orientation === "grid"){
                  orientation = prevOrientation;
               }
               else{
                  prevOrientation = orientation;
                  orientation = "grid";
               }
            }
        }
        
        if (orientation === "vertical"){
           slidePane = '<div id = "' + panelId + '" style="z-index:200;position: fixed;left: 2.0em;top:5px;height: 185px;width:225px;">' +
                       '<div id="' + id + '" style="border: solid 0.2em #787878;cursor:pointer;background-color:#000045;height:20px;width:98%;"><div id="con86" style="margin:0.15em;float:right;background-color:red;width:20px;height:85%;"></div><div id="con85" style="margin:0.15em;float:right;background-color:green;width:20px;height:85%;"></div></div>' +
                       '<div id="sidp" style = "border: solid 0.3em #999999;padding: 0.3em;background-color: #BBBBBB;overflow-y: scroll;overflow-x:hidden;height:' + (getDimension("height") - 65) + 'px;">' +
                       '<table id = "slidePanelTable" style = "width: 98%;" align = "center" cellpadding = "3px" cellspacing = "3px">';
           
           $("#" + contentId).show().css("margin", contentMarginStyle).css("height", getDimension("height") - 100).css("overflow-y", "auto").css("position", "fixed").css("top", "0.25em").css("left", "5em").css("right", "3em");
        }
        else if (orientation === "horizontal"){
           slidePane = '<div id = "' + panelId + '" style="z-index:200;position: fixed;bottom:3em;left:3em;height: 185px;width:' + (getDimension("width") - 75) + 'px;">' +
                       '<div id="' + id + '" style="border: solid 0.2em #787878;cursor:pointer;background-color:#000045;height:20px;width:99.65%;"><div id="con86" style="margin:0.15em;float:right;background-color:red;width:20px;height:85%;"></div><div id="con85" style="margin:0.15em;float:right;background-color:green;width:20px;height:85%;"></div></div>' +
                       '<div id="sidp" style = "border: solid 0.3em #999999;padding: 0.3em;background-color: #BBBBBB;overflow-x: scroll;overflow-y:hidden;">' +
                       '<table id = "slidePanelTable" style = "width: 98%;" align = "center" cellpadding = "3px" cellspacing = "3px"><tr>';
           
           $("#" + contentId).show().css("margin", fullScreenMargins).css("height", getDimension("height") - 300).css("overflow-y", "auto").css("position", "fixed").css("top", "0.25em").css("left", "1em").css("right", "1em");
        }
        else if (orientation === "grid"){
        	slidePane = '<div id = "' + panelId + '" style="z-index:200;position: fixed;left: 2.0em;top:5px;height: 185px;width:' + (getDimension("width") - 75) + 'px">' +
            '<div id="' + id + '" style="border: solid 0.2em #787878;cursor:pointer;background-color:#000045;height:20px;width:98%;"><div id="con86" style="margin:0.15em;float:right;background-color:red;width:20px;height:85%;"></div><div id="con85" style="margin:0.15em;float:right;background-color:green;width:20px;height:85%;"></div></div>' +
            '<div id="sidp" style = "border: solid 0.3em #999999;padding: 0.3em;background-color: #BBBBBB;overflow-y: scroll;overflow-x:scroll;height:' + (getDimension("height") - 65) + 'px;">' +
            '<table id = "slidePanelTable" style = "width: 98%;" align = "center" cellpadding = "3px" cellspacing = "3px">';

            $("#" + contentId).hide();
        }
        
        if (orientation === "vertical" || orientation === "horizontal"){
            slidePane += createMiniSlides();
        }
        else{
            slidePane += createGridView();
        }
        
        slidePane += '</table></div></div>';
        
        // Attach the panel that will hold the slides list
        $("#" + parentId).prepend(slidePane);
        
        attachClones(slides);
        
        $(".handles").bind("mousedown", pickup);
        $("#" + id).bind("mousedown", pickup);
        $("#slidePanelTable td .hyts").bind("mouseover", enlargeSlidePic);
        $("#slidePanelTable td .hyts").bind("click", gotoSlide);
        $("#con86").bind("click", createSorter);
        $("#con85").bind("click", createSorter);
        
        $("#rq" + (slideIndex + 1).toString()).css("border-color", "blue").css("background-color", "#FFFF70");
        //var ta = "rq" + (slideIndex + 1).toString();
        //document.getElementById(ta).style.borderColor = "blue";
        //document.getElementById(ta).style.backgroundColor = "#FFFF70";
    };
    
    this.setup = function(){
        var xcount = 0, i = 0, y = 0, val, exp;
        
        if (!$("#globalWrapper *").is("#" + panelId)){
           $("#col1hidelink, div#column-one, div#p-personal, div#p-cactions, div#footer").hide();

           if (slides.length > 0){
              createSorter(new Object());
              $("#bodyContent *").hide();
              slides[slideIndex][4].show();
              $(window).bind("resize", windResize);
           }
        }
        else{
           remove();
        }
    };
}

var fd = new SlideSorter("globalWrapper",
                         "1.5em 0 2em 20.2em",
                         "content");

/* This class divides a group jQuery object containing HTML
 * elements into slides. */
function SlideFactory(args){

    // private instance variables
    var startIndex = 0,
        stopIndex = 0,
        slidesList = [],
        slidesIndex = 0,
        leftActive,
        rightActive,
        newSlidesLength,
        slides = [],
        settings = (args && args.settings) ? args.settings : undefined,
        bodyContent = (args && args.bodyContent) ? args.bodyContent : null,
        bodyContentLength = (bodyContent) ? bodyContent.length : 0;

    // setters
    this.setContent = function(content){
        bodyContent = content;
        bodyContentLength = content.length;
    };
    this.setSettings = function(s){
        settings = s;
    };
    
    // getters
    this.getContent = function(){
        return bodyContent;
    };
    this.getSlides = function(){
        return slides;
    };
    this.getSettings = function(){
        return settings;
    };

    // Creates slides from collection of elements
    this.generateSlides = function(){

       slides = [];
       startIndex = 0;
       stopIndex = 0;
       slidesIndex = 0;
       slidesList = [];

       while (startIndex < bodyContentLength){

        if (settings.h2TagSlides && bodyContent.slice(startIndex, startIndex + 1).is("h2:has(span.mw-headline)") ||
           (settings.h1TagSlides && bodyContent.slice(startIndex, startIndex + 1).is("h1:has(span.mw-headline)")) ||
           (bodyContent.slice(startIndex, startIndex + 1).is("h3:has(span.mw-headline)"))){

            stopIndex = startIndex + 2;
            
            while (stopIndex <= bodyContentLength){
            	
                 if ((bodyContent.slice(stopIndex, stopIndex + 1).is("h1:has(span.mw-headline)")) ||
                     (bodyContent.slice(stopIndex, stopIndex + 1).is("h2:has(span.mw-headline)")) ||
                     (bodyContent.slice(stopIndex, stopIndex + 1).is("h3:has(span.mw-headline)")) ||
                     (stopIndex >= bodyContentLength)){
                         if (settings.h1TagSlides === false){
                             if (slidesIndex > 0){
                                 leftActive = (bodyContent.slice(slides[slidesIndex - 1][0], startIndex + 1).is("h1")) ? false: true;
                             }
                             else{
                                 leftActive = false;
                             }
                             rightActive = (bodyContent.slice(stopIndex, stopIndex + 1).is("h1")) ? false : true;
                         }
                         else{
                             leftActive = true;
                             rightActive = true;
                         }
                         
                         if (!(!settings.h3TagSlides && bodyContent.slice(startIndex, stopIndex).is("h3:has(span.mw-headline)"))){

                            slides[slidesIndex] = [startIndex,
                            stopIndex, leftActive, rightActive,
                            bodyContent.slice(startIndex, stopIndex),
                            2.000];
                            
                            var clone = bodyContent.slice(startIndex, stopIndex).clone();
                            var cloneA = $.makeArray(clone);
                            slidesList.push(new Slide({jelements: clone,
                            	                       elements: cloneA,
                            	                       pId: "bodyContent"}));
                            slidesIndex += 1;
                            break;
                         }
                 }
                 stopIndex += 1;
            }
        }
        startIndex += 1;
       }
    
    newSlidesLength = slides.length;

    if (newSlidesLength > 0){
        slides[newSlidesLength - 1][3] = false;
        slides[0][2] = false;
    }
    
    fd.setSlides(slides);
    return slides;
  };
  
  this.manualTraverse = function(){
		
	    var count = 0, currentNode = document.getElementById(parentId).firstChild,
	    elementArray = [], slides = [], still = true, subNode = 0, parallelNode,
	    newPath = true, first = true, total = 0, restrain = false;
	    
	    slides = [];
	    
	    for (var i = 0; currentNode !== null; i++){

	       elementArray[elementArray.length] = currentNode;

	       if (presentation.settings.h1TagSlides && elementArray[elementArray.length - 1].nodeName == "H1"){
	           slides[slides.length] = [elementArray.length - 1, 0, true, true];
	           if (slides.length - 2 >= 0){
	              slides[slides.length - 2][1] = elementArray.length - 1;
	           }
	       }
	       if (elementArray[elementArray.length - 1].nodeName == "H2"){
	           slides[slides.length] = [elementArray.length - 1, 0, true, true];
	           if (slides.length - 2 > 0){
	               slides[slides.length - 2][1] = elementArray.length - 1;
	           }
	       }
	       if (settings.h3TagSlides && elementArray[elementArray.length - 1].nodeName == "H3"){
	           slides[slides.length] = [elementArray.length - 1, 0, true, true];
	           if (slides.length - 2 > 0){
	               slides[slides.length - 2][1] = elementArray.length - 1;
	           }
	       }
	       
	       subNode = 0;
	       still = true;
	       newPath = true;

	       if (currentNode.childNodes.length > 0){
	          currentNode = currentNode.firstChild;
	          subNode += 1;
	          while (still){
	             if (currentNode.firstChild !== null && newPath){
	                currentNode = currentNode.firstChild;
	                subNode += 1;
	                elementArray[elementArray.length] = currentNode;
	             }
	             else{
	                if (currentNode.nextSibling !== null){
	                   currentNode = currentNode.nextSibling;
	                   elementArray[elementArray.length] = currentNode;
	                   newPath = true;
	                }
	                else{
	                   currentNode = currentNode.parentNode;
	                   subNode -= 1;
	                   newPath = false;
	                   if (subNode == 0){
	                      still = false;
	                   }
	                }
	             }
	          }
	       }
	       currentNode = currentNode.nextSibling;
	    }
	    if (slides.length > 0){
	       slides[0][2] = false;
	       slides[slides.length - 1][3] = false;
	       slides[slides.length - 1][1] = elementArray.length;
	    }
	    //presentation.slides = slides;
	    //presentation.elem = elementArray;
	    //bodyContent = $();
	    
	    return slides;

	    /*
	    for (var q = 0; q < elementArray.length; q++){
	       if (elementArray[q].nodeName == "#text"){
	          bodyContent.add($('<p></p>'));
	       }
	       else{
	          bodyContent.add($(elementArray[q]));
	       }
	    }
	    */
	};
}

var slideCreator = new SlideFactory();

function Slide(args){
	
	// private instance variables
    var thisObj = this;
    var elements = (args.elements &&
    		       typeof args.elements === "array") ?
    		       args.elements : undefined;
    var jelements = args.jelements;
    var parentId = (args.pId) ? args.pId : "";
    
    // public instance variables
    this.startPosition = args.start;  // position of slide within
    this.stopPosition = args.stop;    // container of all tags
    
    // public interface methods
    this.getElements = function(){
       return jelements;
    };
    this.setElements = function(e){
       jelements = e;
       elements = $.makeArray(e);
    };
    this.getParentId = function(){
       return parentId;
    };
    this.setParentId = function(p){
       parentId = p;
    };
};

var presentation = {
//-----------------------------------------------------------
// This group of properties consists of the settings which
// can be set by the user in the F10 menu. The values here
// are the defaults for presentation mode if settings XML
// code is not found for the page.
//-----------------------------------------------------------
    settings: {textSizeIncrease: 120,            // Text size percentage
               F6Resize : "1024x768",            // Size of page after resize
               incrementalListItemReveal: true,  // show lists in increments
               showListItemsBackwards: true,     // Show entire previous slide
               listHideBackwards: false,         // Hides lists in steps
               h1TagSlides: true,                // Displays h1 sections
               h2TagSlides: true,
               h3TagSlides: false,               // Displays h3 sections
               showControls: false               // Displays button controls
              },
//-----------------------------------------------------------
// The style property of the presentation object contains
// css information needed by presentation mode.
//-----------------------------------------------------------
    style: {contentMargin:
              {"normalTocShown": "1.5em 0 2em 20.2em",
               "presentTocShown": "0.5em 0em 0.5em 20.2em",
               "normalTocHidden": "1.5em 0 2em 1em",
               "presentTocHidden": "0.5em 1em 1em 1em"
              }
           },
    state: {activated: false,
            running: false,
            runBefore: false,
            h1SlidesPrevious: true,
            h2SlidesPrevious: true,
            h3SlidesPrevious: true,
            h3SlidesPossible: false
           },
    toc: {listItems: {},
          subsectionLinks: {},
          targetElements: "",
          display: 
             {normalmode: true,
              presentmode: false,
              action: "entering"
             }
         },
    slides: [],  // Contains start/stop points for each slide
    down: false,
    mousePos: 0,
    origwidth: 0,
    barThis: {},
    thisNum: {},
    slideActing: 0,
    back: false,
    parentId: "globalWrapper",
    contentId: "content",
    pageName: "",
    XML: "",
    xmlObject: {},
    xmlrequestMode: ""
   },
   slidesList = [],
getXMLfromServer = false,
sendXMLToServer = false,
autoStartPresentation = false, // The presentation starts on page load
presentationInProgress = false,
elem = {},
//presentationEditor = {},
presentButtonTimer,
tocBindings = {
     flash: function(event){
        flashHeader(event);
     }
},
documentBindings = {
     outside: function(event){
         if (event.which === 123){
             setupPresentationMode();
             return false;
         }
         if (event.which === 121){
             presentOptionsMenu();
             return false;
         }
         if (event.which === 115){
             showTableofContents();
             return false;
         }
         if (event.which === 116){
             presentationMode(event);
             return false;
         }
     },
     inside: function(event){
         if (event.which === 116){
             exitPresentation();
             return false;
         }  
         if (event.which === 115){
             showTableofContents();
             return false;
         }
         if (event.which === 27){
             exitPresentation();
         }
         if (presentation.settings.incrementalListItemReveal &&
            (listArray.length > 0) &&
            (currentListItem < listArray.length - 2) &&
            (event.which === 32 || event.which === 39 || event.which === 40)){
                displayListItems("forward");
         }
         else if (presentation.settings.incrementalListItemReveal && 
                  presentation.settings.listHideBackwards &&
                 (listArray.length > 0) && 
                 (currentListItem > 0) &&
                 (event.which === 37 || event.which === 38)){
                 displayListItems("backward");
         }
         else{
             if (event.which === 32 || event.which === 40 || event.which === 39){
                 forward();
             }
             if (event.which === 37 || event.which === 38){
                 backward();
             }
         }
    }
},
windowBindings = {
        adjustImages: function(event) { prepareImages("presentation"); }
},
start = 0, stop = 1,
currentSlide = 0,
oldSlidesLength = 0,
imageOriginalDimensions = [], imagesStoredToArray = false, imageStates = "",
previousFrameWidth = 850,
contentElement,
bodyContent, bodyContentImages, bodyContentLength = 0,
presentationDocument, presentationWindow,
presentLinks,
listArray = [], currentListItem = 0,
presentSpanElements = "div#bodyContent span.editsection:has(a.presentationLink)";

function autoPlay(){
    if (!presentation.state.running){
        presentationMode("auto");
    }
    else{
        if (!presentation.back){
           forward();
        }
        else{
           backward();
        }
    }

    setTimeout("autoPlay()", presentation.slides[currentSlide][5]*20);

    if (!presentation.back && currentSlide === presentation.slides.length - 1){
    	presentation.back = true;
    }
    else if (presentation.back && currentSlide === 0){
    	presentation.back = false;
    }
}

function setupControls(){

    var controlsHtml =
        '<table align = "center" style = "width: 15%;" id = "presentControls">' +
          '<tr>' +
            '<td>' +
              '<img style = "cursor: pointer;" align = "center" id = "presentLeft" height = "35" width = "35" border = "0"' + 
              ' src = "http://www.cds130.org/wiki/images/PresentButtonLeft.png"></img>' +
            '</td>' +
            '<td>' +
              '<img style = "cursor: pointer;" align = "center" id = "presentExit" height = "35" width = "35"' +
              ' border = "0" src = "http://www.cds130.org/wiki/images/PresentButtonExit.png"></img>' +
            '</td>' +
            '<td>' +
              '<img style = "cursor: pointer;" align = "center" id = "presentRight" height = "35" width = "35"' +
              ' border = "0" src = "http://www.cds130.org/wiki/images/PresentButtonRight.png"></img>'+
            '</td>' +
          '</tr>' +
        '</table>';

    if (!($("div#content *").is("#presentControls"))){

       $("div#content").prepend(controlsHtml);
       $("table#presentControls").css("position", "relative");
       $("table#presentControls").css("top", "40px");
       
       $("#presentRight").bind("mouseover", function(event){
           buttonMouseAction(event, "over");
       });
       $("#presentRight").bind("mouseout", function(event){
           buttonMouseAction(event, "out");
       });
       $("#presentRight").bind("click", function(event){
           buttonMouseAction(event, "click");
           presentButtonTimer = setTimeout("$('#presentRight').attr('src', 'http://www.cds130.org/wiki/images/PresentButtonRightOver.png'); presentButtonTimer = undefined;", 300);
       });
       $("#presentLeft").bind("mouseover", function(event){
           buttonMouseAction(event, "over");
       });
       $("#presentLeft").bind("mouseout", function(event){
           buttonMouseAction(event, "out");
       });
       $("#presentLeft").bind("click", function(event){
           buttonMouseAction(event, "click");
           presentButtonTimer = setTimeout("$('#presentLeft').attr('src', 'http://www.cds130.org/wiki/images/PresentButtonLeftOver.png'); presentButtonTimer = undefined;", 300);
       });
       $("#presentExit").bind("mouseover", function(event){
           buttonMouseAction(event, "over");
       });
       $("#presentExit").bind("mouseout", function(event){
           buttonMouseAction(event, "out");
       });
       $("#presentExit").bind("click", function(event){
           buttonMouseAction(event, "click");
           presentButtonTimer = setTimeout("$('#presentExit').attr('src', 'http://www.cds130.org/wiki/images/PresentButtonExitOver.png'); presentButtonTimer = undefined;", 300);
           exitPresentation();
       });
    }
    else{
       $("#presentControls").remove();
    }
}

function buttonMouseAction(event, eventType){

    var over, button, mode = eventType;

    if (event.target.id === "presentRight"){
       if (mode === "over"){
          over = "http://www.cds130.org/wiki/images/PresentButtonRightOver.png";
       }
       else if (mode === "out"){
          clearTimeout(presentButtonTimer);
          over = "http://www.cds130.org/wiki/images/PresentButtonRight.png";
       }
       else{
          if (presentButtonTimer !== undefined){
              clearTimeout(presentButtonTimer);
          }
          over = "http://www.cds130.org/wiki/images/PresentButtonRightClick.png";
       }
    }
    else if (event.target.id === "presentLeft"){
         if (mode === "over"){
            over = "http://www.cds130.org/wiki/images/PresentButtonLeftOver.png";
         }
         else if (mode === "out"){
            clearTimeout(presentButtonTimer);
            over = "http://www.cds130.org/wiki/images/PresentButtonLeft.png";
         }
         else{
            if (presentButtonTimer !== undefined){
                clearTimeout(presentButtonTimer);
            }
            over = "http://www.cds130.org/wiki/images/PresentButtonLeftClick.png";
         }
    }
    else if (event.target.id === "presentExit"){
         if (mode === "over"){
            over = "http://www.cds130.org/wiki/images/PresentButtonExitOver.png";
         }
         else if (mode === "out"){
            clearTimeout(presentButtonTimer);
            over = "http://www.cds130.org/wiki/images/PresentButtonExit.png";
         }
         else{
            if (presentButtonTimer !== undefined){
                clearTimeout(presentButtonTimer);
            }
            over = "http://www.cds130.org/wiki/images/PresentButtonExitClick.png";
         }
    }
    button = event.target;
    button.src = over;
    
    if (mode === "out"){
        $("#presentRight").attr("src", "http://www.cds130.org/wiki/images/PresentButtonRight.png");
        $("#presentLeft").attr("src", "http://www.cds130.org/wiki/images/PresentButtonLeft.png");
        $("#presentExit").attr("src", "http://www.cds130.org/wiki/images/PresentButtonExit.png");
    }
}

function getConfig(){

    var configurationElement = $(".config"),
        configText,
        options = {};
    
    if (!($(".config *").is("PresentationModeOptions"))){
       configText = configurationElement.text();
       configurationElement.html(configText);
    }
    
    options = configurationElement.children("PresentationModeOptions").children();
    
    if (configurationElement.length > 0 &&
        configurationElement.children().is("PresentationModeOptions") &&
        configurationElement.children("PresentationModeOptions").children().length > 0){
        options.each(function(x){
            if (this.nodeName.toLowerCase() == "showleftcolumn"){
                if (this.textContent.toLowerCase() == "true"){
                    presentation.toc.display.presentmode = true;
                }
                else if (this.textContent.toLowerCase() == "false"){
                    presentation.toc.display.presentmode = false;
                }
            }
            if (this.nodeName.toLowerCase() == "dynamiclistreveal"){
                if (this.textContent.toLowerCase() == "true"){
                    presentation.settings.incrementalListItemReveal = true;
                }
                else if (this.textContent.toLowerCase() == "false"){
                    presentation.settings.incrementalListItemReveal = false;
                }
            }
            if (this.nodeName.toLowerCase() == "showlistitemsbackward"){
                if (this.textContent.toLowerCase() == "true"){
                    presentation.settings.showListItemsBackwards = true;
                }
                else if (this.textContent.toLowerCase() == "false"){
                    presentation.settings.showListItemsBackwards = false;
                }
            }
            if (this.nodeName.toLowerCase() == "shows3sections"){
                if (this.textContent.toLowerCase() == "true"){
                    presentation.settings.h3TagSlides = true;
                }
                else if (this.textContent.toLowerCase() == "false"){
                    presentation.settings.h3TagSlides = false;
                }
            }
            if (this.nodeName.toLowerCase() == "showh1sections"){
                if (this.textContent.toLowerCase() == "true"){
                    presentation.settings.h1TagSlides = true;
                }
                else if (this.textContent.toLowerCase() == "false"){
                    presentation.settings.h1TagSlides = false;
                }
            }
            if (this.nodeName.toLowerCase() == "showpresentcontrols"){
                if (this.textContent.toLowerCase() == "true"){
                    presentation.settings.showControls = true;
                }
                else if (this.textContent.toLowerCase() == "false"){
                    presentation.settings.showControls = false;
                }
            }
            if (this.nodeName.toLowerCase() == "textsizepercent"){
                if (typeof (parseInt(this.textContent, 10)) === "number" &&
                    parseInt(this.textContent, 10) > 0){
                    presentation.settings.textSizeIncrease =
                       parseInt(this.textContent, 10);
                }
                else{
                    presentation.settings.textSizeIncrease = 120;
                }
            }
            if (this.nodeName.toLowerCase() == "resizedimensions"){
                presentation.settings.F6Resize = this.textContent;
                setResizeBinding();
            }
            if (this.nodeName.toLowerCase() === "startinpresentationmode"){
                if (this.textContent.toLowerCase() === "true"){
                   autoStartPresentation = true;
                }
                else if(this.textContent.toLowerCase() === "false"){
                   autoStartPresentation = false;
                }
            }
        });
        return true;
    }
    else{
        return false;
    }
}

function findCurrentSlidefromToc(tocNumber, headerNodeNames){

    var h1TagsBeforeCurrent = 0, 
    h3TagsBeforeCurrent = 0,
    InactiveSlidesBeforeCurrent = 0,
    headerNames = headerNodeNames,
    tocEntryPosition = tocNumber,
    loopCount = 0;
    
    if (presentation.settings.h1TagSlides === false &&
        presentation.settings.h3TagSlides === false){
        while (loopCount < headerNames.length &&
               loopCount < tocEntryPosition){
            if (headerNames[loopCount] === "H1"){
                h1TagsBeforeCurrent += 1;
            }
            if (headerNames[loopCount] === "H3"){
                h3TagsBeforeCurrent += 1;
            }
            loopCount += 1;
        }
    }
    if (presentation.settings.h1TagSlides === true &&
        presentation.settings.h3TagSlides === false){
        while (loopCount < headerNames.length &&
               loopCount < tocEntryPosition){
             if (headerNames[loopCount] === "H3"){
                 h3TagsBeforeCurrent += 1;
             }
             loopCount += 1;
         }
    }
    if (presentation.settings.h1TagSlides === false &&
        presentation.settings.h3TagSlides === true){
        while (loopCount < headerNames.length &&
                loopCount < tocEntryPosition){
             if (headerNames[loopCount] === "H1"){
                 h1TagsBeforeCurrent += 1;
             }
             loopCount += 1;
         }
    }
    InactiveSlidesBeforeCurrent = h1TagsBeforeCurrent +
                                  h3TagsBeforeCurrent;
    currentSlide = tocEntryPosition - InactiveSlidesBeforeCurrent;
    
    if (currentSlide < 0){
        currentSlide = 0;
    }
}

function setupToolsLink(){
    var toolsLinkHTML = '<li id = "presentToolsListItem">'+
    '<a id = "toolsPresentLink" title = ' +
    '"Enter presentation mode [F5]. '+
    '(Select [F10] for presentation mode options.)">'+
    'Presentation Mode</a></li>';
    $("div#column-one #p-tb .pBody ul").prepend(toolsLinkHTML);
    $("#toolsPresentLink").css("cursor", "pointer");

    setupPresentationMode();
    //$('<li>[<a class = "presentationLink">present</a>]</li>').appendTo($('#p-personal > div > ul'))

}

/* This function activates presentation mode on the page by placing the present
   links and binding the F5 key by which the user can enter the presentation
   mode and display the sections on the page as slides.  The user can
   toggle the present links onto and off of the page with this function. */
function setupPresentationMode(){

    /* Defines several global variables that will be needed
       several times throughout presentation mode and will be used to access
       to objects and values in order to increase speed. */
    bodyContent = $("div#bodyContent *");
    bodyContentImages = $("div#bodyContent img").not(".tex");
    contentElement = $("div#content");
    bodyContentLength = bodyContent.length;

    var presentLinkTarget,
	presentLinkHtml = '<span class = "editsection">' +
	'<a class = "presentationLink" title="Display section in presentation mode. ESC to exit.">+</a></span>';

    /* This if-else if statement allows the user to toggle the state of
       presentation mode between active and inactive as long as the user
       is not currently viewing  slides in presentation mode.
       When presentation mode is activated, the page is prepared through the
       addition of present links and the F5 key binding to allow entry
       into presentation mode.  When it is made inactive, these things are
       removed in order to allow the page to return to its normal state.  */
    if ((presentation.state.running === false) &&
        (presentation.state.activated === false)){

	presentation.state.activated = true;
         
	// Tests to see which header sections can be displayed in
	// presentation mode.
	presentationCapability();
         
	/* Creates present links in the top right corner of each section
	   that will become a slide in presentation mode.  If h1 tags are not
	   being treated as the start points of slides, then only sections
	   beginning with h2 tags will be given present links.  If h1 tags are
	   considered the start points of slides, then the section beginning
	   with h1 tags also receive links, which can be used to start the
	   presentation at that slide if clicked. */
	if (presentation.settings.h1TagSlides === false && presentation.settings.h3TagSlides === false){
	    presentLinkTarget = "div#bodyContent h2:has(span.mw-headline)";
	}
	else if (presentation.settings.h1TagSlides === true && presentation.settings.h3TagSlides === false){
	    presentLinkTarget = "div#bodyContent h1:has(span.mw-headline), " +
		"div#bodyContent h2:has(span.mw-headline)";
	}
	else if (presentation.settings.h1TagSlides === false && presentation.settings.h3TagSlides === true){
	    presentLinkTarget = "div#bodyContent h2:has(span.mw-headline), " +
		"div#bodyContent h3:has(span.mw-headline)";
	}
	else{
	    presentLinkTarget = "div#bodyContent h1:has(span.mw-headline), " +
		"div#bodyContent h2:has(span.mw-headline), " +
		"div#bodyContent h3:has(span.mw-headline)";
	}
	$(presentLinkHtml).prependTo(presentLinkTarget);
	 
	/* Assigns a title attribute with instructions on how to use
	   presentation mode for the user and a css attribute that causes
	   the cursor to change to the pointer style when the user mouses
	   over the links. */

	presentLinks = $("div#bodyContent a.presentationLink");
	/*
	presentLinks.attr("title", "F12 to enter/exit presentation mode, " +
			  "F11 to use full-screen mode, F5 to start " +
			  "presentation, Left/Up to go back, Right/Down to go forward, " +
			  "and ESC to exit presentation.");
	*/
	presentLinks.css("cursor", "pointer");

	/* Prevents a horizontal scrollbar from appearing when the
	   page is resized. */
	$("body").css("overflow-x", "hidden");

	/* Tests whether the options to count h1 and h3 tags as slides
	   are active. */
	if (presentation.settings.h1TagSlides === false && presentation.settings.h3TagSlides === false){
	    presentation.toc.targetElements = "table#toc li.toclevel-2 > a[href^='#'] span";
	    presentation.toc.listItems = $("table#toc li.toclevel-2");
	    presentation.toc.subsectionLinks = $("table#toc li.toclevel-2 > a[href^='#']");
	}
	else if (presentation.settings.h1TagSlides === true && presentation.settings.h3TagSlides === false){
	    presentation.toc.targetElements = "table#toc li.toclevel-1 > a[href^='#'] span, " +
		"table#toc li.toclevel-2 > a[href^='#'] span";
	    presentation.toc.listItems = $("table#toc li.toclevel-1, " +
					   "table#toc li.toclevel-2");
	    presentation.toc.subsectionLinks = $("table#toc li.toclevel-1 > a[href^='#'], " +
						 "table#toc li.toclevel-2 > a[href^='#']");
	}
	else if (presentation.settings.h1TagSlides === false && presentation.settings.h3TagSlides === true){
	    presentation.toc.targetElements = "table#toc li.toclevel-2 > a[href^='#'] span, " +
		"table#toc li.toclevel-3 > a[href^='#'] span";
	    presentation.toc.listItems = $("table#toc li.toclevel-2, " +
					   "table#toc li.toclevel-3");
	    presentation.toc.subsectionLinks = $("table#toc li.toclevel-2 > a[href^='#'], " +
						 "table#toc li.toclevel-3 > a[href^='#']");
	}
	else{
	    presentation.toc.targetElements = "table#toc li.toclevel-1 > a[href^='#'] span, " +
		"table#toc li.toclevel-2 > a[href^='#'] span, " +
		"table#toc li.toclevel-3 > a[href^='#'] span";
	    presentation.toc.listItems = $("table#toc li.toclevel-1, " +
					   "table#toc li.toclevel-2, " +
					   "table#toc li.toclevel-3");
	    presentation.toc.subsectionLinks = $("table#toc li.toclevel-1 > a[href^='#'], " +
						 "table#toc li.toclevel-2 > a[href^='#'], " +
						 "table#toc li.toclevel-3 > a[href^='#']");
	}

	/* Creates an array containing information such as the start and stop
	   points of the slides which will be displayed in presentation mode. */
	//generatePresentation();
	//manualTraverse();
	slideCreator.setSettings(presentation.settings);
	slideCreator.setContent(bodyContent);
	presentation.slides = slideCreator.generateSlides();

	/* Binds the present links for each section so that they begin
	   the presentation at their respective sections when clicked, and 
	   then binds the F5 key so that it causes the presentation mode 
	   to start as well. */
	presentLinks.bind("click", function(event){
		presentationMode(event);
	    });
    }
    else if ((presentation.state.running === false) &&
             (presentation.state.activated === true)){

	presentation.state.activated = false; 
	$("body").removeAttr("style");
	$(presentSpanElements).remove();
    }
}

function presentationMode(event){

    if (presentation.state.activated === false){
        setupPresentationMode();
    }

    presentation.state.running = true;

    /* This if else structure determines whether the table of contents was
       displayed before entering the presentation mode and assigns the result
       to an object that is used for regulation of the display of the 
       table of contents. */
    if ($("div#column-one").css("display") === "none"){
        presentation.toc.display.normalmode = false;
    }
    else{
        presentation.toc.display.normalmode = true;
    }

    if ($("div#content *").is("#presentModeOptionsMenu")){
	$("#presentModeOptionsMenu").remove();
    }

    /* Binds the window with a resize event handler which will resize
       the images of the presentation as the window is resized. */ 
    $(window).bind("resize", windowBindings.adjustImages);
    
    $(document).unbind("keydown", documentBindings.outside);
    $(document).bind("keydown", documentBindings.inside);
    
    /* Unbinds F5 key so the user can't attempt to enter the
       presentation after they have already started it, and the presentation
       mode key bindings are applied. */
    $("#toolsPresentLink").unbind();

    $("table#toc li.toclevel-1 > a span, " +
      "table#toc li.toclevel-2 > a span, " +
      "table#toc li.toclevel-3 > a span").unbind("click", tocBindings.flash);
    /* Binds the subsection links of the table of contents in order to allow the
       user to use them to jump to any slide from within presentation mode. */
    presentation.toc.subsectionLinks.bind("mousedown", function(event){
	    gotoSection(event);
	});
    setResizeBinding();

    /* First, the loop determines which slide name in the table of contents
       should be highlighted by counting the number of present links it passes.
       Then, it iterates through the elements in order to find the position of the
       present link that was clicked in order to enter the presentation.  This
       will allow the presentation to start at the user's chosen subsection. */
    if (event.which !== 116 && event !== "toolsLink" && event !== "auto"){
        presentLinks.each(function(n){
		if (presentLinks.get(n) === event.target){
		    currentSlide = n;
		    start = presentation.slides[currentSlide][0];
		    stop = presentation.slides[currentSlide][1];
		    return false;
		}
	    });
    }
    else{
        start = presentation.slides[currentSlide][0];
        stop = presentation.slides[currentSlide][1];
    }

    
    /* Sets the value of a boolean component of the presentationState object
       to true.  Parts of the presentationMode function need to
       run differently the first time than they will afterwards, and this
       property keeps track of whether the function has already executed. */
    presentation.state.runBefore = true;

    /* Hides the page elements which will not be included in the presentation
       mode and also the entire bodyContent section.  The part of the 
       bodyContent section being viewed will later be made visible in the
       form of a slide. */
    $("div#column-one, div#p-personal, div#p-cactions, div#footer").hide();
    bodyContent.hide();

    /* Alters the padding-top css property of the content div to move it
       closer to the top of the page while in presentation mode. */
    contentElement.css("padding-top", "0.5em").css("height", window.innerHeight - 90);
    contentElement.css("overflow-y", "auto");
    
    // Enlarge the images for presentation mode.
    imageStates = "presentation";
    prepareImages(imageStates);
    
    // Increases the text size for presentation mode.
    fontSize = (presentation.settings.textSizeIncrease/100).toString() + "em";
    $("#bodyContent").css("font-size", fontSize);

    // Displays the current slide in presentation mode.
    prepareSlide(start,stop, "start");

    // Highlights the current slide name in the table of contents.
    tocHighlight(currentSlide, "normal");

    /* Changes the value for the action of the tocDisplay object so that the
       showTableofContents function restores the table of contents to the
       same state that it had when the user was last in presentation mode
       instead of alternating back and forth as it would normally and then
       calls the function. */
    presentation.toc.display.action = "entering";
    showTableofContents();
    
    if (presentation.settings.showControls){
        setupControls();
    
	$("#presentLeft").bind("click", function(event){
		if (presentation.settings.incrementalListItemReveal && 
		    presentation.settings.listHideBackwards &&
		    (listArray.length > 0) && 
		    (currentListItem > 0)){
		    displayListItems("backward");
		}
		else{
		    backward();
		}
	    });
	$("#presentRight").bind("click", function(event){
		if (presentation.settings.incrementalListItemReveal &&
		    (listArray.length > 0) &&
		    (currentListItem < listArray.length - 2)){
                    displayListItems("forward");
		}
		else{
		    forward();
		}
	    });
    }
}

function exitPresentation(){

    var exitScrollPosition;
    
    // Returns the presentation text to its original size.
    $("#bodyContent").css("font-size", "1.0em");

    /* Calls the prepareImages function and passes in the imageStates variable
       with a value that will instruct the prepareImages function to restore the
       images in the presentation to their original dimensions. */
    imageStates = "original";
    prepareImages(imageStates);

    /* Shows the present links and then unbinds the table of 
       contents display link and hides it so that the original 
       can be shown again. */
    $(presentSpanElements).show();

    /* Removes the background color from the current slide name in 
       the table of contents so that it appears normally in regular mode. */
    tocHighlight(currentSlide, "end");
    
    // Shows the page details that were hidden when in the presentation mode.
    $("div#p-personal, div#p-cactions, div#footer, a#col1hidelink, table[class = 'wikitable collapsible collapsed']").show();
    $("embed").show();

    /* Displays all the main content except for the script tag and the  
    jump-to div tag at the top of the content section. */
    bodyContent.not(".smartTOCSettings, script, div#jump-to-nav, div.printfooter, #siteSub, .config").show();

    //bodyContent.find("table[class = 'wikitable collapsible collapsed'] tbody tr").not("table[class = 'wikitable collapsible collapsed'] tbody tr:has(a)").hide();
    //    bodyContent.find("table[class = 'wikitable collapsible collapsed'] tbody tr").hide();
    bodyContent.filter("table[class = 'wikitable collapsible collapsed'] tbody tr:eq(1)").hide();

    /* Sets the action of tocDisplay to the exit value which tells the 
    showTableofContents function that the user is leaving the presentation
    and it should restore the normal mode display to the state that it 
    had before they entered presentation mode and then calls the function. */
    presentation.toc.display.presentmode =
    ($("#column-one").css("display") === "none") ? false : true;
    presentation.toc.display.action = "exiting";
    showTableofContents();

    /* Resets the padding and height for the content div element to their
    original values. */
    contentElement.css("padding-top", "2em").css("height", "auto");
    
    /* Unbinds the key bindings, link bindings, and window resize bindings  
    used in presentation mode, and re-binds the F5 key to allow the user to enter
    the presentation mode by pressing it, as well as F12 to allow the present links
    to be removed. */
    $(window).unbind("resize", windowBindings.adjustImages);
    
    $(document).unbind("keydown", documentBindings.inside);
    $(document).bind("keydown", documentBindings.outside);
    
    presentation.toc.subsectionLinks.unbind("mousedown");
    $("#toolsPresentLink").bind("click", function(event){
        var event = "toolsLink";
        presentOptionsMenu();
    });
    $("table#toc li.toclevel-1 > a span, " +
      "table#toc li.toclevel-2 > a span, " +
      "table#toc li.toclevel-3 > a span").bind("click", tocBindings.flash);
    
    setResizeBinding();
    
    // Gets the position of the first element of the last slide viewed.
    exitScrollPosition = bodyContent.slice(start, start + 1).offset();

    /* Scrolls to the position of the slide that the user was viewing when
    he or she exited presentation mode. */
    window.scrollTo(0,exitScrollPosition.top);
    
    presentation.state.running = false;
    
    //presentationCookie("set");
    
    if ($("div#content *").is("#presentControls")){
        $("#presentControls").remove();
    }
    //tocFitOnPage();
}

function showTableofContents(){

     /* Determines whether to display the table of contents and adjust the contents
     div or not based on several factors.  If the user is entering or exiting
     presentation mode, the table of contents is restored to the state that
     it had when they were last in that particular mode. If they are 
     already in presentation mode, then it simply alternates between 
     displayed and hidden every time the showTableofContents function is called. */
     if (presentation.state.running === true){
     if ((presentation.toc.display.presentmode === false && presentation.toc.display.action === "alternate") ||
         (presentation.toc.display.presentmode === true && presentation.toc.display.action === "entering")){
          $("div#content").css("margin", presentation.style.contentMargin.presentTocShown);
          $("div#column-one").show();
          presentation.toc.display.action = "alternate";
          presentation.toc.display.presentmode = true;
          imageStates = "presentation";
          prepareImages(imageStates);
     }
     else if (presentation.toc.display.normalmode === true && presentation.toc.display.action === "exiting"){
          $("div#column-one").show();
          $("div#content").css("margin", presentation.style.contentMargin.normalTocShown);
          presentation.toc.display.action = "entering";
          presentation.toc.display.normalmode = true;
     }
     else if (presentation.toc.display.normalmode === false && presentation.toc.display.action === "exiting"){
          $("div#column-one").hide();
          $("div#content").css("margin", presentation.style.contentMargin.normalTocHidden);
          presentation.toc.display.action = "entering";
          presentation.toc.display.normalmode = false;
     }
     else{
          $("div#column-one").hide();
          $("div#content").css("margin", presentation.style.contentMargin.presentTocHidden);
          presentation.toc.display.action = "alternate";
          presentation.toc.display.presentmode = false;
          imageStates = "presentation";
          prepareImages(imageStates);
     }
     }
     else{
         if ($("div#column-one").css("display") === "none"){
            $("div#column-one").show();
            $("div#content").css("margin", presentation.style.contentMargin.normalTocShown);
         }
         else{
            $("div#column-one").hide();
            $("div#content").css("margin", presentation.style.contentMargin.normalTocHidden);
         }
     }
}

function tocHighlight(currentSlide, mode){

    var highlightMode = mode;
    
    //if (presentation.settings.h1TagSlides)
    if (presentation.toc.listItems.slice(currentSlide, currentSlide + 1).get(0).style.display !== "none"){
    
       /* Removes the background color from the list items in the table of contents
       so that only one element will be colored at a time to indicate that user's
       current position within the presentation. */
       presentation.toc.listItems.css("background-color", "");

       /* this code highlights the current position in the table of 
       contents if the user has not ended the presentation mode. */
       if (highlightMode !== "end"){
           presentation.toc.listItems.slice(currentSlide, currentSlide + 1).css("background-color", "#FFFF00");
       }
    }
    if (highlightMode === "end"){
        presentation.toc.listItems.css("background-color", "");
        highlightMode = "normal";
    }
}

function displayListItems(command){

    if ((command === "forward") &&
        (listArray.length > 0) &&
        (currentListItem < listArray.length - 2)){
          currentListItem += 1;
          bodyContent.slice(start, listArray[currentListItem + 1]).not("table.wikitable.collapsible.collapsed > tbody > tr:eq(1), script, div#jump-to-nav, div.printfooter, #siteSub, .config").show();
	  //          bodyContent.find("table[class = 'wikitable collapsible collapsed' tbody]").children("tr").slice(1, 3).hide();
    }
    else if ((command === "backward") &&
             (listArray.length > 0) &&
             (currentListItem > 0)){
          bodyContent.slice(listArray[currentListItem], stop).hide();
          currentListItem -= 1;
    }
    else if (command === "refresh"){
          currentListItem = 0;
    }
    else if (command === "lastItem"){
          currentListItem = listArray.length - 2;
          bodyContent.slice(start, stop).not("table.wikitable.collapsible.collapsed > tbody > tr:eq(1), script, div#jump-to-nav, div.printfooter, #siteSub, .config").show();
	  //          bodyContent.slice(start, stop).find("table[class = 'wikitable collapsible collapsed' tbody]").children("tr").slice(1, 3).hide();
    }
}

function prepareSlide(start,stop, direction){

    var listArrayIndex, moveDirection = direction;

    // Shows the next slide of the presentation.
    bodyContent.slice(start, stop).not("table.wikitable.collapsible.collapsed > tbody > tr:eq(1), script, div#jump-to-nav, div.printfooter, #siteSub, .config").show();

    //bodyContent.slice(start, stop).not("script, div#jump-to-nav, div.printfooter, #siteSub, .config").show();
    //bodyContent.slice(start, stop).find("table[class = 'wikitable collapsible collapsed' tbody]").children("tr").slice(1, 3).hide();
    //bodyContent.slice(start,stop).find("table.wikitable.collapsible.collapsed > tbody > tr:eq(1)");
    //bodyContent.slice(start,stop).filter("table.wikitable.collapsible.collapsed > tbody > tr:eq(1)").hide();

    /* Collapse Show/Hide tables if the default state is collapsed */
    //    alert($('.wikitable.collapsible.collapsed > tbody > tr:eq(1)').length);
    //alert(start + " " + stop);
    //alert(bodyContent.slice(start, stop).find("table[class = 'wikitable collapsible collapsed' tbody]").children("tr").slice(1, 3).length);

    $(presentSpanElements).hide();
    $('.editsection').hide();

    //TODO: Use slice to grab presentSpanElement in this slide, replace with x,
    //unbind any existing binds and then bind to exitPresentation();
    //.text('x').click(function(event){exitPresentation();});

    //  presentationMode(event);

    /* Resets the listArray variable for the list positions so
    it starts empty for the next slide. */
    listArray = [];
    
    /* Hides all but the first entry in an unordered list, and prepares
    the slide to be displayed incrementally according to the positions 
    of the list items. */
    if (presentation.settings.incrementalListItemReveal &&
        bodyContent.slice(start, stop).is("li")){
        listArrayIndex = 0;
        bodyContent.slice(start, stop).each(function(x){
            if (bodyContent.slice(start, stop).slice(x, x + 1).is("li")){
                listArray[listArrayIndex] = start + x;
                listArrayIndex += 1;
            }
        });
        listArray[listArrayIndex] = stop;
        bodyContent.slice(listArray[1], stop).hide();
    }

    if (moveDirection === "backward" &&
        presentation.settings.showListItemsBackwards){
        displayListItems("lastItem");
    }
    else{
        displayListItems("refresh");
    }
    
    //bodyContent.slice(start, start + 1).parents().show();
    
    /*
    if (autoStartPresentation){
        presentationCookie("set");
    }
    */
}

function prepareImages(imageStates){

    var currentImage, contentWidth, ratioHeightWidth, widthFactor,
    roundedFactor, width, height, previousWidth, previousHeight;

    if (window.innerHeight !== null &&
        window.innerHeight !== undefined &&
        window.innerHeight !== 0){
       // Adjusts the height of the content window
       contentElement.css("height", parseInt(window.innerHeight.toString(), 10) - 90);
    }
    else{
       contentElement.css("height", parseInt(document.documentElement.clientHeight.toString(), 10) - 90);
    }
    
    /* Checks whether the images need to be displayed or altered
    for presentation mode, or returned to their original sizes. */
    if (imageStates === "presentation"){

        /* Checks if there are images that need to be altered
        for the presentation. */
        if (bodyContent.is("img")){

            /* Loops through the images on the page and changes the width
            and height in a way that preserves the original size ratio. */
            bodyContentImages.each(function(n){

                /* Gets the current image and stores it to a variable 
                for use in the current iteration of the loop. */
                currentImage = bodyContentImages.slice(n, n + 1);

                /* Determines whether the original dimensions of all the images
                in the presentation have already been obtained.  If they have,
                it prevents the code from getting the values again, which would
                cause issues, and it just uses the values already stored in the
                array.  If it hasn't happened yet, it adds the width and
                height of the current image to the array as a 
                compound element. */
                if (imagesStoredToArray === false){
                    if (currentImage.get(0).getAttribute("height") === null){
                        height = currentImage.get(0).naturalHeight;
                        width = currentImage.get(0).naturalWidth;
                        imageRatio = height/width;
                        width = currentImage.attr("width");
                        height = width*imageRatio;
                    }
                    else{
                        width = currentImage.attr("width");
                        height = currentImage.attr("height");
                    }
                    imageOriginalDimensions[n] = [width,height];
                }
                else{
                    width = imageOriginalDimensions[n][0];
                    height = imageOriginalDimensions[n][1];
                }

                /* Calculates the new height and width of the images in the
                presentation so that the original ratio of height to width 
                is preserved.  The code also ensures that the image is not
                too large to fit in the content div element as well. */
                if (typeof width === "number" && typeof height === "number"){
                    contentWidth = contentElement.css("width");
                    contentWidth = contentWidth.slice(0, -2);
                    contentWidth = parseInt(contentWidth, 10);
                    ratioHeightWidth = height/width;
                    width = (width / previousFrameWidth)*contentWidth;
                    if (width > contentWidth - 50){
                    width = contentWidth - 50;
                    }
                    height = width*ratioHeightWidth;
                    if (height > window.innerHeight - 175){
                    height = window.innerHeight - 175;
                    width = height/ratioHeightWidth;
                    }

                    // Rounds width to the nearest multiple of 30.
                    widthFactor = width/30;
                    roundedFactor = Math.round(widthFactor);
                    width = 30*roundedFactor;

                    height = width*ratioHeightWidth;
                    width = width.toString() + "px";
                    height = height.toString() + "px";
                    currentImage.css("width", width).css("height", height);

                }
            });
            imagesStoredToArray = true;
         }   
     }
     else{
        /* Checks whether there are any images in the presentation, and 
        reverts them back to their original dimensions if there are. */
        if (bodyContent.is("img")){
            bodyContentImages.each(function(n){
                previousWidth = imageOriginalDimensions[n][0];
                previousHeight = imageOriginalDimensions[n][1];
                bodyContentImages.slice(n, n + 1).width(previousWidth).height(previousHeight);
            
            });
        }  
    }
}

function forward(){

    var forwardActive;

    /* Determines whether or not there is a valid slide to the right of the
    current position.  The boolean representing the validity of forward
    movement is at index three of each entry in the slides array. */
    forwardActive = presentation.slides[currentSlide][3];

    // Tests whether it is acceptable to move forward.
    if (forwardActive){
    
        // Hides the elements which were displayed on the previous slide.
        bodyContent.slice(start, stop).hide();
        
        /* Increments the index variable for the array of slides and then
        gets the new start and stop positions for the current slide. */
        currentSlide += 1;
        start = presentation.slides[currentSlide][0];
        stop = presentation.slides[currentSlide][1];
        
        /* Call to the prepareSlide function, which enlarges the text and images
        on the current slide and displays it to the user. */
        prepareSlide(start,stop, "forward");
        
        // Highlights the position of the current slide in the table of contents.
        tocHighlight(currentSlide, "normal");
    
    }
}

function backward(){

    var backwardActive;

    /* Checks whether or not there is a valid slide to the left of the current
    position that the user can view. The boolean for backward 
    movement validity is the element at index two of each entry in the 
    array of slide information. */
    backwardActive = presentation.slides[currentSlide][2];

    /* Ensures that the user does not navigate through a presentation
    boundary, such as the beginning of the presentation, or move out of the
    array of slides, which would generate an error. */
    if (backwardActive){
    
        // Hides the elements of the previous slide.
        bodyContent.slice(start, stop).hide();
        
        /* Decrements the index variable for the array of slides and then
        obtains the new start and stop positions. */
        currentSlide -= 1;
        start = presentation.slides[currentSlide][0];
        stop = presentation.slides[currentSlide][1];
        
        /* Enlarges the text and images on the current slide and 
        displays it to the user. */
        prepareSlide(start, stop, "backward");
        
        // Highlights the current slide position in the table of contents.
        tocHighlight(currentSlide, "normal");
    
    }
}

function gotoSection(event){

    // Loops through the sub-section links in the table of contents.
    $(presentation.toc.targetElements).each(function(n){

         /* Tests whether the current element is the same as the one that 
         was used to trigger the event. */
         if ($(presentation.toc.targetElements).get(n) === event.target){

              /* Sets the current slide to the position of the table of contents
              entry that was clicked. */
              currentSlide = n;
              
              // Highlights the current slide position in the table of contents.
              tocHighlight(currentSlide, "normal");
         }
    });

    // Hides the elements comprising the previous slide.
    bodyContent.slice(start, stop).hide();

    // Gets the new start and stop positions of the current slide.
    start = presentation.slides[currentSlide][0];
    stop = presentation.slides[currentSlide][1];

    // Displays the current slide in presentation mode.
    prepareSlide(start,stop, "start");
}

function clearFlashing(){
   $("div#bodyContent span.mw-headline").css("background-color", "white");
}

function flashHeader(event){
    var contentsEntry = $("table#toc li.toclevel-1 > a span, " +
        "table#toc li.toclevel-2 > a span, " +
        "table#toc li.toclevel-3 > a span"),
    headerElements = $("span.mw-headline"),
    presentationHeader = $("div#bodyContent span.mw-headline"),
    headerLocation = 0,
    arraynames = [];

    contentsEntry.each(function(x){
        arraynames[x] = headerElements.parent().get(x).nodeName;
        if (contentsEntry.get(x) == event.target){
            headerLocation = x;
            findCurrentSlidefromToc(x, arraynames);
            return false;
        }
    });
    
    presentationHeader.slice(headerLocation, headerLocation + 1).css("background-color", "#FFFF00");
    setTimeout(clearFlashing, 1000);
}

function presentOptionsMenu(){

    var formHtml;

    if ($("div#content *").is("#presentModeOptionsMenu") === false){
       formHtml =
       '<form id  = "presentModeOptionsMenu"> '+
       '<table align = "center"><tr><td><p style = "text-align: left;">This MediaWiki installation has a presentation mode that simulates a ' +
       'PowerPoint-style presentation.<br>  In presentation mode, only one section ' +
       'is shown at a time and sections are changed using the arrow keys.</p></td></tr></table>' +
          '<table align = "center" style = "background-color: #C8C8C8; border-style: solid; border-width: 0.5em; border-color: #727272;">' +
             '<th style = "text-align: center; background-color: #A8A8A8;">Presentation Mode Options</th>' + 
             '<th />' +
             '<th style = "background-color: #A8A8A8; text-align: center;">Key Bindings</th>' +
             '<tr><td style = "background-color: #E8E8E8;">' +
             '<table align = "center" style = "background-color: #E8E8E8;">' +
                '<tr><td><input type = "checkbox" id = "op2" value = "1" /> Reveal list items incrementally</td></tr>' +
                '<tr><td><input type = "checkbox" id = "op3" /> When going back a slide, show all list items</td></tr>' +
                '<tr><td><input type = "checkbox" id = "op6" /> Show table of contents by default</td></tr>' +
                '<tr><td><input type = "checkbox" id = "op5" /> Show h1 Sections in Presentation Mode</td></tr>' +
                '<tr><td><input type = "checkbox" id = "op12" /> Show h2 Sections in Presentation Mode</td></tr>' +
                '<tr><td><input type = "checkbox" id = "op4" /> Show h3 Sections in Presentation Mode</td></tr>' +
                '<tr><td><input type = "checkbox" id = "op9" /> Show Presentation Controls (Buttons)</td></tr>' +
                '<tr><td><input type = "checkbox" id = "op7" /> Start presentation on page load</td></tr>' +
                '<tr align = "center"><td><input type = "text" id = "op1" /> Text Size (% of normal)</td></tr>' +
             '</table>' +
       
             '<td style = "width: 0.2em;" />' +
             '<td style = "background-color: #E8E8E8;">' +
             '<table align = "center" style= "background-color: #E8E8E8;">' +
                '<th style = "background-color: #D8D8D8; text-align: center;">Key</th>' +
                '<th style = "background-color: #D8D8D8; text-align: center;">Function</th>' +
                '<tr><td style = "text-align: center;">F4</td><td>Display/Hide table of contents</td></tr>' +
                '<tr><td style = "text-align: center;">F5</td><td>Enter/Exit Presentation</td></tr>' +
                '<tr><td style = "text-align: center;">F6</td><td>Resize browser window to ' +
                   '<select id = "presentF6Binding" title = "Not supported by all browsers">' +
                      '<option id = "present800x600" value = "800x600">800x600</option>' +
                      '<option id = "present1024x768" value = "1024x768">1024x768</option>' +
                      '<option id = "present1280x1024" value = "1280x1024">1280x1024</option>' +
                      '<option id = "present1920x1080" value = "1920x1080">1920x1080</option>' +
                   '</select></td></tr>' +
                '<tr><td style = "text-align: center;">F8</td><td>Enter/Exit Slide Sorter</td></tr>' +
                '<tr><td style = "text-align: center;">F10</td><td>Show/Hide Presentation Mode Options</td></tr>' +
                '<tr><td style = "text-align: center;">F11</td><td>Full Screen Mode</td></tr>' +
                '<tr><td style = "text-align: center;">F12</td><td>Show + links</td></tr>' +
                '<tr><td style = "text-align: center;">Right/Down</td><td>Next Section/Show next list item</td></tr>' +
                '<tr><td style = "text-align: center;">Left/Up</td><td>Previous Section/Hide current list item</td></tr>' +
                '<tr><td style = "text-align: center;">Esc</td><td>Exit Presentation</td></tr>' +
             '</table>' +
             '</td></tr>' +

             '<tr><td></td></tr>' +
             '<tr><td colspan = "3" style = "background-color: #A8A8A8;">' +
             '<table align = "center" style = "background-color: #A8A8A8;">' +
                '<tr><td><input type = "button" id = "createStateObject" value = "Save Settings" /></td>' +
                '<td><input type = "button" id = "closeMenu" value = "Close [F10]" /></td></tr>' +
             '</table>' +
             '</td></tr>' +
             '<tr align = "center"><td colspan = "3" style = "text-align: center;">' +
             '<table align = "center" style = "width: 100%; background-color: #C8C8C8; text-align: center;">' +
                '<tr><td id = "presentSettingsTDtag"></td></tr>' +
                '<tr><td id = "presentationStateAreaTDTAG"></td></tr>' +
             '</table>' +
             '</tr>' +
             '</td></tr></table>' +
       '</form>';
       
       $("div#content").prepend(formHtml);
       
       window.scrollTo(0, 0);
       
       $("#op12, input#op2, input#op3, input#op6, input#op5, input#op4, input#op9, input#op7, input#op11").bind("click", function(event){
           updateOptions();
       });
       /*
       $("input#op1").bind("change", function(event){
           updateOptions();
       });
       */
       $("input#op1").bind("keyup", function(event){
           updateOptions();
       });
       $("#presentF6Binding").bind("change", function(event){
           updateOptions();
       });
       
       $("input#closeMenu").bind("click", function(event){
           presentOptionsMenu();
       });
       $("input#createStateObject").bind("click", function(event){
           generateStateHtml(event);
       });
       
       // Determines which tags can be displayed in presentation mode
       presentationCapability();
       
       $("input#op1").attr("value", presentation.settings.textSizeIncrease);
       if (presentation.settings.incrementalListItemReveal){
          $("input#op2").attr("defaultChecked", true);
       }
       if (presentation.settings.showListItemsBackwards){
          $("input#op3").attr("defaultChecked", true);
       }
       if (presentation.settings.h2TagSlides){
          $("input#op12").attr("defaultChecked", true);
       }
       if (presentation.settings.h3TagSlides){
           $("input#op4").attr("defaultChecked", true);
       }
       if (presentation.toc.display.presentmode){
    	   $("input#op6").attr("defaultChecked", true);
       }
       if (autoStartPresentation){
          $("input#op7").attr("defaultChecked", true);
       }
       if (!presentation.state.h3SlidesPossible){
           $("input#op4").attr("disabled", true);
       }
       if (presentation.settings.h1TagSlides){
           $("input#op5").attr("defaultChecked", true);
       }
       if (presentation.settings.showControls){
           $("input#op9").attr("defaultChecked", true);
       }
       if (presentation.settings.F6Resize === "800x600"){
           $("#present800x600").attr("selected", true);
       }
       else if (presentation.settings.F6Resize === "1024x768"){
           $("#present1024x768").attr("selected", true);
       }
       else if (presentation.settings.F6Resize === "1280x1024"){
           $("#present1280x1024").attr("selected", true);
       }
       else if (presentation.settings.F6Resize === "1920x1080"){
           $("#present1920x1080").attr("selected", true);
       }
    }
    else{
        $("#presentModeOptionsMenu").remove();
    }
}

function updateOptions(){
    var textSizeUserInput;
    textSizeUserInput = parseInt($("input#op1").attr("value"), 10);
    if ((typeof textSizeUserInput === "number") && (textSizeUserInput > 0)){
        presentation.settings.textSizeIncrease = textSizeUserInput;
    }
    else{
        presentation.settings.textSizeIncrease = 120;
    }
    
    /*
    if ($("input#op3").attr("checked")){
        listHideBackwards = false;
    }
    else if($("input#op3").attr("checked") && !listSlowReveal){
        alert("Display list items one at a time must also be checked " +
              "in order to use the hide list items one at a time option.");
        $("input#op3").attr("checked", false);
        listHideBackwards = false;
    }
    else{
        listHideBackwards = false;
    }
    */
    presentation.settings.incrementalListItemReveal = $("input#op2").attr("checked");
    presentation.settings.listHideBackwards = presentation.settings.incrementalListItemReveal;
    presentation.settings.showListItemsBackwards = $("input#op3").attr("checked");
    presentation.settings.h1TagSlides = $("input#op5").attr("checked");
    presentation.settings.h2TagSlides = $("input#op12").attr("checked");
    presentation.toc.display.presentmode = $("input#op6").attr("checked");
    autoStartPresentation = $("input#op7").attr("checked");
    presentation.settings.showControls = $("input#op9").attr("checked");
    presentation.settings.F6Resize = $("#presentF6Binding").attr("value");
    
    setResizeBinding();
    
    if (presentation.state.h3SlidesPossible){
        presentation.settings.h3TagSlides = $("input#op4").attr("checked");
    }
    else if ($("input#op4").attr("checked") && !presentation.state.h3SlidesPossible){
       alert("Sorry, this presentation is not eligible for h3 slide display");
       $("input#op4").attr("checked", false);
       presentation.settings.h3TagSlides = false;
    }
    else{
       presentation.settings.h3TagSlides = false;
    }
    
    if ((presentation.state.h1SlidesPrevious !== presentation.settings.h1TagSlides) ||
        (presentation.state.h2SlidesPrevious !== presentation.settings.h2TagSlides) ||
        (presentation.state.h3SlidesPrevious !== presentation.settings.h3TagSlides) &&
        (presentation.state.activated === true)){
         currentSlide = 0;
         setupPresentationMode();
         setupPresentationMode();
         presentation.state.h1SlidesPrevious =
         presentation.settings.h1TagSlides;
         presentation.state.h2SlidesPrevious =
         presentation.settings.h2TagSlides;
         presentation.state.h3SlidesPrevious =
         presentation.settings.h3TagSlides;
    }
    //presentationCookie("set");
    generateStateHtml("onlytext");
}

function setResizeBinding(){

    var windowDimensions, windowWidth, windowHeight;

    windowDimensions = presentation.settings.F6Resize.split("x");
    windowWidth = parseInt(windowDimensions[0], 10);
    windowHeight = parseInt(windowDimensions[1], 10);

    if (!(typeof windowWidth === "number" && windowWidth > 50 &&
          typeof windowHeight === "number" && windowHeight > 50)){
            windowWidth = 1024;
            windowHeight = 768;
            presentation.settings.F6Resize = "1024x768";
    }
    
    $(document).bind("keydown", function(event){
        if (event.which === 117){
            window.resizeTo(windowWidth, windowHeight);
            return false;
        }
    });
}

function generateStateHtml(event){

    var listIncrementalTemp = $("input#op2").attr("checked"),
    listBackTemp = $("input#op3").attr("checked"),
    h1SlidesTemp = $("input#op5").attr("checked"),
    h2SlidesTemp = $("input#op12").attr("checked");
    h3SlidesTemp = $("input#op4").attr("checked"),
    tocDisplayTemp = $("input#op6").attr("checked"),
    autoStartTemp = $("input#op7").attr("checked"),
    showControlsTemp = $("input#op9").attr("checked"),
    textSizeTemp = parseInt($("input#op1").attr("value"), 10),
    sampleConfigurationObject =
               '<span class="config" style="display: none;">\n' +
               '<PresentationModeOptions>\n',
    textArea = '<textarea align = "center" id = "presentMenuTextArea" ' +
               'rows = "14" cols = "70"></textarea>',
    saveExplanation = '<p style = "text-align: left;" id = "presentSaveExplanation">' +
                      "The above settings have been applied.  To make the "+ 
                      "settings persist after a page reload, edit this "+
               "page and <br>copy the following into the top part of the text area:",
    tagNames = ["DynamicListReveal", "ShowListItemsBackward", "ShowLeftColumn",
                "ShowH1Sections", "ShowH3Sections", "showPresentControls",
                "StartInPresentationMode", "TextSizePercent"];
    if (listIncrementalTemp){
        sampleConfigurationObject += '<DynamicListReveal>true</DynamicListReveal>\n';
    }
    else{
    	sampleConfigurationObject += '<DynamicListReveal>false</DynamicListReveal>\n';
    }
    if (listBackTemp){
        sampleConfigurationObject += '<ShowListItemsBackward>true</ShowListItemsBackward>\n';
    }
    else{
    	sampleConfigurationObject += '<ShowListItemsBackward>false</ShowListItemsBackward>\n';
    }
    if (tocDisplayTemp){
        sampleConfigurationObject += '<ShowLeftColumn>true</ShowLeftColumn>\n';
    }
    else{
    	sampleConfigurationObject += '<ShowLeftColumn>false</ShowLeftColumn>\n';
    }
    if (h1SlidesTemp){
        sampleConfigurationObject += '<ShowH1Sections>true</ShowH1Sections>\n';
    }
    else{
    	sampleConfigurationObject += '<ShowH1Sections>false</ShowH1Sections>\n';
    }
    if (h2SlidesTemp){
        sampleConfigurationObject += '<ShowH2Sections>true</ShowH2Sections>\n';
    }
    else{
        sampleConfigurationObject += '<ShowH2Sections>false</ShowH2Sections>\n';
    }
    if (h3SlidesTemp && !($("input#op4").attr("disabled"))){
        sampleConfigurationObject += '<ShowH3Sections>true</ShowH3Sections>\n';
    }
    else if (!h3SlidesTemp && $("input#op4").attr("disabled")){
    	sampleConfigurationObject += '<ShowH3Sections>false</ShowH3Sections>' +
    	' <!--h3 slides disabled--> \n';
    }
    else{
    	sampleConfigurationObject += '<ShowH3Sections>false</ShowH3Sections>\n';
    }
    if (showControlsTemp){
        sampleConfigurationObject += '<showPresentControls>true</showPresentControls>\n';
    }
    else{
    	sampleConfigurationObject += '<showPresentControls>false</showPresentControls>\n';
    }
    if (autoStartTemp){
        sampleConfigurationObject += '<StartInPresentationMode>true</StartInPresentationMode>\n';
    }
    else{
        sampleConfigurationObject += '<StartInPresentationMode>false</StartInPresentationMode>\n';
    }
    if ((typeof textSizeTemp === "number") && (textSizeTemp > 0)){
        sampleConfigurationObject += '<TextSizePercent>' + textSizeTemp +
        '</TextSizePercent>\n';
    }
    else{
        sampleConfigurationObject += '<TextSizePercent>120</TextSizePercent>' +
        ' <!--Invalid Number Entered-->\n';
    }
    sampleConfigurationObject += '<ResizeDimensions>' +
    presentation.settings.F6Resize + '</ResizeDimensions>\n';
    
    sampleConfigurationObject += '</PresentationModeOptions>\n' +
    '</span>';
    
    if (event.target){
    if (!($("#presentModeOptionsMenu *").is("#presentSaveExplanation"))){
       $("#presentSettingsTDtag").prepend(saveExplanation);
    }
    
    if (!($("#presentModeOptionsMenu *").is("#presentMenuTextArea")) &&
          event.target.id === "createStateObject"){
        $("#presentationStateAreaTDTAG").prepend(textArea);
        $("#presentMenuTextArea").attr("value", sampleConfigurationObject);
    }
    else if ($("#presentModeOptionsMenu *").is("#presentMenuTextArea") &&
          event.target.id === "createStateObject"){
        $("#presentMenuTextArea").attr("value", sampleConfigurationObject);
    }
    }
    else{
        presentation.XML = sampleConfigurationObject;
        //if (sendXMLToServer){
        //   sendXMLRequestToServer("save");
        //}
    }
}

function presentationCapability(){

    var h3SpanTag = "h3 span.mw-headline",
    h3TagsLength,
    h3TocEntriesLength;

    presentation.state.h1SlidesPrevious = presentation.settings.h1TagSlides;
    
    h3TagsLength = $("div#bodyContent h3:has(span.mw-headline)").length;
    h3TocEntriesLength = $("table#toc li.toclevel-3").length;
    
    if ($("div#bodyContent *").is(h3SpanTag) &&
       (h3TagsLength === h3TocEntriesLength)){
        presentation.state.h3SlidesPossible = true;
    }
    else{
        presentation.state.h3SlidesPossible = false;
    }
    
    if (!presentation.state.h3SlidesPossible){
        presentation.settings.h3TagSlides = false;
    }
    
    presentation.state.h3SlidesPrevious = presentation.settings.h3TagSlides;
    presentation.settings.listHideBackwards = presentation.settings.incrementalListItemReveal;
}
/*
//getPageName();

$(document).bind("keydown", documentBindings.outside);
$(document).bind("keydown", documentBindings.editor);
$("table#toc li.toclevel-1 > a span, " +
  "table#toc li.toclevel-2 > a span, " +
  "table#toc li.toclevel-3 > a span").bind("click", tocBindings.flash);

if (getXMLfromServer){
   sendXMLRequestToServer("get");
}

getConfig();           // Obtains configuration XML
setupToolsLink();      // Creates tools menu link for presentation mode
setResizeBinding();    // Sets binding for the F6 window resize key

// Assigns tooltip to the link used to display the left column
$("#col1hidelink").attr("title", "Show/Hide Left Column [F4]");

//autoPlay();
*/


var presentationEditor = {};
presentationEditor.move = function(e){
    $("#" + presentationEditor.pickedupId).css("left", (e.screenX - presentationEditor.mouseOffsetX) + "px");
    $("#" + presentationEditor.pickedupId).css("top", (e.screenY - presentationEditor.mouseOffsetY) + "px");
};

presentationEditor.bindToDrop = function(){
    $("#" + presentationEditor.pickedupId).bind("click", presentationEditor.drop);
};

presentationEditor.bindToPickup = function(){
    $("#" + presentationEditor.pickedupId).bind("click", presentationEditor.pickup);
};

presentationEditor.pickup = function(e){
    presentationEditor.pickedupId = presentationEditor.panelKeys[e.target.id];
    $("#" + presentationEditor.pickedupId).unbind("click", presentationEditor.pickup);
    $(document).bind("mousemove", presentationEditor.move);
    presentationEditor.mouseOffsetX = e.screenX - parseInt($("#" + presentationEditor.pickedupId).css("left"));
    presentationEditor.mouseOffsetY = e.screenY - parseInt($("#" + presentationEditor.pickedupId).css("top"));
    setTimeout("presentationEditor.bindToDrop()", 100);
};

presentationEditor.drop = function(){
    $(document).unbind("mousemove", presentationEditor.move);
    $("#" + presentationEditor.pickedupId).unbind("click", presentationEditor.drop);
    //window.alert(presentationEditor.pickedupId);
    setTimeout("presentationEditor.bindToPickup()", 200);
};

presentationEditor.sidePanel = function(){
    
    var id = "slidePanel",
    slidePane = '<div style = "padding: 0.5em;background-color: #BBBBBB;overflow-y: scroll;overflow-x:hidden;position: fixed;left: 2.0em;top:5;width: 225px;height:' + (window.innerHeight - 50) + 'px;" id = "' + id + '"><table id = "slidePanelTable" style = "width: 85%" align = "center" cellpadding = "3px" cellspacing = "3px">',
    i = 1,
    rootElement = {};
    
    if (presentation.slides.length > 0){
        for (i = 1; i < presentation.slides.length + 1; i++){
        	//slidePane += '<div id="sp' + i + '" style="width:75%;height:100px;border-style:solid;border-width:2px;border-color:#000000;">' +
        	//i + '</div>';
            slidePane += '<tr id="sp' + i + '"><td id = "slideP' + i + '"' + 
            'style = "overflow-x: hidden;font-size: 0.8em;text-align: center;width: 75px; height: 100px;border-style:solid;border-width:2px;border-color:#000000;">' + presentation.slides[i-1][4].html();
            '</td></tr>';
            //alert(bodyContent.slice(presentation.slides[i-1][0], presentation.slides[i-1][1]).clone().html());
            //$("#slideP" + i.toString()).prepend(presentation.slides[i-1][4]);
            //$(presentation.slides[i-1][4].clone()).prependTo($("#slideP" + i.toString()));
        }
        
        slidePane += '</table></div>';
    }
    $("#" + presentation.parentId).prepend(slidePane);
    rootElement = document.getElementById(id);
    $(rootElement).bind("click", presentationEditor.pickup);
    $("#slidePanelTable td p").bind("mouseover", presentationEditor.enlargeSlidePic);
    $("#slidePanelTable td p").bind("click", presentationEditor.gotoSlide);
};

presentationEditor.enlargeSlidePic = function(e){
    $("#slidePanelTable td").css("border-width", "2px");
    for (i = 0; i < $("#slidePanelTable td").length; i++){
        if ($("#slidePanelTable td p").get(i) === e.target){
            $("#slidePanelTable td").get(i).style.borderWidth = "5px";
        }
    }
};

presentationEditor.panelKeys = {"grabEditPanel" : "divEditPanel"
		                        };
presentationEditor.mouseOffsetX = 0;
presentationEditor.mouseOffsetY = 0;

presentationEditor.slideTimeLine = function(){

    var id = "divEditPanel",
    bottomPanel = '<div id = "' + id + '" style = "width: ' + (window.innerWidth - 475) + 'px;opacity:0.95;border-style:solid;border-width: 0.3em;border-color:#DDDDDD;background-color:#999999;position: fixed; left:300px;top: ' + (window.innerHeight - 175) +'px;">' +
    '<div id = "grabEditPanel" style = "cursor: pointer;background-color: #BBBBBB;width: 100%;height: 20px;"></div>' +
    '<div style = "overflow-x: scroll;">' +
    '<form style = "padding: 0.5em;width: 75%" id = "editFormPresent">' +
    '<table>' +
       '<tr id = "powert">',
    i = 1,
    rootElement = {};
    
    if (presentation.slides.length > 0){
        for (i = 1; i < presentation.slides.length + 1; i++){
            bottomPanel += "<td><table class = 'botslides'>" +
            '<tr><td style = "text-align: center; font-size: 1.0em;font-weight: bold;">Slide ' + i +'</td></tr>' + 
            '<tr id = "bar1"><td><div id = "push' + i + '" class = "pushout" style = "text-align: center;cursor: e-resize;border-style: solid;border-width: 0.2em;border-color: #000000;height: 20px;width:' + (presentation.slides[i - 1][5]*presentationEditor.factor) + 'px;background-color: #CCCCCC">' + (presentation.slides[i - 1][5]) + '</div></td></tr>' + 
            '<tr id = "bar3"><td align = "right"><div style = "border-style: solid;border-width: 0.1em;border-color:#BBBBBB;background-color: #DDDDDD;text-align: center;position: relative;left: 1.9em;width: 3em;" id = "outtot' + i + '" class = "outtotal" type = "text">' + (presentation.slides[i - 1][5]) + '</div></td></tr>' +
            '</td></table>';
        }
        
        bottomPanel += '</tr>' +
        '</table>' +
        '</form>' +
        '</div>' +
        '</div>';
        
        $("#" + presentation.parentId).prepend(bottomPanel);
        rootElement = document.getElementById(id);
        $(rootElement).bind("click", presentationEditor.pickup);
        $(".pushout").bind("click", presentationEditor.alterTime);
        presentationEditor.calculateTimeTotal();
    }
};

presentationEditor.calculateTimeTotal = function(){
    var t = $(".outtotal"), z = 0, curVal = 0, formattedVal = "";
    for (z = 0; z < t.length; z++){
       curVal += presentation.slides[z][5];
       formattedVal = new Number(curVal).toPrecision(3);
       $(".outtotal").get(z).textContent = formattedVal;
    }
};

presentationEditor.factor = 50;
presentationEditor.slides = {
    leftPanel: [],
    timeLine: []
};

presentationEditor.pickedupId = {};

presentationEditor.bindings = {
		bar: function(eve){
    var widths = parseInt($(presentation.barThis).css("width").slice(0, -2), 10),
    widthnew = 0;
    if (typeof widths === "number" && widths > 0 && (presentation.origwidth + (eve.screenX - presentation.mousePos)) > 0){
          //$(presentation.thisNum).get(0).value = (presentation.origwidth + (eve.screenX - presentation.mousePos))/presentationEditor.factor;
          presentation.slides[presentation.slideActing][5] = (presentation.origwidth + (eve.screenX - presentation.mousePos))/presentationEditor.factor;
          widthnew = (presentation.origwidth + (eve.screenX - presentation.mousePos)) + "px";
          $(presentation.barThis).css("width", widthnew).text(presentation.slides[presentation.slideActing][5]);
          presentationEditor.calculateTimeTotal();
       }
    },
        undo: function(event){
         $(document).unbind("mousemove", presentationEditor.bindings.bar);
       },
       windResize: function(ev){
           $("#content").css("height", window.innerHeight - 300);
           $("#divEditPanel").css("top", window.innerHeight - 175).css("width", window.innerWidth - 350);
       }
};

presentationEditor.setup = function(){
    var xcount = 0, i = 0, y = 0, val, exp;
    
    if (!$("#globalWrapper *").is("#slidePanel")){
    $("div#column-one, div#p-personal, div#p-cactions, div#footer").hide();
    $("#content").css("margin", presentation.style.contentMargin.normalTocShown);
    
    if (presentation.slides.length > 0){

        presentationEditor.sidePanel();
        presentationEditor.slideTimeLine();
    	
        bodyContent.hide();
        $("#" + presentation.contentId).css("height", window.innerHeight - 300).css("overflow-y", "auto").css("position", "fixed").css("top", "0.25em").css("left", "5em").css("right", "3em");
        bodyContent.slice(presentation.slides[0][0], presentation.slides[0][1]).show();
        $(window).bind("resize", presentationEditor.bindings.windResize);
    }
  }
    else{
       presentationEditor.remove();
    }
};

presentationEditor.gotoSlide = function(event){
	var ert = {};
	
    $("#slidePanelTable td").css("border-color", "#000000");
    $(".botslides").css("background-color", "");
    for (y = 0; y < $("#slidePanelTable td p").length; y++){
        if ($("#slidePanelTable td p").get(y) === event.target){
            $("#slidePanelTable td").get(y).style.borderColor = "blue";
            /*
            ert = $("#slidePanelTable td").get(y).cloneNode($("#slidePanelTable td").get(y));
            $(ert).css("position", "fixed").css("left", "20").css("top", "100");
            $(ert).appendTo("#bodyContent");
            */
            $(".botslides").get(y).style.backgroundColor = "#FFFF00";
            bodyContent.hide();
            currentSlide = y;
            presentation.slides[y][4].show();
        }
    }
};

presentationEditor.remove = function(){
    var i = 0;

    $("#slidePanel, #divEditPanel").remove();

    $("#content").css("margin", presentation.style.contentMargin.normalTocShown);
    $("div#column-one, div#p-personal, div#p-cactions, div#footer").hide();
};

presentationEditor.alterTime = function(event){
    $(".pushout").each(function(x){
        if (this === event.target){
          presentation.mousePos = event.screenX;
          presentation.barThis = this;
          presentation.thisNum = $('.pushout').get(x);
          presentation.slideActing = x;
          presentation.origwidth = parseInt($(this).css("width").slice(0, -2), 10);
          $(document).bind("mousemove", presentationEditor.bindings.bar);
          $(document).bind("mouseup", presentationEditor.bindings.undo);
        }
     });
};

$(function(){
    //var presentCookieExists;
    //var presentationInst = new presentation();
    
  //getPageName();

	var editorBind = function(event){
	       if (event.which == 119){
	           if (presentation.slides.length == 0){
	              setupPresentationMode();
	           }
	           fd.setup();
	           return false;
	        }
	};
	
    $(document).bind("keydown", documentBindings.outside);
    $(document).bind("keydown", editorBind);
    $("table#toc li.toclevel-1 > a span, " +
      "table#toc li.toclevel-2 > a span, " +
      "table#toc li.toclevel-3 > a span").bind("click", tocBindings.flash);

    //if (getXMLfromServer){
    //   sendXMLRequestToServer("get");
    //}

    getConfig();           // Obtains configuration XML
    setupToolsLink();      // Creates tools menu link for presentation mode
    setResizeBinding();    // Sets binding for the F6 window resize key

    // Assigns tooltip to the link used to display the left column
    $("#col1hidelink").attr("title", "Show/Hide Left Column [F4]");
    
    if (autoStartPresentation && !getXMLfromServer){
           presentationMode("auto");
    }

    //autoPlay();
});
