﻿Type.registerNamespace('Sunny.Web');
Type.registerNamespace('Sunny.Web.UI'); 

Sunny.Web.UI.ModalExtender = function(flElement)
{     
    /// <summary>
    /// Implements modality functionality for an element.   
    /// </summary>               
    this._windowResizeDelegate = null;
    this._windowScrollDelegate = null;   
    
    this._xCoordinate = -1;
    this._yCoordinate = -1;
    this._backgroundElement = null;
    this._foregroundElement = flElement;
                    
    this._saveTabIndexes = new Array();
    this._saveDesableSelect = new Array();
    this._tagWithTabIndex = new Array('A','AREA','BUTTON','INPUT','OBJECT','SELECT','TEXTAREA','IFRAME');        
}

Sunny.Web.UI.ModalExtender.prototype = {    
            
    dispose : function()
    {
       /// <summary>
       /// Detaches and disposes eventhandlers       
       this.hide();
       this._backgroundElement = null;
       this._foregroundElement = null;
    },
     
    show : function()
    {
        this._attachWindowHandlers(true);    
        //Append the modal overlay
        var elem = this._getModalOverlay(); 
        var foregroundElement = this._foregroundElement;               
        foregroundElement.parentNode.appendChild(elem);
        
        //Set z-Index
        var zIndex = $Sunny.getCurrentStyle(foregroundElement, 'zIndex');
        // In case the foregroundElement does not have a zIndex specified, leave the default zIndex for the overlay element, namely 10000.
        if(!isNaN(parseInt(zIndex)))
        {
            elem.style.zIndex = zIndex - 1;// + 1;  
        }              
        
        //Make the overlay visible
        elem.style.display = '';                        
        
        //Disable TAB
        this._disableTab();
        
//Disable page scrolling        
//Disabling scrolling in Mozilla, causes page to jump. When jumping is compensated, it causes the page to flicker - which is not fixable             
//        this._storeBrowserPosition();        
//        this._enableScroll(false);//MOZ problem - disabling scrolling causes the page to scroll to top
//        this._restoreBrowserPosition();

        //Calculate the overlay size
        this._updatePageLayout();
        // On pages that don't need scrollbars, Firefox and Safari act like
        // one or both are present the first time the layout code runs which
        // obviously leads to display issues - run the layout code a second
        // time to work around this problem
        this._updatePageLayout();
    },
    
    _storeBrowserPosition : function()
    {	    
	    var oBody = document.body;
	    var oDoc = document.documentElement;	
	    this._browserTop  = oBody.scrollTop > oDoc.scrollTop ? oBody.scrollTop  : oDoc.scrollTop;	
	    this._browserLeft = oBody.scrollLeft > oDoc.scrollLeft ? oBody.scrollTop : oDoc.scrollLeft;	
    },

    _restoreBrowserPosition : function(left, top)
    {
	    try
	    {
	        if (null == left) left = this._browserLeft;
	        if (null == top) top = this._browserTop;
	        
		    var oBody = document.body;
		    var oDoc = document.documentElement;		    
		    oBody.scrollTop = top;
		    oBody.scrollLeft = left;
		    oDoc.scrollTop  = top;
		    oDoc.scrollLeft = left;
	    }
	    catch(ex){};
    },
    
    hide : function()
    {                
        //this._backgroundElement.style.display = 'none';        
        this._restoreTab();
//Disabling scrolling in Mozilla, causes page to jump. When jumping is compensated, it causes the page to flicker - which is not fixable     
//        this._enableScroll(true);
        this._attachWindowHandlers(false);
        
        //NEW: In IE a semitransparent overlay causes about 5MB of memory increase (IE obviously loads external code to process transparency).
        //So, to reduce memory used, the this._backgroundElement is removed from the DOM
        var elem = this._backgroundElement;
        if (elem)
        {
            elem.parentNode.removeChild(elem);
            this._backgroundElement = null;
        }
    },     
        
    _enableScroll : function(enable)
    {    
        if (enable)
	    {		        
		    document.body.style.overflow = null != this._overflow ? this._overflow : '';		    
		    document.documentElement.style.overflow = null != this._documentOverflow ? this._documentOverflow : '';
		    
		    document.body.style.marginRight = '';
	    }
	    else
	    {		
	        this._overflow = document.body.style.overflow;	        	        	        
		    document.body.style.overflow = 'hidden';
		    
		    this._documentOverflow = document.documentElement.style.overflow;
		    document.documentElement.style.overflow = 'hidden';
		    
		    //!TODO: Better implementation to prevent the scroller from shaking the page when being hidden 
		    document.body.style.marginRight = '18px';		    
	    }
    },
    
    _getModalOverlay : function()
    {
        if (!this._backgroundElement)
        {
            var div = document.createElement('div');
            div.style.display = 'none';
            div.style.position = 'absolute';
            if($Sunny.isRightToLeft(this._foregroundElement))
            {
                div.style.right = '0px';
            }
            else
            {
                div.style.left = '0px';
            }
            
            div.style.top = '0px';        
            div.style.zIndex = 10000;            
            div.style.backgroundColor = "#aaaaaa";
            div.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=50)";
            div.style.opacity = ".5";
            div.style.mozOpacity = ".5";
            
            //make the modal overlay unselectable
            //works only under IE, not under FF
            //overlay.style["-moz-user-select"] = "none" does not work under FF, too
            div.setAttribute("unselectable","on");
            
            //Classname should be set to allow for devs to output it on the page, and style the DIV
            div.className = "SunnyModalOverlay";
                                    			
            
            this._backgroundElement = div;
        }
        return this._backgroundElement;                
    },
                                        
    _attachWindowHandlers : function(attachEvent)
    {
        var targetElement = window;//document;
        
        if (true == attachEvent)
        {            
            this._windowResizeDelegate = Function.createDelegate(this, this._updatePageLayout);                                
            $addHandler(targetElement, 'resize', this._windowResizeDelegate);  
            
            this._windowScrollDelegate = Function.createDelegate(this, this._updatePageLayout);                                
            $addHandler(targetElement, 'scroll', this._windowScrollDelegate);                          
         }
         else
         {                          
            if (this._windowResizeDelegate) $removeHandler(targetElement, 'resize', this._windowResizeDelegate);                                   
            this._windowResizeDelegate = null;
            
            if (this._windowScrollDelegate) $removeHandler(targetElement, 'scroll', this._windowScrollDelegate);                                   
            this._windowScrollDelegate = null;
         }    
    }, 
                               
    _updatePageLayout : function() {
        
        ///Make the overlay div as big as the page        
        var scrollLeft = (document.documentElement.scrollLeft ? $Sunny.getCorrectScrollLeft(document.documentElement) : $Sunny.getCorrectScrollLeft(document.body));
        var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
        var clientBounds = $Sunny.getClientBounds();
        var clientWidth = clientBounds.width;
        var clientHeight = clientBounds.height;
        
        var elem = this._getModalOverlay();        
        elem.style.width = Math.max(Math.max(document.documentElement.scrollWidth, document.body.scrollWidth), clientWidth)+'px';
        elem.style.height = Math.max(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight), clientHeight)+'px';           
    },
    
     _disableTab : function() {        
        /// Change the tab indices so we only tab through the modal popup
        /// (and hide SELECT tags in IE6)
        
        var i = 0;
        var tagElements;
        var tagElementsInPopUp = new Array();
        Array.clear(this._saveTabIndexes);

        //Save all popup's tag in tagElementsInPopUp
        for (var j = 0; j < this._tagWithTabIndex.length; j++) {
            tagElements = this._foregroundElement.getElementsByTagName(this._tagWithTabIndex[j]);
            for (var k = 0 ; k < tagElements.length; k++) {
                tagElementsInPopUp[i] = tagElements[k];
                i++;
            }
        }

        i = 0;
        for (var j = 0; j < this._tagWithTabIndex.length; j++) {
            tagElements = document.getElementsByTagName(this._tagWithTabIndex[j]);
            for (var k = 0 ; k < tagElements.length; k++) {
                if (Array.indexOf(tagElementsInPopUp, tagElements[k]) == -1)  {
                    this._saveTabIndexes[i] = {tag: tagElements[k], index: tagElements[k].tabIndex};
                    tagElements[k].tabIndex="-1";
                    i++;
                }
            }
        }

        //IE6 Bug with SELECT element always showing up on top
        i = 0;
        if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
            //Save SELECT in PopUp
            var tagSelectInPopUp = new Array();
            for (var j = 0; j < this._tagWithTabIndex.length; j++) {
                tagElements = this._foregroundElement.getElementsByTagName('SELECT');
                for (var k = 0 ; k < tagElements.length; k++) {
                    tagSelectInPopUp[i] = tagElements[k];
                    i++;
                }
            }

            i = 0;
            Array.clear(this._saveDesableSelect);
            tagElements = document.getElementsByTagName('SELECT');
            for (var k = 0 ; k < tagElements.length; k++) {
                if (Array.indexOf(tagSelectInPopUp, tagElements[k]) == -1)  {
                    this._saveDesableSelect[i] = {tag: tagElements[k], visib: $Sunny.getCurrentStyle(tagElements[k], 'visibility')} ;
                    tagElements[k].style.visibility = 'hidden';
                    i++;
                }
            }
        }
    },

    _restoreTab : function() {        
        /// Restore the tab indices so we tab through the page like normal
        /// (and restore SELECT tags in IE6)        

        for (var i = 0; i < this._saveTabIndexes.length; i++) {
            this._saveTabIndexes[i].tag.tabIndex = this._saveTabIndexes[i].index;
        }

        //IE6 Bug with SELECT element always showing up on top
        if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
            for (var k = 0 ; k < this._saveDesableSelect.length; k++) {
                this._saveDesableSelect[k].tag.style.visibility = this._saveDesableSelect[k].visib;
            }
        }
    }
};

Sunny.Web.UI.ModalExtender.registerClass('Sunny.Web.UI.ModalExtender', null);

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();