/* Functions */
// this is the object that stores the string and the timeout settings
// you can adjust delay (milliseconds) to be more or less depending on how fast you think users will type
// global storage object for type-ahead info, including reset() method
var typeAheadInfo = {last:0, accumString:"", delay:500, timeout:null, reset:function() {this.last=0; this.accumString=""}};
// function invoked by select element's onkeypress event handler
function typeAhead() {
   // limit processing to IE event model supporter; don't trap Ctrl+keys
   if (window.event && !window.event.ctrlKey) {
      // timer for current event
      var now = new Date();
      // process for an empty accumString or an event within [delay] ms of last
      if (typeAheadInfo.accumString == "" || now - typeAheadInfo.last < typeAheadInfo.delay) {
         // make shortcut event object reference
         var evt = window.event;
         // get reference to the select element
         var selectElem = evt.srcElement;
         // get typed character ASCII value
         var charCode = evt.keyCode;
//         if (charCode >= 96 && charCode <= 105)
//			charCode -= 48;
         // get the actual character, converted to uppercase
         var newChar =  String.fromCharCode(charCode).toUpperCase();
         // append new character to accumString storage
         typeAheadInfo.accumString += newChar;
         // grab all select element option objects as an array
         var selectOptions = selectElem.options;
         // prepare local variables for use inside loop
         var txt, nearest;
         // look through all options for a match starting with accumString
         for (var i = 0; i < selectOptions.length; i++) {
            // convert each item's text to uppercase to facilitate comparison
            // (use value property if you want match to be for hidden option value)
            txt = selectOptions[i].text.toUpperCase();
            // record nearest lowest index, if applicable
            nearest = (typeAheadInfo.accumString > 
                       txt.substr(0, typeAheadInfo.accumString.length)) ? i : nearest;
            // process if accumString is at start of option text
            if (txt.indexOf(typeAheadInfo.accumString) == 0) {
               // stop any previous timeout timer
               clearTimeout(typeAheadInfo.timeout);
               // store current event's time in object 
               typeAheadInfo.last = now;
               // reset typeAhead properties in [delay] ms unless cleared beforehand
               typeAheadInfo.timeout = setTimeout("typeAheadInfo.reset()", typeAheadInfo.delay);
               // visibly select the matching item
               selectElem.selectedIndex = i;
               // prevent default event actions and propagation
               evt.cancelBubble = true;
               evt.returnValue = false;
               // exit function
               return false;   
            }            
         }
         // if a next lowest match exists, select it
         if (nearest != null) {
            selectElem.selectedIndex = nearest;
         }
      } else {
         // not a desired event, so clear timeout
         clearTimeout(typeAheadInfo.timeout);
      }
      // reset global object
      typeAheadInfo.reset();
   }
   return true;
}

function Open_Modal_Window(url, width, height) {
	var scropt = "dialogTop: px; dialogLeft: px; center: 1; dialogWidth: " + width + "px; dialogHeight: " + height + "px; help: 0; status: 0";
	var ret = window.showModalDialog(url,"",scropt);
}
function Show_Modal_Window(url, title, qstr, width, height) {
	
	var scropt = "dialogTop: px; dialogLeft: px; center: 1; dialogWidth: " + width + "px; dialogHeight: " + height + "px; help: 0; status: 0";
	var url1 = "../UserControls/dialog.aspx?title=" + title + "&pagenet=" + url + "&qstr=" + qstr;
	var ret = showModalDialog(url1,"",scropt);
	return ret;
}
function Secure_Modal_Window(url, title, qstr, width, height) {
	
	var scropt = "dialogTop: px; dialogLeft: px; center: 1; dialogWidth: " + width + "px; dialogHeight: " + height + "px; help: 0; status: 0";
	var url1 = "https://www.TeamSCP1.com/UserControls/dialog.aspx?title=" + title + "&pagenet=" + url + "&qstr=" + qstr;
	var ret = showModalDialog(url1,"",scropt);
	return ret;
}
function help() {
	w = screen.availWidth;
	h = screen.availHeight;
	var popW = 400, popH = 400;
	var leftPos = (w-popW)/2, topPos = (h-popH)/2;
	window.open('../help/help.asp','Help','scrollbars=yes, resizable=yes, width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos);
}
var reAlphanumeric = /^[a-zA-Z0-9]+$/
function isAlphanumeric (s)

{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    else {
       return reAlphanumeric.test(s)
    }
}
function isChecked(object) {
	if (object.checked) {
		return true;
	}
	else {
		return false;
	}
}
function IsNumeric(sText) {
	var ValidChars = "0123456789.";
	var Is_Number=true;
	var Char;
	if (sText.length == 0) {
		Is_Number = false;
	}
	else {
		for (i = 0; i < sText.length && Is_Number == true; i++) { 
			Char = sText.charAt(i); 
			if (ValidChars.indexOf(Char) == -1) {
				Is_Number = false;
			}
		}
	}

	return Is_Number;   
}

function isNumber(txtfld, mdigits, msg)
{
	var str=txtfld.value;
	for (var i = 0; i < str.length; i++) {
		var ch = str.substring(i, i + 1);
		if (ch < "0" || "9" < ch){
			alert("\nThe " + msg + " field only accepts digits.\n\r Please re-enter " + msg + ".");
			txtfld.select();
			txtfld.focus();
			return(false);
      }
   }
   if(str.length>mdigits){
		alert("\nThe " + msg + " field shall have " + mdigits + " digits only.\n\n Please re-enter " + msg + ".");
		txtfld.select();
		txtfld.focus();
		return(false);
   }
	return(true);
}

function detectBrowser() {
	var browser = navigator.appName;
	var version = parseInt(navigator.appVersion);
	return navigator.appName;
}

function isEmpty(txtFld,msg) {
	var str = txtFld.value;
	if (str == "" || str == "0" || str == " " || str == null) {
		if (msg != "") {	
			alert("\nPlease fill in " + msg + ".\n\nIt is required.")
			txtFld.focus();
		}
		return(true);
	}
	return(false);	
}	

function inRange(txtFld,f,t,msg) {
	var str = txtFld.value;
	if (isEmpty(txtFld, "")) return true;

	if ((str < f) || (str > t)) {
		if (msg != "") {	
			alert("\n" + msg + " is Invalid.\n\nPlease correct.")
			txtFld.focus();
			txtFld.select();
		}
		return(false);
	}
	return(true);	
}	
      
function isEmail(txtFld,msg) {
   var str   = txtFld.value;
	if (txtFld.value == "") {
		return(true);
	}

   if (txtFld.value.indexOf ('@',0) == -1 || 
       txtFld.value.indexOf ('.',0) == -1)
      {
      alert("\nThe " + msg + " address entered is not in a proper format. Please re-enter or leave blank." )
      txtFld.select();
      txtFld.focus();
      return(false);
      }
   else
      {
		for (var i = 0; i < str.length; i++) 
		{
			var ch = str.substring(i, i + 1);
			if (((ch < "a" || "z" < ch) && (ch < "A" || "Z" < ch) && (ch < "0" || "9" < ch)) && ch != '@' && ch !='.' && ch !='-' && ch!='_') 
				{
				alert("\nPlease use only letters, numbers and @.-_ for " + msg + ".");
				txtFld.select();
				txtFld.focus();
				return(false);
				}
		}	    
		if ( txtFld.value.length < 7 || 
			 txtFld.value.indexOf ('@',0) >= (txtFld.value.indexOf ('.',0) - 1) )
		   {
		   alert("\nThe " + msg + " address entered is not in a proper format. Please re-enter or leave blank." )
		   txtFld.select();
		   txtFld.focus();
		   return(false);
		   }
		return(true);
      }
}

function isDecimal(txtFld,msg)  {
   var str = clean(txtFld.value);
   if (str == "") {
         alert("\nThe " + msg + " field is blank.\n\nPlease enter a decimal number.");
         txtFld.focus();
         return false;
   }
   for (var i = 0; i < str.length; i++) 
      {
      var ch = str.substring(i, i + 1);
      if ((ch < "0" || "9" < ch) && ch != '.') 
         {
         alert("\nThe " + msg + " field accepts only numbers and a decimal point. \n\nPlease re-enter a decimal number.");
         txtFld.select();
         txtFld.focus();
         return false;
         }
      }
   return true;
   }

function isPercent(txtFld,msg)  {
   var str = clean(txtFld.value);
   if (str == "") {
         alert("\nThe " + msg + " field is blank.\n\nPlease enter a percentage.");
         txtFld.focus();
         return false;
   }
   for (var i = 0; i < str.length; i++) 
      {
      var ch = str.substring(i, i + 1);
      if ((ch < "0" || "9" < ch) && ch != '.') 
         {
         alert("\nThe " + msg + " field only accepts percentage figures. \n\nPlease re-enter a percentage.");
         txtFld.select();
         txtFld.focus();
         return false;
         }
      }
   return true;
   }   

function isPhone(txtFld,msg) {
	var str=txtFld.value;
	var newstr="";
	var i;
	var ch;
 
	if (str == "") return true;
	
    for (var i = 0; i < str.length; i++) {
      ch = str.substring(i, i + 1);
      if ((ch < "0" || "9" < ch) && ch != '-' && ch != '(' && ch != ')' && ch != ' ') {
         alert("\nThe " + msg + " field accepts only numbers and the characters () or -. \n\nPlease re-enter a valid phone number.");
         txtFld.select();
         txtFld.focus();
         return false;
         }
      }

	for(i=0;i<str.length;i++){
		ch=str.substring(i,i+1);
		if(! (ch < "0" || ch > "9")) newstr=newstr + ch;
		}
	//if(newstr.length!=10){
	if(newstr.length<10){
         alert("\nThe " + msg + " field is invalid.\n\nPlease enter the number again.");
         txtFld.focus();
         return false;
		}
	//str = "("+newstr.substring(0,3)+") "+newstr.substring(3,6)+"-"+newstr.substring(6,10)
	txtFld.value = str;
	return true;
}

function isCreditCard(txtFld,msg) {
	var str = txtFld.value;
	if (str == "") {
         alert("\nThe " + msg + " field is blank.\n\nPlease enter the Credit Card Number.");
         txtFld.focus();
         return false;
    }
    for (var i = 0; i < str.length; i++) {
		var ch = str.substring(i, i + 1);
		if (ch < "0" || "9" < ch) {
			alert("\nThe " + msg + " field accepts only digits. \n\nPlease re-enter the Credit Card Number.");
			txtFld.select();
			txtFld.focus();
			return false;
		}
    }
	if (str.length < 13 || str.length > 16) {
		alert("Credit card number must be a string of digits between 13 and 16 characters.  \n\nPlease re-enter the Credit Card Number.")
		txtFld.select();
		txtFld.focus();
		return false;
	}
	if (!isCreditCardValid(str)) {
		alert("Credit card number is Invalid.  \n\nPlease re-enter the Credit Card Number.")
		txtFld.select();
		txtFld.focus();
		return false;
	}
	return true;
}

function isCreditCardValid(st) {
  // Encoding only works on cards with less than 19 digits
  if ((st.length > 19) || (st.length < 13))
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }

  if ((sum % 10) == 0) 
	    return (true);
  else
		return (false);

}

function isExpMonth(monthFld,yearFld,msg) {
	if(monthFld.options[monthFld.selectedIndex].value=="" || yearFld.options[yearFld.selectedIndex].value=="") {
		alert("\nThe " + msg + " fields need to be entered");
		monthFld.focus();
		return (false);
	}
	var intMM = parseInt(monthFld.options[monthFld.selectedIndex].value);
	var intYYYY = parseInt(yearFld.options[yearFld.selectedIndex].value);
	var dtToday = new Date();
	if(intMM<1 || intMM > 12 || intYYYY < dtToday.getFullYear()) {
		alert("\nThe " + msg + " contains invalid date values.\n\nPlease re-enter the values.");
		monthFld.focus();
		return (false);
	}
	if(intYYYY==dtToday.getFullYear() && (intMM - 1) < dtToday.getMonth()) {
		alert("\nThe " + msg + " contains expired date values.\n\nPlease re-enter the values.");
		monthFld.focus();
		return (false);
	}
	return (true);
}

function isDate(txtFld, msg) {
	var str=txtFld.value
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{2,4})$/;
	var matchArray = str.match(datePat); // is the format ok?
	if (matchArray == null) {
		alert("The Date value in " + msg + " is not in a valid format.")
		txtFld.select();
		txtFld.focus();
		return false;
	}
	var month = matchArray[1]; 
	var day = matchArray[3];
	var year = matchArray[5];
	if (month < 1 || month > 12) { 
		alert("The Month in " + msg + " must be between 1 and 12.");
		txtFld.select();
		txtFld.focus();
		return false;
	}
	if (day < 1 || day > 31) {
		alert("The Day in " + msg + " must be between 1 and 31.");
		txtFld.select();
		txtFld.focus();
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert("Month "+month+" doesn't have 31 days!")
		txtFld.select();
		txtFld.focus();
		return false
	}
	if (month == 2) { 
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			alert("February " + year + " doesn't have " + day + " days!");
			txtFld.select();
			txtFld.focus();
			return false;
		}
	}
	return true;
}

function areDatesInOrder(fdate,sdate,fmsg,smsg){
	var fd = new Date(fdate.value);
	var sd = new Date(sdate.value);
	var d,m,y;
	var strf;
	var strs;
	d = fd.getDate();
	m = fd.getMonth();
	y = fd.getFullYear();
	strf = "" + y;
	if(m<10)strf=strf + "0" + m; else strf = strf + m;
	if(d<10)strf=strf + "0" + d; else strf = strf + d;

	d = sd.getDate();
	m = sd.getMonth();
	y = sd.getFullYear();
	strs = "" + y;
	if(m<10)strs=strs + "0" + m; else strs = strs + m;
	if(d<10)strs=strs + "0" + d; else strs = strs + d;
	if(strf > strs){
		alert(fmsg + " is later than " + smsg);
		fdate.select();
		fdate.focus();
		return(false);
	}
	return(true);
}

function isCurrency(txtfld,msg) {
	var strfld = clean(txtfld.value);
	var strlcl = "";
	var ch;
	var bdec = false;
	for (var i = 0; i < strfld.length; i++){
		ch = strfld.substring(i,i+1);
		if(ch>="0" && ch<="9"){ strlcl = strlcl + ch;}
		else if((ch=="." || ch==",") && bdec==false){
				strlcl=strlcl + ch;
				bdec==true;
			}
		else{
			alert(msg + " has invalid characters.  Please re-enter in the correct format.");
			txtfld.select();
			txtfld.focus();
			return(false);
		}
	}
	if(strlcl.indexOf(".")>=0 && strlcl.indexOf(".")<(strlcl.length-1)){
		var strdec = strlcl.substring(strlcl.indexOf(".")+1,strlcl.length);
		if(strdec.length>2){
			alert(msg + " can be up to two decimals only.");
			txtfld.select();
			txtfld.focus();
			return(false);
		}
	}
	return(true);	
}

function replace(s, F, R) {
	var find = 0;
	var start = 0
	while (find != -1) {
		find = s.indexOf(F, start);
		if (find != -1) {
			s = s.substring(0,find) + R + s.substring(find + F.length);
			start = find + R.length;
		}
	}
	return s;
}

function trim(s) {
	return s.replace(/(^\s*)|(\s*$)/g, "");
}

function clean(s) {
	if (!s) return s;
	s = replace(s, '$', '');
	s = replace(s, ',', '');
	s = replace(s, '%', '');	
	return s;
}

function checkempty(elem) {
	if ((elem.value == null) || (elem.value.length<2)) {
		alert('Please enter a value for this field.');
		elem.focus();
		return false;
	}
	return true;
}

function checkamt(elem, dec) {
	if ((elem.value == null) || (elem.value.length==0)) elem.value = 0
	value = parseFloat(clean(elem.value));
	if (isNaN(value)) {
		alert('You have entered an incorrect character in this field. \nPlease check your information and try again.');
		elem.focus();
		return false;
	}
	elem.value = FmtMoney(value,dec)
	return true
}

function checkrate(elem) {
	if ((elem.value == null) || (elem.value.length==0)) elem.value = "0%";
	value = parseFloat(clean(elem.value));
	if (isNaN(value)) {
		alert('You have entered an incorrect character in this field. \nPlease check your information and try again.');
		elem.focus();
		return false;
	}
	if ((value<1) || (value>99)) {
		alert('You have exceeded the range for some information on this tab. \nPlease check your information and try again.');
		elem.focus();
		return false;
	}
	elem.value = FmtRate(value)
	return true
}

function FmtRate(A) {
	N=Math.abs(Math.round(A*1000));
	S=((N<10)?"00":((N<100)?"0":""))+N;
	S=S.substring(0,(S.length-3))+"."+S.substring((S.length-3),S.length)+"%";
	return S;
}

function FmtMoney(A,D) {
	N=Math.abs(Math.round(A*100));
	S=((N<10)?"00":((N<100)?"0":""))+N;
	S=((A<0)?"-":"")+"$"+WGgroup(S.substring(0,(S.length-2))) + 
	      ((D>0)?"."+S.substring((S.length-2),S.length):"");
	return S;
}

function WGgroup(S) {
	return (S.length<4)?S:(WGgroup(S.substring(0,S.length-3))+","+S.substring(S.length-3,S.length));
}

function currentTime() {
	var d = new Date();
	h = d.getHours();
	m = d.getMinutes();
	s = d.getSeconds();
	a = "am";
	if (h == 12) {
		a = "pm";
	}
	else if (h == 0) {
		h = 12;
		a = "am";
	}
	else if (h > 12) {
		a = "pm";
		h = h - 12;
	}
	t = h + ":" + m + ":" + s + " " + a;
	return t;
}

function hideleft() {
	top.window.location.href = replace(replace(window.location.href,"wxplr=1&",""),"&wxplr=1","");
}
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}

// function: ClearMessage
// purpose: Clears Message From System
// create date: 04-04-2005
// create by: John Kane
function ClearMessage(messageClientId) {
	document.getElementById(messageClientId).innerHTML = "";
}

	// function: encodeHtml
	// purpose: Encodes An Html Message
	// create datE: 05-06-2005
	// create by: John Kane
	function encodeHtml(htmlToEncode) {
		
		htmlToEncode = escape(htmlToEncode);
		htmlToEncode = htmlToEncode.replace(/\?/g,"%3F");
		htmlToEncode = htmlToEncode.replace(/=/g,"%3D");
		htmlToEncode = htmlToEncode.replace(/&/g,"%26");
		htmlToEncode = htmlToEncode.replace(/@/g,"%40");
		return htmlToEncode;
	}
   
   // function: milesConfirm
   // purpose: Shows Modal Dialog With Custom Confirmation Box - Returns Boolean Value
   // create date: 05-06-2005
   // create by: John Kane
   function milesConfirm(confirmQuestion, yes, no) {
	
		var confirmed = false;
		
		var url = "../UserControls/Confirm.aspx";
		var queryString = "ConfirmQuestion=" + encodeHtml(confirmQuestion) + "|Yes=" + yes + "|No=" + no;
		var title = "Confirmation";
		var width = "350";
		var height = "100";
		var ret = Show_Modal_Window(url, title, queryString, width, height);
		if ( ret == "1" )
			confirmed = true;
			
		return confirmed;
   }

   // function: openSqlReport
   // purpose: Opens a SQL Reporting Report
   // create date: 12-13-2005
   // create by: John Kane
   function openSqlReport(reportName, queryString, windowWidth, windowHeight)
   {
   	if ( queryString.length > 0)
   		window.open("../SqlReporting/ReportGeneratorPage.aspx?ReportName=" + reportName + "&" + queryString, "", "resizable=yes, menubar=yes, location=yes, toolbar=yes, scrollbars=yes, width=" + windowWidth + ", height=" + windowHeight)
	else
		window.open("../SqlReporting/ReportGeneratorPage.aspx?ReportName=" + reportName, "", "resizable=yes, menubar=yes, location=yes, toolbar=yes, scrollbars=yes, width=" + windowWidth + ", height=" + windowHeight)
   }			

// function: storeScroll
	// purpose: Stores Scroll Information
	// create date: 11-25-2005
	// create by: John Kane
	function setScroll()
	{
		if ( document.getElementById ) 
		{
			var hidVerticalScroll = document.getElementById('HidVerticalScroll');
			if ( hidVerticalScroll != null )
			{	
				// Determine Browser
				if ( document.getElementById && !document.all )
				{
					// Netscape or Firefox
					//hidVerticalScroll.value = document.body.scrollTop;
				}
				else
				{
					// Internet Explorer
					hidVerticalScroll.value = document.body.scrollTop;
				}
			}
		}
	}		  
	
	// function: getScroll
	// purpose: Gets Scroll Information on Page Load
	// create date: 11-25-2005
	// create by: John Kane
	function getScroll()
	{
		if ( document.getElementById ) 
		{
			var hidVerticalScroll = document.getElementById('HidVerticalScroll');
			if ( hidVerticalScroll != null )
			{
			
				// Determine Browser
				if ( document.getElementById && !document.all )
				{
					// Netscape or Firefox
					//document.body.scrollTop = hidVerticalScroll.value;
				}
				else
				{
					// Internet Explorer
					document.body.scrollTop = hidVerticalScroll.value;
				}
			}
		}
	}