﻿
// JScript File


var isValid = true;

// function to check whether a value is empty or not.
// if empty then returns true else false.
function isEmpty(strValue)
{
    if(strValue != '')
    {
        return false;
    }
    else
    {
        return true;
    }
}

// function to show a given alert message and then
// set the focus on a given control
function alertAndFocus(strMessage,objElement)
{
    alert(strMessage);
    objElement.focus();
}

// Function to check whether a textbox is empty or not
// If empty, then it returns false else returns true
// after giving a proper alert message.
function checkTextBoxEmpty(objElement,strFieldName)
{
    if(objElement.value != null || objElement.value != undefined)
    {
        strValue = objElement.value;
        if(isEmpty(strValue) == true)
        {
            var strMessage = strFieldName + ' can\'t be empty';
            alertAndFocus(strMessage,objElement);   
            return false;
        }
        else
        {
            return true;
        }
    }
}

function checkAllTextBoxEmpty(arrTextControls,arrFieldNames)
{
    var retValue = true;
    for(i=0; i < arrTextControls.length; i++)
    {
        if(checkTextBoxEmpty(arrTextControls[i],arrFieldNames[i]) == false)
        {
            retValue = false;
            break;
        }
    }
    return retValue;
}



function persistData()
{
    var txtLogo = document.getElementById('fuLogo');
    var hidLogo = document.getElementById('hidLogo');
    hidLogo.value = txtLogo.value;
}

function genericValidator(arrObjects)
{
//    alert(arrObjects.length);
    for(i=0; i < arrObjects.length ; i++)
    {
        isValid = true;
        var strControlId = arrObjects[i][0];
        var objControlId = document.getElementById(strControlId);
        var strControlType = arrObjects[i][1].toLowerCase();
        var strFieldName = (arrObjects[i][2] != undefined ? arrObjects[i][2]: '');
        var strDataType = (arrObjects[i][3] != undefined ? arrObjects[i][3].toLowerCase() : '');
        var bIsRequired = (arrObjects[i][4] != undefined ? arrObjects[i][4] : 0);
        var iComparisonTypeId = (arrObjects[i][5] != undefined ? arrObjects[i][5] : 0);
        var objMinValue = (arrObjects[i][6] != undefined ? arrObjects[i][6] : -32767);
        var objMaxValue = (arrObjects[i][7] != undefined ? arrObjects[i][7] : 32767);
        //alert('Kanishk reaches validation function and control type is '+ strControlType);
        //alert('Kanishk reaches till data type and data type is ' + strDataType);
        switch (strControlType)
        {
            case 'textbox':
	            switch (strDataType)
	            {
	            
	                case 'int':
			            if(RemoveCharsNoDecimal(objControlId) == true)
			            { 
			                // Remove leading zeros!!!
//                            alert("The selected value is : " + objControlId.value);
			                
			                if(objControlId.value != "") 
			                {
				                switch(iComparisonTypeId)
		                        {
			                        case 1 : 
				                        // Equality validation
				                        isValid = IsEqual(parseInt(objControlId.value), objMinValue);
				                        ValidationError = "Please enter the correct value for " 
									                        + strFieldName + ". \n";
				                        break;

			                        case 2 :
				                        // Less than validation
				                        isValid = IsLessThan(parseInt(objControlId.value), objMinValue);
				                        ValidationError = strFieldName + " should be less than " 
									                        + objMinValue + ". \n";
				                        break;

			                        case 3 :
				                        // Greater than validation
				                        isValid = IsGreaterThan(parseInt(objControlId.value), objMinValue);
				                        ValidationError = strFieldName + " should be greater than " 
								                        + objMinValue + ". \n";
				                        break;

			                        case 4 :
				                        // Range validation
				                        isValid = IsValidateRange(parseInt(objControlId.value), objMinValue, objMaxValue);
				                        ValidationError = strFieldName + " not within the correct range (" 
									                        + objMinValue + ", " + objMaxValue + "). \n";
				                        break;
		                        }
			                    if(!(isValid))
			                    {
				                    // If isValid = False, ie. value doesn't satisfy the applied criteria
				                    sErrorMsg = DisplayError(ValidationError);
				                    objControlId.focus();
				                    return false;
				                }
			                }
			                else if(bIsRequired == true)
			                {
			                    sErrorMsg = DisplayError(strFieldName + " is a required field. It can't be blank");
				                objControlId.focus();
				                return false;
			                }
			            }
			            else
			            {
			                sErrorMsg = DisplayError(strFieldName + " has some invalid characters in it.");
			                objControlId.focus();
			                return false;
			            }
			            break;
        			
                    
		            case 'double':
				            if(RemoveCharsAllowDecimal(objControlId) == true)
				            {
				                if(objControlId.value != "") 
				                {
					                switch(iComparisonTypeId)
					                {
						                case 1 : 
									                // Equality validation
									                isValid = IsEqual(parseFloat(objControlId.value), objMinValue);
									                ValidationError = "Please enter the correct value for " 
														                + strFieldName + ". \n";
									                break;

						                case 2 :
									                // Less than validation
									                isValid = IsLessThan(parseFloat(objControlId.value), objMinValue);
									                ValidationError = sControlDescription + " should be less than " 
														                + strFieldName + ". \n";
									                break;

						                case 3 :
									                // Greater than validation
									                isValid = IsGreaterThan(parseFloat(objControlId.value), objMinValue);
									                ValidationError = strFieldName + " should be greater than " 
														                + objMinValue + ". \n";
									                break;

						                case 4 :
									                // Range validation
									                isValid = IsValidateRange(parseFloat(objControlId.value), objMinValue, objMaxValue);
									                ValidationError = strFieldName + " not within the correct range (" 
														                + objMinValue + ", " + objMaxValue + "). \n";
									                break;
					                }
					                if(!(isValid))
					                {
						                // If length not in range
						                sErrorMsg = DisplayError(ValidationError);
						                objControlId.focus();
						                return false;
						            }
				                }
				                else if(bIsRequired == true)
				                {
				                    sErrorMsg = DisplayError(strFieldName + " is a required field. It can't be blank");
					                objControlId.focus();
					                return false;
				                }
				            }
				            else
				            {
				                sErrorMsg = DisplayError(strFieldName + " has some invalid characters in it.");
			                    objControlId.focus();
			                    return false;
				            }
				            break;
                      
		            case 'string':
		                    //alert('Kanishk reaches till string type');
				            objControlId.value = Trim(objControlId.value);
//				            alert('Kanishk has got the value and its ' + objControlId.value);
				            if(objControlId.value != "")
				            {
					            //If there is data then length validate.
					            isValid = IsValidateLength(objControlId, objMinValue, objMaxValue);
					            if(!(isValid))
					            {
					                //alert('Its not a valid length');
						            // If length not in range
						            sErrorMsg = DisplayError("The number of characters in " + strFieldName 
									            + " should be between " + objMinValue + " and " + objMaxValue + " . \n");
						            objControlId.focus();
						            return false;
						        }
				            }
				            else if(bIsRequired == true)
				            {
				                sErrorMsg = DisplayError(strFieldName + " is a required field. It can't be blank");
					            objControlId.focus();
					            return false;
				            }
				            break;
                    
		            case 'date':
		                    //alert('Kanishk reaches date type validation and comparison type is '+ iComparisonTypeId);
				            objControlId.value = Trim(objControlId.value);
//                            alert("The selected value is : " + objControlId.value);				            
				            if(objControlId.value != "")
				            {
					            isValid = ValidateDate(objControlId.value);
					            if(!(isValid))
					            {
						            // If length not in range
						            sErrorMsg = DisplayError(strFieldName + " is invalid. Format is (mm/dd/yyyy). \n");
						            return false;
					            }
					            else
					            {
					                switch(iComparisonTypeId)
						            {
							            case 1 : 
										            // Equality validation
										            isValid = IsDateEqual(objControlId.value, objMinValue);
										            ValidationError = "Please enter the correct value for " 
											            + strFieldName + ". \n";
										            break;

							            case 2 :
										            // Less than validation
										            isValid = IsDateLess(objControlId.value, objMinValue);
										            ValidationError = strFieldName 
											            + " should be less than " + objMinValue + ". \n";
										            break;

							            case 3 :
										            // Greater than validation
										            //alert('Greater than validation reached');
										            isValid = IsDateGreater(objControlId.value, objMinValue);
										            ValidationError = strFieldName 
											            + " should be greater than " + objMinValue + ". \n";
										            break;

							            case 4 :
										            // Range validation
										            isValid = IsValidateDateRange(ControlId.value, objMinLength, objMaxLength);
										            ValidationError = strFieldName 
											            + " not within the correct range (" + objMinValue + ", " + objMaxValue + "). \n";
										            break;
						            }
						            if(!(isValid))
						            {
							            // If isValid = False, ie. value doesn't satisfy the applied criteria
							            sErrorMsg = DisplayError(ValidationError);
							            return false;
						            }
					            }
				            }
				            else if(bIsRequired == true)
				            {
				                sErrorMsg = DisplayError(strFieldName + " is a required field. It can't be blank");
					            objControlId.focus();
					            return false;
				            }
				            break;
				            
		                case 'time':
		                    //alert('Kanishk reaches date type validation and comparison type is '+ iComparisonTypeId);
				            objControlId.value = Trim(objControlId.value);
				            if(objControlId.value != "")
				            {
					            isValid = IsValidTime(objControlId.value);
					            if(!(isValid))
					            {
						            // If length not in range
						            sErrorMsg = DisplayError(strFieldName + " is invalid. Format is (HH am | HH pm | HH:MM am | HH:MM pm) in 12 hr format. \n");
						            return false;
					            }
					            
				            }
				            else if(bIsRequired == true)
				            {
				                sErrorMsg = DisplayError(strFieldName + " is a required field. It can't be blank");
					            objControlId.focus();
					            return false;
				            }
				            break;
        				
                }	// End of switch (sDataType)
                break;

            case 'dropdown':
                    case 'Int':
//                        alert("The dropdown selected value is : " + objControlId.value);
			            if(objControlId.value != "" && objControlId.value != "-1") 
			            {			            
				            switch(iComparisonTypeId)
		                    {
			                    case 1 : 
				                    // Equality validation
				                    isValid = IsEqual(parseInt(objControlId.value), objMinValue);
				                    ValidationError = "Please enter the correct value for " 
									                    + strFieldName + ". \n";
				                    break;

			                    case 2 :
				                    // Less than validation
				                    isValid = IsLessThan(parseInt(objControlId.value), objMinValue);
				                    ValidationError = strFieldName + " should be less than " 
									                    + objMinValue + ". \n";
				                    break;

			                    case 3 :
				                    // Greater than validation
				                    isValid = IsGreaterThan(parseInt(objControlId.value), objMinValue);
				                     if(objMinValue == "-1" || objMinValue == "")
				                    {
				                        ValidationError = strFieldName + " is a required field.\n";
				                    }
				                    else
				                    {
				                        ValidationError = strFieldName + " should be greater than " 
								                    + objMinValue + ". \n";
								    }
				                    break;

			                    case 4 :
				                    // Range validation
				                    isValid = IsValidateRange(parseInt(objControlId.value), objMinValue, objMaxValue);
				                    ValidationError = strFieldName + " not within the correct range (" 
									                    + objMinValue + ", " + objMaxValue + "). \n";
				                    break;
		                    }
			                if(!(isValid))
			                {
				                // If isValid = False, ie. value doesn't satisfy the applied criteria			            
				                sErrorMsg = DisplayError(ValidationError);
				                objControlId.focus();
				                return false;
				            }
			            }
			            else if(bIsRequired == true)
			            {	
			                sErrorMsg = DisplayError(strFieldName + " is a required field. It can't be blank");
				            objControlId.focus();
				            return false;
			            }
			            break;
	        case 'datesplitter':    
                if(validateDateSplitter(strControlId,bIsRequired) == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
                break
                
            case 'fileupload':
                var strFileName = objControlId.value;
                if(bIsRequired == 1 && strFileName == "")
                {
                    sErrorMsg = DisplayError(strFieldName + " is a required field. It can't be blank");
		            objControlId.focus();
		            return false;		            
                }
                else //if(bIsRequired == 0 && strFileName == "")
                {
                    return true;
                }
                if(validateFilePath(strFileName) == true)
                {
                    if(strDataType != '')
                    {
                        var strFileExtn = strFileName.split(".")[1];
                        //var arrFileTypes = strDataType.split("-");
                        var regRepStr = new RegExp("-","g");
                        var strFileTypes = strDataType.replace(regRepStr,",");
                        var regFileTypes = new RegExp(strFileExtn,"i");
                        var isValid = strDataType.match(regFileTypes);
                        if (isValid == null)
                        {
                            sErrorMsg = DisplayError(strFieldName + " can only have " + strFileTypes + " file type(s).");
                            objControlId.focus();
		                    return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                    return true;
                }
                else
                {
                    alert('File name should not include special characters.');
                    objControlId.focus();   
                    return false; 
                }
	            break;
                
            case 'checkbox':

	            break;

            case 'radio':

	            break;

            case 'listBox':

	            break;
        						
        }	// End of switch(sControlTypeId)
    }       
    return true;
}

function DisplayError(ErrorString)
{
	// Responsible for either generating the error in one single string, or displaying individually
	// Creator: Aditya Mahajan
    //alert('Error message is ' + ErrorString + ' and global setting is ' + g_ShowIndividualError);
	if(g_ShowIndividualError == true)
	{	// If we have to show individual error window
		ShowMsg(ErrorString);
	}
	else
	{	// string containing all error messages.
		g_ErrMsg += ErrorString;
	}
	return(ErrorString);
}

//		/////////////////////////

function ShowMsg(msgs)
{
	// For displaying messages to the user.
	// Called by any code whenever a message needs to be displayed.
	// Creator: Aditya Mahajan
	
	alert(msgs);

}

function IsValidateLength(ControlId, iMinNumChar, iMaxNumChar)
{
	// Checks if the string length is within allowed limits.
	// calls ShowMsg() to display error message.
	// if the string length exceeds the permissible range, IsValidateLength() truncates the string.
	// Creator: Aditya Mahajan

	var iLength = ControlId.value.length
	//alert('Min length is ' + iMinNumChar + ' max length is ' + iMaxNumChar + ' and string length got is ' + iLength);
	if(iMinNumChar <= iLength && iLength <= iMaxNumChar)
	{
		return true;	//Within range
	}
	else
	{
		//if(iLength > iMaxNumChar)
		//{
		//	ControlId.value=ControlId.value.substr(0,iMaxNumChar);
		// ShowMsg("The maximum number of characters allowed are " + iMaxNumChar + "! \n" + "Input string has been truncated.");				
		//}
		return false;	//Outside of range
	}
}

		/////////////////////////

	function IsValidateFloatLength(ControlId, iMinNumCharPreDec, iMaxNumCharPreDec, iMinNumCharPostDec, iMaxNumCharPostDec)
	{
		// Checks if the float quantity length is within allowed limits.
		// checks for both parts of a float quantity, the portion before decimal & after the decimal.
		// returns true if the length is within the specified limits, else returns false.
		// Creator: Aditya Mahajan
		
		var iDecimalPosition, iPreDecimal, iPostDecimal;
		var bLengthFlag = true;
		
		var iLength = ControlId.value.length;
		iPostDecimal = -1;
		iDecimalPosition = ControlId.value.indexOf(".");
		
		if(iDecimalPosition == -1)
		{
			// When no decimal point exists, the whole string is the iPreDecimal.
			iPreDecimal = iLength;
		}
		else
		{
			// When decimal point exists
			iPreDecimal = iDecimalPosition;
			iPostDecimal = iLength - iDecimalPosition - 1;
		}
		
		if(!(iPreDecimal >= iMinNumCharPreDec && iPreDecimal <= iMaxNumCharPreDec))
		{	// if PreDecimal out of range
			bLengthFlag = false;
		}
		if(iPostDecimal != -1)
		{
			if(!(iPostDecimal >= iMinNumCharPostDec && iPostDecimal <= iMaxNumCharPostDec))
			{	// if PostDecimal out of range
				bLengthFlag = false;
			}		
		}

		
		if(bLengthFlag)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

		/////////////////////////

	function ValidateDate(dateValue)
	{
		// Checks if the value passed is a valid date.
		// dateValue: Value to validate
		// Source: MedAppz Old
		
		var dateRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;	// validate string for date format		
		var isValid = dateRegExp.test(dateValue);		
		
		if(!isValid)
			return isValid;
		
		tempDate =  dateValue.split("/");
		
		date = tempDate[1];
		month = tempDate[0];
		year = tempDate[2];
		
		var numDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		days = numDays[month - 1]; //get valid number of days in the month
		
		if((month < 1) ||(month > 12))
			isValid = false;
		else
		{ 
			if((((year%4 == 0) && (year %100 != 0 ))|| (year % 400 == 0)) && month == 2)
				//if Leap year and month is FEB
				days = days + 1 ;  //add 1 day
			
			//Check if valid days
			if( (date > days) || (date < 1))
				isValid = false;	
			else
				isValid = true;			//both month and dates are valid date	
		}
		return isValid;		
	}

		/////////////////////////

	function IsValidateDateRange(DateValue, DateMin, DateMax)
	{
		// Checks if the DateValue lies between the Min & Max date specified.
		// returns true if DateValue lies within the range otherwise returns false.
		// Creator: Aditya Mahajan

		var DaysDiff;
		//Date1 =  new Date(DateValue);
		//Date2 =  new Date(DateMin);
		//Date3 =  new Date(DateMax);
        Date1 = convertDateToStandard(DateValue);
        Date2 = convertDateToStandard(DateMin);
        Date3 = convertDateToStandard(DateMax); 
		DaysDiff1 =  Math.floor((Date1.getTime() - Date2.getTime())/(1000*60*60*24));
		DaysDiff2 =  Math.floor((Date3.getTime() - Date1.getTime())/(1000*60*60*24));
		
		// If DateMin < DateValue < DateMax 
		if(DaysDiff1 > 0 && DaysDiff2 > 0)
			return true;
		else
			return false;
	}

		/////////////////////////

	function FieldValidate(ObjControl, ObjCollection)
	{
		g_ErrMsg = "";
		DoFieldValidation(ObjControl, ObjCollection);
		if(g_ShowIndividualError == false && g_ErrMsg != "")
		{
			// Some error has occured
			ShowMsg(g_ErrMsg);
			//document.getElementById(ObjControl.id).focus();
			return false;
		}
			return true;
	}

		/////////////////////////

	function IsValidateRange(ObjValue,ValueMin,ValueMax)
	{
		// Checks whether the ObjValue is within the specified range
		// Aditya
		if (ObjValue >= ValueMin && ObjValue <= ValueMax)
		{
			return true;	//Within range
		}
		else
		{
			return false;	//Outside of range
		}
	}
    
    // Method to check the validity of time entered by the user
    function IsValidTime(valueTime)
    {
        // alert(valueTime);
//        var _reg = new RegExp(/^(([1-9]|[01]?[0-2]))\ *(:\ *[0-5][0-9])?\ *(a|p)m$/);
        var _reg = new RegExp(/^([1-9]|1[0-2])\ *(:\ *[0-5][0-9])?\ *(a|p)m$/);
        return _reg.test(valueTime);
    }

