//***************************************************************************
//     Web Page: Common.js
//       Author: SupplyCore
//         Date: 02/15/2006
//  Description: Common JavaScript Functions
//
// PopUp - Opens the file specified in the input in a new window
// CloseWindow - Closes the current window
// CloseWindowBack - Either goes back to the previous window or closes 
//                            the current window 
// CloseWindowReload - Closes the current window and reloads the opening window
// ViewHide - Shows or Hides an object
// ViewHideBlock - Shows or Hides an object and all specified objects	
// ViewBlock - Shows an object and all specified objects
// HideBlock - Hides an object and all specified objects
// truncateTextArea - Determines if calling textarea has a value greater than 
//                           the value passed in, if so, it truncates the value and 
//                           alerts the user
// isValidDate - Checks to make sure that a valid date has been entered
// isValidTime - Checks if time is in HH:MM:SS AM/PM format.  The seconds 
//                    and AM/PM are optional
// isValidDateTime - Checks to make sure that a valid date/time has been entered
// round - Rounds number to X decimal places, defaults to 2
// isInteger - Returns true if the input is an integer (whole number)
// isFloat - Returns true if the input is a floating point number 
// isDigit - Returns true if the input is a digit
// isEmpty - Returns true if the input is empty
// isWhitespace - Returns true if the input contains all whitespace characters
// stripWhitespace - Search through string's characters one by one and remove 
//                          any whitespace characters
// isObject - Returns TRUE if the input paramater is an object
// Trim - Remove leading and trailing spaces
// ConvertToDate - Returns the number of days between 2 dates
// DaysDiff - Returns the number of days between 2 dates
// BusinessDays - Returns the number of business days between 2 dates
// DateOnly - Returns the date portion of a date variable
// GetCurrentDateTime - Returns the current date and time
// ClearValue - Clears the specofied object
// ShowDiv - Sets the specified object's visibility to Visible
// HideDiv - Sets the specified object's visibility to Hidden
// findPos - Returns left/top position of an object
// getCookieData - Gets the specified cookie
// setCookie - Saves the specified cookie
// OpenFileAttachments - Opens the Attach Documents window for the specified 
//                                 System, TransCode and TransID
// round - Rounds number to X decimal places, defaults to 2
// cent - Rounds a number to the nearest cent, with proper formatting
// setCalendarSelectDate - Sets the date of a blank Calendar Extender to the current date
//***************************************************************************



//***************************************************************************
//  VARIABLE DECLARATIONS
//***************************************************************************
var whitespace = " \t\n\r";			// whitespace characters



//***************************************************************************
//  FUNCTION: PopUp
//   PURPOSE:	Opens the file specified in the input in a new window
//***************************************************************************
function PopUp(sFileName, iHeight, iWidth, iLeft, iTop, iScreenX, iScreenY, iWindowNo)
{
	var sFeatures;
	var sWindowName = "SupplyCore" + iWindowNo
	
	sFeatures = 'height=' + iHeight + ',width=' + iWidth + ',left=' + iLeft + ',top=' + iTop 
	sFeatures = sFeatures + ',screenX=' + iScreenX + ',screenY=' + iScreenY 
	sFeatures = sFeatures + ',menubar=no,status=no,scrollbars=yes,toolbar=no,location=no,resizable=yes'

	self.open(sFileName, sWindowName, sFeatures)
	//window.open(sFileName, sWindowName, sFeatures)

}
//***************************************************************************


//***************************************************************************
//  FUNCTION: CloseWindow
//   PURPOSE:	Closes the current window
//***************************************************************************
function CloseWindow()
{
	window.open('','_self','');
	window.close();
}
//***************************************************************************


//***************************************************************************
//  FUNCTION: CloseWindowBack
//   PURPOSE:	Either goes back to the previous window or closes the current window 
//***************************************************************************
function CloseWindowBack()
{
	if(history.length != 0)
		history.back();
	else 
	{
		window.open('','_self','');
		window.close();
	}
}
//***************************************************************************


//***************************************************************************
//  FUNCTION: CloseWindowReload
//   PURPOSE:	Closes the current window and reloads the opening window
//***************************************************************************
function CloseWindowReload()
{
		if(window.opener) 
			window.opener.location.reload(true);
			
		window.open('','_self','');
		window.close();
}
//***************************************************************************


//***************************************************************************
//  FUNCTION: ViewHide
//   PURPOSE:	Shows or Hides an object
//***************************************************************************
function ViewHide(sName)
{
  var oObj; 
  
  oObj= document.getElementById(sName)
  if(oObj) oObj.style.display=(oObj.style.display=="none"?"block":"none");

}
//***************************************************************************



//***************************************************************************
//  FUNCTION: ViewHideBlock
//   PURPOSE:	Shows or Hides an object and all specified objects
//***************************************************************************
function ViewHideBlock(sType, sName, sView, sHide)
{
  var oObj; 
  var aBlock;
  
  oObj = document.getElementById(sName);
  if(oObj) oObj.style.display = sType;

	aBlock = sView.split(";");
	for(var i = 0; i < aBlock.length; i++)
	{
		oObj = document.getElementById(aBlock[i] + sName);
		if(oObj) oObj.style.display = "block";
	}

	aBlock = sHide.split(";");
	for(var i = 0; i < aBlock.length; i++)
	{
		oObj = document.getElementById(aBlock[i] + sName);
		if(oObj) oObj.style.display = "none";
	}

}
//***************************************************************************

//***************************************************************************
//  FUNCTION:	ViewBlock
//   PURPOSE:	Shows an object and all specified objects
//***************************************************************************
function ViewBlock(sName, sName1)
{
  var oObj 
  
  oObj= document.getElementById(sName)
  if(oObj) oObj.style.display = "inline";

  oObj = document.getElementById(sName1 + "Col" )
  if(oObj) oObj.style.display = "none";

  oObj = document.getElementById(sName1 + "Exp")
  if(oObj) oObj.style.display = "inline";

}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	HideBlock
//   PURPOSE:	Hides an object and all specified objects
//***************************************************************************
function HideBlock(sName, sName1)
{
  var oObj 
  
  oObj= document.getElementById(sName)
  if(oObj) oObj.style.display = "none";

  oObj = document.getElementById(sName1 + "Col" )
  if(oObj) oObj.style.display = "inline";

  oObj = document.getElementById(sName1 + "Exp")
  if(oObj) oObj.style.display = "none";

}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	truncateTextArea
//  PURPOSE:	Determines if calling textarea has a value greater than the value
//				    passed in, if so, it truncates the value and alerts the user
//***************************************************************************
function truncateTextArea(textbox, iMax)
{

    var maxlength = new Number(iMax); // Change number to your max length.

    if(textbox.value.length > maxlength)
    {
        textbox.value = textbox.value.substring(0,maxlength);
        alert('Maximum character length for this field is ' + iMax + '.');
	}

    textbox.focus();
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	isValidDate
//   PURPOSE:	Checks to make sure that a valid date has been entered
//***************************************************************************
function isValidDate(datein)
{
        
  var indate = datein;

  if (indate.indexOf("-")!=-1)
		var sdate = indate.split("-")
  else
    var sdate = indate.split("/")

  var chkDate = new Date(Date.parse(indate))
        
  var cmpDate = (chkDate.getMonth()+1)+"/"+(chkDate.getDate())+"/"+(chkDate.getYear())
  var indate2 = (Math.abs(sdate[0]))+"/"+(Math.abs(sdate[1]))+"/"+(Math.abs(sdate[2]))
  if (indate2 != cmpDate){
    return false;
  } else {
		if (cmpDate == "NaN/NaN/NaN"){
			return false;
		} else {
			return true;
		}       
  }

}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	isValidTime
//   PURPOSE:	Checks if time is in HH:MM:SS AM/PM format.  The seconds and AM/PM are optional
//***************************************************************************
function isValidTime(strTime) {

	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|Am|aM|PM|pm|Pm|pM))?$/;
	var matchArray = strTime.match(timePat);

	if (matchArray == null) {
		return false;
	}

	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];

	if (second=="") { second = null; }

	if (hour < 0  || hour > 23) {
		return false;
	}

	if (minute<0 || minute > 59) {
		return false;
	}
	if (second != null && (second < 0 || second > 59)) {
		return false;
	}
	return true;
}
//***************************************************************************


//***************************************************************************
//  FUNCTION: isValidDateTime
//   PURPOSE:	Checks to make sure that a valid date/time has been entered
//***************************************************************************
function isValidDateTime(strDateTime)
{
	var dt = Trim(strDateTime);
	var intMatch;
	var intDateOnly = false;

	//if (strDateTime.toLowerCase()=="today" || strDateTime.toLowerCase()=="now"){return true;}
	
	intMatch = dt.indexOf(":");
	if (intMatch < 0)
	{
		intDateOnly = true;
		intMatch = dt.length;
	}
	else
	{
		intMatch = dt.indexOf(" ");
	}

	if (intMatch < 0) {return false;}
	
	// check date
	if (!isValidDate(dt.substr(0,intMatch))){return false;}
	
	// check time
	if (!intDateOnly) {
		if (!isValidTime(dt.substr(intMatch+1,dt.length-intMatch))){return false;}
	}
	
	return true;
}
//***************************************************************************


//***************************************************************************
//  FUNCTION: round
//   PURPOSE:	Rounds number to X decimal places, defaults to 2
//***************************************************************************
function round(number,X) 
{
    X = (!X ? 2 : X);
    return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	isInteger
//   PURPOSE:	Returns true if the input is an integer (whole number)
//***************************************************************************
function isInteger(s)
{
  if (isEmpty(s)) return false;
	s = stripWhitespace(s);
	
	for (var i = 0; i < s.length; i++) 
	{
		var c = s.charAt(i)
		if (!isDigit(c)) 
			return false;	
	}
	
	return true
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	isFloat
//   PURPOSE:	Returns true if the input is a floating point number 
//***************************************************************************
function isFloat(s)
{
  var bDecimalPoint = false;
  
  if (isEmpty(s)) return false;
	s = stripWhitespace(s);

  if (s == ".") 
		return false;

	for (var i = 0; i < s.length; i++) 
	{
		var c = s.charAt(i)

    if ((c == ".") && !bDecimalPoint) 
			bDecimalPoint = true;
    else if (!isDigit(c)) 
			return false;
	}
	
	return true
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	isDigit
//   PURPOSE:	Returns true if the input is a digit
//***************************************************************************
function isDigit (c)
{   
	return ((c >= "0") && (c <= "9"))
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	isEmpty
//   PURPOSE:	Returns true if the input is empty
//***************************************************************************
function isEmpty(s)
{   
	return ((s == null) || (s.length == 0))
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	isValidInteger
//   PURPOSE:	Returns true if the input is an integer (whole number) and not 0
//***************************************************************************
function isValidInteger(s)
{
  if (isEmpty(s)) return false;
	s = stripWhitespace(s);
	if (s == '') return false;
	
	for (var i = 0; i < s.length; i++) 
	{
		var c = s.charAt(i)
		if (!isDigit(c)) 
			return false;	
	}
	if (s == '0') return false;
		
	return true
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	isValidFloat
//   PURPOSE:	Returns true if the input is an ifloating point number  and not 0 or 0.00
//***************************************************************************
function isValidFloat(s)
{
  var bDecimalPoint = false;
  
  if (isEmpty(s)) return false;
	s = stripWhitespace(s);

  if (s == ".") 
		return false;

	for (var i = 0; i < s.length; i++) 
	{
		var c = s.charAt(i)

    if ((c == ".") && !bDecimalPoint) 
			bDecimalPoint = true;
    else if (!isDigit(c)) 
			return false;
	}
	
	if (s == '0' || s == '0.00' || s == '0.0' ) return false;
		
	return true
}
//***************************************************************************


//***************************************************************************
//  FUNCTION: isWhitespace
//   PURPOSE:	Returns true if the input contains all whitespace characters
//***************************************************************************
function isWhitespace (s)
{   
	s = stripWhitespace(s);
  if (isEmpty(s)) return true;

  for (var i = 0; i < s.length; i++)
  {   
		var c = s.charAt(i);
		if (whitespace.indexOf(c) == -1) 
			return false;
  }

  return true;
}
//***************************************************************************
	

//***************************************************************************
//  FUNCTION:	stripWhitespace
//   PURPOSE:	Search through string's characters one by one and remove any.
//            whitespace characters
//***************************************************************************
function stripWhitespace (s)
{   
	var returnString = "";

	for (var i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (whitespace.indexOf(c) == -1) returnString += c;
	}

	return returnString;

}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	isObject
//   PURPOSE:	Returns TRUE if the input paramater is an object
//***************************************************************************
function isObject( r ) 
{ 

  return( r && (( 'object' == typeof r ) || ( 'function' == typeof r ))); 

} 
//***************************************************************************


//***************************************************************************
//  FUNCTION:	Trim
//   PURPOSE:	remove leading and trailing spaces
//***************************************************************************
function Trim(s)
{
	var trimmed="";
	var leading = true;
	var trailing = true;
	
	// strip leading spaces
    for(var i = 0; i < s.length; i++) 
		{
        var c = s.charAt(i);
        if (c == ' ') 
        { 
					if (leading==false) trimmed=trimmed+c;
				}
				else
				{	
				leading=false;
				trimmed=trimmed+c;
			}
    }
    
    // strip trailing spaces
    for (var i = trimmed.length-1; i>0; i--) 
    {
			var c = trimmed.charAt(i);
			if (c != " ")	
				return trimmed;
			else
				trimmed=trimmed.substr(0,trimmed.length-1);
		}
	
	return trimmed;
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	ConvertToDate
//   PURPOSE:	Returns the number of days between 2 dates
//***************************************************************************
function ConvertToDate(date)
{

    var date1;
    
    if(date.indexOf(" ") !=  -1)
        date1 = date.substring(0, date.indexOf(" "));
    else
        date1 = date;

    if (date1.indexOf("-") != -1)
        date1 = date1.split("-")
    else
        date1 = date1.split("/")

    return new Date(date1[2], date1[0] -1, date1[1]);

}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	DaysDiff
//   PURPOSE:	Returns the number of days between 2 dates
//***************************************************************************
function DaysDiff(date1, date2)
{

    var sDate = ConvertToDate(date1)
    var eDate = ConvertToDate(date2)

    return Math.round((sDate.getTime() - eDate.getTime()) / 86400000);
  
}
//***************************************************************************



//***************************************************************************
//  FUNCTION:	BusinessDays
//   PURPOSE:	Returns the number of business days between 2 dates
//***************************************************************************
function BusinessDays(date1, date2) {

    var sDate = ConvertToDate(date1);
    var eDate = ConvertToDate(date2);

    if(sDate.getYear < 2000 || eDate.getYear < 2000)
        return NULL

    if(sDate > eDate) 
    {
        var dTemp = sDate;
        sDate = eDate;
        eDate = dTemp;
    }
	
    var iDateDiff = Math.round((eDate-sDate)/86400000);
    var iWeekEndDays = 0;
    var dCntr = sDate;

    while(dCntr < eDate) 
    {
        if(dCntr.getDay() == 6 || dCntr.getDay() == 0) 
        iWeekEndDays = iWeekEndDays + 1;	
        dCntr.setDate(dCntr.getDate() + 1)
    }

    iDateDiff = iDateDiff - iWeekEndDays;

    if(iDateDiff == 0 && iWeekEndDays != 0)
        iDateDiff = 0;

    return iDateDiff;

}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	DateOnly
//   PURPOSE:	Returns the date portion of a date variable
//***************************************************************************
function DateOnly(date)
{
	
    var date1 = date.substring(0, date.indexOf(" "));
    if (date1.indexOf("-")!=-1)
        date1 = date1.split("-")
    else
        date1 = date1.split("/")

    return date1[0]+"/"+date1[1]+"/"+date1[2];
  
  
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	GetCurrentDateTime
//   PURPOSE:	Returns the current date and time
//***************************************************************************
function GetCurrentDateTime (oObj, iType) 
{
	var sReturn = '';
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds();
	var dateValue = (now.getMonth() + 1) + "/" + now.getDate() + "/" + now.getFullYear() + " ";
	var timeValue = "" + ((hours >12) ? hours -12 :hours)
	if (timeValue == "0") timeValue = 12;
	timeValue += ((minutes < 10) ? ":0" : ":") + minutes
	timeValue += ((seconds < 10) ? ":0" : ":") + seconds
	timeValue += (hours >= 12) ? " PM" : " AM"
	
	switch (iType)
	{
		case 1:		//Return Date only
			sReturn = dateValue;
			break;
			
		case 2:		//Return Time Only
			sReturn = timeValue;
			break;
				
		default:	//Otherwise return both date and time
			sReturn = dateValue + timeValue;
			break;
	}

	eval(oObj + ".value = sReturn;");

}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	ClearValue
//   PURPOSE:	Clears the specofied object
//***************************************************************************
function ClearValue (oObj) 
{

	eval(oObj + ".value = '';");

}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	ShowDiv
//   PURPOSE:	Sets the specified object's visibility to Visible
//***************************************************************************
function ShowDiv(sItem, sDiv)
{
	var hoveritem = document.getElementById(sItem);
	var coors = findPos(hoveritem);

	var hp = document.getElementById(sDiv);
	hp.style.top = coors[1] + 18 + 'px';
	hp.style.left = coors[0] + 20 + 'px';
	hp.style.visibility = "Visible";
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	HideDiv
//   PURPOSE:	Sets the specified object's visibility to Hidden
//***************************************************************************
function HideDiv(sDiv)
{
	hp = document.getElementById(sDiv);
	hp.style.visibility = "Hidden";	
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	findPos
//   PURPOSE:	Returns left/top position of an object
//***************************************************************************
function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
//***************************************************************************



//***************************************************************************
//  FUNCTION:	getCookieData
//   PURPOSE:	Gets the specified cookie
//***************************************************************************
function getCookieData(sCookie)
{
	var iStart; 
	var iEnd;
	
	if (document.cookie.length > 0)
	{
		iStart = document.cookie.indexOf(sCookie + "=");
		if (iStart != -1)
		{ 
			iStart = iStart + sCookie.length + 1; 
			iEnd = document.cookie.indexOf(";", iStart);
			if (iEnd == -1) iEnd = document.cookie.length;
			return unescape(document.cookie.substring(iStart, iEnd));
		} 
	}
	return "";
}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	setCookie
//   PURPOSE:	Saves the specified cookie
//***************************************************************************
function setCookie (name, value) 
{
	var myDate = new Date();
	var year = myDate.getYear();

	year = year + 1;
	myDate.setYear(year);
	//document.cookie = name + "=" + escape (value) + "; expires=" + myDate.toGMTString() + "; path=/;domain=www2.supplycore.com";
	document.cookie = name + "=" + escape (value) + "; expires=" + myDate.toGMTString() + "; path=/;";

}
//***************************************************************************


//***************************************************************************
//  FUNCTION:	OpenFileAttachments
//   PURPOSE:	Opens the Attach Documents window for the specified System, TransCode and TransID
//***************************************************************************
function OpenFileAttachments(SystemCode, TranCode, TransID)
{
	url = location.protocol + '//' + location.hostname + '/IntranetApps/Attachments/default.aspx?syscode=' + SystemCode;
	if (TranCode != null) url = url + '&trancode=' + TranCode;
    url = url + '&id=' + TransID;

	winAttachments = window.open(url, 'attachments', 'width=750,height=600,left=80,top=80,scrollbars=1,resizable=1');
	winAttachments.focus();
}
//***************************************************************************


//***************************************************************************
//  FUNCTION: round
//   PURPOSE:	Rounds number to X decimal places, defaults to 2
//***************************************************************************
function round(number,X) 
{
    X = (!X ? 2 : X);
    return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}
//***************************************************************************


//***************************************************************************
//  FUNCTION: cent
//   PURPOSE:	Rounds number to X decimal places, defaults to 2
//***************************************************************************
function cent(amount) {
    amount -= 0;
    amount = (Math.round(amount*100))/100;
    return (amount == Math.floor(amount)) ? amount + '.00' : (  (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
}
//***************************************************************************


//***************************************************************************
//  FUNCTION: setCalendarSelectDate
//   PURPOSE:	Sets the date of a blank Calendar Extender to the current date
//***************************************************************************
function setCalendarSelectDate(textbox, calendar)
{ 
    if($get(textbox).value == "")
    { 
        $find(calendar).set_selectedDate(new Date());
        $get(textbox).value = "";
    }
} 
//***************************************************************************
  
