/// place holder of all generic JavaScript functions used across pages
/**
 * @file
 * @startcomment
 *  File: GLibJs.js
 *
 *  Current Owner: Raghu Anand (10-10-2007)
 *
 *  Purpose: place holder of all generic JavaScript functions used across pages
 *
 *  Dependencies:   none
 *
 *  Classes:    none
 *
 *  Global functions:
 *  1. Key press functions
 *      NavigateOnEnter ()
 *      IsStringFieldKeyPress ()
 *      IsFloatFieldKeyPress ()
 *      IsIntegerFieldKeyPress ()
 *      IsDateFieldKeyPress ()
 
 *  2. Data validation function 
 *      InputNotNumericReset ()
 *      IsStringFieldEmpty ()
 *      IsAlphaNum ()
 *      IsIntegerValue ()
 *      IsNumericValue ()
 *
 *  3. Other FORM functions
 *      SetCheckboxGroup ()
 *
 *  4. Date Functions 
 *      IsValidDate ()
 *      IsDate ()
 *      CompareDate ()
 *      DateAdd ()
 *      DoDateValidation ()
 *      ChangePeriod ()
 *      IsLeapYear ()
 *      GetMonthDays ()
 *
 *  5. Other functions
 *      CreateProgressBar ()
 *      StartProgressBar ()
 *      IsParentContainerAvailable ()
 *      CommifyArray ()
 *      myrtrim ()
 *      myltrim ()
 *      mytrim ()
 *
 *  Notes:
 *  1. STRING obj's trim() method is defined.
 *     Eg : var string = '   string   '; var trimmed_str = string.trim();
 *
 * @endcomment
 *
 */
// case : STRING JS obj does not have the method 'trim' defined. Hence implement own trim method
if ( typeof String.prototype.trim === 'undefined' ) { 
    String.prototype.trim = function() { 
        //return this.replace(/^\s+|\s+$/g,'');
        var str = this.replace(/^\s+/, '');
        for(var i = str.length - 1; i >= 0; i--){
        	if(/\S/.test(str.charAt(i))){
        		str = str.substring(0, i + 1);
        		break;
        	}
        }
        return str;	// String
    } 
}

//create a Global Namespace
//Define all your so called global variables within this container to prevent any namespace pollutions=
if (typeof TallyJSLib === "undefined" || typeof window.TallyJSLib === "undefined") {
    var TallyJSLib = window.TallyJSLib = {};
    TallyJSLib.Event = {};
}

//Define and execute
(function () {
    var userAgent = window.navigator.userAgent.toLowerCase();
    //From JQuery 1.2.6
    // Figure out which browser is being used
    TallyJSLib.Browser = {
        version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0, '0'])[1],
        safari: /webkit/.test( userAgent ),
        opera: /opera/.test( userAgent ),
        msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
        mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
    };
})();

function vIsPropValueExists(pObj, pVal)
{
    if (!pObj || typeof pObj !== "object" || !pVal || typeof pVal === "undefined")
        return false;

    for (var x in pObj) {
        if (pObj[x] === pVal) return true;
    }

    return false;    
}

/// Class to Parse the date format.
/**
 * @startcomment
 * Purpose: Class to Parse the date format.
 *
 * Input Params:
 * Output Params:
 * Return Value:
 * Notes:
 * @endcomment
 */
function _MyDateParse(pDateTimeStr, pAcceptSlashFlag)
{
	//Private Instance variables
	var vdateTimeStr	= pDateTimeStr,
		vyear 			= 0 ,
		vmonth			= -1, /*since 0 corresponds to Jan (earlier this was 0 - corrected)*/
		vday    		= 0,
		vhour			= 0,
		vfullHour		= 0,
		vmin			= 0,
		vsec			= 0,
		vfullYear		= 0,
		vmilliseconds 	= 0,
		vhourFormat		= 24, /*Default- hours format*/
		vmeridiem       = '',
        vacceptSlashFlag= pAcceptSlashFlag,        
		dateRegExp		= /^(\d{1,2})-(\d{1,2})-(\d{2}|\d{4})$/,
		dateTimeRegExp	= /^(\d{1,2})-(\d{1,2})-(\d{2}|\d{4})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*(am|AM|pm|PM{0,1})$/;

    /*User wants to validate the date against slash format*/
    if (vacceptSlashFlag && vacceptSlashFlag > 0) {

		dateRegExp		= /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{2}|\d{4})$/;
		dateTimeRegExp	= /^(\d{1,2})[-|\/](\d{1,2})[-|\/](\d{2}|\d{4})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*(am|AM|pm|PM{0,1})$/;
    }

	//Private Functions
	function _vGetFullYear(pYear)
	{
		if (!IsInteger(pYear)) { return 0;}

		return ((pYear.length == 2) ? 
				((pYear > 70) ? (1900 + pYear) : (2000+ pYear)) : 
				pYear);
	}

	//Instance functions
	//Privileged Methods (Accessible outside)
	this._ParseDate = function (pDateTimeStr, pAcceptSlashFlag)
	{
        if (pDateTimeStr === undefined && vdateTimeStr === undefined) return false;

		else vdateTimeStr = pDateTimeStr;

		if (IsStringFieldEmpty(vdateTimeStr)) {vdateTimeStr = undefined; return false;}

		vdateTimeStr = vdateTimeStr.trim();

        vacceptSlashFlag= pAcceptSlashFlag;

        /*User wants to validate the date against slash format*/
        if (vacceptSlashFlag && vacceptSlashFlag > 0) {

            dateRegExp		= /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{2}|\d{4})$/;
            dateTimeRegExp	= /^(\d{1,2})[-|\/](\d{1,2})[-|\/](\d{2}|\d{4})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*(am|AM|pm|PM{0,1})$/;
        }
        
		var containsDateTime = 0;
		//case: Date String does not match both the string formats
		if ((matchRes = vdateTimeStr.match(dateRegExp)) === null)
		{
			if ((matchRes = vdateTimeStr.match(dateTimeRegExp)) === null)
			{
				 return false;
			}
			containsDateTime = 1;
		}

		vday	= parseInt(matchRes[1], 10);
		vmonth 	= parseInt(matchRes[2], 10);
		vyear	= parseInt(matchRes[3], 10);

		//???
		//Year exceeds the Max allowed Year Limit(typically the timestamp becomes invalid beyond this range)
		//if ((year = _vGetFullYear(year)) < 1901 || year > 2038) return false;
		vfullYear = _vGetFullYear(vyear);

		//Month is Zero based(i.e., 0-11)
		vmonth -= 1;

		if (containsDateTime)
		{
			vhour	= parseInt(matchRes[4], 10);
			vmin	= parseInt(matchRes[5], 10);
			vsec	= parseInt(matchRes[6], 10);
			vmeridiem= matchRes[7];
			vmeridiem= vmeridiem.trim();

			vhourFormat = 24;
			//case: AM/PM is set, convert hour into 24 hour format
			if (vmeridiem != "")
			{
				vhourFormat = 12;
				vmeridiem = vmeridiem.toLowerCase();
				if (vmeridiem === "am") { vfullHour = (vhour == 12) ? 0 : vhour; }
				else { vfullHour = (vhour < 12) ? (vhour + 12) : vhour; }
			}
		}

		return true;
	}

	this._GetYear 			= function() { return vyear;}
	this._GetFullYear 		= function() { return vyear;}
	this._GetMonths 		= function() { return vmonth;}
	this._GetDate 			= function() { return vday;}
	this._GetHours 			= function() { return vhour;}
	this._GetFullHours		= function() { return vfullHour;}
	this._GetMinutes 		= function() { return vmin;}
	this._GetSeconds 		= function() { return vsec;}
	this._GetMilliseconds 	= function() { return vmilliseconds;}
	this._GetMeridiem		= function() { return vmeridiem;}
	this.valueOf            = function() { return (vyear +" "+vmonth +" "+vday +" "+vhour+" "+vmin +" "+vsec +" "+vmeridiem);}
}


/// brief description of function.
/**
 * @startcomment
 * Purpose:
 *
 * Input Params:
 *  1.  Param1 - DataType - Desc
 *  2.  Param1 - DataType - Desc
 * Output Params:
 * Return Value:
 *  ReturnVal - DataType - Desc
 *
 * Notes:
 * @endcomment
 */
function IsDateValidWithSlash(pDateTimeStr )
{
	if (IsStringFieldEmpty(pDateTimeStr)) return false;

    //create a local Date Object and Parse the given string
	var dtObj = new _MyDateParse();

	if (dtObj._ParseDate(pDateTimeStr, 1) === false) return false;

	var year 	= dtObj._GetFullYear(),
		month	= dtObj._GetMonths(),
		day		= dtObj._GetDate(),
		hour	= dtObj._GetFullHours(),
		min		= dtObj._GetMinutes(),
		sec		= dtObj._GetSeconds();

	//Date is all Zeros
	if (year === 0 || month === -1 || month > 11 || day === 0) return false;

	var dt = new Date(year, month, day, hour, min, sec, 0);

	// case : if inputs match the date object
	if( year == dt.getFullYear() && month == dt.getMonth() && day == dt.getDate() &&
		hour == dt.getHours() && min == dt.getMinutes() && sec == dt.getSeconds()) 
		return true;

	return false;
}


/// brief description of function.
/**
 * @startcomment
 * Purpose:
 *
 * Input Params:
 *  1.  Param1 - DataType - Desc
 *  2.  Param1 - DataType - Desc
 * Output Params:
 * Return Value:
 *  ReturnVal - DataType - Desc
 *
 * Notes: Under Construction
 * @endcomment
 */ 
function SetDateProper(pDateTimeStr )
{
	if (IsStringFieldEmpty(pDateTimeStr)) return false;

	//create a local Date Object and Parse the given string
	var dtObj = new _MyDateParse();

	if (dtObj._ParseDate(pDateTimeStr, 1) === false) return false;

	var year 	= dtObj._GetFullYear(),
		month	= dtObj._GetMonths(),
		day		= dtObj._GetDate(),
		hour	= dtObj._GetFullHours(),
		min		= dtObj._GetMinutes(),
		sec		= dtObj._GetSeconds();

	//Date is all Zeros
	if (year === 0 || month === -1 || month > 11 || day === 0) return false;

	var dt = new Date(year, month, day, hour, min, sec, 0);

	// case : if inputs match the date object
	if( year == dt.getFullYear() && month == dt.getMonth() && day == dt.getDate() &&
		hour == dt.getHours() && min == dt.getMinutes() && sec == dt.getSeconds()) {

        return day + "-" + month +"-"+year;
    }

	return false;
}
/// To check if any of the parent containers are unrendered/invisible
/**
 * @startcomment
 * Purpose: To check if any of the parent containers are unrendered/invisible
 * Input Params:
 *  1.  pSrcElem - obj - source element object
 * Output Params:
 * Return Value:
 *  1  - parent containers are rendered/visible
 *  -1 - Any of parent containers is unrendered/invisible
 * Notes:
 *  1. This function is recursively called till all the parent containers are reached.
 * @endcomment
 */
function IsParentContainerAvailable ( pSrcElem )
{
    // case: parent node exist
    if( pSrcElem.parentNode != null && pSrcElem.parentNode.tagName != null )
    {
        // case: parent node is hidden/unrendered
        if( pSrcElem.parentNode.style.visibility === 'hidden' || pSrcElem.parentNode.style.display === 'none' ) return -1;

        // case: check for this container's parent
        return IsParentContainerAvailable ( pSrcElem.parentNode );
    }

    // case: no more parent node
    else return 1;
}

/// to set the focus to the next available FORM control on enter key pressed
/**
 * @startcomment
 * Purpose: to set the focus to the next available FORM control on enter key pressed
 * Input Params:
 *  1.	pEvent				- Obj	- Event Object
 *  2.  pFormName           - str   - The FORM name
 *  3.  pNavigateOnTextArea - int   - Flag denoting if navigation is to be executed on a textarea
 * Output Params:   none
 * Return Value:    none
 * Notes:
 *  1. No setting focus on a radio button, or on a read only type
 *  2. By default, no navigation from a textarea on enter key press.
 *  3. Will return without execution if browser is not IE
 *  4. Requires all the FORM elements to specify the 'ID' attribute
 * @endcomment
 */
function NavigateOnEnter ( pEvent, pFormName, pNavigateOnTextArea )
{
    //Determine if TextArea Navigation is needed
    var do_nav_on_textarea = pNavigateOnTextArea ? parseInt ( pNavigateOnTextArea ) : 0;    

	var evt =  window.event || pEvent;
	var key_code = TallyJSLib.Browser.msie ? evt.keyCode : evt.which;
    var element = evt.srcElement || evt.target;

    // check if pressed key is enter
    if ( key_code !== 13 ) return;
        
    // case : no navigation from textarea on enter keypress
    if ( do_nav_on_textarea == 0 && element.type === 'textarea' ) return true;

    //reset key code ??? Need to check if this is mandatory
    //window.event.keyCode = 0;
	//var form = document.getElementsByName(pFormName)[0];
    var form = document.getElementById(pFormName) || document.getElementsByName(pFormName)[0];

    // loop to walk through each form element 
    for( n = 0; n < form.elements.length; n++ )
    {
        // do not consider other controls except source control
        if ( form.elements[n].id !== element.id ) continue;

        // find next eligible control to have focus
        for( i = n + 1; i < form.elements.length; i++ ) {
            // if next control is <input type='hidden'> / disabled element / READONLY element / is hidden / is unrendered, then skip it
            if ( form.elements[i].type === 'hidden'
                 || form.elements[i].disabled === true
                 || form.elements[i].style.visibility === 'hidden'
                 || form.elements[i].style.display === 'none' )
                    continue;

            // case : if any of the parent containers of the next control are hidden/unrendered, then skip it
            if ( IsParentContainerAvailable ( form.elements[i] ) < 0 ) continue;
            
            // if has a tab index -1
            if ( form.elements[i].tabIndex < 0 ) continue;
            
            // if control is read only( readonly is not applicable for combobox and listbox )
            if ( form.elements[i].type !== 'select-one' 
                 && form.elements[i].type !== 'select-multiple' 
                 && form.elements[i].readOnly === true )
                    continue;

            //handling checkbox
            if (form.elements[i].type === 'checkbox' ) {
                form.elements[i].focus();
            }
            if(form.elements[i].type === 'button'
               || form.elements[i].type === 'submit' || form.elements[i].type === 'reset'
               || /^button$/i.test(form.elements[i].tagName) ) {

                form.elements[i].focus();
                if (!TallyJSLib.Browser.msie) {
                    form.elements[i].click();
                }
            }
            else {
                try {
                    form.elements[i].select();                    
                } catch (e) {
                    // set the focus
                    form.elements[i].focus();
                }
            }

            if (evt.preventDefault) evt.preventDefault();
            evt.cancelBubble = true;
            return true;
        }
    }
}

/// To avoid inputting double quotes in html text input
/**
 * @startcomment
 * Purpose: To avoid inputting double quotes in html text input
 * Input Params:
 *  1.  pEventObj - obj - DOM event object handle
 * Output Params:
 * Return Value:
 *  true - if string is blank
 *  false - if string is not blank
 * Notes:
 *  1. In database, we store single quote, but not double quote. Hence, in the whole FORM, we might 
 *     want to supress double quotes.
 *  2. Sending of event handler is must for this function to work for Netscape and mozilla
 *     For example, onKeyPress='IsTextFieldKeyPress( event )'
 *  3. In case IE also, please send the event handler like previous example
 *  4. In IE, with out passing event handler will also work. This is to keep compatability
 *     with existing call/references. 
 * @endcomment
 */
function IsStringFieldKeyPress ( pEvent )
{
	pEvent = window.event || pEvent;
    var key_code = TallyJSLib.Browser.msie ? pEvent.keyCode : pEvent.which;

    if (pEvent.type !== "keypress" || key_code === 0 || key_code === 8) return true;

    // case : if key code is 34( means " ), then stop the key press event
    if ( key_code === 34 )
    {
        if( TallyJSLib.Browser.msie ) pEvent.returnValue = false;
        else pEvent.preventDefault();
    }
}

/// To allow entry of numbers with a single "." for a html text input
/**
 * @startcomment
 * Purpose: To allow entry of numbers with a single "." for a html text input
 * Input Params:
 *	pEvent			- Obj	- Event Object (for Non-IE browsers)
 *	pIsSignedFlag	- Int	- Flag to indicate if the Number should be considered as Signed
 * Output Params:   none
 * Return Value:    none
 * Notes:
 *	pIsSignedFlag is a optional parameter, by default this checks as Unsigned
 *  1.  event.returnValue = TRUE  - if any numeric key or '.' is pressed
 *  2.  event.returnValue = FALSE - any other key is pressed
 * @endcomment
 */
function IsFloatFieldKeyPress (pEvent, pIsSignedFlag)
{
	var evt     = window.event || pEvent;
    var keyCode = TallyJSLib.Browser.msie ? evt.keyCode : evt.which;
	var element = evt.srcElement || evt.target;

    if (evt.type !== "keypress" || keyCode === 0 || keyCode === 8) return true;
    
    if ( keyCode >= 48 && keyCode <= 57 ) return true;

	//Dot symbol- Dot symbol is not present already- allow it
    else if (keyCode === 46 && (element.value.indexOf('.', 0) === -1)) return true;

	//Minus symbol - symbol is not present already- allow it
	else if (pIsSignedFlag == 1 && keyCode === 45 && (element.value.indexOf('-', 0) === -1)) return true;

	//Cancel the Default event Action
    (TallyJSLib.Browser.msie) ? (evt.returnValue = false) : evt.preventDefault();

    //Anything else is not allowed
	return false;
}

/// Compare to floating point values.
/**
 * @startcomment
 * Purpose: Compare to floating point values.
 * Input Params:
 *  1.  pFloatVal1  - Number - Floating point value
 *  2.  pFloatVal2  - Number - Floating point value
 * Output Params:
 * Return Value:
 *  NaN  - Invalid Input
 *  -1  - First Number is Less than Second
 *   0  - Two Numbers are equal
 *   1  - First Number is greater than second
 * Notes:
 * @endcomment
 */
function CompareRealNumbers( pFloatVal1, pFloatVal2 )
{
    var EPSILON = 1.0e-8;

    if(isNaN(parseFloat(pFloatVal1)) || isNaN(parseFloat(pFloatVal2))) return NaN;

    var diff = pFloatVal1 - pFloatVal2;

    if(isNaN(parseFloat(diff))) return NaN;

    //Any difference too negligible is treated as being equal
    if( Math.abs(diff) < EPSILON ) return 0;
    else return (diff < 0) ? -1 : 1;
}

/// Check if a given Numeric value is Empty.
/**
 * @startcomment
 * Purpose: Check if a given Numeric value is Empty.
 * Input Params:
 *  1.  pVal    - Str - Numeric Value
 * Output Params:
 * Return Value:
 *  true    - Field is Empty
 *  false   - Field is Not empty
 * Notes:
 * @endcomment
 */
function IsFloatFieldEmpty( pVal )
{
    if(!IsFloat(pVal)) return true;
    //Compare Against 0 - since 0 is considered empty
    var c = CompareRealNumbers(pVal, 0.000);
    return (isNaN(c) || c === 0) ? true : false;
}

/// Check if a given Integer value is Empty.
/**
 * @startcomment
 * Purpose: Check if a given Integer value is Empty.
 * Input Params:
 *  1.  pVal    - Str - Integer Value
 * Output Params:
 * Return Value:
 *  true    - Field is Empty
 *  false   - Field is Not empty
 *
 * Notes:
 * @endcomment
 */
function IsIntegerFieldEmpty( pVal )
{
    if (!IsInteger(pVal)) return true;
    var r = parseInt(pVal, 10);
    return (isNaN(r) || r === 0) ? true : false;
}

/// Check if a given Integer value is Empty.
/**
 * @startcomment
 * Purpose: Check if a given Integer value is Empty.
 *
 * Input Params:
 *  1.  pStr    - Str - Integer Value
 *
 * Output Params:
 *
 * Return Value:
 *  true    - Field is Empty
 *  false   - Field is Not empty
 *
 * Notes:
 * @endcomment
 */
function IsStringFieldEmpty( pStr )
{
    if (typeof(pStr) === "undefined" || pStr === undefined || pStr === null) return true;
	return ((""+pStr).trim() === "") ? true : false;
}

/// Check if a given Date value is Empty.
/**
 * @startcomment
 * Purpose: Check if a given Date value is Empty.
 * Input Params:
 *  1.  pVal    - Str - Integer Value
 * Output Params:
 *
 * Return Value:
 *  true    - Field is Empty/ 00-00-0000
 *  false   - Field is Not empty
 *
 * Notes:
 * @endcomment
 */
function IsDateFieldEmpty( pDate )
{
	//create a local Date Object and Parse the given string
	var dtObj = new _MyDateParse();
	if (dtObj._ParseDate(pDate) === false) return true;
	
	var year 	= dtObj._GetFullYear(),
		month	= dtObj._GetMonths(),
		day		= dtObj._GetDate();

	//Date is all Zeros
	return (year == 0 || month == -1 || day == 0) ? true : false;
}

/// Check if a given Hour value is Empty.
/**
 * @startcomment
 * Purpose: Check if a given Hour value is Empty.
 *
 * Input Params:
 *  1.  pVal    - Str - Integer Value
 *
 * Output Params:
 *
 * Return Value:
 *  true    - Field is Empty/ 00
 *  false   - Field is Not empty
 *
 * Notes:
 * @endcomment
 */
function IsHourFieldEmpty( pVal )
{
	return IsIntegerFieldEmpty(pVal);
}

/// Check if a given Minute value is Empty.
/**
 * @startcomment
 * Purpose: Check if a given Minute value is Empty.
 *
 * Input Params:
 *  1.  pVal    - Str - Integer Value
 *
 * Output Params:
 *
 * Return Value:
 *  true    - Field is Empty/ 00
 *  false   - Field is Not empty
 *
 * Notes:
 * @endcomment
 */
function IsMinuteFieldEmpty( pVal )
{
    if (!IsInteger(pVal)) return true;
    var r = parseInt(pVal, 10);
	return (isNaN(r) || r < 0) ? true : false;
}

/// Check if a given Seconds value is Empty.
/**
 * @startcomment
 * Purpose: Check if a given Seconds value is Empty.
 *
 * Input Params:
 *  1.  pVal    - Str - Integer Value
 *
 * Output Params:
 *
 * Return Value:
 *  true    - Field is Empty/ 00
 *  false   - Field is Not empty
 *
 * Notes:
 * @endcomment
 */
function IsSecondsFieldEmpty( pVal )
{
	return IsIntegerFieldEmpty(pVal);
}

/// Validate an Email address for well formedness.
/**
 * @startcomment
 * Purpose: Validate an Email address for well formedness.
 *
 * Input Params:
 *  1.  pEmailAddress - String  - Email address to be validated
 *
 * Output Params:
 * Return Value:
 *  true    - Email address is valid
 *  false   - Invalid Email address
 *
 * Notes:
 * @endcomment
 */
function IsValidEmail( pEmailAddress )
{
    if (IsStringFieldEmpty(pEmailAddress)) return false;

    //case : validate string for proper mail address
    return ((""+pEmailAddress).search(/^\w+((\.|-)\w+)*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/i) != -1) ? true : false;
}

/// Validate an URL for well formedness.
/**
 * @startcomment
 * Purpose: Validate an URL for well formedness.
 *
 * Input Params:
 *  1.  pURL - String  - URL to be validated
 * Output Params: none
 * Return Value:
 *  true    - URL is valid
 *  false   - Invalid URL
 *
 * Notes: Needs to be optimised
 * @endcomment
 */
function IsValidURL( pURL )
{
    if (IsStringFieldEmpty(pURL)) return false;

    //case : validate string for proper mail address
    return ((""+pURL).search(/^((https?|ftp)\:\/\/)?\w+\.\w+$/i) != -1) ? true : false;///???????????????????
}

/// Set Default Integer Value on Invalid Input.
/**
 * @startcomment
 * Purpose: Set Default Integer Value on Invalid Input.
 *
 * Input Params:
 *  1.  pDefaultVal - Int   - Value to set as Default
 *	2.	pIsSignedFlag _ int	- Optional. Indicate is the Number is signed
 * Output Params: none
 * Return Value:  none
 *
 * Notes:
 * @endcomment
 */
function SetDefaultIntegerValue( pEvent, pDefaultVal, pIsSignedFlag )
{
	pEvent 	= window.event || pEvent;
	var element = pEvent.srcElement || pEvent.target;

    if (pDefaultVal === undefined || pDefaultVal === null || !IsInteger(pDefaultVal,pIsSignedFlag)) pDefaultVal = 0;

    // case : not a number, or blank value
    if ( !IsInteger(element.value,pIsSignedFlag) ) element.value = pDefaultVal;
}

/// Set Default Numeric/Float Value on Invalid Input.
/**
 * @startcomment
 * Purpose: Set Default Numeric/Float Value on Invalid Input.
 *
 * Input Params:
 *  1.  pDefaultVal - Float   - Value to set as Default
 *	2.	pIsSignedFlag _ int	- Optional. Indicate is the Number is signed
 * Output Params: none
 * Return Value:  none
 *
 * Notes:
 * @endcomment
 */
function SetDefaultFloatValue( pEvent, pDefaultVal, pIsSignedFlag )
{
	pEvent 	= window.event || pEvent;
	var element = pEvent.srcElement || pEvent.target;

    if (pDefaultVal === undefined || pDefaultVal === null || !IsFloat(pDefaultVal, pIsSignedFlag)) pDefaultVal = 0.00;

    // case : not a number, or blank value
    if ( !IsFloat(element.value, pIsSignedFlag ) ) element.value = pDefaultVal;
}

/// Set Default Date Value on Invalid Input.
/**
 * @startcomment
 * Purpose: Set Default Date Value on Invalid Input.
 *
 * Input Params:
 *  1.  pDefaultVal - Str   - Value to set as Default
 *
 * Output Params: none
 * Return Value:  none
 *
 * Notes:
 * @endcomment
 */
function SetDefaultDateValue( pEvent, pDefaultVal )
{
	pEvent 	= window.event || pEvent;
	var element = pEvent.srcElement || pEvent.target;

    if (pDefaultVal === undefined || pDefaultVal === null || !IsDate(pDefaultVal)) pDefaultVal = '';

    // case : not a number, or blank value
    if ( !IsDate2(element.value) ) element.value = pDefaultVal;
}

/// Set Default Hour Value on Invalid Input.
/**
 * @startcomment
 * Purpose: Set Default Hour Value on Invalid Input.
 *
 * Input Params:
 *  1.  pDefaultVal - Int - Value to set as Default
 *
 * Output Params: none
 * Return Value:  none
 *
 * Notes:
 * @endcomment
 */
function SetDefaultHourValue( pEvent, pDefaultVal )
{
	SetDefaultIntegerValue(pEvent, pDefaultVal, 0);
}

/// Set Default Minute Value on Invalid Input.
/**
 * @startcomment
 * Purpose: Set Default Minute Value on Invalid Input.
 *
 * Input Params:
 *  1.  pDefaultVal - Int - Value to set as Default
 *
 * Output Params: none
 * Return Value:  none
 *
 * Notes:
 * @endcomment
 */
function SetDefaultMinuteValue( pEvent, pDefaultVal )
{
	SetDefaultIntegerValue(pEvent, pDefaultVal, 0);
}

/// Set Default Seconds Value on Invalid Input.
/**
 * @startcomment
 * Purpose: Set Default Seconds Value on Invalid Input.
 *
 * Input Params:
 *  1.  pDefaultVal - Int - Value to set as Default
 *
 * Output Params: none
 * Return Value:  none
 *
 * Notes:
 * @endcomment
 */
function SetDefaultSecondsValue( pEvent, pDefaultVal )
{
	SetDefaultIntegerValue(pEvent, pDefaultVal, 0);
}

/// Check if the Passed Value is Valid Hour.
/**
 * @startcomment
 * Purpose: Check if the Passed Value is Valid Hour.
 *
 * Input Params:
 *  1.  pHour   - Int   - Hour to be checked
 *  2.  pFormat - Int   - Hour Format, values can 12 or 24
 *
 * Output Params:
 *
 * Return Value:
 *  true    - Hour is Valid
 *  false   - Hour input is invalid
 *
 * Notes:
 * @endcomment
 */
function IsValidHour( pHour, pFormat)
{
    if (!IsInteger(pHour)) return false;

    var h = parseInt(pHour, 10);

    switch(pFormat) {
    case 12 :
        if(isNaN(h) || h < 0 || h > 12) return false;
        break;
    case 24 :
        if(isNaN(h) || h < 0 || h > 23 ) return false;
        break;
    default :
        return false;
    }

    return true;
}

/// Check if the Passed Value is Valid Minutes.
/**
 * @startcomment
 * Purpose: Check if the Passed Value is Valid Minutes.
 *
 * Input Params:
 *  1.  pMin   - Int   - Minute to be checked
 * Output Params: none
 * Return Value:
 *  true    - Hour is Valid
 *  false   - Hour input is invalid
 *
 * Notes:
 * @endcomment
 */
function IsValidMinute( pMin )
{
    if (!IsInteger(pMin)) return false;

    var m = parseInt(pMin, 10);
    if(isNaN(m) || m < 0 || m > 59) return false;

    return true;
}

/// Check if the Passed Value is Valid Seconds.
/**
 * @startcomment
 * Purpose: Check if the Passed Value is Valid Seconds.
 *
 * Input Params:
 *  1.  pSec   - Int   - Second to be checked
 * Output Params: none
 * Return Value:
 *  true    - Hour is Valid
 *  false   - Hour input is invalid
 *
 * Notes:
 * @endcomment
 */
function IsValidSecond( pSec )
{
	return IsValidMinute( pSec );
}

/// To allow entry of numbers for a html text input
/**
 * @startcomment
 * Purpose: To allow entry of numbers for a html text input
 *
 * Input Params:
 *	pIsSignedFlag	- Int	- Flag to indicate if '-' sign is allowed
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * Notes:
 *	pIsSignedFlag is a optional parameter, by Default this behaves as Unsigned
 *   1.  event.returnValue = TRUE  - if any numeric key is pressed
 *   2.  event.returnValue = FALSE - any other key is pressed
 * @endcomment
 */
function IsIntegerFieldKeyPress ( pEvent, pIsSignedFlag)
{
	pEvent 	= window.event || pEvent;
    var keyCode = TallyJSLib.Browser.msie ? pEvent.keyCode : pEvent.which;
	var element = pEvent.srcElement || pEvent.target;

    if (pEvent.type !== "keypress" || keyCode === 0 || keyCode === 8) return true;

	//case: Signed Interger && minus symbol
	if (pIsSignedFlag == 1 && keyCode === 45) { 

		//case: User has already enter -
		if(element && element.value && (element.value.indexOf('-', 0) > -1)) 
        {
			(TallyJSLib.Browser.msie) ? (pEvent.returnValue = false) : (pEvent.preventDefault());
			return false;
		}
        return true;
	}

    // case : numeric key, or enter key
    if ( ( keyCode >= 48 && keyCode <= 57 ) || keyCode === 13 )
    {
        return true; 
    }

	(TallyJSLib.Browser.msie) ? (pEvent.returnValue = false) : (pEvent.preventDefault());
	return false;
}

/// To allow entry of numbers for a html text input
/**
 * @startcomment
 * Purpose: To allow entry of numbers for a html text input
 *
 * Input Params:
 *	pHourFormat	- Int	- 12/24 hour format
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * Notes:
 *   1.  event.returnValue = TRUE  - if any numeric key is pressed
 *   2.  event.returnValue = FALSE - any other key is pressed
 * @endcomment
 */
function IsHourFieldKeyPress (pEvent, pHourFormat)
{
	pEvent 	= window.event || pEvent;
	var keyCode = pEvent.which || pEvent.keyCode;
	var element = pEvent.srcElement || pEvent.target;

    if (pEvent.type !== "keypress" || keyCode === 0 || keyCode === 8) return true;

    // case : numeric key, or enter key
    if ( ( keyCode >= 48 && keyCode <= 57 ) || keyCode === 13 )
    {
		var val = parseInt(element.value, 10);
		if (pHourFormat == 12)
		{
            if(isNaN(val) || val < 1 || val > 12)
			{
				(TallyJSLib.Browser.msie) ? (pEvent.returnValue = false) : (pEvent.preventDefault());
				return false;
			}
		}
		else
		{
            if(isNaN(val) || val < 0 || val > 23)
			{
				(TallyJSLib.Browser.msie) ? (pEvent.returnValue = false) : (pEvent.preventDefault());
				return false;
			}
		}
        return true;
    }

    (TallyJSLib.Browser.msie) ? (pEvent.returnValue = false) : (pEvent.preventDefault());
	return false;
}

/// To allow entry of Minutes for a html text input
/**
 * @startcomment
 * Purpose: To allow entry of Minutes for a html text input
 *
 * Input Params:	none
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * Notes:
 *   1.  event.returnValue = TRUE  - if any numeric key is pressed
 *   2.  event.returnValue = FALSE - any other key is pressed
 * @endcomment
 */
function IsMinuteFieldKeyPress (pEvent)
{
	pEvent 	= window.event || pEvent;
	var keyCode = pEvent.which || pEvent.keyCode;
	var element = pEvent.srcElement || pEvent.target;

    if (pEvent.type !== "keypress" || keyCode === 0 || keyCode === 8) return true;

    // case : numeric key, or enter key
    if ( ( keyCode >= 48 && keyCode <= 57 ) || keyCode === 13 )
    {
		var val = parseInt(element.value, 10);
		if(isNaN(val) || val < 0 || val > 59)
		{
			(TallyJSLib.Browser.msie) ? (pEvent.returnValue = false) : (pEvent.preventDefault());
			return false;
		}

        return true;
    }

	(TallyJSLib.Browser.msie) ? (pEvent.returnValue = false) : (pEvent.preventDefault());
	return false;
}

/// To allow entry of Seconds for a html text input
/**
 * @startcomment
 * Purpose: To allow entry of Seconds for a html text input
 *
 * Input Params:	none
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * Notes:
 *   1.  event.returnValue = TRUE  - if any numeric key is pressed
 *   2.  event.returnValue = FALSE - any other key is pressed
 * @endcomment
 */
function IsSecondsFieldKeyPress (pEvent)
{
	return IsMinuteFieldKeyPress (pEvent);
}

/// To allow entry of valid date
/**
 * @startcomment
 * Purpose: To allow entry of valid date
 *
 * Input Params:    none
 * Output Params:   none
 * Return Value:    none
 *
 * Notes:
 *  1. Will allow '-' as separating char
 * @endcomment
 */
function IsDateFieldKeyPress (pEvent)
{
	pEvent 		= window.event || pEvent;
	var keyCode = pEvent.which || pEvent.keyCode;

    if (pEvent.type !== "keypress" || keyCode === 0 || keyCode === 8) return true;

    // if valid key (number, - )
    if ( ( keyCode >= 48 && keyCode <= 57 ) || keyCode === 13 || keyCode === 45 ) return true;

	(TallyJSLib.Browser.msie) ? (pEvent.returnValue = false) : (pEvent.preventDefault());
	return false;
}

/// To allow entry of valid date
/**
 * @startcomment
 * Purpose: To allow entry of valid date
 *
 * Input Params:    none
 * Output Params:   none
 * Return Value:    none
 *
 * Notes:
 *  1. Will allow '-' as separating char
 * @endcomment
 */
function IsDateFieldKeyPressAlt (pEvent)
{
	pEvent 		= (window.event) ? window.event : pEvent;
	var keyCode = (TallyJSLib.Browser.msie) ? pEvent.keyCode : pEvent.which;

    if (pEvent.type !== "keypress" || keyCode === 0 || keyCode === 8) return true;

    // if valid key (number, - )
    if ( ( keyCode >= 48 && keyCode <= 57 ) || keyCode === 13 || keyCode === 45 ) return true;

    //case: Ignore any special Keys, Eg: home, del, backspace
    if (vIsPropValueExists(TallyJSLib.Event.SplKeys, keyCode)) {
        return true;
    }

	(TallyJSLib.Browser.msie) ? (pEvent.returnValue = false) : (pEvent.preventDefault());
	return false;
}

/// To check if input is a +ve integer value
/**
 * @startcomment
 * Purpose: To check if input is a +ve integer value
 *
 * Input Params:
 *  1.  pVal - str - input to be checked for digits
 *	2.	pIsSignedFlag _ int	- Optional. Indicate is the Number is signed
 *
 * Output Params:
 *
 * Return Value:
 *  true - if input is a +ve integer
 *  false - if input is not an integer
 *
 * Notes:
 *  1. Will check each char in input for digits 0 to 9
 *  Regular Expressions are supported JS 1.2 onwards only!
 * @endcomment
 */
function IsInteger ( pVal, pIsSignedFlag )
{
    // case : if blank input, then return false
	if ( IsStringFieldEmpty(pVal)) return false;

    return (pIsSignedFlag == 1) ? /^-?\d+$/.test(pVal) : /^\d+$/.test(pVal);
}

/// To check if input is a numeric value (+ or -)
/**
 * @startcomment
 * Purpose: To check if input is numeric value (+ or -)
 *
 * Input Params:
 *  1.  pVal - str - input to be checked
 *
 * Output Params:
 *
 * Return Value:
 *  true - if input is numeric
 *  false - if input is not numeric
 *
 * Notes:
 * 1. Example inputs : 2.5687, -3.58, 0.12, .12
 * @endcomment
 */
function IsFloat( pVal, pIsSignedFlag )
{
    // case : if blank input, then return false
	if ( IsStringFieldEmpty(pVal)) return false;

    //!! Converts to boolean
    return (pIsSignedFlag == 1) ? !!(/^-?(\d+)?(\.\d+)?$/.test(pVal)) : !!(/^(\d+)?(\.\d+)?$/.test(pVal));
}

/// To check if string is alphanumeric
/**
 * @startcomment
 * Purpose: To check if string is alphanumeric
 *
 * Input Params:
 *  1. pStr - string - string to be tested
 *
 * Output Params:   none
 *
 * Return Value:
 *  true - if all characters in the string are a character from 0-9 or a-z or A-Z
 *  false - if otherwise
 *
 * Notes:
 * @endcomment
 */
function IsAlphaNum ( pStr )
{
    // Return immediately if an invalid value was passed in
	if ( IsStringFieldEmpty(pStr)) return false;

	return !!(/^[0-9a-zA-Z]+$/.test(pStr +""));
}

/// To set a checkbox group to on/off
/**
 * @startcomment
 * Purpose: To set a checkbox group to on/off
 *
 * Input Params:
 *  1. pCheckItem - obj - check box group id/name attribute
 *  2. pFlag - int - group to be checked on/off (1/0)
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * Notes:
 *  1. pFlag = 1 if group to be checked
 *  2. pFlag = 0 if group to be unchecked
 * @endcomment
 */
function ToggleCheckboxSelection ( pChkItem, pFlag )
{
    if ( !pChkItem ) return;

    if (pChkItem.length && pChkItem.length > 0) {
        for (var i=0,l=pChkItem.length; i<l; i++ ) 
            pChkItem[i].checked = ( pFlag == 1 ) ? true : false;
    }
    else pChkItem.checked = ( pFlag == 1 ) ? true : false;
}

/// To build date from the supplied params and check it is valid or not
/**
 * @startcomment
 * Purpose: To build date from the supplied params and check it is valid or not
 *
 * Input Params:
 *  1. pYear  - String - to get the string which represents year
 *  2. pMonth - String - to get the string which represents month
 *  3. pDay   - String - to get the string which represents day
 *
 * Output Params:   none
 *
 * Return Value:
 *  true  - if supplied date is a valid
 *  false - if supplied date is invalid
 *
 * Notes:
 * @endcomment
 */
function IsDate ( pDateTimeStr )
{
	if (IsStringFieldEmpty(pDateTimeStr)) return false;

	//create a local Date Object and Parse the given string
	var dtObj = new _MyDateParse();

	if (dtObj._ParseDate(pDateTimeStr) === false) return false;

	var year 	= dtObj._GetFullYear(),
		month	= dtObj._GetMonths(),
		day		= dtObj._GetDate(),
		hour	= dtObj._GetFullHours(),
		min		= dtObj._GetMinutes(),
		sec		= dtObj._GetSeconds();

	//Date is all Zeros
	if (year == 0 || month == -1 || month > 11 || day == 0) return false;

	var dt = new Date(year, month, day, hour, min, sec, 0);

	// case : if inputs match the date object
	if( year == dt.getFullYear() && month == dt.getMonth() && day == dt.getDate() &&
		hour == dt.getHours() && min == dt.getMinutes() && sec == dt.getSeconds()) 
		return true;

	return false;
}


/// Calculate the Difference between two date formats.
/**
 * @startcomment
 * Purpose: Calculate the Difference between two date formats.
 *
 * Input Params:
 *  1.  pDateTime1  - Str   - Date Time
 *  2.  pDateTime2  - Str   - Date Time
 *  3.  pDiffType   - Str   - Date Time Difference type
 *
 * Output Params:
 *
 * Return Value:
 *  Int - Difference in the specified format
 *
 * Notes:
 * @endcomment
 */
function GetDateDiff( pDateTime1, pDateTime2, pDiffType )
{
    var d1, d2;

	if (!IsDate(pDateTime1)) return false;

	if (!IsDate(pDateTime2)) return false;

	var dtObj, day, month, year, hour, min, sec;
	dtObj = new _MyDateParse();

	//Parse and get the first Date components
	dtObj._ParseDate(pDateTime1);
	year 	= dtObj._GetFullYear();
	month	= dtObj._GetMonths();
	day		= dtObj._GetDate();
	hour	= dtObj._GetFullHours();
	min		= dtObj._GetMinutes();
	sec		= dtObj._GetSeconds();
	var d1 = new Date(year, month, day, hour, min,sec, 0);

	//Parse and get the second Date components
	dtObj._ParseDate(pDateTime2);
	year 	= dtObj._GetFullYear();
	month	= dtObj._GetMonths();
	day		= dtObj._GetDate();
	hour	= dtObj._GetFullHours();
	min		= dtObj._GetMinutes();
	sec		= dtObj._GetSeconds();
	var d2 = new Date(year, month, day, hour, min,sec, 0);

    var diff = d1.getTime() - d2.getTime();

    switch( pDiffType )
    {
	//Months???
	//case "MM" : diff = intval( diff / ( 24 * 60 * 60 * 1000 )); break;
	case "Y"    : 
	case "y"    :
	diff = parseInt( diff / ( 365 * 24 * 60 * 60 * 1000 )); break;

	case "D"    : 
	case "d"    :
	diff = parseInt( diff / ( 24 * 60 * 60 * 1000 )); break;
	case "H"    : 
	case "h"    :
	diff = parseInt( diff / ( 60 * 60 * 1000)); break;
	case "M"    :
	case "m"    :
	diff = parseInt( diff / ( 60 * 1000 )); break;
	case "S"    : 
	case "s"    : 
	diff = parseInt( diff / 1000 ); break;
	default   : break;
    }

    return diff;
}


/// Compare Two Date & Time Fields.
/**
 * @startcomment
 * Purpose: Compare Two Date & Time Fields.
 *
 * Input Params:
 *  1.  pDate1  - Str   - Date 1 format
 *  2.  pDate2  - Str   - Date 2 format
 *
 * Output Params: None
 *
 * Return Value:
 *  -2  - First Date Time format is Invalid
 *  -1  - First Date Time < Second Date time
 *   0  - First Date Time is equal to Second
 *   1  - First Date Time greater than second
 *   2  - Second date time is Invalid
 * Notes:
 * Date can be in any one of these formats - dd-mm-yyyy / dd-mm-yyyy hh:mm:ss / dd-mm-yyyy hh:mm:ss am/pm
 *
 * @endcomment
 */
function CompareDate( pDateTime1, pDateTime2 )
{
	//First date is invalid
	if (!IsDate(pDateTime1)) return -2;

	//Second date is invalid
	if (!IsDate(pDateTime2)) return 2;

	//Obtain the difference in time stamp between two dates
	var diff = GetDateDiff( pDateTime1, pDateTime2 );

    //case: First Datetime > second Datetime
    if (diff > 0) return 1;

    //case: First Datetime < second Datetime
    else if (diff < 0) return -1;

    //case: First Datetime == second Datetime
    else return 0;
}

/// To add the supplied interval with the supplied date and return the new date
/**
 * @startcomment
 * Purpose: To add the supplied interval with the supplied date and return the new date
 *
 * Input Params:
 *  dateval   - String - date
 *  interval  - String - interval
 *  addtype   - String - type ('D' / 'M' / 'Y' /'H' /'I'/'S')
 *
 * Output Params:   none
 *
 * Return Value:
 *  date - the new date after adding the supplied interval with supplied date
 *
 * Notes:
 *  1. pAddType specifies that, interval is added to days, months or with year
 * @endcomment
 */
function DateAdd ( pDate, pInterval, pAddType )
{
    var day 	= pDate.getDate(),
		month 	= pDate.getMonth(),
		year 	= pDate.getFullYear(),
		hour	= pDate.getHours(),
		min		= pDate.getMinutes(),
		sec		= pDate.getSeconds();

    switch ( pAddType )
    {
	case 'H' :
		hour	= parseInt(hour, 10) + parseInt(pInterval, 10);
		return new Date( year, month, day, hour, min, sec, 0);

    case 'i' : 
    case 'I' : 
		min	= parseInt(min, 10) + parseInt(pInterval, 10);
		return new Date( year, month, day, hour, min, sec, 0);

	case 'S' :
		sec	= parseInt(sec, 10) + parseInt(pInterval, 10);
		return new Date( year, month, day, hour, min, sec, 0);

	// add day
	case 'D':
		day = parseInt(day, 10) + parseInt(pInterval, 10);
		return new Date(year, month, day);

	// add month
	case 'M':
		month = parseInt(month, 10) + parseInt(pInterval, 10);
		return new Date(year, month, day);

	// add year
	case 'Y':
		year = parseInt(year, 10) + parseInt(pInterval, 10);
		return new Date(year, month, day);
    }
}

/// To display the startdate & end date based on the selected period
/**
 * @startcomment
 * Purpose: To display the startdate & end date based on the selected period
 *
 * Input Params:
 *  pFrmName          - String  - form
 *  pPeriodConstName  - String  - Period constant
 *  pStartDateName    - String  - start date control
 *  pEndDateName      - integer - end date control
 *  pDisableDtFldFlag - integer - flag to identify whether to disable/enable the date controls
 *
 * Output Params:
 *  1.  Param1 - DataType - Desc
 *  2.  Param1 - DataType - Desc
 *
 * Return Value:
 *  ReturnVal - DataType - Desc
 *
 * Notes:
 * @endcomment
 */
function ChangePeriod ( pFrmName, pPeriodConstName, pStartDateName, pEndDateName, pDisableDtFldFlag )
{
    var _TODAY                  = 1,
        _YESTERDAY              = 2,
        _YESTERDAY_AND_TODAY    = 3,
        _TOMORROW               = 4,
        _LAST_SEVEN_DAYS        = 5,
        _NEXT_SEVEN_DAYS        = 6,
        _LAST_FIFTEEN_DAYS      = 7,
        _NEXT_FIFTEEN_DAYS      = 8,
        _LAST_MONTH             = 9,
        _THIS_MONTH             = 10,
        _NEXT_MONTH             = 11,
        _LAST_YEAR              = 12,
        _THIS_YEAR              = 13,
        _LAST_FINANCIAL_YEAR    = 14,
        _THIS_FINANCIAL_YEAR    = 15,
        _TILL_TODAY             = 16,
        _MENTION_PERIOD         = 101;

    var form_obj = document.forms( pFrmName ),
        period_const_obj = form_obj.elements( pPeriodConstName ),
        start_dt_obj = form_obj.elements( pStartDateName ), 
        end_date_obj = form_obj.elements( pEndDateName ),
        periodConst = parseInt( period_const_obj.value );
    var dt_obj = new Date();    

    if ( pDisableDtFldFlag == 1 ) 
    {
        // set the dafault display status as disabled
        start_dt_obj.disabled = true;
        end_date_obj.disabled = true;
    }
    //Store the initial display state
    var ts = start_dt_obj.disabled, 
        te = end_date_obj.disabled;

    // Enable controls, non-IE browsers does not display values in disabled state
    start_dt_obj.disabled = end_date_obj.disabled = false;

    // set dates on the period const value
    switch ( periodConst )
    {
        case _TODAY :
            day_interval        = 0;
            dt_obj              = DateAdd( dt_obj, day_interval, 'D' );
            end_date_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            start_dt_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _YESTERDAY :
            day_interval        = -1;
            dt_obj              = DateAdd( dt_obj, day_interval, 'D' );
            end_date_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            start_dt_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _YESTERDAY_AND_TODAY :
            day_interval        = -1;
            end_date_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            dt_obj              = DateAdd( dt_obj, day_interval, 'D' );
            start_dt_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _TOMORROW :
            day_interval        = 1;
            dt_obj              = DateAdd( dt_obj, day_interval, 'D' );
            end_date_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            start_dt_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _LAST_SEVEN_DAYS :
            day_interval        = -7;
            end_date_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            dt_obj              = DateAdd( dt_obj, day_interval, 'D' );
            start_dt_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _NEXT_SEVEN_DAYS :
            day_interval        = 7;
            start_dt_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            dt_obj              = DateAdd( dt_obj, day_interval, 'D' );
            end_date_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _LAST_FIFTEEN_DAYS :
            day_interval        = -15;
            end_date_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            dt_obj              = DateAdd( dt_obj, day_interval, 'D' );
            start_dt_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _NEXT_FIFTEEN_DAYS :
            day_interval        = 15;
            start_dt_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            dt_obj              = DateAdd( dt_obj, day_interval, 'D' );
            end_date_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _THIS_MONTH :
            start_dt_obj.value  = '01' + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            end_date_obj.value  = GetMonthDays( dt_obj.getMonth() + 1, dt_obj.getYear() ) + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _LAST_MONTH :
            dt_obj              = DateAdd( dt_obj,  -( dt_obj.getDate()), 'D');
            start_dt_obj.value  = '01' + '-' + (dt_obj.getMonth()+1) + '-' + dt_obj.getYear();
            end_date_obj.value  =  dt_obj.getDate() + '-' + (dt_obj.getMonth()+1) + '-' + dt_obj.getYear();
            break;

        case _NEXT_MONTH :
            var dayinterval     = GetMonthDays( dt_obj.getMonth() + 1, dt_obj.getYear() ) - dt_obj.getDate() + 1;
            dt_obj              = DateAdd( dt_obj,  dayinterval, 'D');
            start_dt_obj.value  = dt_obj.getDate () + '-' + (dt_obj.getMonth() + 1 ) + '-' + dt_obj.getYear() ;
            end_date_obj.value  = GetMonthDays(dt_obj.getMonth()+1, dt_obj.getYear()) + '-' + (dt_obj.getMonth()+1) + '-' + dt_obj.getYear() ;
            break;

        case _THIS_YEAR :
            start_dt_obj.value  = '01' + '-' + '01' + '-' + dt_obj.getYear();
            end_date_obj.value  = '31' + '-' + '12' + '-' + dt_obj.getYear();
            break;

        case _LAST_YEAR :
            start_dt_obj.value  = '01' + '-' + '01' + '-' + ( dt_obj.getYear() + (-1) );
            end_date_obj.value  = '31' + '-' + '12' + '-' + ( dt_obj.getYear() + (-1) );
            break;

        case _THIS_FINANCIAL_YEAR :
            var year            = ( ( dt_obj.getMonth() + 1 ) > 3 ? dt_obj.getYear() : ( dt_obj.getYear() + (- 1) ));
            var end_year        = ( ( dt_obj.getMonth() + 1 ) > 3 ? ( dt_obj.getYear() + 1 ) : ( dt_obj.getYear() ));
            start_dt_obj.value  = '01' + '-' + '04' + '-' + year;
            end_date_obj.value  = '31' + '-' + '03' + '-' + end_year;
            break;
    
        case _LAST_FINANCIAL_YEAR :
            year                = ( ( dt_obj.getMonth() + 1 ) > 3 ? ( dt_obj.getYear() + (- 1) ) : ( dt_obj.getYear() + (- 2)));
            end_year            = ( ( dt_obj.getMonth() + 1 ) > 3 ? ( dt_obj.getYear() ) : ( dt_obj.getYear() + (- 1)));
            start_dt_obj.value  = '01' + '-' + '04' + '-' + year;
            end_date_obj.value  = '31' + '-' + '03' + '-' + end_year;
            break;

        case _TILL_TODAY :
            day_interval        = 0;
            dt_obj              = DateAdd( dt_obj, day_interval, 'D' );
            start_dt_obj.value  = '';
            end_date_obj.value  = dt_obj.getDate() + '-' + (dt_obj.getMonth() + 1) + '-' + dt_obj.getYear();
            break;

        case _MENTION_PERIOD :
            // remove the disabled status of the elt
            start_dt_obj.disabled = false;
            end_date_obj.disabled = false;
            break;
    
        default: 
            start_dt_obj.value = "";
            end_date_obj.value = "";
            // start_dt_obj.disabled = true;    // ????
            // end_date_obj.disabled = true;    // ????
            break;
    }

    //revert back the disabled state
    if ( periodConst != _MENTION_PERIOD) {
        start_dt_obj.disabled = ts; 
        end_date_obj.disabled = te;
    }

    return;
}

/// To check if the year is a leap year or not
/**
 * @startcomment
 * Purpose: To check if the year is a leap year or not
 *
 * Input Params:
 * pYear  - String - to get the year to check it is a leap year or not 
 *
 * Output Params:   none
 *
 * Return Value:
 *  true - if leap year
 *  false - if not a leap year
 *
 * Notes:
 * @endcomment
 */
function IsLeapYear ( pYear )
{
    var quotient;
    var is_leap_year = false;

    // If the year is evenly divisible by 4 and not by 100, then this is a leap year
    if( !( pYear%4 ) && ( pYear%100 ) ) is_leap_year = true;

    else
    {
        // If the year is evenly divisible by 4 and 100, then check to
        // see if the quotient of year divided by 100 is also evenly 
        // divisible by 4. If it is, then this is a leap year.
        if( !( pYear%4 ) && !( pYear%100 ) )
        {
            quotient = pYear/100;
            if(!( quotient%4 )) is_leap_year = true;
        }
    }

    return is_leap_year;
}

/// To get number of days in a month
/**
 * @startcomment
 * Purpose: To get number of days in a month
 *
 * Input Params:
 *  pMonth  - Integer - month 
 *  pYear   - Integer - year 
 *
 * Output Params:   none
 *
 * Return Value:
 *  Integer - Number of days in the month
 *
 * Notes:
 * @endcomment
 */
function GetMonthDays ( pMonth, pYear )
{
    switch( parseInt(pMonth) )
    {
        case 1: // Jan
            return 31;
        case 2: // Feb
            if ( IsLeapYear(pYear) == true ) return 29;
            else return 28;
        case 3: // Mar
            return 31;
        case 4: // Apr
            return 30;
        case 5: // May
            return 31;
        case 6: // Jun
            return 30;
        case 7: // Jul
            return 31;
        case 8: // Aug
            return 31;
        case 9: // Sept
            return 30;
        case 10: // Oct
            return 31;
        case 11: // Nov
            return 30;
        case 12: // Dec
            return 31;
    }
}

/// To create the progress bar
/**
 * @startcomment
 * Purpose: To create the progress bar
 *
 * Input Params:
 *  1. pWidth - int - the width of progress bar
 *  2. pHeight - int - the height of the progress bar
 *
 * Output Params:   none
 *
 * Return Value:
 *  intervalobj of the progress bar
 *
 * Notes:
 *  1. The progress bar can be stopped by calling clearInterval(intervalobj)
 *  2. Implemented in GLibProject.php
 * @endcomment
 */
function CreateProgressBar( pWidth, pHeight )
{
    // is IE
    // is browser w3c compliant
    var is_w3c = (document.getElementById) ? true : false;

    // progress speed
    var speed = 85;

    // number of progress blocks
    num_blocks = 7;

    // max counter ???? unsure what this is required for
    count = 3;

    // case : progress bar will work only in IE or w3c compliant browsers
    if( TallyJSLib.Browser.msie || is_w3c )
    {
        var html = '<div id="ProgressBarContainer" style="visibility:visible; position:relative; overflow:hidden; width:'+pWidth+'px; height:'+pHeight+'px; background-color:white; border-color:black; border-width:1px; border-style:solid; font-size:1px;">';
        html += '<span id="ProgressBarBlocks" style="left:-' + (pHeight*2+1) + 'px; position:absolute; font-size:1px">';

        for( i=0; i<num_blocks; i++ )
        {
            html += '<span style="background-color: blue; left:-' + ((pHeight*i)+i) + 'px; font-size:1px; position:absolute; width:' + pHeight + 'px; height:' + pHeight + 'px; ';
            html += (TallyJSLib.Browser.msie) ? 'filter:alpha(opacity=' + (100-i*(100/num_blocks))+ ')' : '-Moz-opacity:'+((100-i*(100/num_blocks))/100);
            html += '"></span>';
        }
        html += '</span></div>';

        //document.write(html);
        var t = document.getElementById("probar");
        t.innerHTML=html;

        var progress_bar = (TallyJSLib.Browser.msie)?document.all['ProgressBarBlocks']:document.getElementById('ProgressBarBlocks');
        progress_bar.bar = (TallyJSLib.Browser.msie)?document.all['ProgressBarContainer']:document.getElementById('ProgressBarContainer');
        progress_bar.Blocks = num_blocks;
        progress_bar.BarWidth = pWidth;
        progress_bar.BarHeight = pHeight;
        progress_bar.Speed = speed;
        progress_bar.Counter = 0;
        progress_bar.Count = count;
        progress_bar.IntervalId = setInterval( 'StartProgressBar()', speed );

        return progress_bar.IntervalId;
    }
}

/// To start the progress bar
/**
 * @startcomment
 * Purpose: To start the progress bar
 *
 * Input Params:
 *  1.  pBarNumber - str - the bar that is to start progressing
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * Notes:
 *  1. Implemented in GLibProject.php
 * @endcomment
 */
function StartProgressBar ()
{
    var span_obj = (TallyJSLib.Browser.msie) ? document.all['ProgressBarBlocks'] : document.getElementById('ProgressBarBlocks');

    if( parseInt(span_obj.style.left) + span_obj.BarHeight + 1 - ( span_obj.Blocks * span_obj.BarHeight + span_obj.Blocks ) > span_obj.BarWidth )
    {
        span_obj.style.left=-(span_obj.BarHeight*2+1)+'px';

        span_obj.Counter++;

        if(span_obj.Counter>=span_obj.Count)
        {
            span_obj.Counter=0;
        }
    }

    else span_obj.style.left=(parseInt(span_obj.style.left)+span_obj.BarHeight+1)+'px';
}

/// to make a client-side request to the server, and obtain the response
/**
 * Purpose: to make a client-side request to the server, and obtain the response
 *
 * Input Params:
 *  1. pURL - string - request URL
 *  2. pPostVars - string - POST variables
 *  3. pCallbackFunc - function reference - function that is to be called on successful response
 *  4. pAsync - int - if request to be asynchronous - 1/0
 *
 * Output Params:   none
 *
 * Return Value:
 *  on success - string - the response from the server
 *  on failure - bool - false
 *
 * Notes:
 *  1. By default the request will *NOT* be asynchronous. This behavour can be changed by
 *     the param pAsync. 1 is for asynchronous, and 0 is for synchronous.
 *  2. By default the request method is GET. If however pPostVars is passed to the func, then
 *     the request method will be POST.
 *     pPostVars will a set of post variables as "var1=val1&var2=val2&var3=val3&varn=valn"
 *  3. pCallbackFunc is a reference to a JS function. If specified, this function must mandatorily 
 *     take a parameter to which the server response string will be passed.
 *  4. In most cases, if the request is going to be asynchronous, then it is always better
 *     to pass a callback function to do the needful scripting after the server response.
 */
function GetServerResponse ( pURL, pPostVars, pCallbackFunc, pAsync )
{
    var http_request = false,
        http_method = "GET",
        request_type = false,
        server_response;

    if ( pPostVars && pPostVars != "") http_method = "POST";
    if ( pAsync && pAsync == 1 ) request_type = true;

    // Evil IE, use ActiveXObject as much as possible
    // IE 7 & above have native XMLHttpRequest
    // But ie7 allows switching it off!!!
    if ( window.ActiveXObject ) {
        /*
        src: http://snook.ca/archives/javascript/xmlhttprequest_activex_ie/
        http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
        */
        try { http_request = new ActiveXObject ( "MSXML2.XMLHTTP.6.0" ); }
        catch (e) {
            try { http_request = new ActiveXObject ( "MSXML2.XMLHTTP" ); }
            catch (e) { http_request = false;}
        }
    }
    // Good browsers...
    else if ( window.XMLHttpRequest ) {
        http_request = new XMLHttpRequest ();

        // some versions of Mozilla browsers won't work properly if 
        // response from server doesn't have xml mime-type header
        if ( http_request.overrideMimeType ) http_request.overrideMimeType ( "text/xml" );
    }

    if (! http_request) {
        alert('Error : Cannot create an XMLHTTP instance');
        return false;
    }

    //Asynchronous req, on State changes, AJAX obj will fire events
    if (request_type === true) {
    // return server output on successful retrieval
    http_request.onreadystatechange = function() {
		//completed
            if ( http_request.readyState == 4 ) {
            // successfully got response
                if ( http_request.status == 200 ) {

                server_response = http_request.responseText;
                    // case : if callback function specified, pass on the server response string to it as a parameter
                    if ( pCallbackFunc && typeof(pCallbackFunc) === "function" ) { 
                        pCallbackFunc(http_request.responseText);
            }
                } //status
                else {
                alert ( 'Error : Server returned a status code : ' + http_request.status );
                server_response = false;
            }
            } //ready state
        } //func
        }

    // GET method
    if ( http_method === "GET" ) {
        http_request.open ( "GET", pURL, request_type );
        http_request.send ( null );
    }

    // POST method
    else if ( http_method === "POST" ) {
        http_request.open ( "POST", pURL, request_type );
        http_request.setRequestHeader ( "Content-Type", "application/x-www-form-urlencoded" );
        //Some versions of Mozilla also require, the usage of these two headers
        //var numBytes = (""+pPostVars).length;
        //http_request.setRequestHeader ( "Content-Length: "+numBytes);
        //http_request.setRequestHeader ( "Connection: Close");
        http_request.send ( pPostVars );
    }

    //sync requests
    if ( ! request_type) { 
        server_response = http_request.responseText;

        if (pCallbackFunc && typeof(pCallbackFunc) === "function" ) {
            pCallbackFunc(http_request.responseText);
        }
    }

    return server_response;
}

/// To show and hide all table
/**
 * @startcomment
 * Purpose: To show and hide all table
 *
 * Input Params:
 *  1. pString      - String - pair of button id, related table id, related hidden variable id ( saperated by ~~ )
 *  2. pID          - String - id of group show and hide button
 *  3. pShowText    - String - Text that represent to show all containter
 *  4. pHideText    - String - Text that represent to hide all containter
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * @endcomment
 */
function OnClickShowHideAll (pString,pID, pShowText, pHideText)
{
    var arrIDBlock = [], arrID = []; //Init a Array
    var obj, objButton, objTable, objHidden, i;

    // case : if blank input, then return false
	if ( IsStringFieldEmpty ( pString ) 
         || IsStringFieldEmpty ( pID )
         || IsStringFieldEmpty ( pShowText )
         || IsStringFieldEmpty ( pHideText )) return false;

    var reg = new RegExp(pShowText,"i"); /*Search String*/

    arrIDBlock = pString.trim().split('~~');
    obj = document.getElementById(pID);

    if( obj.innerHTML.search(reg) >=0 )
    {
        obj.innerHTML = pHideText;

        for ( i=0; i < arrIDBlock.length ; i++)
        {
            arrID = arrIDBlock[i].trim().split('~');

            objButton = document.getElementById(arrID[0].trim());
            objTable = document.getElementById( arrID[1].trim() );

            objButton.innerHTML = '-';
            objTable.style.display='';

            if(arrID [2])
            {
                objHidden = document.getElementById( arrID[2].trim() );
                objHidden.value = '1';
            }
        }
    }
    else
    {
        obj.innerHTML = pShowText;

        for ( i=0; i < arrIDBlock.length ; i++)
        {
            arrID = arrIDBlock[i].trim().split('~');

            objButton = document.getElementById(arrID [0].trim());
            objTable = document.getElementById( arrID [1].trim() );

            objButton.innerHTML = '+';
            objTable.style.display='none';

            if(arrID [2])
            {
                objHidden = document.getElementById( arrID [2].trim() );
                objHidden.value = '0';
            }
        }
    }
}

/// To show and hide table
/**
 * @startcomment
 * Purpose: To show and hide table
 *
 * Input Params:
 *  1. pString      - String - button id, related table id, related hidden variable id ( saperated by ~ )
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * @endcomment
 */
function OnClickShowHide (pString)
{
    var arrID = [];
    var obj, objButton, objTable, objHidden;

    // case : if blank input, then return false
	if ( IsStringFieldEmpty ( pString ) ) return false;

    arrID = pString.trim().split('~');

    objButton = document.getElementById( arrID [0].trim());
    objTable = document.getElementById( arrID [1].trim());

    if( objButton.innerHTML === '+' )
    {
        objButton.innerHTML = '-';
        objTable.style.display = '';
        if(arrID [2]) document.getElementById( arrID [2].trim() ).value = 1;
    }
    else
    {
        objButton.innerHTML = '+';
        objTable.style.display='none';

        if(arrID [2]) document.getElementById( arrID [2].trim() ).value = 0;
    }
}

/// To show and hide all table on body loading
/**
 * @startcomment
 * Purpose: To show and hide table on body loading
 *
 * Input Params:
 *  1. pString      - String - pair of button id, related table id, related hidden variable id ( saperated by ~~ )
 *  2. pID          - String - id of group show and hide button
 *  3. pShowText    - String - Text that represent to show all containter
 *  4. pHideText    - String - Text that represent to hide all containter
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * @endcomment
 */
function OnBodyLoadShowHide (pString, pID, pShowText, pHideText )
{
    var arrIDBlock = [], arrID = [], //Init a Array
        obj, objButton, objTable, objHidden, 
        i, boolShow = 0;

    // case : if blank input, then return false
	if ( IsStringFieldEmpty ( pString ) 
         || IsStringFieldEmpty ( pID )
         || IsStringFieldEmpty ( pShowText )
         || IsStringFieldEmpty ( pHideText )) return false;

    obj = document.getElementById(pID);
    arrIDBlock = pString.trim().split('~~');
    
    for ( i=0; i < arrIDBlock.length ; i++)
    {
        arrID = arrIDBlock[i].trim().split('~');

        objButton = document.getElementById(arrID [0].trim());
        objTable = document.getElementById( arrID [1].trim() );
        objHidden = document.getElementById( arrID [2].trim() );
        
        if( objHidden.value == 1 )
        {
            objButton.innerHTML = '-';
            objTable.style.display='';
        }
        else
        {
            objButton.innerHTML = '+';
            objTable.style.display='none';
            boolShow = 1;
        }
    }

    obj.innerHTML = ( boolShow == 1 ) ? pShowText : pHideText;
}

/// toggle class name on mouse over and out event
/**
 * @startcomment
 * Purpose: toggle class name on mouse over and out event
 *
 * Input Params:
 *  1. pID          - String - id of html element
 *
 * Output Params:   none
 *
 * Return Value:    none
 *
 * @endcomment
 */
function ToggleIcon( pID )
{
    var re = new RegExp("MouseOver", "g");
    obj_image = document.getElementById(pID);
    obj_image.className = (re.test(obj_image.className)) ? obj_image.className.replace( re, "" ) : obj_image.className + "MouseOver";
}

/// to show counter for no. of characters in a textarea.
/**
 * @startcomment
 * Purpose:  to show counter for no. of characters in a textarea
 *
 * Input Params:
 *  1. pCountedTextAreaID - Str - ID of the textarea
 *  2. pCountBodyID       - Str - ID of the display div
 *  3. pMaxLen            - Int - maximum no of characters allowed
 *
 * Output Params: none
 * Return Value: none
 *
 * Notes:
 * @endcomment
 */
function DisplayRemainingCharCount(pCountedTextAreaID,pCountBodyID,pMaxLen)
{
    // set default value for maxlen
    var pMaxLen = (pMaxLen && pMaxLen > 0) ? pMaxLen : 255;

    // get the obj of textarea of which characters to be counted
    var txtAreaObj = document.getElementById(pCountedTextAreaID);

    // case : the length of the  value is greater than maxlen 
    if(txtAreaObj.value.length >= pMaxLen)
    {
        txtAreaObj.value = txtAreaObj.value.substring(0, pMaxLen);
    }
    
    // get the Counter Object
    var cntObj = document.getElementById(pCountBodyID);
    if(cntObj)
    {
		var rem = parseInt(pMaxLen, 10) - parseInt(txtAreaObj.value.length, 10);
        // set the value of the counter
        cntObj.innerText= isNaN(rem) ? 0 : rem;
    }
}


/// To add rows for advance details
/**
 * @startcomment
 * Purpose:         To add rows for advance details
 *
 * Input Params:
 *	1. id of the table in which one row is to be added
 * Output Params:   None
 * Return Value:    None
 *
 * Notes: The JSON string is of the form: [{element: html element, content: "html content"}...]
 *		Essentially, the json string is a
 * @endcomment
 */
function AddLine ( pTableId )
{
    //get the table object
    var table = document.getElementById( pTableId );

    //case : if not a table
    if (!table) return false;

    //section name abbriviation
    var sec_name = pTableId.substr( 3 );
    // number of data rows in the table
    var line_cnt_obj = document.getElementById( 'str'+sec_name+'LineCount' );
    //number of max data rows in the table
    var max_line_num_obj = document.getElementById( 'str'+sec_name+'MaxLineNum' );
    //template object to get the reference of the row to make
    var line_template_obj = document.getElementById( 'str'+sec_name+'LineTemplate' );
    //case: if any of the obj is not available
    if (!line_cnt_obj || !max_line_num_obj || !line_template_obj) return false;

    //case: if the template is empty
    if (line_template_obj.value.trim() == "" ) {
        return false;
    }

    //create the first row
    new_row = table.insertRow(table.rows.length);
    //get the new row id
    var new_id = parseInt(max_line_num_obj.value, 10) + 1;
    //get the template obj and replace their ids with the new one
    var temp_template = line_template_obj.value.replace(/strLineX/g,"strLine" + new_id);

	// evaluate the json template
    var cellContent = eval(temp_template);
    //new object to insert the columns
    var cellObj = null;
    //case: loop through the number of columns
    for (var idx = 0; idx < cellContent.length; idx++) {
        //create a new column with the json 'element'
        cellObj = document.createElement(cellContent[idx].element.trim());
        //put the 'content' of the json element into the innerHTML of the column
        cellObj.innerHTML = cellContent[idx].content;
        //append the child in the newly created row
        new_row.appendChild(cellObj);
        //alert(cellObj.innerHTML)
    }

    //put the new id in the maximum line number obj
    max_line_num_obj.value = new_id;

    //increment the line count
    line_cnt_obj.value = parseInt(line_cnt_obj.value, 10) + 1 ;

    //true
    return true;
}


/// To add rows for advance details
/**
 * @startcomment
 * Purpose:         To add rows for advance details
 *
 * Input Params:    1. id of the table in which one row is to be added
 *
 * Output Params:   None
 *
 * Return Value:    None
 * @endcomment
 */
function DeleteLine ( pTableId, pThisObj, pConfirmFlag )
{
    
    //get the table object
    var table = document.getElementById( pTableId );

    if (!table) return false;

	//section name abbr
    var sec_name = pTableId.substr( 3 );

	// number of data rows in the table
    var line_cnt_obj = document.getElementById( 'str'+sec_name+'LineCount' );

	//number of max data rows in the table
    var max_line_num_obj = document.getElementById( 'str'+sec_name+'MaxLineNum' );

    //case: confirmflag is on then ask confirmation
    if(pConfirmFlag 
       && (confirm("Are you sure you want to delete?") == false)) {
        return false;
    }
    
    //get the row which is clicked
    var rowObj = null,
        idx = 0;

	//case: search for the tr element
    while(idx <= 10) {

        if (pThisObj.parentNode && pThisObj.parentNode.nodeName == "TR") {
            rowObj = pThisObj.parentNode;
            break;
        }
        idx++;
        pThisObj = pThisObj.parentNode;
    }

    //case: if not found 
    if (!rowObj) return false;
    
    //get the row index
    var rowindex =  rowObj.rowIndex;

    //delete the row
    table.deleteRow( rowindex );

    //decrement the line count
    line_cnt_obj.value = parseInt(line_cnt_obj.value, 10) - 1 ;

    //true
    return true;
}

