/* The global Stericycle Javascript */
var Stericycle = {
    Plans: {
        HazCom: {}
        , ECP: {}
        , EP: {}
        , SH: {}
    } 
    , Controls: { 
                HelpControl: { },
                PlanFileResource: { },
                MultiEmployeeSelect: {}
              },
    Enum: { 
        'CheckboxIndicatorImage' : "<img src='../images/loading_indicator.gif' align='top' style='padding: 3px' />"
    }
    ,Localization: []
};

/* Javascript for the HelpControl. 
   Dependencies:  Prototype
*/
Stericycle.Controls.HelpControl = {
    currentUrl: "", 
    currentWindow: "", 
    helpControl: "",
    _x: 0,  
    _y: 0,
    _xOffset: 0,
    _yOffset: 0,
    _timer: -1,
    hideDelay: 700,  /* how long we show the div before hiding it */
    
    Initialize: function()
    {
        var me = this;
    },
    
    LaunchContent: function( cnid, helpControl )
    {
        //console.log( 'hello!' );
        //console.log( this );
        this.helpControl = helpControl;
        var url = SITE_RELATIVE_URL + '/Controls/HelpContent.aspx?cnid=' + cnid;
        this.Open( url );
        
        /* also need to attach event handler for the control */
        var me = this;
        // Event.observe( this.helpControl, "mouseover", function( e ) { me.ControlMouseOverHandler( e ); }, false );
        // Event.observe( this.helpControl, "mouseout", function( e ) { me.ControlMouseOutHandler( e) }, false );

        /* make the ? draggable */
        // new Draggable( this.helpControl, { } ); 
        
        // console.log( this + this.title );      

    },
    /* create a helpWindow hidden at the bottom of the body */
    _CreateWindow: function()
    {
        if( !this.currentWindow )
        {
            var html = '<div id="helpWindow" class="hc_helpWindow_container" style="position:absolute;display:block;z-index: 999;">';
            //html += '<div class="hc_helpWindow_title"><a href="javascript:Stericycle.Controls.HelpControl.Hide()">Close</a></div>';
            html += '<div class="hc_helpWindow_content"><div style="text-align: right;" class="hc_helpWindow_title"><a href="javascript:Stericycle.Controls.HelpControl.Hide()">Close X</a></div><iframe id="helpWindowUrl" name="helpWindowUrl" src="" width="100%" frameborder="0"/></div>';
            html += '</div>';
            new Insertion.Bottom( document.body , html );
            this.currentWindow = $( 'helpWindow' );
            this.currentWindow.hide();
            this.currentWindowUrl = $( 'helpWindowUrl' );
            
            // make the help window draggable
            // new Draggable( this.currentWindow, { handle: 'hc_helpWindow_title' } );
            
            
            /* attach the event */
            var me = this;
            // Event.observe( this.currentWindow, "mouseover", function( e ) { me.WindowMouseOverHandler( e ); }, false );
            // Event.observe( this.currentWindow, "mouseout", function( e ) { me.WindowMouseOutHandler( e) }, false );
            return true;
        }
    },

    /* Open the window */
    Open: function( url )
    {
        this._CreateWindow();
        this.currentWindow.show();
        var coords = Position.cumulativeOffset( this.helpControl );
            
        var positions = [ 
                           /* bottom right quadrant: default */ 
                          { topLeft: { top: coords[1] + this.helpControl.clientHeight, left: coords[0] + this.helpControl.clientWidth },
                            bottomRight: { top: coords[1] + this.currentWindow.clientHeight + this.helpControl.clientHeight, left: coords[0] + this.currentWindow.clientWidth } 
                          },
                           /* bottom left quadrant */
                          { topLeft: { top: coords[1] + this.helpControl.clientHeight, left: coords[0] - this.currentWindow.clientWidth },
                            bottomRight: { top: coords[1] + this.currentWindow.clientHeight, left: coords[0] } 
                          },                      
                          /* top left quadrant */ 
                          { topLeft: { top: coords[1] - this.currentWindow.clientHeight, left: coords[0] - this.currentWindow.clientWidth - 10},
                            bottomRight: { top: coords[1] , left: coords[0] - this.helpControl.clientWidth} 
                          },
                          /* top right quadrant */
                          { topLeft: { top: coords[1] - this.currentWindow.clientHeight, left: coords[0] } ,
                            bottomRight: { top: coords[1], left: coords[0] + this.currentWindow.clientWidth } 
                          }
                        ];
        
        
        /* get the coordinate of the viewport to compare with the coordinates of the popup div */
        var viewportSize = { width: ( document.documentElement.clientWidth || document.body.clientWidth ),
                             height: ( document.documentElement.clientHeight || document.body.clientHeight ) } 

        
        /* cal
        
        
        /* to check if a position is okay, we check the boundary of the div to see if it's within the viewable area.
           - if yes:  use that positionculate the topLeft and BottomRight corner of the viewport so that we can use these 2 points 
           for comparison with the previously computed positions
        */
        /* calculating the scroll position */
        var scroll = { top:window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop ,left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft}
        var viewport = { topLeft: {top: scroll.top , left: scroll.left , toString: function() { return this.top + "," + this.left} }, 
                         bottomRight: { top: scroll.top + viewportSize.height, left: scroll.left + viewportSize.width, toString: function() { return this.top + "," + this.left} }
                       }
        /* which position will we display, if all things fail, then use the default value assigned here */
        var whichPosition = 0;
        /*
           - if no:  skip
           - if all the 4 positions failed, use the default position
        */
        for( i = 0; i < positions.length; i++ )
        {
            if( positions[i].topLeft.left >= viewport.topLeft.left && positions[i].topLeft.left <= viewport.bottomRight.left && 
                positions[i].topLeft.top >= viewport.topLeft.top && positions[i].topLeft.top <= viewport.bottomRight.top &&
                positions[i].bottomRight.left >= viewport.topLeft.left && positions[i].bottomRight.left <= viewport.bottomRight.left && 
                positions[i].bottomRight.top >= viewport.topLeft.top && positions[i].bottomRight.top <= viewport.bottomRight.top
              )
            { 
                whichPosition = i;
                break;
            }
        } 
        this.currentWindow.style.top = ( positions[ whichPosition].topLeft.top ) + "px";
        this.currentWindow.style.left = ( positions[ whichPosition].topLeft.left ) + "px";
        this.SetUrl( url );
        
    },

    /* Set the souce of the iFrame.  Do some checking for caching purposes */
    SetUrl: function( url )
    {
        this.currentUrl = url;
        this.currentWindowUrl.src = url;
    },

    /* Event to handle the MouseOut/ Over */
    WindowMouseOverHandler: function( e )
    {
        clearTimeout( this._timer );
        this._timer = -1;
    },

    WindowMouseOutHandler: function( e )
    {
        var me = this;
        this._timer = setTimeout( function(){me.Hide();}, 700 );
    },

    /* Event to handle the MouseOut/ Over */
    ControlMouseOverHandler: function( e )
    {
        clearTimeout( this._timer );
        this._timer = -1;
    },

   ControlMouseOutHandler: function( e )
    {
        var me = this;
        if( this._timer < 0 ) this._timer = setTimeout( function(){me.Hide();}, this.hideDelay ); 
    },

    Hide: function()
    {
        this.currentWindow.hide();
        clearTimeout( this._timer );
        this._timer = -1;
    },

    LaunchEditor: function( ContentName )
    {
        /* have to get the rad window object into here.  Travese the document window up to the top */
        var parent;
        do{ parent = window.parent; } while ( parent != window.top ) 
        parent.radopen( SITE_RELATIVE_URL + "/Admin/Editor.aspx?id=" + ContentName, "EditorWindow");
    }
}

/* make sure it's legal to execute the help.  Otherwise IE will crash */
Stericycle.Controls.HelpControl.Initialize();


/**********************************************
 * This "Static" Class/Object is used to display
 * a page loading indicator.  The position is calculated
 * on the fly regarding the scroll position and window's size.
 */
Stericycle.Controls.PageLoadingIndicator = {
    name: "PageLoadingIndicator",
    indicator: "",
    eventHandlers : {
        onScroll: function( e ) { this._setPosition() },
        onResize: function( e ) { this._setPosition() }
    },
    boundEventHandlers: {
        onScroll: "",
        onResize: ""
    },
    
    isReady: false,
    
    /**
     * option: {duration: int - howlong we show the indicator for }
     * callback : { onShow: functionName, onHide: functionName }
     */
    Show: function( option, callback )
    {
        
        this._Create();
        var duration = 0;
        
        this.isModal = false;
        
        /* getting the option */
        if( option )
        {
            duration = ( option.duration ) ? option.duration : "";
            this.isModal = ( option.isModal ) ? option.isModal : false;
        }
        
        if( duration )
        {
            var me = this;
            setTimeout( function() { me.Hide(); }, duration );
        }
        
       
//        if (Prototype.Browser.IE){
//            this.getScroll();
//            //this.prepareIE('100%', 'hidden');
//            //this.setScroll(0,0);
//            this.overlay.style.margingTop= this.yPos;
//            //this.hideSelects('hidden');
//        }
    
   
        this.indicator.show();
//        if( this.isModal )
//        {
//        
//        }
//        
        
            this.overlay.show();
            //Element.absolutize(this.overlay);
            
            this.overlay.style.display="block";
            this.indicator.style.display="block";
            
        /* align the div in the middle of the screen */
        this._setPosition();
        /* attach onscroll event to correctly set the position of the div when user scroll the page 
           we have to "cache" the eventHandler function separately so that later on we can stopObserving it 
        */
        this.boundEventHandlers.onScroll = this.eventHandlers.onScroll.bindAsEventListener( this );
        this.boundEventHandlers.onResize = this.eventHandlers.onResize.bindAsEventListener( this );
        Event.observe( window, 'scroll', this.boundEventHandlers.onScroll );
        Event.observe( window, 'resize', this.boundEventHandlers.onResize );
        /* allow the user to click and close the indicator */
        Event.observe( this.indicator, 'click', function(e){ this.Hide() }.bind(this) );

    },
    
    /**
     * Create the indicator div 
     */
    _Create: function()
    {
        if( !this.indicator )
        {
            var html = '<div id="pg_indicator_overlay" class="pg_indicator_overlay"></div><div id="stericycle_indicator" class="pg_indicator_container" style="position:absolute;z-index: 9999;"><img src="' + SITE_RELATIVE_URL + '/images/loading.gif" align="middle"/> <span class="pg_indicator_text">Loading...</span></div>';
             
            new Insertion.Top( document.body , html );
            this.indicator = $( 'stericycle_indicator' );
            this.overlay = $('pg_indicator_overlay');
            this.isReady = true;
        }
        
    },

    /**
     * Hide the idicator div & execute onHide callback
     */
    Hide: function()
    {
        if( this.indicator )
        {
            this.indicator.hide();
            this.overlay.hide();
            Event.stopObserving( window, 'scroll', this.boundEventHandlers.onScroll );
            Event.stopObserving( window, 'resize', this.boundEventHandlers.onResize );
        /*    
            if (Prototype.Browser.IE){
                this.setScroll(0,this.yPos);
                this.prepareIE("auto", "auto");
               //this.hideSelects("visible");
            }
            */
        }
    },
    
    /**
     * Calculate the position of the indicator
     */
    _setPosition: function()
    {
        if( this.indicator )
        {
            var viewportSize = { width: ( document.documentElement.clientWidth || document.body.clientWidth ),
                                 height: ( document.documentElement.clientHeight || document.body.clientHeight ) } 
            var scroll = { top:window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop ,left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft}
            this.indicator.style.top = ( ( viewportSize.height / 2 ) + scroll.top - this.indicator.clientHeight/2 ) + "px";
            this.indicator.style.left = ( ( viewportSize.width / 2 ) + scroll.left - this.indicator.clientWidth/2 ) + "px";

            if (Prototype.Browser.IE)
            {
                this.overlay.style.position ="absolute";
                this.overlay.style.top = scroll.top + "px";
            }

        }
    },
    getScroll:function (){
        var yScroll;

        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop; 
        } else if (document.body) {// all other Explorers
            yScroll = document.body.scrollTop;
        }
            this.yPos = yScroll;
    },

    setScroll:function(x, y){
        window.scrollTo(x, y); 
    },
    
    prepareIE: function(height, overflow){
        bod = document.getElementsByTagName('body')[0];
        bod.style.height = height;
        bod.style.overflow = overflow;

        htm = document.getElementsByTagName('html')[0];
        htm.style.height = height;
        htm.style.overflow = overflow; 
    },

    toString: function() { return "Stericycle.Controls.PageLoadingIndicator"; }
};
// Event.observe( window, 'load', function() { Stericycle.Controls.PageLoadingIndicator.Show(); } );

/* Persisting the MultiEmployeeSelect to a hidden field */
Stericycle.Controls.MultiEmployeeSelect.updateEmployeeMultiSelect = function( container, checkbox )
{
    // console.log( container );
    var hf = $(container).up().up().select( "input[container='" + container + "']" )[0];
    var siteEmployeeId = $( checkbox ).up('.empMultiSelect_checkbox_container').getAttribute( 'siteEmployeeId' );
    var isChecked = checkbox.checked ? true : false;
    /* Remove item from the comma-dellimited list and append it afterwards at the end of the string */
    /* match 234:true, or 234:false (with/without comma) */
    var re = new RegExp( siteEmployeeId + "[^,]+,?" );
    hf.value = hf.value.replace( re, "" ); 
    hf.value += "," + siteEmployeeId + ":" + isChecked + ",";
    
    /* remove beginning,last and unnesseary commas */
    hf.value = hf.value.replace(/,{2,}/g, "," );
    if( hf.value.startsWith(",") ) { hf.value = hf.value.substring( 1, hf.value.length ); }    
    if( hf.value.endsWith(",") ) { hf.value = hf.value.substring( 0, hf.value.length -1 ); }    
    // alert( hf.value );
}

/* Reset the hidden field */
Stericycle.Controls.MultiEmployeeSelect.toggleLabelsEnable = function( container, checkbox )
{
    /* reset the hidden field */
    $(container).up().up().select( "input[container='" + container + "']" )[0].value = "";
    var formLabels;
    $(container).select(".employee_checkbox").each( function( item ) {        
        if( checkbox.checked ) 
        {
            $(item).removeClassName('formlabel').addClassName('disablelabel').firstChild.checked = false;
            $(item).firstChild.disabled = true;   
            // console.log( 'disable lablel' + $(item).className );
        }
        else
        {
            $(item).removeClassName('disablelabel').addClassName('formlabel').firstChild.disabled = false ;
	    if ($(item).hasAttribute('disabled'))
		{
			$(item).removeAttribute('disabled');
		}
            // console.log( 'enable lablel' + $(item).className );
        }
    } );
}

/* Persit the selection for each checkbox */
Stericycle.Plans.HazCom.updateHC_TapItem = function( checkbox, container, hfId )
{
    var id = $(checkbox).up("span").getAttribute('item_value');
    var hfValue =  $F(hfId);
    /* Remove item from the comma-dellimited list and append it afterwards at the end of the string */
    /* match 234:true, or 234:false (with/without comma) */
    var re = new RegExp( id + "[^,]+,?" );
    hfValue = hfValue.replace( re, "" );
    hfValue += "," + id + ":" + checkbox.checked + ",";
    
    /* remove beginning,last and unnesseary commas */
    hfValue = hfValue.replace(/,{2,}/g, "," );
    if( hfValue.startsWith(",") ) { hfValue = hfValue.substring( 1, hfValue.length ); }    
    if( hfValue.endsWith(",") ) { hfValue = hfValue.substring( 0, hfValue.length -1 ); }
    $(hfId).value = hfValue;
}
