﻿/*
	File Name: medAppz.js
	Date Created: April 12, 2004
	Created By: Naushad
	Description: All common JavaScript functions should be in this file
*/

    
	//var g_MEDAPPZ_ROOT = "http://localhost/medAppz2/";
	function DateIsValid(dateValue)
	{
		// Checks if the value passed is a valid date.
		
		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("/");
		
		month = tempDate[0];
		date = tempDate[1];
		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	
		}
		
		// Check if between sql date range or not
		if(CompareDate(dateValue, '01/01/1850', false) < 0){
		 	isValid = false;
		}
		
		return isValid;		
	}	
	//	Show Calendar dialog
	function ShowCalendar(oCalendarTextBox)
	{
		
		if ( oCalendarTextBox.value == "" )
		{
			
			var oDate = new Date();
			oCalDate=(oDate.getMonth()+1) +  '/'  + oDate.getDate()  + '/' + oDate.getFullYear();
			
		}else
		{
		// Check if not valid date then shoe todays date
	
		if(DateIsValid(oCalendarTextBox.value))
		{
		oDate = new Date(oCalendarTextBox.value);
		oCalDate= (oDate.getMonth()+1) +  '/'  + oDate.getDate()  + '/' + oDate.getFullYear();
		}
		else{
		
			var oDate = new Date();
			oCalDate=(oDate.getMonth()+1) +  '/'  + oDate.getDate()  + '/' + oDate.getFullYear();
			}
		
		}
		
		
		oCalendarTextBox.value = window.showModalDialog(sRootPath + 'Controls/Calendar.htm', oCalDate, 'dialogLeft:500px;dialogTop:500px;dialogHeight:219px;dialogWidth:265px;center:No;help:No;scroll:No;resizable:No;status:No;');
		oCalendarTextBox.select();
		oCalendarTextBox.focus();
	}

///////////////

	function Trim(input)
	{
		var lre = /^\s*/; 
		var rre = /\s*$/; 
		input = input.replace(lre, ""); 
		input = input.replace(rre, ""); 
		return input; 
	}
///////////////
function CompareDate(dateValue1, dateValue2, isCurrentDate)
{   	
	var isPastDate = -1;
	var isSameDate = 0;
	var isFutureDate = 1;							
	var month, day, year,toMonth, toDay, toYear
	
	startDate =  new Date(dateValue1);
	
	if(! isCurrentDate)
		endDate =  new Date(dateValue2);
	else
		endDate = new Date();	
	//alert("start date : " + startDate + " End date : " + endDate);
	daysDiff =  Math.floor((startDate.getTime() - endDate.getTime())/(1000*60*60*24));
	
	if(daysDiff > 0 )
		return isFutureDate;
	else if( daysDiff == 0)
		return isSameDate;
	else 
		return	isPastDate;
			
}

// Will also consider hh:mm am/pm passed
function CompareDateTime(dateValue1, dateValue2, isCurrentDate)
{   	
	var isPastDate = -1;
	var isSameDate = 0;
	var isFutureDate = 1;							
	var month, day, year,toMonth, toDay, toYear
	
	startDate =  new Date(dateValue1);
	
	if(! isCurrentDate)
		endDate =  new Date(dateValue2);
	else
		endDate = new Date();	
	//alert("start date : " + startDate + " End date : " + endDate);
	Diff =  Math.floor((startDate.getTime() - endDate.getTime()));
	
	
	if(Diff > 0 )
		return isFutureDate;
	else if( Diff == 0)
		return isSameDate;
	else 
		return	isPastDate;
			
}

// Fx to Show Modal Dialog for Date Calculation
// Returns: null (if user clicked cancel on dialog - OR - some error occurred)
// Otherwise: returns Calculated Date
//return value is determined by isDateReturnType
//if isDateReturnType == true , then return as number of days
//if isDateReturnType == false, return interval and duration as string
//isDateReturnType is defined as an optional parameter.
//if isDateReturnType is not passed as call time it will default to true and function will
//return number of days 
function CalculateDateByPopup(objBaseDate, dateLabel, left, top, isDateReturnType){

	var windowfeatures = "";
	var numAddInterval = -1;
	var objReturnDate = null;
	var returntype = null;	//whether (num of days) or (interval + duration as string)
	
	width = 500;
	height = 200;
		
	if (!(left > -1 && top > -1)) {
		left = 100;
		top = 100;
	}
	
	windowfeatures = "dialogLeft:" + left + "px;" + "dialogTop:" + top + "px;" 
	windowfeatures += "dialogHeight:" + height + "px;" + "dialogWidth:" + width + "px;status:no;help:no;";	

	//if return type is dateFormat, then return interval+duration in days
	//else return interval and duration as plain strings

	//determine if isDateReturnType is passed at call time
	if(typeof(isDateReturnType) == "undefined")
	{
		//not passed so used default value of  true
		isDateReturnType = true;	//set default value
	}
	
	//else use the  passed value
	
	//call the function with desired return type
	if(isDateReturnType)
	{
		//function should return as num of days
		returnType = "dateformat";
		
	}
	else
		//function should return as interval + duration as string
		returnType = "stringformat";	
	   
	
	//numAddInterval = window.showModalDialog(g_MEDAPPZ_ROOT + "Controls/DateCalculator.aspx?datelabel=" + dateLabel+ "&returntype=" + returnType, window, windowfeatures);
	numAddInterval = window.showModalDialog(sRootPath + "Controls/DateCalculator.aspx?datelabel=" + dateLabel+ "&returntype=" + returnType, window, windowfeatures);
	
	//alert("Interval to be added is " + numAddInterval);
	if(numAddInterval != -1 && numAddInterval != null)
	{
		if(isDateReturnType)
		{
			if(numAddInterval > -1){
				// Valid Interval
				objReturnDate = AddDaysToDate(objBaseDate, numAddInterval);
			}else{
				// Either User Cancelled -OR- some error
				objReturnDate = null;
			}
			//alert(objReturnDate);
			return(objReturnDate);
		}
		else
		{
			//alert("days is " + numAddInterval.split(' ')[2]);
			objReturnDate = AddDaysToDate(objBaseDate, numAddInterval.split(' ')[2]);
			//return as string
			//alert(numAddInterval.split(' ')[0]+ ' ' + numAddInterval.split(' ')[1] + ' ' + ((objReturnDate.getMonth()+1) + '/' + objReturnDate.getDate() + '/' + objReturnDate.getFullYear()));
			return numAddInterval.split(' ')[0]+ ' ' + numAddInterval.split(' ')[1] + ' ' +  ((objReturnDate.getMonth()+1) + '/' + objReturnDate.getDate() + '/' + objReturnDate.getFullYear());
		}
	}
	else
	{
		return '';
	}
}

// Adds given number of days to a date object and return a new date object
function AddDaysToDate(objBaseDate, numDaysToAdd){
	//alert("base date is : " + objBaseDate + " and days to add : " + numDaysToAdd);
	var objReturnDate = new Date(objBaseDate);
	//alert("base date . getdate : " + objBaseDate.getDate());
	objReturnDate.setDate(objReturnDate.getDate() + parseInt(numDaysToAdd));	
	//alert(objReturnDate);
	return(objReturnDate);
}

//Loops through all the elements in the form and clears there value based on
//control type.
//INPUT : name of form which is to be cleared
//To provide some default value for reset, Declare custom attribute
//medappzDefaultValue.//
//SAMPLE :<input type="text" id="txt_One" medappzDefaultValue="default value">
function ClearFormEntries(frmName)
{   	
	var frmObj;		//frm object
	
	if((frmName != undefined) && (frmName != null) && (frmName != ''))
	{
		frmObj = document.forms[frmName];
	}
	else
	{
		frmObj = document.froms[0];
	}
	
	//Loop all childs on form and reset based on type
	for(i=0; i<frmObj.elements.length ; i++)
	{   
		var defaultValue;						//default value to set
		var isDefaultValue = false;				//true if default value is to be set
				
		control  = frmObj.elements[i];
		
		if((control == undefined ) ||(control == null))
		{
			continue;
		}
		
		var controlType = frmObj.elements[i].type ;				
		
		
		if((controlType == undefined) ||(controlType == null) || (controlType == ''))
		{   			
			continue;
		}	
		
		controlType = controlType.toLowerCase();
		
		//if default value is to be set
		x = control.getAttribute("medappzDefaultValue");
		
		if((x != undefined) && (x != null) && (x != '')) 
		{
			defaultValue = x;
			isDefaultValue = true;
		}			
		
		
		//TEXT BOX control
		if(controlType == 'text')
		{                          			
			if(isDefaultValue)
			{
				control.value = defaultValue;				
			}
			else
			{
				control.value = '';				
			}
		}
		
		//TEXT BOX control
		if(controlType == 'textarea')
		{                          			
			if(isDefaultValue)
			{
				control.value = defaultValue;				
			}
			else
			{
				control.value = '';				
			}
		}		
		
		//CHECK BOX control
		if(controlType == 'checkbox')
		{
			if(isDefaultValue)
			{
				if(defaultValue == 'checked')
				{
					control.checked = true;				
				}
			}
			else
			{
				control.checked = false;
			}
		}
				
		//SELECT control
		if(controlType == 'select-one')
		{   
			
			if(isDefaultValue)
			{
				control.selectedIndex = defaultValue;				
			}
			else
			{
				control.selectedIndex = 0;				
			}
		}
		
		if(controlType == 'hidden')
		{
			//ignore __VIEWSTATE __EVENTTARGET and __EVENTAGRUMENT 
			if( (control.name.toUpperCase() == '__VIEWSTATE') || (control.name.toUpperCase() == '__EVENTTARGET') ||
				(control.name.toUpperCase() == '__EVENTARGUMENT')
			 )
			 {
				continue;
			 }
			 
			 //COMBOCONTRL
			 if(control.name.indexOf('cmbSimple') != -1)
			 {
				//generate combo id
				//comboID = control.name.substring(0,control.name.indexOf(":")) + "_" + control.name.substring(control.name.indexOf(":")+1 );				
				//alert(control.name);
				comboID = control.name.replace(/:/g,'_');
				//alert(comboID);
				comboObj = document.getElementById(comboID);
				
				
				if(isDefaultValue)
				{
					comboObj.selectedIndex = defaultValue;				
				}
				else
				{
					comboObj.selectedIndex = 0;
				}				
			 }
			 else
			 {
				if(isDefaultValue)
				{
					control.value = defaultValue;				
				}
				else
				{
					control.value = "";
				}
			}
		}
		
		//Hide all error images 
		HideErrorImages();
		
		
	}
	
}

//Hides all error images on form with name='ErrorImage'
function HideErrorImages()
{
	imgArray = new Array();
	imgArray = document.getElementsByName('ErrorImage');
	
	for(imgCount = 0;imgCount<imgArray.length;imgCount++)
	{
		imgArray[imgCount].style.display = 'none';		
	}
}

function GetXmlHttpObject(handler)
{ 
    //alert('kanishk comes in GetXmlHttpObject function')
	objXMLHttp=null
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	if(objXMLHttp != null)
	{
	    //alert('kanishk has created xmlhttp object')
	}
	return objXMLHttp
}

function gotoPageWithMessage(strMessage,strLocation)
{
    if(strMessage != '')
    {
        window.alert(strMessage);
    }
    if(strLocation != '')
    {
        window.location = strLocation;
    }
}

function validateFilePath(fileName)
{
    var IsValid = true;
    var regEx;
    
    //var validExcelFileRegExStr = /^([a-zA-Z]\:|\\)\\([^\\]+\\)*[^\/:*?"<>|]+\.xls(l)?$/;
    var splCharsFilePathRegExStr = /([,!@#$%^&*()\[\]]+|\\\.\.|\\\\\.|\.\.\\\|\.\\\|\.\.\/|\.\/|\/\.\.|\/\.|;|(<![a-zA-Z]):)/gi;
    //var validFilePathRegExStr = /^([a-zA-Z]\:|\\\\[^\/\\:*?"<>|]+\\[^\/\\:*?"<>|]+)(\\[^\/\\:*?"<>|]+)+(\.[^\/\\:*?"<>|]+)$/; 
    
    if (fileName != "")
    {
        regEx = new RegExp(splCharsFilePathRegExStr);
        fileName = fileName.replace(/\\/g,"-");
        if(regEx.test(fileName.toLowerCase()))
            IsValid = false;
        
//        regEx = new RegExp(validFilePathRegExStr);
//        if(!regEx.test(val.toLowerCase()))
//            IsValid = false;

//        regEx = new RegExp(validExcelFileRegExStr);
//        if(!regEx.test(val.toLowerCase()))
//            IsValid = false;

        
    }   

    return IsValid;
}

// For Login JS
var strPrefix = "ctl00_";
function btnLoginClick() 
{
    if(validatePage() == true)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function validatePage() 
{
    var txtUserName = document.getElementById(strPrefix + 'txtUserName');
    var txtPassword = document.getElementById(strPrefix + 'txtPassword');
        
    if(checkTextBoxEmpty(txtUserName,"User Name") == true)
    {
        if(checkTextBoxEmpty(txtPassword,"Password") == true)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

function controlEnter (event)
 {      
     var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;      
     if (keyCode == 13)
     {                  
       var btnLogin = document.getElementById(strPrefix + 'btnLogin');
        btnLogin.click();              
     }      
 }

// Login JS End
