﻿//Create a global instance of the pop up
var myBrotherDistribPopUp = new ContextPopUp();

//Add the event listener to the page onload event
if (window.addEventListener) {
    //Modern non-ie browsers
    if (!window.opera)
        window.addEventListener("load", myBrotherDistribPopUp.prepPage, false);
} else if (window.attachEvent) {
    //IE

    window.attachEvent("onload", myBrotherDistribPopUp.prepPage);
} else {
    //Older browsers
    window.onload = myBrotherDistribPopUp.prepPage;
}

//This is the main class
function ContextPopUp() {

    //This is the default width if the
    //docment that is retrieved does not have one specified
    //I don't think this is used - 3-5-09
    //this.contentWidth = 350;

    //This is the max height for the pop up window.  If the 
    //supplied height is larger than this we go with this value
    this.maxPopUpHeight = 350;

    //How far in from the left and right edges the arrow will appear
    this.xOffsetOfArrowOnBox = 15;

    //How far vertically from the cursor the box will appear
    //Don't forget to take into account the height of the arrow
    this.yOffsetForBoxFromCursor = 30;




    this.cursorXPosition;
    this.cursorYPosition;

    //This is the extra height that must be added to the wrapping div (in pixels)
    //(add it to the height of the content div).  It is the total
    //of the header and footer div section heights
    this.extraWrapperHeight;

    //This is the extra width that must be added to the wrapping div (in pixles)
    //(add it to the width of the content div).  It is the side border
    //widths of the border div.
    this.extraWrapperWidth;

    //This is the element that triggered the Pop Up
    this.trigger;

    this.isIE = function() {
        if (document.all && !window.opera) {
            return true;
        } else {

            return false;
        }
    };

    //The IFrame that gets the content from the getting page
    this.ContentGetter;

    //The div that has the header and footer bars
    this.ContentWrapper;

    //the div that contains the content that is gotten from the ContentGetter
    this.ContentContainer;

    //The width of the arrow image
    this.arrowWidth;

    //Title element for the box
    this.titleElement;


    //This is used to trigger the pop up to appear
    //Doesn't really belong in this object as it is, but it works.
    this.triggerPopUp = function(trigger, evt) {

        //We have to close the pop up window each time
        //so that the height of the window will reset so we
        //can use a max height.  Otherwise the height of the window
        //for items that are smaller than max height will be the max
        //height
        myBrotherDistribPopUp.closePopUp();

        if (trigger.id) {
            myBrotherDistribPopUp.trigger = trigger;
        } else {
            //Gets the triggering element for IE browsers
            myBrotherDistribPopUp.trigger = window.event.srcElement;
            trigger = myBrotherDistribPopUp.trigger;
            evt = window.event;
        }

        this.cursorXPosition = evt.clientX;
        this.cursorYPosition = evt.clientY;

        if (myBrotherDistribPopUp.isIE()) {
            iframetag = '<iframe></iframe>';
            dtag = '<div></div>';

        } else {
            iframetag = 'iframe';
            dtag = 'div';
        }

        //Create the various elements we will need
        var ContentHeader, ContentFooter, ContentBorder, HeaderText, HeaderImage;
        myBrotherDistribPopUp.ContentGetter = document.createElement(iframetag);
        myBrotherDistribPopUp.ContentWrapper = document.createElement(dtag);

        //We don't want to show anything since we are about
        //to redraw/move it it.
        myBrotherDistribPopUp.ContentWrapper.style.visibility = 'hidden';

        myBrotherDistribPopUp.ContentContainer = document.createElement(dtag);
        ContentHeader = document.createElement(dtag);
        ContentBorder = document.createElement(dtag);
        ContentFooter = document.createElement(dtag);
        HeaderText = document.createElement(dtag);

        HeaderText.className = "bdTitle";
        myBrotherDistribPopUp.titleElement = HeaderText;

        //        if (trigger.title) 
        //        {
        //              
        //            HeaderText.innerHTML = trigger.title;//'b-learning';
        //        } else {
        HeaderText.innerHTML = '<img src="/USAImages/DistributedLearning/book.gif" alt="" style="float: left;"  /> <span style="float: left; color: #87a2cf; padding: 2px 0px 0px 5px;">Brother Learning</span>';
        //HeaderText.innerHTML = 'b-learning';
        //        }

        //Create the header image (the x that closes the pop up)
        HeaderImage = new Image();
        HeaderImage.src = '/USAImages/DistributedLearning/x.gif';
        HeaderImage.alt = 'Close the box';
        HeaderImage.className = 'bdBoxClose';

        //Add the event listener to the image to close the pop up
        if (window.addEventListener) {
            //Modern non-ie browsers
            HeaderImage.addEventListener("click", myBrotherDistribPopUp.closePopUp, false);
        } else if (window.attachEvent) {
            //IE

            HeaderImage.attachEvent("onclick", myBrotherDistribPopUp.closePopUp);
        } else {
            //Older browsers
            HeaderImage.onclick = myBrotherDistribPopUp.closePopUp;
        }

        //Append the items to appear in the PopUp title bar
        ContentHeader.appendChild(HeaderText);
        ContentHeader.appendChild(HeaderImage);

        //Set the IDs and classes for the newly created items
        myBrotherDistribPopUp.ContentWrapper.id = 'bdWrapper';
        myBrotherDistribPopUp.ContentWrapper.className = "bdWrap";

        myBrotherDistribPopUp.ContentContainer.id = 'bdContent';
        myBrotherDistribPopUp.ContentContainer.className = 'bdContent';

        ContentBorder.className = 'bdContentBorder';

        myBrotherDistribPopUp.ContentGetter.id = 'bdIFrame';
        myBrotherDistribPopUp.ContentGetter.className = 'bdIFrame';

        ContentHeader.id = 'bdHeader';
        ContentHeader.className = 'bdHeader';

        ContentFooter.id = 'bdFooter';
        ContentFooter.className = 'bdFooter';

        //Set the IFrame to continue the process once it has loaded
        if (window.addEventListener) {
            //Modern non-ie browsers
            myBrotherDistribPopUp.ContentGetter.addEventListener("load", myBrotherDistribPopUp.getContent, false);
        } else if (window.attachEvent) {
            //IE

            myBrotherDistribPopUp.ContentGetter.attachEvent("onload", myBrotherDistribPopUp.getContent);
        } else {
            //Older browsers
            myBrotherDistribPopUp.ContentGetter.onload = myBrotherDistribPopUp.getContent;
        }



        //Append the other newly created items
        document.body.appendChild(myBrotherDistribPopUp.ContentGetter);

        ContentBorder.appendChild(ContentHeader);

        ContentBorder.appendChild(myBrotherDistribPopUp.ContentContainer);

        ContentBorder.appendChild(ContentFooter);

        myBrotherDistribPopUp.ContentWrapper.appendChild(ContentBorder);

        document.body.appendChild(myBrotherDistribPopUp.ContentWrapper);


        //Set the extra width we need for the wrapper.  This is the left and right border
        //width of the border object
        if (ContentBorder.currentStyle) {
            //IE version
            this.extraWrapperWidth = parseInt(ContentBorder.currentStyle['borderLeftWidth']) + parseInt(ContentBorder.currentStyle['borderRightWidth']);
        } else {
            //Standards version
            this.extraWrapperWidth = parseInt(getComputedStyle(ContentBorder, '').getPropertyValue('border-left-width')) + parseInt(getComputedStyle(ContentBorder, '').getPropertyValue('border-right-width'));

        }


        //Set the extra height we need
        this.extraWrapperHeight = ContentHeader.offsetHeight + ContentFooter.offsetHeight;





        //Get the ID of the content we want from the ID of the trigger.  It will be the number after the
        //first "_", but before the second one      
        var contentID = myBrotherDistribPopUp.trigger.id.substring(myBrotherDistribPopUp.trigger.id.indexOf('_') + 1, myBrotherDistribPopUp.trigger.id.lastIndexOf('_'));

        //Set the IFrame source to our page which generates the content based upon the ID passed in
        if (!isNaN(contentID)) {

            myBrotherDistribPopUp.ContentGetter.src = "/BDShowContent.aspx?ID=" + contentID;
        }




    }   //this.triggerPopUp = function ()


    this.getContent = function() {

        var myFrame = myBrotherDistribPopUp.ContentGetter;
        var ContentContainer = myBrotherDistribPopUp.ContentContainer;

        var ContentHeight;
        var ContentWidth;


        var titleFromPage;

        //Check to see if they have specified a title element
        titleFromPage = myFrame.contentWindow.document.getElementById("ItemTitle");

        if (titleFromPage) {
            //There is a title element, so display it and then remove it from the frame
            myBrotherDistribPopUp.titleElement.innerHTML = titleFromPage.innerHTML;
            titleFromPage.parentNode.removeChild(titleFromPage);
        }

        ContentContainer.innerHTML = myFrame.contentWindow.document.body.innerHTML;



        //Get the hieght and width we need from the document
        if (document.getElementById("MyBrotherDistribContent").childNodes.length == 1) {
            //Since there is only one item, we need to get its dimensions
            ContentHeight = document.getElementById("MyBrotherDistribContent").childNodes[0].offsetHeight;
            ContentWidth = document.getElementById("MyBrotherDistribContent").childNodes[0].offsetWidth;

        } else {
            //loop through the items and get the deminsions of the first item we come to
            //that has anything specified

            for (var x = 0; x < document.getElementById("MyBrotherDistribContent").childNodes.length; x++) {

                if (document.getElementById("MyBrotherDistribContent").childNodes[x].offsetWidth) {
                    ContentHeight = document.getElementById("MyBrotherDistribContent").childNodes[x].offsetHeight;
                    ContentWidth = document.getElementById("MyBrotherDistribContent").childNodes[x].offsetWidth;


                }
            }
        }



        //Width will not scale automatically, so we need to set it here. (height does,
        //so we don't need a like function for it)
        if (ContentWidth) {
            ContentContainer.style.width = ContentWidth + "px";
        } else {
            ContentContainer.style.width = myBrotherDistribPopUp.contentWidth + "px";
        }



        //See if the content is larger than the max allow height
        if (ContentContainer.offsetHeight > myBrotherDistribPopUp.maxPopUpHeight) {
            ContentContainer.style.height = myBrotherDistribPopUp.maxPopUpHeight + "px";


            if (ContentContainer.offsetWidth == ContentContainer.clientWidth) {
                //Sometimes IE 7 doesn't recognize that it has already put a scroll bar on the content
                //why this happens I don't know, but when it does the the clientWidth and offsetWidth
                //are the same, so we need to manually add a value to the width to make it so that
                //there are no horizontal scroll bars
                //If we ever figure out WHY it does this and how to keep it from happening, 
                //then we can remove this.
                ContentContainer.style.width = (ContentContainer.clientWidth + 17)  + 'px';
               
            } else {
                //We need to add some extra to the width to account for the scroll bars.
                //If we subtract the clientWidth from the offsetWidth then that will give
                //us the width of the scroll bar, which we then want to add to the width
                ContentContainer.style.width = parseInt(ContentContainer.style.width) + (ContentContainer.offsetWidth - ContentContainer.clientWidth) + 'px';
            }


            //alert("2: " + ContentContainer.style.width);
        } else {
            //Do this to keep the code consistent.  If you don't then the 
            //bottom arrows will be out of whack.
            ContentContainer.style.height = ContentContainer.offsetHeight + "px";
        }


        //Set the height of the wrapper to the new content offset height and the wrapper extra
        myBrotherDistribPopUp.ContentWrapper.style.height = parseInt(myBrotherDistribPopUp.ContentContainer.offsetHeight) + myBrotherDistribPopUp.extraWrapperHeight + 'px';


        //Only need to use the offset width for this one because that is entire width           
        myBrotherDistribPopUp.ContentWrapper.style.width = myBrotherDistribPopUp.ContentContainer.offsetWidth + myBrotherDistribPopUp.extraWrapperWidth + 'px';


        myBrotherDistribPopUp.setPopUpVerticalPosition();
        myBrotherDistribPopUp.setPopUpHorizontalPosition();




    }                        //this.getContent = function()



    this.setPopUpVerticalPosition = function() {
        var vpos;
        var useBottomArrow = false;


        //Remove the arrow element if it already exists
        if (document.getElementById('bdArrow')) {

            document.getElementById('bdArrow').parentNode.removeChild(document.getElementById('bdArrow'));
        }


        var Arrow;

        var wrapperHeight = myBrotherDistribPopUp.ContentWrapper.offsetHeight;


        //Check to see if the current position of the mouse (which is in windows coordinates)
        //is larger than the height of the pop up plus the vertical offset the pop up is from the item
        if (!this.isIE()) {

            if (this.cursorYPosition > (wrapperHeight + this.yOffsetForBoxFromCursor)) {
                useBottomArrow = true;

            }

            Arrow = document.createElement('img');

            //Convert the windows position of the mouse to document position   
            vpos = this.cursorYPosition + window.pageYOffset
        } else {

            if (this.cursorYPosition > (wrapperHeight + this.yOffsetForBoxFromCursor)) {
                useBottomArrow = true;
            }
            Arrow = document.createElement('<img />');
            vpos = this.cursorYPosition + document.documentElement.scrollTop
        }


        if (useBottomArrow) {
            //Since this arrow is on the bottom of the pop up then we need to subtract the height
            //of the popup and the extra offset from the current cursor position.             
            vpos = vpos - this.yOffsetForBoxFromCursor - wrapperHeight;


            Arrow.src = '/USAImages/DistributedLearning/bottom_arrow.gif';
            Arrow.className = 'bdDownArrow';

            //Append the Arrow to the footer
            document.getElementById("bdFooter").appendChild(Arrow);



        } else {
            vpos = vpos + this.yOffsetForBoxFromCursor;
            Arrow.src = '/USAImages/DistributedLearning/top_arrow.gif';
            Arrow.className = 'bdUpArrow';
            //Append the arrow to the header
            document.getElementById("bdHeader").appendChild(Arrow);
        }

        Arrow.id = 'bdArrow';
        this.arrowWidth = Arrow.width;

        this.ContentWrapper.style.top = vpos + 'px';

    } //End this.setPopUpVerticalPosition = function ()




    this.setPopUpHorizontalPosition = function() {

        var hpos;
        var useRightArrow = false;

        //We need to make sure that there is enough space to the left of the current position
        //of the mouse to see if we can display the pop up box on the left
        //If the current position of the mouse (which is a window cooridnate, not document cooridnate)
        //is more than the width of the wrapping div, then there is enough room on the left 
        if (!this.isIE()) {

            if (this.cursorXPosition > parseInt(this.ContentWrapper.offsetWidth)) {
                useRightArrow = true;
            }

            //convert the window coordinate to a document one.
            hpos = this.cursorXPosition + window.pageXOffset;

        } else {
            //IE browsers
            if (this.cursorXPosition > parseInt(this.ContentWrapper.offsetWidth)) {
                useRightArrow = true;
            }

            //convert the window coordinate to a document one.
            hpos = this.cursorXPosition + document.documentElement.scrollLeft;
        }



        if (useRightArrow) {
            //Since this image in on the right we need to subtract the width of the pop up 
            //from the cursor position, and then add back how far in the arrow appears and 1/2
            //the width of the arrow so that it is centered on the cursor
            hpos = hpos - this.ContentWrapper.offsetWidth + this.xOffsetOfArrowOnBox + this.arrowWidth / 2;
            document.getElementById('bdArrow').style.right = this.xOffsetOfArrowOnBox + 'px';



        } else {
            //Since the image is on the left we just need to subtract how far in the arrow appears
            //and 1/2 the width to line it up over the cursor
            //Note that this will make the box appear off the left side of the screen
            //if the cursor is too close to.  This shouldn't be a problem on our site
            //since we have a left nav.
            hpos = hpos - this.xOffsetOfArrowOnBox - this.arrowWidth / 2;
            document.getElementById('bdArrow').style.left = this.xOffsetOfArrowOnBox + 'px';


        }

        this.ContentWrapper.style.left = hpos + 'px';

        //make the window visible since we are done moving it aroung
        this.ContentWrapper.style.visibility = 'visible';



    } //End this.setPopUpHorizontalPosition = function () 

    //Close the poop up, which means remove the items from the DOM
    this.closePopUp = function() {

        if (myBrotherDistribPopUp.ContentWrapper) {

            myBrotherDistribPopUp.ContentWrapper.parentNode.removeChild(myBrotherDistribPopUp.ContentWrapper);

            myBrotherDistribPopUp.ContentGetter.parentNode.removeChild(myBrotherDistribPopUp.ContentGetter);

            myBrotherDistribPopUp.ContentWrapper = null;
            myBrotherDistribPopUp.ContentGetter = null;
            myBrotherDistribPopUp.ContentContainer = null;
        }
    }

    //Prep the page to have the pop ups appear
    this.prepPage = function() {


        //Get all the triggers on the page
        var popLinks = getElementsByClass('bdistriblearn');

        //loop through the triggers and do what we want to them
        for (i = 0; i < popLinks.length; i++) {

            //Change the ID value of the item.  It is possible that
            //the same pop up tag will be used multiple times on
            //the same page, so changing the ID will create a 
            //unique id
            popLinks[i].id = popLinks[i].id + '_' + i

            //Add the class that actually changes the appearance of the tag
            popLinks[i].className = popLinks[i].className + " bdTrigger";

            //

            if (window.addEventListener) {
                //Modern non-ie browsers

                popLinks[i].addEventListener("mouseover", function(event) { myBrotherDistribPopUp.triggerPopUp(this, event); }, false);

            } else if (window.attachEvent) {
                //IE
                popLinks[i].attachEvent("onmouseover", function(event) { myBrotherDistribPopUp.triggerPopUp(this, event); });
            } else {
                //Older browsers
                popLinks[i].onmouseover = function(event) { myBrotherDistribPopUp.triggerPopUp(this, event); };
            }

        }
    } // End this.prepPage = function () 


} //End Class ContextPopUp() 


function getElementsByClass(searchClass, node, tag) {
    var classElements = new Array();
    if (node == null)
        node = document;
    if (tag == null)
        tag = '*';
    var els = node.getElementsByTagName(tag);


    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}
