//************************************************************************************************************
//***************************DATE/CALENDAR FUNCTIONS**********************************************************
//**** This is a block of functions that launch, build, and manipulate the
//**** calendar lookup and related date fields
//**** This file contains all functions for manipulating dates
//************************************************************************************************************
//************************************************************************************************************

//==================================================================================================
//== Define and Set Global variables
//==================================================================================================
var gByMonthFixedDay=0;
var gByMonthLatestDay=0;
var gCalSplitDate= new Array()		// used by PopupCalendar
var gCalFieldRef					// used by PopupCalendar
//==================================================================================================
//== displayCalendarOnKey
//==
//== Displays calendar when user hits F9 or Ctrl-up/down arrow
//==================================================================================================
function displayCalendarOnKey(pObject,evt)
{
	if (document.all){KeyEvent = window.event;}
	else{KeyEvent = evt;}
	var vShow = false;
	if (pObject.onblur){var bp=pObject.onblur.toString()}
	if(KeyEvent.keyCode==120){vShow=true;}// f9
	if((KeyEvent.altKey==true)&&(KeyEvent.keyCode==40)){vShow=true;}//Alt+Arrow Down
	if(KeyEvent.keyCode==32){
		now = new Date();
		if (pObject.value == " "){
			if(bp && bp.indexOf("isDateTime") > -1){
				pObject.value=now.getMonth()+1 + '/' + now.getDate() + '/' + now.getFullYear() + ' ' + now.getHours() + ':' + now.getMinutes();	
			}
			else{
				pObject.value=now.getMonth()+1 + '/' + now.getDate() + '/' + now.getFullYear();	
			}
		}
	}
	if (vShow){
		for(i=0;i<pObject.parentNode.childNodes.length;i++){
			if(pObject.parentNode.childNodes.item(i).id){
				var lookupid=pObject.parentNode.childNodes.item(i);
			}
		}
		displayCalendar(lookupid);
	}
	KeyEvent.returnValue=false;
}
//==================================================================================================
//== hideCalendar
//==	Hides calendar when user clicks anywhere on the page
//==================================================================================================
function hideCalendar()
{
	if(document.getElementById("iframeCalendar")){
	document.getElementById("iframeCalendar").style.display="none";}
	SelectRedisplayer();
}
//==================================================================================================
//== displayCalendar
//==	displays calendar in iframe
//==	The object passed in is always the image object
//==================================================================================================
function displayCalendar(pObject,ralph)
{
	if (document.all){
	var vDivX=window.event.x
	var vDivY=window.event.y
	}
	else{
	var vDivX=pObject.x
	var vDivY=pObject.y
	}
	var vDivWidth = 140		// 7=borders
	var vDivHeight = 150	// 27=borders+buttons
	var vDivMargin = 0		// extra space for dropshadow and frame and buttons

	var vCalendar=document.getElementById("iframeCalendar")

	//----------------------------------------------------------
	// store the parent element fieldid and value
	// into variables on the window so the calender
	// htc can handle setting of initial and selected values
	//----------------------------------------------------------
	var fieldid=pObject.previousSibling.previousSibling.name;
	gCalFieldRef=document.getElementById(fieldid);

	var vCurrentValue = document.getElementById(fieldid).value
	if (vCurrentValue == "")
	{
		var vToday		= new Date()
		gCalSplitDate.year	= vToday.getFullYear();
		gCalSplitDate.month= vToday.getMonth() + 1;
		gCalSplitDate.day	= vToday.getDate();
	}
	else
	{
		//gCalSplitDate = splitYearMonthDay(vCurrentValue)
		//if (!isValidDate(gCalSplitDate)) return	// don't open window
	}
	//----------------------------------------------------------
	// Launch the popup
	//----------------------------------------------------------
	vCalendar.scrolling = "no";
	if(ralph && ralph!=''){
	vCalendar.src = "includes/calendar.cfm?&caller="+fieldid+"&cdate="+vCurrentValue+"&time="+ralph;
		}
	else{
	vCalendar.src = "includes/calendar.cfm?&caller="+fieldid+"&cdate="+vCurrentValue+"&time=no";
	}
	//----------------------------------------------------------
	// Position and Display the calendar
	//----------------------------------------------------------
	vCalendar.style.position = "absolute"
	vCalendar.style.display	= "block";
	vCalendar.style.top = vDivY;
	vCalendar.style.left = vDivX;
	vCalendar.style.width = vDivWidth;
	vCalendar.style.height = vDivHeight;
	vCalendar.style.border = "0px solid black";

	if(document.all){
		setElementPosition(vCalendar.id, fieldid, 0, 0 , 'left', 'bottom', 'left', 'down')
		//vCalendar.focus();
		SelectHider('iframeCalendar');
	}
	else{
		vCalendar.style.top = vDivY;
		vCalendar.style.left = vDivX;
	}
}
//==================================================================================================
//==ReturnDate()
//==
//==  Returns the date passed from the calendar to the calling form
//==  
//==================================================================================================
function ReturnDate(iMonth, iDay, iYear, iField, iTime){
	if (iTime=='no'){
	document.getElementById(iField).value=iMonth + "/" + iDay + "/" + iYear;
	}
	else{
	clearFieldErrors();
	if (iTime=='time'){var iTime = '13:00'}
	document.getElementById(iField).value=iMonth + "/" + iDay + "/" + iYear + " "+iTime;
	}
	hideCalendar();	
	document.getElementById(iField).focus();
	document.getElementById(iField).blur();
}
//==================================================================================================
//== getElementPosition
//==
//==	retrieves an array of x,y coordinates for any element
//==	pElement is string id or a reference to the element object for which to locate
//==================================================================================================
function getElementPosition(pElement)
{
	var vSearch = 1; //SMR-  loop condition
	if(typeof(pElement) == "object")
	{
		var vObjToCheck = pElement;
	}
	else
	{
		var vObjToCheck = document.getElementById(pElement);
	}
	var vTagName = vObjToCheck.tagName;
	var vLeft = 0// x - coordinate
	var vTop = 0// y - coordinate
	//-------------------------------------------------------
	// Loop through parent elements looking calculating
	// total offset.
	//-------------------------------------------------------
	do
	{
		if (vTagName != "") //SMR- This should never happen
		{
			//-------------------------------------------------------
			//  body is the last item to check, stop after calculating it
			//-------------------------------------------------------
			if(vTagName.toLowerCase( ) != "body")
			{
				vLeft = vLeft + vObjToCheck.offsetLeft;
				vTop = vTop + vObjToCheck.offsetTop;
				if(vTagName.toLowerCase( ) == "table" && vObjToCheck.border != 0)
				{
					//-------------------------------------------------------
					// for some reason, tables loose 1px if they have a border defined
					//-------------------------------------------------------
					vLeft = vLeft + 1;
					vTop = vTop + 1;
				}

				vObjToCheck = vObjToCheck.offsetParent;  //SMR- next parent
				vTagName = vObjToCheck.tagName;			 //SMR- next parent's tag

			}
			else
			{
				vSearch = 0; //SMR- body tag has been processed, end loop
			}
		}
		else
		{
			vSearch = 0; //SMR- something is wrong, end loop and return 0,0 relative to client area
		}
	}
	while (vSearch == 1);

	//-------------------------------------------------------
	// return array of coordinates[x,y]
	//-------------------------------------------------------
	var rvCoordinates = new Array(vLeft,vTop);

	return rvCoordinates;
}

//==================================================================================================
//== setElementPosition
//==
//==	sets the position of an element relative to another
//==	pElementToMove is string id or reference to the element object to be moved
//==    pElementToMoveTo is string id or reference to the element object to move in relation to
//==
//==	phAlign is:		left (def),		center,			right
//==	pVAlign is:		top,			middle,			bottom (default)
//==	pHDraw  is:		left (def),		right
//==	pVDraw	is:		up,				down (default)
//==
//==	pHDraw is from the alignment point,
//==			left --draw the left edge of object and draw towards the right
//==			right--draw the right edge of the object and draw towards the left
//==	pVDraw is from the alignment point,
//==			up  --draw the botoom edige of the object and paint upwards
//==			down--draw the top edge of the object and paint downwards
//==================================================================================================
function setElementPosition(pElementToMove, pElementToMoveTo, pXPad, pYPad, pHAlign, pVAlign, pHDraw, pVDraw)
{
	var vXPad;
	var vYPad;
	var vPos = getElementPosition(pElementToMoveTo); //SMR - get position of destination
	if(typeof(pElementToMove) == "object")
	{
		var vSourceElement = pElementToMove;
	}
	else
	{
		var vSourceElement = document.getElementById(pElementToMove);
	}
	if(typeof(pElementToMoveTo) == "object")
	{
		var vTargetElement = pElementToMoveTo;
	}
	else
	{
		var vTargetElement = document.getElementById(pElementToMoveTo);
	}
	var vPosLeft = vPos[0];
	var vPosTop = vPos[1];
	var vTargetWidth = vTargetElement.offsetWidth;
	var vTargetHeight = vTargetElement.offsetHeight;
	var vSourceWidth = vSourceElement.offsetWidth;
	var vSourceHeight = vSourceElement.offsetHeight;
	var vPageBottom = document.body.scrollHeight;
	var vPageEdge = document.body.scrollWidth;
	var vScreenBottom = document.body.scrollTop + document.body.clientHeight;
	var vScreenEdge = document.body.scrollLeft + document.body.clientWidth;

	vXPad = (pXPad) ? pXPad : 0;
	vYPad = (pYPad) ? pYPad : 0;

	switch (pHAlign)
	{
		case "left" :
			break;
		case "center" :
			vPosLeft += vTargetWidth / 2;
			break;
		case "right" :
			vPosLeft += vTargetWidth;
			break;
		default :
			pHAlign = "left";
	}
	switch (pVAlign)
	{
		case "top" :
			break;
		case "middle" :
			vPosTop += vTargetHeight / 2;
			break;
		case "bottom" :
			vPosTop += vTargetHeight;
			break;
		default :
			pVAlign = "bottom";
			vPosTop += vTargetHeight;
	}
	switch (pHDraw)
	{
		case "left" :
			vPosLeft = vPosLeft + vXPad;
			break;
		case "right" :
			vPosLeft = vPosLeft - vSourceWidth - vXPad;
			break;
		default :
			pHDraw = "left";
			vPosLeft = vPosLeft + vXPad;
	}
	switch (pVDraw)
	{
		case "up" :
			vPosTop = vPosTop - vSourceHeight - vYPad;
			break;
		case "down" :
			vPosTop = vPosTop + vYPad;
			break;
		default :
			pVDraw = "down";
			vPosTop = vPosTop + vYPad;
	}
	//----------------------------------------------------------------
	// begin checks to see if source would render off screen,
	//	if so change orientation
	//----------------------------------------------------------------
	if (vPosTop + vSourceHeight > vScreenBottom) //off the bottom of screen
	{
		vPosTop = vPosTop - vSourceHeight;

		if (pVAlign == "bottom")
			vPosTop = vPosTop - vTargetHeight - (2 * vYPad);

		if (pVAlign == "top")
			vPosTop = vPosTop + vTargetHeight - (2 * vYPad);
	}
	//----------------------
	// off the top of screen
	//----------------------
	if (vPosTop < document.body.scrollTop)
	{
		vPosTop = vPosTop + vSourceHeight;

		if(pVAlign == "top")
			vPosTop = vPosTop + vTargetHeight + (2 * vYPad);

		if(pVAlign == "bottom")
			vPosTop = vPosTop - vTargetHeight + (2 * vYPad);
	}
	//----------------------
	// off the right of screen
	//----------------------
	if (vPosLeft + vSourceWidth > vScreenEdge)
	{
		vPosLeft = vPosLeft - vSourceWidth;
		if(pHAlign == "right")
			vPosLeft = vPosLeft - vTargetWidth - (2 * vXPad);

		if(pHAlign == "left")
			vPosLeft = vPosLeft + vTargetWidth - (2 * vXPad);
	}
	//----------------------
	// off the left of screen
	//----------------------
	if (vPosLeft < document.body.scrollLeft)
	{
		vPosLeft = vPosLeft + vSourceWidth;
		if(pHAlign == "left")
			vPosLeft = vPosLeft + vTargetWidth + (2 * vXPad);

		if(pHAlign == "right")
			vPosLeft = vPosLeft - vTargetWidth + (2 * vXPad);
	}


	//----------------------------------------------------------------
	// second set of checks to make sure the re-render isn't still off screen..
	//----------------------------------------------------------------
	if(vPosLeft <= document.body.scrollLeft)		// off left of screen
		vPosLeft = document.body.scrollLeft + 3;

	if(vPosLeft + vSourceWidth >= vScreenEdge)		// off right of screen
		vPosLeft = vScreenEdge - vSourceWidth - 3;

	if(vPosTop <= document.body.scrollTop)			// off top of screen
		vPosTop = document.body.scrollTop + 3;

	if(vPosTop + vSourceHeight >= vScreenBottom)	// off bottom of screen
		vPosTop = vScreenBottom - vSourceHeight - 3;

	vSourceElement.style.position = "absolute";
	vSourceElement.style.posLeft = vPosLeft; //SMR- set x
	vSourceElement.style.posTop = vPosTop; //SMR- set y
	return vPosLeft;
}
//==================================================================================================
//== SelectHider()
//== Hides any select boxes that are below a div or iframe so that they don't
//== display on top of it.  Pass through the id of the div or iframe
//==================================================================================================
function SelectHider(ElNameO){
	var veasy=document.getElementById(ElNameO);
	var roro=getElementPosition(veasy);
	var chTop=roro[1];
	var chLeft=roro[0];
	var vDivWidth=veasy.offsetWidth;
	var vDivHeight=veasy.offsetHeight;
	//--alert(chLeft + '--' + chTop + '--' + vDivWidth + '--' + vDivHeight);
	var chRight=chLeft + vDivWidth;
	var chBottom=chTop + vDivHeight;
    for (i=0;i<document.getElementsByTagName('select').length;i++) 
         {
			 var tempobj=document.getElementsByTagName('select')[i];
			 if (tempobj.style.display!='none'){
				var bobo=getElementPosition(tempobj);
				var tp=bobo[1];
				var bm=tp + tempobj.offsetHeight;
				var lt=bobo[0];
				var rt=lt + tempobj.offsetWidth;
					if ((tp >= chTop && tp <= chBottom && lt >= chLeft && lt <= chRight) || (tp >= chTop && tp <= chBottom && rt >= chLeft && rt <= chRight) || (bm >= chTop && bm <= chBottom && rt >= chLeft && rt <= chRight) || (bm >= chTop && bm <= chBottom && lt >= chLeft && lt <= chRight)||(tempobj.id=='Tasks')){
						//if(vSpanArray[i-1].id.substr(0,9) == "flderror_")
						var theClass=tempobj.className;
						tempobj.className="HideSelec_" + theClass;
						tempobj.style.display='none';
					}
			 } 
		 }
	if (document.getElementsByTagName('object')[0]){
	document.getElementsByTagName('object')[0].style.display='none';
	}
	}
//----------------------------------------------------------
// If Select boxes were hidden when a div or iframe was displayed, 
// this sets them back to their previous state.
//----------------------------------------------------------
function SelectRedisplayer(){
    for (i=0;i<document.getElementsByTagName('select').length;i++) 
         {		
         var tempobj=document.getElementsByTagName('select')[i];
			 if (tempobj.style.display=='none' && tempobj.className.substr(0,10) == "HideSelec_"){
			 		var theClass=tempobj.className;
					var theLength=theClass.length;
					var newString=theClass.substring(10, theLength);
					tempobj.className=newString;
					tempobj.style.display='inline';
				}
			 }
	if (document.getElementsByTagName('object')[0]){
	document.getElementsByTagName('object')[0].style.display='inline';
	}
}
//==================================================================================================
//==   									isDate()
//== Checks to see if a field contains a properly formatted date.
//==
//==================================================================================================

function calisDate(vDate)
{
clearFieldErrors();
if(document.getElementById(vDate)){
var theThing=document.getElementById(vDate);
}
else{
var theThing=vDate;
}

var strDate=theThing.value;
    if(strDate.length>0)
         {
            var dateregex=/^[ ]*[0]?(\d{1,2})\/(\d{1,2})\/(\d{4,})[ ]*$/;
             var match=strDate.match(dateregex);
             if (match) 
              {
                       var tmpdate=new Date(match[3],parseInt(match[1])-1,match[2]);
                  if (tmpdate.getDate()==parseInt(match[2], 10) && tmpdate.getFullYear()==parseInt(match[3],10) && (tmpdate.getMonth()+1)==parseInt(match[1],10))
                   { 
                   return true; 
                   }
             }
	 		displayFieldError(theThing.name, 'MM/DD/YYYY');
			theThing.value='';
			theThing.focus();
         return false;
         }
    else
         {
         return true;
         }
} 
//==================================================================================================
//==   									isDateTime()
//== Checks to see if a field contains a properly formatted date & Time.
//==
//==================================================================================================
   
function makeYear(str) {
  if (parseInt(str,10) < 1900) return 1900+parseInt(str,10)
  return str
}
function calisDateTime(theForm) {
	clearFieldErrors();
  dateString = theForm.value;
  if (dateString == ''){
  return true
  }
  if (!dateString || 
       dateString.indexOf('/')==-1 || 
       dateString.indexOf(':')==-1) {
    displayFieldError(theForm.name, 'MM/DD/YYYY HH:MM');
    return false
  }

  date = new Date(dateString)
  testDate = dateString.split(' ')[0].split('/')
  testTime = dateString.split(' ')[1].split(':')
  mm = parseInt(testDate[0],10)
  dd = parseInt(testDate[1],10)
  yyyy=makeYear(parseInt(testDate[2],10))
  hh = parseInt(testTime[0],10)
  mins = parseInt(testTime[1],10)
  if (
  date.getMonth()   !=(mm-1) || 
  date.getDate()    !=dd ||
  date.getFullYear()!= yyyy||
  date.getHours()!= hh||
  date.getMinutes()!= mins
  ) { 
     displayFieldError(theForm.name, 'MM/DD/YYYY HH:MM');
     return false
  }
  return true
} 