﻿// JScript File

// Catches the enter key press and replaces it with a tab unless the focus is on a button
 function catchEnter() {
    if (event.keyCode==13) {
	    if (document.activeElement.type != 'submit') {
		    event.keyCode=9; 
		}
	    return event.keyCode;
    }
}


//Set the focus to the specified control
function setFocus(control) {
		document.getElementById(control).focus();
		return true;
}



//Find an element even if in a master page. This function should eventually become obsolete as control names should not be hard coded
function mxGetElementById(objName) {
    if (document.getElementById(objName) == undefined) {
        return document.getElementById('_ctl0_ph_'+objName);
    } else { 
        return document.getElementById(objName);
    }
}
       
// Select/deselect all item's checkboxes in a datagrid when the parent checkbox is checked/unchecked
// Select/deselect the parent checkbox when all item's checkboxes in the grid is checked/unchecked
function select_deselectAll(chkVal, thisChbId, datagridId, headerChbId, itemChbId, performUpdate) {
  
	// Note:
    // - IMPORTANT: Preconditions :
    //      + headerChbId string and itemChbId string must NOT be a subset of each other
    //      + if there are multiple grids on the page, headerChbId and itemChbId for each grid must be unique
	// - performUpdate: is a true/false param. 
	//   If true, javascript function update(chbObj, datagridId) will be called to do extra stuff.
	//   This update function needs to be implemented.										
	var frm = document.forms[0];
	var allItemsChecked = true;   
	var chbSelectAll = null;
    
	// Loop through all elements 
	for (i=0; i<frm.length; i++) 
	{
		// Look for our Header Template's Checkbox
		if (thisChbId.indexOf (headerChbId) != -1) 
		{
			// Check if main checkbox is checked, then select or deselect datagrid checkboxes 
			if (frm.elements[i].id.indexOf (itemChbId) != -1)
			{
			    // if header is checked
				if(chkVal == true) 
				{				
					frm.elements[i].checked = frm.elements[i].disabled ? frm.elements[i].checked : true;		
					if (frm.elements[i].id.indexOf (datagridId) != -1 & !frm.elements[i].disabled)
					{	
						var chb1 = document.getElementById(frm.elements[i].id);
						if(performUpdate) 
						{
							update(chb1, datagridId);		
						}											
					}															
				} 
				else 
				{
				    frm.elements[i].checked = frm.elements[i].disabled ? frm.elements[i].checked : false;	
				}
			}
		} 
		else if (thisChbId.indexOf (itemChbId) != -1) 
		{                         
			// Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
			if (chkVal == false) 
			{
				if (frm.elements[i].id.indexOf (headerChbId) != -1)
				{					
					frm.elements[i].checked = false; //Uncheck main select all checkbox
				}
			}
			else
			{
				if (frm.elements[i].id.indexOf (headerChbId) != -1)
				{
					chbSelectAll = frm.elements[i];
				}
			}
            
			// Check if all child items are checked
			if (frm.elements[i].id.indexOf (itemChbId) != -1)
			{
				allItemsChecked = allItemsChecked & (frm.elements[i].checked || (frm.elements[i].disabled));
			}												
		}
	}  
																			
	if ((thisChbId.indexOf (itemChbId) != -1) & (chkVal == true) & (thisChbId.indexOf (datagridId) != -1) & !(document.getElementById(thisChbId).disabled))
	{
		// Update confirm tick and invoice amount					
		var chb1 = document.getElementById(thisChbId);									
		if(performUpdate) 
		{
		    update(chb1, datagridId);		
		}					
	}
				
	if (chbSelectAll != null) 
	{
		chbSelectAll.checked = allItemsChecked;
	}	
}


//Used to check/deselect all checkboxes in a datalist
//isChecked is checked value
//checkBoxFieldName is the name of the checkbox in the datalist
//make sure that the checkBoxFieldName is unique in the page and that it is not a subset of anything else 
    function CheckAll(isChecked, checkBoxFieldName) {
        var frm = document.forms[0];
        for (i = 0; i < frm.length; i++) {
            e = frm.elements[i];
            if (e.type == 'checkbox' && e.name.indexOf(checkBoxFieldName) != -1)
                e.checked = isChecked;
        }
    }

// The following 2 functions are used in the email text box

var multiEmailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)(\s*,\s*\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+))*$/i;  
var blankfilter=/^\s*$/i;
var oldValue='';
var selectedTextBoxId = ''; 
function validateEmailAddressFromRadTextBox(sender, args)  
{  
	oldValue = ''
    var radTextBox = sender;     
    var isBlank = blankfilter.test(radTextBox.GetValue())  
    if (!isBlank)   
    {         
        radTextBox.SetValue(radTextBox.GetValue().replace(/[(\s*;\s*)(\s*,\s*)]+/, ","))
		var returnval = multiEmailfilter.test(radTextBox.GetValue())  
		if (!returnval)   
		{  
			oldValue = radTextBox.GetValue()
			radTextBox.SetValue('');  
		}  
		
    }
    selectedTextBoxId = radTextBox.ClientID
}  
        
function selectTextFromRadTextBox(sender, args)  
{  
     var radTextBox = sender;     
     if (radTextBox.ClientID == selectedTextBoxId) 
     {
        if (oldValue != '')
        {
		    radTextBox.SetValue(oldValue)
        }
     }         
     radTextBox.SelectAllText();
 }

 // Function returns boolean as to whether one checkbox in a RadGrid has been selected
 // See WIKI for usage requirements
 // NB. The radGrid must have EnableClientKeyValues="true" in the ClientSettings tag (again see WIKI)
function AtLeastOneCheckBoxChecked(radGridClientSideID, checkBoxColName) {
     var radGrid = window[radGridClientSideID];
     var radGridMasterTable = radGrid.MasterTableView;
     var radGridRows = radGridMasterTable.Rows;
     var row, checkBox;
     var checkBoxChecked;

     for (i = 0; i < radGridRows.length; i++) {
         row = radGridRows[i];

         // Ensure that only one INPUT element (checkbox) exists
         // Ensure that there is no TABLE element (to remove sub-ordinates)
         var cell = radGridMasterTable.GetCellByColumnUniqueName(row, checkBoxColName);
         if (cell.getElementsByTagName("INPUT").length == 1 && cell.getElementsByTagName("TABLE").length == 0 ) {
             checkBoxChecked = cell.getElementsByTagName("INPUT")(0).checked;
             if (checkBoxChecked) return true;
         }

     }
     return false;
}




// TODO: April: Fix this ---- Please don't use following functions
// Tick check box utilities

function tickCheckBoxWithSameParent(obj, objId, chbId, value) {
    //var id = obj.id.replace(objId, chbId);
    var id = obj.id.substring(0, obj.id.indexOf(objId)) + chbId;
    tickBox(id, value);
}

function tickBox(id, value) {
    var chb = document.getElementById(id);
    if (chb != null) {
        chb.checked = value;
    }
}



// TODO: April :Fix this


function triggerTickCheckBox(obj,val) {

    if (obj.id.indexOf("CountSelector") != -1) {
        tickCheckBoxWithSameParent(obj, "CountSelector", "ChbSelect" + val + "Count", true);
    }
    else if (obj.id.indexOf("PickerUomReportingUnit") != -1) {
    tickCheckBoxWithSameParent(obj, "PickerUomReportingUnit", "ChbSelectReportingUnit", true);
    }
    else if (obj.id.indexOf("PickerUomStocktakeBoxUnit") != -1) {
        tickCheckBoxWithSameParent(obj, "PickerUomStocktakeBoxUnit", "ChbSelectStocktakeUnit1", true);
    }
    else if (obj.id.indexOf("PickerUomStocktakeInnerUnit") != -1) {
        tickCheckBoxWithSameParent(obj, "PickerUomStocktakeInnerUnit", "ChbSelectStocktakeUnit2", true);
    }
    else if (obj.id.indexOf("PickerVendorUomStockCountUnit") != -1) {
        tickCheckBoxWithSameParent(obj, "PickerVendorUomStockCountUnit", "ChbSelectVendorStockCountUnit", true);
    }
    else if (obj.id.indexOf("PickerVendorUomPurchaseUnit") != -1) {
        tickCheckBoxWithSameParent(obj, "PickerVendorUomPurchaseUnit", "ChbSelectVendorPurchaseUnit", true);
    }
    else if (obj.id.indexOf("OrderRatioPanel") != -1) {
        tickCheckBoxWithSameParent(obj, "OrderRatioPanel", "ChbSelectOrderRatio", true);
    }
    else if (obj.id.indexOf("OrderCategoryPickerOpener1") != -1) {
        tickCheckBoxWithSameParent(obj, "OrderCategoryPickerOpener1", "ChbSelectOrderCategoryID", true);
    }
    
}
// TODO: April: Fix this
function triggerTickCheckBoxByRadControl(obj) {
    if (obj.ComboBox.ClientID.indexOf("SelectorSimilarItem") != -1) {
        var id = obj.ComboBox.ClientID.substring(0, obj.ComboBox.ClientID.indexOf("SelectorSimilarItem")) + "ChbSelectSimilarItem";
        tickBox(id, true);
    }
    else if (obj.ComboBox.ClientID.indexOf("EntitySelectorCopyFrom") != -1) {
    var id = obj.ComboBox.ClientID.substring(0, obj.ComboBox.ClientID.indexOf("EntitySelectorCopyFrom")) + "CbhSelectCopyEntity";
        tickBox(id, true);
    }
}

// --------- END TODO --------------------------



function replaceId(obj, replaceRegEx, newText) {
    return obj.id.replace(replaceRegEx, newText);

}


function ShowProcessing(control) {
    control.outerHTML = "<img src='/Images/small_loading.gif' />";
}




/* start of timeout functionality */

var sessionWasExtended = false;
var ignoreTimerIds = [];
var sessionWindowToolTip;

$(document).ready(function()
{
    sessionWindowToolTip = $('[id$=tpSessionTimeout]');
    SessionTimeoutTimer();
});

function SessionTimeoutTimer()
{
    if (typeof (sessionLength) == "undefined")
        return;

    var text = $('[id$=hdnSessionCounterMessage]').val();
    var temp = text;
    $('.session-value').text(temp.replace('{0}', sessionLength));

    jQuery.fjTimer(
    {
        interval: 60000,
        repeat: sessionLength,
        tick: function(counter, timerId)
        {
            var remainingMinutes = sessionLength - (counter + 1);
            var warningMinute = (sessionLength - sessionWarningAt);

            if (sessionWasExtended == false || $.inArray(timerId, ignoreTimerIds) == -1)
            {
                var temp = text;
                $('.session-value').text(temp.replace('{0}', remainingMinutes));
            }

            //alert(counter);
            if ((counter + 1) == warningMinute)
            {
                $find(sessionWindowToolTip.attr('id')).show();
                $('[id$=tpSessionTimeout]').find('.rtCloseButton').hide();
                $('[id$=btnExtendSession]').click(function(e)
                {
                    ignoreTimerIds.push(timerId);
                    e.preventDefault();
                    ExtendSession();
                    return false;
                });
            }
        },
        onComplete: function()
        {
            if (sessionWasExtended == false)
                window.location = "/MMS_Logon.aspx?SessionTimeout=True";
            else
                sessionWasExtended = false;
        }
    });
}

function ExtendSession()
{
    var result = false;

    $.ajax(
    {
        async: false,
        type: "get",
        url: "/Handlers/PingHandler.ashx",
        success: function(data, status, xmlReq)
        {
            if (data.IsAuthenticated == false)
                SessionTimeout();
            else
                result = true;
        }
    });

    if (result)
    {
        sessionWasExtended = true;
        SessionTimeoutTimer();
        $find(sessionWindowToolTip.attr('id')).hide();
    }
}

/* end of timeout functionality */
