﻿/// <reference name="MicrosoftAjax.js"/>
///this javascript object follows the pattern laid out for ms ajax controls.  It is initialized by a $create script
//generated by the SubjectAreaNavigation control and utilizes the MS AJAX framework inherent with ASP.NET 3.5
///initialize is called by the ms ajax framework after all of the pages components have loaded.
///dispose is called on page unload and allows for the cleaning up of resources (such as event handlers)
Type.registerNamespace("GiantEagle.IVET");
GiantEagle.IVET.SubjectAreaNavigationControl = function(element) {
GiantEagle.IVET.SubjectAreaNavigationControl.initializeBase(this, [element]);
    this._subNavigation = null; //holds reference to sub navigation

    this._timedDelay = null;

    this._isIE6Browser = false;
    //this._IFRAME = null;
    this._tabs = new Array();

    this._loadingImage = null;
    this._loadingImageSrc = null;

    this._tabMouseOverDelegates = null;
    this._tabMouseOutDelegates = null;
    this._tabContentMouseOverDelegtes = null;
    this._tabContentMouseOutDelegtes = null;
}

GiantEagle.IVET.SubjectAreaNavigationControl.prototype = {
    initialize: function() {
    GiantEagle.IVET.SubjectAreaNavigationControl.callBaseMethod(this, 'initialize');

        this.getTabReferences();
        if (this._tabs) {
            this.setHandlers();
        }
        this.detectIE6Browser();

        this.buildLoadingImage();

    },
    dispose: function() {
        //Add custom dispose actions here
        $clearHandlers(this._element);
        this.removeHandlers();

        if (this._timedDelay) {
            clearTimeout(this._timedDelay);
            this._timedDelay = null;
        }
        GiantEagle.IVET.SubjectAreaNavigationControl.callBaseMethod(this, 'dispose');
    },

    buildLoadingImage: function() {
        if (this._loadingImageSrc && this._loadingImageSrc !== "") {
            this._loadingImage = document.createElement('img');
            if (this._loadingImage) {
                if (_geApplicationRoot) {
                    this._loadingImageSrc = _geApplicationRoot + this._loadingImageSrc;
                }
                this._loadingImage.src = this._loadingImageSrc;
                Sys.UI.DomElement.setVisible(this._loadingImage, false);
                // document.body.appendChild(this._loadingImage);
                document.getElementById("flyoutPlaceholder").appendChild(this._loadingImage);
                Sys.UI.DomElement.addCssClass(this._loadingImage, 'flyOutloadingImage');
            }
        }
    },

    detectIE6Browser: function() {
        if (navigator.appName == 'Microsoft Internet Explorer') {
            if (navigator.appName == 'Microsoft Internet Explorer') {
                var ua = navigator.userAgent;
                var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
                if (re.exec(ua) != null) {
                    this._isIE6Browser = (parseInt(RegExp.$1) == 6);
                }
            }
        }
    },

    // builds array references to the image tabs with their bounds  
    //needs to loop the top level images
    getTabReferences: function() {
        var c = this._element.childNodes;
        var myDivs = new Array();
        if (c && c.length > 0) {
            for (var x = 0; x < c.length; x++) {
                if (c[x].nodeType == 1 && c[x].nodeName == "DIV") {

                    Array.add(myDivs, c[x]);
                }
            }
            if (myDivs.length > 0) {
                for (var x = 0; x < myDivs.length; x++) {//server control renders tabs in two div sets--the first div contains the tab images, the second div the flyout content area
                    if (myDivs[x].getAttribute('tabImages')) {//is div containing images
                        var images = myDivs[x].getElementsByTagName("IMG");
                        if (images && images.length > 0) {
                            var innerDivs = myDivs[x + 1].childNodes; //myDivs[x + 1] is the flyout content div
                            for (var z = 0; z < innerDivs.length; z++) {
                                if (innerDivs[z].nodeType == 1 && innerDivs[z].getAttribute('cntid')) {//has content div
                                    innerDivs[z].setAttribute('id', innerDivs[z].getAttribute('cssID'));
                                    //this._tabs is an array containg the the following json object
                                    Array.add(this._tabs, { tab: myDivs[x],
                                        normalImage: images[0], //non-active tab image
                                        activeImage: (images[1]) ? images[1] : images[0], //active tab image 
                                        flyOutContent: myDivs[x + 1], //positioning div that will contain the flyout navigation content
                                        contentDiv: innerDivs[z], //content div for flyout navigation content (is inside of positioning div
                                        cntid: innerDivs[z].getAttribute('cntid'), //cntid for CMS, sent to SubjectAreaNavigation Service
                                        displayStatus: null, //used as a flag for display logig
                                        loadingStatus: null, //used as a flag for display logic and when to call server for content
                                        activeTab: false, //used as a flag for display logig
                                        timer: null, //used to delay the hiding of the navigation
                                        loadingImageIsShowing: false//used in rendering logic
                                    });

                                    Sys.UI.DomElement.setVisible(myDivs[x + 1], false);
                                    //remove from inline and append to body
                                    myDivs[x + 1].parentNode.removeChild(myDivs[x + 1]);
                                    // document.body.appendChild(myDivs[x + 1]);
                                    document.getElementById("flyoutPlaceholder").appendChild(myDivs[x + 1]);
                                }

                            }
                        }
                    }
                }
            }
        }
    },

    //  responsible for wiring event handlers to the tab navigation 
    //Function.createCallback is used to pass a tab index into the event handler as a context object
    setHandlers: function() {
        if (this._tabs) {
            for (var indexer = 0; indexer < this._tabs.length; indexer++) {
                $addHandler(this._tabs[indexer].tab, 'mouseover', Function.createDelegate(this, Function.createCallback(this.onTabMouseOver, indexer)));
                $addHandler(this._tabs[indexer].tab, 'mouseout', Function.createDelegate(this, Function.createCallback(this.onTabMouseOut, indexer)));
                $addHandler(this._tabs[indexer].flyOutContent, 'mouseover', Function.createDelegate(this, Function.createCallback(this.onContentContainerMouseOver, indexer)));
                $addHandler(this._tabs[indexer].flyOutContent, 'mouseout', Function.createDelegate(this, Function.createCallback(this.onContentContainerMouseOut, indexer)));
                $addHandler(this._tabs[indexer].contentDiv, 'mouseout', this.onContentMouseOut);
                $addHandler(this._tabs[indexer].contentDiv, 'mouseover', this.onContentMouseOver);
            }

        }
    },

    //  responsible for clearing event handlers to the tab navigation 
    removeHandlers: function() {
        if (this._tabs) {
            for (var x = 0; x < this._tabs.length; x++) {
                $clearHandlers(this._tabs[x].tab);
                $clearHandlers(this._tabs[x].flyOutContent);
                $clearHandlers(this._tabs[x].contentDiv);
            }

        }
    },

    getSubNavigationFromServer: function(index) {
        //call web service and load navigation
        if (!this._tabs[index].loadingStatus) {
            this._tabs[index].loadingStatus = 'loading';
            GiantEagle.IVET.SubjectAreaNavigationService.GetSubjectAreaNavigationContent(this._tabs[index].cntid, this.subNavigationLoadedSuccess, this.subNavigationLoadedFailure, { index: index, obj: this });
        }
    },

    //result is of type GEAjaxResponseMessage
    //context is a reference to an instance of this javascript class
    subNavigationLoadedSuccess: function(result, context, method) {
        context.obj._tabs[context.index].loadingStatus = 'loaded';
        if (!result.OperationSucceeded) {
            context.obj._tabs[context.index].contentDiv.innerHTML = "";
        }
        else {
            context.obj._tabs[context.index].contentDiv.innerHTML = result.ClientData;
        }

        if (context.obj._isIE6Browser) {
            //this adds an iframe inline to the content returned

            Sys.UI.DomElement.setLocation(context.obj._tabs[context.index].flyOutContent, -1000, -1000);
            Sys.UI.DomElement.setVisible(context.obj._tabs[context.index].flyOutContent, true);
            var content = context.obj._tabs[context.index].contentDiv;
            var flyOutBounds = Sys.UI.DomElement.getBounds(content);

            var iframe = document.createElement("IFRAME");
            if (iframe) {
                //add relative position
                iframe.style.position = 'absolute';
                iframe.style.top = '0';
                iframe.style.left = '0';
                iframe.style.display = 'block';
                iframe.src = "javascript:'<html></html>'";
                iframe.allowTransparency = false;
                iframe.frameBorder = "0";
                iframe.style.width = flyOutBounds.width;
                iframe.style.height = flyOutBounds.height;
                iframe.style.zIndex = -10;
            }

            //remove the children of the container and add the iframe first.  add the children afterward so they will render correctly overtop of the iframe
            if (content.childNodes) {
                var contentChildrenHolding = new Array();
                var contentChildren = content.childNodes;
                //remove the children
                while (contentChildren.length > 0) {
                    Array.add(contentChildrenHolding, contentChildren[0]);
                    content.removeChild(contentChildren[0]);
                }
                //add iframe
                content.appendChild(iframe);
                //add back children
                while (contentChildrenHolding.length > 0) {
                    content.appendChild(Array.dequeue(contentChildrenHolding));
                }
            }

        }
        context.obj.showSubNavigation(context.index);
    },

    subNavigationLoadedFailure: function(result, context, method) {
        context.obj._tabs[context.index].loadingStatus = 'failedToLoad';
        context.obj._tabs[context.index].contentDiv.innerHTML = "";
        context.obj.showSubNavigation(context.index);
    },

    showLoadingImage: function(index) {
        if (index >= this._tabs.length) {
            return;
        }
        if (this._tabs[index].loadingStatus == 'loading' && this._loadingImage) {
            this._loadingImage.parentNode.removeChild(this._loadingImage);
            this._tabs[index].tab.appendChild(this._loadingImage);
            Sys.UI.DomElement.setVisible(this._loadingImage, true);
            this._tabs[index].loadingImageIsShowing = true;
        }
    },

    hideLoadingImageTab: function(index) {
        if (this._loadingImage && index < this._tabs.length) {
            Sys.UI.DomElement.setVisible(this._loadingImage, false);
            this._tabs[index].loadingImageIsShowing = false;
        }
    },

    hideLoadingImageForAllTabs: function() {
        if (this._loadingImage) {
            Sys.UI.DomElement.setVisible(this._loadingImage, false);
            for (var x = 0; x < this._tabs.length; x++) {
                this._tabs[x].loadingImageIsShowing = false;
            }
        }
    },

    hideLoadingImageForAllTabsButIndex: function(index) {
        if (this._loadingImage) {
            if (index >= 0 && index < this._tabs.length) {
                for (var x = 0; x < this._tabs.length; x++) {
                    if (index != x) {
                        this._tabs[x].loadingImageIsShowing = false;
                    }
                }
            }
        }
    },

    showSubNavigation: function(index) {
        //see if sub navigation already exists and if so what stte is it in
        if (index >= this._tabs.length) {
            return;
        }
        var tab = this._tabs[index];
        if (!tab.activeTab) {
            return;
        }
        if (tab.timer) {//clears out the tab mouseout hide navigation call
            clearTimeout(tab.timer); tab.timer = null;
        }
        if (tab.displayStatus == 'displaying') {
            return;
        }
        if (!tab.loadingStatus) {//no load of the menu has occured yet
            this.getSubNavigationFromServer(index);
        }
        if (tab.loadingStatus && tab.loadingStatus == 'failedToLoad') {//content failed to load corretly--don't display
            return;
        }
        if (tab.loadingStatus == 'loading') {
            this.showLoadingImage(index);
            this.hideLoadingImageForAllTabsButIndex(index);
        }
        if (tab.loadingStatus == 'loaded') {
            this.hideLoadingImageForAllTabs();
            var tabBounds = Sys.UI.DomElement.getBounds(this._tabs[index].tab);
            Sys.UI.DomElement.setLocation(this._tabs[index].flyOutContent, tabBounds.x, tabBounds.y);
            Sys.UI.DomElement.setVisible(this._tabs[index].flyOutContent, true);
            //swap the tap images
            Sys.UI.DomElement.setVisible(tab.normalImage, false);
            Sys.UI.DomElement.setVisible(tab.activeImage, true);
            tab.displayStatus = 'displaying';
        }
    },

    hideSubNaviagtion: function(index) {
        if (index >= this._tabs.length) {
            return;
        }
        var tab = this._tabs[index];
        //when a tab is mouseout'ed its active property is set to false.
        //this is done with a delay so that the user has a chance to mouseover the exposed content flyout
        if (tab.activeTab) {
            return;
        }
        Sys.UI.DomElement.setVisible(tab.normalImage, true);
        Sys.UI.DomElement.setVisible(tab.activeImage, false);
        Sys.UI.DomElement.setVisible(tab.flyOutContent, false);
        tab.displayStatus = 'hidden';

    },

    //this method is triggered by the tab mouseout.  By using a delay we allow the use a chance to mouseover the exposed content area.
    hideSubNavigationWithDelay: function(index) {
        if (index >= this._tabs.length) {
            return;
        }
        //change the active status on a delay to allow the mouse to rollovers on a delay
        var tab = this._tabs[index];
        if (!tab.timer) {
            tab.timer = setTimeout(
                Function.createDelegate(
                    this, function() {
                        this._tabs[index].activeTab = false; this.hideSubNaviagtion(index); this._tabs[index].timer = null;
                    }
                ),
            100);
        }
    },

    onGetSubNavigationError: function(error, context, methodName) {
        context.cancelTimedDelay(); //clears out any pending timedDelays for displaying the subNavigation
    },

    cancelTimedDelay: function() {
        if (context._timedDelay) {
            clearTimeout(context._timedDelay);
            context._timedDelay = null;
        }
    },

    hideOtherTabs: function(index) {
        for (var x = 0; x < this._tabs.length; x++) {
            if (x == index) {
                continue;
            }
            this._tabs[x].activeTab = false;
            this.hideSubNaviagtion(x);
        }
    },

    // Event Handlers 

    // clears out current sub nav
    onTabMouseOver: function(evt, index) {
        if (index >= this._tabs.length) {
            return;
        }
        //makesure the other tabs are not showing
        this._tabs[index].activeTab = true;
        this.hideOtherTabs(index);
        this.showSubNavigation(index);
    },


    onTabMouseOut: function(evt, index) {
        if (index >= this._tabs.length) {
            return;
        }
        //change the active status on a delay to allow the mouse to rollovers on a delay
        this.hideSubNavigationWithDelay(index);
        if (this._tabs[index].loadingImageIsShowing) {
            this.hideLoadingImageTab(index);
        }

    },

    onContentContainerMouseOver: function(evt, index) {
        if (index >= this._tabs.length) {
            return;
        }
        if (this._tabs[index].timer) {
            clearTimeout(this._tabs[index].timer);
            this._tabs[index].timer = null;
        }
        this.showSubNavigation(index);


    },

    onContentContainerMouseOut: function(evt, index) {
        if (index >= this._tabs.length) {
            return;
        }
        this.hideSubNavigationWithDelay(index);
    },

    onContentMouseOver: function(evt) {
        evt.stopPropagation;
    },

    onContentMouseOut: function(evt) {
        evt.stopPropagation;
    },

    /* properties  */
    get_loadingImageSrc: function() {
        return this._loadingImageSrc;
    },

    set_loadingImageSrc: function(value) {
        this._loadingImageSrc = value;
    }
}
GiantEagle.IVET.SubjectAreaNavigationControl.registerClass('GiantEagle.IVET.SubjectAreaNavigationControl', Sys.UI.Control);

if (typeof (Sys) !== 'undefined') { Sys.Application.notifyScriptLoaded(); }
