﻿/* GLOBAL VARIABLES */
var associationHandlerUrl = "../Controls/AssociationHandler.ashx";

var today = new Date();
var currentyear =today.getFullYear();


// JScript File
function GetRadWindow()   
{   
    var oWindow = null;   
    if (window.radWindow) oWindow = window.radWindow; 
    else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;  
    return oWindow;   
}   

function RadWindowClose(sender)
{
    var radWindow = GetRadWindow();
    radWindow.Argument = sender.id;
    radWindow.Close();
}

function CloseModal()
{
    var radWindow = GetRadWindow();
    radWindow.Close();
}

function LaunchVideo(path)
{
   var width = 900;
   var height = 500;
   var left = ( screen.width - width ) / 2;
   var top = ( screen.height - height ) /2;
   var options = 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left;
   // console.log( options );
   window.open(path,'mywindow', options );
}

function SizeToFit()
{
    window.setTimeout( function()
        {
            var oWnd = GetRadWindow();
            oWnd.SetWidth(document.body.scrollWidth + 4);
            oWnd.SetHeight(document.body.scrollHeight + 70);
        }, 400);
}

function LaunchEditor(contentName, fileLocation, type)
{
 //   var radWindow = window.radopen(fileLocation +"?id=" + contentName +"&t="+type , "EditorWindow");
    
    //radWindow.SetSize( 492, 573);
    
   var parent;
   do{ parent = window.parent; } while ( parent != window.top ) 
   var radWindow = parent.radopen(fileLocation +"?id=" + contentName +"&t="+type , "EditorWindow");
   radWindow.SetSize( 560, 573);
   radWindow.Center();     
   return false;
   
}

   /*eflores 5.6.10  addition of js function to display new message*/
    function LaunchMessage(MessageType)
    {
         var parent;
        do{ parent = window.parent; } while ( parent != window.top ) 
        var radWindow = parent.radopen( SITE_RELATIVE_URL + "/Information/message.aspx?type=" + MessageType, "EditorWindow");
        radWindow.SetSize(400,318);           
        radWindow.Center();
        return false;
    }

        
function OnClientClose(e)
{
    // debug code
    //console.log("RadWndow Closing");
    //var radWindow = GetRadWindow();
    // console.log("Show splash");
    
    /* TODO:  only show if page is being refreshed */
    // Stericycle.Controls.PageLoadingIndicator.Show({duration: 1500}); 
}


function CloseModalWindow(sender)
{
    var radWindow = GetRadWindow();
    // use this to determine if we need to refresh drop down
    radWindow.Argument = sender;
    radWindow.Close();
}


function DoAjaxRequest(ajaxManager, requestArg, callback )
{
    /* Added by Alex to enable custom event-hooking */
    if( callback )
    {
        callback.name( callback.options );
    }
    /*********************
    // NOTE: Firefox workaround for Error 
    // Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIXMLHttpRequest.open]"
    // Result: http://www.telerik.com/community/forums/thread/b311D-mheaa.aspx
    *********************/
    window.setTimeout(function() {
        // Do the callback, 100 miliseconds after, and not right away
        ajaxManager.AjaxRequest(requestArg);
    }, 100);
    

            
}

/* Toggles checkboxes check value for all checkboxes in the container */
function ToggleCheckedSelection(sender, containerId, callback, options)
{
    if(sender.checked)
    {
        CheckAll(containerId);
    }
    else
    {
        UnCheckAll(containerId);
    }
    
    // console.log( 'executing callback ' + callback );
    
    // console.log( options );
    
    /* Hook the call back to execute the event after we uncheck/ check the items */
    if( callback != null )
    {
        /* pass in the containerId, make sure we have the options */
        if( options == null )
        {
            options = {};
        }
        
        options.containerId = containerId;
        options.checkbox = sender;
        callback( options );
    }
    
}

/*eflores : for issue 472, 443 : javascript function to uncheck any selected and disable the container */
function ToggleCheckedSelectionForMultiSelect(sender,containerId)
{
    // console.log('MultiSelect Checkbox Click');
    ToggleInputEnableForMultiSelect(sender,containerId);    
    if (sender.checked)
    {
        UnCheckAll(containerId);
    }
}

/* Select all the checkbox found in the container */
function CheckAll(containerId)
{
    var container = $(containerId);
    var checkboxList  = container.getElementsByTagName("input");
    
    for (i = 0; i < checkboxList.length; i++)
    {
	    checkboxList[i].checked = true ;
	}
}

/* Unselects all the checkboxes found in the container */
function UnCheckAll(containerId)
{
    var container = $(containerId);
    var checkboxList  = container.getElementsByTagName("input");
    
    for (i = 0; i < checkboxList.length; i++)
    {
	    checkboxList[i].checked = false ;
	}
}

/* for all input controls in the container, the disabled property will be toggled */
function ToggleInputEnable(sender, containerId)
{
    
    var container = $(containerId);
    var inputListControls  = container.getElementsByTagName("input");
    
    for (i = 0; i < inputListControls.length; i++)
    {
	    inputListControls[i].disabled = !sender.checked;
	}
	
	ToggleLabelsEnable(sender, containerId);
}
/* for all input controls in the container, the disabled property will be toggled */
/*eflores : for issue 472, 443 : javascript function to uncheck any selected and disable the container */
function ToggleInputEnableForMultiSelect(sender, containerId)
{
    
    var container = $(containerId);
    var inputListControls  = container.getElementsByTagName("input");
    
    for (i = 0; i < inputListControls.length; i++)
    {     
         
        if (sender.checked)
        {        
             inputListControls[i].disabled = true;
             inputListControls[i].parentNode.disabled = true;
        }
        else
        {
            inputListControls[i].disabled = false;
            inputListControls[i].parentNode.disabled = false;
        }	     
        
	}
}



function BuildCheckListModalWindowArgument(containerId)
{
    
    var container = $(containerId);
    var checkListItems  = container.getElementsByTagName("input");
    var callBackArgument = "";
    
    for (i = 0; i < checkListItems.length; i++)
    {    
        var inputCheck = 0;
        if( checkListItems[i].checked)
        {
            inputCheck = 1;
        }
        
        var checkListText = checkListItems[i].nextSibling.innerHTML;
        // Format the string
        callBackArgument += String.Format("[{0}|{1}|{2}]",checkListItems[i].value, checkListText,  inputCheck);
  
        // Append the delimiter if there are more items in the list
        if(i < checkListItems.length -1)
        {
            callBackArgument += ",";
        }
        
	}
	
	return callBackArgument;
}



String.Format = function()
{
    // Check for arguments
    if( arguments.length == 0 ) return null;
    // Get the string which is the first argument
    var stringToFormat = arguments[0];
    for(var i=1; i < arguments.length;i++)
    {
        var replaceExpression = new RegExp('\\{' + (i-1) + '\\}','gm');
        // Replace argument
        stringToFormat = stringToFormat.replace(replaceExpression, arguments[i]);
    }

    // Return the formated string
    return stringToFormat;
}



function ToggleTextAreaEnable(sender,containerId)
{
    
    var container = $(containerId);
    var inputListControls  = container.getElementsByTagName("textarea");
    
    for (i = 0; i < inputListControls.length; i++)
    {
	    inputListControls[i].disabled = !sender.checked;
	}
	
	ToggleLabelsEnable(sender, containerId);
}

function ToggleLabelsEnable(sender, containerId)
{ 
    var container = $(containerId);
    var formLabels;
    var disable = false;
    // If the check box was just checked, then toggle to enable
    

    if(sender.checked)
    {
        formLabels  = container.getElementsByClassName("disablelabel");
    }
    else
    {   
        formLabels  = container.getElementsByClassName("formlabel");
        disable = true;
    }
        
    for (i = 0; i < formLabels.length; i++)
    {
        if(disable)
        {
            formLabels[i].removeClassName('formlabel');
            formLabels[i].addClassName('disablelabel'); 
        }
        else
        {
            formLabels[i].removeClassName('disablelabel');
            formLabels[i].addClassName('formlabel'); 
        }        
    }
	
}

function IsPhoneValid(phoneValue)
{    
    // Remove the input value Mask
    phoneValue = phoneValue.replace("(", "").replace(")", "").replace("-", "").replace(" ", "");
       
    if(phoneValue =="911")
    {
        return true;
    }
    
    var myregexp = /^(\d{10})$/;// Check for 10 digits
    if (phoneValue.match(myregexp)) 
    {
	    return true;	    
    }
   else 
   {   
         return false;
    }

}


function ValidateTelephone(sender,args)
{
        if(IsPhoneValid(args.Value))
        {
            args.IsValid = true;
            HideValidatorSummaryBox();
        }
        else
        {
            args.IsValid = false;
             ShowValidatorSummaryBox();
        }
}

        
/******************************************************  */
/* This section is for different Association pages */
    /**
     * Run through the checkbox list within a container
     * and request the AJAX accordingly
     */
    function batchUpdateCheckBoxList( options )
    {
        
        /* prevent the checkbox from getting click while it is being processed */
        if( !$(options.checkbox).visible() )
        {
            $(options.checkbox).checked = !$(options.checkbox).checked;
            // console.log( 'crazy user clicks' );
            return 
        }

        var json = new Array();
        /* we do have teh containerId in the options callback argument */
        $A( $$( "#" + options.containerId + " input" ) ).each( function( checkbox ) {
            /* delegate to the options' collectData method */
            json[ json.length ] = options.collectData( { "checkbox": checkbox } );
        } );
        

        /* Only submit if we have something in the json */
         if( json.length > 0 )
         {
            var url = associationHandlerUrl ;
            var params = "type=" + options.type + "&options=" + Object.toJSON( json );
            //console.log( params );
            
            // console.log( url );
            new Ajax.Request( url, {
                method: 'POST',
                parameters: params, 
                onCreate: function() {
                    batchUpdateOnCreateHandler( options );
                }, 
                onSuccess: function(response) {

                    if( response.responseText.strip() != 'OK' )
                    {
                        batchUpdateErrorHandler( options );
                    }
                    else
                    {
                        $( options.checkbox ).up().removeClassName( 'checkbox_error' );
                        batchUpdateSuccessfulHandler( options );
                    }
                },
                onFailure: function( response ){ 
                    batchUpdateErrorHandler( options ); 
                },
                onComplete: function( response )
                {
                    batchUpdateOnCompleteHandler( options );
                }
            } );        
        }
    };
    
    function batchUpdateOnCreateHandler( options ) 
    {
        
        $( options.checkbox ).hide();
        Element.insert( $( options.checkbox ), { "after": Stericycle.Enum.CheckboxIndicatorImage } );
        $A( $$( "#" + options.containerId + " input" ) ).each( function( checkbox ) {
            $( checkbox ).hide();
            Element.insert( $( checkbox ), { "after": Stericycle.Enum.CheckboxIndicatorImage } );
        } );        
    };
    
    function batchUpdateOnCompleteHandler( options ) 
    {
        $( options.checkbox ).show();
        Element.remove( $(options.checkbox).nextSibling );
        $A( $$( "#" + options.containerId + " input" ) ).each( function( checkbox ) {
            Element.remove( $(checkbox).nextSibling );
            $( checkbox ).show();
            // Element.insert( $( checkbox ), { "after": Stericycle.Enum.CheckboxIndicatorImage } );
        } );        
    };
    
    
    
    function batchUpdateErrorHandler( options ) 
    {
        if( !$(options.checkbox).up().hasClassName('checkbox_error') )
        {   
            $( options.checkbox ).up().addClassName( 'checkbox_error' );
        }
        $(options.checkbox).checked = !$(options.checkbox).checked;
        $A( $$( "#" + options.containerId + " input" ) ).each( function( checkbox ) {
            if( !$( checkbox).up().hasClassName('checkbox_error') )
            {   
                $( checkbox ).up().addClassName( 'checkbox_error' );
            };
            $(checkbox).checked = !$(checkbox).checked;
        } );
        
    };

    function batchUpdateSuccessfulHandler( options ) 
    {
        //console.log( 'successfulHandler' );
        new Effect.Highlight( $( options.checkbox ).up(), {duration: 0.5} );
        $A( $$( "#" + options.containerId + " input" ) ).each( function( checkbox ) {
            if( $( checkbox).up().hasClassName('checkbox_error') )
            {   
                $( checkbox ).up().removeClassName( 'checkbox_error' );
            };

            new Effect.Highlight( $(checkbox).up(), { duration: 0.5 } );
        } );        
    };
    
    function CheckboxValueChanged(checkbox, options )
    {
        /* prevent the checkbox from getting click while it is being processed */
        if( !$(checkbox).visible() )
        {
            $(checkbox).checked = !$(checkbox).checked;
            // console.log( 'crazy user clicks' );
            return 
        }
        // return false;
         /* Delegate to options's collectData method */
        var json = [ options.collectData( { "checkbox" : checkbox } ) ] ; 
        var url = associationHandlerUrl;
        var ajaxParams = "type=" + options.type + "&options=" + Object.toJSON( json );
        
        new Ajax.Request( url, {
            method: 'POST',
            parameters: ajaxParams,
            
            onCreate: function( options ) {
                $( checkbox ).hide();
                Element.insert( $( checkbox ), { "after": Stericycle.Enum.CheckboxIndicatorImage } );
            }, 
            
            onSuccess: function(response) {
                if( response.responseText.strip() != 'OK' )
                {
                    if( !$(checkbox).up().hasClassName('checkbox_error') )
                    {
                        $( checkbox ).up().toggleClassName( 'checkbox_error' );
                    }
                    
                    /* We revert back the state of the checkbox, since the previous action failed */
                    $( checkbox ).checked = !$( checkbox ).checked;                     
                }
                else
                {
                    $( checkbox ).up().removeClassName( 'checkbox_error' );
                    /* Some visual effect to signify that the user have saved the item */
                    new Effect.Highlight( $(checkbox).up(), {duration: 0.5} );
                }
                
                
               
            },
            onFailure: function( response ){ 
                if( !$(checkbox).up().hasClassName('checkbox_error') )
                {
                    $( checkbox ).up().toggleClassName( 'checkbox_error' );
                }
                
                /* We revert back the state of the checkbox, since the previous action failed */
                $( checkbox ).checked = !$( checkbox ).checked; 
            },
            
            onComplete: function( response )
            {
                Element.remove( $(checkbox).nextSibling );
                $( checkbox ).show();
            }
        } );
        
           
}


function EmployeeListChange(item) 
{
    if( item.Text == Stericycle.Localization['SiteEmployeeDropDown_AddNewItem'] )  
    { 
        ShowInsertForm( item.ComboBox.ClientID ); 
    } 
};
