﻿if (typeof(_fileVersions) == 'undefined')
	eval('var _fileVersions = new Array()');
_fileVersions.push('DirtyGroupHandling 6.6.0.0');

var _dirtyGroupHandler = new DirtyGroupHandler();
var _dirtyGroupReceiverHandler = new DirtyGroupReceiverHandler();

// Controltype enum
var ControlType = new Object();
ControlType.TextBox = 'textbox';
ControlType.Select = 'select';
ControlType.ListBox = 'select';
ControlType.RadioButton = 'radio';
ControlType.RadioButtonList = 'radiolist';
ControlType.CheckBox = 'checkbox';
ControlType.NCDatePicker = 'ncdatepicker';
ControlType.NCRadEditor = 'ncradeditor';

// DirtyStatus enum
var DirtyStatus = new Object();
DirtyStatus.NotDirty = 1;
DirtyStatus.NonRequiredFieldDirty = 2;
DirtyStatus.RequiredFieldDirty = 3;

//=============================================================
// Helper functions
//=============================================================
function InitializeDirtyGroupHandling()
{
	_dirtyGroupHandler.Initialize();
}

function ResetDirtyGroupState()
{
	for(var receiverName in _dirtyGroupHandler.DirtyGroups)
	{
	    var dirtyGroup = _dirtyGroupHandler.DirtyGroups[receiverName];
	
	    if(dirtyGroup != 'undefined' && dirtyGroup != null)
	    {
	        dirtyGroup.Reset();
	    }
	}

	InitializeDirtyGroupHandling();
}

//=============================================================
// DirtyGroupHandler
//=============================================================
function DirtyGroupHandler()
{
	this.DirtyGroups = new Array();
}

DirtyGroupHandler.prototype.Initialize = function()
{
    for (var dirtyGroupName in _dirtyGroupHandler.DirtyGroups)
    {
        var dirtyStatus = _dirtyGroupHandler.GetDirtyStatus(dirtyGroupName);
        var receiverName = 'receiver' + dirtyGroupName;

        _dirtyGroupReceiverHandler.ChangeEnabled(receiverName, dirtyStatus);
    }
}

DirtyGroupHandler.prototype.AddDirtyGroup = function(receiverName, dirtyGroups)
{
	this.DirtyGroups[receiverName] = dirtyGroups;
}

DirtyGroupHandler.prototype.HandleEvents = function(e)
{
    var evt = e || window.event;
    var srcElement = evt.target || evt.srcElement;
    srcElement = GetDirtyGroupElement(srcElement);
    
    if (srcElement != null)
    {
        var receiverName = srcElement.getAttribute('DirtyGroup');
        var receiverGroupName = 'receiver' + receiverName;
        var dirtyStatus = _dirtyGroupHandler.GetDirtyStatus(receiverName);

        _dirtyGroupReceiverHandler.ChangeEnabled(receiverGroupName, dirtyStatus);
    }
}

function GetDirtyGroupElement(srcElement)
{
	if(srcElement != null)
	{
	    if (srcElement.getAttribute &&
	        srcElement.getAttribute('DirtyGroup') != null && 
	        srcElement.getAttribute('DirtyGroup') != '')
			return srcElement;
	
		if(srcElement.tagName != 'body')
			return GetDirtyGroupElement(srcElement.parentNode)
	}
	return null;
}

DirtyGroupHandler.prototype.HandleClickEvents = function(e)
{
    var evt = e || window.event;
    var srcElement = evt.target || evt.srcElement;

    if (srcElement != null && typeof (srcElement.tagName) != 'undefined')
    {        
        if (srcElement.tagName.toLowerCase() == 'input' &&
	    (srcElement.type.toLowerCase() == 'radio' || srcElement.type.toLowerCase() == 'checkbox'))
        {
            _dirtyGroupHandler.HandleEvents(e);
        }
    }
}

DirtyGroupHandler.prototype.HandleEditorEvents = function(editor)
{
	InitializeDirtyGroupHandling();
}

DirtyGroupHandler.prototype.IsAnyGroupDirty = function()
{
	for(var name in this.DirtyGroups)
	{
		if (this.GetDirtyStatus(name) != DirtyStatus.NotDirty)
		{
			return true;
		}
	}
	
	return false;
}

DirtyGroupHandler.prototype.GetDirtyStatus = function(dirtyGroupName)
{
    var dirtyGroup = this.DirtyGroups[dirtyGroupName];
    var dirtyStatus = DirtyStatus.NotDirty;

    if (dirtyGroup != 'undefined' && dirtyGroup != null)
    {
        var dirtyGroupItems = dirtyGroup.DirtyGroupItems;
        var length = dirtyGroupItems.length;

        for (var index = 0; index < length; index++)
        {
            var dirtyGroupItem = dirtyGroupItems[index];

            if (dirtyGroupItem.IsRequiredAndEmpty())
            {
                dirtyStatus = DirtyStatus.RequiredFieldDirty;
                break;
            }

            if (dirtyGroupItem.IsDirty())
            {
                dirtyStatus = DirtyStatus.NonRequiredFieldDirty;
            }
        }
    }

    return dirtyStatus;
}

  DirtyGroupHandler.prototype.ResetGroup = function (dirtyGroupName)
{
	_dirtyGroupReceiverHandler.ChangeEnabled('receiver' + dirtyGroupName, false);
}

//=============================================================
// DirtyGroup
//=============================================================
function DirtyGroup(name)
{
	this.DirtyGroupItems;
	this.Name = name;
	this.Dirty = false;
}

DirtyGroup.prototype.AddDirtyGroupItemsArray = function (dirtyGroupItems)
{
    // the clearing of the array passed is needed because 
    // ScriptManager.RegisterArrayDeclaration arrays are not cleared in update panel postbacks.
    this.DirtyGroupItems = dirtyGroupItems.slice();
    dirtyGroupItems.splice(0, dirtyGroupItems.length);
}

DirtyGroup.prototype.Reset = function()
{
    var dirtyGroupItems = this.DirtyGroupItems;
    var length = dirtyGroupItems.length;

    for(var index = 0; index < length; index++)
    {
        var dirtyGroupItem = dirtyGroupItems[index];

        dirtyGroupItem.Reset();
    }
}

//=============================================================
// DirtyGroupItem
//=============================================================
function DirtyGroupItem(dirtyGroup, controlId, initialValue, controlType)
{
	this.ControlId = controlId;
	
	if(controlType == ControlType.Select)
	{
		$get(this.ControlId).onchange = _dirtyGroupHandler.HandleEvents;
	}

	this.DirtyGroup = dirtyGroup;
	this.InitialValue = initialValue;
	this.ControlType = controlType;
}

// If the control is required and empty, true is returned. 
// Only applicable to controls that uses a text input field. For other controls (like a checkbox), 
// false is always returned.
DirtyGroupItem.prototype.IsRequiredAndEmpty = function()
{
	var element = this.GetElement();
	var isRequiredAndEmpty = false;

	if (element != null && element.Required != null &&
		(element.Required.toLowerCase() == "true" || element.Required == "1"))
	{
		switch (this.ControlType)
		{
			case ControlType.TextBox:
			case ControlType.Select:
				{
					value = element.value.replace(/\r/g, "");
					break;
				}
			case ControlType.NCRadEditor:
				{
					var editor = $find(element.id);

					if (!editor)
					{
						alert("DirtyGroupHandling.js:IsRequiredAndEmpty: Cannot find editor with id " + element.id);
					}

					value = editor.get_html();
					break;
				}
			case ControlType.NCDatePicker:
				{
					value = (element.value != "") ? element.value : "";
					break;
				}
		}

		if (value != null)
		{
			isRequiredAndEmpty = (value == "");
		}
	}

	return isRequiredAndEmpty;
}

DirtyGroupItem.prototype.GetElement = function ()
{
    var element = null;

    if (this.ControlType == ControlType.RadioButtonList)
    {
        element = document.getElementsByName(this.ControlId);
    }
    else
    {
        element = $get(this.ControlId);
    }

    return element;
}

DirtyGroupItem.prototype.IsDirty = function()
{
    var element = this.GetElement();
    var isDirty = false;

    if (element != null)
    {
    	switch (this.ControlType)
        {
            case ControlType.TextBox:
            case ControlType.Select:
                {
                    var cleanedValue = element.value.replace(/\r/g, '');
                    isDirty = this.InitialValue.toUpperCase() != cleanedValue.toUpperCase();
                    break;
                }
            case ControlType.RadioButtonList:
                {
                	for (var index = element.length - 1; index >= 0; index--) 
                    {
                    	if (this.InitialValue == '' && element[index].checked) 
                        {
                            isDirty = true;
                            break;
                        }

                        if (this.InitialValue != '' &&
						element[index].value == this.InitialValue &&
						!element[index].checked) 
						{
                            isDirty = true;
                            break;
                        }
                    }

                    break;
                }
            case ControlType.RadioButton:
                {
                	if (this.InitialValue.toString() != element.checked.toString())
                    {
                        isDirty = true;
                    }

                    break;
                }
            case ControlType.CheckBox:
                {
                	switch (this.InitialValue)
                    {
                        case 'false':
                        	if (element.checked)
                            {
                                isDirty = true;
                            }
                            break;
                        case 'true':
                        	if (!element.checked)
                            {
                                isDirty = true;
                            }
                            break;
                    }

                    break;
                }
            case ControlType.NCRadEditor:
                {
                    var editor = $find(element.id);

                    if (!editor)
                    {
                        alert("DirtyGroupHandling.js:IsDirty: Cannot find editor with id " + element.id);
                    }
                    else if (this.InitialValue != editor.get_html())
                    {
                        isDirty = true;
                    }

                    break;
                }
            case ControlType.NCDatePicker:
                {
                    // element.value is always in the format yyyy-mm-dd-hh-mm
                	if (element.value != this.InitialValue)
                    {
                        isDirty = true;
                    }

                    break;
                }
            case ControlType.NCTimePicker:
                {
                    // element.value is always in the format yyyy-mm-dd-hh-mm
                    // Only care about the time part
                	if (element.value.substring(11) != this.InitialValue.substring(11))
                    {
                        isDirty = true;
                    }

                    break;
                }
        }
    }

    return isDirty;
}

DirtyGroupItem.prototype.Reset = function()
{
	var element = null;

	if(this.ControlType == ControlType.RadioButtonList)
	{
		element = document.getElementsByName(this.ControlId);
	}
	else if(this.ControlType == ControlType.NCRadEditor)
	{
		element = this.ControlId
	}
	else
	{
		element = $get(this.ControlId);
	}
	
	if(element != null)
	{
		switch(this.ControlType)
		{
			case ControlType.TextBox:
			case ControlType.Select:
			case ControlType.NCTimePicker:
			case ControlType.NCDatePicker:
			{
				this.InitialValue = element.value;
				break;
			}	
			case ControlType.RadioButtonList:
			{	
				for(var index = element.length - 1; index >= 0; index--)
				{
					if(element[index].checked)
					{
				        this.InitialValue = element[index].value;
				        break;
					}					
				}
				
				break;
			}	
			case ControlType.RadioButton:
			case ControlType.CheckBox:
			{
				this.InitialValue = element.checked.toString();
				break;
			}
			case ControlType.NCRadEditor:
			{
				var editor = $find(element.id); 
			
				this.InitialValue = editor.get_html();
				break;
			}
		}
	}
}


//=============================================================
// DirtyGroupReceiverHandler
//=============================================================
function DirtyGroupReceiverHandler()
{
	this.ReceiverGroups = new Array();
	this.ReceiverCallBackFunctions = new Array();
}

DirtyGroupReceiverHandler.prototype.AddReceivers = function (receiverName, receiverGroupItems)
{
    // the clearing of the array passed is needed because 
    // ScriptManager.RegisterArrayDeclaration arrays are not cleared in update panel postbacks.
    this.ReceiverGroups[receiverName] = receiverGroupItems.slice();
    receiverGroupItems.splice(0, receiverGroupItems.length);
}

DirtyGroupReceiverHandler.prototype.AddCallBackFunction = function(dirtyGroupName, callBackFunction)
{	
	var receiverName = "receiver" + dirtyGroupName;
	var callBackFunctions = this.ReceiverCallBackFunctions[receiverName];	

	if(callBackFunctions == 'undefined' || callBackFunctions == null)
	{
		callBackFunctions = new Array();
	}

	callBackFunctions.push(callBackFunction);
	this.ReceiverCallBackFunctions[receiverName] = callBackFunctions;
}

DirtyGroupReceiverHandler.prototype.ChangeEnabled = function(receiverName, dirtyStatus)
{
	var receiverGroupItems = this.ReceiverGroups[receiverName];
	var callBackFunctions = this.ReceiverCallBackFunctions[receiverName];
	
	if(receiverGroupItems != 'undefined' && receiverGroupItems != null)
	{
		var length = receiverGroupItems.length;
		
		for(var index = 0; index < length; index++)
		{
			var receiverGroupItem = receiverGroupItems[index];

			receiverGroupItem.ChangeEnabled(dirtyStatus);
		}
	}

	if(callBackFunctions != 'undefined' && callBackFunctions != null)
	{
		var length = callBackFunctions.length;
		
		for(var index = 0; index < length; index++)
		{
			var callBackfunction = callBackFunctions[index];
			
			callBackfunction(receiverName, dirtyStatus);
		}
	}
}

//=============================================================
// DirtyGroupReceiverItem
//=============================================================
function DirtyGroupReceiverItem(dirtyGroup, controlID, requiredTrackingEnabled)
{
	this.SetEnabledState = function(enabled) 
	{ 
		var control = $get(controlID);
		
		control.disabled = !enabled; 
	};
	this.DirtyGroup = dirtyGroup;
	this.RequiredTrackingEnabled = requiredTrackingEnabled;
}

DirtyGroupReceiverItem.prototype.ChangeEnabled = function(dirtyStatus)
{
	if(this.SetEnabledState)
	{
		if (this.RequiredTrackingEnabled && 
			dirtyStatus == DirtyStatus.RequiredFieldDirty)
		{
			this.SetEnabledState(false);
		}
		else
		{
			var enabled = dirtyStatus != DirtyStatus.NotDirty;
			
			this.SetEnabledState(enabled);
		}
	}
}

//=============================================================
// Dirty group event initialization
//=============================================================

if (typeof (Sys) != 'undefined')
{
    $addHandler(document, 'click', _dirtyGroupHandler.HandleClickEvents);
    $addHandler(document, 'mousewheel', _dirtyGroupHandler.HandleEvents);
    $addHandler(document, 'keyup', _dirtyGroupHandler.HandleEvents);
    Sys.Application.add_load(InitializeDirtyGroupHandling);
    
    // Notify the ScriptManager that this script file has finished loading.
    Sys.Application.notifyScriptLoaded();
}

