(function(factory){if(typeof define==="function"&&define.amd){define(["jquery"],function($){return factory($)})}else if(typeof module==="object"&&typeof module.exports==="object"){exports=factory(require("jquery"))}else{factory(jQuery)}})(function($){$.easing.jswing=$.easing.swing;var pow=Math.pow,sqrt=Math.sqrt,sin=Math.sin,cos=Math.cos,PI=Math.PI,c1=1.70158,c2=c1*1.525,c3=c1+1,c4=2*PI/3,c5=2*PI/4.5;function bounceOut(x){var n1=7.5625,d1=2.75;if(x<1/d1){return n1*x*x}else if(x<2/d1){return n1*(x-=1.5/d1)*x+.75}else if(x<2.5/d1){return n1*(x-=2.25/d1)*x+.9375}else{return n1*(x-=2.625/d1)*x+.984375}}$.extend($.easing,{def:"easeOutQuad",swing:function(x){return $.easing[$.easing.def](x)},easeInQuad:function(x){return x*x},easeOutQuad:function(x){return 1-(1-x)*(1-x)},easeInOutQuad:function(x){return x<.5?2*x*x:1-pow(-2*x+2,2)/2},easeInCubic:function(x){return x*x*x},easeOutCubic:function(x){return 1-pow(1-x,3)},easeInOutCubic:function(x){return x<.5?4*x*x*x:1-pow(-2*x+2,3)/2},easeInQuart:function(x){return x*x*x*x},easeOutQuart:function(x){return 1-pow(1-x,4)},easeInOutQuart:function(x){return x<.5?8*x*x*x*x:1-pow(-2*x+2,4)/2},easeInQuint:function(x){return x*x*x*x*x},easeOutQuint:function(x){return 1-pow(1-x,5)},easeInOutQuint:function(x){return x<.5?16*x*x*x*x*x:1-pow(-2*x+2,5)/2},easeInSine:function(x){return 1-cos(x*PI/2)},easeOutSine:function(x){return sin(x*PI/2)},easeInOutSine:function(x){return-(cos(PI*x)-1)/2},easeInExpo:function(x){return x===0?0:pow(2,10*x-10)},easeOutExpo:function(x){return x===1?1:1-pow(2,-10*x)},easeInOutExpo:function(x){return x===0?0:x===1?1:x<.5?pow(2,20*x-10)/2:(2-pow(2,-20*x+10))/2},easeInCirc:function(x){return 1-sqrt(1-pow(x,2))},easeOutCirc:function(x){return sqrt(1-pow(x-1,2))},easeInOutCirc:function(x){return x<.5?(1-sqrt(1-pow(2*x,2)))/2:(sqrt(1-pow(-2*x+2,2))+1)/2},easeInElastic:function(x){return x===0?0:x===1?1:-pow(2,10*x-10)*sin((x*10-10.75)*c4)},easeOutElastic:function(x){return x===0?0:x===1?1:pow(2,-10*x)*sin((x*10-.75)*c4)+1},easeInOutElastic:function(x){return x===0?0:x===1?1:x<.5?-(pow(2,20*x-10)*sin((20*x-11.125)*c5))/2:pow(2,-20*x+10)*sin((20*x-11.125)*c5)/2+1},easeInBack:function(x){return c3*x*x*x-c1*x*x},easeOutBack:function(x){return 1+c3*pow(x-1,3)+c1*pow(x-1,2)},easeInOutBack:function(x){return x<.5?pow(2*x,2)*((c2+1)*2*x-c2)/2:(pow(2*x-2,2)*((c2+1)*(x*2-2)+c2)+2)/2},easeInBounce:function(x){return 1-bounceOut(1-x)},easeOutBounce:bounceOut,easeInOutBounce:function(x){return x<.5?(1-bounceOut(1-2*x))/2:(1+bounceOut(2*x-1))/2}})});
//CSS input form input styling - combine with _input.css

function inputCustomStyle(parentEle){
	//dynamic input element additions
	if(typeof parentEle=='undefined'){parentEle='body';}
	//wrap select lists in order to add custom expand arrow
	$(parentEle+" select").each(function(){
		if(!$(this).hasClass('input-style-added')){
			$(this).addClass('input-style-added');
			$(this).wrap('<span class="select-wrap'+($(this).attr('class')?' '+$(this).attr('class')+'-wrap':'')+'"'+($(this).attr('id')?' id="'+$(this).attr('id')+'-wrap"':'')+'></span>');
		}
	}); 
	//wrap radio buttons in order to add custom styling
	$(parentEle+" input[type=radio]").each(function(){
		if(!$(this).hasClass('input-style-added')){
			$(this).addClass('input-style-added');
			$(this).wrap('<span class="radio-wrap'+($(this).attr('class')?' '+$(this).attr('class')+'-wrap':'')+'"'+($(this).attr('id')?' id="'+$(this).attr('id')+'-wrap"':'')+'></span>');$(this).parent().append('<span></span>');
		}
	}); 
	//wrap checkboxes in order to add custom styling
	$(parentEle+" input[type=checkbox]").each(function(){
		if(!$(this).hasClass('input-style-added')){
			$(this).addClass('input-style-added');
			$(this).wrap('<span class="check-wrap'+($(this).attr('class')?' '+$(this).attr('class')+'-wrap':'')+'"'+($(this).attr('id')?' id="'+$(this).attr('id')+'-wrap"':'')+'></span>');$(this).parent().append('<span></span>');
		}
	}); 	
}

$(document).ready(function(){inputCustomStyle();});

//alert('validatorscript up')
/*
*  The Validator
*   The class that handles all validation related issues
*
*   pass the name of the form while constructing.
*   methods:
*    addValidation(input_item_name,validation_descriptor,error_string)
		or
*    addValidation(input_item_name,validation_descriptor,error_string,field_to_check_also)
*       call this method for each input item. Single input item can have
*       many validations
*
*    setAddnlValidationFunction(function_name)
*             call this function to set a custom validat function, which
will
*       be called after other validations are over.
*          The function should return 'true' or 'false'
*/
//alert('validator2.js is running');

function Validator(frmname)
  {
this.formobj=document.forms[frmname];
//preserve the form's name in a seperate property in case one of the input fields is also named "name"
this.formobj.formName=frmname;
 if(!this.formobj)
 {
   alert("BUG: could not get Form object "+frmname);
  return;
 }
 if(this.formobj.onsubmit)
 {//console.log('move onsub');
  this.formobj.old_onsubmit = this.formobj.onsubmit;
  this.formobj.onsubmit=null;
 }
 else
 {
  this.formobj.old_onsubmit = null;
 }
 this.formobj.onsubmit=form_submit_handler;
 //special handler to invoke validator
 this.formobj.validateNow=form_submit_handler;
 //end special handler
 this.addValidation = add_validation;
 this.setAddnlValidationFunction=set_addnl_vfunction;
 this.clearAllValidations = clear_all_validations;
}

function set_addnl_vfunction(functionname, params)
{
  //console.log('set_addnl_vfunction, functionname='+functionname+', params='+params);
  this.formobj.addnlvalidation = functionname;
  this.formobj.addnlvalparams = params;
}
function clear_all_validations()
{
 for(var itr=0;itr < this.formobj.elements.length;itr++)
 {
  this.formobj.elements[itr].validationset = null;
 }
}
function form_submit_handler()
{//console.log('form_submit_handler'); 
 for(var itr=0;itr < this.elements.length;itr++)
 {//console.log('form_submit_handler loop');
  if(this.elements[itr].validationset &&
    !this.elements[itr].validationset.validate())
  {//console.log('form_submit_handler found false - return');
    return false;
  }
 }
 if(this.addnlvalidation)
 {
   //console.log("this.addnlvalidation="+this.addnlvalidation+", this.addnlvalparams="+this.addnlvalparams);
   str =" var ret = "+this.addnlvalidation+"('"+this.addnlvalparams+"')";
   eval(str);
    if(!ret) return ret;
 }
 return true;
}

function add_validation(itemname,descriptor,errstr,fieldname){
	if(!this.formobj){
		alert("BUG: the form object is not set properly");
  		return;
 	}//if
	if(descriptor=="radioGroup"){
	//alert('found radioGroup named '+ itemname)
	//alert('this.formobj.formName= '+ this.formobj.formName)
	//alert('radioGroup button 1 name= '+ this.formobj[itemname][0].name)
 		//treat the formObj differently if we are validating a range of radio buttons
		//use the first radio button in the array of radio buttons to hold the validation info for the entire set
	 	this.formobj[itemname][0].formName=this.formobj.formName;
	 	var itemobj = this.formobj[itemname][0];
 	}else{
	 	var itemobj = this.formobj[itemname];
	 	var fieldobj = this.formobj[fieldname];
 	}
 	if(!itemobj){
   		alert("BUG: Could not get the input object named: "+itemname);
  		return;
 	}
	 /* NOTE- dont use this because there will not always be a fieldobj
	  if(!fieldobj){
   		alert("BUG: Couldnot get the input field object named: "+fieldname);
  		return;
 	  }
    */
	 if(!itemobj.validationset){
		itemobj.validationset = new ValidationSet(itemobj,fieldobj);
	 }
	 itemobj.validationset.add(descriptor,errstr);
}

function ValidationDesc(inputitem,desc,error,fielditem){
   this.desc=desc;
   this.error=error;
   this.itemobj = inputitem;
   this.validate=vdesc_validate;
   this.fieldobj=fielditem;
}

function vdesc_validate(){
   if(!V2validateData(this.desc,this.itemobj,this.error,this.fieldobj)){
      if(this.fieldobj) {
         this.fieldobj.focus();
      }else{
         this.itemobj.focus();
      }
      return false;
   }
   return true;
}

function ValidationSet(inputitem,fielditem){
   this.vSet=new Array();
   this.add= add_validationdesc;
   this.validate= vset_validate;
   this.itemobj = inputitem;
   this.fieldobj = fielditem;
}

function add_validationdesc(desc,error){
   this.vSet[this.vSet.length]=
   new ValidationDesc(this.itemobj,desc,error,this.fieldobj);
}

function vset_validate(){
   for(var itr=0;itr<this.vSet.length;itr++){
      if(!this.vSet[itr].validate()){
         return false;
      }
   }
   return true;
}

function validateEmailv2(email){
  //updated 9-25-21 for HODAG
  //https://www.simplilearn.com/tutorials/javascript-tutorial/email-validation-in-javascript
  emTest=email.trim();
  if(emTest.indexOf('.')==-1){return false;}
  if(emTest.indexOf('@')==-1){return false;}
  var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
  return validRegex.test(emTest);
  //return emTest.match(validRegex);
  /*
  //https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript
  const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);

	//https://www.w3resource.com/javascript/form/email-validation.php
	return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,40})+$/.test(email));
  */
}

function V2validateData(strValidateStr,objValue,strError,fieldValue){ //console.log(objValue.type); alert(strValidateStr); alert(objValue.offsetHeight);
	if(objValue.offsetHeight==0 && objValue.type!='hidden'){return true;} //DONT VALIDATE INVISIBLE INPUTS (unless invisible element specifically requested) - http://davidwalsh.name/offsetheight-visibility

   var epos = strValidateStr.search("=");
   var command = "";
   var cmdvalue = "";
   if(epos >= 0){
      command  = strValidateStr.substring(0,epos);
      cmdvalue = strValidateStr.substr(epos+1);
   }else{
      command = strValidateStr;
   }
   
   switch(command){
      case "req":
      case "required": 
         if(eval(objValue.value.length) == 0){
            if(!strError || strError.length ==0){
               strError = objValue.name + " : Required Field";
            }
            alert(strError);
            return false;
         }
      break;
      case "maxlength":
      case "maxlen":
         if(eval(objValue.value.length) >  eval(cmdvalue)){
            if(!strError || strError.length ==0){
               strError = objValue.name + " : "+cmdvalue+" charactersmaximum ";
            }
            alert(strError + "\n[Current length = " + objValue.value.length + " ]");
            return false;
         }
      break;
      case "minlength":
      case "minlen":
         if(eval(objValue.value.length) <  eval(cmdvalue)){
            if(!strError || strError.length ==0){
               strError = objValue.name + " : " + cmdvalue + " charactersminimum ";
            }
            alert(strError + "\n[Current length = " + objValue.value.length + " ]");
            return false;
         }
      break;
      case "alnum":
      case "alphanumeric":
         var charpos = objValue.value.search("[^A-Za-z0-9]");
         if(objValue.value.length > 0 &&  charpos >= 0){
            if(!strError || strError.length ==0){
               strError = objValue.name+": Only alpha-numeric charactersallowed ";
            }
            alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
            return false;
         }
      break;
      case "num":
      case "numeric":
         var charpos = objValue.value.search("[^0-9]");
         if(objValue.value.length > 0 &&  charpos >= 0){
            if(!strError || strError.length ==0){
               strError = objValue.name+": Only digits allowed ";
            }
            alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
            return false;
         }
      break;
      case "float":
         var charpos = objValue.value.search("[^0-9\.]");
         if(objValue.value.length > 0 &&  charpos >= 0){
            if(!strError || strError.length ==0){
               strError = objValue.name+": Only digits and periods allowed ";
            }
            alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
            return false;
         }
      break;
      case "alphabetic":
      case "alpha":
         var charpos = objValue.value.search("[^A-Za-z]");
         if(objValue.value.length > 0 &&  charpos >= 0){
            if(!strError || strError.length ==0){
               strError = objValue.name+": Only alphabetic characters allowed ";
            }
            alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
            return false;
         }
      break;
      case "alnumhyphen":
         var charpos = objValue.value.search("[^A-Za-z0-9\-_]");
         if(objValue.value.length > 0 &&  charpos >= 0){
            if(!strError || strError.length ==0){
               strError = objValue.name+": characters allowed are A-Z,a-z,0-9,- and _";
            }
            alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
            return false;
         }
      break;
      case "email":
         if(!validateEmailv2(objValue.value)){
            if(!strError || strError.length ==0){
               strError = objValue.name+": Enter a valid Email address ";
            }
            alert(strError);
            return false;
         }
      break;
      case "lt":
      case "lessthan":
         if(isNaN(objValue.value)){
            alert(objValue.name+": Should be a number ");
            return false;
         }
         if(eval(objValue.value) >=  eval(cmdvalue)){
            if(!strError || strError.length ==0){
               strError = objValue.name + " : value should be less than "+ cmdvalue;
            }
            alert(strError);
            return false;
         }
      break;
      case "gt":
      case "greaterthan":
         if(isNaN(objValue.value)){
            alert(objValue.name+": Should be a number ");
            return false;
         }
         if(eval(objValue.value) <=  eval(cmdvalue)){
            if(!strError || strError.length ==0){
               strError = objValue.name + " : value should be greater than "+ cmdvalue;
            }
            alert(strError);
            return false;
         }
      break;
      case "regexp":
         if(!objValue.value.match(cmdvalue)){
            if(!strError || strError.length ==0){
               strError = objValue.name+": Invalid characters found ";
            }
            alert(strError);
            return false;
         }
      break;
      case "dontselect":
         if(objValue.selectedIndex == null){
            alert("BUG: dontselect command for non-select Item");
            return false;
         }
         if(objValue.selectedIndex == eval(cmdvalue)){
            if(!strError || strError.length ==0){
               strError = objValue.name+": Please Select one option ";
            }
            alert(strError);
            return false;
         }
      break;
      case "checked":
         if (!objValue.checked){
            if(!strError || strError.length ==0){
               strError = objValue.name + " : You must check this box";
            }
            alert(strError);
            return false;
         }
      break;
      case "checkedAndField":
         if (objValue.checked) {
            if (!fieldValue.value) {
               if(!strError || strError.length ==0) {
                  strError = objValue.name + " : You must specify a date for the class";
               }
               alert(strError);
               return false;
            }
         }
      break;
      case "fieldAndChecked":
         if (fieldValue.value) {
            if (!objValue.checked) {
               if(!strError || strError.length ==0) {
                  strError = objValue.name + " : You must check te box next to your chosen date";
               }
               alert(strError);
               return false;
            }
         }
      break;
      case "radioGroup":
         //reset the objValue to represent all of the buttons in the radio group, not just the first button which is storing the validation code
         checkFound=0
         radioSet=document.forms[objValue.formName][objValue.name]
         for(inc=0;inc<radioSet.length;inc++){
            if(radioSet[inc].checked){
               checkFound=1
            }
         }
         //now alert if no check was found in this radio group
         if(!checkFound){
            if(!strError||strError.length==0){
               strError=objValue.name+" : You must select a radio button"
            }
            alert(strError)
            return false
         }
      break;
      case 'selectOrField':
         if(objValue.value.length==0 || objValue.value=='addNew'){ //console.log('check field');
            newName='new__'+(objValue.name.replace('db__','')); //console.log(newName);
            addNewObj=document.getElementById(newName); //console.log(addNewObj.value);
            if(addNewObj.value.length==0){
               if(!strError||strError.length==0){
                  strError=objValue.name+" : A selection is required"
               }
               alert(strError)
               return false
            }
         }
      break;
      case 'fileUpload':
         if(objValue.value.length==0){ //if no new file upload check for a previously uploaded file
            savedName=(objValue.name.replace('__new','__saved')); //console.log(savedName);
            savedObj=document.getElementById(savedName);
            if(!savedObj || savedObj.value.length==0){ //console.log('no saved item');
               selName=(objValue.name.replace('__new','__select')); //console.log(selName);
               selObj=document.getElementById(selName);
               if(!selObj || selObj.value.length==0){ //console.log('no selected item');
                  if(!strError||strError.length==0){
                     strError=objValue.name+" : A file upload is required"
                  }
                  alert(strError)
                  return false
               }
            }
         }
      break;
   }
   
   return true; //return true if not stopped somewhere above
}
/**
 * Copyright (c) 2007-2015 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
 * Licensed under MIT
 * @author Ariel Flesler
 * @version 2.1.2
 */
;(function(f){"use strict";"function"===typeof define&&define.amd?define(["jquery"],f):"undefined"!==typeof module&&module.exports?module.exports=f(require("jquery")):f(jQuery)})(function($){"use strict";function n(a){return!a.nodeName||-1!==$.inArray(a.nodeName.toLowerCase(),["iframe","#document","html","body"])}function h(a){return typeof a==="function"||$.isPlainObject(a)?a:{top:a,left:a}}var p=$.scrollTo=function(a,d,b){return $(window).scrollTo(a,d,b)};p.defaults={axis:"xy",duration:0,limit:!0};$.fn.scrollTo=function(a,d,b){"object"=== typeof d&&(b=d,d=0);"function"===typeof b&&(b={onAfter:b});"max"===a&&(a=9E9);b=$.extend({},p.defaults,b);d=d||b.duration;var u=b.queue&&1<b.axis.length;u&&(d/=2);b.offset=h(b.offset);b.over=h(b.over);return this.each(function(){function k(a){var k=$.extend({},b,{queue:!0,duration:d,complete:a&&function(){a.call(q,e,b)}});r.animate(f,k)}if(null!==a){var l=n(this),q=l?this.contentWindow||window:this,r=$(q),e=a,f={},t;switch(typeof e){case "number":case "string":if(/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(e)){e= h(e);break}e=l?$(e):$(e,q);case "object":if(e.length===0)return;if(e.is||e.style)t=(e=$(e)).offset()}var v=typeof b.offset==="function"&&b.offset(q,e)||b.offset;$.each(b.axis.split(""),function(a,c){var d="x"===c?"Left":"Top",m=d.toLowerCase(),g="scroll"+d,h=r[g](),n=p.max(q,c);t?(f[g]=t[m]+(l?0:h-r.offset()[m]),b.margin&&(f[g]-=parseInt(e.css("margin"+d),10)||0,f[g]-=parseInt(e.css("border"+d+"Width"),10)||0),f[g]+=v[m]||0,b.over[m]&&(f[g]+=e["x"===c?"width":"height"]()*b.over[m])):(d=e[m],f[g]=d.slice&& "%"===d.slice(-1)?parseFloat(d)/100*n:d);b.limit&&/^\d+$/.test(f[g])&&(f[g]=0>=f[g]?0:Math.min(f[g],n));!a&&1<b.axis.length&&(h===f[g]?f={}:u&&(k(b.onAfterFirst),f={}))});k(b.onAfter)}})};p.max=function(a,d){var b="x"===d?"Width":"Height",h="scroll"+b;if(!n(a))return a[h]-$(a)[b.toLowerCase()]();var b="client"+b,k=a.ownerDocument||a.document,l=k.documentElement,k=k.body;return Math.max(l[h],k[h])-Math.min(l[b],k[b])};$.Tween.propHooks.scrollLeft=$.Tween.propHooks.scrollTop={get:function(a){return $(a.elem)[a.prop]()}, set:function(a){var d=this.get(a);if(a.options.interrupt&&a._last&&a._last!==d)return $(a.elem).stop();var b=Math.round(a.now);d!==b&&($(a.elem)[a.prop](b),a._last=this.get(a))}};return p});

//alert('sharedscripts up');

//variables that will only be reset if header-standard.php script has not been loaded
if(typeof headerJSloaded=='undefined'){
	var appleDevice=0;
	var mobileDevice=0;
	var tabletDevice=0;
	var mobileOrTabletDevice=0;
	var isltIE9=0;
	var cufonUsed=0;
	var httpsPg=0;
}
var inAdminCMS=0; //this will be updated by the admin-shared.js script if in the admin
var curTogDiv=0;
var curTogVals=new Array();
var openDivs=new Array();
var curGalleryOL=""; //1-17-24 NFI - track current, or most recent, gallery overlay gRef
var validate=0;
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1||navigator.appVersion.indexOf("Trident") != -1) ? true : false;    // true if we're on ie
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; // true if we're on windows
//reset popwin variables
var popWin=0, popWin_x=0, popWin_y=0, popWin_h=0, popWin_w=0;
//reset nav variables
var curAccessArea="", navMainData=new Array(), navSubData=new Array();
//var defAdminPanel="";
var availableImgs1=new Array(), availableImgs2=new Array(), availableImgs3=new Array();

//3-5-25 SMEI
async function copyLinkToClipboard(txt) {
   try {
      await navigator.clipboard.writeText(txt);
      alert("Link copied.");
   } catch (error) {
      alert('Unable to copy link.'); //alert(error.message);
   }
}

//1-12-24 - strip_tags eqiuvalent for javascript
function removeHtmlTags(origStr){
   return origStr.replace(/(<([^>]+)>)/gi, "");
}

//11-3-23 - functions to clean values provided by user via javascript before re-using these values in other javascript based actions or output
//https://portswigger.net/web-security/cross-site-scripting/preventing#how-to-prevent-xss-client-side-in-javascript
function jsEscape(str){ //encoding data to be used within a <script> context -> <script>x="'+jsEscape(untrustedValue)+'";<\/script>
   return String(str).replace(/[^\w. ]/gi, function(c){
       return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
   });
}
function jsHtmlEncode(str){ //encoding data to be shown as HTML output via javascript -> <script>document.body.innerHTML = htmlEncode(untrustedValue)</script>
   return String(str).replace(/[^\w. ]/gi, function(c){
       return '&#'+c.charCodeAt(0)+';';
   });
}

//Test for HTML5 video and audio playback capability
function checkHtml5Media(ckType){
	//if(!!document.createElement('video').canPlayType){}
	//if(isltIE9!=1){}
	var ckEle = document.createElement(ckType); //ckVideo.setAttribute('id','ckVid');
	if(!!ckEle.canPlayType){
		if(ckType=='video'){return ckEle.canPlayType('video/mp4')!=""?1:0;}
		if(ckType=='audio'){return ckEle.canPlayType('audio/mpeg')!=""?1:0;}
	}
	//var killVid = document.getElementById('ckVid'); document.removeChild(killVid);
}
var noHTML5Media=0; //this HTML media override value could potentially be set in the header-standard include
var html5Video=checkHtml5Media('video');
var html5Audio=checkHtml5Media('audio');
//alert(html5Video+','+html5Audio);

function toggleBkgdVideoPlay(dir){
	if(typeof dir=='undefined'){dir='stop';}
	if(dir=='stop'){$("video").each(function(){if($(this)[0].hasAttribute('playsinline') && $(this)[0].readyState==4){$(this)[0].pause();/*console.log('pause '+$(this).attr('id'));*/}});}
	if(dir=='play'){$("video").each(function(){if($(this)[0].hasAttribute('playsinline') && $(this)[0].hasAttribute('loop') && $(this)[0].readyState==4){$(this)[0].play();/*console.log('play '+$(this).attr('id'));*/}});}
}

//live top offset calculation - used by _form.php, form.php and init auto scroll below
function topOffsetCalc(offsetPad,ignoreBanner,headerOnly){
   if(typeof headerOnly!='undefined' && ($("#header").length==0||$("#header").css('display')=='none')){return offsetPad;} //2-29-24 TLI
   if(typeof ignoreBanner=='undefined'){ignoreBanner=0;}
	return ($("#header-reference-small").length>0?$("#header-reference-small").height():
   ($("#header-reference").length>0?$("#header-reference").height():
   ($("#header-push").length>0?$("#header-push").height():
   ($(".mobileFixedNavBar").length>0?$(".mobileFixedNavBar").height():
	($("#pFormScrollTopMargin").length>0?$("#pFormScrollTopMargin").height():
   ($("#overlay-top-margin").length>0?$("#overlay-top-margin").height():0))))))
   +(!ignoreBanner && $("#header-banner").length>0?$("#header-banner").height():0) //add banner height if available
   +(typeof offsetPad!='undefined'?offsetPad:15);
}

function updateClickTrack(tbl,rID){//alert('tbl='+tbl+", rID="+rID);
	//$.get("/_clicktrack?tbl="+tbl+"&rID="+rID,{},function(){});
	$.ajax({
			url: "/_clicktrack?tbl="+tbl+"&rID="+rID,
			success: function(data){},
			async: false
		});
	return true;
}

function jqueryFormReset(formID,skipCheckboxes,skipRadioBtns){
	$(':input','#'+formID).not(':button, :submit, :reset, :hidden').val('');
	if(skipCheckboxes!=1){$(':input','#'+formID).prop('checked',false);} //CHANGED FOR JQUERY 1.7.1+ COMPATABILITY
	if(skipRadioBtns!=1){$(':input','#'+formID).prop('selected',false);} //CHANGED FOR JQUERY 1.7.1+ COMPATABILITY
}

//STANDARD SUBSCRIBE, EMAIL AND SEARCH FUNCTIONS
function runSearch(fmName,txtField,txtAlert){
	def=$("#"+(txtField?txtField:"st")+"Def").length>0?$("#"+(txtField?txtField:"st")+"Def").val():'';
	if($("#"+(txtField?txtField:"st")).val()==""||$("#"+(txtField?txtField:"st")).val()=="Search" || $("#"+(txtField?txtField:"st")).val()==def){
		//$("#"+(txtField?txtField:"st")).focus();
		alert(txtAlert?txtAlert:"Please enter search text");return false;
	}else{//alert('submit');
		$("#"+(fmName?fmName:"searchForm")).removeAttr("onsubmit").off("submit").trigger("submit"); //the submission validation has already run, so remove it here to avoid an infinite loop and allow submission
	}
}

function ePersonalShopper(){openOverlay('iframe','Request a Personal Shopper','/content/forms/personal-shopper.php?prc=sub',410,410);}

function eWishList(altTitle){openOverlay('iframe',(altTitle!=null?altTitle:(typeof eRefTitle!='undefined'?eRefTitle:'Email Wish List to a Friend')),'/content/forms/wishlist.php?prc=sub',410,410);}

function eReferral(altTitle){openOverlay('iframe',(altTitle!=null?altTitle:(typeof eRefTitle!='undefined'?eRefTitle:'Email Page Link to a Friend')),'/content/forms/referral.php?prc=sub',410,410);}

//function eReferral(altTitle){openOverlay('iframe',(altTitle!=null?altTitle:(typeof eRefTitle!='undefined'?eRefTitle:'Email Link to a Friend')),'/content/forms/referral.php?p=ref',390,300);}

function enewsForward(mID){openOverlay('iframe','Forward to a friend','/content/forms/enewsletters-forward.php?prc=sub&mID='+mID,410,220);}

function eSubscribe(optType,altTitle,colType,altWidth,altHeight){
	ttl=altTitle?altTitle:(typeof eSubTitle!='undefined'?eSubTitle:'Subscribe To Our Mailing List');
	openOverlay('iframe',ttl,'/content/forms/subscription.php?prc=sub&opt='+(optType?optType:'')+(colType?'&cols='+colType:''),(altWidth?altWidth:440),(altHeight?altHeight:360));
}

function eUnsubscribe(optType,altTitle,colType,altWidth,altHeight){
	ttl=altTitle?altTitle:(typeof eUnsubTitle!='undefined'?eUnsubTitle:'Unsubscribe From Our Mailing List');
	openOverlay('iframe',ttl,'/content/forms/subscription.php?prc=unsub&opt='+(optType?optType:'')+(colType?'&cols='+colType:''),(altWidth?altWidth:440),(altHeight?altHeight:260));
}

function eSubscribeAJAX(step,op,data){
	switch(step){
		case 1:
			//make sure an email address, and name if included, are supplied
			if($("#subName_"+op).length>0 && ($("#subName_"+op).val()=='' || $("#subName_"+op).val()=='name' || $("#subName_"+op).val()=='Name')){alert("Please enter your name");$("#subName_"+op).focus();return false;}
			if($("#subFirstName_"+op).length>0 && ($("#subFirstName_"+op).val()=='' || $("#subFirstName_"+op).val()=='first name' || $("#subFirstName_"+op).val()=='First Name')){alert("Please enter your first name");$("#subFirstName_"+op).focus();return false;}
			if($("#subLastName_"+op).length>0 && ($("#subLastName_"+op).val()=='' || $("#subLastName_"+op).val()=='last name' || $("#subLastName_"+op).val()=='Last Name')){alert("Please enter your last name");$("#subLastName_"+op).focus();return false;}
			//validate the email - validateEmailv2() is found in the validator.js script, so that script must be available for this to work properly
			if($("#subEmail_"+op).length>0 && validateEmailv2($("#subEmail_"+op).val())==false){alert("Please enter a valid email address");$("#subEmail_"+op).focus();return false;}
			//submit the subscription
			if($("#subBtn_"+op).length>0){$("#subBtn_"+op).css('display','none');}
			if($("#subProcess_"+op).length>0){$("#subProcess_"+op).css('display','block');}
			em=$("#subEmail_"+op).length>0?$("#subEmail_"+op).val():'';
			fn=$("#subName_"+op).length>0?$("#subName_"+op).val():($("#subFirstName_"+op).length>0?$("#subFirstName_"+op).val():'');
			ln=$("#subLastName_"+op).length>0?$("#subLastName_"+op).val():'';
			dbOpt=op.split('_')[0].replace("--", "."); //alert('dbOpt='+dbOpt); //replace any double dashes with periods for submission - double dashes separate multiple subscription columns
			if($("#"+op+"_submit").length>0&&$("#"+op+"_submitting").length>0){
				$("#"+op+"_submit").css('display','none');$("#"+op+"_submitting").css('display','');
			}
			$.post("/content/forms/subscription.php",{ajax:1,prc:'subGo',opt:dbOpt,eAdd:em,firstName:fn,lastName:ln,cols:'multi'},function(html){eSubscribeAJAX(2,op,html);});
			return false;
		break;	
		case 2:
			//display the submission process response and reset the subscription form
         if(typeof eSubscribePostCustom == 'function'){eSubscribePostCustom(data);} //6-21-25 DBH - allow a custom post signup process if needed
			else{alert(data);}
			if($("#subBtn_"+op).length>0){$("#subBtn_"+op).css('display','');}
			if($("#subProcess_"+op).length>0){$("#subProcess_"+op).css('display','none');}
			if($("#subEmail_"+op).length>0){$("#subEmail_"+op).val('');}
			if($("#subName_"+op).length>0){$("#subName_"+op).val('');}
			if($("#subFirstName_"+op).length>0){$("#subFirstName_"+op).val('');}
			if($("#subLastName_"+op).length>0){$("#subLastName_"+op).val('');}
			if($("#"+op+"_submit").length>0&&$("#"+op+"_submitting").length>0){
				$("#"+op+"_submit").css('display','');$("#"+op+"_submitting").css('display','none');
			}
			return false;
		break;
	}
}

/*function validateEmail(email) { //https://stackoverflow.com/questions/46155/how-to-validate-email-address-in-javascript
	//var re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}*/
	
//function to calculate new image dimensions ## MOVE THIS TO SHARED.JS ##
function resizeRect(curW,curH,maxW,maxH){
	newSize=new Array(0,0);
	hRatio=curH/maxH;
	wRatio=curW/maxW;
	if(hRatio>wRatio){
		newSize[0]=Math.round(curW*(maxH/curH));
		newSize[1]=parseInt(maxH);
	}else{
		newSize[0]=parseInt(maxW);
		newSize[1]=Math.round(curH*(maxW/curW));
	}
	return newSize;
}

//generate an image and display it in a shadowbox overlay
function generateOverlayImg(imgPath,imgMaxW,imgMaxH,imgFolder,imgQual,imgCropW,imgCropH,noEnlarge){
	$.get("/_libs/image_output.php?output=printData&outputFolder="+imgFolder+"&maxW="+imgMaxW+"&maxH="+imgMaxH+"&quality="+imgQual+"&cropToW="+imgCropW+"&cropToH="+imgCropH+"&src="+imgPath+(noEnlarge==1?'&noEnlarge=1':''),{},
		function(html){
			iData=html.split('|');
			openOverlay('iframe','',iData[3],iData[1],iData[2],'');
		} 
	);
}

//cross browser safe mouse coordinates - basically to cover IE<9
function getMouseCoords(ev){  
	if(ev.pageX || ev.pageY){  
		return {x:ev.pageX, y:ev.pageY};  
	} else {  
		return {  
		x:ev.clientX + document.documentElement.scrollLeft,  
		y:ev.clientY + document.documentElement.scrollTop  
		};  
	}  
}

//COMMENTS CONTROL - updated 9-29-25 MOORE sites to use modern captcha, adapted from _form.php
//recapVers and recapKey used below are set in comments.php
function commentsRecapInit(){//console.log('grecapInit');
   grecapEle=$('#fbRecaptchaContainerInv')[0];
   grecaptcha.render(grecapEle, {
      'sitekey' : recapKey,
      'size' : 'invisible',
      //'badge' : 'inline',
      'callback' : function(token){
         if(!token){submitComments('Sorry, your submission has expired. Please try again',2);}
         else{commentsRecapValidate(token);}
      }
   });
}
function commentsRecapValidate(grtoken){ console.log('commentsRecapValidate');
   hashStr=typeof recapStr!='undefined'?recapStr:'123321';
   $.post('/_libs/recaptcha_verify.php?rcv='+recapVers,{gresponse:grtoken,hashret:1,ghash:hashStr},
      function(ret){console.log('validate ret: '+ret);
         ret=ret.split('|'); recapHsh=ret[1]; console.log('recapHsh: '+recapHsh);
         submitComments(ret[0],2);
      }
   );
}
var cmtData={};
function submitComments(data,step,table,cID,ckCaptcha,toggleInput){console.log('submitComments, data: '+data+', step: '+step);
	//alert('submit comments, step '+step);	
   if(step==1){
      ckCaptcha=ckCaptcha==1&&typeof recapKey!='undefined' && typeof recapVers!='undefined'?1:0;
      cmtData.table=table;
      cmtData.cID=cID;
      cmtData.ckCaptcha=ckCaptcha;
      cmtData.toggleInput=toggleInput;
   }else{
      cID=cmtData.cID;
      table=cmtData.table;
      ckCaptcha=cmtData.ckCaptcha;
      toggleInput=cmtData.toggleInput;
   }
	switch(step){
		case 1:
			$("#subBtn"+cID).css('display','none');
			$("#subProcess"+cID).css('display','block');
         if(ckCaptcha==1){ console.log('ckCaptcha');
            //if using recaptcha, validate captcha data
            if(recapVers!='v2'){ console.log('captcha execute');
               grecaptcha.execute();
            }else if(recapVers=='v2' && $("#pFormCaptchaDiv").css('display')!='none'){ //do we need to check v2 display?
               if($("#g-recaptcha-response").length==0){submitComments("Captcha failed to load. Please reload the form and try again.",2);return;}
               recaptchaResponse=grecaptcha.getResponse(); //alert('recaptchaResponse: '+recaptchaResponse);
               if(recaptchaResponse==""){submitComments("Please complete the visual confirmation",2);return;}
               else{commentsRecapValidate(recaptchaResponse);}
            }
			}else{
            submitComments('valid',2,table,cID,ckCaptcha,toggleInput);
         }
			return false;
		break;	
		case 2:
			//if captcha entry is incorrect, display the error, reset the submit button and load a new captcha
			if(data!='valid'){
				alert(data); //alert("The visual confirmation was not completed correctly. Please try again.");
				$("#subBtn"+cID).css('display','block');
				$("#subProcess"+cID).css('display','none');
				if(ckCaptcha==1){grecaptcha.reset();}
			}else{
            ckObj={uc:1,tbl:table,rID:cID,cDo:'post',em:$("#em"+cID).val(),nm:$("#nm"+cID).val(),cmt:$("#cmt"+cID).val(),ttl:$("#ttl"+cID).val()};
            if(ckCaptcha==1){ckObj.capHash=recapHsh;ckObj.capStck=recapStr;}
				$.post("/_panels/admin/_comments_process.php",ckObj,
               function(retData){submitComments(retData,3);}
            );
			}
			return false;
		break;
		case 3:
			$("#subBtn"+cID).css('display','block');
			$("#subProcess"+cID).css('display','none');
			if(parseInt(data)>0){
				alert("Thank you for your comments."+(parseInt(data)==1?"\n They have been received and will be reviewed shortly.":""));
				//route differently for immediately approved comments, and moderated comments
				if(parseInt(data)==2){ //if the comment is immediately live, reload the page to show it
					//tmp=window.location.href.split('#'); window.location=tmp[0]+"#comments"; window.location.reload();
					tpl=$("#cmtTpl"+cID).clone(false).attr('id','cmt'+(new Date().getTime()));
					tpl.html(tpl.html().replace('%NAME%',$("#nm"+cID).val()));
					tpl.html(tpl.html().replace('%DATE%',(new Date().toLocaleDateString())));
					tpl.html(tpl.html().replace('%COMMENTS%',$("#cmt"+cID).val().replace(/\n/g, '<br />')));
					tpl.appendTo($('#cmtAdd'+cID));
					$("#curCmtCt"+cID).html(parseInt($("#curCmtCt"+cID).html())+1); //update the comment count
					if($("#bblCmtCt"+cID).length!=0){$("#bblCmtCt"+cID).html(parseInt($("#bblCmtCt"+cID).html())+1);} //update the bubble comment count if available
				}//else{ //if the comments require review, simply clear the form and hide it if requested
				$("#em"+cID).val(''); $("#nm"+cID).val(''); $("#cmt"+cID).val('');
				if(ckCaptcha==1){grecaptcha.reset();} 
				if(toggleInput==1){toggleContDiv('ac'+cID,'ADD COMMENT','','CANCEL COMMENT','','',300,0);}
			}else{
            err=data!='0'?data:"Sorry, your comments could not be submitted. Please try again.";
				alert(err);
			}
		break;
	}
}

//SHADOWBOX OVERLAY CONTROL
var sbContent=""; //variable to hold current shadowbox content path

function openOverlay(oPlayer,oTitle,oContent,oWidth,oHeight,pgHash){
	//set defaults for any missing arguments
	if(typeof oPlayer=='undefined' || oPlayer==0){oPlayer='iframe';}
	if(typeof oTitle=='undefined' || oTitle==0){oTitle='';}
	if(typeof oContent=='undefined' || oContent==0){oContent='';}
	if(typeof oWidth=='undefined' || oWidth==0){oWidth=700;}
	if(typeof oHeight=='undefined' || oHeight==0){oHeight=525;}

	//if the current page is under https and we're opening an iframe, make sure the iframe is also under https
	if(oPlayer=='iframe' && httpsPg==1 && oContent.indexOf('https')==-1){oContent+=(oContent.indexOf('?')==-1?'?':'&')+'https=1';}
	//indicate that this is an overlay page
	if(oPlayer=='iframe' && oContent.indexOf('/')==0){oContent+=(oContent.indexOf('?')==-1?'?':'&')+'olpg=1';}
	//update browser URL has if required
	if(typeof top.curURL!='undefined' && typeof pgHash!='undefined' && pgHash!='' && pgHash!=0 && (typeof alwaysSkipGoPage=='undefined'||alwaysSkipGoPage==0)){
		if(pgHash==1){pgHash=encodeURIComponent(oContent).replace(/\./g, '%2E')+'.'+oWidth+'.'+oHeight;}
		top.goPage(top.curURL+'#ol.'+pgHash);
	}

	//redirect YouTube videos to use new inline overlay system, which allows greater control and autoplay on desktop 
	//if(mobileOrTabletDevice!=1 && inAdminCMS!=1 && oPlayer=='iframe' && oContent.indexOf('youtube.com/embed')!==-1){
   if(mobileOrTabletDevice!=1 && inAdminCMS!=1 && oPlayer=='iframe' && oContent.indexOf('youtu')!==-1){
		ytLink=oContent.split('?'); //only send the bare URL - parameters will be managed in the media_embed script
		mWidth=oWidth?oWidth:(vWidthHD?vWidthHD:960);
		mHeight=mWidth*.5625; //use youtube standard aspect ratio regardless of supplied height
		$("#flPopDiv").addClass("popMedia");
		flPad=parseInt($("#flPopDiv #flPopContentDiv").css('paddingLeft'))*2; //include any content padding in the total width value for the overlay window - css 'padding' DOES NOT WORK in FIREFOX, must be side contextual
		flPopWidth=flPad+mWidth; //console.log('showPopDiv');
		showPopDiv('fl','','','','',1,(mobileOrTabletDevice==1?0:1),'',1,'/_libs/media_embed.php?ret=overlay&html5player=1&autostart=1&src='+encodeURIComponent(ytLink[0])+'&tp=youtube&ht='+mHeight+'&wt='+mWidth+'&pop=fl&ttl='+encodeURIComponent(oTitle),flPopWidth);
		return;
	}
		
	toggleBkgdVideoPlay('stop');
	
	//if the current player is swf, and the file is an MP3 file, AND we're on a mobile device, play the media directly
	if(oPlayer=='swf' && mobileOrTabletDevice==1 && oContent.indexOf('.mp3')!=-1 /*oContent.indexOf('dewplayer')!=-1 appleDevice==1*/){
		mp3PathStart=oContent.indexOf('mp3=');
		mp3PathEnd=oContent.indexOf('.mp3');
		var mp3Path=oContent.substring(mp3PathStart+4,mp3PathEnd+4);
		top.location.href=mp3Path;
		return;
	}

	//if this is a Youtube or Video video, attempt to maintain the requested aspect ratio if the window is smaller than the provided width or height
	if(oContent.indexOf('youtu')!=-1||oContent.indexOf('vimeo')!=-1){
		//https://developers.google.com/youtube/iframe_api_reference - NO WAY TO AUTOSTART ON MOBILE
		//if(oContent.indexOf('youtu')!=-1){oContent=oContent.replace('/embed/','/watch?v=');/*console.log(oContent);return;*/}
		//if(mobileOrTabletDevice==1){top.location.href=oContent;return;} //directly play the video if on a mobile device and do not open the overlay
		if($(window).width()<oWidth||$(window).height()<oHeight){ //RESIZING UPDATED 2-3-22 - DBH
			hRatio=oHeight/$(window).height();
			wRatio=oWidth/$(window).width();
			if(hRatio>wRatio){
				oWidth=Math.round(oWidth*($(window).height()/oHeight));
				oHeight=$(window).height();
			}else{
				oHeight=Math.round(oHeight*($(window).width()/oWidth));
				oWidth=$(window).width();
			}
			//console.log(oHeight+','+oWidth);
		}
		/*if($(window).width()<oWidth||$(window).height()<oHeight){ //DOESN'T WORK CORRECTLY
			largestDimension=oWidth>oHeight?'w':'h';
			ratio=largestDimension=='w'?oHeight/oWidth:oWidth/oHeight;
			oWidth=largestDimension=='w'?$(window).width():$(window).height()*ratio;
			oHeight=largestDimension=='h'?$(window).height():$(window).width()*ratio;
		}*/
	}
   
	//save the currently loading content in the sbContent variable for use below
	sbContent=oContent; 
	//open overlay
	Shadowbox.open({
        player:     oPlayer,
		title:      oTitle,
		content:    oContent,
		width:      oWidth,
		height:     oHeight,
		options:	{onOpen:sbOpening,onClose:sbClosing}
	});
}

//functions to check that shadowbox content was successfully loaded, and force it to load if not - NEEDED FOR CHROME AND SHADOWBOX CONTENT THAT LOADS ON PAGE LOAD
function sbOpening(ele){setTimeout(sbOpenedCk,2000);}

function sbClosing(ele){toggleBkgdVideoPlay('play');/*console.log('shadowbox closing');*/}

function sbOpenedCk(){
	//alert($("#shadowbox_content").contents().find('html').html());
	if(sbContent.indexOf('youtu')!=-1||sbContent.indexOf('vimeo')!=-1){return;} //do not attempt to check youtube or vimeo content - cross domain restriction error
	if($("#shadowbox_content").contents().find('html').html()=='<head></head><body marginwidth="0" marginheight="0"></body>'){$("#shadowbox_content").attr('src',sbContent);}
}
	
//function to automatically close the shadowbox overlay when the playing video is completed
function closeShadowboxVid(){
	if(top.closeShadowboxInt==null || top.closeShadowboxInt==0){top.closeShadowboxInt=setInterval('closeShadowboxVid();',500);}
	vidState=shadowbox_content.getConfig().state;
	//alert('vid state='+vidState);
	if(vidState=='COMPLETED'){clearInterval(top.closeShadowboxInt);top.Shadowbox.close();}
}


//FULLY AJAX SYSTEM FOR LOADING DYNAMIC GALLERY OVERLAYS 
function lg(gID,gTable,gImg,updateURL,generateImages,sglTitle,gReset,ordByTitle){
   if(typeof gReset =='undefined'){gReset=0;}
   if(typeof ordByTitle =='undefined'){ordByTitle=0;}
   Shadowbox.clearCache();//1-17-24 NFI - always clear the cache! helps avoid unintended reopening overlay BLANK if clicking through too fast
	//load the selected gallery if needed
	gRef="gal_"+gTable+gID; gClass=$("."+gRef);
   if(gReset){//console.log('sb reset'); //1-14-24 - added for NFI em-archive to reload gallery div when new images are added via ajax
      if($('#'+gRef+'Div').length>0){$('#'+gRef+'Div').remove();/*Shadowbox.clearCache();*/}
      return;
	}else if($('#'+gRef+'Div').length>0){ //load the gallery HTML if already retrieved by ajax and available
		if(typeof gSlidePause=='undefined' || gSlidePause==0){gSlidePause=4;}
		if(gClass.length){//console.log('sb setup');
			Shadowbox.setup(gClass,{gallery:gRef,slideshowDelay:gSlidePause,continuous:true});
			gCurImages=$('#'+gRef+'Div a'); //console.log($(gCurImages).length);
			top.Shadowbox.open(gCurImages[gImg?gImg:0]);
			if(updateURL==1){goPage(top.curURL+'#gc.'+gTable+'.'+gID);}
		}
	}else{ //if gallery HTML is not yet available, load it here via ajax
      //console.log('sb generate');
		$.get("/content/pages/gallery.php?ol=1&id="+gID+"&tbl="+gTable+"&genImgs="+generateImages+(ordByTitle?"&ordByTitle=1":"")+(sglTitle?"&sglTitle="+encodeURIComponent(sglTitle):""),{},function(data){//alert('data='+data);
			if(data==""||data.indexOf('<div')!==0){
				alert('Sorry, the gallery could not be loaded.');return;
			}else{//alert(data);
				if($('#'+gRef+'Div').length>0){$('#'+gRef+'Div').remove();} //remove gallery data if it already exists 
				$("body").append(data); lg(gID,gTable,gImg); return;
			}
		});
	}
   curGalleryOL=gRef; //1-17-24 NFI - track the current or most recently opened gallery overlay ref
}

function doFakeClick(eleID,area){
	anchorObj = area=='popWin'?popWin.document.getElementById(eleID):document.getElementById(eleID);
	var evt = area=='popWin'?popWin.document.createEvent("MouseEvents"):document.createEvent("MouseEvents"); 
	evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); 
	var allowDefault = anchorObj.dispatchEvent(evt);
}

//media play function	
function mp(mFile,mTitle,mWidth,mHeight,mType,pgHash,S3,forceIframe){ //console.log('mp mFile: '+mFile+', mType: '+mType); //alert('in mp, Shadowbox='+Shadowbox);
	// ## mType KEY: 0-> SD video, 1-> HD video, 2-> audio ## //
	mType=parseInt(mType);
	if(mTitle==null){mTitle="";}
   if(S3==null){S3=0;}
	//if medida height and/or width were not sent, use the default values for audio, SD or HD content
	if(mHeight==null||mHeight==0){mHeight=(mType==2?(html5Audio==1&&noHTML5Media!=1?60:20):(mType==1||mType==3?(vHeightHD?vHeightHD:540):(vHeightSD?vHeightSD:480)));}
	if(mWidth==null||mWidth==0){mWidth=(mType==2?(html5Audio==1&&noHTML5Media!=1?360:200):(mType==3?parseInt((mHeight/16)*9):(mType==1?(vWidthHD?vWidthHD:960):(vWidthSD?vWidthSD:640))));}
   //console.log('mHeight: '+mHeight+', mWidth: '+mWidth);
	//add the standard video filepath to the mFile variable if it does not already have a path included - NOTE this is only used for non-encrypted plain text media files
	mPath=(mFile.indexOf('enc|')!=0 && mFile.indexOf('/')!=0?'/_uploads/_media_uploads/':'')+mFile; //console.log(mPath);
	//create a direct video stream if this is an apple mobile device - NOTE - DIRECT PLAY ON ANDROID DEVICES OPENS A NEW BROWSER PAGE TO PLACE AND OFFERS DOWNLOAD OPTION
	//if(mType!=2 && appleDevice==1 && mobileDevice==1 /*mobileOrTabletDevice==1)*/){ //console.log('direct play'); 
	//	$.get("/_libs/media_embed.php?",{'enc':mPath},function(dPath){top.location.href='/_libs/media_embed.php?dp='+dPath;/*console.log('/_libs/media_embed.php?dp='+data);*/});
	//	return;
	//generate HTML5 playback if available (and not disallowed)
	//}else if(noHTML5Media!=1 && ((mType!=2 && html5Video==1) || (mType==2 && html5Audio==1))){
		if(inAdminCMS==1||forceIframe==1){
			Shadowbox.open({player:'iframe',title:mTitle,content:'/_libs/media_embed.php?ret=doc&html5player=1&autostart=1&src='+encodeURIComponent(mPath)+'&S3='+S3+'&tp='+(mType==2?'audio':'video')+'&ht='+mHeight+'&wt='+mWidth,height:mHeight,width:mWidth});
		}else{ //console.log('showPopDiv');
			$("#flPopDiv").addClass("popMedia");
			flPad=parseInt($("#flPopDiv #flPopContentDiv").css('paddingLeft'))*2; //include any content padding in the total width value for the overlay window - NOTE that "padding" DOES NOT WORK IN FIREFOX - so using just one side, which does
			flPopWidth=flPad+mWidth; //console.log('mWidth: '+mWidth+', flPad: '+flPad+', flPopWidth: '+flPopWidth);
         //flPopHeight=mType==3?mHeight:0;
         showPopDiv('fl','','','','',1,(mobileOrTabletDevice==1?0:1),'',1,'/_libs/media_embed.php?ret=overlay&html5player=1&autostart=1&src='+encodeURIComponent(mPath)+'&S3='+S3+'&tp='+(mType==2?'audio':'video')+'&ht='+mHeight+'&wt='+mWidth+'&pop=fl&ttl='+encodeURIComponent(mTitle),flPopWidth);
		}
   //}
	//if pgHash was sent, then we update the Hash in the browser URL as well
	if(typeof top.curURL!='undefined' && typeof pgHash!='undefined' && pgHash!='' && pgHash!=0 && (typeof alwaysSkipGoPage=='undefined'||alwaysSkipGoPage==0)){
		top.goPage(top.curURL+'#ov.'+mType+'.'+encodeURIComponent(mFile));
	}
}

function updateCompProgBar(progData){
	//alert('updateCompProgBar, progData= '+progData);
	progData=progData.split('|');
	//if compData[0]>=100 then reload the page - but ONLY if a popWin is not open
	if(parseInt(progData[0])>=100 && popWin==0){
		//alert('refresh panel');
		top.refreshPanel(); //setTimeout("top.refreshPanel()",1500);
	}else{
		//otherwise update the progress bar
		$("#uploadProgBar_"+progData[1]).progressCtrl(parseInt(progData[0]));
	}
}

function firstCharUpper(txt){
	return txt.substr(0,1).toUpperCase()+txt.substr(1);
}

function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function addInputField(col){
	if(popWin.$('#'+col+'Inputs')!=null){
		popWin[col+'Ct']++;
		addHTML='<div style="padding:3px 0px 3px 30px;"><nobr><span class="bodySmallPlain">'+popWin[col+'Label']+' '+popWin[col+'Ct']+':</span> ';
		addHTML+='<input type="text" name="'+col+'_'+popWin[col+'Ct']+'" id="'+col+'_'+popWin[col+'Ct']+'" value="" style="width:440px;" /></nobr></div>';
		popWin.$('#'+col+'Inputs').append(addHTML);
		//also increment the input line count tracking hidden input variable
		//alert(popWin.$('#inputCt__'+col).attr('value'));
		popWin.$('#inputCt__'+col).attr('value',popWin[col+'Ct']);
		//alert(popWin.$('#inputCt__'+col).attr('value'));
	}
}

function jqueryScroll(anchorID,speed,showPageHash){
	if(speed==null){speed=800;}
	$.scrollTo('#'+anchorID,speed,{easing:'easeInOutQuart',axis:'y',onAfter:function(){if(showPageHash==1){goPage('#'+anchorID);}}});
}

function goPage(page){
	//window.top.location=page;
	window.location=page;
}

function assocUpdate(frameID,inputID,area){
	//alert('in assocProdUpdate');
	pathPrefix=getPathPrefix(area,1);
	framePrefix=getPathPrefix(area,0);
	assocString="";
	items=framePrefix.frames[frameID].document.getElementsByTagName('input');
	for(i=0;i<items.length;i++){
		if(items[i].checked){
			//tilda separate values
			if(assocString!=""){assocString+="~";}
			assocString+=items[i].name;
		}
	}
	//alert(assocString);
	//alert(pathPrefix.tableForm[inputID]);
	//now attach any value found for associated items to the database input variable
	pathPrefix.tableForm[inputID].value=assocString;
	return true;
}

function leaveDiv(e,divName) {
if (!e) var e = window.event;
var tg = (window.event) ? e.srcElement : e.target;
if (tg.nodeName != 'DIV'){return;}
//now work backwards from the current target to make sure we arent in a sub object from the actual target div
var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
while (reltg != tg && reltg.nodeName != 'BODY'){
	reltg= reltg.parentNode;
	if (reltg== tg){return;}
}
// Mouseout took place when mouse actually left layer
// Handle event
//alert('mouse out of div');
//hidediv("dropdown_menu");//another fx that works fine
toggleDivVisible(divName,0)
}


function toggleDivShow(divName,animDur){
	//alert('in toggleDivShow'); 
	if(divObj=findObjectPath(divName)){
		displayChange = (divObj.style.display == 'none') ? 'block' : 'none';
		divObj.style.display=displayChange;
		fixIEBug();
	}
}	

function toggleDivVisible(divName,direction){
	//alert('in toggleDivVisible'); 
	if(divObj=findObjectPath(divName)){
		//alert(divObj);
		if(direction=='1'){divObj.style.display='block';}
		if(direction=='0'){divObj.style.display='none';}
		fixIEBug();
	}
}


function toggleTransp(objName,direction){
	if(obj=findObjectPath(objName)){
		//alert(obj.name);
		if(direction=='1'){ 
			obj.setAttribute("class", "semiTransparent");
			obj.setAttribute("className", "semiTransparent");
		}
		if(direction=='0'){
			obj.setAttribute("class", "opaque");
			obj.setAttribute("className", "opaque");
		}
	}
}


function assocListUpdate(colName,area){
	//alert('in assocListUpdate');
	pathPrefix=getPathPrefix(area,1);
	framePrefix=getPathPrefix(area,0);
	assocString="";
	//assocList=framePrefix.frames['iframeList_'+colName].document.getElementsByTagName('input');
	alert(framePrefix.frames[colName+'_iframe'].document);
	assocList=framePrefix.frames[colName+'_iframe'].document.getElementsByTagName('input');
	for(i=0;i<assocList.length;i++){
		if(assocList[i].checked){
			//tilda separate values
			if(assocString!=""){assocString+="~";}
			assocString+=assocList[i].name;
		}
	}
	//alert(assocString);
	//alert(pathPrefix.tableForm['db__'+colName]);
	//now attach any value found for associated items to the hidden input element for this variable
	pathPrefix.tableForm['db__'+colName].value=assocString;
	//alert(pathPrefix.tableForm['db__'+colName].value);
	return true;
}


function toggleOpenNavFS(togVal){
	openFSobj=findObjectPath('openNavFS');
	//alert(openFSobj);
	if(openFSobj!=null){openFSobj.value=togVal;}
}


function updateTabState(navTab,newFlag,updateNav){
	//alert('in updateTabState, navTab='+navTab+" newFlag="+newFlag);
	//this function allows javascript to update the tabFlag entry in the navMainData array
	navTabs=navTab.split("__");
	for(i=0;i<navMainData.length;i++){
		if((navObj=findObjectPath(navMainData[i][1],'navTop')) && (navMainData[i][1]==navTabs[0])){
			//the nav tab was found, so update the tabFlag
			navMainData[i][4]=newFlag;
			//now update the nav bar, and exit the function
			if(updateNav){
				if(navObj && navMainData[i][4]=='dead'){
					navObj.className='headerNavDead';
				}else if(navObj && navMainData[i][4]=='done'){
					navObj.className='headerNavDone';
				}
			}
			break;
		}
	}
}


function goNavFrame(navTab,filePath,updateNav,linkVars){
	//alert('in goNavFrame');
	//navMainData and navSubData are arrays created by the navTop.php script - curAccessArea holds the current accessArea name
	decision=true;
	//first see if there are any warnings or pre-processing required for the area we are GOING TO
	switch(navTab){
		case "adminPanels":
			//reset the default admin panel for initial display
			//if(defAdminPanel==null){defAdminPanel=0;}
			if(defAdminObj=findObjectPath("defAdminPanel",'navTop')){parseInt(defAdminPos=defAdminObj.value);}else{defAdminPos=0;}
			//if(selectObj=findObjectPath('panelList','navTop')){selectObj.options[defAdminPanel].selected=1;}
			if(selectObj=findObjectPath('panelList','navTop')){selectObj.options[defAdminPos].selected=1;}
			if(addRecsObj=findObjectPath('addRecords','navTop')){addRecsObj.style.display='none';}
			//update the default top panel controls for this new admin panel
			//top.switchPanels(1);
		break;
	}
	//alert('next step');
	//next see if there are any warnings or pre-processing required for the area we are LEAVING (curAccessArea is the CURRENTLY LIVE TAB)
	//alert(curAccessArea.indexOf('cciModules'));
	switch(curAccessArea){
		case "posasap":
		case "marketingMaterials__posasap":
			decision=confirm('Are you sure you want to leave P.O.S. ASAP?\nAny unsaved changes will be lost.');
		break;
	}
	if(curAccessArea.indexOf('cciModules')==0){
		decision=confirm('Are you sure you want to leave the current training module?');
	}
	//if the user didnt click cancel on an option dialog above, continue here
	if(decision==true){
		navArrayLoc=0;
		navTabs=navTab.split("__");
		//reset main and sub nav
		if(updateNav==1){
			titleObj=findObjectPath('navTitle','navTop');
			titleObj.innerHTML="";
			//subTitleObj=findObjectPath('navSubTitle','navTop');
			//subTitleObj.innerHTML="";
			//alert(navTabs[0]);
			//alert(navMainData.length);
			for(i=0;i<navMainData.length;i++){
				//toggle the sub nav if it exists
				if((subObj=findObjectPath(navMainData[i][1]+"_sub",'navTop')) && (navMainData[i][1]+"_sub"==navTabs[0]+"_sub")){
					subObj.style.display='block';
					subObj.className='headerSubMenu';
					//also set the correct sub menu link hilighting
					for(ii=0;ii<navSubData[navArrayLoc].length;ii++){
						if((subLinkObj=findObjectPath(navSubData[i][ii],'navTop')) && (navTab==navSubData[i][ii])){
							//alert('found sub');
							subLinkObj.className='headerSubLive';
							//update the sub title as well
							//subTitleObj.innerHTML='&nbsp;&#x203a; '+subLinkObj.innerHTML;
						}else if(subLinkObj){
							subLinkObj.className='headerSub';
						}
					}
				}else if(subObj){
					subObj.style.display='none';
					subObj.className='offScreen';
				}
				//toggle the main nav if it exists
				if((navObj=findObjectPath(navMainData[i][1],'navTop')) && (navMainData[i][1]==navTabs[0])){
					//capture the array position of this nav item
					navArrayLoc=i;
					//insert the correct title 
					titleObj.innerHTML=navMainData[navArrayLoc][3];
					//setup the correct CSS class
					navObj.className='headerNavLive';
				}else if(navObj && navMainData[i][4]=='dead'){
					navObj.className='headerNavDead';
				}else if(navObj && navMainData[i][4]=='done'){
					navObj.className='headerNavDone';
				}else if(navObj){
					navObj.className='headerNavLink';
				}
			}
		}
		//save the new accessArea variable
		curAccessArea=navTab; goString="";
		//now go to the requested nav frame
		if(filePath=='useRouter'){
			goString='/_libs/access_router.php?accessArea='+navTab+"&";
		}else if(filePath!=null && filePath!=''){
			goString=filePath+"?";
		}
		//add any GET link variables we need to pass along (mm_index uses this)
		if(linkVars!=null){goString+=linkVars;}
		//finally GO FORTH!.. unless filePath==none, in which case we simply wanted to update the nav
		//alert('goString='+goString);
		if(filePath!='none'){window.top.bottomFrame.location=goString;}
	}
}


function checkPopSize(){resizePopup(1,1,0,0,'modifyTable');}


function resizePopup(resizeHeight,resizeWidth,forceHeight,forceWidth,resizeObj){
	//popWin.alert('resizeHeight='+resizeHeight+" resizeWidth="+resizeWidth);
	//if height or width force sizing was sent, use that
	if(resizeHeight==1 || resizeWidth==1){
		//if(typeof popWin.$ != 'undefined'){
		//	h=popWin.$('#modifyTable').height(); w=popWin.$('#modifyTable').width();
		//	h=popWin.$('#modifyTable').height(); w=popWin.$('#modifyTable').width();
		//}else{
		if(resizeObj!=null){refObj=resizeObj;}else{refObj='contentDiv';}
		divObj=findObjectPath(refObj,'popWin');
		h=divObj.offsetHeight; w=divObj.offsetWidth;
		//}
		//force the width or height if requested
		if(forceHeight!=null && forceHeight!=0){h=forceHeight;}
		if(forceWidth!=null && forceWidth!=0){w=forceWidth;}
		//enlarge the popup size - IE and FF require the large vertical extension - camino and safari could go with half or less of this amount
		//the horizontal extension is mostly for IE, but all benefit visually from a little more horizontal space
		//popWin.alert('popWin_h:'+popWin_h+', h:'+h);
		if(popWin_h>=(h+40)){resizeHeight=0;}else{h+=120;}
		if(popWin_w>=w){resizeWidth=0;}else{w+=40;} 
		//dont let the height get larger than the screen height or width minus 46
		//NOTE that if we have to reduce size in one dimension, enlarge the other dimension a bit to compensate for appearance of the resized dimension's scroll bar
		if(h>(screen.height-40)){h=screen.height-46;w+=35;}
		y=Math.round((screen.height - h)/2);
		if(w>(screen.width-40)){w=screen.width-46;h+=35;}
		x=Math.round((screen.width - w)/2);
		//now resize and reposition the popup window - ONLY continue if the new popwin width or height is different than the saved value
		if(resizeHeight==0){y=popWin_y;h=popWin_h;}
		if(resizeWidth==0){x=popWin_x;w=popWin_w;}
		popWin.moveTo(x,y)
		popWin.resizeTo(w,h);
		//save the current x,y,h & w
		popWin_x=x, popWin_y=y, popWin_h=h, popWin_w=w;
	}
	return
}


function calcHeight(){
  //find the height of the internal page
  var the_height=document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;
 //change the height of the iframe
  document.getElementById('the_iframe').height=the_height;
}


function existingFileDownload(checkName,curFile,area){
	//if there is an image select menu for this checkName, then use its value for download, otherwise
	if(selectList=findObjectPath(checkName+"__select",area)){
		//alert('select list found');
		newFile=selectList.options[selectList.selectedIndex].value;
		//if the selection in the select menu has a value, then use it as the download image
		if(newFile!=""){curFile=newFile;}
	}
	location.href='/_libs/file_download.php?fcdwn=1&src='+curFile;

}


function toggleUnderline(checkName,toggle,area){
	if(textObj=findObjectPath(checkName,area)){
		switch(toggle){
			case 'over':
				textObj.style.textDecoration='underline';
				break;
				
			case 'norm':
				textObj.style.textDecoration='none';
				break;
		}
	}
}


function fileSelectStart(checkName,area){
	//function to automatically move a select list to a given entry based upon text found in the startField - good for moving around in huge select lists
	//alert('in fileSelectStart');
	selectList=findObjectPath(checkName+"__select",area);
	startField=findObjectPath("fileSelectStart",area);
	if(selectList!=null && startField!=null && selectList.selectedIndex==0 && startField.value!=""){
		//NOTE - if startField.value=="useCustomSelectStart", then call the customSelectStart function found in the site.js script
		if(startField.value=="useCustomSelectStart"){
			customSelectStart(checkName,area);
		}else{
			//alert('ok to reposition');
			for(ii=0;ii<selectList.options.length;ii++){
				if(selectList.options[ii].value.indexOf(startField.value)!=-1){
					//alert('found match');
					selectList.selectedIndex=ii-1;
					break;
				}
			}
		}
	}
}


function restrictSelect(checkName,area){
	//function to automatically restrict a list selection to selections whose value includes the value of the startField
	//alert('in fileSelectStart');
	selectList=findObjectPath(checkName+"__select",area);
	startField=findObjectPath("fileSelectStart",area);
	if(selectList && startField && selectList.selectedIndex!=0 && startField.value!=""){
		if(selectList.options[selectList.selectedIndex].value.indexOf(startField.value)==-1){
			selectList.selectedIndex=0;
		}
	}
}


function toggleFileDisplay(checkName,toggle,area,arg4,arg5){
	//alert('in toggleFileDisplay, checkName='+checkName);
	//get the file type, if there is one
	//alert('in toggleFileDisplay');
	if(fileType=findObjectPath(checkName+"__fType",area)){fType=fileType.value;}else{fType='file';}
	showFile="";hidePreview=0;
	switch(toggle){
		case "select":
			//reset the file upload, if there is one
			if(fileUpload=findObjectPath(checkName+"__new",area)){fileUpload.value="";}
			//reset remove checkbox if there is one
			if(removeBox=findObjectPath(checkName+'__remove',area)){removeBox.checked=0;}
			//modify the selection if needed
			if(selectList=findObjectPath(checkName+'__select',area)){
				selectFile=selectList.options[selectList.selectedIndex].value;
				if(selectFile==""){
					//if there is no saved image, set status to 'no image', otherwise revert to the saved image
					if(savedFile=findObjectPath(checkName+"__saved",area)){
						toggleFileDisplay(checkName,'saved',area);
						//revertToSaved(checkName,area);
					}else{
						//update the image status if there is one
						changeText('statDiv_'+checkName,'(no&nbsp;'+fType+')','#830000',area);
						showFile='/_images/shared/_xc_image_noUpload.jpg';
						hidePreview=1;
					}
				}else{
					//if the current selected image matches the saved image, say 'image ok', otherwise say 'new selection'
					if((savedFile=findObjectPath(checkName+"__saved",area)) && (savedFile.value==selectFile)){
						toggleFileDisplay(checkName,'saved',area);
					}else{
						//update the image status if there is one
						changeText('statDiv_'+checkName,'(new&nbsp;selection)','#A99228',area);
					}
				}
			}
			break;
		case "new":
			//reset the select list if there is one
			if(selectList=findObjectPath(checkName+"__select",area)){selectList.selectedIndex=0;}
			//reset remove checkbox if there is one
			if(removeBox=findObjectPath(checkName+'__remove',area)){removeBox.checked=0;}
			//update the image status if there is one
			changeText('statDiv_'+checkName,'(new&nbsp;upload)','#A99228',area);
			//show the upload image placeholder in the preview frame
			showFile="/_images/shared/_xc_image_uploadReady.jpg";
			break;
		case "remove":
			if(checkObj=findObjectPath(checkName+'__remove',area)){
				if(checkObj.checked==1){
					//reset the caption, if there is one
					if(fileCaption=findObjectPath("db__"+checkName+"_cap",area)){fileCaption.value="";}
					//reset the file upload, if there is one
					if(fileUpload=findObjectPath(checkName+"__new",area)){fileUpload.value="";}
					//reset file rename, if there is one
					if(fileRename=findObjectPath(checkName+"__rename",area)){fileRename.value="";}
					//reset the select list if there is one
					if(selectList=findObjectPath(checkName+"__select",area)){selectList.selectedIndex=0;}
					//update the image status if there is one
					changeText('statDiv_'+checkName,'(remove&nbsp;'+fType+')','#A99228',area);
					//show the upload image placeholder in the preview frame
					showFile="/_images/shared/_xc_image_remove.jpg";
					hidePreview=1;
				}else{
					//revert to the saved image (remove button wouldn't be available if there wasn't one)
					toggleFileDisplay(checkName,'saved',area);
					//revertToSaved(checkName,area);
				}
			}
			break;
		case "saved":
			//reset the file upload, if there is one
			if(fileUpload=findObjectPath(checkName+"__new",area)){fileUpload.value="";}
			//reset remove checkbox if there is one
			if(removeBox=findObjectPath(checkName+'__remove',area)){removeBox.checked=0;}
			//make sure we havge a saved image before continuing
			if(savedFile=findObjectPath(checkName+"__saved",area)){
				//if there is a select list, move it to the position of the saved image
				selectList=findObjectPath(checkName+"__select",area);
				//there may be a selectList input that IS NOT actually a select list, so determine that here
				if(selectList!=null){
					if(selectList.options!=null){
						//find the saved image in the list - then update the list to reflect that image and break out of the for loop
						for(ii=0;ii<selectList.options.length;ii++){
							if(selectList.options[ii].value==savedFile.value){selectList.selectedIndex=ii;break;}
						}
					}
				}
				//use the saved image in the image preview
				showFile=savedFile.value;
				//update the image status if there is one
				changeText('statDiv_'+checkName,'('+fType+'&nbsp;ok)','#174917',area);
			}
			break;
		case "matchField":
			//NOTE - this is currently incompatible with popups wherein the image list is available as a select list BECAUSE in those cases, the javascript image list is not created
			//alert(checkName+"__array");
			//if(selectList=findObjectPath(checkName+'__select',area)){selectList.value="";}
			fileArray=checkName+"__array";
			//if a file upload is selected, ignore this whole sectiontoggleContDiv
			if((fileUpload=findObjectPath(checkName+"__new",area)) && (fileUpload.value!="")){return;}
			//now search for file matches
			if((fieldObj=findObjectPath(arg4,area)) && (popWin[fileArray]!=null)){
				fieldText=fieldObj.value;
				for(inc in popWin[fileArray]){
					basename=popWin[fileArray][inc].split("/");
					filename=basename[basename.length-1];
					basename=filename.substr(0,filename.length-4);
					//check for a file match - use the arg5 suffix if sent
					if(arg5==null){arg5="";}
					if((fieldText+arg5)==basename){
					 	//alert('found match');
						showFile=popWin[fileArray][inc];
						changeText('statDiv_'+checkName,'('+fType+'&nbsp;ok)','#174917',area);
						changeText('dispFileName_'+checkName,' : '+filename,'#000000',area);
						//reset the file upload, if there is one
						if(fileUpload=findObjectPath(checkName+"__new",area)){fileUpload.value="";}
						if(removeImage=findObjectPath(checkName+"__remove",area)){removeImage.value="0";}
						if(selectList=findObjectPath(checkName+'__select',area)){selectList.value=showFile;}
						break;
					}
				}
				//if no matching file was found, change thte title accordingly
				if(showFile==""){
					changeText('statDiv_'+checkName,'(no&nbsp;'+fType+')','#830000',area);
					changeText('dispFileName_'+checkName,'','#000000',area);
					if(removeImage=findObjectPath(checkName+"__remove",area)){removeImage.value="1";}
					if(selectList=findObjectPath(checkName+'__select',area)){selectList.value="";}
				}
				break;
			}
			break;
	}	
	//now update the image display
	if(showFile==""){
		//only proceed if selectList exists and is in fact a list and not a hidden input
		if((selectList=findObjectPath(checkName+'__select',area)) && (selectList.type!='hidden')){
			showFile=selectList.options[selectList.selectedIndex].value;
		}else{
			showFile="/_images/shared/_xc_image_none.jpg";
		}
	}
	//alert(showFile);
	//toggle image preview visibility
	if(divObj=findObjectPath("filePrevTitle_"+checkName,area)){divObj.style.display=(hidePreview==1?'none':'block');}
	if(divObj=findObjectPath("filePrevCont_"+checkName,area)){divObj.style.display=(hidePreview==1?'none':'block');}
	if(divObj=findObjectPath("fileCapTitle_"+checkName,area)){divObj.style.display=(hidePreview==1?'none':'block');}
	if(divObj=findObjectPath("fileCapCont_"+checkName,area)){divObj.style.display=(hidePreview==1?'none':'block');}
	if(divObj=findObjectPath("cropSelWidthTitle_"+checkName,area)){divObj.style.display=(hidePreview==1?'none':'block');}
	if(divObj=findObjectPath("cropSelWidthCont_"+checkName,area)){divObj.style.display=(hidePreview==1?'none':'block');}
	if(divObj=findObjectPath("cropSelHeightTitle_"+checkName,area)){divObj.style.display=(hidePreview==1?'none':'block');}
	if(divObj=findObjectPath("cropSelHeightCont_"+checkName,area)){divObj.style.display=(hidePreview==1?'none':'block');}
	if(hidePreview!=1){
		//now see if there is an anchor tag that we should scroll to
		scrollToAnchor("anchor_"+checkName,area);
		//update the preview pane
		if(previewFrame=findObjectPath("iframe_"+checkName,area)){
			//alert('found previewFrame');
			previewFrame.src='/_libs/image_output.php?src='+showFile+'&output=thumbDoc';
		}
	}
}


function openPopPreview(checkName,area){
	//capture the popup link data from the preview iframe and use it to open the media preview popup
	if(lData=top.frames[area]["iframe_"+checkName].document.getElementById('popLink')){
		//alert(lData);
		lData=lData.toString();
		lData=lData.substring(21,lData.length-1).split(',');
		for(x in lData){lData[x]=lData[x].substring(1,lData[x].length-1);}
		goURL(lData[0],lData[1],lData[2],lData[3],lData[4],lData[5]);
	}
}


function changeText(objID,newText,newColor,area){
	//alert('toggleContDiv');
	if(divObj=findObjectPath(objID,area)){
		divObj.innerHTML=newText;
		if(newColor!=0 && newColor!=null){divObj.style.color=newColor;}
	}
}


function toggleContDiv(checkName,openName,openColor,closeName,closeColor,area,animDur,togglePrev,doNudgeScroll){ //alert(checkName+', '+openName+', '+openColor+', '+closeName+', '+closeColor+', '+area+', '+animDur+', '+togglePrev);
	//get toggle div and signal references
	togDivObj=area=='popWin'?popWin.$('#contDiv_'+checkName):$('#contDiv_'+checkName);
	togImgObj=area=='popWin'?popWin.$('#divTogSign_'+checkName):$('#divTogSign_'+checkName);
	togTxtObj=area=='popWin'?popWin.$('#divTogTitle_'+checkName):$('#divTogTitle_'+checkName);
	animDur=animDur=='none'?0:(animDur==null?400:animDur);
	isOpening=togDivObj.css('display')=='none'?1:0;
	openName=openName.split('|'); //openName may contain both a name and instructions to toggle a graphic - 'someTitleTxt|1' or 'image' will invoke toggling an image
	//first switch the signal image and/or button text
	if(togImgObj.length>0){
      if(togImgObj.hasClass('divTogAnimate')){ //added 11-4-24 DAH console.log('animate this');
         if(togDivObj.css('display')=='none'){togImgObj.addClass('divTogOpen');}else{togImgObj.removeClass('divTogOpen');}
      }else{
         //if there is an image to toggle, do that here
         if(openName.length>1 || openName[0]=="image"){//alert('toggle a graphic'); alert('togDivObj.css(display)='+togDivObj.css('display'));
            newImgPath=stringReplace(togImgObj.attr('src'),(togDivObj.css('display')=='none'?'_closed':'_open'),(togDivObj.css('display')=='none'?'_open':'_closed'));
            togImgObj.attr('src',newImgPath);
         }
      }
	}
	//check for text title to update
	if(openName[0]!="" && openName[0]!="image"){
		curTxtObj=togTxtObj.length>0?togTxtObj:togImgObj; //use the divTogTitle_ID object if we also toggled a graphic
		if(isOpening==1){
			curTxtObj.html(openName[0]);
			if(openColor!=""){curTxtObj.css(openColor=='underline'?'text-decoration':'color',openColor=='underline'?'underline':openColor);}
		}else{
			curTxtObj.html(closeName);
			if(closeColor!=""||openColor=='underline'){curTxtObj.css(openColor=='underline'?'text-decoration':'color',openColor=='underline'?'none':closeColor);}
			scrollToAnchor("anchor_"+checkName,area); //now see if there is an anchor tag that we should scroll to
		}
	}
	togDivObj.animate({opacity:(isOpening?'show':'hide'),height:(isOpening?'show':'hide')},animDur,(area=='popWin'||!doNudgeScroll?'':(isOpening?function(){nudgeScroll(checkName);}:nudgeScroll))); //add nudgeScroll callback for non-popWin opening situations
	//if togglePrev argument was sent, then, using the arguments for this item, toggle the previously opened div
	if(togglePrev==1){
		//capture any existing toggle values
		prevTogDiv=curTogDiv;
		prevTogVals=curTogVals;
		//set new toggle values
		curTogDiv=isOpening==1?checkName:0;
		curTogVals=isOpening==1?new Array(checkName,openName.join('|'),openColor,closeName,closeColor,area,animDur):new Array();
		//if previous div needs to be toggled, proceed here
		if(prevTogDiv!=0 && prevTogDiv!=checkName && isOpening==1){//alert("toggle previous");
			if(prevTogVals.length==0){prevTogVals=new Array(prevTogDiv,openName[0],openColor,closeName,closeColor,area,animDur);}
			//if(prevTogVals[0]=='trigger'){$("#title_"+prevTogDiv).trigger('click');}else{
			toggleContDiv(prevTogVals[0],prevTogVals[1],prevTogVals[2],prevTogVals[3],prevTogVals[4],prevTogVals[5],prevTogVals[6],0);//}
		}
	}
	fixIEBug();
	return isOpening; //calling script may want to know whether we are opening or closing the current div
}


function nudgeScroll(checkName){
	//dont use the nudgeScroll on mobile devices
	if(typeof(mobileDevice) !== 'undefined'){if(mobileDevice==1){return;}}
	//get document scroll top position
	docScrollTop=$(window).scrollTop();
	//check for scroll top position of the currently animated object if available
	objScrollTop=0;
	if(checkName){//alert(checkName);
		togDivObjID=$('#encloseDiv_'+checkName).length>0?'#encloseDiv_'+checkName:($('#groupDiv_'+checkName).length>0?'#groupDiv_'+checkName:($('#contDiv_'+checkName).length>0?'#contDiv_'+checkName:''));
		if(togDivObjID){
			togDivObjPos=$(togDivObjID).offset();
			objScrollTop=parseInt(togDivObjPos.top);
		}
	}
	//move page position if needed to show top of newly opened object
	if(objScrollTop>0 && objScrollTop<docScrollTop){
		//alert(objScrollTop+' is less than '+docScrollTop);
		$(window).scrollTo(objScrollTop,300,{easing:'easeInOutQuad','axis':'y',onAfter:function(){}});
	}else{ //moving the vertical scroll position by a pixel helps remove artifacts that sometimes appear when browser needs to scroll up - 4/18/19 - IS THIS NEEDED ANYMORE?
		window.scrollTo(0,docScrollTop-1);
		window.scrollTo(0,docScrollTop);  //can we instantly move back to original position and still have the clean-up effect?
	}
}


//function to scroll document to a given anchor
function scrollToAnchor(anchorName,area){
	//alert(anchorName);
	//if(anchorObj=findObjectPath(anchorName,area)){
	anchorObj=findObjectPath(anchorName,area);
	if(anchorObj!=null && anchorObj!=""){
		//get the correct pathprefix
		pathPrefix=getPathPrefix(area,0);
		//NOTE that the getAnchorPosition script must be directly linked to whatever page is specified in the pathprefix 
		//(ie, popwin must have this script directly attached)
		scrollCoords=pathPrefix.getAnchorPosition(anchorName);
		//find the actual height of the popWin
		if(pathPrefix.innerHeight){
			frameHeight = pathPrefix.innerHeight;
		}else if(pathPrefix.document.documentElement && pathPrefix.document.documentElement.clientHeight){
			frameHeight = pathPrefix.document.documentElement.clientHeight;
		}else if(pathPrefix.document.body){
			frameHeight = pathPrefix.document.body.clientHeight;
		}
		//grab the current scroll position
		//scrollx = (pathPrefix.document.all)?pathPrefix.document.body.scrollLeft:pathPrefix.pageXOffset;
  		scrolly = (pathPrefix.document.all)?pathPrefix.document.body.scrollTop:pathPrefix.pageYOffset; 
		//now, if the desired anchor is below the window height, scroll down just enough to reveal that anchor
		if((frameHeight+scrolly)<scrollCoords.y){
			//alert('scrolly='+scrolly+' frameHeight='+frameHeight+' scrollCoords.y='+scrollCoords.y);
			pathPrefix.scrollTo(0,(scrollCoords.y-frameHeight)+10);
		}
	}
}


function triggerDateFilter(dateName,area){
	pathPrefix=getPathPrefix(area,1);
	radioSet=pathPrefix.forms['tableForm']['filter__'+dateName+'__dateRange'];
	//radioSet=findObjectPath('filter__'+dateName+'__dateRange',area);
	for(inc=0;inc<radioSet.length;inc++){
		if(radioSet[inc].value=='range'){radioSet[inc].checked=1;break;}
	}
}


function resizeOuterTo(w,h) {
 if (parseInt(navigator.appVersion)>3) {
   if (navigator.appName=="Netscape") {
    top.outerWidth=w;
    top.outerHeight=h;
   }
   else top.resizeTo(w,h);
 }
}


function checkChars(checkText,formCall){
//now check for illegal characters
	//charList=Array("~","$","&","?","@","\"","\\","�","�","�","�");
	charList=Array("~","$","&","?","@","\"","\\","�","i","�");
	for(i=0;i<charList.length;i++){
		if(checkText.indexOf(charList[i])!=-1){
			alert("Sorry, your text cannot contain the "+charList[i]+" character.");
			if(formCall){
				return false;
			}else{
				return;
			}
		}
	}
}

function fixIEBug(){
	//alert("in fixIEDbug")
	///Defeat IE6 fixed bug by opening and closing the last div
	if(x = document.getElementById('defeatIEBug')){
		currentStyle = x.style.display;
		newStyle = (currentStyle == 'none') ? 'block' : 'none';
		x.style.display = newStyle;
		x.style.display = currentStyle;
	}
	return;
}

function goURL(url,target,popWidth,popHeight,resize,scrollbars,escapeParams) {//console.log('url: '+url+', popWidth: '+popWidth+', popHeight: '+popHeight);
	if(escapeParams!=null){url+=encodeURIComponent(escapeParams);}
	//create the popup according to indended target
	switch(target){
		case 'top':
			window.location=url;
			break;
		case 'popup':
			//alert('here');
			//only a 'popup' target gets assigned the popWin variable, other popups (media previews, etc) are NOT tracked, as an open popWin may spawn those requests
			closePopup();
			popWin=0; popWin_h=0; popWin_w=0;
		case 'previewPop':
		case 'img_pop':
		case 'subPop':
			//set variable defaults
			if(!resize){resize=1;}
			if(!scrollbars){scrollbars=0;}
			if(!popWidth){popWidth=400;}
			if(!popHeight){popHeight=400;}
			var winLeft=parseInt((screen.width - popWidth)/2);
			var winTop=parseInt((screen.height - popHeight)/2);
			//alert('width=' + popWidth + ',height=' + popHeight + ',left=' + winLeft + ',top=' + winTop + ',resizable=' + resize +',scrollbars=' + scrollbars);
			tempWin=window.open('','','width=' + popWidth + ',height=' + popHeight + ',left=' + winLeft + ',top=' + winTop + ',resizable=' + resize +',scrollbars=' + scrollbars);
			if(target=="img_pop"){
				//img pops have a special setup here
				tempWin.document.write('<html><head><title>Image Window</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>');
				tempWin.document.write('<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">');	
				tempWin.document.write('<table id="imageTable" width="100%" height="100%" border="0" cellpadding="0" cellspacing="0"><tr><td align="center" valign="middle">');
				tempWin.document.write('<img src="'+url+'"><br /><img src="/_images/spacer.gif" width="1" height="10"><br />');
				tempWin.document.write('<input type="button" name="close" id="close" value="Close Window" onClick="JavaScript:window.close();" /></td></tr></table></body></html>');
			}else{
				//any other popup type, simply apply the sent URL
				tempWin.location=url;
			}
			tempWin.focus();
			//only set the popWin variable for a popup target
			if(target=="popup"){popWin=tempWin;}
			break;
	}
}


function clearFilter(area){
	//alert("in clearFilter, area="+area);
	//DONT CAPTURE THE OPEN DIVS - WANT THEM TO BE CLOSED WHEN PAGE IS RELOADED
	//openDivList=captureOpenDivs(area);
	pathPrefix=getPathPrefix(area,0);
   if(pathPrefix.document.getElementById('filterLoadingContainer')){
      pathPrefix.document.getElementById('filterLoadingContainer').style.display='block';
      pathPrefix.document.getElementById('filterActionContainer').style.display='none';
   }
	goAction=pathPrefix.document.tableForm.action;
	obj=findObjectPath("useSavedFilters","navBottom");
	if(obj){obj.value=0;}
	//SKIP THE SUBMIT ACTION, AND THUS RESET THE FILTERS
	//pathPrefix.location.href=goAction+"?curPage=1&newFilters=1&openDivs="+openDivList;
	pathPrefix.location.href=goAction+"?curPage=1";
}


function filterRecords(area,xlsOutput,customXLS,xlsDataColsOnly,xlsArgs,forcePage){
	//alert("in filterRecords, area="+area);
	pathPrefix=getPathPrefix(area,1);
   captureOpenDivs(area);
   //show loading button
   if(pathPrefix.getElementById('filterLoadingContainer')){
      pathPrefix.getElementById('filterLoadingContainer').style.display='block';
      pathPrefix.getElementById('filterActionContainer').style.display='none';
   }
	//setup filter tableForm action - add the xlsOutput variables if requested
	saveAction=pathPrefix.tableForm.action;
	saveTarget=pathPrefix.tableForm.target;
   newAction=pathPrefix.tableForm.action+"?curPage=1&newFilters=1"+(xlsOutput?"&xlsOutput="+xlsOutput+"&customXLS="+customXLS+"&xlsDataColsOnly="+xlsDataColsOnly+(xlsArgs?"&xlsArgs="+xlsArgs:""):"");
   //4-26-23 TLC HR - open a new page to show resulting HTML page - NOTE for this to work the current page filters must ALREADY allow viewing XLS output as a webpage
	if(xlsOutput && pathPrefix.getElementById('fExt_pg')!= null && (forcePage==1 || pathPrefix.getElementById('fExt_pg').checked)){
      pathPrefix.getElementById('fExt_pg').checked=1;
      pathPrefix.tableForm.target="_blank";
      //NOTE - adding the fExt DOES NOT mean that a spreadsheet page will be shown for the current panel EVERY TIME - to create a durable URL, the following URL would have to be used with all search criteria in the GET parameters
      //<site>/_panels/scripts/_xls_filters.php?curPanel=<panel>&fExt=pg<filters>
      newAction+='&fExt=pg';
   } 
   //process form submission & reset submit values
   pathPrefix.tableForm.action=newAction;
   pathPrefix.tableForm.submit();
   pathPrefix.tableForm.action=saveAction;
   pathPrefix.tableForm.target=saveTarget
   //reset filter buttons if xls output (no page reload)
   if(xlsOutput && pathPrefix.getElementById('filterLoadingContainer')){
      setTimeout(function(){
      pathPrefix.getElementById('filterLoadingContainer').style.display='none';
      pathPrefix.getElementById('filterActionContainer').style.display='block';
      },2500);
   }
}


function flipPage(selectList,area,goPage){
//alert("in flipPage, area="+area+" selectList="+selectList);
	captureOpenDivs(area);
	pathPrefix=getPathPrefix(area,1);
	//alert(pathPrefix.tableForm.action);
	goAction=pathPrefix.tableForm.action;
	if(!goPage){goPage=pathPrefix.tableForm[selectList].options[pathPrefix.tableForm[selectList].selectedIndex].text;}
	pathPrefix.tableForm.action=goAction+"?curPage="+goPage;
	//alert(pathPrefix.tableForm.action)
	pathPrefix.tableForm.submit();
}


function changeSort(sortBy,sortDir,area){
	//alert("in changeSort, area="+area+" sortBy="+sortBy);
	captureOpenDivs(area);
	pathPrefix=getPathPrefix(area,1);
	//update the sortBy and sortDir hidden inputs
	objBy=findObjectPath("sortBy","navBottom");
	objBy.value=sortBy;
	objToggle=findObjectPath("sortDir","navBottom");
	objToggle.value=sortDir;
	//now add the openDivs list and go!
	goAction=pathPrefix.tableForm.action;
	pathPrefix.tableForm.action=goAction;
	//alert(pathPrefix.tableForm.action)
	pathPrefix.tableForm.submit();
}


function captureOpenDivs(area){
	//alert("in captureOpenDivs");
	//capture a list of all open divs in openDivs array for the current resource page for use when the page reloads after the update
	top.openDivs=new Array();
	pathPrefix=getPathPrefix(area,1);
	/*x=pathPrefix.getElementsByTagName('div');
	for(i=0;i<x.length;i++){//alert(x[i].id+','+x[i].style.display);
		//record any open divs in the current resource so we can reopen these after the resource has ben updated
		//if(x[i].id.indexOf('contDiv_')>=0 && (x[i].style.display=='block')){//alert('open found');
		if(x[i].id.indexOf('contDiv_')>=0 && (x[i].style.display!='none')){alert('open found'); alert(x[i].style.opacity);
			top.openDivs[openDivs.length]=x[i].id;
		}
	}*/
	$("div",pathPrefix).each(function(){
		if(typeof($(this).attr('id'))!='undefined' && $(this).attr('id').indexOf('contDiv_')!=-1 && $(this).css('display')=='block'){
			//alert('found one: '+$(this).attr('id')+" "+$(this).css('display'));
			top.openDivs[openDivs.length]=$(this).attr('id');
		}
	});
}


function showOpenDivs(area){
	//alert('in show open divs, '+top.openDivs.length);
	reopenToggleDivCt=0; reopenToggleDiv=[];
	for(i in top.openDivs){
		//alert(top.openDivs[i]);
		pathPrefix=getPathPrefix(area,1);
		x=pathPrefix.getElementById(top.openDivs[i]);
		if(x!=null){
			//only increment the reopenToggleDivCt if the current div has a title onclick link - only top toggled collapsable content like categories should have this, not the filter div
			togDivCk=top.openDivs[i].replace('contDiv','title');
			if($("#"+togDivCk).length>0){
				reopenToggleDivCt++; reopenToggleDiv=top.openDivs[i];
			}
			x.style.display='block';
			//flip the toggle arrow if available
			togSign=top.openDivs[i].replace('contDiv','divTogSign');
			if(signalObj=findObjectPath(togSign,area)){
				//signalObj.src=stringReplace(signalObj.src,'_closed','_open');
				$(signalObj).attr('src',$("#"+togSign).attr('src').replace('_closed','_open'));
			}
			//switch toggle title text if available
			togTitle=top.openDivs[i].replace('contDiv','divTogTitle'); //alert(togTitle);
			if($("#"+togTitle).length>0){
				$("#"+togTitle).html($("#"+togTitle).html().replace('+ Show','- Hide'));
				$("#"+togTitle).html($("#"+togTitle).html().replace('+ Open','- Close'));
				$("#"+togTitle).html($("#"+togTitle).html().replace('Show','Hide'));
				$("#"+togTitle).html($("#"+togTitle).html().replace('Open','Close'));
			}
		}
	}
	//if there is only one div being opened, set it up as the current open toggle div
	if(reopenToggleDivCt==1){
		curTogDiv=reopenToggleDiv.replace('contDiv_','');
		str=$("#title_"+curTogDiv).attr('onclick').replace(/'/g,"").split(',');//alert(str[1]);
		curTogVals=new Array(curTogDiv,str[1],str[2],str[3],str[4],str[5],str[6]);
	}
	//reset the openDivs
	top.openDivs=new Array();
}


function clearText(objID,area,newClass,newType){
	//alert('in clearText');
	if((curObj=findObjectPath(objID,area))!=null){
		curObj.value="";
		//if a newClass value was sent, apply this class to the current input
		if(newClass!=null && newClass!=0){curObj.className=newClass;}
		//if a new Type was sent, replace the current field with a new field of the new type
		if(newType){
		//if(isIE==true){
			//to get around the fact IE can not change the type property of an existing input, we create a new input object with the new type to replace the existing input.
			newClass=curObj.className;
			newSize=curObj.size;
			newWidth=curObj.style.width;
			//create new input object
			newObj = document.createElement('input');
			newObj.name=objID;
			newObj.id=objID;
			newObj.type=newType;
			newObj.value="";
			//now swap out old input, and pass old input class and size props to new input
			curObj.parentNode.replaceChild(newObj, curObj);
			curObj=findObjectPath(objID,area);
			curObj.className=newClass;
			curObj.size=newSize;
			curObj.style.width=newWidth;
			curObj.focus();
		//}else{
			//for non IE browsers, simply change the type property
			//curObj.type=newType;	
		//}
		}
		//run this here again - IE and safari have trouble with this - NOTE that safari does NOT retain focus if this field was reached via TAB... why? got me.
		curObj.focus();
	}
}


function clearAllText(area){
	//alert("in clearAllText");
	windowPrefix=window;
	if(area=='popWin'){windowPrefix=popWin;}else if(area!=null){windowPrefix=window[area];}
	//confirm to clear fields
	decision=windowPrefix.confirm('Are you sure you want clear all input fields?');
	if(decision){
		docForms=windowPrefix.document.forms;
		//alert("total forms="+docForms.length);
		//now walk though all form inputs, find text inputs and set their value=""
		for(i=0;i<docForms.length;i++){
		//alert("current form length="+docForms[i].length);
			for(ii=0;i<docForms[i].length;ii++){
				if(docForms[i][ii].type=="text" && docForms[i][ii].readonly==null){
					//alert("found text input, value="+docForms[i][ii].value);
					docForms[i][ii].value="";
				}
			}
		}
	}
}


function preloadImages(imageList) { 
	if(httpsPg!=1){//dont preload on https pages
		//alert('preloading images')
		var doc=document; //put the document object into a variable for abbreviated handling
		if(doc.images){ //if this browser is capable of finding document images, then proceed
			if(!doc.loadedImages) doc.loadedImages=new Array(); //if the loadedimages array doesn't yet exist, create it & attach it to the document object
			var i,len=doc.loadedImages.length; //set up variables
			for(i=0; i<imageList.length; i++){//cycle through the image paths passed as arguments and preload them
				doc.loadedImages[len]=new Image(); 
				doc.loadedImages[len++].src=imageList[i];//note that putting the ++ after "len" increments "len" AFTER the current expression is evaluated!
				//alert(doc.loadedImages.length + ' images have been preloaded');
			}
		}
	}
}


/*function changeImageURL() { 
	//alert('preloading images')
	var doc=document; //put the document object into a variable for abbreviated handling
	if(doc.images){ //if this browser is capable of finding document images, then proceed
		//alert("there are "+doc.images.length+" images in this document")
		for(i=0;i<doc.images.length;i++){
			startPath=doc.images[i].src
			//alert(startPath)
			if(startPath.indexOf("_images")==-1){
				valueArray=startPath.split("images")
				//alert("subPath= "+valueArray[valueArray.length-1])
				newPath="http://www.jennieoturkeystore.com/images"+valueArray[valueArray.length-1]
				doc.images[i].src=newPath
				//return
			}
			//return
		}
	}
}*/


function closePopup() {
	//alert('in closePopup');
	//make sure the popUp is gone and update the main database display
	if(popWin){popWin.close(); popWin=0; popWin_h=0; popWin_w=0;}
}


//controls images swaping for both mouseEnter & mouseLeave actions
function imageSwap(mouseDir,objID,area) { 
	//alert('in imageSwap')
	imageInfo=null;
	if ((imgObjPath=findObjectPath(objID,area))!=null){
  		switch (mouseDir) {
			case'enter':
  				newImgPath=stringReplace(imgObjPath.src,'_norm','_over');
				imgObjPath.src = newImgPath;
			break;
			case'leave':
  				newImgPath=stringReplace(imgObjPath.src,'_over','_norm');
				imgObjPath.src = newImgPath;
			break;
			case'down':
  				newImgPath=stringReplace(imgObjPath.src,'_over','_down');
				imgObjPath.src = newImgPath;
			break;
			case'up':
  				newImgPath=stringReplace(imgObjPath.src,'_down','_over');
				imgObjPath.src = newImgPath;
			break;
			case'enterLive':
  				newImgPath=stringReplace(imgObjPath.src,'_live','_over');
				imgObjPath.src = newImgPath;
			break;
			case'leaveLive':
  				newImgPath=stringReplace(imgObjPath.src,'_over','_live');
				imgObjPath.src = newImgPath;
			break;
			case'liveToNorm':
  				newImgPath=stringReplace(imgObjPath.src,'_live','_norm');
				imgObjPath.src = newImgPath;
			break;
			case'normToLive':
  				newImgPath=stringReplace(imgObjPath.src,'_norm','_live');
				imgObjPath.src = newImgPath;
			break;
			case'overToLive':
  				newImgPath=stringReplace(imgObjPath.src,'_over','_live');
				imgObjPath.src = newImgPath;
			break;
			default:
				//if the mouseDir argument is none of the above, then just replace the last section of the image path with whatever was sent
				imgSrc=imgObjPath.src.split("_");
				imgSrc.pop();
				imgSrc=imgSrc.join("_");
				imgObjPath.src=(imgSrc+=mouseDir);
			break;
		}
	}
}


//controls images swaping for both mouseEnter & mouseLeave actions
function newImage(imagePath,objID) { 
	//alert('in imageSwap')
	imageInfo=null;
	if ((imgObjPath=findObjectPath(objID))!=null){
  		//newImgPath=stringReplace(imgObjPath.src,'_over','_norm');
		imgObjPath.src = imagePath;
	}
}

//toggle a group of checkboxes
function toggleCheckboxes(togList,area){
	//if the togList argument is not an array, assume it is a single object name and convert it to an array here
	if(!isArray(togList)){togList=new Array(togList);}
	//continue only if there are values in the togList
	if(togList.length>0){
		togBtn=findObjectPath('ckBoxToggle',area);
		if(togBtn.value=="Check All"){
			for(i=0;i<togList.length;i++){
				ckObj=findObjectPath(togList[i],area);
				ckObj.checked = true ;
			}
			togBtn.value="UnCheck All";
		}else if(togBtn.value=="UnCheck All"){
			for(i=0;i<togList.length;i++){
				ckObj=findObjectPath(togList[i],area);
				ckObj.checked = false ;
			}
			togBtn.value="Check All";
		}
	}
}

//chk if an object is an array or not.
function isArray(obj){
	//returns true is it is an array
	if(obj.constructor.toString().indexOf("Array") == -1){return false;}else{return true;}
}

function findObjectPath(objID,area){
	//alert('finding object path')
	//alert('objID='+objID+' area='+area);
	var pathInfo;
	var pathPrefix;
	//first come up with a path prefix depending on where the object is
	pathPrefix=getPathPrefix(area,1);
	//now track down the element using the pathPrefix
	//return the appropriate object path depending on what browser we are using.
	if(pathPrefix.getElementById){
		//alert('found getElementByID, objID= ' + objID)
		pathInfo=pathPrefix.getElementById(objID);
	}else if (pathPrefix.all){
		//alert('found all, objID= ' + objID)
		pathInfo=pathPrefix.all[objID];
	}else if(pathPrefix.layers){
		//alert('found layers, objID= ' + objID)
		pathInfo=pathPrefix.images[objID];
	}else{ 
		//alert('unable to process DHTML on this browser')
		pathInfo=null;
	}
	//alert('pathInfo=' + pathInfo)
	return pathInfo;
}


function getPathPrefix(area,includeDoc){
	var pathPrefix;
	//create the window level path prefix
	if(!area){
		pathPrefix=window;
	}else{
		switch(area){
			
			case(""):
			case(0):
			case(null):
			pathPrefix=window;
			break;
			
			case("popWin"):		
			pathPrefix=popWin;
			break;
			
			case("navBottom"):
			pathPrefix=window.top.bottomFrame;
			break;
			
			case("navTop"):
			pathPrefix=window.top.topFrame;
			break;
			
			case("navBottomEmailer"):
			pathPrefix=window.top.bottomFrame.iframe_emailer;
			break;
			
			default:
			//if another area argument was sent,assume it is the name of the target frame 
			pathPrefix=window.top[area];
			break;
		}
	}
	//add the document element if requested
	if(includeDoc){pathPrefix=pathPrefix.document;}
	return pathPrefix;
}


//this is a script to modify a given string with the given new string info
function stringReplace(modifyString,findString,replaceString) {
	//alert('in stringReplace')
	var pos=0,len=findString.length;
	pos=modifyString.indexOf(findString);
	//using the 'while(pos != -1)' here allows us to escape if the 'findString' we are sending isn't found in the 'modifyString' at all
	while(pos != -1) {
		preString=modifyString.substring(0,pos);
		postString=modifyString.substring(pos+len,modifyString.length);
		modifyString=preString+replaceString+postString;
		pos=modifyString.indexOf(findString);
	}
	return modifyString;
}

//newer shared functions and setup - may not be used by some older sites

//SETUP VARIABLES MAY BE OVERWRITTEN OR UPDATED in site.js

//page setup/animation variables
var pageAnimProps={animDelay:400,delayInc:40,animFast2:250,animFast:300,animSlow:700} //other timing properties may be added to this object below

var skrollrActive=0;//$(".parallax-parent").length>0/*||$(".split-static-slides").length>0*/?1:0; //check for all classes that use skrollr
var skrollrObj=0;

var shadowBoxNoTouchEvents=1; //10-23-25 TLC

var waypointAnimations={};
var waypointAnimOffset='90%';

var lazyLoaderInstances={};
var lazyLoaderNoGroupLoad=1; //added 8-2-24 Orton - not sure when we would NOT want this 
var lazyLoaderNoFade=0; //added 9-29-5 TLC
var lazyLoaderGroupDelay=300;
var lazyLoaderThreshold=300;
var lazyLoaderFadeTime=600;

var bkgdVideoMobileShow=0; //whether or not to show background video on mobile
var bkgdVideoAnimDelayCustom=0;
var bkgdVideoLoadCustom=0; //11-21-25 TLC - delay background video loading until after first callout image has loaded
var bkgdVideoLoadAfterHero=0;
var bkgdVideoLoadReady=0;

//nav control variables
var noNavUpdate=0;
var navInitHeight=0;
var mobileNavActive=0;
var mobileNavNoToggle=0;
var mobileNavPosChangeSensitivity=13;
var mobileNavSavedScrollTop=-1; //setting to -1 will serve to stop the navBarUpdate function from running on page load
var mobileNavOpenNonFixedHeader=0; //set to 1 if the mobile nav header will NOT be in a fixed position when the mobile nav is open
var mobileNavCollapseUL=0; //for TLI - collapsing ul instead of div on top level mobile nav
var mobileNavItemAnimSpeed=50;
var mobileNavFullScreen=1;
var mobileNavSubTogCSS=0;

var mobileNavForceShowDistance=1.1;
var mobileNavAnimResizeDistance=.5;
var mobileNavForceShowOffset=0;
var mobileNavAnimResizeOffset=0;

var headerActive=0;
var headerFullHeight=0;
var headerSmallHeight=0;

//autoscroll variables
var autoScrollTimeoutInt=0;
var autoScrolling=0;
var autoScrollDisabled=0;
var autoScrollActive=!mobileOrTabletDevice && $(".autoScrollDiv").length>0 && !window.matchMedia("(max-width:800px)").matches?1:0;// at 800px wide we abandon some of the viewport full height divs so do not use auto scroll as it could pass by some content //console.log('autoScrollActive: '+autoScrollActive);
//var autoScrollActiveSave=0; //used to retain original autoScrollActive value when disbled during non-pg overlay visibility
var autoScrollAnimSpeed=900;
var autoScrollTimeoutWait=300;
var autoScrollMouseDownScrollTop=0;
var autoScrollSensitivity=10; //px of movement required by track pad or wheel to trigger auto scrolling
var autoScrollTriggered=0;
var autoScrollFullBlock=0;
var autoScrollPartialHeightPerc=0; //any element smaller than this percentage of window height will scroll up to align with window bottom instead of top

//page layout variables
var pageLayoutSizePrev='';
var pageLayoutSize=''; 
var pageLayout800=0;
var pageLayout600=0;
var pageLayoutOrient='';
var pageLayoutOrientChange=0;
var pageLimitedViewport=0;
var pageFadeBlockCustom=typeof pageFadeBlockCustom!='undefined'?pageFadeBlockCustom:0; //this may be set by an enclosing script
if(typeof disablePageFade=='undefined'){var disablePageFade=0;} //may be set in header-standard.php by site prefs
if(typeof pageFadeSpeed=='undefined'){var pageFadeSpeed=300;} //may be set in header-standard.php by site prefs
var pageLayoutNoResizeUpdate=0;
var pageFadeColorizeBkgd=0; //TLI
var pageInitScrollTop=0;

//overlay toggle variables
var overlayDivFreezePos=0;
var overlayDivScrollTopSaved=0;
var overlayDivFadeSpeed=300;
var popDivLoadingTimeout=0;
var popDivID=0; //NEED to convert this to track individial pop IDs in case multiple overlays are open
var popDivNoAjaxAdjust=0; //this may be set prior to an ajax call to prevent window adjustment once ajax process is complete - will be reset every time an ajax call is made
var popDivVertPos=0;

var noHashUpdate=0;
var prevWinHash=window.location.hash;

//setting staticPopTop will make all overlay popDivs top align relative the top of the window instead of centered in the window
var staticPopTop=0;
var curWindowWidth=0;
var curWindowHeight=0;
var popPosAdjustDelay=0; //7-25-24 NFI - add a slight delay for overlay display if requested (setup in site.js)

//function to open or close overlay windows when browser back/forward buttons are pushed - requires hash updates on overlay open
$(window).on('hashchange', function() { //console.log('hash change! '+window.location.hash);
   if(noHashUpdate){noHashUpdate=0;return;} //10-28-22 DONT process any hash actions if explicitly requested to skip
	var prevHashArgs=prevWinHash!=""?prevWinHash./*replace("#","").*/split('.'):[""];
	var newHashArgs=window.location.hash!=""?window.location.hash./*replace("#","").*/split('.'):[""];
	hashVal=newHashArgs.length>1?newHashArgs[0]:"#";
	//console.log(prevHashArgs[0]+', '+newHashArgs[0]);
	//CLOSE overlay
	if(popDivID!=0 && prevHashArgs[0].length==3 && (window.location.hash=="" || window.location.hash=="#-")){
		if(popDivID.indexOf(prevHashArgs[0].substr(1))!=-1 && $(prevHashArgs[0]+'PopDiv').length>0 && $(prevHashArgs[0]+'PopDiv').hasClass('popDivOpened')){
	 		hidePopDiv(prevHashArgs[0].substr(1),0);
		}
	}
	//OPEN overlay
	if(popDivID==0 && window.location.hash!="" && (prevWinHash=="" || prevWinHash=="#-")){//console.log('check open');
		if($(newHashArgs[0]+'PopDiv').length>0 && !$(newHashArgs[0]+'PopDiv').hasClass('popDivOpened')){//console.log('processHashAction: '+newHashArgs[0]);
	 		processHashAction(newHashArgs,0);
		}
	}
	//UPDATE overlay
	if(popDivID!=0 && prevHashArgs[0].length==3 && prevWinHash!=window.location.hash && $(newHashArgs[0]+'PopDiv').length>0){
		processHashAction(newHashArgs,0);
	}
	
	prevWinHash=window.location.hash;
});
//$(window).on('popstate'),function(){console.log('window popstate!');}

function generateRandomString(length){
   return Math.random().toString(36).substring(2, length + 2);
 }

function toggleMediaShare(mID){
	opening=$("#mediashare"+mID).css('display')=='none'?1:0;
	$("#mediashareBtn"+mID).css('display',(opening?'none':'block'));
	$("#mediashare"+mID).css('display',(opening?'block':'none'));
}

function addThisTog(divID,dir){
	if(dir=='show'){$("#addThisTogEnclose"+divID).addClass('addThisTogVisible');}
	if(dir=='hide'){$("#addThisTogEnclose"+divID).removeClass('addThisTogVisible');}
	//$("#addThisTogEnclose"+divID).animate({opacity:(dir=='show'?'show':'hide')},200);
}

function processHashAction(hashArgs,init){ //console.log('processHashAction');
	switch(hashArgs[0]){
		case '#dv':
			if($("#encloseDiv_"+hashArgs[1]).length>0){
				if(init==1){ openItem=0; openItemSub=0; //make sure NO previous openItem or openItemSub values are set, as this is an INIT call - everything should be closed
					//open the requested group and possibly sub group
					isSub=typeof hashArgs[2]!='undefined' && $("#encloseDiv_"+hashArgs[1]+"_"+hashArgs[2]).length>0?1:0;
					switchOpenGroup(hashArgs[1]+(isSub?'_'+hashArgs[2]:''),1,1,0,0,1,(isSub?'sub':''),init);
					//scroll the window to this item - set a timeout to give the div time to open (open time is set to 1 millisecond)
					setTimeout(
                  function(){
                     scrollToNavAware(openItemSub?openItemSub:openItem);
                     //window.location.hash=(openItemSub?openItemSub:openItem);
                  },100
               );
				}else{ //if this is not an initializing call, then run the updateDivGroup function
					updateDivGroup(hashArgs[1],(typeof hashArgs[2]!='undefined' && $("#encloseDiv_"+openItem+"_"+hashArgs[2]).length>0?'sub':''),0,1,1,0);
				}
			}
		break;
		case '#st'://store item detail
		case '#ac'://account item detail
		case '#ft'://floating item detail
		case '#fl'://full cover item detail
		case '#pg'://full page item detail
			showPopDiv(hashVal.substr(1),hashArgs[1],hashArgs[2],hashArgs[3],hashArgs[4],1); //open pop div overlay and DONT update the page URL	
		break;
		case '#ov': top.mp(decodeURIComponent(window.location.hash.substr(6)),'',0,0,parseInt(hashArgs[1])); break; //overlay video
		case '#ol': openOverlay('iframe','',(hashArgs[1].indexOf('http')==-1?'/'+hashArgs[1]:decodeURIComponent(hashArgs[1])),hashArgs[2],hashArgs[3]); break; //overlay page - width and height values will be sent as well
		case '#ts': openOverlay('iframe','','/forms/testimonial',460,380); break; //overlay testimonial form
		case '#gl': loadNewGallery(1,hashArgs[1]); break; //on-page gallery collection
		case '#gc': top.lg(hashArgs[2],hashArgs[1]); break; //overlay gallery collection
		case '#cr': showCareer(1,hashArgs[1]); break; //load career
		//case '#pr': showProject(1,hashArgs[1]); break; //load project
		case '#gh': toggleGridDetails(hashArgs[1]); break; //show grid item details
		case '#sl': loadNewSlide(1,hashArgs[1]); break; //load on-page slide
		case '#sc': //scroll to indicated hash
         if(typeof closeNavShowHash =='function'){closeNavShowHash(hashArgs[1]);}
         else if(typeof scrollToNavAware =='function'){scrollToNavAware(hashArgs[1]);}
			else{jqueryScroll(hashArgs[1]);}
		break; 
		default: if(init!=1 && hashArgs[0].indexOf("#")!=-1){goPage(hashArgs[0]);} break;
	}
}

function switchOpenGroup(groupID,togSign,togFade,closeOld,closeIfOpen,animDur,group,init){//alert("#contDiv_"+groupID+", display="+$("#contDiv_"+groupID).css('display'));
	if($("#"+groupID).length==0){return;/*element not found*/}
	//set variable defaults
	if(togSign==1){togSign='image';}
   togSignClose=togSign=='-'?'+':''; 
	if(animDur==null){animDur=300;}
	//if we are NOT closing previously open divs, simply proceed here to toggle the current div selection
	if(closeOld!=1 && init!=1){
		if($("#encloseDiv_"+groupID).hasClass('noCollapse')==false){
			curDivDisp=$("#contDiv_"+groupID).css('display'); //alert(curDivDisp);
			if(curDivDisp=='none'){
				$("#encloseDiv_"+groupID).addClass('encloseDiv'+($("#encloseDiv_"+groupID).hasClass('divSubEnclose')?'Sub':'')+'Live');
			}else{
				$("#encloseDiv_"+groupID).removeClass('encloseDiv'+($("#encloseDiv_"+groupID).hasClass('divSubEnclose')?'Sub':'')+'Live');
			}
			toggleContDiv(groupID,togSign,'',togSignClose,'',0,animDur);
		}
	}else{ //proceed here if closing previous divs and tracking open divs
		//if a top group, and a subgroup is open, close the subgroup as well (using most of the same function arguments as the top category)
		if(group!='sub' && openItemSub!=0){switchOpenGroup(openItemSub,1,1,1,1,animDur,'sub',init);}
		//if a subgroup is being opened, but the top group is NOT open, open the top group as well
		if(group=='sub'){
			topID=groupID.split('_');
			if(openItem!=topID[0]){switchOpenGroup(topID[0],1,1,1,1,animDur,'',init);}
		}
		//set oItem val
		if(group=='sub'){oItem=openItemSub;}else{oItem=openItem;} 
		//doOpen MUST be set here, after possible sub group updates above
		doOpen=1;
		//alert('group='+group+', groupID='+groupID+', oItem='+oItem+', openItemSub='+openItemSub+', openItem='+openItem);
		//if there is an open item, and it is the current item, or we are requested to close open items, close it here
		if(closeIfOpen==1 || groupID!=oItem){
			if(oItem!=0 && (groupID==oItem || closeOld==1) && $("#encloseDiv_"+oItem).hasClass('noCollapse')==false/* && $("#"+oItem).length>0*/){
				toggleContDiv(oItem,togSign,'',togSignClose,'',0,animDur);
				//reset the open item styling
				$("#encloseDiv_"+oItem).removeClass('encloseDiv'+($("#encloseDiv_"+oItem).hasClass('divSubEnclose')?'Sub':'')+'Live');
				//if we are simply closing an openItem, clear the openItem variable and stop any further group toggling
				if(groupID==oItem){ //alert('groupID==oItem, group='+group);
					if(group=='sub'){openItemSub=0;}else{openItem=0;}
					doOpen=0;
				}
				//alert('group='+group+', groupID='+groupID+', oItem='+oItem+', openItemSub='+openItemSub+', openItem='+openItem);
			}
			//now do the openening toggle if requested
			if(doOpen==1){//alert('do open, groupID='+groupID);
				if($("#contDiv_"+groupID).css('display')=='none'){
					toggleContDiv(groupID,togSign,'',togSignClose,'',0,animDur);
					$("#encloseDiv_"+groupID).addClass('encloseDiv'+($("#encloseDiv_"+groupID).hasClass('divSubEnclose')?'Sub':'')+'Live');
				}
				//set the openItem variable
				if(group=='sub'){openItemSub=groupID;}else{openItem=groupID;}
			}
		}
	}
}

function updateDivGroup(rID,group,altHash,closeOld,closeIfOpen,skipGoPage,togPlusMinus){
	//alert('updateDivGroup');
	if(mobileOrTabletDevice==1||(typeof openItemNeverClose!='undefined'&&openItemNeverClose==1)){closeOld=0;} //DONT close old in mobile (content may scroll too much) OR if globally prohibited (in header-standard.php)
	if(typeof closeOld=='undefined'){closeOld=1;}
	if(typeof closeIfOpen=='undefined'){closeIfOpen=1;}
	if(typeof togPlusMinus=='undefined'){togPlusMinus=0;}
	if(typeof alwaysSkipGoPage!='undefined'&&alwaysSkipGoPage==1){skipGoPage=1;}
	rID=String(rID);//must conver the rID value to a string for the split/join operation below
	switchOpenGroup(rID,(togPlusMinus?'-':1),1,closeOld,closeIfOpen,300,group,0);
	//if(group=='blog'){updateIframe();}
	if(skipGoPage!=1){
		//goPage(curURL+'#'+((typeof altHash!='undefined'&&altHash!=0)?altHash:'dv')+'.'+(group=='nosplit'?rID:rID.split('_').join('.')));
	}
}

function updateDivGroupMobile(rID,group,altHash,closeOld,closeIfOpen,animSpeed){ //rID=String(rID);
	//capture current scroll pos and window height
	winHeight=$(window).height();
	curScrollTop=$(document).scrollTop(); 
	//get final body height after accordion animations would be complete
	$('#contDiv_'+rID).css('display',openItem==rID?'none':'block');
	if(openItem!=0 && openItem!=rID){$('#contDiv_'+openItem).css('display','none');}
	finalHeight=$('body').height(); //finalHeight=$(document).height(); <- USE THIS?
	finalScrollTop=$("#"+rID).offset().top;
	//now put everything back
	$('#contDiv_'+rID).css('display',openItem==rID?'block':'none');
	if(openItem!=0 && openItem!=rID){$('#contDiv_'+openItem).css('display','block');}
	//if the scrolltop wont leave enough room left for the page to fill the window, move the scroll top immediately
	if(finalHeight-finalScrollTop<winHeight){
		finalScrollTop=finalHeight-winHeight-35; //NOTE - this 35px pad seems to be needed when testing on iPod - not sure what that's about...
		if(finalScrollTop<0){finalScrollTop=0;}
		$('body').scrollTop(finalScrollTop);
	}
	//if(finalScrollTop!=curScrollTop){$('html, body').animate({scrollTop:finalScrollTop},Math.round(animSpeed/2));}
	else if(rID!=openItem){setTimeout(function(){jqueryScroll(rID,200);},(animSpeed+100));} //IDEALLY THIS WOULD SIMPLY BE RUN AFTER THE ANIMATION IS COMPLETE
	//now animate the divs
	updateDivGroup(rID,group,altHash,closeOld,closeIfOpen,1,animSpeed);
}

function olPgOrNavOpen(overlayDiv){
   pgOL='pgPopDiv'; navOL='header-nav-mobile-container'; 
   if(overlayDiv=='openck'){ //return true if NEITHER page overlay or nav is open
      return $("#"+navOL).css('display')=='none'&&$("#"+pgOL).css('display')=='none'?0:1;
   }else{ //return true if the requested overlay is NOT already open
      return (overlayDiv==pgOL && $("#"+navOL).css('display')=='none')||(overlayDiv==navOL && $("#"+pgOL).css('display')=='none')?1:0;
   }
}

//function to toggle overlay divs - also collapse the page content so no background scrolling can take place if requested
//updated 7-15-21 NOPAIN - to only process toggle if no force open/close argument was sent
function toggleOverlayDiv(overlayDiv,freezePagePos,forceDisp,clearContainer){//console.log('toggleOverlayDiv: '+overlayDiv+', freezePagePos: '+freezePagePos+', forceDisp: '+forceDisp+', overlayDivScrollTopSaved: '+overlayDivScrollTopSaved);
   if(typeof forceDisp=="undefined"){forceDisp=0;}
   if(typeof clearContainer=="undefined"){clearContainer="";}
	newDispState='';
	if($("#"+overlayDiv).css('display')=='none'&&forceDisp=='hide'){return 'none';} //7-15-21
	if($("#"+overlayDiv).css('display')=='block'&&forceDisp=='show'){$(document).stop().scrollTop(0);return 'block';} //7-15-21
	pgOL='pgPopDiv'; navOL='header-nav-mobile-container'; //1-24-22 - ONLY process the body alterations for overlay setup IF there is not already one of the full page overlays open
	olProcess=olPgOrNavOpen(overlayDiv);
	if($("#"+overlayDiv).css('display')!='block'){ newDispState='block';
      $("body").addClass('overlay-div-opening');

      //7-31-25 - TLC v2 (and TWRP) if there is a header top banner that is NOT part of the header itself, and we use a fixed nav during mobile nav overlay open, 
      //then move the header-outer div up to the top of the viewport to cover the banner so there is no jump when the header goes from relative or absolute position to fixed
      if(overlayDiv==navOL && !mobileNavOpenNonFixedHeader && $("#header-top-banner").length>0 && $(document).scrollTop()<$("#header-top-banner").outerHeight()){
         if($("#header-outer").length>0 && $("#header-outer").css('position')=='relative' && $('#header').offset().top>0 && $('#header').css('position')!='fixed'){
            $("#header-outer").data('headerMoved',$("#header-top-banner").outerHeight()-$(document).scrollTop()); //console.log('move '+$("#header-outer").data('headerMoved'));
            $("#header-outer").animate({top:-$("#header-outer").data('headerMoved')},overlayDivFadeSpeed);
         }
      }

      if(olProcess){//console.log('save pos'); //1-20-22 DONT process this if opening an overlay while the mobile nav is also open
			if(freezePagePos==1){
				overlayDivFreezePos=1; 
				overlayDivScrollTopSaved=$(document).scrollTop();
			}
		}
		if($('body').height() > $(window).height()){
			$("#"+overlayDiv).addClass('overlay-with-scrollbars');
		}

      //run fade in animation
		$("#"+overlayDiv).stop().fadeIn(overlayDivFadeSpeed,function(){
			$("body").addClass('overlay-div-open');//$('#header').css({top:0});
			if(freezePagePos==1){
				$('.mobile-nav-collapse').addClass('content-collapse');
				$(document).stop().scrollTop(0);
				if(overlayDiv==pgOL && $("#"+navOL).css('display')!='none' && typeof toggleMobileNav=='function'){toggleMobileNav();} //1-24-22 - if opening a page overlay and the nav is open, close the nav
			}
		});
	}else{ 
		newDispState='none';
      $("body").removeClass('overlay-div-opening');

      //7-31-25 TLC/TWRP - if the header-outer div has been moved to accommodate a header top banner when opening the nav overlay, move it back to normal position
      if(overlayDiv==navOL && $("#header-outer").length>0 && $("#header-outer").data('headerMoved')){//console.log('move back');
         $("#header-outer").data('headerMoved',0);
         $('#header-outer').animate({top:0},overlayDivFadeSpeed);
      }

		//1-24-22 - switch the overlay to fixed position during fadeout so that it will retain its current scrolltop position - then revert to normal positioning once fadeout is complete
		olPos=$("#"+overlayDiv).css('position');
		$("#"+overlayDiv).css({position:'fixed',top:-$(document).scrollTop()}).stop().removeClass('overlay-with-scrollbars').fadeOut(overlayDivFadeSpeed,
         function(){
            $("#"+overlayDiv).css({position:'',top:0});
            if(clearContainer!=""){$(clearContainer).html('');}
         }
      );
		if(olProcess){//console.log('reset'); //1-20-22 DONT process this if closing an overlay while the mobile nav is also open
			$("body").removeClass('overlay-div-open');
			overlayDivFreezePos=0;
			if(freezePagePos==1){
				$('.mobile-nav-collapse').removeClass('content-collapse');
				$(document).scrollTop(overlayDivScrollTopSaved);
				if(typeof autoScrollTimeout=='function'){autoScrollTimeout();} //TLI autoscroll function
			}
		}
	}//console.log('toggleOverlayDiv end, olProcess: '+olProcess+', newDispState: '+newDispState+', overlayDivScrollTopSaved: '+overlayDivScrollTopSaved);
	return newDispState;
}

function hidePopDiv(popType,noPgUpdate,forceClose){ //console.log('hidePopDiv: '+popType);
   if(typeof popType=="undefined"){popType='pg';}
   if(popType=='all'){ //close any open standard overlay
      ckPops=['ac','pg','fl','ft','st'];
      for(i in ckPops){hidePopDiv(ckPops[i],noPgUpdate,forceClose);}
      return;
   }
   if(typeof forceClose=="undefined"){forceClose=0;}
   if(typeof pauseAnims!="undefined"){pauseAnims=0;}
   overlayDivFreezePos=0; //TLI
   //alert(popType);
   popDivID='#'+popType+'PopDiv';
   //if this popup has the popDivOpened class, assume it needs to be shut down
   if($(popDivID).hasClass('popDivOpened')||forceClose){
      //clear the hash from the URL
      if(window.location.hash!="" && noPgUpdate!=1){goPage(curURL+"#-");}
      //remove the popDivOpened class
      $(popDivID).removeClass('popDivOpened');
      //restart any inline (always playing) video as needed
      toggleBkgdVideoPlay('play');
      //process full page or modal overlays
      if(popDivID.indexOf('pg')!=-1){ //use the toggleOverlayDiv function for full page overlays
         toggleOverlayDiv(popDivID.substr(1),1,'hide',"#"+popType+"PopContentDiv");//7-15-21 added "hide" force action
      }else{
			if($("body").hasClass('overlay-div-open') && !olPgOrNavOpen('openck')){ //added for TLC facilities site, remove overlay-div-open if it exists but #pg overlay or nav is NOT open, assuming fl overlay uses overlayDivScrollTopSaved
				setTimeout(function(){
               $("body").removeClass('overlay-div-open');
               if(overlayDivScrollTopSaved){$(document).scrollTop(overlayDivScrollTopSaved);overlayDivScrollTopSaved=0;}
               hidePopDiv(popType,1,1);
            },overlayDivFadeSpeed); return;
			}
         $(popDivID).delay(overlayDivFadeSpeed).animate({top:-50,height:0},0,
            function(){ //DONT use popDivID variable here as it will have been cleared by the enclosing script
               //make sure to properly unload a playing video before closing the overlay - https://stackoverflow.com/questions/3258587/how-to-properly-unload-destroy-a-video-element
               if($("#"+popType+"PopDiv").hasClass("popMedia") && $("#"+popType+"PopDiv video").length>0){ //"#olVid"
                  vidObj=$("#"+popType+"PopDiv video");
                  vidEle=vidObj[0];
                  vidEle.pause();
                  vidEle.removeAttribute('src');
                  //vidObj.prop('src','');
                  vidObj.children('source').prop('src', '');
                  vidEle.load();
                  $.get("/_libs/media_embed.php?vsclose=1",{},function(){}); //5-12-21 MAS - ALSO unset open vid session value
               }
               $("#"+popType+"PopDiv").removeClass("popMedia");
               $("#"+popType+"PopContentDiv").html('');
            }
         );
      }
      //if overlay has a full cover div, fade that out too
      if($('#'+popType+'CoverDiv').length>0){$('#'+popType+'CoverDiv').stop().fadeOut(isltIE9?0:overlayDivFadeSpeed);}
   }
   popDivID=0;
}


//showPopDiv(hashVal.substr(1),hashArgs[1],hashArgs[2],hashArgs[3],hashArgs[4])
function showPopDiv(popType,rID,tbl,rt,act,noPgUpdate,vertPos,content,step,altURL,altWidth,addPopMedia,ajaxContent){//console.log('showPopDiv - popType: '+popType+', rID: '+rID+', tbl: '+tbl+', rt: '+rt+', act: '+act+', step: '+step);
   if(typeof pauseAnims!="undefined"){pauseAnims=1;}
   if(typeof step=="undefined"){step=1;}
   overlayDivFreezePos=1; //TLI
   //pause any inline (always playing) video as needed
   if(step==1){toggleBkgdVideoPlay('stop');}
   //setup argument variables - NOTE, if popType includes pipe characters, it is being used as a shorthand to include altWidth and addPopMedia info in the first argument
   if(popType.indexOf('|')!=-1){
      popBits=popType.split('|');   
      popType=popBits[0];
      altWidth=popBits[1];
      addPopMedia=popBits[2];
   }
   if(typeof rID=="undefined"){rID="";}
   if(typeof tbl=="undefined"){tbl="";}
   if(typeof rt=="undefined"){rt="";}
   if(typeof act=="undefined"){act="";}
   if(typeof noPgUpdate=="undefined"){noPgUpdate=0;}//default to updating URL bar
   if(typeof vertPos=="undefined"){vertPos=0;}
   if(vertPos==0 && typeof fixedTopOverlays!=='undefined' && fixedTopOverlays.includes(popType)){vertPos=9999;} //5-1-25 NOPAIN - if fixedTopOverlays array exists and the current overlay type is in it, always force this overlay to top align
   if(vertPos==9999){vertPos=findStaticPopTop();} //5-1-25 : 9999 is code for find the staticPopTop value
   popDivVertPos=vertPos;
   if(typeof content=="undefined"){content="";}
   if(typeof step=="undefined"){step=1;}
   if(typeof altURL=="undefined"){altURL="";}
   if(typeof ajaxContent=="undefined"){ajaxContent=0;}
	if(step==1){ //7-16-21 - if the requested overlay div is already open and only having its contents updated, fade out the content opacity first so the transition to the new content is smooth
		popAlreadyOpen=popDivID=='#'+popType+'PopDiv'?1:0;
		popDivID='#'+popType+'PopDiv';
		if(popAlreadyOpen){
			popDivID=0; //empty popDivID so it can be reset next time through to prevent a continuous loop here
         //5-1-25 popFadeDiv may be set in site.js if wanting to fade the popScrollDiv instead, or some other nested div
			$("#"+popType+(typeof popFadeDiv !=='undefined'?popFadeDiv:"PopContentDiv")).animate({opacity:0},150,function(){showPopDiv(popType,rID,tbl,rt,act,noPgUpdate,vertPos,content,step,altURL,altWidth,addPopMedia,ajaxContent);});return;
		}
	}
   switch(step){
      case 1:
         //if we are attempting to load the acct popup, make sure the current page is under SSL
         if(tbl=='acct' && acctHttps==1 && liveSite==1 && httpsPg!=1 /*curURL.indexOf('https')==-1*/){
            goURL=curURL.split('http').join('https')+(curURL.indexOf('?')==-1?'?':'&')+'https=1'+'#'+popType+'.'+rID+'.'+tbl+'.'+rt+'.'+act;
            //alert(goURL);
            window.top.location=goURL; return;
         }
			//fade up background cover if available 
			popDivCoverCK=popDivID.replace('Pop','Cover');
			if($(popDivCoverCK).length>0 && $(popDivCoverCK).css('display')!='block'){
				$(popDivCoverCK).fadeIn(isltIE9?0:overlayDivFadeSpeed);
			}
         //set a timeout for the loading animation if available
         if($(popDivID+'Loading').length>0){
            popDivLoadingTimeout=setTimeout(function(){$(popDivID+'Loading').stop().css({display:'none',opacity:1}).fadeIn(isltIE9?0:overlayDivFadeSpeed);},1000);
         }
         //if content is already available in step 1, proceed immediately to step 2
         if(content!=""){
            if(content.indexOf("#")==0){contentID=content; content=$(content).html();} //if content is an HTML element ID reference, get the content of that element
            if((popType=='fl'||popType=='ft') && content.indexOf(popType+'PopClose')==-1){ //if the content does not include a close button, add one here
               content+='<a class="'+popType+'PopClose" href="javascript:void(0);" onclick="hidePopDiv(\''+popType+
               '\');" aria-label="Close Window" tabindex="0"><span></span><span></span>'+/*<div>CLOSE</div>*/'</a>';
               //content+='<a class="'+popType+'PopClose" href="javascript:void(0);" onclick="hidePopDiv(\''+popType+
               //'\');"><img src="/_images/shared/pop-close-lg.png" width="33" height="33" align="absbottom" class="mouseTogOpacity" id="'+popType+'PopCloseImg" /></a>';
            }
            showPopDiv(popType,rID,tbl,rt,act,noPgUpdate,vertPos,content,2,altURL,altWidth,addPopMedia,0);
         }else{ //otherwise load content based on popType
            switch(popType){
               case 'ac':
               case 'pg':
               case 'fl':
               case 'ft':
                  curPopWidth=altWidth&&altWidth!='auto'?altWidth:parseInt($("#"+popType+"PopDiv").css('width')); //alert(curPopWidth);
                  $.get((altURL?altURL:"/content/pages/overlay.php?tp="+popType+"&id="+rID+"&tbl="+tbl+"&rt="+rt+"&act="+act+"&popWidth="+curPopWidth),{},function(content){
                     showPopDiv(popType,rID,tbl,rt,act,noPgUpdate,vertPos,content,2,altURL,altWidth,addPopMedia,1);  
                  });
               break;
               case 'st': //vertPos=1;
                  $.get("/content/pages/estore-detail.php?id="+rID,{},function(content){
                     showPopDiv(popType,rID,tbl,rt,act,noPgUpdate,vertPos,content,2,altURL,altWidth,addPopMedia,1);                                    
                  });
               break;
            }
         }
      break;
      case 2:
         //remove any loading indicator
         clearTimeout(popDivLoadingTimeout);
         //12-8-23 NJ - don't continue if no content was generated for some reason
         if(!content){alert('content unavailable'); hidePopDiv(popType,noPgUpdate,1);return;}
         //update the page URL
         if(noPgUpdate!=1){
				prevWinHash='#'+popType+'.'+rID+(tbl?'.'+tbl:'')+(rt?'.'+rt:'')+(rt&&act?'.'+act:''); //7-15-21 NOPAIN - set the prevWinHash value here to stop the onhashchange handler from reading this new hash and reprocessing this showPopDiv function call
				goPage(curURL+prevWinHash);
			}
         if($(popDivID+'Loading').length>0){$(popDivID+'Loading').stop().fadeOut(isltIE9?0:100);}
         //populate the selected overlay with the provided content
         $("#"+popType+"PopContentDiv").html(content).animate({opacity:1},150);
         //make other overlay adjustments UNLESS this is a full page overlay
         if(popType!='pg'){
				//add popMedia class if requested
				if(addPopMedia==1){$("#"+popType+"PopDiv").addClass("popMedia");}
				hasPopMedia=$("#"+popType+"PopDiv").hasClass("popMedia");//console.log('hasPopMedia: '+hasPopMedia);
				//change positioning from fixed to absolute for mobile devices where the screen may be zoomed, OR if jScrollPane is not available - vertPos==1 means center vertically
				//if((mobileOrTabletDevice!=1||hasPopMedia)&&vertPos==1){$(popDivID).css({'position':'fixed'});} //popMedia overlays are ALWAYS fixed position - centered on viewport
				if(hasPopMedia){$(popDivID).css({'position':'fixed'});} //popMedia overlays are ALWAYS fixed position - centered on viewport
				else if(staticPopTop>0||mobileOrTabletDevice==1||!jScrollPaneUsed){$(popDivID).css({'position':'absolute'});}
				//change the width of the current overlay if requested, otherwise will use class defined width
				$("#"+popType+"PopDiv").css('width',(altWidth?(altWidth=='auto'?'auto':altWidth+'px'):''));
			}
         //run initial window position adjust unless waiting for ajax content to finish loading
         if(!ajaxContent){popWinPosAdjust(vertPos,1);}
      break;
   }
}

//http://api.jquery.com/ajaxcomplete/ - THIS IS TRIGGERED AFTER ANY AJAX CALL!
$(document).on('ajaxComplete',function(){ //console.log("Triggered ajaxComplete handler");
   if(!popDivNoAjaxAdjust){ //this value may be set by function initiating an ajax call if pop win adjustment is not desired after a specific ajax process
      setTimeout(function(){popWinPosAdjust(popDivVertPos,1);},popPosAdjustDelay); //give action just a bit of time to complete if requested - 7-24-24 NFI expense image overlays
   }
   popDivNoAjaxAdjust=0; //reset
});

function popWinPosAdjust(vertPos,init){ //console.log('popwinAdjust, vertPos: '+vertPos);
   if(popDivID!=0 && (init==1||$(popDivID).hasClass('popDivOpened'))){//console.log('popWinPosAdjust width:'+$(popDivID).width());
      //set popOpening value based on popDivOpened class presence
      popOpening=!$(popDivID).hasClass('popDivOpened')?1:0;
      popProcess=init||popOpening?1:0;
      //console.log('popOpening: '+popOpening+', popProcess: '+popProcess);
      if(popProcess){
         $(popDivID).css({height:'auto'});
         //run init functions over newly loaded content for any HTML mods that are needed - NOTE that the account overlay runs these separately via account.js script
         //noContentInitSetup added 9-29-25 for TLC staff bio overlays
         if(popDivID.indexOf('ac')==-1 && typeof contentInitSetup == 'function' && (typeof noContentInitSetup == 'undefined'||noContentInitSetup==0)){contentInitSetup(popDivID);}
         if(popDivID.indexOf('ac')==-1 && typeof inputCustomStyle == 'function'){inputCustomStyle(popDivID);}
         if(popDivID.indexOf('ac')==-1 && typeof inputsConfig == 'function'){inputsConfig(popDivID);}
         if($(popDivID+' #fbPageContainerDiv').length>0 && typeof resizeFbOptGroups == 'function'){resizeFbOptGroups();}
      }
      //always position full page overlays at the top of the current viewport area - any content padding will be handled internally
      if(popDivID.indexOf('pg')!=-1){
         if(popOpening){toggleOverlayDiv(popDivID.substr(1),1);} //no adjustment to pg overlays after opening since they are fullscreen - TLI
      }else{ //console.log('$(window).height(): '+$(window).height()+', $(document).height(): '+$(document).height()+', window.innerHeight: '+window.innerHeight);
         //update the current window size variables for use in auto resize function below
         widthMinMargin=20;
         heightMinMargin=60;
         curScrollTop=$(window).scrollTop(); if(curScrollTop<0){curScrollTop=0;} //scrollTop() can be NEGATIVE on mobile safari - elastic scrolling
         curWindowWidth=$(window).width();
         curWindowHeight=window.innerHeight;//$(window).height(); - this is somehow being set to $(document).height() on store category pages by something in Brad's GA4 tracking code
         wSize=new Object();
         wSize.x=curWindowWidth/2;
         wSize.y=curWindowHeight/2;
         //2-14-25 - if this is a fixed position overlay make sure it is not too tall to be fully viewable (currently only adjusting for media overlays which have flexible heights)
         if(vertPos==0 && $(popDivID).hasClass("popMedia") && $(popDivID).css('position')=='fixed' && ($(popDivID).width()+widthMinMargin > curWindowWidth || $(popDivID).height()+heightMinMargin > curWindowHeight)){//console.log('too big');
            rzMax=100; rzCt=0;
            while($(popDivID).width()+widthMinMargin>curWindowWidth || $(popDivID).height()+heightMinMargin > curWindowHeight){
               rzCt++; if(rzCt==rzMax){break;} //cut off resize after 100 loops if needed to avoid runaway conditions
               $(popDivID).css('width',$(popDivID).width()-20); //console.log('new width: '+$(popDivID).css('width')+', new height: '+$(popDivID).css('height'));
            } 
         }
         xOffset=parseInt($(popDivID).width())/2; 
         yOffset=parseInt($(popDivID).height())/2;
         popLeft=curWindowWidth>$(popDivID).width()+widthMinMargin?wSize.x-xOffset:10; //console.log('popLeft: '+popLeft);
         $(popDivID).css('left',popLeft); 
         if(vertPos>1){ //vertPos==1 means center vertically, anything higher is an exact requested vertical position
            //popTop=vertPos;//console.log('vert poptop');
            popTop=curScrollTop+vertPos; //1-25-24 LH - add vertPos to curScrollTop to open overlay relative to current position, rather than top of page (which forces a scroll back to page top)
            $(popDivID).css('transform-origin','50% 5%');//if this popDiv is scaling, start from top
         }else if($(popDivID).css('position')=='absolute'){ //console.log('absolute');//absolutely positioned overlays are always positioned relative to the site top
            if(staticPopTop && responsiveSite){staticPopTop=findStaticPopTop();}
            //center popDiv if its height is less than the window height minus the staticPopTop margin - but not with account overlays (and not on mobile devices for now)
            if(popDivID.indexOf('ac')==-1 && !mobileDevice && curWindowHeight>$(popDivID).outerHeight(false)+(staticPopTop*2)){//console.log('center overlay');
               popTop=curScrollTop+((curWindowHeight-$(popDivID).outerHeight(false))/2); //console.log('curScrollTop: '+curScrollTop+', curWindowHeight: '+curWindowHeight+',$(popDivID).outerHeight(false): '+$(popDivID).outerHeight(false)+', popTop: '+popTop);
               $(popDivID).css('transform-origin','50% 50%'); //if this popDiv is scaling, start from center
               //console.log('scrollTop: '+$(window).scrollTop()+', curWindowHeight: '+curWindowHeight+', popDiv outerHeight: '+$(popDivID).outerHeight(false)+', staticPopTop: '+staticPopTop+', calc popTop: '+popTop);
            }else if(popOpening){//console.log('set top, curScrollTop: '+curScrollTop+', staticPopTop: '+staticPopTop);
               popTop=curScrollTop+staticPopTop; 
               $(popDivID).css('transform-origin','50% 5%');//if this popDiv is scaling, start from top
            }
         }else{ //console.log('vert center');//center vertically - NOTE, if mobile overlay shouldn't be centered, position was set to absolute in showPopDiv() function
            //popTop=(wSize.y-yOffset>15?wSize.y-yOffset:15)+(mobileOrTabletDevice==1||($(popDivID).css('position')=='absolute'&&!jScrollPaneUsed)?$(document).scrollTop():0); //THIS doesn't work with video overlays on mobile - needed for anything else?
            popTop=wSize.y-yOffset>30?wSize.y-yOffset:30; //console.log('popTop: '+popTop);
         }
         //set the pop div top position
         if(popTop>0){$(popDivID).css('top',popTop);}
         //fade up pop div if required
         if(popOpening){$(popDivID).stop().css({display:'block'}).fadeIn(isltIE9?0:overlayDivFadeSpeed);}
      }
      //add the popDivOpened class if needed
      if(popOpening){$(popDivID).addClass('popDivOpened');}
   }
}

function findStaticPopTop(){//alert('stat');
	return $("#overlay-top-margin").length>0?$("#overlay-top-margin").height():($("#header").height()+10);
}

function lazyLoader(parentEle,lazyClass,lazyNoFade,noGroupLoad){ //console.log('lazyLoader parentEle: '+parentEle);//console.log('loading laziness, parentEle: '+parentEle+', lazyNoFade: '+lazyNoFade+', noGroupLoad: '+noGroupLoad);
   //1-21-24 ROSANN K - MAKE SURE THE .lazy CLASS IS NOT SET TO display:none; IN _layout.css - THIS WAS USED FOR OLD LAZY LOADER AND WILL FORCE ALL IMAGES TO LOAD AT ONCE IF PRESENT WITH NEW LOADER >> img.lazy{display:none;}
   //8-21-24 ORTON - MAKE SURE TARGET IMAGE IS NOT SET TO transition:all - this will disallow the fade up of loaded images, set to transition:transform or something else specific so that opacity is NOT part of the transform
	if(typeof $.fn.lazy !=="function"){return;}
	if(typeof lazyClass=='undefined'){lazyClass='lazy';}
	if(typeof lazyNoFade=='undefined'){lazyNoFade=lazyLoaderNoFade;} //9-29-25 - use global preset if not designated
   if(typeof noGroupLoad=='undefined'){noGroupLoad=lazyLoaderNoGroupLoad;} //8-21-24 - use global preset if not specifically designated
	if(typeof pageLayout800 == 'undefined'){pageLayout800=0;}//currently pageLayout800 is set in site.js 
	parentEle=typeof parentEle=='undefined'?'':(parentEle?parentEle.trim()+' ':''); //console.log(parentEle+"."+lazyClass+', ct: '+$(parentEle+"."+lazyClass).length);
   //noThreshold=$(parentEle+"."+lazyClass).hasClass('lazy-load-in-viewport')?1:0; //global, NOT PER ITEM
   //noEffect=$(parentEle+"."+lazyClass).hasClass('lazy-load-no-fade')||$(parentEle+"."+lazyClass).hasClass('parallax-parent')?1:0; //global, NOT PER ITEM
   $(parentEle+"."+lazyClass).not('.lazy-loaded').each(function(){ //.lazy-img elements should also have lazy class added in site-functions when processed
      if(typeof($(this).attr('id'))=='undefined'){$(this).attr('id','id_'+Math.floor(Math.random() * 100001));} //CGA - generate an element ID if one does not exist
		$(this).attr('data-src-show',$(this).data(pageLayout800&&$(this).data('src-mobile')?'src-mobile':'src')); //set alternate mobile image source if needed and available
		lazyLoaderInstances[$(this).attr('id')]=$(this).lazy({
         chainable: false,
         visibleOnly: false,
         removeAttribute:false,
         attribute: 'data-src-show', //7-24-22 cannot use any code here to return the proper attribute name string, data-src-show value must be set above before lazy instantiation
         threshold: $(this).hasClass('lazy-load-in-viewport')?0:lazyLoaderThreshold, //pixels below viewport at which images are loaded - BCO tested $(this) works here
         effect: lazyNoFade||$(this).hasClass('split-static-slide')||$(this).hasClass('lazy-load-no-fade')||$(this).hasClass('parallax-parent')?'show':'fadeIn', //BCO tested $(this) works here
         effectTime: lazyNoFade||$(this).hasClass('split-static-slide')||$(this).hasClass('lazy-load-no-fade')||$(this).hasClass('parallax-parent')?0:lazyLoaderFadeTime, //BCO tested $(this) works here
         delay:parentEle&&!noGroupLoad?lazyLoaderGroupDelay:-1, //if a value is set here, ALL images in the current group will load together after this delay in miliseconds - http://jquery.eisbehr.de/lazy/example_delayed-loading
         afterLoad: function(element){ //console.log('lazy loaded '+element.attr('id'));//console.log(element.hasClass('lazy-load-no-fade'));
            element.addClass('lazy-loaded');
            if(element.hasClass('lazy-title-anim')){slideTitleAnim('.lazy-title-anim',1);} //TLI extra action
            if(element.hasClass('lazy-title-animate')){slideTitleAnim('.lazy-title-animate',1);} //TLI/EFCB extra action
				if(element.hasClass('split-static-slide')){element.addClass('slide-loaded');} //TLI/EFCB
            if(element.hasClass('parallax-parent')){ //TLI/EFCB - transfer the loaded background image from the parallax parent container to the skrollr display container
               element.data('bkgd-loaded',element.css('background-image'));
               if(skrollrObj){ //update the pximg element if skrollr is active
                  $('#pximg_'+element.attr('id')).css({backgroundImage:element.css('background-image'),backgroundPosition:element.css('background-position')}).addClass('pximg-loaded');
                  element.css('background-image','');
               }
            }
            //this.destroy(); console.log('destroyed');
         }
		});
	});
}

function waypointAnimSetup(parentEle){ //console.log('waypointAnimSetup parentEle: '+parentEle+', waypointAnimOffset: '+waypointAnimOffset);
	//setup waypoint controlled element animation - exact animation setup in CSS
	$(parentEle+".animate-item").not('.animated-item').each(function(){
      if(typeof($(this).attr('id'))=='undefined'){$(this).attr('id','id_'+Math.floor(Math.random() * 100001));} //CGA - generate an element ID if one does not exist
      waypointAnimations[$(this).attr('id')]=new Waypoint({
         element: $(this)[0], 
         handler: function(direction){ //console.log('waypoint triggered: #'+this.element.id); this.destroy();
            $("#"+this.element.id).addClass('animated-item'); //Waypoint.refreshAll();
         },
         offset: waypointAnimOffset//'85%'//'98%' //"bottom-in-view"//'95%'//
      });
	});
}

function returnPageOrientation(){//alert($(window).width()+'x'+$(window).height()+', '+window.innerWidth+'x'+window.innerHeight);
	//innerWidth and innerHeight are more accurate in mobile browsers, especially when the device is being flipped, causing a resize event
	return (mobileOrTabletDevice?window.innerWidth:$(window).width())>(mobileOrTabletDevice?window.innerHeight:$(window).height())?'landscape':'portrait';	
}

function pageFade(pgLink){
	if(pgLink=="#"){return;}
   if($("#fade-block").length==0){if(typeof pgLink!='undefined'){top.location.href=pgLink;}return;} //process here if no fade-block element
	if(typeof pgLink=='undefined'){//page fadein
      if(pageFadeColorizeBkgd){$('html').css('background',$("#content-inner").css('background-color'));} //TLI
		if(disablePageFade){$("#fade-block").css('display','none');} 
      else{$("#fade-block").delay(100).fadeOut(pageFadeSpeed);}
	}else{//page fadeout
		if(disablePageFade){top.location.href=pgLink;}
      else{
         $("#sidebar-flyout").removeClass("sidebar-flyout-open"); //TLI/EFCB close the sidebar menu if needed
         $("#fade-block").fadeIn((pageFadeSpeed-100),function(){
            top.location.href=pgLink;
            /*if(isSafari){*/$("#fade-block").delay(500).fadeOut(pageFadeSpeed);/*}*/ //4-3-25 Chrome now needs this as well when using back button
         }); 
      }
	}
}

function pageFadeConfig(parentEle){
   parentEle=typeof parentEle == 'undefined'?'':parentEle+' ';
   if(disablePageFade){return;}
   //capture all on-site page href links to first trigger fade-block fadeout before loading new page
   $(parentEle+"a:not(.noPageFade)").not('.initLink').each(function(){
		lnk=$(this).attr('href');
		if(typeof lnk!='undefined' && lnk.indexOf('/')===0 && lnk.indexOf('_uploads')==-1 && lnk.indexOf('/?')==-1 && lnk.indexOf('/_pdf')==-1 && $(this).attr('target')!='_blank'){ //console.log('page link found: '+lnk);
			//$(this).attr('href',"javascript:pageFade('"+lnk+"');").addClass('initLink');
			$(this).addClass('initLink').on('click',function(){pageFade($(this).attr('href'));return false;});
		}
	});
	//capture any onsite page links triggered by element onclick attributes
	$(parentEle+"[onclick]").each(function(){
		lnk=$(this).attr('onclick');
		if(typeof lnk!='undefined' && lnk.indexOf("window.location='/")===0 && lnk.indexOf('_uploads')==-1 && lnk.indexOf('/?')==-1 && $(this).attr('target')!='_blank'){ //console.log('onclick link found: '+lnk);
			$(this).attr('onclick',"javascript:pageFade("+lnk.replace('window.location=','').replace(';','')+");").addClass('initLink');
		}
	});
}

//mobile nav setup
function closeNavShowHash(hashArg){
	if($("#header-nav-mobile-container").css('display')=='block'){toggleMobileNav();}
   if(typeof scrollToNavAware =='function'){scrollToNavAware(hashArg);}
	else{jqueryScroll(hashArg);}
}

function toggleMobileNav(hashArg,navPfx){//console.log('toggleMobileNav, hashArg: '+hashArg+', navPfx: '+navPfx);
   if($("#mobile-nav-icon").length>0){toggleMobileNavAlt();return;}//rerout to older mobile nav toggle
	if(typeof navPfx=='undefined'){navPfx='mobi-menu';}
	$("#nav-toggle").toggleClass('mobile-nav-open');
	$("body").toggleClass('mobile-nav-open');
	if(!mobileNavFullScreen){ //TLC Rentals is NOT a full-screen nav
      newDispState=$("#nav-toggle").hasClass('mobile-nav-open')?'block':'none';
   }else{
      newDispState=toggleOverlayDiv('header-nav-mobile-container',mobileNavFullScreen);
   }
   if(newDispState=='block'){//console.log('open');
      //$('#header').stop().css({top:0}); console.log('top zeo');
      //10-24-20 added for HODAG - header-nav-mobile-container padding top set here - mobile nav overlay will always be 100vh and nav bar should remain fixed position so nav scrolls under - this makes sure the content of the mobilenav is not obscured by the navbar
      //this cant be done via CSS for HODAG because the banner bar within the header may have variable height depending on its content
      //$("#header-nav-mobile-container").css('padding-top',$("#header").css('position')=='fixed'?$("#header").outerHeight():0); //this DOES NOT WORK because header css position change from absolute to relative triggered in toggleOverlayDiv is not reflected here immediately
      if(!mobileNavOpenNonFixedHeader){$("#header-nav-mobile-content").css('padding-top',$("#header").outerHeight());} //this should ONLY BE USED if the header is to remain fixed position during mobile nav display
      navCt=0;
      $(window).clearQueue().delay(overlayDivFadeSpeed).queue(function(next){ 
         //console.log($("#header").css('position'));
         $("."+navPfx+" .topnav_a").each(function(){
            $(this).delay(navCt*mobileNavItemAnimSpeed).queue(function(next){ 
               $(this).addClass('navAnimated');
               if($(this).next().hasClass(navPfx+'-subtoggle')){$(this).next().addClass('navAnimated');}
               next(); 
            });
            navCt++;
         });
         next(); 
      });
   }else{//console.log('close');
      if(mobileNavCollapseUL){$("."+navPfx+" ul").each(function(){$(this).css('display','none');});} //TLI collapses UL
      else{$("."+navPfx+" div").each(function(){$(this).css('display','none');});}
      $("."+navPfx+" a").each(function(){
         $(this).clearQueue().removeClass('navAnimated').removeClass('subNavOpen');
      });
      $("."+navPfx+" ."+navPfx+"-subtoggle").html('+');
   }
   if(typeof toggleMobileNavCustom == 'function'){toggleMobileNavCustom();}//additional nav toggle actions - iPoint
	if(hashArg){jqueryScroll(hashArg);}
}

function toggleMobileNavAlt(inlineDisplay,skipNavAnim,animVert){ //older mobile nav toggle
   if(skipNavAnim!=1){skipNavAnim=0;}
	if(inlineDisplay!=1){inlineDisplay=0;}
	if(animVert!=1){animVert=0;}
	switch($("#header-nav-mobile").css('display')){
		case 'block':
			if(!skipNavAnim){$("#mobile-nav-icon").animate({'top':-17,'opacity':1},200);}
			$("#header-nav-mobile-container").removeClass('nav-mobile-enclose-shadow');
			if(animVert==1){$("#header-nav-mobile").animate({opacity:'hide',height:'hide'},200);}
			else{$("#header-nav-mobile").fadeOut(200);}
		break;
		case 'none': 
			if(!skipNavAnim){$("#mobile-nav-icon").animate({'top':0,'opacity':.6},200);}
			if(!inlineDisplay){$("#header-nav-mobile-container").css({'position':'fixed'});}
			$("#header-nav-mobile-container").addClass('nav-mobile-enclose-shadow');
			if(animVert==1){$("#header-nav-mobile").animate({opacity:'show',height:'show'},200);}
			else{
				$("#header-nav-mobile").fadeIn(200,
					function(){if(!inlineDisplay){
						if($(window).scrollTop()>0){$(window).scrollTop(0);} 
						$("#header-nav-mobile-container").css('position','absolute');
					}}
				);
			}
		break;
	}
}

function toggleMobileSubNav(jqThis,checkNext,navPfx){ //console.log($(jqThis).next().hasClass('mobi-menu-subtoggle')+', '+$(jqThis).next().css('display'));
   //if($("#mobile-nav-icon").length>0){toggleMobileSubNavAlt(jqThis,checkNext,navPfx);return;}//reroute to older mobile subnav toggle
	jqInit=checkNext==1?jqThis:jqThis.prev(); //console.log(jqInit.attr('id'));
	if(typeof navPfx=='undefined'){navPfx='mobi-menu';}
   jqTarget=jqThis.next();
	if(checkNext==1 && jqTarget.hasClass(navPfx+'-subtoggle')){jqTarget=jqTarget.next();}
	isOpening=jqTarget.css('display')=='none'?1:0; //console.log('isOpening: '+isOpening);
	jqTarget.animate({height:(isOpening?'show':'hide')},250,'easeOutQuad');
	if(isOpening){jqInit.addClass('subNavOpen');}
	else{jqInit.removeClass('subNavOpen');}
	//toggle subnav item visibility animation
	navCt=0; 
   jqTarget.children("ul").children("li").children(".subnav_a").each(function(){ //restrict to the current sublevel
		//console.log($(this).attr('id')+' / '+$(this).attr('class'));
		if(isOpening){
			$(this).delay(navCt*65).queue(function(next){ 
				$(this).addClass('navAnimated'); //console.log($(this).attr('id')+' - '+"."+navPfx+"subtoggle: "+$(this).siblings("."+navPfx+"-subtoggle").length);
				$(this).siblings("."+navPfx+"-subtoggle").addClass('navAnimated');
				next(); 
			});
			navCt++;
		}else{
			$(this).clearQueue().removeClass('navAnimated');
			$(this).siblings("."+navPfx+"-subtoggle").removeClass('navAnimated');
		}
	});
	//toggle the subnav open/close indiactor
   if(mobileNavSubTogCSS!=1){
	   jqInit.siblings("."+navPfx+"-subtoggle").html(isOpening?'&ndash;':'+');
   }else if(isOpening){
      jqInit.siblings("."+navPfx+"-subtoggle").addClass('subToggleOpen');
   }else{
      jqInit.siblings("."+navPfx+"-subtoggle").removeClass('subToggleOpen');
   }
}

function scrollToNavAware(anchorID,animSpeed,addOffset,noInterrupt){ //console.log('scrollToNavAware');
	if(typeof animSpeed=='undefined'){animSpeed=400;}
	if(typeof addOffset=='undefined'){addOffset=0;}
	if(typeof noInterrupt=='undefined'){noInterrupt=0;}
   scrTarget=anchorID.indexOf('.')===0?anchorID:"#"+anchorID; //console.log(topOffsetCalc(addOffset));
   scrollOffset=topOffsetCalc(addOffset,0,1); //console.log('scrollOffset: '+scrollOffset);
	gotoScrollTop=$(scrTarget).offset().top-scrollOffset; //console.log(scrTarget); //console.log(gotoScrollTop); - topOffsetCalc() is nav aware
   autoScrolling=1; setTimeout(function(){autoScrolling=0;},animSpeed); //added autoScrolling indicator timeout so mobile nav will NOT hide during this auto-scroll - 2-29-24 TLI
	$.scrollTo(gotoScrollTop,animSpeed,{easing:'easeInOutQuart',interrupt:(mobileOrTabletDevice||noInterrupt==1?false:true)/*,onAfter:function(){autoScrolling=0;}*/}); //onAfter doesnt seem to fire if scroll is interrupted
}

function navBarUpdate(forceDir,navOnly,init){ //console.log('navBarUpdate, navOnly: '+navOnly+', init: '+init); 
	//update variables and full height divs when called during init or resize operations (skipped for calls during scrolling)
	if(noNavUpdate){return;}
   navBarChanged='';
   if(init){pageInitScrollTop=$(document).scrollTop();}
   if(init||!navOnly){//console.log('update divs');
      mobileNavForceShowOffset=$(window).height()*mobileNavForceShowDistance; 
      mobileNavAnimResizeOffset=$(window).height()*mobileNavAnimResizeDistance;
		headerActive=$("#header").css('display')=='block'?1:0; //needed for TLI/EFCB where sidenav is used on desktop
      mobileNavActive=$("#header-nav-mobile-toggle-container").css('display')=='block'?1:0; //window.matchMedia("(max-width:959px)").matches?1:0;
		headerBannerHeight=$("#header-banner").length>0?$("#header-banner").outerHeight():0;
		headerFullHeight=$("#header-reference").outerHeight()+headerBannerHeight;
		headerSmallHeight=($("#header-reference-small").length==0?headerFullHeight:$("#header-reference-small").outerHeight())+headerBannerHeight;//console.log('headerSmallHeight: '+headerSmallHeight);
		$("#header-push").height(headerFullHeight); //header reference is always the initial full nav height
      $("#header").css('position','fixed'); //10-18-22 - only make the header fixed AFTER the header-push height is set to avoid page shift down while loading and waiting for header-push to have an assigned height
      //MOORE, BCO - change heights for flex full height and full page divs 
      if(pageInitScrollTop==0){ //4-2-24 - DO NOT RESIZE DIVS if NOT at top of page when it loads - THIS WILL REALLY HURT CLS SCORE if everything shifts around above the current location on the page (HODAG home)
         $('.flex-full-height, .flex-full-page').each(function(){
            if((!pageLayout800||!$(this).hasClass('flex-nat-height-800'))&&(!pageLayout600||!$(this).hasClass('flex-nat-height-600'))){
               //top div uses the full nav height (same height as header-push) any subsequent divs use the small header height - on mobile where nav show/hide is used, small header height should be zero, assuming total full height with hidden nav
               fixedHeight=$(window).height()-($(this).offset().top<=mobileNavAnimResizeOffset?headerFullHeight:headerSmallHeight);
               $(this).css({height:fixedHeight+'px'});
            }
         });
         // ### 12-06-23 NOT SURE IF THIS IS STILL USED ON SOME SITES - was commented out for most recent sites ###
         //fix height of designated divs - CANT USE 100vh on mobile browsers because viewport height changes dynamically and some (chrome) will change the alerted viewport height on that change - SHOULD USE 100dvh instead
         if(mobileOrTabletDevice && pageLayoutOrientChange){//console.log('full height fix');
            $('.mobile-restricted-full-height, .mobile-hero-full-height').each(function(){
               //## show fullscreen as long as the width is not less than 1/2 the screen height, otherwise the image is too tall and cropped - this could also be set to exclude iPads
               useFixed=$(window).height()*.5<$(window).width() && $(window).height()< 1000?1:0;
               fixedHeight=$(window).height()-(headerFullHeight?headerFullHeight:headerSmallHeight);
               //apply the fixed div height
               $(this).css({height:useFixed?fixedHeight+'px':'',maxHeight:useFixed?'none':''});
            });
         }
      }	
   }

   //12-16-24 TWRP/CavCom - allow for a promo banner above nav
   if($("#header-top-banner").length>0){
      headRelPos=$(document).scrollTop()-$("#header-top-banner").height(); //console.log(headRelPos);
      $("#header").css('position',headRelPos>0?'fixed':'absolute');
   }

	//update header drop shadow
	if($(document).scrollTop()>0 && !$("#header").hasClass('header-dropshad')){$("#header").addClass('header-dropshad');}
	else if($(document).scrollTop()<=0 && $("#header").hasClass('header-dropshad')){$("#header").removeClass('header-dropshad');}
	
	//resize header navbar if needed - skip this if an overlay is open
	if(!$("body").hasClass("overlay-div-open")){
      headerRef=$("#header-outer").length>0?$("#header-outer"):$("#header"); //TLI/EFCB don't use header-outer
		//added 10-22-20 to avoid jerky flashing on iOS browsers when going negative top scroll - CSS header-static class REMOVED 12-16-21 - created flash during initial scroll down
		if(!init){
			if($(document).scrollTop()<=0 && headerRef.hasClass('header-static')==false){headerRef.addClass('header-static');}
			else if($(document).scrollTop()>0 && headerRef.hasClass('header-static')!=false){headerRef.removeClass('header-static');}
		}
		//display standard or small header
		if($(window).scrollTop()>mobileNavAnimResizeOffset){ 
			if(headerRef.hasClass('header-small')==false){
				headerRef.addClass('header-small'); navBarChanged+='height';
			}
		}else if(headerRef.hasClass('header-small')==true){
			headerRef.removeClass('header-small'); navBarChanged+='height';
		}
	}
	
	//update nav show/hide on mobile 
	if(mobileDevice && mobileNavActive==1 && (mobileNavNoToggle!=1 || $(document).scrollTop()<=0)){ //continue only if mobile nav is active and nav toggle is currently available
		if(typeof forceDir=='undefined'){forceDir='';}
      curScrollTop=$(document).scrollTop();
		
      posChange=init?0:curScrollTop-mobileNavSavedScrollTop;
      
		mobileNavSavedScrollTop=curScrollTop;//save current scrolltop for future show/hide checks
		
      //force the mobile navbar to display if the scrolltop is less than the mobileNavForceShowOffset and another forceDir has not already been set
		if(!forceDir && (curScrollTop<=mobileNavForceShowOffset)){forceDir='show';} //console.log('forceDir: '+forceDir);
		//show or hide the nav bar if needed
		if(forceDir!='' || (mobileNavNoToggle==0 && autoScrolling==0)){ //console.log('navBarUpdate proceed, autoScrolling: '+autoScrolling);
			if($("#header").hasClass('header-hide') && (forceDir=='show' || curScrollTop<mobileNavForceShowOffset || posChange<-mobileNavPosChangeSensitivity)){//console.log('show nav');
				$("#header").removeClass('header-hide'); navBarChanged+='disp';
			}else if(!$("#header").hasClass('header-hide') && (forceDir=='hide' || (curScrollTop>=mobileNavForceShowOffset && posChange>mobileNavPosChangeSensitivity))){//console.log('hide nav');
				$("#header").addClass('header-hide'); navBarChanged+='disp';
			}
		}
	}

   //needed by TLI/EFCB for additional div sizing
   if(typeof navBarUpdateCustom=='function'){navBarUpdateCustom(forceDir,navOnly,init,navBarChanged);} 
}

function navbarSubnavCenter(){ //MGS - desktop subnav centering
	$(".topnav_li > ul").on('centerSubNav',function(){//console.log('triggered');
		//adjust drop menu LI placement based on parent LI location
		parentWidth=$(this).parent().width(); 
		//have the drop nav be at least as wide as the parent div
		if($(this).width()<parentWidth){ 
			$(this).width(parentWidth);
			//also adjust any submenus offset
			$(this).find('ul').each(function(){$(this).css('left',(parentWidth-5));});
		}
		//center the dropdown menu under the parent li
		myLeftOffset=Math.floor((parentWidth-$(this).width())/2);
		if(myLeftOffset!=0){$(this).css('left',myLeftOffset);}
	});
	$(".topnav_li").on('mouseenter',function(){//console.log('entered');
		$(this).children("ul").trigger('centerSubNav');
	});
}

function pageLayoutVarSetup(init){
	//if these variables are already set and this is a page init call, don't reset them - this function may be called more than once on initial page load
	if(init && pageLayoutSize!=''){return;} 
	//setup device and viewport variables that help control layout
	pageLayout800=window.matchMedia("(max-width:800px)").matches?1:0;
	pageLayout600=window.matchMedia("(max-width:600px)").matches?1:0;
	pageLayoutSizePrev=pageLayoutSize;
	pageLayoutSize=(mobileOrTabletDevice==1 || pageLayout800)?'mobile':'desktop';
	pageLayoutOrientPrev=pageLayoutOrient; 
	pageLayoutOrient=returnPageOrientation();
	pageLayoutOrientChange=pageLayoutOrient!=pageLayoutOrientPrev?1:0;
	pageLimitedViewport=(pageLayoutSize=='mobile' && pageLayoutOrient=='landscape')||($(window).width()<360||$(window).height()<620)?1:0;
	//console.log('pageLayout800: '+pageLayout800+', pageLayoutSize: '+pageLayoutSize+', pageLayoutOrient: '+pageLayoutOrient+', pageLimitedViewport: '+pageLimitedViewport);
}

function updateBkgdVideo(init){ // NOTE WE ASSUME ONLY ONE OF THESE PER PAGE - NOT TARGETING ANY UNIQUE IDs
	if($(".bkgd-video-slide").length==0){return;} //dont continue if no background video is available
	if(init==3){ //video source load
      if(bkgdVideoLoadReady==0){setTimeout(function(){updateBkgdVideo(3);},100);}
      $(".bkgd-video-slide-video")[0].src=$(".bkgd-video-slide-video").attr('data-src'+(pageLayoutSize=='mobile'?'-mobile':'')); //NOTE - the mask and bkgd fadeout will be triggered by the video oncanplay event set above
   }else if(init==2){ //play/pause check
		if($(".bkgd-video-slide-video").data('videoActive')==1){//console.log('active');
			docScrollTop=$(document).scrollTop();
			//viewHeightCut=($(window).height()-$("#header-push").height())/2;
			vidTop=$(".bkgd-video-slide").offset().top;//console.log('vidTop: '+vidTop);
			vidHeight=$(".bkgd-video-slide").height();
			vidViewStart=parseInt(vidTop-($(window).height()/*-$("#header-push").height()*/)/*viewHeightCut*/);
			vidViewStop=parseInt(vidTop+vidHeight-($("#header").height()+10)/*-viewHeightCut*/);
			//console.log(docScrollTop+': '+vidViewStart+', '+vidViewStop+', '/*+viewHeightCut+', '*/+vidTop);
			if(docScrollTop>=vidViewStart && docScrollTop<=vidViewStop){ 
				if($(".bkgd-video-slide-video").data('videoLooping')==0){//console.log('play');
					$(".bkgd-video-slide-video").data('videoLooping',1);
					$(".bkgd-video-slide-video")[0].play();
				}
			}else if($(".bkgd-video-slide-video").data('videoLooping')==1){//console.log('pause');
				$(".bkgd-video-slide-video").data('videoLooping',0);
				$(".bkgd-video-slide-video")[0].pause();
			}
		}
	}else if(init || pageLayoutSizePrev!=pageLayoutSize){ //check for background videos which cannot play on mobile devices
		bkgdVideoMobileShow=bkgdVideoMobileShow&&$(".bkgd-video-slide-video").attr('data-src-mobile')?1:0;
		bkgdVideoAnimDelay=pageAnimProps.animDelay; //set initial convenience animation delay variable for use below
		if(typeof bkgdVideoAnimDelayCustom!=='undefined'){bkgdVideoAnimDelay=bkgdVideoAnimDelayCustom;}
		if(pageLayoutSize=='mobile' && !bkgdVideoMobileShow){
			//fade out background video if loaded
			if($(".bkgd-video-slide-video").data('videoInit')==1){
				$(".bkgd-video-slide-video").data('videoActive',0);
				$(".bkgd-video-slide-video").data('videoLooping',0);
				$(".bkgd-video-slide-mask").stop().css({opacity:1,display:'none'}).fadeIn(pageAnimProps.animSlow,function(){$(".bkgd-video-slide-video")[0].src='';/*console.log('kill src');/*$("#home1video")[0].pause();*/});
			}
			//load and fade up background image if needed - preload before fading
			$(".bkgd-video-slide-bkgd").stop().css({opacity:1,display:'none'});
			if($(".bkgd-video-slide-bkgd").css('background-image').indexOf('spacer.png')!=-1){
				pageAnimProps['bkgd-video-slide-preloader']=Date.now();
				$('body').append('<img src="" id="bkgd-video-slide-preloader" style="display:none;" />');
				$("#bkgd-video-slide-preloader").on('load',function(){
					myAnimDelay=bkgdVideoAnimDelay-(Date.now()-pageAnimProps['bkgd-video-slide-preloader']); 
               if(myAnimDelay<0||$(".bkgd-video-slide-video").data('videoInit')==1){myAnimDelay=0;}
					$(".bkgd-video-slide-bkgd").css({backgroundImage:"url('"+$(this).attr('src')+"')"}).delay(myAnimDelay).fadeIn(pageAnimProps.animSlow);
					$(this).remove();
				}).attr('src',$(".bkgd-video-slide-bkgd").attr('data-src'));
			}else{
				$(".bkgd-video-slide-bkgd").fadeIn(pageAnimProps.animSlow); //no delay here since the image would have already been loaded previously, so initial animation would be complete
			}	
		}else if(pageLayoutSize=='desktop'||bkgdVideoMobileShow){//console.log('desktop');
			//if the video has not yet been loaded, do it here, otherwise reset the src below
			if($(".bkgd-video-slide-video").data('videoInit')!=1){//console.log('load video');
				$(".bkgd-video-slide-video").data('videoInit',1);
				//COMMENT OUT THIS oncanplay() SETUP IF IT CAUSES ISSUES - AND USE THE setTimout() BELOW INSTEAD
				videoPlayDelayTimer=new Date().getTime()+bkgdVideoAnimDelay;
				$(".bkgd-video-slide-video")[0].oncanplay=function(){//console.log('canplay'); //NOTE - oncanplay is called on each loop of the video 
					if($(".bkgd-video-slide-video").data('videoActive')!=1){//console.log('setTimeout');
						$(".bkgd-video-slide-video").data('videoLooping',0);
						$(".bkgd-video-slide-video")[0].pause();
						jsTimeout=videoPlayDelayTimer-new Date().getTime(); if(jsTimeout<0){jsTimeout=1;}
						setTimeout(
							function(){if(pageLayoutSize=='desktop'||bkgdVideoMobileShow){ //check to make sure a source is available - will not be if viewport was changed from desktop to mobile size BEFORE video started playing
								$(".bkgd-video-slide-video").data('videoActive',1);
								//$(".bkgd-video-slide-video").data('videoLooping',1);
								//$(".bkgd-video-slide-video")[0].play();
                        updateBkgdVideo(2); //8-14-25 TLC - use the scroll callback to initiate play rather than assuming immediate play - this way background videos not currently in the viewport will not play until visible
								$(".bkgd-video-slide-mask, .bkgd-video-slide-bkgd").stop().animate({'opacity':0},pageAnimProps.animSlow,function(){$(this).css('display','none');});
								window.addEventListener('scroll',function(){updateBkgdVideo(2)});
							}},
							jsTimeout
						);
					}
				}
				bkgdVidOpts={src:[''],autoplayFallback:$(".bkgd-video-slide-bkgd").attr('data-src')};//bkgdVidOpts.parallax={effect:1.4};
				//bkgdVidOpts.parallax={};//bkgdVidOpts.parallax={effect:1.5}; is default value. set parallax object to empty to eliminate parallax effect
				const bkgdVideoVar = new BackgroundVideo('.bkgd-video-slide-video',bkgdVidOpts); //add the video below for consistency for init and post-init operations
            bkgdVideoLoadReady=1;
			}//console.log($(".bkgd-video-slide-video").attr('data-src'+(pageLayoutSize=='mobile'?'-mobile':'')));
         if(bkgdVideoLoadCustom==0&&bkgdVideoLoadAfterHero==0){
            updateBkgdVideo(3); //11-21-25 TLC - actually attach the video via an additional function call so it can be delayed if desired
         } 
			/*//USE THIS - IF SKIPPING THE oncanplay() SETUP ABOVE FOR WHATEVER REASON
			setTimeout(
				function(){if(pageLayoutSize=='desktop'){ //check to make sure a source is available - will not be if viewport was changed from desktop to mobile size BEFORE video started playing
					$(".bkgd-video-slide-video").data('videoActive',1);
					$(".bkgd-video-slide-video").data('videoLooping',1);
					$(".bkgd-video-slide-mask, .bkgd-video-slide-bkgd").stop().fadeOut(pageAnimProps.animSlow);
				}},
				animDelay
			);*/
		}
	}
}

//autoscroll initial setup
function autoScrollInit(){
	//autoscroll window events - if the current page uses auto scrolling to content divs, setup additional event listeners here
	if(autoScrollActive==1){
		//cancel autoscrolling on user input
		$(window).on('mousedown keydown touchstart', function(e){ //console.log('ACTION: '+e.type);   $(window).on('mousedown keydown touchstart wheel DOMMouseScroll mousewheel
			$(window).stop(); $("html,body").stop(); autoScrolling=0;
			//prevent any autoscrolling if the mouse is down - user may be manually scrolling the page - this does NOT work on IE 10 & 11
			if((e.type=='mousedown'||e.type=='touchstart')&&isIE!=1&&overlayDivFreezePos!=1){autoScrollMouseDownScrollTop=$(document).scrollTop(); autoScrollDisabled=1;/*console.log('autoScrollDisabled');*/} 
		});
		//once the user releases the mouse, check immediately for autoscroll
		$(window).on('mouseup', function(e){ //console.log('mouseup ACTION: '+e.type);
			autoScrollDisabled=0;  
			//only run autoscroll process if the page has been moved since the mousedown event
			if(autoScrollMouseDownScrollTop!=$(document).scrollTop()&&overlayDivFreezePos!=1){autoScrollToNearestDiv();} 
		});
		$(window).on('touchend', function(e){ //console.log('mouseup ACTION: '+e.type);
			autoScrollDisabled=0;  
			//only run autoscroll process if the page has been moved since the mousedown event
			//if(autoScrollMouseDownScrollTop!=$(document).scrollTop()&&overlayDivFreezePos!=1){autoScrollToNearestDiv();} 
		});
		//ONLY add this if autoscroll is meant to force scroll wheel to move full auto-scroll blocks at a time (HODAG), vs free scrolling and then snapping (TLI/EFCB)
		if(autoScrollFullBlock){
			jQuery.fn.reverse = [].reverse; //tiny jquery core plugin to add reversal of returned selectors - used by mouse wheel tracking for div navigation
			window.addEventListener('wheel', function(event){ //console.log(event.deltaY); 
				d=new Date();curTime=d.getTime(); //console.log(autoScrollTriggered+', '+curTime);
				tmCk=(curTime-100)-autoScrollTriggered; //console.log(tmCk+', '+Math.abs(event.deltaY));
				if(!autoScrolling && tmCk>0){ //console.log('trigger'); //only trigger scroll if the wheel rolled at least the specified minimum distance - DOESNT WORK WITH FIREFOX
					if(event.deltaY<0 && $(document).scrollTop()>0){autoScrollRun('prev');}
					else if(event.deltaY>0 && $(document).scrollTop() < ($(document).height()-$(window).height())){autoScrollRun('next');}
				}
				if(Math.abs(event.deltaY)<autoScrollSensitivity){autoScrollTriggered=curTime;}
				event.preventDefault();
				event.stopPropagation();
			},{passive:false});
		}
		//add listener to track auto scroll action
		window.addEventListener('scroll',function(){autoScrollTimeout()});
	}
}

//start scroll position check timer
function autoScrollTimeout(){ //console.log('autoScrollTimeout, autoScrolling: '+autoScrolling+', autoScrollActive: '+autoScrollActive+', autoScrollDisabled: '+autoScrollDisabled);
	if(autoScrollActive!=1 || isIE==1){return;} 
	clearTimeout(autoScrollTimeoutInt);
	if(autoScrolling!=1 && autoScrollDisabled!=1){ //console.log('autoScrollTimeout set autoScrollTimeoutInt');
		autoScrollTimeoutInt=setTimeout(function(){autoScrollToNearestDiv();},autoScrollTimeoutWait);
	}
}

//run autoscrolling action
function autoScrollRun(scrollToID,animSpeed,parentDiv){ //console.log('autoScrollRun, scrollToID:'+scrollToID+', autoScrolling: '+autoScrolling);
	if(autoScrolling==1){return;}
	if(typeof scrollToID=='undefined'||!scrollToID){scrollToID='next';}
	if(typeof animSpeed=='undefined'||!animSpeed){animSpeed=autoScrollAnimSpeed;}
   addHeaderShim=$("#header").length>0&&headerActive&&!$("#header").hasClass('header-hide')?1:0;//headerActive set in navBarUpdate
	//find div if moving between autoscroll target elements
	if(scrollToID=='prev'||scrollToID=='next'){ 
		divGroup=typeof parentDiv=='undefined'||!parentDiv?'.autoScrollDiv':"#"+parentDiv+" > div";
		scrollDir=scrollToID; scrollToID=''; foundID=0;
		divData=findClosestDiv(parentDiv,scrollDir); //console.log('closest: '+divData[0].id+', lastID: '+divData[1]);
		if(scrollDir=='next'){
			$(divGroup).each(function(){
				//if(!scrollToID && $(this).offset().top>$(document).scrollTop() && $(document).scrollTop()<($(document).height()-$(window).height())){scrollToID=$(this).attr('id');} //DOESNT COMPENSATE FOR NAV HEIGHT (PUSH)
				if(foundID==1){scrollToID=$(this).attr('id');foundID++;}
				else if(!foundID && divData[0].id == $(this).attr('id')){foundID=1;}
			});
         //console.log('scrollToID: '+scrollToID);
		} 
		if(scrollDir=='prev'){
         //NOTE - the reverse() function is a custom add-on to the jquery core, setup in autoScrollInit function
			$(divGroup).reverse().each(function(){ //console.log(divData[0].id +' / '+ $(this).attr('id')); 
				if(!scrollToID){	
					gotoScrollTop=$(this).offset().top;
               scrollTopShim=!addHeaderShim?0:(gotoScrollTop<=mobileNavAnimResizeOffset?headerFullHeight:headerSmallHeight); //headerFullHeight and headerSmallHeight are set in navBarUpdate
					if(gotoScrollTop-($(document).scrollTop()+(scrollTopShim-2))<0){scrollToID=$(this).attr('id');} 
               //add -2 to the scrollTopShim because sometimes there is a very small negative fractional value returned for top position of currently visible div when it is not set to be exactly full viewport height, like -0.01, so just using 0 doesn't work reliably
				}
			});
		} //console.log('scrollToID: '+scrollToID);
	} //console.log('scrollToID: '+scrollToID);
	if(scrollToID!=''){ //console.log('scrollto: '+scrollToID); //continue if a scrollToID value is available
		initScrollTop=gotoScrollTop=$('#'+scrollToID).offset().top; //console.log('init gotoScrollTop: '+gotoScrollTop+', document scrolltop: '+$(document).scrollTop());
      scrollTopShim=!addHeaderShim?0:(gotoScrollTop<=mobileNavAnimResizeOffset?headerFullHeight:headerSmallHeight); //headerFullHeight and headerSmallHeight are set in navBarUpdate
      usePartialOffset=$('#'+scrollToID).hasClass('partialScroll')||(autoScrollPartialHeightPerc && !$('#'+scrollToID).hasClass('fullScroll') && $('#'+scrollToID).outerHeight()<=($(window).height()*autoScrollPartialHeightPerc))?1:0;
      partialHeightOffset=usePartialOffset?$(window).height()-$('#'+scrollToID).outerHeight():0; //use partial offset 
      //partialHeightOffset=!autoScrollPartialHeightPerc?0:(!$('#'+scrollToID).hasClass('fullScroll') && $('#'+scrollToID).outerHeight()<=($(window).height()*autoScrollPartialHeightPerc)?$(window).height()-$('#'+scrollToID).outerHeight():0); //use partial offset if the current div is less than specified percent of the window height	
		gotoScrollTop-=(partialHeightOffset?partialHeightOffset:scrollTopShim);

		scrollMax=$(document).height()-$(window).height();
		if(gotoScrollTop>scrollMax){gotoScrollTop=scrollMax;} //autoscroll to the bottom of the page
      //run scroll only if there is a change in scroll position - OR if the current scrollto div is not already at the top if usually setup for partial scroll
		if($(document).scrollTop()!=gotoScrollTop && (!usePartialOffset||$(document).scrollTop()!=initScrollTop)){ //console.log('animate scrolltop from: '+$(document).scrollTop()+' to '+gotoScrollTop);
			autoScrolling=1;
			$.scrollTo(gotoScrollTop,animSpeed,{easing:'easeInOutQuart',interrupt:(mobileOrTabletDevice?false:true),onAfter:function(){autoScrolling=0;},fail:function(){autoScrolling=0;}}); //slight delay after scroll is complete before allowing scroll again
		}
      if(typeof autoScrollRunCustom == 'function'){autoScrollRunCustom(scrollToID,animSpeed,parentDiv);} //TLI/EFCB
	}
}

//scroll to nearest content block
function autoScrollToNearestDiv(parentDiv){ //console.log('autoScrollToNearestDiv, parentDiv: '+parentDiv);
	if(overlayDivFreezePos!=1){
		curScrollTop=$(document).scrollTop(); 
		if(curScrollTop==$(document).height()-$(window).height()){return;} //dont auto scroll if at the bottom of the document
		divData=findClosestDiv(parentDiv); //console.log('divData[0].id: '+divData[0].id);
		if(divData[0].id!='' && (pageLimitedViewport!=1 || !$('#'+divData[0].id).hasClass('mobile-landscape-natural-height'))){//console.log('#'+divData[0].id);
			//DONT run the auto scroll IF ...
			//1. the top of the scrollto element is below the viewport midline
			//2. the bottom of the scrollto element is above the viewport midline 
			//3. the bottom of the scrollto element is above the top of the viewport, but there is not more than half a viewport of height left below the scrollto item - meaning the content below could never be seen as the document would always scroll back up
			halfHeight=$(window).height()/2;
			//setup autoscroll min and max - compensate for half-height-div half-height divs
			autoScrollMin=$('#'+divData[0].id).offset().top-($('#'+divData[0].id).hasClass('half-height-div')?halfHeight:0);
			autoScrollMax=$('#'+divData[0].id).offset().top+$('#'+divData[0].id).outerHeight();
			autoScrollMaxCk=halfHeight>$('#'+divData[0].id).outerHeight()?autoScrollMax:autoScrollMax-halfHeight;
			if(curScrollTop+halfHeight > autoScrollMin && curScrollTop < autoScrollMaxCk && (curScrollTop < autoScrollMin || $(document).height() > autoScrollMax+halfHeight+10)){ //console.log('divData[0].id: '+divData[0].id);
				autoScrollRun(divData[0].id); 
			}
		}
	}
}

//find closest child div under the specified parent div OR among all available autoScrollDivs
function findClosestDiv(parentDiv,scrollDir){ //console.log('findClosestDiv for parentDiv: '+parentDiv+', scrollDir: '+scrollDir);
	divGroup=typeof parentDiv=='undefined'||!parentDiv?'.autoScrollDiv':"#"+parentDiv+" > div";
	lastDivID=""; curScrollTop=$(document).scrollTop(); closestDiv={'id':'','pos':0}; curOffset=0; absOffset=0; //console.log('curScrollTop: '+curScrollTop);
	$(divGroup).each(function(){//autoScrollDiv - DONT adjust fixed divs or divs that are over 1.3x the window height (1.3x to accomodate divs that may still be be animating height adjustment after a screen resize)
		//if(typeof $(this).attr('id')!='undefined' && $(this).css('position')!='fixed' && $(this).height()<=$(window).height()+($(window).height()/3)){ 
		if(typeof $(this).attr('id')!='undefined' && $(this).css('position')!='fixed'){ 
			lastDivID=$(this).attr('id'); //console.log('cur div ID: '+lastDivID+', position: '+$(this).css('position'));
			//compensate for half-height-div half-height divs
			curOffset=$(this).offset().top-($(this).hasClass('half-height-div')?$(window).height()/2:0)-curScrollTop;
			//compensate for the height of the header if visible
			if($("#header").length>0&&headerActive&&!$("#header").hasClass('header-hide')){curOffset-=($(this).offset().top<=mobileNavAnimResizeOffset?headerFullHeight:headerSmallHeight);} //headerFullHeight and headerSmallHeight are set in navBarUpdate

			//console.log('cur div ID: '+lastDivID+', curOffset: '+curOffset);
			//only continue if the current div is less than 1.3x the size of the window OR we are above that div
			if(curOffset>0 || $(this).height()<=$(window).height()+($(window).height()/3)){
				absOffset=Math.abs(curOffset); //console.log($(this).attr('id')+', '+closestDiv.pos+', '+curOffset+', '+absOffset);
				//if(closestDiv.id=='' || closestDiv.pos>=absOffset){
				if(closestDiv.id=='' || closestDiv.pos>absOffset || (scrollDir=='next' && Math.round($(this).offset().top) < Math.round(curScrollTop+($(window).height()/2)))){
					closestDiv.pos=absOffset; closestDiv.id=$(this).attr('id'); //console.log('cur closestDiv: '+closestDiv.id+', pos: '+closestDiv.pos);
				} 
			}
		}
	}); 
	return [closestDiv,lastDivID];
}

//animate specified characters or words - TLI
function textAnim(txtBlock,animType,animDelay,delayInc){
	txtBlockObj=typeof txtBlock=='object'?txtBlock:$(txtBlock); //console.log(txtBlockObj.html());
	if(typeof animType=='undefined'){animType='block';}
	if(typeof animDelay=='undefined'){animDelay=pageAnimProps.animDelay;}
	if(typeof delayInc=='undefined'){delayInc=pageAnimProps.delayInc;}
	txtNew=""; typeDelayInc=delayInc;
	switch(animType){
		case 'char':
			txtChars=txtBlockObj.html().split('<br>').join('~').split(' ').join('^').split('&nbsp;').join('`');
			for(i=0,len=txtChars.length;i<len;i++){txtNew+='<span>'+txtChars[i]+'</span>';}
			$(txtBlock).html(txtNew.split('<span>~</span>').join('</span><br><span>').split('<span>^</span>').join('</span> <span>').split('`').join('&nbsp;'));
		break;
		case 'word':
		case 'line': typeDelayInc+=(typeDelayInc*(animType=='line'?5:4));
			txtNew=txtBlockObj.html();
			wordSplits=animType=='line'?['<br>']:['<br>','&nbsp;',' ']; 
			for(i in wordSplits){
				txtSplit=txtNew.split(wordSplits[i]); txtNew="";
				for(ii in txtSplit){
					txtNew+=(txtNew!=''?'</span>'+wordSplits[i]+'<span>':'')+'<span>'+txtSplit[ii]+'</span>';
				}
			}
			txtBlockObj.html(txtNew);
		break;
		case 'block': break; //nothing more needed for full block animation
	}
	txtBlockObj.html('<span class="txtAnim-'+animType+'">'+txtBlockObj.html()+'</span>');
	txtBlockObj.find("span > span").each(function(){
		$(this).delay(animDelay).queue(function(next){ 
			$(this).addClass('txtAnimated');
			next(); 
		});
		animDelay+=typeDelayInc;
	});
	txtBlockObj.css({visibility:'visible'});
	return animDelay;
}

//function to update variables and layout on page init and viewport resize
function updatePageLayout(init){ //console.log('update page layout'); //console.log('updatePageLayout');
	//set current page layout size and orientation variables - this will already have been done 
	pageLayoutVarSetup(init);
	//make sure mobile nav height and variables are accurate
	navBarUpdate('',0,init);	
	//update background video or image as needed
	updateBkgdVideo(init); 
   //run any special page animations setup in site.js - CavCom
   if(typeof updatePageLayoutCustom=='function'){updatePageLayoutCustom(init);}
   //run any special page animations setup in site.js - CavCom
   if(typeof pageAnimation=='function'){pageAnimation();}
	//check for autoscroll realignment after page resize
	autoScrollTimeout();
   //mobileImageInsertion(init);
}

function updatePageScroll(init){ //console.log('updatePageScroll, init: '+init);
	//add scrolling event listener on init	
	if(init){window.addEventListener('scroll',function(){updatePageScroll()});}
	//make no scrolling adjustments to the main page content if an overlay window is open
	if(!init && overlayDivFreezePos!=0){return;} 
	//make sure mobile nav height and variables are accurate
	navBarUpdate('',1,init);
   if(typeof updatePageScrollCustom == 'function'){updatePageScrollCustom(init);} //TLI/EFCB
	//check if the footer CTA should be fixed
	fixedFooterCheck(init);
}

//control fixed footer call-to-action div placement - CavCom v2
function fixedFooterCheck(init){ 
	if(!mobileOrTabletDevice && $("#page").hasClass('fixed-footer') && !$("body").hasClass('overlay-div-open')){//console.log('fixedFooterCheck');
		triggerPos=$("#footer").offset().top-$(window).height();
		//console.log($(document).scrollTop()+' '+triggerPos);
		if(triggerPos>0&&$(document).scrollTop()<triggerPos){//console.log('add fixed');
			$("#footer-cta-fixed-spacer").height($("#footer-cta").outerHeight()); //console.log($("#footer-cta-fixed-spacer").height());
			$("#footer-cta").addClass('footer-cta-fixed');
			if(init){
				$("#footer-cta").css({bottom:-$("#footer-cta").outerHeight()}).delay(4000).animate({bottom:0},500);
			}
		}else{//console.log('remove fixed');
			$("#footer-cta-fixed-spacer").height(0);
			$("#footer-cta").stop().css({bottom:0}).removeClass('footer-cta-fixed');
		}
	}
}

//autoscroll page if an autoscroll target has been set - values set in admin, called in footer-standard.php onload setup
function initAutoScrollCheck(){//console.log('initAutoScrollTarget: '+initAutoScrollTarget);
	if(typeof initAutoScrollTarget=='undefined'||typeof initAutoScrollMobileOnly=='undefined'||typeof mobileOrTabletDevice=='undefined'){return;}
   if(initAutoScrollTarget!="" && $("#"+initAutoScrollTarget).length>0 && (initAutoScrollMobileOnly==0 || mobileOrTabletDevice==1)){
      scrollTargetTop=$("#"+initAutoScrollTarget).offset().top;
      winScrollTop=$(window).scrollTop();
      winScrollThreshold=$(window).height()*initAutoScrollThreshold;
      //alert(scrollTargetTop+','+winScrollTop+','+winScrollThreshold);
      if(scrollTargetTop>(winScrollTop+winScrollThreshold)){//alert('adjust');
         setTimeout (function(){
            topOffset=topOffsetCalc(); //topOffsetCalc() in shared.js
            $.scrollTo(($("#"+initAutoScrollTarget).offset().top-topOffset),300,{easing:'easeInOutQuad','axis':'y',onAfter:function(){}});
         },0);
      }	
   }
}

function parallaxBkgdSetup(parentEle){
   $(parentEle+".parallax-bkgd").each(function(){
		$(this).parallax({imageSrc: $(this).data('parallax-src'),speed:.7});
	});
}

//2-29-24 TLI/EFCB - function triggered on window init and resize to make sure the specified text block font sizes are resized to fit the viewport
function fixedTextResize(fixedTextCk,init){//console.log('fixedTextResize, fixedTextCk:'+fixedTextCk);
	if(typeof fixedTextCk=='undefined'||fixedTextCk==''){fixedTextCk=".fixedSizeContent, .fixedSizeChildren";}//fixedSizeContent uses its parent as the target size, fixedSizeChildren uses itself as the target size
	$(fixedTextCk).each(function(){ 
		//capture container height and reset content height	
		noParent=$(this).hasClass('fixedSizeChildren')?1:0;																		
		containerHeight=(noParent?$(this).height():$(this).parent().height())+1; //+1 is to accommodate div size rounding errors
      containerWidth=(noParent?$(this).width():$(this).parent().width())+1; //console.log(containerWidth+', '+containerHeight);
		parentEle=noParent?'':$(this);
      $(this).data('displaySaved',$(this).css('display'));
		$(this).css('display','inline-block');
		//reset each text block to its original font size and height, then save its original font size and any transition data
		$(this).find(".fixedSizeText, .fixedSizeTextHalf, .fixedSizeTextMobile").each(function(){
			$(this).addClass('resizeItem'); //ths class is used below to quickly identify targets for resize loop below
         $(this).data('resizeDone',0); //reset resize done indicator
			$(this).data('transition',$(this).css('transition')); //save transition data
			$(this).css('transition','none'); //REMOVE any transition css so font-size changes are instantly reflected
			$(this).css('font-size',''); //reset to default font size
			$(this).data('origSize',parseFloat($(this).css('font-size'))); //save original size for reduction below
		});
		//reduce text block font sizes until overall content size is within the container size or the font simply can't go smaller
		for(i=99;i>=1;i--){ 
         reduceMore=0;
			$(this).find(".resizeItem").each(function(){
				if(!$(this).hasClass('fixedSizeTextMobile') || pageLimitedViewport==1){
					if((!$(this).data('resizeDone'))){ 
						newFontSize=parseFloat($(this).data('origSize')*(.01*i)).toFixed(2); //console.log('newFontSize: '+newFontSize);
						//reduce the font size half as much if requested
						if($(this).hasClass('fixedSizeTextHalf') && pageLimitedViewport!=1){newFontSize=(($(this).data('origSize')-newFontSize)/2)+newFontSize;}
						$(this).css('font-size',newFontSize+'px');
					}
					compareEle=parentEle?parentEle:$(this);
               //console.log(compareEle.width() +' <= '+ containerWidth  +', '+ compareEle.height()  +' <= '+ containerHeight);
               if(compareEle.width() <= containerWidth && compareEle.height() <= containerHeight){
                  $(this).data('resizeDone',1); $(this).css('transition',$(this).data('transition'));
               }else{
                  reduceMore=1;//console.log('reduce more');
               }
				}
			});
			if(!reduceMore){//console.log('breaking');
				break;
			}
		}
		$(this).css('display',$(this).data('displaySaved'));
	});
}

function loadQtip(){ // QTIP v2 - MGS / SMEI
   $('.tipSetup').each(function(){
      $(this).qtip({
         content: $(this).attr('alt'), // Use the ALT attribute as content source
         position: {
            my: 'bottom center',  // Position my top left...
            at: 'top center', // at the bottom right of...
            target: $(this)//'event' // my target
         },
         show:{
            delay:250//,
            //effect:{type:'fade',length:150}
         },
         hide:{
            delay:0//,
            //effect:{type:'fade',length:150}
         },
         style:{ 
            classes: 'qtip-smei qtip-shadow'
         }
      });
   });
   //tool tip setup, will be used if needed (if the tTipSetup array has values)
   if(typeof tTipSetup != "undefined"){
      for(i=0;i<tTipSetup.length;i++){
         $("#"+tTipSetup[i][0]).qtip({
            content:tTipSetup[i][1]
         });
      }
   }
} 

$(document).ready(function(){
   //setup lazy load
	if(typeof $.fn.lazy === "function" && (typeof lazyCustomLoad=='undefined'||lazyCustomLoad!=1)){lazyLoader();}
	
   //setup image map dynamic resizing if available
	if(typeof $.fn.rwdImageMaps === "function"){$('img[usemap]').rwdImageMaps();}
	
   //toggle fixed position elements on mobile devices when any inputs are in focus (when the keyboard is present) so they don't interfere with other elements on the page
	//this will add and remove the mobileFixedFix class to the document - make sure any fixed elements that need to be hidden when the keyboard is present include the mobileFixedFix class
	if(mobileOrTabletDevice==1){
		/* cache dom references */ 
		var $body = jQuery('body'); 
		/* bind events */
		$(document)
		.on('focus', 'input, textarea, select', function(e) { //alert($(e.target).hasClass("noMobileFixedFix"));
			if($(e.target).hasClass("noMobileFixedFix")==false && $(e.target).is(":radio")==false && $(e.target).is(":checkbox")==false){ //DONT apply the mobileFixedFix class if explicity told not to by the current input
				$body.addClass('mobileFixedFix');
			}
		})
		.on('blur', 'input, textarea, select', function(e) {
			$body.removeClass('mobileFixedFix');
		});
	}

	//setup overlay behavior
	if($("#onetimeAlertDiv").length>0){
		$("#onetimeAlertDiv").on('click',function(event){event.stopPropagation();$('#onetimeAlertDiv').css('display','none').html('&nbsp;');});
		$("#onetimeAlertPopClose").on('click',function(event){event.stopPropagation();$('#onetimeAlertDiv').css('display','none').html('&nbsp;');});
		$("#onetimeAlertMsg").on('click',function(event){event.stopPropagation();});
	}
	olDivs=['fl','ft','ac','st','pg'];
	for(i in olDivs){//alert(olDivs[i]);
		if($("#"+olDivs[i]+"PopDiv").length>0){$("#"+olDivs[i]+"PopDiv").on('click',function(event){event.stopPropagation();});}
		if($("#"+olDivs[i]+"PopHandleDiv").length>0){$("#"+olDivs[i]+"PopHandleDiv").on('click',function(event){event.stopPropagation();});}
		if($("#"+olDivs[i]+"CoverDiv").length>0){$("#"+olDivs[i]+"CoverDiv").on('click',function(event){event.stopPropagation();hidePopDiv($(this).attr('id').substr(0,2));});}
		//$("#"+olDivs[i]+"PopDiv").easydrag(true);$("##"+olDivs[i]+"PopDiv").setHandler("#"+olDivs[i]+"HandlePopDiv");
	}

	//add standard mouse over actions to designated items
	preloadTogImgs=new Array();
	$(".mouseTogImage").each(function(){ //if the rel attribute has value, use it as the fading target - or situation where rolling over one element triggers fading of another
		//setup over image preload
		imgItem=$(this).attr('rel')?$(this).attr('rel'):$(this).attr('id');
		if($("#"+imgItem).attr('src')){
			newImgPath=stringReplace($("#"+imgItem).attr('src'),'_norm','_over');
			preloadTogImgs[preloadTogImgs.length]=newImgPath;//alert(newImgPath);
		}
		//aply mouse actions
		$(this).on('mouseenter',function(){imageSwap('enter',($(this).attr('rel')?$(this).attr('rel'):$(this).attr('id')));});
		$(this).on('mouseleave',function(){imageSwap('leave',($(this).attr('rel')?$(this).attr('rel'):$(this).attr('id')));});
	});

	if(preloadTogImgs.length>0){preloadImages(preloadTogImgs);} //if over state images were found, preload them here
	
   //setup automatic pinterest sharing overlay for selected images
	$(".pin-img").each(function(){
		if($(this).css('position')!='absolute'&&$(this).css('position')!='fixed'){
			if(typeof(pinterestBtn)=='undefined'){pinterestBtn='small';}//pinterestBtn may be set by header or footer scripts
			//check for lazy loading images, and get the actual image source if needed
			imgSrc=$(this).attr('src').indexOf('spacer.gif')==-1?$(this).attr('src'):(typeof $(this).attr('data-original')!='undefined'?$(this).attr('data-original'):(typeof $(this).attr('data-src')!='undefined'?$(this).attr('data-src'):"")); 
			if(imgSrc!=""){ //continue only if there is a source value for the current image
				$(this).css('position','relative');
				if($(this).css('display')=='block'&&($(this).css('margin-left')=='auto'||$(this).css('margin-right')=='auto')){$(this).css('clear','both');}
				$(this).wrap('<span class="pin-span">');
				pinPage=location.protocol+'//'+location.host+location.pathname;
				pinImgURL=imgSrc.indexOf('http')==-1?location.protocol+'//'+location.host+imgSrc:imgSrc;
				pinURL="http://pinterest.com/pin/create/button/?url="+encodeURIComponent(pinPage)+"&media="+encodeURIComponent(pinImgURL)+"&description="+encodeURIComponent($(this).attr('alt'));
				pinTrack="";//"";
				//for some reason the display:none in the pin-btn class isn't reliable, so manually adding it here
				$(this).after('<a href="'+pinURL+'" onclick="'+pinTrack+'" class="pin-btn'+(pinterestBtn=='small'?'-sm':'')+'" target="_blank" style="display:none;"></a>'); 
				$(this).on('mouseenter',function(){ //adjust pin button location dynamically when the user rolls over the image
					pinTop=$(this).position().top+(($(this).css('margin-top')!='' && $(this).css('margin-top')!='auto')?parseInt($(this).css('margin-top'))-(pinterestBtn=='small'?53:60):0)+$(this).height(); //alert(pinTop);
					pinLeft=$(this).position().left+(($(this).css('margin-left')=='auto')?(($(this).outerWidth(true)-$(this).width())/2):parseInt($(this).css('margin-left')))+$(this).width()-(pinterestBtn=='small'?44:60); //alert(pinLeft);
					$(this).next().css({'top':pinTop,'left':pinLeft,'display':'block'});
				});
				$(this).parent().on('mouseleave',function(){$(this).children('a').css({'display':'none'});}); //hide the pin button when the user rolls out of the image enclosing SPAN (added above)
			}
		}
	});

	$(".presetLowOpacity").each(function(){ //if the rel attribute has value, use it as the fading target - or situation where rolling over one element triggers fading of another
		$($(this).attr('rel')?'#'+$(this).attr('rel'):this).css({opacity:.35});
	});
	$(".mouseTogOpacity").each(function(){ //if the rel attribute has value, use it as the fading target - or situation where rolling over one element triggers fading of another
		$(this).on('mouseenter',function(){$($(this).attr('rel')&&$(this).attr('rel')!='shadowbox'?'#'+$(this).attr('rel'):this).stop().animate({opacity:.75},200,'easeOutQuad');});
		$(this).on('mouseleave',function(){$($(this).attr('rel')&&$(this).attr('rel')!='shadowbox'?'#'+$(this).attr('rel'):this).stop().animate({opacity:1},200,'easeOutQuad');});
	});
	$(".mouseTogOpacity2").each(function(){ //if the rel attribute has value, use it as the fading target - or situation where rolling over one element triggers fading of another
		$(this).on('mouseenter',function(){$($(this).attr('rel')&&$(this).attr('rel')!='shadowbox'?'#'+$(this).attr('rel'):this).stop().animate({opacity:.5},200,'easeOutQuad');});
		$(this).on('mouseleave',function(){$($(this).attr('rel')&&$(this).attr('rel')!='shadowbox'?'#'+$(this).attr('rel'):this).stop().animate({opacity:1},200,'easeOutQuad');});
	});
	$(".mouseTogOpacityUp").each(function(){ //if the rel attribute has value, use it as the fading target - or situation where rolling over one element triggers fading of another
		$($(this).attr('rel')?'#'+$(this).attr('rel'):this).css({opacity:.75});
		$(this).on('mouseenter',function(){$($(this).attr('rel')&&$(this).attr('rel')!='shadowbox'?'#'+$(this).attr('rel'):this).stop().animate({opacity:1},200,'easeOutQuad');});
		$(this).on('mouseleave',function(){$($(this).attr('rel')&&$(this).attr('rel')!='shadowbox'?'#'+$(this).attr('rel'):this).stop().animate({opacity:.75},200,'easeOutQuad');});
	});
	$(".mouseTogOpacityUp2").each(function(){ //if the rel attribute has value, use it as the fading target - or situation where rolling over one element triggers fading of another
		$($(this).attr('rel')?'#'+$(this).attr('rel'):this).css({opacity:.5});
		$(this).on('mouseenter',function(){$($(this).attr('rel')&&$(this).attr('rel')!='shadowbox'?'#'+$(this).attr('rel'):this).stop().animate({opacity:1},200,'easeOutQuad');});
		$(this).on('mouseleave',function(){$($(this).attr('rel')&&$(this).attr('rel')!='shadowbox'?'#'+$(this).attr('rel'):this).stop().animate({opacity:.5},200,'easeOutQuad');});
	});
   
	//add hide parent mouse action where needed
	$(".hideParentDiv").each(function(){
		$(this).on("mouseup",function(){$(this).parent().fadeOut(200);/*$(this).parent().css('display','none')*/;});
	});

	//add media thumbnail play button animation - on mousedown for mobile devices - NOT rollovers
	$(".media-callout").on((mobileOrTabletDevice==1?"mousedown":"mouseenter"),function(){
		tSize=$(this).find('.media-callout-thumb'); tWidth=tSize.width(); tHeight=tSize.height(); bStartSize=52; bEndSize=65;
		$(this).find('.media-callout-play').stop()
		.css({width:bStartSize,top:parseInt((tHeight/2)-(bStartSize/2)),left:parseInt((tWidth/2)-(bStartSize/2)),opacity:.7})
		.animate({width:bEndSize,top:parseInt((tHeight/2)-(bEndSize/2)),left:parseInt((tWidth/2)-(bEndSize/2)),opacity:1},130,'');
		//$(this).find('.media-callout-share-btn').stop().css({display:'block'});
		$(this).find('.media-callout-share-btn').stop().delay((mobileOrTabletDevice==1?500:0)).fadeIn(130);
	});
	if(mobileOrTabletDevice!=1){
		$(".media-callout").on("mouseleave",function(){
			tSize=$(this).find('.media-callout-thumb'); tWidth=tSize.width(); tHeight=tSize.height(); bStartSize=52; bEndSize=65;
			$(this).find('.media-callout-play').stop().
			animate({width:bStartSize,top:parseInt((tHeight/2)-(bStartSize/2)),left:parseInt((tWidth/2)-(bStartSize/2)),opacity:.7},130,'');
			//$(this).find('.media-callout-share-btn').stop().css({display:'none'});
			$(this).find('.media-callout-share-btn').stop().fadeOut(130);
		});
	}

   staticPopTop=findStaticPopTop();

   //when resizing or changing orientation, update page layout elements that may have changed with the resize
   $(window).on("resize",function(){//alert('resize'+', '+pageLayoutOrient+', '+returnPageOrientation()); //console.log(window.innerHeight+"\n"+console.log());
      if(!pageLayoutNoResizeUpdate && (!mobileOrTabletDevice || pageLayoutOrient!=returnPageOrientation())){ //on mobile devices, only run resize code when changing orientation, since vertical size changes quite a bit with browser nav bar movement
         updatePageLayout(0);
      }
      //move the overlay popup div with the window resize if not a mobile device and a popup div is open
      //NOTE that internet explorer will fire this resize event when ANY element on the page is resized, NOT just the window - so only run popWinPosAdjust when the actual window is resized
      if(mobileOrTabletDevice!=1 && popDivID!=0){
         if(curWindowWidth!=$(window).width() || curWindowHeight!=$(window).height()){ //alert(curWindowWidth+','+$(window).width()+','+curWindowHeight+','+$(window).height()); 
            popWinPosAdjust();
         }
      }
   });

   //finally run the default fade-block fadeout if not otherwise configured
   if(pageFadeBlockCustom!=1){pageFade();/*console.log('page fade');*/} 
});



//*************************************************//
//*********** SITE SPECIFIC FUNCTIONS *************//
//*************************************************//

//title variables for subscribe, unsubscribe, and email referral overlays - leave blank to use defaults
//var eSubTitle='';
//var eUnsubTitle='';
//var eRefTitle='';

//override defaults in shared2.js
var bkgdVideoMobileShow=0;
var autoScrollFullBlock=0;

//misc setup variables
var noShadowboxInit=1; //not using shadowbox for this site (and no touchswipe)
var lazyCustomLoad=1; //stop standard lazy load function in shared2.js from firing - setup here within the contentInitSetup instead
var noAutoLazyLoad=0; //for media page we DO NOT want the initial overall page lazy load to run

//function to assign special attributes to input elements - this function is referenced by other functions, so keep even if empty
function inputsConfig(){
	/*ckFields=["input[type='text']","input[type='password']","textarea"];
	for(fct=0;fct<ckFields.length;fct++){
		$(ckFields[fct]).each(function(){
			$(this).on("focus",function(){$(this).addClass('usrval');});
		});
	}*/
}

//NOTE - standard input custom styling setup is handled in inputs.js
function contentInitSetup(parentEle){//console.log('contentInitSetup: '+parentEle);
	parentEle=typeof parentEle == 'undefined'?'':parentEle+' ';
	//set current page layout size and orientation variables if needed (on page init, this function is called before the updatePageLayout() function, so need to set these values here for use below)
	pageLayoutVarSetup(1);
	//capture all on-site page href links to first trigger fade-block fadeout before loading new page
	//pageFadeConfig(parentEle);
	//setup waypoint controlled element animation - exact animation setup in CSS
	//waypointAnimSetup(parentEle);
	//setup parallax background - HODAG
	//parallaxBkgdSetup(parentEle);
	//separate function just to update CSS buttons - so this can be called independently - setup for forms.php for BLC
	//cssBtnCustomStyle(parentEle);
	//call lazyLoader function
	if(!noAutoLazyLoad){lazyLoader(parentEle);}
}

//document ready processes
$(document).ready(function(){
	if(typeof adminPanel!='undefined' && adminPanel==1){return;}
	if(typeof isOverlay=='undefined'){isOverlay=0;}
	if(isOverlay==0){ //only run setup functions for non-overlay pages
		//initial content config - this may be called again on ajax loaded content
		contentInitSetup(); 
		//initial page layout setup
		updatePageLayout(1); 
		//initial page scroll setup 
		updatePageScroll(1); 
		//inital autoscroll setup if used
		autoScrollInit(); 
      //make header search input execute on return keypress
      if($("#pg_search").length>0){
         $("#pg_search")[0].addEventListener('keypress',function(event){
            if(event.keyCode === 13){pageSearch();}
         });
      }
	}//end overlay check
}); //end document ready processes

/** ADDITIONAL SITE SPECIFIC FUNCTIONS **/

function fullSearch(step){ //console.log('fullSearch, step: '+step);
   switch(step){
      case 'reset':
         $("#search_country").val('');
         $("#search-country, #country-flag").removeClass();
         $("#search-group, #search-type").removeClass().html('');
      break;
      case 'country':
         $("#search-country, #country-flag").removeClass();
         $("#search-group, #search-type").removeClass().html('');
         if($("#search_country").val()!=''){
            $("#search-country").addClass('selection_made');
            $("#country-flag").addClass('fflag ff-lg ff-round fflag-'+$("#search_country").val());
            $.get("/content/includes/site-functions.php?ajx=sch&sel=country",{cnk:$("#search_country").val()},function(data){;
               $("#search-group").html(data); inputCustomStyle("#search-group"); fullSearch('tblcheck');
            });
         }
      break;
      case 'group':
         $("#search-group").removeClass();
         $("#search-type").removeClass().html('');
         if($("#search_group").val()!=''){
            $("#search-group").addClass('selection_made');
            $.post("/content/includes/site-functions.php?ajx=sch&sel=group",{cnk:$("#search_country").val(),grp:$("#search_group").val()},function(data){
               $("#search-type").html(data); inputCustomStyle("#search-type"); fullSearch('tblcheck');
            });
         }
      break;
      case 'type':
         fullSearch('tblcheck');
      break;
      case 'tblcheck':
         curCountry=$("#search_country").length>0?$("#search_country").val():'';
         curGroup=$("#search_group").length>0?$("#search_group").val():'';
         curType=$("#search_type").length>0?$("#search_type").val():'';
         if(curCountry && curGroup && curType){ 
            lnk="/?tbl="+btoa(curCountry+'|'+curGroup+'|'+curType); 
            pageFade(lnk);
         }
      break;
   }
}

function fullSearchTog(){
   $("#header-search").toggleClass("header-search-open");
   $("#header-search-btn-tog").toggleClass("header-search-open");
   searchOpen=$("#header-search").hasClass("header-search-open")?1:0;
   if(searchOpen){
      fullSearch('reset');
   }
}

function pageSearch(){
   searchTxt=$("#pg_search").val();
   if(searchTxt==""){alert("Please enter a document name or model number to search");return;}
   //console.log(curDoc); console.log(curDoc.disp);
   loadDocsContent(curDoc.disp,'table',0,0,'','',searchTxt);
}

//resource docs content populate function
function loadDocsContent(dDisp,dRet,dScroll,langReset,sortCol,sortDir,searchTxt){//console.log('langReset: '+langReset);
   if(typeof dDisp=="undefined"){dDisp='cur';}
   if(typeof dRet=="undefined"){dRet='table';}
   if(typeof dScroll=="undefined"){dScroll=0;}
   if(typeof langReset=="undefined"){langReset=0;}
   if(typeof sortCol=="undefined"){sortCol='';}
   if(typeof sortDir=="undefined"){sortDir='';}
   if(typeof searchTxt=="undefined"){searchTxt='';}
   if(dRet=='all'){
      loadDocsContent(dDisp,'head',dScroll,langReset,sortCol,sortDir);
      loadDocsContent(dDisp,'table',dScroll,langReset,sortCol,sortDir);
      return;
   }	
   $("#docs-"+dRet+"-loading").stop().css({display:'none',opacity:1}).fadeIn(200,function(){
      $(".docs-table-fixed").remove();
      svHeight=$("#docs-"+dRet+"-container").height(); $("#docs-"+dRet+"-container").height(svHeight);
      crtbl=atob($("#curtbl").val()).split('|'); 
      urlStr="/content/includes/site-functions.php?ajx=tbl&ret="+dRet+"&dsp="+dDisp+"&scl="+sortCol+"&sdr="+sortDir+"&sch="+searchTxt+"&lng="+(langReset||$("#lang_select").length==0?"":$("#lang_select").val())+"&tbl="+$("#curtbl").val(); //console.log(urlStr);
      $.get(urlStr,{},function(content){
         $("#docs-"+dRet+"-loading").stop().fadeOut(200);
         $("#docs-"+dRet+"-ajax").html(content);
         if(typeof inputCustomStyle == 'function'){inputCustomStyle("#docs-"+dRet+"-ajax");}
         newHeight=$("#docs-"+dRet+"-ajax").outerHeight(); //console.log(dRet+' new height: '+newHeight);
         $("#docs-"+dRet+"-container").animate({height:newHeight},300,function(){
            $("#docs-"+dRet+"-container").css({height:'auto'});
            if(dScroll){jqueryScroll("page",500);}
         });
      });
   });
}

//table column sorting
function tblSort(dDisp,sortCol,sortDir){
   loadDocsContent(dDisp,'table',0,0,sortCol,sortDir);
}

//statis table header functions
function staticHeaderSetup(){//console.log('staticHeaderSetup');
   hd='<table class="docs-table-content docs-table-fixed"><thead>'+$("#docs-table thead").html()+'</thead></table>';
   $("#header").append(hd);
   staticHeaderResize();
   //staticHeaderScroll();
   $(window).on("resize",function(){staticHeaderResize();});
   $(window).scroll(function(){staticHeaderScroll();});
}
function staticHeaderResize(){//console.log('staticHeaderResize');
   tblWidth=$("#docs-table").width();
   lf=(($(window).width()-tblWidth)/2);
   $(".docs-table-fixed").css({width:tblWidth,left:lf});
   wd=[];
   $("#docs-table thead td").each(function(){wd.push($(this).css('width'));});
   $(".docs-table-fixed thead td").each(function(){
      curWidth=wd.shift();
      $(this).css({width:curWidth,minWidth:curWidth,maxWidth:curWidth});
   });
   staticHeaderScroll();
}
function staticHeaderScroll(){
   $(".docs-table-fixed").css({display:$(window).scrollTop()>$("#docs-table").offset().top-$("#header").height()?'table':'none'});
   if($(window).scrollLeft()>0||parseInt($(".docs-table-fixed").css('left'))<0){
      $(".docs-table-fixed").css({left:-$(window).scrollLeft()});
   }
}

