(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();});
/**
 * jQuery Plugin to obtain touch gestures from iPhone, iPod Touch and iPad, should also work with Android mobile phones (not tested yet!)
 * Common usage: wipe images (left and right to show the previous or next image)
 * 
 * @author Andreas Waltl, netCU Internetagentur (http://www.netcu.de)
 * @version 1.1.1 (9th December 2010) - fix bug (older IE's had problems)
 * @version 1.1 (1st September 2010) - support wipe up and wipe down
 * @version 1.0 (15th July 2010)
 */
(function($){$.fn.touchwipe=function(settings){var config={min_move_x:20,min_move_y:20,wipeLeft:function(){},wipeRight:function(){},wipeUp:function(){},wipeDown:function(){},preventDefaultEvents:true};if(settings)$.extend(config,settings);this.each(function(){var startX;var startY;var isMoving=false;function cancelTouch(){this.removeEventListener('touchmove',onTouchMove);startX=null;isMoving=false}function onTouchMove(e){if(config.preventDefaultEvents){e.preventDefault()}if(isMoving){var x=e.touches[0].pageX;var y=e.touches[0].pageY;var dx=startX-x;var dy=startY-y;if(Math.abs(dx)>=config.min_move_x){cancelTouch();if(dx>0){config.wipeLeft()}else{config.wipeRight()}}else if(Math.abs(dy)>=config.min_move_y){cancelTouch();if(dy>0){config.wipeDown()}else{config.wipeUp()}}}}function onTouchStart(e){if(e.touches.length==1){startX=e.touches[0].pageX;startY=e.touches[0].pageY;isMoving=true;this.addEventListener('touchmove',onTouchMove,false)}}if('ontouchstart'in document.documentElement){this.addEventListener('touchstart',onTouchStart,false)}});return this}})(jQuery);

//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;
}

//---------------------------------EMailCheck ------------------------------------ 

/*  checks the validity of an email address entered
*   returns true or false
*
*/

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
*  Checks each field in a form

*/
function V2validateData(strValidateStr,objValue,strError,fieldValue)
{
	//alert(strValidateStr);
	//alert(objValue.offsetHeight);
	if(objValue.offsetHeight==0){return true;} //DONT VALIDATE INVISIBLE INPUTS - 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";
              }//if
              alert(strError);
              return false;
           }//if
           break;
         }//case required
        case "maxlength":
        case "maxlen":
          {
             if(eval(objValue.value.length) >  eval(cmdvalue))
             {
               if(!strError || strError.length ==0)
               {
                 strError = objValue.name + " : "+cmdvalue+" charactersmaximum ";
               }//if
               alert(strError + "\n[Current length = " + objValue.value.length + " ]");
               return false;
             }//if
             break;
          }//case maxlen
        case "minlength":
        case "minlen":
           {
             if(eval(objValue.value.length) <  eval(cmdvalue))
             {
               if(!strError || strError.length ==0)
               {
                 strError = objValue.name + " : " + cmdvalue + " charactersminimum  ";
               }//if
               alert(strError + "\n[Current length = " + objValue.value.length + " ]");
               return false;
             }//if
             break;
            }//case minlen
        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 ";
                }//if
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
                return false;
              }//if
              break;
           }//case alphanumeric
        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 ";
                }//if
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
                return false;
              }//if
              break;
           }//numeric
        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 ";
                }//if
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
                return false;
              }//if
              break;
           }//float
        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 ";
                }//if
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
                return false;
              }//if
              break;
           }//alpha
  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 _";
                }//if
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]");
                return false;
              }//if
   break;
   }
        case "email":
          {
               if(!validateEmailv2(objValue.value))
               {
                 if(!strError || strError.length ==0)
                 {
                    strError = objValue.name+": Enter a valid Email address ";
                 }//if
                 alert(strError);
                 return false;
               }//if
           break;
          }//case email
        case "lt":
        case "lessthan":
         {
            if(isNaN(objValue.value))
            {
              alert(objValue.name+": Should be a number ");
              return false;
            }//if
            if(eval(objValue.value) >=  eval(cmdvalue))
            {
              if(!strError || strError.length ==0)
              {
                strError = objValue.name + " : value should be less than "+ cmdvalue;
              }//if
              alert(strError);
              return false;
             }//if
            break;
         }//case lessthan
        case "gt":
        case "greaterthan":
         {
            if(isNaN(objValue.value))
            {
              alert(objValue.name+": Should be a number ");
              return false;
            }//if
             if(eval(objValue.value) <=  eval(cmdvalue))
             {
               if(!strError || strError.length ==0)
               {
                 strError = objValue.name + " : value should be greater than "+ cmdvalue;
               }//if
               alert(strError);
               return false;
             }//if
            break;
         }//case greaterthan
        case "regexp":
         {
            if(!objValue.value.match(cmdvalue))
            {
              if(!strError || strError.length ==0)
              {
                strError = objValue.name+": Invalid characters found ";
              }//if
              alert(strError);
              return false;
            }//if
           break;
         }//case regexp
        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 ";
              }//if
              alert(strError);
              return false;
             }
             break;
         }//case dontselect
    //====
  case "checked":
      {
          if (!objValue.checked)
        {
    if(!strError || strError.length ==0)
          {
           strError = objValue.name + " : You must check this box";
        }
          alert(strError);
          return false;
         }
         break;
      }//case checked

  case "checkedAndField":
  //alert('in checkedAndField')
  //alert('objValue= ' + objValue)
  //alert('fieldValue= ' + fieldValue)
    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":
  //alert('in fieldAndCheck')
  //alert('objValue= ' + objValue)
  //alert('fieldValue= ' + fieldValue)
     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":
  		//alert('in radioGroup')
		//alert(document.forms[objValue.formName][objValue.name])
		//alert(document.forms[objValue.formName][objValue.name].length)
  		//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;
	  
 }//switch
    return true;
}
"use strict";var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target};var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}(function(root,factory){var pluginName="BackgroundVideo";if(typeof define==="function"&&define.amd){define([],factory(pluginName))}else if((typeof exports==="undefined"?"undefined":_typeof(exports))==="object"){module.exports=factory(pluginName)}else{root[pluginName]=factory(pluginName)}})(window||module||{},function(pluginName){var defaults={parallax:{effect:1.5},pauseVideoOnViewLoss:false,preventContextMenu:false,minimumVideoWidth:400,onBeforeReady:function onBeforeReady(){},onReady:function onReady(){}};var addClass=function addClass(el,className){if(el.classList){el.classList.add(className)}else{el.className+=" "+className}};var BackgroundVideo=function(){function BackgroundVideo(element,options){_classCallCheck(this,BackgroundVideo);this.element=document.querySelectorAll(element);this.options=_extends({},defaults,options);this.options.browserPrexix=this.detectBrowser();this.shimRequestAnimationFrame();this.options.has3d=this.detect3d();this.setWindowDimensions();for(var i=0;i<this.element.length;i++){this.init(this.element[i],i)}}_createClass(BackgroundVideo,[{key:"init",value:function init(element,iteration){this.el=element;this.playEvent=this.videoReadyCallback.bind(this);this.setVideoWrap(iteration);this.setVideoProperties();this.insertVideos();if(this.options&&this.options.onBeforeReady())this.options.onBeforeReady();if(this.el.readyState>3){this.videoReadyCallback()}else{this.el.addEventListener("canplaythrough",this.playEvent,false);this.el.addEventListener("canplay",this.playEvent,false)}if(this.options.preventContextMenu){this.el.addEventListener("contextmenu",function(){return false})}}},{key:"videoReadyCallback",value:function videoReadyCallback(){this.el.removeEventListener("canplaythrough",this.playEvent,false);this.el.removeEventListener("canplay",this.playEvent,false);this.options.originalVideoW=this.el.videoWidth;this.options.originalVideoH=this.el.videoHeight;this.bindEvents();this.requestTick();if(this.options&&this.options.onReady())this.options.onReady()}},{key:"bindEvents",value:function bindEvents(){this.ticking=false;if(this.options.parallax){window.addEventListener("scroll",this.requestTick.bind(this))}window.addEventListener("resize",this.requestTick.bind(this));window.addEventListener("resize",this.setWindowDimensions.bind(this))}},{key:"setWindowDimensions",value:function setWindowDimensions(){this.windowWidth=window.innerWidth;this.windowHeight=window.innerHeight}},{key:"requestTick",value:function requestTick(){if(!this.ticking){this.ticking=true;window.requestAnimationFrame(this.positionObject.bind(this))}}},{key:"positionObject",value:function positionObject(){var scrollPos=window.pageYOffset;var _scaleObject=this.scaleObject(),xPos=_scaleObject.xPos,yPos=_scaleObject.yPos;if(this.options.parallax){if(scrollPos>=0){yPos=this.calculateYPos(yPos,scrollPos)}else{yPos=this.calculateYPos(yPos,0)}}else{yPos=-yPos}var transformStyle=this.options.has3d?"translate3d("+xPos+"px, "+yPos+"px, 0)":"translate("+xPos+"px, "+yPos+"px)";this.el.style[""+this.options.browserPrexix]=transformStyle;this.el.style.transform=transformStyle;this.ticking=false}},{key:"scaleObject",value:function scaleObject(){var heightScale=this.windowWidth/this.options.originalVideoW;var widthScale=this.windowHeight/this.options.originalVideoH;var scaleFactor=void 0;this.options.bvVideoWrap.style.width=this.windowWidth+"px";this.options.bvVideoWrap.style.height=this.windowHeight+"px";scaleFactor=heightScale>widthScale?heightScale:widthScale;if(scaleFactor*this.options.originalVideoW<this.options.minimumVideoWidth){scaleFactor=this.options.minimumVideoWidth/this.options.originalVideoW}var videoWidth=scaleFactor*this.options.originalVideoW;var videoHeight=scaleFactor*this.options.originalVideoH;this.el.style.width=videoWidth+"px";this.el.style.height=videoHeight+"px";return{xPos:-parseInt((videoWidth-this.windowWidth)/2),yPos:parseInt(videoHeight-this.windowHeight)/2}}},{key:"calculateYPos",value:function calculateYPos(yPos,scrollPos){var videoPosition=parseInt(this.options.bvVideoWrap.offsetTop);var videoOffset=videoPosition-scrollPos;yPos=-(videoOffset/this.options.parallax.effect+yPos);return yPos}},{key:"setVideoWrap",value:function setVideoWrap(iteration){var wrapper=document.createElement("div");this.options.bvVideoWrapClass=this.el.className+"-wrap-"+iteration;addClass(wrapper,"bv-video-wrap");addClass(wrapper,this.options.bvVideoWrapClass);wrapper.style.position="relative";wrapper.style.overflow="hidden";wrapper.style.zIndex="10";this.el.parentNode.insertBefore(wrapper,this.el);wrapper.appendChild(this.el);this.options.bvVideoWrap=document.querySelector("."+this.options.bvVideoWrapClass)}},{key:"setVideoProperties",value:function setVideoProperties(){this.el.setAttribute("preload","metadata");this.el.setAttribute("loop","true");this.el.setAttribute("autoplay","true");this.el.style.position="absolute";this.el.style.zIndex="1"}},{key:"insertVideos",value:function insertVideos(){for(var i=0;i<this.options.src.length;i++){var videoTypeArr=this.options.src[i].split(".");var videoType=videoTypeArr[videoTypeArr.length-1];this.addSourceToVideo(this.options.src[i],"video/"+videoType)}}},{key:"addSourceToVideo",value:function addSourceToVideo(src,type){var source=document.createElement("source");source.src=src;source.type=type;this.el.appendChild(source)}},{key:"detectBrowser",value:function detectBrowser(){var val=navigator.userAgent.toLowerCase();var browserPrexix=void 0;if(val.indexOf("chrome")>-1||val.indexOf("safari")>-1){browserPrexix="webkitTransform"}else if(val.indexOf("firefox")>-1){browserPrexix="MozTransform"}else if(val.indexOf("MSIE")!==-1||val.indexOf("Trident/")>0){browserPrexix="msTransform"}else if(val.indexOf("Opera")>-1){browserPrexix="OTransform"}return browserPrexix}},{key:"shimRequestAnimationFrame",value:function shimRequestAnimationFrame(){var lastTime=0;var vendors=["ms","moz","webkit","o"];for(var x=0;x<vendors.length&&!window.requestAnimationFrame;++x){window.requestAnimationFrame=window[vendors[x]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[vendors[x]+"CancelAnimationFrame"]||window[vendors[x]+"CancelRequestAnimationFrame"]}if(!window.requestAnimationFrame)window.requestAnimationFrame=function(callback,element){var currTime=(new Date).getTime();var timeToCall=Math.max(0,16-(currTime-lastTime));var id=window.setTimeout(function(){callback(currTime+timeToCall)},timeToCall);lastTime=currTime+timeToCall;return id};if(!window.cancelAnimationFrame)window.cancelAnimationFrame=function(id){clearTimeout(id)}}},{key:"detect3d",value:function detect3d(){var el=document.createElement("p"),t,has3d,transforms={WebkitTransform:"-webkit-transform",OTransform:"-o-transform",MSTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(el,document.body.lastChild);for(t in transforms){if(el.style[t]!==undefined){el.style[t]="matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)";has3d=window.getComputedStyle(el).getPropertyValue(transforms[t])}}el.parentNode.removeChild(el);if(has3d!==undefined){return has3d!=="none"}else{return false}}}]);return BackgroundVideo}();return BackgroundVideo});
/*! skrollr 0.6.30 (2015-08-12) | Alexander Prinzhorn - https://github.com/Prinzhorn/skrollr | Free to use under terms of MIT license */
!function(a,b,c){"use strict";function d(c){if(e=b.documentElement,f=b.body,T(),ha=this,c=c||{},ma=c.constants||{},c.easing)for(var d in c.easing)W[d]=c.easing[d];ta=c.edgeStrategy||"set",ka={beforerender:c.beforerender,render:c.render,keyframe:c.keyframe},la=c.forceHeight!==!1,la&&(Ka=c.scale||1),na=c.mobileDeceleration||y,pa=c.smoothScrolling!==!1,qa=c.smoothScrollingDuration||A,ra={targetTop:ha.getScrollTop()},Sa=(c.mobileCheck||function(){return/Android|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent||navigator.vendor||a.opera)})(),Sa?(ja=b.getElementById(c.skrollrBody||z),ja&&ga(),X(),Ea(e,[s,v],[t])):Ea(e,[s,u],[t]),ha.refresh(),wa(a,"resize orientationchange",function(){var a=e.clientWidth,b=e.clientHeight;(b!==Pa||a!==Oa)&&(Pa=b,Oa=a,Qa=!0)});var g=U();return function h(){$(),va=g(h)}(),ha}var e,f,g={get:function(){return ha},init:function(a){return ha||new d(a)},VERSION:"0.6.30"},h=Object.prototype.hasOwnProperty,i=a.Math,j=a.getComputedStyle,k="touchstart",l="touchmove",m="touchcancel",n="touchend",o="skrollable",p=o+"-before",q=o+"-between",r=o+"-after",s="skrollr",t="no-"+s,u=s+"-desktop",v=s+"-mobile",w="linear",x=1e3,y=.004,z="skrollr-body",A=200,B="start",C="end",D="center",E="bottom",F="___skrollable_id",G=/^(?:input|textarea|button|select)$/i,H=/^\s+|\s+$/g,I=/^data(?:-(_\w+))?(?:-?(-?\d*\.?\d+p?))?(?:-?(start|end|top|center|bottom))?(?:-?(top|center|bottom))?$/,J=/\s*(@?[\w\-\[\]]+)\s*:\s*(.+?)\s*(?:;|$)/gi,K=/^(@?[a-z\-]+)\[(\w+)\]$/,L=/-([a-z0-9_])/g,M=function(a,b){return b.toUpperCase()},N=/[\-+]?[\d]*\.?[\d]+/g,O=/\{\?\}/g,P=/rgba?\(\s*-?\d+\s*,\s*-?\d+\s*,\s*-?\d+/g,Q=/[a-z\-]+-gradient/g,R="",S="",T=function(){var a=/^(?:O|Moz|webkit|ms)|(?:-(?:o|moz|webkit|ms)-)/;if(j){var b=j(f,null);for(var c in b)if(R=c.match(a)||+c==c&&b[c].match(a))break;if(!R)return void(R=S="");R=R[0],"-"===R.slice(0,1)?(S=R,R={"-webkit-":"webkit","-moz-":"Moz","-ms-":"ms","-o-":"O"}[R]):S="-"+R.toLowerCase()+"-"}},U=function(){var b=a.requestAnimationFrame||a[R.toLowerCase()+"RequestAnimationFrame"],c=Ha();return(Sa||!b)&&(b=function(b){var d=Ha()-c,e=i.max(0,1e3/60-d);return a.setTimeout(function(){c=Ha(),b()},e)}),b},V=function(){var b=a.cancelAnimationFrame||a[R.toLowerCase()+"CancelAnimationFrame"];return(Sa||!b)&&(b=function(b){return a.clearTimeout(b)}),b},W={begin:function(){return 0},end:function(){return 1},linear:function(a){return a},quadratic:function(a){return a*a},cubic:function(a){return a*a*a},swing:function(a){return-i.cos(a*i.PI)/2+.5},sqrt:function(a){return i.sqrt(a)},outCubic:function(a){return i.pow(a-1,3)+1},bounce:function(a){var b;if(.5083>=a)b=3;else if(.8489>=a)b=9;else if(.96208>=a)b=27;else{if(!(.99981>=a))return 1;b=91}return 1-i.abs(3*i.cos(a*b*1.028)/b)}};d.prototype.refresh=function(a){var d,e,f=!1;for(a===c?(f=!0,ia=[],Ra=0,a=b.getElementsByTagName("*")):a.length===c&&(a=[a]),d=0,e=a.length;e>d;d++){var g=a[d],h=g,i=[],j=pa,k=ta,l=!1;if(f&&F in g&&delete g[F],g.attributes){for(var m=0,n=g.attributes.length;n>m;m++){var p=g.attributes[m];if("data-anchor-target"!==p.name)if("data-smooth-scrolling"!==p.name)if("data-edge-strategy"!==p.name)if("data-emit-events"!==p.name){var q=p.name.match(I);if(null!==q){var r={props:p.value,element:g,eventType:p.name.replace(L,M)};i.push(r);var s=q[1];s&&(r.constant=s.substr(1));var t=q[2];/p$/.test(t)?(r.isPercentage=!0,r.offset=(0|t.slice(0,-1))/100):r.offset=0|t;var u=q[3],v=q[4]||u;u&&u!==B&&u!==C?(r.mode="relative",r.anchors=[u,v]):(r.mode="absolute",u===C?r.isEnd=!0:r.isPercentage||(r.offset=r.offset*Ka))}}else l=!0;else k=p.value;else j="off"!==p.value;else if(h=b.querySelector(p.value),null===h)throw'Unable to find anchor target "'+p.value+'"'}if(i.length){var w,x,y;!f&&F in g?(y=g[F],w=ia[y].styleAttr,x=ia[y].classAttr):(y=g[F]=Ra++,w=g.style.cssText,x=Da(g)),ia[y]={element:g,styleAttr:w,classAttr:x,anchorTarget:h,keyFrames:i,smoothScrolling:j,edgeStrategy:k,emitEvents:l,lastFrameIndex:-1},Ea(g,[o],[])}}}for(Aa(),d=0,e=a.length;e>d;d++){var z=ia[a[d][F]];z!==c&&(_(z),ba(z))}return ha},d.prototype.relativeToAbsolute=function(a,b,c){var d=e.clientHeight,f=a.getBoundingClientRect(),g=f.top,h=f.bottom-f.top;return b===E?g-=d:b===D&&(g-=d/2),c===E?g+=h:c===D&&(g+=h/2),g+=ha.getScrollTop(),g+.5|0},d.prototype.animateTo=function(a,b){b=b||{};var d=Ha(),e=ha.getScrollTop(),f=b.duration===c?x:b.duration;return oa={startTop:e,topDiff:a-e,targetTop:a,duration:f,startTime:d,endTime:d+f,easing:W[b.easing||w],done:b.done},oa.topDiff||(oa.done&&oa.done.call(ha,!1),oa=c),ha},d.prototype.stopAnimateTo=function(){oa&&oa.done&&oa.done.call(ha,!0),oa=c},d.prototype.isAnimatingTo=function(){return!!oa},d.prototype.isMobile=function(){return Sa},d.prototype.setScrollTop=function(b,c){return sa=c===!0,Sa?Ta=i.min(i.max(b,0),Ja):a.scrollTo(0,b),ha},d.prototype.getScrollTop=function(){return Sa?Ta:a.pageYOffset||e.scrollTop||f.scrollTop||0},d.prototype.getMaxScrollTop=function(){return Ja},d.prototype.on=function(a,b){return ka[a]=b,ha},d.prototype.off=function(a){return delete ka[a],ha},d.prototype.destroy=function(){var a=V();a(va),ya(),Ea(e,[t],[s,u,v]);for(var b=0,d=ia.length;d>b;b++)fa(ia[b].element);e.style.overflow=f.style.overflow="",e.style.height=f.style.height="",ja&&g.setStyle(ja,"transform","none"),ha=c,ja=c,ka=c,la=c,Ja=0,Ka=1,ma=c,na=c,La="down",Ma=-1,Oa=0,Pa=0,Qa=!1,oa=c,pa=c,qa=c,ra=c,sa=c,Ra=0,ta=c,Sa=!1,Ta=0,ua=c};var X=function(){var d,g,h,j,o,p,q,r,s,t,u,v;wa(e,[k,l,m,n].join(" "),function(a){var e=a.changedTouches[0];for(j=a.target;3===j.nodeType;)j=j.parentNode;switch(o=e.clientY,p=e.clientX,t=a.timeStamp,G.test(j.tagName)||a.preventDefault(),a.type){case k:d&&d.blur(),ha.stopAnimateTo(),d=j,g=q=o,h=p,s=t;break;case l:G.test(j.tagName)&&b.activeElement!==j&&a.preventDefault(),r=o-q,v=t-u,ha.setScrollTop(Ta-r,!0),q=o,u=t;break;default:case m:case n:var f=g-o,w=h-p,x=w*w+f*f;if(49>x){if(!G.test(d.tagName)){d.focus();var y=b.createEvent("MouseEvents");y.initMouseEvent("click",!0,!0,a.view,1,e.screenX,e.screenY,e.clientX,e.clientY,a.ctrlKey,a.altKey,a.shiftKey,a.metaKey,0,null),d.dispatchEvent(y)}return}d=c;var z=r/v;z=i.max(i.min(z,3),-3);var A=i.abs(z/na),B=z*A+.5*na*A*A,C=ha.getScrollTop()-B,D=0;C>Ja?(D=(Ja-C)/B,C=Ja):0>C&&(D=-C/B,C=0),A*=1-D,ha.animateTo(C+.5|0,{easing:"outCubic",duration:A})}}),a.scrollTo(0,0),e.style.overflow=f.style.overflow="hidden"},Y=function(){var a,b,c,d,f,g,h,j,k,l,m,n=e.clientHeight,o=Ba();for(j=0,k=ia.length;k>j;j++)for(a=ia[j],b=a.element,c=a.anchorTarget,d=a.keyFrames,f=0,g=d.length;g>f;f++)h=d[f],l=h.offset,m=o[h.constant]||0,h.frame=l,h.isPercentage&&(l*=n,h.frame=l),"relative"===h.mode&&(fa(b),h.frame=ha.relativeToAbsolute(c,h.anchors[0],h.anchors[1])-l,fa(b,!0)),h.frame+=m,la&&!h.isEnd&&h.frame>Ja&&(Ja=h.frame);for(Ja=i.max(Ja,Ca()),j=0,k=ia.length;k>j;j++){for(a=ia[j],d=a.keyFrames,f=0,g=d.length;g>f;f++)h=d[f],m=o[h.constant]||0,h.isEnd&&(h.frame=Ja-h.offset+m);a.keyFrames.sort(Ia)}},Z=function(a,b){for(var c=0,d=ia.length;d>c;c++){var e,f,i=ia[c],j=i.element,k=i.smoothScrolling?a:b,l=i.keyFrames,m=l.length,n=l[0],s=l[l.length-1],t=k<n.frame,u=k>s.frame,v=t?n:s,w=i.emitEvents,x=i.lastFrameIndex;if(t||u){if(t&&-1===i.edge||u&&1===i.edge)continue;switch(t?(Ea(j,[p],[r,q]),w&&x>-1&&(za(j,n.eventType,La),i.lastFrameIndex=-1)):(Ea(j,[r],[p,q]),w&&m>x&&(za(j,s.eventType,La),i.lastFrameIndex=m)),i.edge=t?-1:1,i.edgeStrategy){case"reset":fa(j);continue;case"ease":k=v.frame;break;default:case"set":var y=v.props;for(e in y)h.call(y,e)&&(f=ea(y[e].value),0===e.indexOf("@")?j.setAttribute(e.substr(1),f):g.setStyle(j,e,f));continue}}else 0!==i.edge&&(Ea(j,[o,q],[p,r]),i.edge=0);for(var z=0;m-1>z;z++)if(k>=l[z].frame&&k<=l[z+1].frame){var A=l[z],B=l[z+1];for(e in A.props)if(h.call(A.props,e)){var C=(k-A.frame)/(B.frame-A.frame);C=A.props[e].easing(C),f=da(A.props[e].value,B.props[e].value,C),f=ea(f),0===e.indexOf("@")?j.setAttribute(e.substr(1),f):g.setStyle(j,e,f)}w&&x!==z&&("down"===La?za(j,A.eventType,La):za(j,B.eventType,La),i.lastFrameIndex=z);break}}},$=function(){Qa&&(Qa=!1,Aa());var a,b,d=ha.getScrollTop(),e=Ha();if(oa)e>=oa.endTime?(d=oa.targetTop,a=oa.done,oa=c):(b=oa.easing((e-oa.startTime)/oa.duration),d=oa.startTop+b*oa.topDiff|0),ha.setScrollTop(d,!0);else if(!sa){var f=ra.targetTop-d;f&&(ra={startTop:Ma,topDiff:d-Ma,targetTop:d,startTime:Na,endTime:Na+qa}),e<=ra.endTime&&(b=W.sqrt((e-ra.startTime)/qa),d=ra.startTop+b*ra.topDiff|0)}if(sa||Ma!==d){La=d>Ma?"down":Ma>d?"up":La,sa=!1;var h={curTop:d,lastTop:Ma,maxTop:Ja,direction:La},i=ka.beforerender&&ka.beforerender.call(ha,h);i!==!1&&(Z(d,ha.getScrollTop()),Sa&&ja&&g.setStyle(ja,"transform","translate(0, "+-Ta+"px) "+ua),Ma=d,ka.render&&ka.render.call(ha,h)),a&&a.call(ha,!1)}Na=e},_=function(a){for(var b=0,c=a.keyFrames.length;c>b;b++){for(var d,e,f,g,h=a.keyFrames[b],i={};null!==(g=J.exec(h.props));)f=g[1],e=g[2],d=f.match(K),null!==d?(f=d[1],d=d[2]):d=w,e=e.indexOf("!")?aa(e):[e.slice(1)],i[f]={value:e,easing:W[d]};h.props=i}},aa=function(a){var b=[];return P.lastIndex=0,a=a.replace(P,function(a){return a.replace(N,function(a){return a/255*100+"%"})}),S&&(Q.lastIndex=0,a=a.replace(Q,function(a){return S+a})),a=a.replace(N,function(a){return b.push(+a),"{?}"}),b.unshift(a),b},ba=function(a){var b,c,d={};for(b=0,c=a.keyFrames.length;c>b;b++)ca(a.keyFrames[b],d);for(d={},b=a.keyFrames.length-1;b>=0;b--)ca(a.keyFrames[b],d)},ca=function(a,b){var c;for(c in b)h.call(a.props,c)||(a.props[c]=b[c]);for(c in a.props)b[c]=a.props[c]},da=function(a,b,c){var d,e=a.length;if(e!==b.length)throw"Can't interpolate between \""+a[0]+'" and "'+b[0]+'"';var f=[a[0]];for(d=1;e>d;d++)f[d]=a[d]+(b[d]-a[d])*c;return f},ea=function(a){var b=1;return O.lastIndex=0,a[0].replace(O,function(){return a[b++]})},fa=function(a,b){a=[].concat(a);for(var c,d,e=0,f=a.length;f>e;e++)d=a[e],c=ia[d[F]],c&&(b?(d.style.cssText=c.dirtyStyleAttr,Ea(d,c.dirtyClassAttr)):(c.dirtyStyleAttr=d.style.cssText,c.dirtyClassAttr=Da(d),d.style.cssText=c.styleAttr,Ea(d,c.classAttr)))},ga=function(){ua="translateZ(0)",g.setStyle(ja,"transform",ua);var a=j(ja),b=a.getPropertyValue("transform"),c=a.getPropertyValue(S+"transform"),d=b&&"none"!==b||c&&"none"!==c;d||(ua="")};g.setStyle=function(a,b,c){var d=a.style;if(b=b.replace(L,M).replace("-",""),"zIndex"===b)isNaN(c)?d[b]=c:d[b]=""+(0|c);else if("float"===b)d.styleFloat=d.cssFloat=c;else try{R&&(d[R+b.slice(0,1).toUpperCase()+b.slice(1)]=c),d[b]=c}catch(e){}};var ha,ia,ja,ka,la,ma,na,oa,pa,qa,ra,sa,ta,ua,va,wa=g.addEvent=function(b,c,d){var e=function(b){return b=b||a.event,b.target||(b.target=b.srcElement),b.preventDefault||(b.preventDefault=function(){b.returnValue=!1,b.defaultPrevented=!0}),d.call(this,b)};c=c.split(" ");for(var f,g=0,h=c.length;h>g;g++)f=c[g],b.addEventListener?b.addEventListener(f,d,!1):b.attachEvent("on"+f,e),Ua.push({element:b,name:f,listener:d})},xa=g.removeEvent=function(a,b,c){b=b.split(" ");for(var d=0,e=b.length;e>d;d++)a.removeEventListener?a.removeEventListener(b[d],c,!1):a.detachEvent("on"+b[d],c)},ya=function(){for(var a,b=0,c=Ua.length;c>b;b++)a=Ua[b],xa(a.element,a.name,a.listener);Ua=[]},za=function(a,b,c){ka.keyframe&&ka.keyframe.call(ha,a,b,c)},Aa=function(){var a=ha.getScrollTop();Ja=0,la&&!Sa&&(f.style.height=""),Y(),la&&!Sa&&(f.style.height=Ja+e.clientHeight+"px"),Sa?ha.setScrollTop(i.min(ha.getScrollTop(),Ja)):ha.setScrollTop(a,!0),sa=!0},Ba=function(){var a,b,c=e.clientHeight,d={};for(a in ma)b=ma[a],"function"==typeof b?b=b.call(ha):/p$/.test(b)&&(b=b.slice(0,-1)/100*c),d[a]=b;return d},Ca=function(){var a,b=0;return ja&&(b=i.max(ja.offsetHeight,ja.scrollHeight)),a=i.max(b,f.scrollHeight,f.offsetHeight,e.scrollHeight,e.offsetHeight,e.clientHeight),a-e.clientHeight},Da=function(b){var c="className";return a.SVGElement&&b instanceof a.SVGElement&&(b=b[c],c="baseVal"),b[c]},Ea=function(b,d,e){var f="className";if(a.SVGElement&&b instanceof a.SVGElement&&(b=b[f],f="baseVal"),e===c)return void(b[f]=d);for(var g=b[f],h=0,i=e.length;i>h;h++)g=Ga(g).replace(Ga(e[h])," ");g=Fa(g);for(var j=0,k=d.length;k>j;j++)-1===Ga(g).indexOf(Ga(d[j]))&&(g+=" "+d[j]);b[f]=Fa(g)},Fa=function(a){return a.replace(H,"")},Ga=function(a){return" "+a+" "},Ha=Date.now||function(){return+new Date},Ia=function(a,b){return a.frame-b.frame},Ja=0,Ka=1,La="down",Ma=-1,Na=Ha(),Oa=0,Pa=0,Qa=!1,Ra=0,Sa=!1,Ta=0,Ua=[];"function"==typeof define&&define.amd?define([],function(){return g}):"undefined"!=typeof module&&module.exports?module.exports=g:a.skrollr=g}(window,document);
/* qtip2 v3.0.3 | Plugins: None | Styles: core | qtip2.com | Licensed MIT | Wed May 11 2016 22:31:32 */

!function(a,b,c){!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):jQuery&&!jQuery.fn.qtip&&a(jQuery)}(function(d){"use strict";function e(a,b,c,e){this.id=c,this.target=a,this.tooltip=z,this.elements={target:a},this._id=I+"-"+c,this.timers={img:{}},this.options=b,this.plugins={},this.cache={event:{},target:d(),disabled:y,attr:e,onTooltip:y,lastClass:""},this.rendered=this.destroyed=this.disabled=this.waiting=this.hiddenDuringWait=this.positioning=this.triggering=y}function f(a){return a===z||"object"!==d.type(a)}function g(a){return!(d.isFunction(a)||a&&a.attr||a.length||"object"===d.type(a)&&(a.jquery||a.then))}function h(a){var b,c,e,h;return f(a)?y:(f(a.metadata)&&(a.metadata={type:a.metadata}),"content"in a&&(b=a.content,f(b)||b.jquery||b.done?(c=g(b)?y:b,b=a.content={text:c}):c=b.text,"ajax"in b&&(e=b.ajax,h=e&&e.once!==y,delete b.ajax,b.text=function(a,b){var f=c||d(this).attr(b.options.content.attr)||"Loading...",g=d.ajax(d.extend({},e,{context:b})).then(e.success,z,e.error).then(function(a){return a&&h&&b.set("content.text",a),a},function(a,c,d){b.destroyed||0===a.status||b.set("content.text",c+": "+d)});return h?f:(b.set("content.text",f),g)}),"title"in b&&(d.isPlainObject(b.title)&&(b.button=b.title.button,b.title=b.title.text),g(b.title||y)&&(b.title=y))),"position"in a&&f(a.position)&&(a.position={my:a.position,at:a.position}),"show"in a&&f(a.show)&&(a.show=a.show.jquery?{target:a.show}:a.show===x?{ready:x}:{event:a.show}),"hide"in a&&f(a.hide)&&(a.hide=a.hide.jquery?{target:a.hide}:{event:a.hide}),"style"in a&&f(a.style)&&(a.style={classes:a.style}),d.each(H,function(){this.sanitize&&this.sanitize(a)}),a)}function i(a,b){for(var c,d=0,e=a,f=b.split(".");e=e[f[d++]];)d<f.length&&(c=e);return[c||a,f.pop()]}function j(a,b){var c,d,e;for(c in this.checks)if(this.checks.hasOwnProperty(c))for(d in this.checks[c])this.checks[c].hasOwnProperty(d)&&(e=new RegExp(d,"i").exec(a))&&(b.push(e),("builtin"===c||this.plugins[c])&&this.checks[c][d].apply(this.plugins[c]||this,b))}function k(a){return L.concat("").join(a?"-"+a+" ":" ")}function l(a,b){return b>0?setTimeout(d.proxy(a,this),b):void a.call(this)}function m(a){this.tooltip.hasClass(S)||(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this.timers.show=l.call(this,function(){this.toggle(x,a)},this.options.show.delay))}function n(a){if(!this.tooltip.hasClass(S)&&!this.destroyed){var b=d(a.relatedTarget),c=b.closest(M)[0]===this.tooltip[0],e=b[0]===this.options.show.target[0];if(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this!==b[0]&&"mouse"===this.options.position.target&&c||this.options.hide.fixed&&/mouse(out|leave|move)/.test(a.type)&&(c||e))try{a.preventDefault(),a.stopImmediatePropagation()}catch(f){}else this.timers.hide=l.call(this,function(){this.toggle(y,a)},this.options.hide.delay,this)}}function o(a){!this.tooltip.hasClass(S)&&this.options.hide.inactive&&(clearTimeout(this.timers.inactive),this.timers.inactive=l.call(this,function(){this.hide(a)},this.options.hide.inactive))}function p(a){this.rendered&&this.tooltip[0].offsetWidth>0&&this.reposition(a)}function q(a,c,e){d(b.body).delegate(a,(c.split?c:c.join("."+I+" "))+"."+I,function(){var a=s.api[d.attr(this,K)];a&&!a.disabled&&e.apply(a,arguments)})}function r(a,c,f){var g,i,j,k,l,m=d(b.body),n=a[0]===b?m:a,o=a.metadata?a.metadata(f.metadata):z,p="html5"===f.metadata.type&&o?o[f.metadata.name]:z,q=a.data(f.metadata.name||"qtipopts");try{q="string"==typeof q?d.parseJSON(q):q}catch(r){}if(k=d.extend(x,{},s.defaults,f,"object"==typeof q?h(q):z,h(p||o)),i=k.position,k.id=c,"boolean"==typeof k.content.text){if(j=a.attr(k.content.attr),k.content.attr===y||!j)return y;k.content.text=j}if(i.container.length||(i.container=m),i.target===y&&(i.target=n),k.show.target===y&&(k.show.target=n),k.show.solo===x&&(k.show.solo=i.container.closest("body")),k.hide.target===y&&(k.hide.target=n),k.position.viewport===x&&(k.position.viewport=i.container),i.container=i.container.eq(0),i.at=new u(i.at,x),i.my=new u(i.my),a.data(I))if(k.overwrite)a.qtip("destroy",!0);else if(k.overwrite===y)return y;return a.attr(J,c),k.suppress&&(l=a.attr("title"))&&a.removeAttr("title").attr(U,l).attr("title",""),g=new e(a,k,c,!!j),a.data(I,g),g}var s,t,u,v,w,x=!0,y=!1,z=null,A="x",B="y",C="top",D="left",E="bottom",F="right",G="center",H={},I="qtip",J="data-hasqtip",K="data-qtip-id",L=["ui-widget","ui-tooltip"],M="."+I,N="click dblclick mousedown mouseup mousemove mouseleave mouseenter".split(" "),O=I+"-fixed",P=I+"-default",Q=I+"-focus",R=I+"-hover",S=I+"-disabled",T="_replacedByqTip",U="oldtitle",V={ie:function(){var a,c;for(a=4,c=b.createElement("div");(c.innerHTML="<!--[if gt IE "+a+"]><i></i><![endif]-->")&&c.getElementsByTagName("i")[0];a+=1);return a>4?a:NaN}(),iOS:parseFloat((""+(/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))||y};t=e.prototype,t._when=function(a){return d.when.apply(d,a)},t.render=function(a){if(this.rendered||this.destroyed)return this;var b=this,c=this.options,e=this.cache,f=this.elements,g=c.content.text,h=c.content.title,i=c.content.button,j=c.position,k=[];return d.attr(this.target[0],"aria-describedby",this._id),e.posClass=this._createPosClass((this.position={my:j.my,at:j.at}).my),this.tooltip=f.tooltip=d("<div/>",{id:this._id,"class":[I,P,c.style.classes,e.posClass].join(" "),width:c.style.width||"",height:c.style.height||"",tracking:"mouse"===j.target&&j.adjust.mouse,role:"alert","aria-live":"polite","aria-atomic":y,"aria-describedby":this._id+"-content","aria-hidden":x}).toggleClass(S,this.disabled).attr(K,this.id).data(I,this).appendTo(j.container).append(f.content=d("<div />",{"class":I+"-content",id:this._id+"-content","aria-atomic":x})),this.rendered=-1,this.positioning=x,h&&(this._createTitle(),d.isFunction(h)||k.push(this._updateTitle(h,y))),i&&this._createButton(),d.isFunction(g)||k.push(this._updateContent(g,y)),this.rendered=x,this._setWidget(),d.each(H,function(a){var c;"render"===this.initialize&&(c=this(b))&&(b.plugins[a]=c)}),this._unassignEvents(),this._assignEvents(),this._when(k).then(function(){b._trigger("render"),b.positioning=y,b.hiddenDuringWait||!c.show.ready&&!a||b.toggle(x,e.event,y),b.hiddenDuringWait=y}),s.api[this.id]=this,this},t.destroy=function(a){function b(){if(!this.destroyed){this.destroyed=x;var a,b=this.target,c=b.attr(U);this.rendered&&this.tooltip.stop(1,0).find("*").remove().end().remove(),d.each(this.plugins,function(){this.destroy&&this.destroy()});for(a in this.timers)this.timers.hasOwnProperty(a)&&clearTimeout(this.timers[a]);b.removeData(I).removeAttr(K).removeAttr(J).removeAttr("aria-describedby"),this.options.suppress&&c&&b.attr("title",c).removeAttr(U),this._unassignEvents(),this.options=this.elements=this.cache=this.timers=this.plugins=this.mouse=z,delete s.api[this.id]}}return this.destroyed?this.target:(a===x&&"hide"!==this.triggering||!this.rendered?b.call(this):(this.tooltip.one("tooltiphidden",d.proxy(b,this)),!this.triggering&&this.hide()),this.target)},v=t.checks={builtin:{"^id$":function(a,b,c,e){var f=c===x?s.nextid:c,g=I+"-"+f;f!==y&&f.length>0&&!d("#"+g).length?(this._id=g,this.rendered&&(this.tooltip[0].id=this._id,this.elements.content[0].id=this._id+"-content",this.elements.title[0].id=this._id+"-title")):a[b]=e},"^prerender":function(a,b,c){c&&!this.rendered&&this.render(this.options.show.ready)},"^content.text$":function(a,b,c){this._updateContent(c)},"^content.attr$":function(a,b,c,d){this.options.content.text===this.target.attr(d)&&this._updateContent(this.target.attr(c))},"^content.title$":function(a,b,c){return c?(c&&!this.elements.title&&this._createTitle(),void this._updateTitle(c)):this._removeTitle()},"^content.button$":function(a,b,c){this._updateButton(c)},"^content.title.(text|button)$":function(a,b,c){this.set("content."+b,c)},"^position.(my|at)$":function(a,b,c){"string"==typeof c&&(this.position[b]=a[b]=new u(c,"at"===b))},"^position.container$":function(a,b,c){this.rendered&&this.tooltip.appendTo(c)},"^show.ready$":function(a,b,c){c&&(!this.rendered&&this.render(x)||this.toggle(x))},"^style.classes$":function(a,b,c,d){this.rendered&&this.tooltip.removeClass(d).addClass(c)},"^style.(width|height)":function(a,b,c){this.rendered&&this.tooltip.css(b,c)},"^style.widget|content.title":function(){this.rendered&&this._setWidget()},"^style.def":function(a,b,c){this.rendered&&this.tooltip.toggleClass(P,!!c)},"^events.(render|show|move|hide|focus|blur)$":function(a,b,c){this.rendered&&this.tooltip[(d.isFunction(c)?"":"un")+"bind"]("tooltip"+b,c)},"^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)":function(){if(this.rendered){var a=this.options.position;this.tooltip.attr("tracking","mouse"===a.target&&a.adjust.mouse),this._unassignEvents(),this._assignEvents()}}}},t.get=function(a){if(this.destroyed)return this;var b=i(this.options,a.toLowerCase()),c=b[0][b[1]];return c.precedance?c.string():c};var W=/^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,X=/^prerender|show\.ready/i;t.set=function(a,b){if(this.destroyed)return this;var c,e=this.rendered,f=y,g=this.options;return"string"==typeof a?(c=a,a={},a[c]=b):a=d.extend({},a),d.each(a,function(b,c){if(e&&X.test(b))return void delete a[b];var h,j=i(g,b.toLowerCase());h=j[0][j[1]],j[0][j[1]]=c&&c.nodeType?d(c):c,f=W.test(b)||f,a[b]=[j[0],j[1],c,h]}),h(g),this.positioning=x,d.each(a,d.proxy(j,this)),this.positioning=y,this.rendered&&this.tooltip[0].offsetWidth>0&&f&&this.reposition("mouse"===g.position.target?z:this.cache.event),this},t._update=function(a,b){var c=this,e=this.cache;return this.rendered&&a?(d.isFunction(a)&&(a=a.call(this.elements.target,e.event,this)||""),d.isFunction(a.then)?(e.waiting=x,a.then(function(a){return e.waiting=y,c._update(a,b)},z,function(a){return c._update(a,b)})):a===y||!a&&""!==a?y:(a.jquery&&a.length>0?b.empty().append(a.css({display:"block",visibility:"visible"})):b.html(a),this._waitForContent(b).then(function(a){c.rendered&&c.tooltip[0].offsetWidth>0&&c.reposition(e.event,!a.length)}))):y},t._waitForContent=function(a){var b=this.cache;return b.waiting=x,(d.fn.imagesLoaded?a.imagesLoaded():(new d.Deferred).resolve([])).done(function(){b.waiting=y}).promise()},t._updateContent=function(a,b){this._update(a,this.elements.content,b)},t._updateTitle=function(a,b){this._update(a,this.elements.title,b)===y&&this._removeTitle(y)},t._createTitle=function(){var a=this.elements,b=this._id+"-title";a.titlebar&&this._removeTitle(),a.titlebar=d("<div />",{"class":I+"-titlebar "+(this.options.style.widget?k("header"):"")}).append(a.title=d("<div />",{id:b,"class":I+"-title","aria-atomic":x})).insertBefore(a.content).delegate(".qtip-close","mousedown keydown mouseup keyup mouseout",function(a){d(this).toggleClass("ui-state-active ui-state-focus","down"===a.type.substr(-4))}).delegate(".qtip-close","mouseover mouseout",function(a){d(this).toggleClass("ui-state-hover","mouseover"===a.type)}),this.options.content.button&&this._createButton()},t._removeTitle=function(a){var b=this.elements;b.title&&(b.titlebar.remove(),b.titlebar=b.title=b.button=z,a!==y&&this.reposition())},t._createPosClass=function(a){return I+"-pos-"+(a||this.options.position.my).abbrev()},t.reposition=function(c,e){if(!this.rendered||this.positioning||this.destroyed)return this;this.positioning=x;var f,g,h,i,j=this.cache,k=this.tooltip,l=this.options.position,m=l.target,n=l.my,o=l.at,p=l.viewport,q=l.container,r=l.adjust,s=r.method.split(" "),t=k.outerWidth(y),u=k.outerHeight(y),v=0,w=0,z=k.css("position"),A={left:0,top:0},B=k[0].offsetWidth>0,I=c&&"scroll"===c.type,J=d(a),K=q[0].ownerDocument,L=this.mouse;if(d.isArray(m)&&2===m.length)o={x:D,y:C},A={left:m[0],top:m[1]};else if("mouse"===m)o={x:D,y:C},(!r.mouse||this.options.hide.distance)&&j.origin&&j.origin.pageX?c=j.origin:!c||c&&("resize"===c.type||"scroll"===c.type)?c=j.event:L&&L.pageX&&(c=L),"static"!==z&&(A=q.offset()),K.body.offsetWidth!==(a.innerWidth||K.documentElement.clientWidth)&&(g=d(b.body).offset()),A={left:c.pageX-A.left+(g&&g.left||0),top:c.pageY-A.top+(g&&g.top||0)},r.mouse&&I&&L&&(A.left-=(L.scrollX||0)-J.scrollLeft(),A.top-=(L.scrollY||0)-J.scrollTop());else{if("event"===m?c&&c.target&&"scroll"!==c.type&&"resize"!==c.type?j.target=d(c.target):c.target||(j.target=this.elements.target):"event"!==m&&(j.target=d(m.jquery?m:this.elements.target)),m=j.target,m=d(m).eq(0),0===m.length)return this;m[0]===b||m[0]===a?(v=V.iOS?a.innerWidth:m.width(),w=V.iOS?a.innerHeight:m.height(),m[0]===a&&(A={top:(p||m).scrollTop(),left:(p||m).scrollLeft()})):H.imagemap&&m.is("area")?f=H.imagemap(this,m,o,H.viewport?s:y):H.svg&&m&&m[0].ownerSVGElement?f=H.svg(this,m,o,H.viewport?s:y):(v=m.outerWidth(y),w=m.outerHeight(y),A=m.offset()),f&&(v=f.width,w=f.height,g=f.offset,A=f.position),A=this.reposition.offset(m,A,q),(V.iOS>3.1&&V.iOS<4.1||V.iOS>=4.3&&V.iOS<4.33||!V.iOS&&"fixed"===z)&&(A.left-=J.scrollLeft(),A.top-=J.scrollTop()),(!f||f&&f.adjustable!==y)&&(A.left+=o.x===F?v:o.x===G?v/2:0,A.top+=o.y===E?w:o.y===G?w/2:0)}return A.left+=r.x+(n.x===F?-t:n.x===G?-t/2:0),A.top+=r.y+(n.y===E?-u:n.y===G?-u/2:0),H.viewport?(h=A.adjusted=H.viewport(this,A,l,v,w,t,u),g&&h.left&&(A.left+=g.left),g&&h.top&&(A.top+=g.top),h.my&&(this.position.my=h.my)):A.adjusted={left:0,top:0},j.posClass!==(i=this._createPosClass(this.position.my))&&(j.posClass=i,k.removeClass(j.posClass).addClass(i)),this._trigger("move",[A,p.elem||p],c)?(delete A.adjusted,e===y||!B||isNaN(A.left)||isNaN(A.top)||"mouse"===m||!d.isFunction(l.effect)?k.css(A):d.isFunction(l.effect)&&(l.effect.call(k,this,d.extend({},A)),k.queue(function(a){d(this).css({opacity:"",height:""}),V.ie&&this.style.removeAttribute("filter"),a()})),this.positioning=y,this):this},t.reposition.offset=function(a,c,e){function f(a,b){c.left+=b*a.scrollLeft(),c.top+=b*a.scrollTop()}if(!e[0])return c;var g,h,i,j,k=d(a[0].ownerDocument),l=!!V.ie&&"CSS1Compat"!==b.compatMode,m=e[0];do"static"!==(h=d.css(m,"position"))&&("fixed"===h?(i=m.getBoundingClientRect(),f(k,-1)):(i=d(m).position(),i.left+=parseFloat(d.css(m,"borderLeftWidth"))||0,i.top+=parseFloat(d.css(m,"borderTopWidth"))||0),c.left-=i.left+(parseFloat(d.css(m,"marginLeft"))||0),c.top-=i.top+(parseFloat(d.css(m,"marginTop"))||0),g||"hidden"===(j=d.css(m,"overflow"))||"visible"===j||(g=d(m)));while(m=m.offsetParent);return g&&(g[0]!==k[0]||l)&&f(g,1),c};var Y=(u=t.reposition.Corner=function(a,b){a=(""+a).replace(/([A-Z])/," $1").replace(/middle/gi,G).toLowerCase(),this.x=(a.match(/left|right/i)||a.match(/center/)||["inherit"])[0].toLowerCase(),this.y=(a.match(/top|bottom|center/i)||["inherit"])[0].toLowerCase(),this.forceY=!!b;var c=a.charAt(0);this.precedance="t"===c||"b"===c?B:A}).prototype;Y.invert=function(a,b){this[a]=this[a]===D?F:this[a]===F?D:b||this[a]},Y.string=function(a){var b=this.x,c=this.y,d=b!==c?"center"===b||"center"!==c&&(this.precedance===B||this.forceY)?[c,b]:[b,c]:[b];return a!==!1?d.join(" "):d},Y.abbrev=function(){var a=this.string(!1);return a[0].charAt(0)+(a[1]&&a[1].charAt(0)||"")},Y.clone=function(){return new u(this.string(),this.forceY)},t.toggle=function(a,c){var e=this.cache,f=this.options,g=this.tooltip;if(c){if(/over|enter/.test(c.type)&&e.event&&/out|leave/.test(e.event.type)&&f.show.target.add(c.target).length===f.show.target.length&&g.has(c.relatedTarget).length)return this;e.event=d.event.fix(c)}if(this.waiting&&!a&&(this.hiddenDuringWait=x),!this.rendered)return a?this.render(1):this;if(this.destroyed||this.disabled)return this;var h,i,j,k=a?"show":"hide",l=this.options[k],m=this.options.position,n=this.options.content,o=this.tooltip.css("width"),p=this.tooltip.is(":visible"),q=a||1===l.target.length,r=!c||l.target.length<2||e.target[0]===c.target;return(typeof a).search("boolean|number")&&(a=!p),h=!g.is(":animated")&&p===a&&r,i=h?z:!!this._trigger(k,[90]),this.destroyed?this:(i!==y&&a&&this.focus(c),!i||h?this:(d.attr(g[0],"aria-hidden",!a),a?(this.mouse&&(e.origin=d.event.fix(this.mouse)),d.isFunction(n.text)&&this._updateContent(n.text,y),d.isFunction(n.title)&&this._updateTitle(n.title,y),!w&&"mouse"===m.target&&m.adjust.mouse&&(d(b).bind("mousemove."+I,this._storeMouse),w=x),o||g.css("width",g.outerWidth(y)),this.reposition(c,arguments[2]),o||g.css("width",""),l.solo&&("string"==typeof l.solo?d(l.solo):d(M,l.solo)).not(g).not(l.target).qtip("hide",new d.Event("tooltipsolo"))):(clearTimeout(this.timers.show),delete e.origin,w&&!d(M+'[tracking="true"]:visible',l.solo).not(g).length&&(d(b).unbind("mousemove."+I),w=y),this.blur(c)),j=d.proxy(function(){a?(V.ie&&g[0].style.removeAttribute("filter"),g.css("overflow",""),"string"==typeof l.autofocus&&d(this.options.show.autofocus,g).focus(),this.options.show.target.trigger("qtip-"+this.id+"-inactive")):g.css({display:"",visibility:"",opacity:"",left:"",top:""}),this._trigger(a?"visible":"hidden")},this),l.effect===y||q===y?(g[k](),j()):d.isFunction(l.effect)?(g.stop(1,1),l.effect.call(g,this),g.queue("fx",function(a){j(),a()})):g.fadeTo(90,a?1:0,j),a&&l.target.trigger("qtip-"+this.id+"-inactive"),this))},t.show=function(a){return this.toggle(x,a)},t.hide=function(a){return this.toggle(y,a)},t.focus=function(a){if(!this.rendered||this.destroyed)return this;var b=d(M),c=this.tooltip,e=parseInt(c[0].style.zIndex,10),f=s.zindex+b.length;return c.hasClass(Q)||this._trigger("focus",[f],a)&&(e!==f&&(b.each(function(){this.style.zIndex>e&&(this.style.zIndex=this.style.zIndex-1)}),b.filter("."+Q).qtip("blur",a)),c.addClass(Q)[0].style.zIndex=f),this},t.blur=function(a){return!this.rendered||this.destroyed?this:(this.tooltip.removeClass(Q),this._trigger("blur",[this.tooltip.css("zIndex")],a),this)},t.disable=function(a){return this.destroyed?this:("toggle"===a?a=!(this.rendered?this.tooltip.hasClass(S):this.disabled):"boolean"!=typeof a&&(a=x),this.rendered&&this.tooltip.toggleClass(S,a).attr("aria-disabled",a),this.disabled=!!a,this)},t.enable=function(){return this.disable(y)},t._createButton=function(){var a=this,b=this.elements,c=b.tooltip,e=this.options.content.button,f="string"==typeof e,g=f?e:"Close tooltip";b.button&&b.button.remove(),e.jquery?b.button=e:b.button=d("<a />",{"class":"qtip-close "+(this.options.style.widget?"":I+"-icon"),title:g,"aria-label":g}).prepend(d("<span />",{"class":"ui-icon ui-icon-close",html:"&times;"})),b.button.appendTo(b.titlebar||c).attr("role","button").click(function(b){return c.hasClass(S)||a.hide(b),y})},t._updateButton=function(a){if(!this.rendered)return y;var b=this.elements.button;a?this._createButton():b.remove()},t._setWidget=function(){var a=this.options.style.widget,b=this.elements,c=b.tooltip,d=c.hasClass(S);c.removeClass(S),S=a?"ui-state-disabled":"qtip-disabled",c.toggleClass(S,d),c.toggleClass("ui-helper-reset "+k(),a).toggleClass(P,this.options.style.def&&!a),b.content&&b.content.toggleClass(k("content"),a),b.titlebar&&b.titlebar.toggleClass(k("header"),a),b.button&&b.button.toggleClass(I+"-icon",!a)},t._storeMouse=function(a){return(this.mouse=d.event.fix(a)).type="mousemove",this},t._bind=function(a,b,c,e,f){if(a&&c&&b.length){var g="."+this._id+(e?"-"+e:"");return d(a).bind((b.split?b:b.join(g+" "))+g,d.proxy(c,f||this)),this}},t._unbind=function(a,b){return a&&d(a).unbind("."+this._id+(b?"-"+b:"")),this},t._trigger=function(a,b,c){var e=new d.Event("tooltip"+a);return e.originalEvent=c&&d.extend({},c)||this.cache.event||z,this.triggering=a,this.tooltip.trigger(e,[this].concat(b||[])),this.triggering=y,!e.isDefaultPrevented()},t._bindEvents=function(a,b,c,e,f,g){var h=c.filter(e).add(e.filter(c)),i=[];h.length&&(d.each(b,function(b,c){var e=d.inArray(c,a);e>-1&&i.push(a.splice(e,1)[0])}),i.length&&(this._bind(h,i,function(a){var b=this.rendered?this.tooltip[0].offsetWidth>0:!1;(b?g:f).call(this,a)}),c=c.not(h),e=e.not(h))),this._bind(c,a,f),this._bind(e,b,g)},t._assignInitialEvents=function(a){function b(a){return this.disabled||this.destroyed?y:(this.cache.event=a&&d.event.fix(a),this.cache.target=a&&d(a.target),clearTimeout(this.timers.show),void(this.timers.show=l.call(this,function(){this.render("object"==typeof a||c.show.ready)},c.prerender?0:c.show.delay)))}var c=this.options,e=c.show.target,f=c.hide.target,g=c.show.event?d.trim(""+c.show.event).split(" "):[],h=c.hide.event?d.trim(""+c.hide.event).split(" "):[];this._bind(this.elements.target,["remove","removeqtip"],function(){this.destroy(!0)},"destroy"),/mouse(over|enter)/i.test(c.show.event)&&!/mouse(out|leave)/i.test(c.hide.event)&&h.push("mouseleave"),this._bind(e,"mousemove",function(a){this._storeMouse(a),this.cache.onTarget=x}),this._bindEvents(g,h,e,f,b,function(){return this.timers?void clearTimeout(this.timers.show):y}),(c.show.ready||c.prerender)&&b.call(this,a)},t._assignEvents=function(){var c=this,e=this.options,f=e.position,g=this.tooltip,h=e.show.target,i=e.hide.target,j=f.container,k=f.viewport,l=d(b),q=d(a),r=e.show.event?d.trim(""+e.show.event).split(" "):[],t=e.hide.event?d.trim(""+e.hide.event).split(" "):[];d.each(e.events,function(a,b){c._bind(g,"toggle"===a?["tooltipshow","tooltiphide"]:["tooltip"+a],b,null,g)}),/mouse(out|leave)/i.test(e.hide.event)&&"window"===e.hide.leave&&this._bind(l,["mouseout","blur"],function(a){/select|option/.test(a.target.nodeName)||a.relatedTarget||this.hide(a)}),e.hide.fixed?i=i.add(g.addClass(O)):/mouse(over|enter)/i.test(e.show.event)&&this._bind(i,"mouseleave",function(){clearTimeout(this.timers.show)}),(""+e.hide.event).indexOf("unfocus")>-1&&this._bind(j.closest("html"),["mousedown","touchstart"],function(a){var b=d(a.target),c=this.rendered&&!this.tooltip.hasClass(S)&&this.tooltip[0].offsetWidth>0,e=b.parents(M).filter(this.tooltip[0]).length>0;b[0]===this.target[0]||b[0]===this.tooltip[0]||e||this.target.has(b[0]).length||!c||this.hide(a)}),"number"==typeof e.hide.inactive&&(this._bind(h,"qtip-"+this.id+"-inactive",o,"inactive"),this._bind(i.add(g),s.inactiveEvents,o)),this._bindEvents(r,t,h,i,m,n),this._bind(h.add(g),"mousemove",function(a){if("number"==typeof e.hide.distance){var b=this.cache.origin||{},c=this.options.hide.distance,d=Math.abs;(d(a.pageX-b.pageX)>=c||d(a.pageY-b.pageY)>=c)&&this.hide(a)}this._storeMouse(a)}),"mouse"===f.target&&f.adjust.mouse&&(e.hide.event&&this._bind(h,["mouseenter","mouseleave"],function(a){return this.cache?void(this.cache.onTarget="mouseenter"===a.type):y}),this._bind(l,"mousemove",function(a){this.rendered&&this.cache.onTarget&&!this.tooltip.hasClass(S)&&this.tooltip[0].offsetWidth>0&&this.reposition(a)})),(f.adjust.resize||k.length)&&this._bind(d.event.special.resize?k:q,"resize",p),f.adjust.scroll&&this._bind(q.add(f.container),"scroll",p)},t._unassignEvents=function(){var c=this.options,e=c.show.target,f=c.hide.target,g=d.grep([this.elements.target[0],this.rendered&&this.tooltip[0],c.position.container[0],c.position.viewport[0],c.position.container.closest("html")[0],a,b],function(a){return"object"==typeof a});e&&e.toArray&&(g=g.concat(e.toArray())),f&&f.toArray&&(g=g.concat(f.toArray())),this._unbind(g)._unbind(g,"destroy")._unbind(g,"inactive")},d(function(){q(M,["mouseenter","mouseleave"],function(a){var b="mouseenter"===a.type,c=d(a.currentTarget),e=d(a.relatedTarget||a.target),f=this.options;b?(this.focus(a),c.hasClass(O)&&!c.hasClass(S)&&clearTimeout(this.timers.hide)):"mouse"===f.position.target&&f.position.adjust.mouse&&f.hide.event&&f.show.target&&!e.closest(f.show.target[0]).length&&this.hide(a),c.toggleClass(R,b)}),q("["+K+"]",N,o)}),s=d.fn.qtip=function(a,b,e){var f=(""+a).toLowerCase(),g=z,i=d.makeArray(arguments).slice(1),j=i[i.length-1],k=this[0]?d.data(this[0],I):z;return!arguments.length&&k||"api"===f?k:"string"==typeof a?(this.each(function(){var a=d.data(this,I);if(!a)return x;if(j&&j.timeStamp&&(a.cache.event=j),!b||"option"!==f&&"options"!==f)a[f]&&a[f].apply(a,i);else{if(e===c&&!d.isPlainObject(b))return g=a.get(b),y;a.set(b,e)}}),g!==z?g:this):"object"!=typeof a&&arguments.length?void 0:(k=h(d.extend(x,{},a)),this.each(function(a){var b,c;return c=d.isArray(k.id)?k.id[a]:k.id,c=!c||c===y||c.length<1||s.api[c]?s.nextid++:c,b=r(d(this),c,k),b===y?x:(s.api[c]=b,d.each(H,function(){"initialize"===this.initialize&&this(b)}),void b._assignInitialEvents(j))}))},d.qtip=e,s.api={},d.each({attr:function(a,b){if(this.length){var c=this[0],e="title",f=d.data(c,"qtip");if(a===e&&f&&f.options&&"object"==typeof f&&"object"==typeof f.options&&f.options.suppress)return arguments.length<2?d.attr(c,U):(f&&f.options.content.attr===e&&f.cache.attr&&f.set("content.text",b),this.attr(U,b))}return d.fn["attr"+T].apply(this,arguments)},clone:function(a){var b=d.fn["clone"+T].apply(this,arguments);return a||b.filter("["+U+"]").attr("title",function(){return d.attr(this,U)}).removeAttr(U),b}},function(a,b){if(!b||d.fn[a+T])return x;var c=d.fn[a+T]=d.fn[a];d.fn[a]=function(){return b.apply(this,arguments)||c.apply(this,arguments)}}),d.ui||(d["cleanData"+T]=d.cleanData,d.cleanData=function(a){for(var b,c=0;(b=d(a[c])).length;c++)if(b.attr(J))try{b.triggerHandler("removeqtip")}catch(e){}d["cleanData"+T].apply(this,arguments)}),s.version="3.0.3",s.nextid=0,s.inactiveEvents=N,s.zindex=15e3,s.defaults={prerender:y,id:y,overwrite:x,suppress:x,content:{text:x,attr:"title",title:y,button:y},position:{my:"top left",at:"bottom right",target:y,container:y,viewport:y,adjust:{x:0,y:0,mouse:x,scroll:x,resize:x,method:"flipinvert flipinvert"},effect:function(a,b){d(this).animate(b,{duration:200,queue:y})}},show:{target:y,event:"mouseenter",effect:x,delay:90,solo:y,ready:y,autofocus:y},hide:{target:y,event:"mouseleave",effect:x,delay:0,fixed:y,inactive:y,leave:"window",distance:y},style:{classes:"",widget:y,width:y,height:y,def:x},events:{render:z,move:z,show:z,hide:z,toggle:z,visible:z,hidden:z,focus:z,blur:z}}})}(window,document);
//# sourceMappingURL=jquery.qtip.min.map
/**
 * 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});
/*! jQuery & Zepto Lazy v1.7.10 - http://jquery.eisbehr.de/lazy - MIT&GPL-2.0 license - Copyright 2012-2018 Daniel 'Eisbehr' Kern */
!function(t,e){"use strict";function r(r,a,i,u,l){function f(){L=t.devicePixelRatio>1,i=c(i),a.delay>=0&&setTimeout(function(){s(!0)},a.delay),(a.delay<0||a.combined)&&(u.e=v(a.throttle,function(t){"resize"===t.type&&(w=B=-1),s(t.all)}),u.a=function(t){t=c(t),i.push.apply(i,t)},u.g=function(){return i=n(i).filter(function(){return!n(this).data(a.loadedName)})},u.f=function(t){for(var e=0;e<t.length;e++){var r=i.filter(function(){return this===t[e]});r.length&&s(!1,r)}},s(),n(a.appendScroll).on("scroll."+l+" resize."+l,u.e))}function c(t){var i=a.defaultImage,o=a.placeholder,u=a.imageBase,l=a.srcsetAttribute,f=a.loaderAttribute,c=a._f||{};t=n(t).filter(function(){var t=n(this),r=m(this);return!t.data(a.handledName)&&(t.attr(a.attribute)||t.attr(l)||t.attr(f)||c[r]!==e)}).data("plugin_"+a.name,r);for(var s=0,d=t.length;s<d;s++){var A=n(t[s]),g=m(t[s]),h=A.attr(a.imageBaseAttribute)||u;g===N&&h&&A.attr(l)&&A.attr(l,b(A.attr(l),h)),c[g]===e||A.attr(f)||A.attr(f,c[g]),g===N&&i&&!A.attr(E)?A.attr(E,i):g===N||!o||A.css(O)&&"none"!==A.css(O)||A.css(O,"url('"+o+"')")}return t}function s(t,e){if(!i.length)return void(a.autoDestroy&&r.destroy());for(var o=e||i,u=!1,l=a.imageBase||"",f=a.srcsetAttribute,c=a.handledName,s=0;s<o.length;s++)if(t||e||A(o[s])){var g=n(o[s]),h=m(o[s]),b=g.attr(a.attribute),v=g.attr(a.imageBaseAttribute)||l,p=g.attr(a.loaderAttribute);g.data(c)||a.visibleOnly&&!g.is(":visible")||!((b||g.attr(f))&&(h===N&&(v+b!==g.attr(E)||g.attr(f)!==g.attr(F))||h!==N&&v+b!==g.css(O))||p)||(u=!0,g.data(c,!0),d(g,h,v,p))}u&&(i=n(i).filter(function(){return!n(this).data(c)}))}function d(t,e,r,i){++z;var o=function(){y("onError",t),p(),o=n.noop};y("beforeLoad",t);var u=a.attribute,l=a.srcsetAttribute,f=a.sizesAttribute,c=a.retinaAttribute,s=a.removeAttribute,d=a.loadedName,A=t.attr(c);if(i){var g=function(){s&&t.removeAttr(a.loaderAttribute),t.data(d,!0),y(T,t),setTimeout(p,1),g=n.noop};t.off(I).one(I,o).one(D,g),y(i,t,function(e){e?(t.off(D),g()):(t.off(I),o())})||t.trigger(I)}else{var h=n(new Image);h.one(I,o).one(D,function(){t.hide(),e===N?t.attr(C,h.attr(C)).attr(F,h.attr(F)).attr(E,h.attr(E)):t.css(O,"url('"+h.attr(E)+"')"),t[a.effect](a.effectTime),s&&(t.removeAttr(u+" "+l+" "+c+" "+a.imageBaseAttribute),f!==C&&t.removeAttr(f)),t.data(d,!0),y(T,t),h.remove(),p()});var m=(L&&A?A:t.attr(u))||"";h.attr(C,t.attr(f)).attr(F,t.attr(l)).attr(E,m?r+m:null),h.complete&&h.trigger(D)}}function A(t){var e=t.getBoundingClientRect(),r=a.scrollDirection,n=a.threshold,i=h()+n>e.top&&-n<e.bottom,o=g()+n>e.left&&-n<e.right;return"vertical"===r?i:"horizontal"===r?o:i&&o}function g(){return w>=0?w:w=n(t).width()}function h(){return B>=0?B:B=n(t).height()}function m(t){return t.tagName.toLowerCase()}function b(t,e){if(e){var r=t.split(",");t="";for(var a=0,n=r.length;a<n;a++)t+=e+r[a].trim()+(a!==n-1?",":"")}return t}function v(t,e){var n,i=0;return function(o,u){function l(){i=+new Date,e.call(r,o)}var f=+new Date-i;n&&clearTimeout(n),f>t||!a.enableThrottle||u?l():n=setTimeout(l,t-f)}}function p(){--z,i.length||z||y("onFinishedAll")}function y(t,e,n){return!!(t=a[t])&&(t.apply(r,[].slice.call(arguments,1)),!0)}var z=0,w=-1,B=-1,L=!1,T="afterLoad",D="load",I="error",N="img",E="src",F="srcset",C="sizes",O="background-image";"event"===a.bind||o?f():n(t).on(D+"."+l,f)}function a(a,o){var u=this,l=n.extend({},u.config,o),f={},c=l.name+"-"+ ++i;return u.config=function(t,r){return r===e?l[t]:(l[t]=r,u)},u.addItems=function(t){return f.a&&f.a("string"===n.type(t)?n(t):t),u},u.getItems=function(){return f.g?f.g():{}},u.update=function(t){return f.e&&f.e({},!t),u},u.force=function(t){return f.f&&f.f("string"===n.type(t)?n(t):t),u},u.loadAll=function(){return f.e&&f.e({all:!0},!0),u},u.destroy=function(){return n(l.appendScroll).off("."+c,f.e),n(t).off("."+c),f={},e},r(u,l,a,f,c),l.chainable?a:u}var n=t.jQuery||t.Zepto,i=0,o=!1;n.fn.Lazy=n.fn.lazy=function(t){return new a(this,t)},n.Lazy=n.lazy=function(t,r,i){if(typeof r==="function"&&(i=r,r=[]),typeof i==="function"){t=n.isArray(t)?t:[t],r=n.isArray(r)?r:[r];for(var o=a.prototype.config,u=o._f||(o._f={}),l=0,f=t.length;l<f;l++)(o[t[l]]===e||typeof o[t[l]]==="function")&&(o[t[l]]=i);for(var c=0,s=r.length;c<s;c++)u[r[c]]=t[0]}},a.prototype.config={name:"lazy",chainable:!0,autoDestroy:!0,bind:"load",threshold:500,visibleOnly:!1,appendScroll:t,scrollDirection:"both",imageBase:null,defaultImage:"data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==",placeholder:null,delay:-1,combined:!1,attribute:"data-src",srcsetAttribute:"data-srcset",sizesAttribute:"data-sizes",retinaAttribute:"data-retina",loaderAttribute:"data-loader",imageBaseAttribute:"data-imagebase",removeAttribute:!0,handledName:"handled",loadedName:"loaded",effect:"show",effectTime:0,enableThrottle:!0,throttle:250,beforeLoad:e,afterLoad:e,onError:e,onFinishedAll:e},n(t).on("load",function(){o=!0})}(window);
/*!
Waypoints - 4.0.1
Copyright © 2011-2016 Caleb Troughton
Licensed under the MIT license.
https://github.com/imakewebthings/waypoints/blob/master/licenses.txt
*/
!function(){"use strict";function t(o){if(!o)throw new Error("No options passed to Waypoint constructor");if(!o.element)throw new Error("No element option passed to Waypoint constructor");if(!o.handler)throw new Error("No handler option passed to Waypoint constructor");this.key="waypoint-"+e,this.options=t.Adapter.extend({},t.defaults,o),this.element=this.options.element,this.adapter=new t.Adapter(this.element),this.callback=o.handler,this.axis=this.options.horizontal?"horizontal":"vertical",this.enabled=this.options.enabled,this.triggerPoint=null,this.group=t.Group.findOrCreate({name:this.options.group,axis:this.axis}),this.context=t.Context.findOrCreateByElement(this.options.context),t.offsetAliases[this.options.offset]&&(this.options.offset=t.offsetAliases[this.options.offset]),this.group.add(this),this.context.add(this),i[this.key]=this,e+=1}var e=0,i={};t.prototype.queueTrigger=function(t){this.group.queueTrigger(this,t)},t.prototype.trigger=function(t){this.enabled&&this.callback&&this.callback.apply(this,t)},t.prototype.destroy=function(){this.context.remove(this),this.group.remove(this),delete i[this.key]},t.prototype.disable=function(){return this.enabled=!1,this},t.prototype.enable=function(){return this.context.refresh(),this.enabled=!0,this},t.prototype.next=function(){return this.group.next(this)},t.prototype.previous=function(){return this.group.previous(this)},t.invokeAll=function(t){var e=[];for(var o in i)e.push(i[o]);for(var n=0,r=e.length;r>n;n++)e[n][t]()},t.destroyAll=function(){t.invokeAll("destroy")},t.disableAll=function(){t.invokeAll("disable")},t.enableAll=function(){t.Context.refreshAll();for(var e in i)i[e].enabled=!0;return this},t.refreshAll=function(){t.Context.refreshAll()},t.viewportHeight=function(){return window.innerHeight||document.documentElement.clientHeight},t.viewportWidth=function(){return document.documentElement.clientWidth},t.adapters=[],t.defaults={context:window,continuous:!0,enabled:!0,group:"default",horizontal:!1,offset:0},t.offsetAliases={"bottom-in-view":function(){return this.context.innerHeight()-this.adapter.outerHeight()},"right-in-view":function(){return this.context.innerWidth()-this.adapter.outerWidth()}},window.Waypoint=t}(),function(){"use strict";function t(t){window.setTimeout(t,1e3/60)}function e(t){this.element=t,this.Adapter=n.Adapter,this.adapter=new this.Adapter(t),this.key="waypoint-context-"+i,this.didScroll=!1,this.didResize=!1,this.oldScroll={x:this.adapter.scrollLeft(),y:this.adapter.scrollTop()},this.waypoints={vertical:{},horizontal:{}},t.waypointContextKey=this.key,o[t.waypointContextKey]=this,i+=1,n.windowContext||(n.windowContext=!0,n.windowContext=new e(window)),this.createThrottledScrollHandler(),this.createThrottledResizeHandler()}var i=0,o={},n=window.Waypoint,r=window.onload;e.prototype.add=function(t){var e=t.options.horizontal?"horizontal":"vertical";this.waypoints[e][t.key]=t,this.refresh()},e.prototype.checkEmpty=function(){var t=this.Adapter.isEmptyObject(this.waypoints.horizontal),e=this.Adapter.isEmptyObject(this.waypoints.vertical),i=this.element==this.element.window;t&&e&&!i&&(this.adapter.off(".waypoints"),delete o[this.key])},e.prototype.createThrottledResizeHandler=function(){function t(){e.handleResize(),e.didResize=!1}var e=this;this.adapter.on("resize.waypoints",function(){e.didResize||(e.didResize=!0,n.requestAnimationFrame(t))})},e.prototype.createThrottledScrollHandler=function(){function t(){e.handleScroll(),e.didScroll=!1}var e=this;this.adapter.on("scroll.waypoints",function(){(!e.didScroll||n.isTouch)&&(e.didScroll=!0,n.requestAnimationFrame(t))})},e.prototype.handleResize=function(){n.Context.refreshAll()},e.prototype.handleScroll=function(){var t={},e={horizontal:{newScroll:this.adapter.scrollLeft(),oldScroll:this.oldScroll.x,forward:"right",backward:"left"},vertical:{newScroll:this.adapter.scrollTop(),oldScroll:this.oldScroll.y,forward:"down",backward:"up"}};for(var i in e){var o=e[i],n=o.newScroll>o.oldScroll,r=n?o.forward:o.backward;for(var s in this.waypoints[i]){var a=this.waypoints[i][s];if(null!==a.triggerPoint){var l=o.oldScroll<a.triggerPoint,h=o.newScroll>=a.triggerPoint,p=l&&h,u=!l&&!h;(p||u)&&(a.queueTrigger(r),t[a.group.id]=a.group)}}}for(var c in t)t[c].flushTriggers();this.oldScroll={x:e.horizontal.newScroll,y:e.vertical.newScroll}},e.prototype.innerHeight=function(){return this.element==this.element.window?n.viewportHeight():this.adapter.innerHeight()},e.prototype.remove=function(t){delete this.waypoints[t.axis][t.key],this.checkEmpty()},e.prototype.innerWidth=function(){return this.element==this.element.window?n.viewportWidth():this.adapter.innerWidth()},e.prototype.destroy=function(){var t=[];for(var e in this.waypoints)for(var i in this.waypoints[e])t.push(this.waypoints[e][i]);for(var o=0,n=t.length;n>o;o++)t[o].destroy()},e.prototype.refresh=function(){var t,e=this.element==this.element.window,i=e?void 0:this.adapter.offset(),o={};this.handleScroll(),t={horizontal:{contextOffset:e?0:i.left,contextScroll:e?0:this.oldScroll.x,contextDimension:this.innerWidth(),oldScroll:this.oldScroll.x,forward:"right",backward:"left",offsetProp:"left"},vertical:{contextOffset:e?0:i.top,contextScroll:e?0:this.oldScroll.y,contextDimension:this.innerHeight(),oldScroll:this.oldScroll.y,forward:"down",backward:"up",offsetProp:"top"}};for(var r in t){var s=t[r];for(var a in this.waypoints[r]){var l,h,p,u,c,d=this.waypoints[r][a],f=d.options.offset,w=d.triggerPoint,y=0,g=null==w;d.element!==d.element.window&&(y=d.adapter.offset()[s.offsetProp]),"function"==typeof f?f=f.apply(d):"string"==typeof f&&(f=parseFloat(f),d.options.offset.indexOf("%")>-1&&(f=Math.ceil(s.contextDimension*f/100))),l=s.contextScroll-s.contextOffset,d.triggerPoint=Math.floor(y+l-f),h=w<s.oldScroll,p=d.triggerPoint>=s.oldScroll,u=h&&p,c=!h&&!p,!g&&u?(d.queueTrigger(s.backward),o[d.group.id]=d.group):!g&&c?(d.queueTrigger(s.forward),o[d.group.id]=d.group):g&&s.oldScroll>=d.triggerPoint&&(d.queueTrigger(s.forward),o[d.group.id]=d.group)}}return n.requestAnimationFrame(function(){for(var t in o)o[t].flushTriggers()}),this},e.findOrCreateByElement=function(t){return e.findByElement(t)||new e(t)},e.refreshAll=function(){for(var t in o)o[t].refresh()},e.findByElement=function(t){return o[t.waypointContextKey]},window.onload=function(){r&&r(),e.refreshAll()},n.requestAnimationFrame=function(e){var i=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||t;i.call(window,e)},n.Context=e}(),function(){"use strict";function t(t,e){return t.triggerPoint-e.triggerPoint}function e(t,e){return e.triggerPoint-t.triggerPoint}function i(t){this.name=t.name,this.axis=t.axis,this.id=this.name+"-"+this.axis,this.waypoints=[],this.clearTriggerQueues(),o[this.axis][this.name]=this}var o={vertical:{},horizontal:{}},n=window.Waypoint;i.prototype.add=function(t){this.waypoints.push(t)},i.prototype.clearTriggerQueues=function(){this.triggerQueues={up:[],down:[],left:[],right:[]}},i.prototype.flushTriggers=function(){for(var i in this.triggerQueues){var o=this.triggerQueues[i],n="up"===i||"left"===i;o.sort(n?e:t);for(var r=0,s=o.length;s>r;r+=1){var a=o[r];(a.options.continuous||r===o.length-1)&&a.trigger([i])}}this.clearTriggerQueues()},i.prototype.next=function(e){this.waypoints.sort(t);var i=n.Adapter.inArray(e,this.waypoints),o=i===this.waypoints.length-1;return o?null:this.waypoints[i+1]},i.prototype.previous=function(e){this.waypoints.sort(t);var i=n.Adapter.inArray(e,this.waypoints);return i?this.waypoints[i-1]:null},i.prototype.queueTrigger=function(t,e){this.triggerQueues[e].push(t)},i.prototype.remove=function(t){var e=n.Adapter.inArray(t,this.waypoints);e>-1&&this.waypoints.splice(e,1)},i.prototype.first=function(){return this.waypoints[0]},i.prototype.last=function(){return this.waypoints[this.waypoints.length-1]},i.findOrCreate=function(t){return o[t.axis][t.name]||new i(t)},n.Group=i}(),function(){"use strict";function t(t){this.$element=e(t)}var e=window.jQuery,i=window.Waypoint;e.each(["innerHeight","innerWidth","off","offset","on","outerHeight","outerWidth","scrollLeft","scrollTop"],function(e,i){t.prototype[i]=function(){var t=Array.prototype.slice.call(arguments);return this.$element[i].apply(this.$element,t)}}),e.each(["extend","inArray","isEmptyObject"],function(i,o){t[o]=e[o]}),i.adapters.push({name:"jquery",Adapter:t}),i.Adapter=t}(),function(){"use strict";function t(t){return function(){var i=[],o=arguments[0];return t.isFunction(arguments[0])&&(o=t.extend({},arguments[1]),o.handler=arguments[0]),this.each(function(){var n=t.extend({},o,{element:this});"string"==typeof n.context&&(n.context=t(this).closest(n.context)[0]),i.push(new e(n))}),i}}var e=window.Waypoint;window.jQuery&&(window.jQuery.fn.waypoint=t(window.jQuery)),window.Zepto&&(window.Zepto.fn.waypoint=t(window.Zepto))}();
if(typeof jQuery=="undefined"){throw"Unable to load Shadowbox, jQuery library not found"}var Shadowbox={};Shadowbox.lib={adapter:"jquery",getStyle:function(B,A){return jQuery(B).css(A)},setStyle:function(C,B,D){if(typeof B!="object"){var A={};A[B]=D;B=A}jQuery(C).css(B)},get:function(A){return(typeof A=="string")?document.getElementById(A):A},remove:function(A){jQuery(A).remove()},getTarget:function(A){return A.target},getPageXY:function(A){return[A.pageX,A.pageY]},preventDefault:function(A){A.preventDefault()},keyCode:function(A){return A.keyCode},addEvent:function(C,A,B){jQuery(C).on(A,B)},removeEvent:function(C,A,B){jQuery(C).off(A,B)},append:function(B,A){jQuery(B).append(A)}};(function(A){A.fn.shadowbox=function(B){return this.each(function(){var E=A(this);var D=A.extend({},B||{},A.metadata?E.metadata():A.meta?E.data():{});var C=this.className||"";D.width=parseInt((C.match(/w:(\d+)/)||[])[1])||D.width;D.height=parseInt((C.match(/h:(\d+)/)||[])[1])||D.height;Shadowbox.setup(E,D)})}})(jQuery);
if(typeof Shadowbox=="undefined"){throw"Unable to load Shadowbox, no base library adapter found"}(function(){var version="2.0";var options={animate:true,animateFade:true,animSequence:"wh",flvPlayer:"flvplayer.swf",modal:false,overlayColor:"#000",overlayOpacity:0.8,flashBgColor:"#000000",autoplayMovies:true,showMovieControls:true,slideshowDelay:0,resizeDuration:0.55,fadeDuration:0.35,displayNav:true,continuous:false,displayCounter:true,counterType:"default",counterLimit:10,viewportPadding:20,handleOversize:"resize",handleException:null,handleUnsupported:"link",initialHeight:160,initialWidth:320,enableKeys:true,onOpen:null,onFinish:null,onChange:null,onClose:null,skipSetup:false,errors:{fla:{name:"Flash",url:"http://www.adobe.com/products/flashplayer/"},qt:{name:"QuickTime",url:"http://www.apple.com/quicktime/download/"},wmp:{name:"Windows Media Player",url:"http://www.microsoft.com/windows/windowsmedia/"},f4m:{name:"Flip4Mac",url:"http://www.flip4mac.com/wmv_download.htm"}},ext:{img:["png","jpg","jpeg","gif","bmp","webp"],swf:["swf"],flv:["flv"],qt:["dv","mov","moov","movie","mp4"],wmp:["asf","wm","wmv"],qtwmp:["avi","mpg","mpeg"],iframe:["asp","aspx","cgi","cfm","htm","html","pl","php","php3","php4","php5","phtml","rb","rhtml","shtml","txt","vbs"]}};var SB=Shadowbox;var SL=SB.lib;var default_options;var RE={domain:/:\/\/(.*?)[:\/]/,inline:/#(.+)$/,rel:/^(light|shadow)box/i,gallery:/^(light|shadow)box\[(.*?)\]/i,unsupported:/^unsupported-(\w+)/,param:/\s*([a-z_]*?)\s*=\s*(.+)\s*/,empty:/^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i};var cache=[];var gallery;var current;var content;var content_id="shadowbox_content";var dims;var initialized=false;var activated=false;var slide_timer;var slide_start;var slide_delay=0;var ua=navigator.userAgent.toLowerCase();var client={isStrict:document.compatMode=="CSS1Compat",isOpera:ua.indexOf("opera")>-1,isIE:ua.indexOf("msie")>-1,isIE7:ua.indexOf("msie 7")>-1,isSafari:/webkit|khtml/.test(ua),isWindows:ua.indexOf("windows")!=-1||ua.indexOf("win32")!=-1,isMac:ua.indexOf("macintosh")!=-1||ua.indexOf("mac os x")!=-1,isLinux:ua.indexOf("linux")!=-1};client.isBorderBox=client.isIE&&!client.isStrict;client.isSafari3=client.isSafari&&!!(document.evaluate);client.isGecko=ua.indexOf("gecko")!=-1&&!client.isSafari;var ltIE7=client.isIE&&!client.isIE7;var plugins;if(navigator.plugins&&navigator.plugins.length){var detectPlugin=function(plugin_name){var detected=false;for(var i=0,len=navigator.plugins.length;i<len;++i){if(navigator.plugins[i].name.indexOf(plugin_name)>-1){detected=true;break}}return detected};var f4m=detectPlugin("Flip4Mac");plugins={fla:detectPlugin("Shockwave Flash"),qt:detectPlugin("QuickTime"),wmp:!f4m&&detectPlugin("Windows Media"),f4m:f4m}}else{var detectPlugin=function(plugin_name){var detected=false;try{var axo=new ActiveXObject(plugin_name);if(axo){detected=true}}catch(e){}return detected};plugins={fla:detectPlugin("ShockwaveFlash.ShockwaveFlash"),qt:detectPlugin("QuickTime.QuickTime"),wmp:detectPlugin("wmplayer.ocx"),f4m:false}}var apply=function(o,e){for(var p in e){o[p]=e[p]}return o};var isLink=function(el){return el&&typeof el.tagName=="string"&&(el.tagName.toUpperCase()=="A"||el.tagName.toUpperCase()=="AREA")};SL.getViewportHeight=function(){var h=window.innerHeight;var mode=document.compatMode;if((mode||client.isIE)&&!client.isOpera){h=client.isStrict?document.documentElement.clientHeight:document.body.clientHeight}return h};SL.getViewportWidth=function(){var w=window.innerWidth;var mode=document.compatMode;if(mode||client.isIE){w=client.isStrict?document.documentElement.clientWidth:document.body.clientWidth}return w};SL.createHTML=function(obj){var html="<"+obj.tag;for(var attr in obj){if(attr=="tag"||attr=="html"||attr=="children"){continue}if(attr=="cls"){html+=' class="'+obj.cls+'"'}else{html+=" "+attr+'="'+obj[attr]+'"'}}if(RE.empty.test(obj.tag)){html+="/>"}else{html+=">";var cn=obj.children;if(cn){for(var i=0,len=cn.length;i<len;++i){html+=this.createHTML(cn[i])}}if(obj.html){html+=obj.html}html+="</"+obj.tag+">"}return html};var ease=function(x){return 1+Math.pow(x-1,3)};var animate=function(el,p,to,d,cb){var from=parseFloat(SL.getStyle(el,p));if(isNaN(from)){from=0}if(from==to){if(typeof cb=="function"){cb()}return }var delta=to-from;var op=p=="opacity";var unit=op?"":"px";var fn=function(ease){SL.setStyle(el,p,from+ease*delta+unit)};if(!options.animate&&!op||op&&!options.animateFade){fn(1);if(typeof cb=="function"){cb()}return }d*=1000;var begin=new Date().getTime();var end=begin+d;var timer=setInterval(function(){var time=new Date().getTime();if(time>=end){clearInterval(timer);fn(1);if(typeof cb=="function"){cb()}}else{fn(ease((time-begin)/d))}},10)};var clearOpacity=function(el){var s=el.style;if(client.isIE){if(typeof s.filter=="string"&&(/alpha/i).test(s.filter)){s.filter=s.filter.replace(/[\w\.]*alpha\(.*?\);?/i,"")}}else{s.opacity="";s["-moz-opacity"]="";s["-khtml-opacity"]=""}};var getComputedHeight=function(el){var h=Math.max(el.offsetHeight,el.clientHeight);if(!h){h=parseInt(SL.getStyle(el,"height"),10)||0;if(!client.isBorderBox){h+=parseInt(SL.getStyle(el,"padding-top"),10)+parseInt(SL.getStyle(el,"padding-bottom"),10)+parseInt(SL.getStyle(el,"border-top-width"),10)+parseInt(SL.getStyle(el,"border-bottom-width"),10)}}return h};var getPlayer=function(url){var m=url.match(RE.domain);var d=m&&document.domain==m[1];if(url.indexOf("#")>-1&&d){return"inline"}var q=url.indexOf("?");if(q>-1){url=url.substring(0,q)}if(RE.img.test(url)){return"img"}if(RE.swf.test(url)){return plugins.fla?"swf":"unsupported-swf"}if(RE.flv.test(url)){return plugins.fla?"flv":"unsupported-flv"}if(RE.qt.test(url)){return plugins.qt?"qt":"unsupported-qt"}if(RE.wmp.test(url)){if(plugins.wmp){return"wmp"}if(plugins.f4m){return"qt"}if(client.isMac){return plugins.qt?"unsupported-f4m":"unsupported-qtf4m"}return"unsupported-wmp"}else{if(RE.qtwmp.test(url)){if(plugins.qt){return"qt"}if(plugins.wmp){return"wmp"}return client.isMac?"unsupported-qt":"unsupported-qtwmp"}else{if(!d||RE.iframe.test(url)){return"iframe"}}}return"unsupported"};var handleClick=function(ev){var link;if(isLink(this)){link=this}else{link=SL.getTarget(ev);while(!isLink(link)&&link.parentNode){link=link.parentNode}}if(link){SB.open(link);if(gallery.length){SL.preventDefault(ev)}}};var toggleNav=function(id,on){var el=SL.get("shadowbox_nav_"+id);if(el){el.style.display=on?"":"none"}};var buildBars=function(cb){var obj=gallery[current];var title_i=SL.get("shadowbox_title_inner");title_i.innerHTML=obj.title||"";var nav=SL.get("shadowbox_nav");if(nav){var c,n,pl,pa,p;if(options.displayNav){c=true;var len=gallery.length;if(len>1){if(options.continuous){n=p=true}else{n=(len-1)>current;p=current>0}}if(options.slideshowDelay>0&&hasNext()){pa=slide_timer!="paused";pl=!pa}}else{c=n=pl=pa=p=false}toggleNav("close",c);toggleNav("next",n);toggleNav("next_center",n);toggleNav("play",pl);toggleNav("pause",pa);toggleNav("previous",p);toggleNav("previous_center",p);toggleNav("mobile",p)}var counter=SL.get("shadowbox_counter");if(counter){var co="";if(options.displayCounter&&gallery.length>1){if(options.counterType=="skip"){var i=0,len=gallery.length,end=len;var limit=parseInt(options.counterLimit);if(limit<len){var h=Math.round(limit/2);i=current-h;if(i<0){i+=len}end=current+(limit-h);if(end>len){end-=len}}while(i!=end){if(i==len){i=0}co+='<a onclick="Shadowbox.change('+i+');"';if(i==current){co+=' class="shadowbox_counter_current"'}co+=">"+(++i)+"</a>"}}else{co=(current+1)+" "+SB.LANG.of+" "+len}}counter.innerHTML=co}cb()};var hideBars=function(anim,cb){var obj=gallery[current];var title=SL.get("shadowbox_title");var info=SL.get("shadowbox_info");var title_i=SL.get("shadowbox_title_inner");var info_i=SL.get("shadowbox_info_inner");var fn=function(){buildBars(cb)};var title_h=getComputedHeight(title);var info_h=getComputedHeight(info)*-1;if(anim){animate(title_i,"margin-top",title_h,0.35);animate(info_i,"margin-top",info_h,0.35,fn)}else{SL.setStyle(title_i,"margin-top",title_h+"px");SL.setStyle(info_i,"margin-top",info_h+"px");fn()}};var showBars=function(cb){var title_i=SL.get("shadowbox_title_inner");var info_i=SL.get("shadowbox_info_inner");var t=title_i.innerHTML!="";if(t){animate(title_i,"margin-top",0,0.35)}animate(info_i,"margin-top",0,0.35,cb)};var loadContent=function(){var obj=gallery[current];if(!obj){return }var changing=false;if(content){content.remove();changing=true}var p=obj.player=="inline"?"html":obj.player;if(typeof SB[p]!="function"){SB.raise("Unknown player "+obj.player)}content=new SB[p](content_id,obj);listenKeys(false);toggleLoading(true);hideBars(changing,function(){if(!content){return }if(!changing){SL.get("shadowbox").style.display=""}var fn=function(){resizeContent(function(){if(!content){return }showBars(function(){if(!content){return }SL.get("shadowbox_body_inner").innerHTML=SL.createHTML(content.markup(dims));toggleLoading(false,function(){if(!content){return }if(typeof content.onLoad=="function"){content.onLoad()}if(options.onFinish&&typeof options.onFinish=="function"){options.onFinish(gallery[current])}if(slide_timer!="paused"){SB.play()}listenKeys(true)})})})};if(typeof content.ready!="undefined"){var id=setInterval(function(){if(content){if(content.ready){clearInterval(id);id=null;fn()}}else{clearInterval(id);id=null}},100)}else{fn()}});if(gallery.length>1){var next=gallery[current+1]||gallery[0];if(next.player=="img"){var a=new Image();a.src=next.content}var prev=gallery[current-1]||gallery[gallery.length-1];if(prev.player=="img"){var b=new Image();b.src=prev.content}}};var setDimensions=function(height,width,resizable){resizable=resizable||false;var sb=SL.get("shadowbox_body");var h=height=parseInt(height);var w=width=parseInt(width);var view_h=SL.getViewportHeight();var view_w=SL.getViewportWidth();var border_w=parseInt(SL.getStyle(sb,"border-left-width"),10)+parseInt(SL.getStyle(sb,"border-right-width"),10);var extra_w=border_w+2*options.viewportPadding;if(w+extra_w>=view_w){w=view_w-extra_w}var border_h=parseInt(SL.getStyle(sb,"border-top-width"),10)+parseInt(SL.getStyle(sb,"border-bottom-width"),10);var bar_h=getComputedHeight(SL.get("shadowbox_title"))+getComputedHeight(SL.get("shadowbox_info"));var extra_h=border_h+2*options.viewportPadding+bar_h;if(h+extra_h>=view_h){h=view_h-extra_h}var drag=false;var resize_h=height;var resize_w=width;var handle=options.handleOversize;if(resizable&&(handle=="resize"||handle=="drag")){var change_h=(height-h)/height;var change_w=(width-w)/width;if(handle=="resize"){if(change_h>change_w){w=Math.round((width/height)*h)}else{if(change_w>change_h){h=Math.round((height/width)*w)}}resize_w=w;resize_h=h}else{var link=gallery[current];if(link){drag=link.player=="img"&&(change_h>0||change_w>0)}}}dims={height:h+border_h+bar_h,width:w+border_w,inner_h:h,inner_w:w,top:(view_h-(h+extra_h))/2+options.viewportPadding,resize_h:resize_h,resize_w:resize_w,drag:drag}};var resizeContent=function(cb){if(!content){return }setDimensions(content.height,content.width,content.resizable);if(cb){switch(options.animSequence){case"hw":adjustHeight(dims.inner_h,dims.top,true,function(){adjustWidth(dims.width,true,cb)});break;case"wh":adjustWidth(dims.width,true,function(){adjustHeight(dims.inner_h,dims.top,true,cb)});break;case"sync":default:adjustWidth(dims.width,true);adjustHeight(dims.inner_h,dims.top,true,cb)}}else{adjustWidth(dims.width,false);adjustHeight(dims.inner_h,dims.top,false);var c=SL.get(content_id);if(c){if(content.resizable&&options.handleOversize=="resize"){c.height=dims.resize_h;c.width=dims.resize_w}if(gallery[current].player=="img"&&options.handleOversize=="drag"){var top=parseInt(SL.getStyle(c,"top"));if(top+content.height<dims.inner_h){SL.setStyle(c,"top",dims.inner_h-content.height+"px")}var left=parseInt(SL.getStyle(c,"left"));if(left+content.width<dims.inner_w){SL.setStyle(c,"left",dims.inner_w-content.width+"px")}}}}};var adjustHeight=function(height,top,anim,cb){height=parseInt(height);var sb=SL.get("shadowbox_body");if(anim){animate(sb,"height",height,options.resizeDuration)}else{SL.setStyle(sb,"height",height+"px")}var s=SL.get("shadowbox");if(anim){animate(s,"top",top,options.resizeDuration,cb)}else{SL.setStyle(s,"top",top+"px");if(typeof cb=="function"){cb()}}};var adjustWidth=function(width,anim,cb){width=parseInt(width);var s=SL.get("shadowbox");if(anim){animate(s,"width",width,options.resizeDuration,cb)}else{SL.setStyle(s,"width",width+"px");if(typeof cb=="function"){cb()}}};var listenKeys=function(on){if(!options.enableKeys){return }SL[(on?"add":"remove")+"Event"](document,"keydown",handleKey)};var handleKey=function(e){var code=SL.keyCode(e);SL.preventDefault(e);if(code==81||code==88||code==27){SB.close()}else{if(code==37){SB.previous()}else{if(code==39){SB.next()}else{if(code==32){SB[(typeof slide_timer=="number"?"pause":"play")]()}}}}};var toggleLoading=function(on,cb){var loading=SL.get("shadowbox_loading");if(on){loading.style.display="";if(typeof cb=="function"){cb()}}else{var p=gallery[current].player;var anim=(p=="img"||p=="html");var fn=function(){loading.style.display="none";clearOpacity(loading);if(typeof cb=="function"){cb()}};if(anim){animate(loading,"opacity",0,options.fadeDuration,fn)}else{fn()}}};var fixTop=function(){SL.get("shadowbox_container").style.top=document.documentElement.scrollTop+"px"};var fixHeight=function(){SL.get("shadowbox_overlay").style.height=SL.getViewportHeight()+"px"};var hasNext=function(){return gallery.length>1&&(current!=gallery.length-1||options.continuous)};var toggleVisible=function(cb){var els,v=(cb)?"hidden":"visible";var hide=["select","object","embed"];for(var i=0;i<hide.length;++i){els=document.getElementsByTagName(hide[i]);for(var j=0,len=els.length;j<len;++j){els[j].style.visibility=v}}var so=SL.get("shadowbox_overlay");var sc=SL.get("shadowbox_container");var sb=SL.get("shadowbox");if(cb){SL.setStyle(so,{backgroundColor:options.overlayColor,opacity:0});if(!options.modal){SL.addEvent(so,"click",SB.close)}if(ltIE7){fixTop();fixHeight();SL.addEvent(window,"scroll",fixTop)}sb.style.display="none";sc.style.visibility="visible";animate(so,"opacity",parseFloat(options.overlayOpacity),options.fadeDuration,cb)}else{SL.removeEvent(so,"click",SB.close);if(ltIE7){SL.removeEvent(window,"scroll",fixTop)}sb.style.display="none";animate(so,"opacity",0,options.fadeDuration,function(){sc.style.visibility="hidden";sb.style.display="";clearOpacity(so)})}};Shadowbox.init=function(opts){if(initialized){return }if(typeof SB.LANG=="undefined"){SB.raise("No Shadowbox language loaded");return }if(typeof SB.SKIN=="undefined"){SB.raise("No Shadowbox skin loaded");return }apply(options,opts||{});var markup=SB.SKIN.markup.replace(/\{(\w+)\}/g,function(m,p){return SB.LANG[p]});var bd=document.body||document.documentElement;SL.append(bd,markup);if(ltIE7){SL.setStyle(SL.get("shadowbox_container"),"position","absolute");SL.get("shadowbox_body").style.zoom=1;var png=SB.SKIN.png_fix;if(png&&png.constructor==Array){for(var i=0;i<png.length;++i){var el=SL.get(png[i]);if(el){var match=SL.getStyle(el,"background-image").match(/url\("(.*\.png)"\)/);if(match){SL.setStyle(el,{backgroundImage:"none",filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,src="+match[1]+",sizingMethod=scale);"})}}}}}for(var e in options.ext){RE[e]=new RegExp(".("+options.ext[e].join("|")+")s*$","i")}var id;SL.addEvent(window,"resize",function(){if(id){clearTimeout(id);id=null}id=setTimeout(function(){if(ltIE7){fixHeight()}resizeContent()},50)});if(!options.skipSetup){SB.setup()}initialized=true};Shadowbox.loadSkin=function(skin,dir){if(!(/\/$/.test(dir))){dir+="/"}skin=dir+skin+"/";/*document.write('<link rel="stylesheet" type="text/css" href="'+skin+'skin.css">');document.write('<script type="text/javascript" src="'+skin+'skin.js"><\/script>')*/};Shadowbox.loadLanguage=function(lang,dir){if(!(/\/$/.test(dir))){dir+="/"}document.write('<script type="text/javascript" src="'+dir+"shadowbox-"+lang+'.js"><\/script>')};Shadowbox.loadPlayer=function(players,dir){if(typeof players=="string"){players=[players]}if(!(/\/$/.test(dir))){dir+="/"}for(var i=0,len=players.length;i<len;++i){document.write('<script type="text/javascript" src="'+dir+"shadowbox-"+players[i]+'.js"><\/script>')}};Shadowbox.setup=function(links,opts){if(!links){var links=[];var a=document.getElementsByTagName("a"),rel;for(var i=0,len=a.length;i<len;++i){rel=a[i].getAttribute("rel");if(rel&&RE.rel.test(rel)){links[links.length]=a[i]}}}else{if(!links.length){links=[links]}}var link;for(var i=0,len=links.length;i<len;++i){link=links[i];if(typeof link.shadowboxCacheKey=="undefined"){link.shadowboxCacheKey=cache.length;SL.addEvent(link,"click",handleClick)}cache[link.shadowboxCacheKey]=this.buildCacheObj(link,opts)}};Shadowbox.buildCacheObj=function(link,opts){var href=link.href;var o={el:link,title:link.getAttribute("title"),player:getPlayer(href),options:apply({},opts||{}),content:href};var opt,l_opts=["player","title","height","width","gallery"];for(var i=0,len=l_opts.length;i<len;++i){opt=l_opts[i];if(typeof o.options[opt]!="undefined"){o[opt]=o.options[opt];delete o.options[opt]}}var rel=link.getAttribute("rel");if(rel){var match=rel.match(RE.gallery);if(match){o.gallery=escape(match[2])}var params=rel.split(";");for(var i=0,len=params.length;i<len;++i){match=params[i].match(RE.param);if(match){if(match[1]=="options"){eval("apply(o.options, "+match[2]+")")}else{o[match[1]]=match[2]}}}}return o};Shadowbox.applyOptions=function(opts){if(opts){default_options=apply({},options);options=apply(options,opts)}};Shadowbox.revertOptions=function(){if(default_options){options=default_options;default_options=null}};Shadowbox.open=function(obj,opts){this.revertOptions();if(isLink(obj)){if(typeof obj.shadowboxCacheKey=="undefined"||typeof cache[obj.shadowboxCacheKey]=="undefined"){obj=this.buildCacheObj(obj,opts)}else{obj=cache[obj.shadowboxCacheKey]}}if(obj.constructor==Array){gallery=obj;current=0}else{var copy=apply({},obj);if(!obj.gallery){gallery=[copy];current=0}else{current=null;gallery=[];var ci;for(var i=0,len=cache.length;i<len;++i){ci=cache[i];if(ci.gallery){if(ci.content==obj.content&&ci.gallery==obj.gallery&&ci.title==obj.title){current=gallery.length}if(ci.gallery==obj.gallery){gallery.push(apply({},ci))}}}if(current==null){gallery.unshift(copy);current=0}}}obj=gallery[current];if(obj.options||opts){this.applyOptions(apply(apply({},obj.options||{}),opts||{}))}var match,r;for(var i=0,len=gallery.length;i<len;++i){r=false;if(gallery[i].player=="unsupported"){r=true}else{if(match=RE.unsupported.exec(gallery[i].player)){if(options.handleUnsupported=="link"){gallery[i].player="html";var s,a,oe=options.errors;switch(match[1]){case"qtwmp":s="either";a=[oe.qt.url,oe.qt.name,oe.wmp.url,oe.wmp.name];break;case"qtf4m":s="shared";a=[oe.qt.url,oe.qt.name,oe.f4m.url,oe.f4m.name];break;default:s="single";if(match[1]=="swf"||match[1]=="flv"){match[1]="fla"}a=[oe[match[1]].url,oe[match[1]].name]}var msg=SB.LANG.errors[s].replace(/\{(\d+)\}/g,function(m,i){return a[i]});gallery[i].content='<div class="shadowbox_message">'+msg+"</div>"}else{r=true}}else{if(gallery[i].player=="inline"){var match=RE.inline.exec(gallery[i].content);if(match){var el;if(el=SL.get(match[1])){gallery[i].content=el.innerHTML}else{SB.raise("Cannot find element with id "+match[1])}}else{SB.raise("Cannot find element id for inline content")}}}}if(r){gallery.splice(i,1);if(i<current){--current}else{if(i==current){current=i>0?current-1:i}}--i;len=gallery.length}}if(gallery.length){if(options.onOpen&&typeof options.onOpen=="function"){options.onOpen(obj)}if(!activated){setDimensions(options.initialHeight,options.initialWidth);adjustHeight(dims.inner_h,dims.top,false);adjustWidth(dims.width,false);toggleVisible(loadContent)}else{loadContent()}activated=true}};Shadowbox.change=function(num){if(!gallery){return }if(!gallery[num]){if(!options.continuous){return }else{num=num<0?(gallery.length-1):0}}if(typeof slide_timer=="number"){clearTimeout(slide_timer);slide_timer=null;slide_delay=slide_start=0}current=num;if(options.onChange&&typeof options.onChange=="function"){options.onChange(gallery[current])}loadContent()};Shadowbox.next=function(){this.change(current+1)};Shadowbox.previous=function(){this.change(current-1)};Shadowbox.play=function(){if(!hasNext()){return }if(!slide_delay){slide_delay=options.slideshowDelay*1000}if(slide_delay){slide_start=new Date().getTime();slide_timer=setTimeout(function(){slide_delay=slide_start=0;SB.next()},slide_delay);toggleNav("play",false);toggleNav("pause",true)}};Shadowbox.pause=function(){if(typeof slide_timer=="number"){var time=new Date().getTime();slide_delay=Math.max(0,slide_delay-(time-slide_start));if(slide_delay){clearTimeout(slide_timer);slide_timer="paused"}toggleNav("pause",false);toggleNav("play",true)}};Shadowbox.close=function(){if(!activated){return }listenKeys(false);toggleVisible(false);if(content){content.remove();content=null}if(typeof slide_timer=="number"){clearTimeout(slide_timer)}slide_timer=null;slide_delay=0;if(options.onClose&&typeof options.onClose=="function"){options.onClose(gallery[current])}activated=false};Shadowbox.clearCache=function(){for(var i=0,len=cache.length;i<len;++i){if(cache[i].el){SL.removeEvent(cache[i].el,"click",handleClick);delete cache[i].el.shadowboxCacheKey}}cache=[]};Shadowbox.getPlugins=function(){return plugins};Shadowbox.getOptions=function(){return options};Shadowbox.getCurrent=function(){return gallery[current]};Shadowbox.getVersion=function(){return version};Shadowbox.getClient=function(){return client};Shadowbox.getContent=function(){return content};Shadowbox.getDimensions=function(){return dims};Shadowbox.raise=function(e){if(typeof options.handleException=="function"){options.handleException(e)}else{throw e}};Shadowbox.dynamicResize=function(w,h){if(content){content.width=w;content.height=h;resizeContent(function(){;});}}})();;
if(typeof Shadowbox=="undefined"){throw"Unable to load Shadowbox language file, base library not found."}Shadowbox.LANG={code:"en",of:"of",loading:"loading",cancel:"Cancel",next:"Next",previous:"Previous",play:"Play",pause:"Pause",close:"Close",errors:{single:'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',shared:'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',either:'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'}};
(function(){var F=Shadowbox;var L=F.lib;var A=F.getClient();var I;var M;var J="shadowbox_drag_layer";var K;var D=function(){I={x:0,y:0,start_x:null,start_y:null}};var E=function(N,O,C){if(N){D();var P=["position:absolute","height:"+O+"px","width:"+C+"px","cursor:"+(A.isGecko?"-moz-grab":"move"),"background-color:"+(A.isIE?"#fff;filter:alpha(opacity=0)":"transparent")];L.append(L.get("shadowbox_body_inner"),'<div id="'+J+'" style="'+P.join(";")+'"></div>');L.addEvent(L.get(J),"mousedown",H)}else{var Q=L.get(J);if(Q){L.removeEvent(Q,"mousedown",H);L.remove(Q)}}};var H=function(N){L.preventDefault(N);var C=L.getPageXY(N);I.start_x=C[0];I.start_y=C[1];M=L.get("shadowbox_content");L.addEvent(document,"mousemove",G);L.addEvent(document,"mouseup",B);if(A.isGecko){L.setStyle(L.get(J),"cursor","-moz-grabbing")}};var B=function(){L.removeEvent(document,"mousemove",G);L.removeEvent(document,"mouseup",B);if(A.isGecko){L.setStyle(L.get(J),"cursor","-moz-grab")}};var G=function(Q){var O=F.getContent();var R=F.getDimensions();var P=L.getPageXY(Q);var N=P[0]-I.start_x;I.start_x+=N;I.x=Math.max(Math.min(0,I.x+N),R.inner_w-O.width);L.setStyle(M,"left",I.x+"px");var C=P[1]-I.start_y;I.start_y+=C;I.y=Math.max(Math.min(0,I.y+C),R.inner_h-O.height);L.setStyle(M,"top",I.y+"px")};Shadowbox.img=function(O,N){this.id=O;this.obj=N;this.resizable=true;this.ready=false;var C=this;K=new Image();K.onload=function(){C.height=C.obj.height?parseInt(C.obj.height,10):K.height;C.width=C.obj.width?parseInt(C.obj.width,10):K.width;C.ready=true;K.onload="";K=null};K.src=N.content};Shadowbox.img.prototype={markup:function(C){return{tag:"img",id:this.id,height:C.resize_h,width:C.resize_w,src:this.obj.content,style:"position:absolute"}},onLoad:function(){var C=F.getDimensions();if(C.drag&&F.getOptions().handleOversize=="drag"){E(true,C.resize_h,C.resize_w)}},remove:function(){var C=L.get(this.id);if(C){L.remove(C)}E(false);if(K){K.onload="";K=null}}}})();
(function(){var A=Shadowbox;var B=A.lib;Shadowbox.html=function(D,C){this.id=D;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):300;this.width=this.obj.width?parseInt(this.obj.width,10):500};Shadowbox.html.prototype={markup:function(C){return{tag:"div",id:this.id,cls:"html",html:this.obj.content}},remove:function(){var C=B.get(this.id);if(C){B.remove(C)}}}})();
(function(){var A=Shadowbox;var B=A.lib;var D=A.getClient();Shadowbox.iframe=function(E,C){this.id=E;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):B.getViewportHeight();this.width=this.obj.width?parseInt(this.obj.width,10):B.getViewportWidth()};Shadowbox.iframe.prototype={markup:function(E){var C={tag:"iframe",id:this.id,name:this.id,height:"100%",width:"100%",frameborder:"0",marginwidth:"0",marginheight:"0",scrolling:"auto"};if(D.isIE){C.allowtransparency="true";if(!D.isIE7){C.src='javascript:false;document.write("");'}}return C},onLoad:function(){var C=(D.isIE)?B.get(this.id).contentWindow:window.frames[this.id];C.location=this.obj.content},remove:function(){var C=B.get(this.id);if(C){B.remove(C);if(D.isGecko){delete window.frames[this.id]}}}}})();
(function(){var A=Shadowbox;var B=A.lib;Shadowbox.swf=function(D,C){this.id=D;this.obj=C;this.resizable=true;this.height=this.obj.height?parseInt(this.obj.height,10):300;this.width=this.obj.width?parseInt(this.obj.width,10):300};Shadowbox.swf.prototype={markup:function(D){var C=A.getOptions().flashBgColor;return{tag:"object",id:this.id,name:this.id,type:"application/x-shockwave-flash",data:this.obj.content,children:[{tag:"param",name:"movie",value:this.obj.content},{tag:"param",name:"bgcolor",value:C}],height:D.resize_h,width:D.resize_w}},remove:function(){var C=B.get(this.id);if(C){B.remove(C)}}}})();
(function(){var A=Shadowbox;var B=A.lib;Shadowbox.flv=function(D,C){this.id=D;this.obj=C;this.resizable=true;this.height=this.obj.height?parseInt(this.obj.height,10):300;if(A.getOptions().showMovieControls==true){this.height+=20}this.width=this.obj.width?parseInt(this.obj.width,10):300};Shadowbox.flv.prototype={markup:function(G){var E=this.obj;var F=G.resize_h;var I=G.resize_w;var L=A.getOptions();var C=String(L.autoplayMovies);var J=L.showMovieControls;var H=String(J);var K=F-(J?20:0);var D=["file="+this.obj.content,"height="+F,"width="+I,"autostart="+C,"displayheight="+K,"showicons="+H,"backcolor=0x000000","frontcolor=0xCCCCCC","lightcolor=0x557722"];return{tag:"object",id:this.id,name:this.id,type:"application/x-shockwave-flash",data:L.flvPlayer,children:[{tag:"param",name:"movie",value:L.flvPlayer},{tag:"param",name:"flashvars",value:D.join("&amp;")},{tag:"param",name:"allowfullscreen",value:"true"}],height:F,width:I}},remove:function(){var C=B.get(this.id);if(C){B.remove(C)}}}})();
(function(){var A=Shadowbox;var B=A.lib;var D=A.getClient();Shadowbox.qt=function(E,C){this.id=E;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):300;if(A.getOptions().showMovieControls==true){this.height+=16}this.width=this.obj.width?parseInt(this.obj.width,10):300};Shadowbox.qt.prototype={markup:function(H){var F=A.getOptions();var G=String(F.autoplayMovies);var E=String(F.showMovieControls);var C={tag:"object",id:this.id,name:this.id,height:this.height,width:this.width,children:[{tag:"param",name:"src",value:this.obj.content},{tag:"param",name:"scale",value:"aspect"},{tag:"param",name:"controller",value:E},{tag:"param",name:"autoplay",value:G}],kioskmode:"true"};if(D.isIE){C.classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B";C.codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0"}else{C.type="video/quicktime";C.data=this.obj.content}return C},remove:function(){try{document[this.id].Stop()}catch(E){}var C=B.get(this.id);if(C){B.remove(C)}}}})();
(function(){var A=Shadowbox;var B=A.lib;var D=A.getClient();Shadowbox.wmp=function(E,C){this.id=E;this.obj=C;this.height=this.obj.height?parseInt(this.obj.height,10):300;if(A.getOptions().showMovieControls){this.height+=(D.isIE?70:45)}this.width=this.obj.width?parseInt(this.obj.width,10):300};Shadowbox.wmp.prototype={markup:function(H){var F=A.getOptions();var G=F.autoplayMovies?1:0;var E={tag:"object",id:this.id,name:this.id,height:this.height,width:this.width,children:[{tag:"param",name:"autostart",value:G}]};if(D.isIE){var C=F.showMovieControls?"full":"none";E.classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6";E.children[E.children.length]={tag:"param",name:"url",value:this.obj.content};E.children[E.children.length]={tag:"param",name:"uimode",value:C}}else{var C=F.showMovieControls?1:0;E.type="video/x-ms-wmv";E.data=this.obj.content;E.children[E.children.length]={tag:"param",name:"showcontrols",value:C}}return E},remove:function(){if(D.isIE){try{window[this.id].controls.stop();window[this.id].URL="non-existent.wmv";window[this.id]=function(){}}catch(E){}}var C=B.get(this.id);if(C){setTimeout(function(){B.remove(C)},10)}}}})();

/**
 * The "concept" theme markup for Shadowbox.
 *
 * This file is part of Shadowbox.
 *
 * @author      FrosT ]S[tudio Design - "Infernal" <FrosT@frost-haker.com>
 * @copyright   2000-2008 FrosT ][orporation
 * @license     http://www.frost-haker.com
 * @version     V.1.0.1 $
 */

if(typeof Shadowbox == 'undefined'){
    throw 'Unable to load Shadowbox skin, base library not found.';
}

/**
 * The HTML markup to use for Shadowbox.
 *
 * IMPORTANT: The script depends on most of these elements being present.
 *
 * @property    {Object}    SKIN
 * @public
 * @static
 */
Shadowbox.SKIN = {

    markup:     '<div id="shadowbox_container">' +
                    '<div id="shadowbox_overlay"></div>' +
                    '<div id="shadowbox">' +
                        '<div id="shadowbox_title">' +
                            '<div id="shadowbox_title_inner"></div>' +
                        '</div>' +
                        '<div id="shadowbox_body">' +
                            '<div id="shadowbox_body_inner"></div>' +
                            '<div id="shadowbox_loading">' +
                                '<div id="shadowbox_loading_indicator"></div>' +
                                '<span><a onclick="Shadowbox.close();">{cancel}</a></span>' +
                            '</div>' +
                        '</div>' +
						
						'<div id="shadowbox_nav_next_center" onclick="Shadowbox.next()"></div>' +
						'<div id="shadowbox_nav_previous_center" onclick="Shadowbox.previous()"></div>' +
						'<div id="shadowbox_nav_close_top" onclick="Shadowbox.close()"></div>' +
						
                        '<div id="shadowbox_info">' +
                            '<div id="shadowbox_info_inner">' +
                                '<div id="shadowbox_counter"></div>' +
                                '<div id="shadowbox_nav">' +
                                    '<a id="shadowbox_nav_close" title="{close}" onclick="Shadowbox.close()"></a>' +
                                    '<a id="shadowbox_nav_next" title="{next}" onclick="Shadowbox.next()"></a>' +
                                    '<a id="shadowbox_nav_play" title="{play}" onclick="Shadowbox.play()"></a>' +
                                    '<a id="shadowbox_nav_pause" title="{pause}" onclick="Shadowbox.pause()"></a>' +
                                    '<a id="shadowbox_nav_previous" title="{previous}" onclick="Shadowbox.previous()"></a>' +
                                    '<div id="shadowbox_nav_mobile">Swipe to navigate</div>' + 
                                '</div>' +
								         //'<div id="shadowbox_nav_mobile">Swipe to navigate</div>' +
                                '<div class="shadowbox_clear"></div>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>',

    png_fix:    [
        'shadowbox_nav_close',
        'shadowbox_nav_next',
        'shadowbox_nav_play',
        'shadowbox_nav_pause',
        'shadowbox_nav_previous'
    ]

};

/*! @vimeo/player v2.18.0 | (c) 2022 Vimeo | MIT License | https://github.com/vimeo/player.js */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e="undefined"!=typeof globalThis?globalThis:e||self).Vimeo=e.Vimeo||{},e.Vimeo.Player=t())}(this,function(){"use strict";function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var e="undefined"!=typeof global&&"[object global]"==={}.toString.call(global);function i(e,t){return 0===e.indexOf(t.toLowerCase())?e:"".concat(t.toLowerCase()).concat(e.substr(0,1).toUpperCase()).concat(e.substr(1))}function l(e){return/^(https?:)?\/\/((player|www)\.)?vimeo\.com(?=$|\/)/.test(e)}function c(e){return/^https:\/\/player\.vimeo\.com\/video\/\d+/.test(e)}function s(e){var t,n=0<arguments.length&&void 0!==e?e:{},r=n.id,o=n.url,i=r||o;if(!i)throw new Error("An id or url must be passed, either in an options object or as a data-vimeo-id or data-vimeo-url attribute.");if(t=i,!isNaN(parseFloat(t))&&isFinite(t)&&Math.floor(t)==t)return"https://vimeo.com/".concat(i);if(l(i))return i.replace("http:","https:");if(r)throw new TypeError("“".concat(r,"” is not a valid video id."));throw new TypeError("“".concat(i,"” is not a vimeo.com url."))}var t=void 0!==Array.prototype.indexOf,n="undefined"!=typeof window&&void 0!==window.postMessage;if(!(e||t&&n))throw new Error("Sorry, the Vimeo Player API is not available in this browser.");var o,a,u,f,d="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function h(){if(void 0===this)throw new TypeError("Constructor WeakMap requires 'new'");if(f(this,"_id","_WeakMap_"+m()+"."+m()),0<arguments.length)throw new TypeError("WeakMap iterable is not supported")}function v(e,t){if(!p(e)||!a.call(e,"_id"))throw new TypeError(t+" method called on incompatible receiver "+typeof e)}function m(){return Math.random().toString().substring(2)}function p(e){return Object(e)===e}(o="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:d).WeakMap||(a=Object.prototype.hasOwnProperty,u=Object.defineProperty&&function(){try{return 1===Object.defineProperty({},"x",{value:1}).x}catch(e){}}(),f=function(e,t,n){u?Object.defineProperty(e,t,{configurable:!0,writable:!0,value:n}):e[t]=n},o.WeakMap=(f(h.prototype,"delete",function(e){if(v(this,"delete"),!p(e))return!1;var t=e[this._id];return!(!t||t[0]!==e)&&(delete e[this._id],!0)}),f(h.prototype,"get",function(e){if(v(this,"get"),p(e)){var t=e[this._id];return t&&t[0]===e?t[1]:void 0}}),f(h.prototype,"has",function(e){if(v(this,"has"),!p(e))return!1;var t=e[this._id];return!(!t||t[0]!==e)}),f(h.prototype,"set",function(e,t){if(v(this,"set"),!p(e))throw new TypeError("Invalid value used as weak map key");var n=e[this._id];return n&&n[0]===e?n[1]=t:f(e,this._id,[e,t]),this}),f(h,"_polyfill",!0),h));var g,y=(function(e){var t,n,r;r=function(){var t,n,r,o,i,a,e=Object.prototype.toString,u="undefined"!=typeof setImmediate?function(e){return setImmediate(e)}:setTimeout;try{Object.defineProperty({},"x",{}),t=function(e,t,n,r){return Object.defineProperty(e,t,{value:n,writable:!0,configurable:!1!==r})}}catch(e){t=function(e,t,n){return e[t]=n,e}}function c(e,t){this.fn=e,this.self=t,this.next=void 0}function l(e,t){r.add(e,t),n=n||u(r.drain)}function s(e){var t,n=typeof e;return null==e||"object"!=n&&"function"!=n||(t=e.then),"function"==typeof t&&t}function f(){for(var e=0;e<this.chain.length;e++)!function(e,t,n){var r,o;try{!1===t?n.reject(e.msg):(r=!0===t?e.msg:t.call(void 0,e.msg))===n.promise?n.reject(TypeError("Promise-chain cycle")):(o=s(r))?o.call(r,n.resolve,n.reject):n.resolve(r)}catch(e){n.reject(e)}}(this,1===this.state?this.chain[e].success:this.chain[e].failure,this.chain[e]);this.chain.length=0}function d(e){var n,r=this;if(!r.triggered){r.triggered=!0,r.def&&(r=r.def);try{(n=s(e))?l(function(){var t=new m(r);try{n.call(e,function(){d.apply(t,arguments)},function(){h.apply(t,arguments)})}catch(e){h.call(t,e)}}):(r.msg=e,r.state=1,0<r.chain.length&&l(f,r))}catch(e){h.call(new m(r),e)}}}function h(e){var t=this;t.triggered||(t.triggered=!0,t.def&&(t=t.def),t.msg=e,t.state=2,0<t.chain.length&&l(f,t))}function v(e,n,r,o){for(var t=0;t<n.length;t++)!function(t){e.resolve(n[t]).then(function(e){r(t,e)},o)}(t)}function m(e){this.def=e,this.triggered=!1}function p(e){this.promise=e,this.state=0,this.triggered=!1,this.chain=[],this.msg=void 0}function g(e){if("function"!=typeof e)throw TypeError("Not a function");if(0!==this.__NPO__)throw TypeError("Not a promise");this.__NPO__=1;var r=new p(this);this.then=function(e,t){var n={success:"function"!=typeof e||e,failure:"function"==typeof t&&t};return n.promise=new this.constructor(function(e,t){if("function"!=typeof e||"function"!=typeof t)throw TypeError("Not a function");n.resolve=e,n.reject=t}),r.chain.push(n),0!==r.state&&l(f,r),n.promise},this.catch=function(e){return this.then(void 0,e)};try{e.call(void 0,function(e){d.call(r,e)},function(e){h.call(r,e)})}catch(e){h.call(r,e)}}var y=t({},"constructor",g,!(r={add:function(e,t){a=new c(e,t),i?i.next=a:o=a,i=a,a=void 0},drain:function(){var e=o;for(o=i=n=void 0;e;)e.fn.call(e.self),e=e.next}}));return t(g.prototype=y,"__NPO__",0,!1),t(g,"resolve",function(n){return n&&"object"==typeof n&&1===n.__NPO__?n:new this(function(e,t){if("function"!=typeof e||"function"!=typeof t)throw TypeError("Not a function");e(n)})}),t(g,"reject",function(n){return new this(function(e,t){if("function"!=typeof e||"function"!=typeof t)throw TypeError("Not a function");t(n)})}),t(g,"all",function(t){var a=this;return"[object Array]"!=e.call(t)?a.reject(TypeError("Not an array")):0===t.length?a.resolve([]):new a(function(n,e){if("function"!=typeof n||"function"!=typeof e)throw TypeError("Not a function");var r=t.length,o=Array(r),i=0;v(a,t,function(e,t){o[e]=t,++i===r&&n(o)},e)})}),t(g,"race",function(t){var r=this;return"[object Array]"!=e.call(t)?r.reject(TypeError("Not an array")):new r(function(n,e){if("function"!=typeof n||"function"!=typeof e)throw TypeError("Not a function");v(r,t,function(e,t){n(t)},e)})}),g},(n=d)[t="Promise"]=n[t]||r(),e.exports&&(e.exports=n[t])}(g={exports:{}}),g.exports),w=new WeakMap;function b(e,t,n){var r=w.get(e.element)||{};t in r||(r[t]=[]),r[t].push(n),w.set(e.element,r)}function k(e,t){return(w.get(e.element)||{})[t]||[]}function E(e,t,n){var r=w.get(e.element)||{};if(!r[t])return!0;if(!n)return r[t]=[],w.set(e.element,r),!0;var o=r[t].indexOf(n);return-1!==o&&r[t].splice(o,1),w.set(e.element,r),r[t]&&0===r[t].length}function T(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){return console.warn(e),{}}return e}function P(e,t,n){var r,o;e.element.contentWindow&&e.element.contentWindow.postMessage&&(r={method:t},void 0!==n&&(r.value=n),8<=(o=parseFloat(navigator.userAgent.toLowerCase().replace(/^.*msie (\d+).*$/,"$1")))&&o<10&&(r=JSON.stringify(r)),e.element.contentWindow.postMessage(r,e.origin))}function _(n,r){var t,e,o=[];(r=T(r)).event?("error"===r.event&&k(n,r.data.method).forEach(function(e){var t=new Error(r.data.message);t.name=r.data.name,e.reject(t),E(n,r.data.method,e)}),o=k(n,"event:".concat(r.event)),t=r.data):!r.method||(e=function(e,t){var n=k(e,t);if(n.length<1)return!1;var r=n.shift();return E(e,t,r),r}(n,r.method))&&(o.push(e),t=r.value),o.forEach(function(e){try{if("function"==typeof e)return void e.call(n,t);e.resolve(t)}catch(e){}})}var M=["autopause","autoplay","background","byline","color","controls","dnt","height","id","interactive_params","keyboard","loop","maxheight","maxwidth","muted","playsinline","portrait","responsive","speed","texttrack","title","transparent","url","width"];function N(r,e){var t=1<arguments.length&&void 0!==e?e:{};return M.reduce(function(e,t){var n=r.getAttribute("data-vimeo-".concat(t));return!n&&""!==n||(e[t]=""===n?1:n),e},t)}function F(e,t){var n=e.html;if(!t)throw new TypeError("An element must be provided");if(null!==t.getAttribute("data-vimeo-initialized"))return t.querySelector("iframe");var r=document.createElement("div");return r.innerHTML=n,t.appendChild(r.firstChild),t.setAttribute("data-vimeo-initialized","true"),t.querySelector("iframe")}function x(i,e,t){var a=1<arguments.length&&void 0!==e?e:{},u=2<arguments.length?t:void 0;return new Promise(function(t,n){if(!l(i))throw new TypeError("“".concat(i,"” is not a vimeo.com url."));var e="https://vimeo.com/api/oembed.json?url=".concat(encodeURIComponent(i));for(var r in a)a.hasOwnProperty(r)&&(e+="&".concat(r,"=").concat(encodeURIComponent(a[r])));var o=new("XDomainRequest"in window?XDomainRequest:XMLHttpRequest);o.open("GET",e,!0),o.onload=function(){if(404!==o.status)if(403!==o.status)try{var e=JSON.parse(o.responseText);if(403===e.domain_status_code)return F(e,u),void n(new Error("“".concat(i,"” is not embeddable.")));t(e)}catch(e){n(e)}else n(new Error("“".concat(i,"” is not embeddable.")));else n(new Error("“".concat(i,"” was not found.")))},o.onerror=function(){var e=o.status?" (".concat(o.status,")"):"";n(new Error("There was an error fetching the embed code from Vimeo".concat(e,".")))},o.send()})}var C,j,A,S=new WeakMap,q=new WeakMap,V={},Player=function(){function Player(u){var e,t,c=this,n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};if(!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,Player),window.jQuery&&u instanceof jQuery&&(1<u.length&&window.console&&console.warn&&console.warn("A jQuery object with multiple elements was passed, using the first element."),u=u[0]),"undefined"!=typeof document&&"string"==typeof u&&(u=document.getElementById(u)),e=u,!Boolean(e&&1===e.nodeType&&"nodeName"in e&&e.ownerDocument&&e.ownerDocument.defaultView))throw new TypeError("You must pass either a valid element or a valid id.");if("IFRAME"===u.nodeName||(t=u.querySelector("iframe"))&&(u=t),"IFRAME"===u.nodeName&&!l(u.getAttribute("src")||""))throw new Error("The player element passed isn’t a Vimeo embed.");if(S.has(u))return S.get(u);this._window=u.ownerDocument.defaultView,this.element=u,this.origin="*";var r,o=new y(function(i,a){var e;c._onMessage=function(e){if(l(e.origin)&&c.element.contentWindow===e.source){"*"===c.origin&&(c.origin=e.origin);var t=T(e.data);if(t&&"error"===t.event&&t.data&&"ready"===t.data.method){var n=new Error(t.data.message);return n.name=t.data.name,void a(n)}var r=t&&"ready"===t.event,o=t&&"ping"===t.method;if(r||o)return c.element.setAttribute("data-ready","true"),void i();_(c,t)}},c._window.addEventListener("message",c._onMessage),"IFRAME"!==c.element.nodeName&&x(s(e=N(u,n)),e,u).then(function(e){var t,n,r,o=F(e,u);return c.element=o,c._originalElement=u,t=u,n=o,r=w.get(t),w.set(n,r),w.delete(t),S.set(c.element,c),e}).catch(a)});return q.set(this,o),S.set(this.element,this),"IFRAME"===this.element.nodeName&&P(this,"ping"),V.isEnabled&&(r=function(){return V.exit()},this.fullscreenchangeHandler=function(){(V.isFullscreen?b:E)(c,"event:exitFullscreen",r),c.ready().then(function(){P(c,"fullscreenchange",V.isFullscreen)})},V.on("fullscreenchange",this.fullscreenchangeHandler)),this}var e,t,n;return e=Player,(t=[{key:"callMethod",value:function(n,e){var r=this,o=1<arguments.length&&void 0!==e?e:{};return new y(function(e,t){return r.ready().then(function(){b(r,n,{resolve:e,reject:t}),P(r,n,o)}).catch(t)})}},{key:"get",value:function(n){var r=this;return new y(function(e,t){return n=i(n,"get"),r.ready().then(function(){b(r,n,{resolve:e,reject:t}),P(r,n)}).catch(t)})}},{key:"set",value:function(n,r){var o=this;return new y(function(e,t){if(n=i(n,"set"),null==r)throw new TypeError("There must be a value to set.");return o.ready().then(function(){b(o,n,{resolve:e,reject:t}),P(o,n,r)}).catch(t)})}},{key:"on",value:function(e,t){if(!e)throw new TypeError("You must pass an event name.");if(!t)throw new TypeError("You must pass a callback function.");if("function"!=typeof t)throw new TypeError("The callback must be a function.");0===k(this,"event:".concat(e)).length&&this.callMethod("addEventListener",e).catch(function(){}),b(this,"event:".concat(e),t)}},{key:"off",value:function(e,t){if(!e)throw new TypeError("You must pass an event name.");if(t&&"function"!=typeof t)throw new TypeError("The callback must be a function.");E(this,"event:".concat(e),t)&&this.callMethod("removeEventListener",e).catch(function(e){})}},{key:"loadVideo",value:function(e){return this.callMethod("loadVideo",e)}},{key:"ready",value:function(){var e=q.get(this)||new y(function(e,t){t(new Error("Unknown player. Probably unloaded."))});return y.resolve(e)}},{key:"addCuePoint",value:function(e,t){var n=1<arguments.length&&void 0!==t?t:{};return this.callMethod("addCuePoint",{time:e,data:n})}},{key:"removeCuePoint",value:function(e){return this.callMethod("removeCuePoint",e)}},{key:"enableTextTrack",value:function(e,t){if(!e)throw new TypeError("You must pass a language.");return this.callMethod("enableTextTrack",{language:e,kind:t})}},{key:"disableTextTrack",value:function(){return this.callMethod("disableTextTrack")}},{key:"pause",value:function(){return this.callMethod("pause")}},{key:"play",value:function(){return this.callMethod("play")}},{key:"requestFullscreen",value:function(){return V.isEnabled?V.request(this.element):this.callMethod("requestFullscreen")}},{key:"exitFullscreen",value:function(){return V.isEnabled?V.exit():this.callMethod("exitFullscreen")}},{key:"getFullscreen",value:function(){return V.isEnabled?y.resolve(V.isFullscreen):this.get("fullscreen")}},{key:"requestPictureInPicture",value:function(){return this.callMethod("requestPictureInPicture")}},{key:"exitPictureInPicture",value:function(){return this.callMethod("exitPictureInPicture")}},{key:"getPictureInPicture",value:function(){return this.get("pictureInPicture")}},{key:"unload",value:function(){return this.callMethod("unload")}},{key:"destroy",value:function(){var n=this;return new y(function(e){var t;q.delete(n),S.delete(n.element),n._originalElement&&(S.delete(n._originalElement),n._originalElement.removeAttribute("data-vimeo-initialized")),n.element&&"IFRAME"===n.element.nodeName&&n.element.parentNode&&(n.element.parentNode.parentNode&&n._originalElement&&n._originalElement!==n.element.parentNode?n.element.parentNode.parentNode.removeChild(n.element.parentNode):n.element.parentNode.removeChild(n.element)),n.element&&"DIV"===n.element.nodeName&&n.element.parentNode&&(n.element.removeAttribute("data-vimeo-initialized"),(t=n.element.querySelector("iframe"))&&t.parentNode&&(t.parentNode.parentNode&&n._originalElement&&n._originalElement!==t.parentNode?t.parentNode.parentNode.removeChild(t.parentNode):t.parentNode.removeChild(t))),n._window.removeEventListener("message",n._onMessage),V.isEnabled&&V.off("fullscreenchange",n.fullscreenchangeHandler),e()})}},{key:"getAutopause",value:function(){return this.get("autopause")}},{key:"setAutopause",value:function(e){return this.set("autopause",e)}},{key:"getBuffered",value:function(){return this.get("buffered")}},{key:"getCameraProps",value:function(){return this.get("cameraProps")}},{key:"setCameraProps",value:function(e){return this.set("cameraProps",e)}},{key:"getChapters",value:function(){return this.get("chapters")}},{key:"getCurrentChapter",value:function(){return this.get("currentChapter")}},{key:"getColor",value:function(){return this.get("color")}},{key:"setColor",value:function(e){return this.set("color",e)}},{key:"getCuePoints",value:function(){return this.get("cuePoints")}},{key:"getCurrentTime",value:function(){return this.get("currentTime")}},{key:"setCurrentTime",value:function(e){return this.set("currentTime",e)}},{key:"getDuration",value:function(){return this.get("duration")}},{key:"getEnded",value:function(){return this.get("ended")}},{key:"getLoop",value:function(){return this.get("loop")}},{key:"setLoop",value:function(e){return this.set("loop",e)}},{key:"setMuted",value:function(e){return this.set("muted",e)}},{key:"getMuted",value:function(){return this.get("muted")}},{key:"getPaused",value:function(){return this.get("paused")}},{key:"getPlaybackRate",value:function(){return this.get("playbackRate")}},{key:"setPlaybackRate",value:function(e){return this.set("playbackRate",e)}},{key:"getPlayed",value:function(){return this.get("played")}},{key:"getQualities",value:function(){return this.get("qualities")}},{key:"getQuality",value:function(){return this.get("quality")}},{key:"setQuality",value:function(e){return this.set("quality",e)}},{key:"getSeekable",value:function(){return this.get("seekable")}},{key:"getSeeking",value:function(){return this.get("seeking")}},{key:"getTextTracks",value:function(){return this.get("textTracks")}},{key:"getVideoEmbedCode",value:function(){return this.get("videoEmbedCode")}},{key:"getVideoId",value:function(){return this.get("videoId")}},{key:"getVideoTitle",value:function(){return this.get("videoTitle")}},{key:"getVideoWidth",value:function(){return this.get("videoWidth")}},{key:"getVideoHeight",value:function(){return this.get("videoHeight")}},{key:"getVideoUrl",value:function(){return this.get("videoUrl")}},{key:"getVolume",value:function(){return this.get("volume")}},{key:"setVolume",value:function(e){return this.set("volume",e)}}])&&r(e.prototype,t),n&&r(e,n),Player}();return e||(C=function(){for(var e,t=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],n=0,r=t.length,o={};n<r;n++)if((e=t[n])&&e[1]in document){for(n=0;n<e.length;n++)o[t[0][n]]=e[n];return o}return!1}(),j={fullscreenchange:C.fullscreenchange,fullscreenerror:C.fullscreenerror},A={request:function(o){return new Promise(function(e,t){function n(){A.off("fullscreenchange",n),e()}A.on("fullscreenchange",n);var r=(o=o||document.documentElement)[C.requestFullscreen]();r instanceof Promise&&r.then(n).catch(t)})},exit:function(){return new Promise(function(t,e){var n,r;A.isFullscreen?(n=function e(){A.off("fullscreenchange",e),t()},A.on("fullscreenchange",n),(r=document[C.exitFullscreen]())instanceof Promise&&r.then(n).catch(e)):t()})},on:function(e,t){var n=j[e];n&&document.addEventListener(n,t)},off:function(e,t){var n=j[e];n&&document.removeEventListener(n,t)}},Object.defineProperties(A,{isFullscreen:{get:function(){return Boolean(document[C.fullscreenElement])}},element:{enumerable:!0,get:function(){return document[C.fullscreenElement]}},isEnabled:{enumerable:!0,get:function(){return Boolean(document[C.fullscreenEnabled])}}}),V=A,function(e){function n(e){"console"in window&&console.error&&console.error("There was an error creating an embed: ".concat(e))}var t=0<arguments.length&&void 0!==e?e:document;[].slice.call(t.querySelectorAll("[data-vimeo-id], [data-vimeo-url]")).forEach(function(t){try{if(null!==t.getAttribute("data-vimeo-defer"))return;var e=N(t);x(s(e),e,t).then(function(e){return F(e,t)}).catch(n)}catch(e){n(e)}})}(),function(e){var r=0<arguments.length&&void 0!==e?e:document;window.VimeoPlayerResizeEmbeds_||(window.VimeoPlayerResizeEmbeds_=!0,window.addEventListener("message",function(e){if(l(e.origin)&&e.data&&"spacechange"===e.data.event)for(var t=r.querySelectorAll("iframe"),n=0;n<t.length;n++)if(t[n].contentWindow===e.source){t[n].parentElement.style.paddingBottom="".concat(e.data.data[0].bottom,"px");break}}))}(),function(e){var a=0<arguments.length&&void 0!==e?e:document;window.VimeoSeoMetadataAppended||(window.VimeoSeoMetadataAppended=!0,window.addEventListener("message",function(e){if(l(e.origin)){var t=T(e.data);if(t&&"ready"===t.event)for(var n=a.querySelectorAll("iframe"),r=0;r<n.length;r++){var o=n[r],i=o.contentWindow===e.source;c(o.src)&&i&&new Player(o).callMethod("appendVideoMetadata",window.location.href)}}}))}(),function(e){var a,u=0<arguments.length&&void 0!==e?e:document;window.VimeoCheckedUrlTimeParam||(window.VimeoCheckedUrlTimeParam=!0,a=function(e){"console"in window&&console.error&&console.error("There was an error getting video Id: ".concat(e))},window.addEventListener("message",function(e){if(l(e.origin)){var t=T(e.data);if(t&&"ready"===t.event)for(var n=u.querySelectorAll("iframe"),r=0;r<n.length;r++){var o=n[r],i=o.contentWindow===e.source;c(o.src)&&i&&function(){var r=new Player(o);r.getVideoId().then(function(e){var t,n=new RegExp("[?&]vimeo_t_".concat(e,"=([^&#]*)")).exec(window.location.href);n&&n[1]&&(t=decodeURI(n[1]),r.setCurrentTime(t))}).catch(a)}()}}}))}()),Player});
//Find all video iframes
//var $allVideos = $("iframe[src^='http://player.vimeo.com'], iframe[src^='http://www.youtube.com']");
var $allVideoIframes = $("iframe[src*='player.vimeo.com'], iframe[src*='youtube.com'], iframe[src*='youtube-nocookie.com'], iframe[src*='media_embed.php'], iframe[src*='subsplash.com'], iframe[src*='facebook.com/plugins/video.php'], iframe[src*='wistia.net'], iframe[src*='boxcast.tv/view-embed']");

//Figure out and save aspect ratio for each video and update css maxwidth value
$allVideoIframes.each(function(){//console.log('found one, id: '+$(this).attr('id')+', width: '+$(this).width()+', height: '+$(this).height());
  //$(this).data('aspectRatio', this.height / this.width).css({maxWidth:'100%'});
  $(this).data('aspectRatio', $(this).height() / $(this).width()).css({maxWidth:'100%'});
});

function resizeAllVids(){//console.log('resize!');
  //Resize all videos according to their own aspect ratio
  $allVideoIframes.each(function(){
    var $el = $(this);
	//add 10px for control bar for media_embed.php videos (control bar is always 20px high)
	newHeight=(($el.width() * $el.data('aspectRatio'))+10); 
	$el.height(newHeight);
	//console.log('resize video id: '+$(this).attr('id')+' to new height: '+newHeight+' and actual height: '+$(this).height());
  });
}

//When the window is resized
$(window).on("resize",function(){resizeAllVids();});
$(document).ready(function(){resizeAllVids();}); //Kick off one resize to fix all videos on page load

//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].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
			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
var cmtBtnID=0;
function submitComments(data,step,table,cID,ckCaptcha,toggleInput){
	//alert('submit comments, step '+step);	
	switch(step){
		case 1:
			$("#subBtn"+cID).css('display','none');
			$("#subProcess"+cID).css('display','block');
			//test the captcha IF in use
			/*ReCaptcha v1
			if(ckCaptcha==1){
				ckVals={
					recaptcha_challenge_field:$("#captcha"+cID).contents().find("#recaptcha_challenge_field").val(),
					recaptcha_response_field:$("#captcha"+cID).contents().find("#recaptcha_response_field").val()
				};
				$.post("/_libs/recaptchack.php",ckVals,function(html){submitComments(html,2,table,cID,toggleInput);});
			}else{
				submitComments('valid',2,table,cID,toggleInput);
			}*/
			//ReCaptcha v2
			if(ckCaptcha==1 && $("#g-recaptcha-response").length>0 && $("#captchaDiv"+cID).css('display')!='none'){
				recaptchaResponse=grecaptcha.getResponse(); //alert(recaptchaResponse);
				if(recaptchaResponse==""){submitComments("Please complete the visual confirmation",2,table,cID,ckCaptcha,toggleInput);}
				else{$.post("/_libs/recaptcha_verify.php",{gresponse:recaptchaResponse},function(retData){submitComments(retData,2,table,cID,ckCaptcha,toggleInput);});}
				//else{$.post("/_composer/vendor/recaptcha-master/_recaptcha_verify.php",{gresponse:recaptchaResponse},function(retData){submitComments(retData,2,table,cID,toggleInput);});}
			}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();} //ReCaptcha v2 reset
				//$("#captcha"+cID)[0].contentWindow.location.reload(true); //ReCaptcha v1 reset
			}else{
				$.post("/_panels/admin/_comments_process.php",{uc:1,tbl:table,rID:cID,cDo:'post',em:$("#em"+cID).val(),nm:$("#nm"+cID).val(),cmt:$("#cmt"+cID).val(),ttl:$("#ttl"+cID).val()},function(retData){submitComments(retData,3,table,cID,ckCaptcha,toggleInput);});
			}
			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('');
				//$("#captcha"+cID)[0].contentWindow.location.reload(true); //ReCaptcha v1 reset
				if(ckCaptcha==1){grecaptcha.reset();} //ReCaptcha v2 reset
				if(toggleInput==1){toggleContDiv('ac'+cID,'ADD COMMENT','','CANCEL COMMENT','','',300,0);}
			}else{
				alert("Sorry, your comments could not be submitted. Please try again.");
			}
		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 waypointAnimations={};
var waypointAnimOffset='90%';

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

var bkgdVideoMobileShow=0; //whether or not to show background video on mobile
var bkgdVideoAnimDelayCustom=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 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 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(){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{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){//console.log('toggleOverlayDiv: '+overlayDiv+', freezePagePos: '+freezePagePos+', forceDisp: '+forceDisp+', overlayDivScrollTopSaved: '+overlayDivScrollTopSaved);
	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';
		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');
		}
		$("#"+overlayDiv).stop().fadeIn(overlayDivFadeSpeed,function(){
			$("body").addClass('overlay-div-open');
			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';
		//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(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(typeof forceClose=="undefined"){forceClose=0;}
   if(typeof pauseAnims!="undefined"){pauseAnims=0;}
   overlayDivFreezePos=0; //TLI
   //restart any inline (always playing) video as needed
   toggleBkgdVideoPlay('play');
   //alert(popType);
   popDivID='#'+popType+'PopDiv';
   //clear the hash from the URL
   if(window.location.hash!="" && noPgUpdate!=1){goPage(curURL+"#-");}
   //if this popup has the popDivOpened class, assume it needs to be shut down
   if($(popDivID).hasClass('popDivOpened')||forceClose){
      //remove the popDivOpened class
      $(popDivID).removeClass('popDivOpened');
      //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');//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 NOT updating URL bar
   if(typeof vertPos=="undefined"){vertPos=0;} 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; //reset popDivID so it can be reset next time through to prevent a continuous loop here
			$("#"+popType+"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');
   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
         if(popDivID.indexOf('ac')==-1 && typeof contentInitSetup == 'function'){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=0;} 
   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();}
	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');
      //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
	jqInit.siblings("."+navPfx+"-subtoggle").html(isOpening?'&ndash;':'+');
}

function scrollToNavAware(anchorID,animSpeed,addOffset,noInterrupt){
	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==2){ //play/pause check
		if($(".bkgd-video-slide-video").data('videoActive')==1){
			docScrollTop=$(document).scrollTop();
			viewHeightCut=($(window).height()-$("#header-push").height())/2;
			vidTop=$(".bkgd-video-slide").offset().top;
			vidHeight=$(".bkgd-video-slide").height();
			vidViewStart=parseInt(vidTop-viewHeightCut);
			vidViewStop=parseInt(vidTop+vidHeight-viewHeightCut);
			//console.log(docScrollTop+': '+vidViewStart+', '+vidViewStop+', '+viewHeightCut);
			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();
			}
		}
		return; //dont continue below if only a playpause check
	}
	//check for background videos which cannot play on mobile devices
	if(init || pageLayoutSizePrev!=pageLayoutSize){
		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(){
					myAminDelay=bkgdVideoAnimDelay-(Date.now()-pageAnimProps['bkgd-video-slide-preloader']); if(myAminDelay<0||$(".bkgd-video-slide-video").data('videoInit')==1){myAminDelay=0;}
					$(".bkgd-video-slide-bkgd").css({backgroundImage:"url('"+$(this).attr('src')+"')"}).delay(myAminDelay).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();
								$(".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={};//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
			}//console.log($(".bkgd-video-slide-video").attr('data-src'+(pageLayoutSize=='mobile'?'-mobile':'')));
			$(".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
			/*//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="";//"_gaq.push(['_trackEvent','outbound-article','http://pinterest.com']);";
				//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=1;
var autoScrollAnimSpeed=1200;
var autoScrollTimeoutWait=600;
var pageFadeColorizeBkgd=1;

//misc setup variables
//page setup/animation variables
var pageAnimLive='';
var pageAnimInitDone=0;

var lazyCustomLoad=1; //stop standard lazy load function in footer-standard.php from firing - setup here within the contentInitSetup instead
var mobileNavAdjustDivsActive=!mobileOrTabletDevice?1:0;

var autoScrollAnimSpeed=1200;
var autoScrollTimeoutWait=600;
var autoScrollPartialHeightPerc=.75; //any element smaller than this percentage of window height will scroll up to align with window bottom instead of top

var pageScrollAnimSpeed=1400;
var autoScrollClickedDivPos=0;

var bkgdVideoAnimDelayCustom=2000;

var slideTitleAnimInitDelay=500; //delay here give a bit of time for any image loading to complete prior to loading the corresponding text, when text is shown after a lazy-loaded image
var splitSlideDisplace=400;
var topSlideDisplace=220;//600;
var topSlideScrollSpeed=1000;
var buttonTxtCropTimeout=0;
var buttonTxtCropDelay=600; //make sure this is longer than the CSS animation duration for thumbnail resizing - currently 500ms

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

var gridAjaxLoadWaypoint=0;

var mobileNavForceShowDistance=1.1;
var mobileNavAnimResizeDistance=1.1;

var mobileNavAdjustDivs={}; //TLI/EFCB
var mobileNavAdjustDivsActive=0; //TLI/EFCB - set to 1 in site.js if active and needed
var mobileNavAdjustDivsSpeed=350; //make sure this matches the css header/mobile nav easing timing 

var gMapNativeWidth=typeof gMapNativeWidth!='undefined'?gMapNativeWidth:1024; //default to zoom level 2
var ajaxWaypoints={};
var waypointOffsets={};
var mobileFixedHeightDivs=[".flex-full-viewport",".flex-half-viewport-vert",".flex-half-viewport-mobile-vert > div.parallax-parent", ".flex-vert-center-content",".image-slides-content",".split-static-slides-inner",".split-static-slides-inner .split-static-slide",".top-slide-image"/*, ".flex-full-viewport > div.parallax-parent"*/];

//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).bind("focus",function(){$(this).addClass('usrval');});
		});
	}*/
}

//used in EFCB on-page nav tables - keeps nav from disappearing during autoscroll
function pgScroll(anchorID){
	autoScrollRun(anchorID,pageScrollAnimSpeed);
}

//function for HTML setup that runs on page load AND whenever ajax items are loaded
function contentInitSetup(parentEle){//console.log('contentInitSetup, parentEle: '+parentEle);
	//if(=='pgPopDiv')pgPopContentDiv
	//define the parent element if not provided
	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);
   pageFadeConfig(parentEle);//in shared2.js
   //custom layout class and extra element setup
   customLayoutSetup(parentEle);
	//call lazyLoader function
	lazyLoader(parentEle,'lazy-img'); //TLI has lazy-img used all over instead of just "lazy"
	//TLI/EFCB check if the footer should be fixed now that the content has been updated
	//fixedFooterCheck();
}

function customLayoutSetup(parentEle){
   //add IDs to any autoScrollDiv class containers that dont have an ID
	$(parentEle+".autoScrollDiv").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
	});
   //setup waypoint controlled element animation - exact animation setup in CSS
	$(parentEle+".item-animate .grid-item, "+parentEle+".item-animate .list-item").each(function(){
		if(!$(this).hasClass('waypoint-added')&&!$(this).hasClass('item-animated')){
			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
         tID=$(this).attr('id');
         waypointOffsets[tID]=pageLayoutSize=='mobile'?'100%':((!$(this).hasClass('slide-title-animate')&&!$(this).hasClass('animate-text-blocks'))?'90%':'35%'); 
			$(this).addClass('waypoint-added'); //console.log('add waypoint: '+tID);
         ajaxWaypoints[tID]=new Waypoint({
            element: $(this)[0], 
            handler: function(direction){ //this.destroy();
               $("#"+this.element.id).addClass('item-animated');
            },
            offset: waypointOffsets[tID]// '98%' //"bottom-in-view"//'95%'//
         });
      }
	}); //console.log(waypointOffsets);
   //EFCB dynamic next-arrow action - ON TLI next-arrow action is currently hardcoded in CMS pages
   //$(parentEle+".next-arrow").on('click',function(){autoScrollClickedDivPos=$(this).offset().top; autoScrollRun('next');});//track the location of the current next-arrow for use in determining which div to scroll to below
	//EFCB - allow registration links to function when laid over a parent div with its own detail page action
	$(parentEle+".item-link").on('click',function(event){event.stopPropagation();});
	//setup any progress meter animation waypoints
	$(parentEle+".progress-meter-container").each(function(){//console.log('meter ID: '+$(this).attr('id'));
		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
		tID=$(this).attr('id');
		ajaxWaypoints[tID]=new Waypoint({
			element: $(this)[0], 
			handler: function(direction){ this.destroy(); //console.log($(this)[0].element.className);
				raised=parseInt($("#"+this.element.id+ " .progress-meter-title > span:first-child").html().split(',').join('').substr(1));
				needed=parseInt($("#"+this.element.id+ " .progress-meter-title > span:last-child").html().split(',').join('').substr(1));
				raisedPerc=Math.ceil((raised/needed)*100);
				//console.log(raised+', '+needed+', '+raisedPerc+'%');
				$("#"+this.element.id+ " .progress-meter-bar-raised").animate({width:raisedPerc+'%'},1800,'easeInOutQuad');
				
			},
			offset: $(this).hasClass('progress-meter-detail')?'88%':'97%' //"bottom-in-view"//'95%'//
		});
	});
   $(parentEle+".credit-line").each(function(){
		thisHTML=$(this).html().split('/',2);
		if(thisHTML.length>1){$(this).html(thisHTML[0]+'<span>/</span><span>'+thisHTML[1]+'</span>');}
	});

   if(mobileOrTabletDevice){$(parentEle+".item-action").each(function(){$(this).on('click',function(){});});} //add empty onclick function to item-action container to invoke the :hover state on mobile devices
	
	if(parentEle.indexOf('PopContentDiv')!=-1 || parentEle.indexOf('PopDiv')!=-1){
		$(parentEle+".linkbar").each(function(){$(this).wrap('<div class="linkbar-wrapper"></div>');});
	}
   
	$(parentEle+"a.cssBtn1, "+parentEle+"a.cssBtn2, "+parentEle+"a.cssBtn3, "+parentEle+"a.cssBtn4, "+parentEle+"a.cssBtn5, "+parentEle+"a.cssBtnDead").each(function(){$(this).prepend('<div></div>').append('<div></div>');}); //add css btn rollover expansion divs 

	$(parentEle+".three-column-callouts > div").each(function(){
		$(this).data('click-target',$(this).attr('id').split('-')[1]);	
		$(this).on('click',function(){
			//jqueryScroll($(this).data('click-target'),1000);
         scrollToNavAware($(this).data('click-target'),1000,0);
		});
	});

	$(parentEle+".video-btn").each(function(){
		thisHTML=$(this).html().split('/',2);
		if(thisHTML.length>1){$(this).html(thisHTML[0]+'<span>/</span><span>'+thisHTML[1]+'</span>');}
		$(this).prepend('<div><div></div></div>');
	});

	$(parentEle+".next-arrow").each(function(){$(this).html('<div></div><div></div><div></div>');});
	$(parentEle+".linkbar > a, .journal-download > a").each(function(){$(this).append('<div></div><div></div>');});
	
	//layout updates that are only performed on the root page level, no parent element
	if(!parentEle && !isOverlay){
      //setup desktop nav submenu
      $('ul.sf-menu > li').not(".navDivider").each(function(){
         if($(this).children('ul').length>0){ 
            $(this).on('mouseenter',function(){ 
               $(this).addClass("li-subnav-open");
               $("#sidebar-flyout").addClass("sidebar-flyout-open");
               navSubLinkCt=0;
               $(this).children('ul').children('li').each(function(){
                  subnavID=$(this).attr('id');
                  parentID=$(this).parent().parent().attr('id');
                  animateSubnavItem(1,'show',subnavID,parentID,navSubLinkCt);
                  navSubLinkCt++;
               });
            });
            $(this).on('mouseleave',function(){ 
               $("#sidebar-flyout").removeClass("sidebar-flyout-open");
               $(this).removeClass("li-subnav-open");
               $(this).children('ul').children('li').each(function(){
                  $(this).css({zIndex:-1});
                  $(this).stop().animate({paddingLeft:20,opacity:0},250,'easeOutQuart');
               });
            });
         }
      });

      //ONLY allow the nav to have a fixed position IF the window is taller than the nav
      if(($("#sidebar-inner").height()+100)>$(window).height()){ 
         $("#sidebar").css({position:'absolute'});
         $("#sidebar-flyout").css({position:'absolute'});
      }
      $(".fixedContentScrollContainer").each(function(){$(this).prepend('<div class="fixedContentScrollSlug"></div>');});

      //populate text slideshows and setup next/previous buttons if needed 
      $(".text-slides, .image-slides").each(function(){
         tp=$(this).hasClass('text-slides')?'text':'image';								   
         //add first slide content if available
         if($(this).children('.'+tp+'-slides-storage').children('div').length>0){
            $(this).data('curSlide',1); $(this).data('slideCt',$(this).find('.'+tp+'-slides-storage > div').length); //console.log($(this).data('slideCt'));
            if(tp=='text'){
               $(this).children('.'+tp+'-slides-content').html($(this).find('.'+tp+'-slides-storage > div:nth-child(1)').html());
            }else if(tp=='image'){
               imgSrc=$(this).find('.'+tp+'-slides-storage > div:nth-child(1)').attr('data-src');
               $(this).children('.'+tp+'-slides-content').css('background-image','url('+imgSrc+')');
            }
            //if more than one slide is available, add navigation
            if($(this).data('slideCt')>1){
               $(this).prepend('<div class="slides-navbar"><div class="slides-ct">1 / '+$(this).data('slideCt')+'</div><div class="slides-nav"><div class="slides-prev"><div></div></div><div class="slides-next"><div></div></div></div></div>');
               $(this).find(".slides-prev").on('click',function(){slideshowMove('prev',tp,$(this).parent().parent().parent().attr('id'),1);});								 
               $(this).find(".slides-next").on('click',function(){slideshowMove('next',tp,$(this).parent().parent().parent().attr('id'),1);});
            }
         }
      });

      //add parallax via skrollr (skrollr init must come AFTER this html is added) - EFCB HAS A REWORKED VERSION OF THIS
      $pxIndex=0;
      $(".parallax-parent").each(function(){$pxIndex-=1;
         divBkgd=$(this).attr('data-bkgd')?$(this).attr('data-bkgd'):($(this).attr('data-bkgd-desktop')?$(this).attr('data-bkgd-desktop'):'');
         divBkgdMobile=$(this).attr('data-bkgd-mobile')?$(this).attr('data-bkgd-mobile'):divBkgd;
         $(this).prepend('<div class="parallax-div" style="z-index:'+$pxIndex+'"'+
         'data-1-bottom-top="display:!none;" '+
         'data-bottom-top="transform:translateY(35vh);height:100vh;display:!block;" '+
         'data-center-center="transform:translateY(0vh);height:100vh;" '+
         'data-1-top-bottom="transform:translateY(-35vh);height:35vh;display:!block;" '+
         'data-top-bottom="display:!none;" '+
         'data-anchor-target="#'+$(this).attr('id')+'"'+'>'+
         '<div'+(divBkgd?' class="lazy-parallax" data-src-desktop="'+divBkgd+'" data-src-mobile="'+divBkgdMobile:'')+'"></div>'+
         '<div data-bottom-top="height:65vh;" data-center-center="height:0vh;" data-anchor-target="#'+$(this).attr('id')+'"></div>'+ //top mask
         '</div>');
      });
   } //CLOSE setup that is root level ONLY (no parentEle)
	/* INPUT STYLING HANDLED BY input.js NOW
	$(parentEle+" select").each(function(){$(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(){$(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(){$(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>');}); 	
	*/
	//check if the footer should be fixed now that the content has been updated
	//fixedFooterCheck();
}

//function to update variables and layout on page init and viewport resize
function updatePageLayoutCustom(init){ //console.log('updatePageLayoutCustom, tabletDevice: '+tabletDevice+', mobileOrTabletDevice: '+mobileOrTabletDevice);
   //fix the height of the top image so it doesnt resize as mobile browser elements appear and disappear
   if(init && mobileOrTabletDevice){$(".top-slide-image").height($(".top-slide-image").height()+'px');}

	//add or remove limited viewport classes if needed
	$(".flex-half-viewport-mobile-vert, .flex-third-viewport-mobile-vert").each(function(){
		if(pageLimitedViewport==1 && !$(this).hasClass('landscape-viewport')){$(this).addClass('landscape-viewport');/*console.log('addedClass');*/}
		else if(pageLimitedViewport!=1 && $(this).hasClass('landscape-viewport')){$(this).removeClass('landscape-viewport');/*console.log('removedClass');*/}														 
	});
	//fix filter results if needed - may have a fixed height after filtering
	if($(".filter-records-results").length>0){$(".filter-records-results").css('height','');}
	//fix filter bar if needed
	if($(".filter-bar-selects").length>0 && $(".filter-bar-selects").css('display')!='block' && !window.matchMedia("(max-width:639px)").matches){
		$(".filter-bar-selects").css({'display':'','height':''});
	}
	if(headerActive && pageLayoutOrientChange && mobileFixedHeightDivs.length>0){
		for(i in mobileFixedHeightDivs){$(mobileFixedHeightDivs[i]).css('height','');}
	}
   //TLI ONLY
	//lazy load setup - http://jquery.eisbehr.de/lazy/ - setup parallaxLazyImgSrc here so we have layout info for possible switching
	parallaxLazyImgSrc='data-src-'+(pageLayout800?'mobile':'desktop');//pageLayoutSize; //determine which background image should be used for lazy loading - layout switches at 800px width
	if(init==1){ //initialize parallax div lazy loading on page init
		parallaxLazyInst=$('.lazy-parallax').lazy({
			chainable: false, 
			removeAttribute:false,
			//autoDestroy:false,
			attribute: parallaxLazyImgSrc,
			threshold: 400, //pixels below viewport at which images are loaded
			effect: 'fadeIn',
			effectTime: 600,
			afterLoad: function(element) {
				element.addClass('parallaxLazyLoadComplete'); 
			},
			//onFinishedAll: function(){console.log('ALL DONE'); parallaxLazyInst.destroy();},
			visibleOnly: false
		});
	}else{
		//update the lazy load source attribute to be used for not-yet-loaded images //console.log('parallaxLazyInst: '+typeof parallaxLazyInst);
		if(typeof parallaxLazyInst==='object'){
			parallaxLazyInst.config('attribute',parallaxLazyImgSrc); //console.log('getItems: '+(parallaxLazyInst.getItems().length)+', attribute: '+parallaxLazyInst.config('attribute'));
		}
		//now manually switch out background images if needed for any parallax divs that have already loaded
		$(".parallaxLazyLoadComplete").each(function(){ //console.log('load complete for: '+$(this).parent().parent().attr('id')+', '+$(this).css('background-image')+', '+$(this).attr(parallaxLazyImgSrc));
			if($(this).css('background-image').indexOf($(this).attr(parallaxLazyImgSrc))==-1){//console.log('swap image');
				$(this).css('background-image','url("'+$(this).attr(parallaxLazyImgSrc)+'")');
			}
		});
	}
    //END TLI ONLY
	//need to run mobileNavAdjustDivHeights each time through to populate the mobileNavAdjustDivs object for desktop and mobile use
	mobileNavAdjustDivHeights('resetAll','','',pageLayoutOrientChange);

   if(headerActive && pageLayoutOrientChange && mobileFixedHeightDivs.length>0){
		for(i in mobileFixedHeightDivs){
			$(mobileFixedHeightDivs[i]).each(function(){
            if(!headerActive || $(this).hasClass('mobile-full-height')){
               fixedHeight=$(window).height()-($(this).offset().top==headerFullHeight?headerFullHeight:headerSmallHeight);
               $(this).css({height:fixedHeight+'px'});
            }
            /* OLD TLI - STILL NEED TO USE THIS INSTEAD OF ABOVE CODE FROM EFCB??
            //using outerHeight value here - ASSUMING these divs are set to include any padding in total height value -> box-sizing: border-box;
				fixedHeight=$(this).hasClass('mobile-full-height')?$(window).height():$(this).outerHeight();
				//top divs have mobile-nav-full-height - on mobile Safari, the extra bottom browser bars will always appear, so adjust div height accordingly
				if(mobileSafari && $(this).hasClass('mobile-nav-full-height') && pageLayoutOrient=='portrait'){ //console.log('mobileSafari: '+mobileSafari);
					if($(this).hasClass('bkgd-video-slide')||$(this).parent().hasClass('top-slide')){fixedHeight-=74;}
					if($(this).parent().hasClass('top-slide')){
						$(".top-slide-intro .top-slide-title, .top-slide-intro .next-arrow").css('transform','translateY(-35px)');
						$(".top-slide-intro .video-btn").css('transform','translateY(-40px)');
					}
				}
				//apply the fixed div height
				$(this).css('height',fixedHeight+'px');*/
			});
		}
   }
   
	//adjust any indicated content divs to fill the viewport height accounting for the footer
	$(".fill-inner-height").each(function(){
		minHeight=$(window).height()-$("#footer").height()-(headerActive?$("#header-push").height():0);
		$(this).css('min-height',minHeight);
	});

	//resize text in fixed text boxes if needed - should come before before page animation
	fixedTextResize('',init); 
	//crop text if needed
	cropTextLines(init);
	//update any additional layout elements that are affected by both scroll and resize
	updateScrollAndResizeElements(); 
	//skrollr init setup is triggered by document ready call below
	if(!init){skrollrUpdate();} 
	//run any special page animations - TLI only
	pageAnimation();
	//set autoscroll if needed - scroll immediately to nearest div on init if page autoscroll is active - STILL NEEDED FOR TLI?
	//if(autoScrollActive==1){if(init==1){autoScrollToNearestDiv();}else{autoScrollTimeout();}}
	//check if the footer should be fixed - NOTE this does NOT need to run on page INIT as it is also called in the contentInitSetup() function 
	//if(init!=1){fixedFooterCheck();}
}

function updatePageScrollCustom(init){ //console.log('updatePageScroll');
	//TLI/EFCB update any additional layout elements that are affected by both scroll and resize
	updateScrollAndResizeElements();
}

function navBarUpdateCustom(forceDir,navOnly,init,navBarChanged){
   if(navBarChanged!=''){//console.log('navBarChanged: '+navBarChanged+', navOnly: '+navOnly);
      //only restrict nav bar animation if the display is changing - allow height changes as needed - if mobileNavNoToggle already==1, then another timeOut is still running already
      if((init || navBarChanged.indexOf('disp')!=-1) && mobileNavNoToggle!=1){mobileNavNoToggle=1; setTimeout(function(){mobileNavNoToggle=0;},mobileNavAdjustDivsSpeed+100);}
      //adjust div heights if not specifically adjusting navbar only
      if(navOnly!=1){mobileNavAdjustDivHeights('closest','divAndBelow',mobileNavAdjustDivsSpeed,pageLayoutOrientChange);}
   }
}

function autoScrollRunCustom(scrollToID,animSpeed,parentDiv){
   //TLI/EFCB also adjust the height of the current div if needed - adjustments to subsequent divs are handled by the mobile nav show/hide function
   if(headerActive==1){mobileNavAdjustDivHeights(scrollToID);}
}

//setup for TLI/EFCB
function mobileNavAdjustDivHeights(ckDivID,divAnim,animSpeed,forceUpdate){//console.log('mobileNavAdjustDivHeights, forceUpdate: '+forceUpdate);
   //console.log('mobileNavAdjustDivsActive: '+mobileNavAdjustDivsActive);
	if(mobileNavAdjustDivsActive!=1 && forceUpdate!=1){return;} 
	//reset adjusted div heights if any have been changed and recapture current native height of each div for the current viewport size
	if(typeof ckDivID=='undefined'||ckDivID==''){ckDivID='resetAll';}
	if(typeof divAnim=='undefined'||divAnim==''){divAnim='div';}
	if(typeof animSpeed=='undefined'||animSpeed==0){animSpeed=autoScrollAnimSpeed;}
	//create object of all adjustable divs and run initial adjustment if needed
	if(Object.keys(mobileNavAdjustDivs).length==0 || ckDivID=='resetAll'){
		$(".mobile-nav-adjust").each(function(){ 
			$(this).stop().css('height',''); //reset to css default value
			//DONT adjust 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).attr('id','id_'+Math.floor(Math.random() * 100001));} //Generate an element ID if needed
			if($(this).height()<=$(window).height()+($(window).height()/3)){
				//only capture and resize divs if NOT mobile in landscape
				mobileNavAdjustDivs[$(this).attr('id')]=$(this).outerHeight(); //capture current natural calculated height - including borders (outerHeight)
				if(headerActive==1 && ckDivID=='resetAll' && (pageLimitedViewport!=1 || !$(this).hasClass('mobile-landscape-natural-height')) && (pageLayout600!=1 || !$(this).hasClass('mobile-natural-height'))){ //if mobile nav is active and resetAll, set all divs to be the correct height WITH the nav visible by default
					//mobile-nav-full-height div will ALWAYS use the full mobile nav height
					heightAdjust=$(this).hasClass('mobile-nav-full-height')?headerFullHeight:(!mobileNavAdjustDivsActive||mobileOrTabletDevice?($(this).offset().top<=mobileNavAnimResizeOffset?headerFullHeight:headerSmallHeight):$("#header").outerHeight());
               //console.log('id: '+$(this).attr('id')+', heightAdjust: '+heightAdjust+', headerFullHeight: '+headerFullHeight+', headerSmallHeight: '+headerSmallHeight);
					//finally set the div height
					$(this).css('height',(mobileNavAdjustDivs[$(this).attr('id')]-heightAdjust)+'px');
				}
			}
		});
	}
	//if the header bar is visible and the current div has adjustable height - adjust here based on mobile nav visibility
	//NOTE - we NEVER run this if on a mobile device - div sizes are only changed on init and orientation change, 
   //console.log('mobileNavAdjustDivsActive: '+mobileNavAdjustDivsActive+', headerActive: '+headerActive+', keys: '+Object.keys(mobileNavAdjustDivs).length);
	if(mobileNavAdjustDivsActive==1 && headerActive==1 && Object.keys(mobileNavAdjustDivs).length>0/* && pageLimitedViewport!=1*/){ //console.log('headerActive, adjust div: '+ckDivID);
		if(ckDivID=='resetAll'||ckDivID=='closest'){divData=findClosestDiv();ckDivID=divData[0].id;} //console.log('ckDivID: '+ckDivID); //find the closest div if one was not provided
		if(mobileNavAdjustDivs[ckDivID]){ //continue only if a resize div was found - if the closest div is not be a resize div then we cannot run any extra resizing on above or below divs
			ckDivFound=0; divsAdjusted=0; //console.log('continue');
			for(curDivID in mobileNavAdjustDivs){ //cycle through available resize divs and resize as many as needed to fulfull the request
				if(curDivID==ckDivID){ckDivFound=1;isCkDiv=1;}else{isCkDiv=0;}//$("#devtxt").val($("#devtxt").val()+"\ncheck: "+curDivID);
				if($('#'+curDivID).hasClass('mobile-nav-full-height')){continue;} //never adjust mobile-nav-full-height div since it will always have the navbar at the top when visible - UNLESS we are changing the viewport size
				if(pageLimitedViewport==1 && $("#"+curDivID).hasClass('mobile-landscape-natural-height')){/*console.log('skip resize for: #'+curDivID);*/ continue;} //never adjust these divs if in mobile landscape mode
				if(pageLayout600==1 && $(this).hasClass('mobile-natural-height')){continue;}
				if($('#'+curDivID).height()>$(window).height()+($(window).height()/3)){continue;} //dont adjust divs that are taller than the current window height  (1.3x window height to accommodate possibly animating divs)
				//$("#devtxt").val($("#devtxt").val()+"\nid: "+curDivID+', fnd:'+ckDivFound+', isCk:'+isCkDiv);
				if(divAnim=='all' || (divAnim=='above' && isCkDiv!=1 && ckDivFound==0) || (divAnim=='divAndAbove' && (ckDivFound==0 || isCkDiv==1)) || (divAnim=='div' && isCkDiv==1) || (divAnim=='divAndBelow' && ckDivFound==1) || (divAnim=='below' && isCkDiv!=1 && ckDivFound==1)){
               heightAdjust=$('#'+curDivID).hasClass('mobile-nav-full-height')?headerFullHeight:(!mobileNavAdjustDivsActive||mobileOrTabletDevice?($(this).offset().top<=mobileNavAnimResizeOffset?headerFullHeight:headerSmallHeight):$("#header").outerHeight());
               //heightAdjust=$("#header").hasClass('header-hide')?0:$("#header").outerHeight();
               newDivHeight=mobileNavAdjustDivs[curDivID]-heightAdjust;  
					$('#'+curDivID).stop().animate({height:newDivHeight},animSpeed,'easeInOutQuad');
				}
			}
		}
	}
}

function cropTextLines(forceRun,parentEle){
	if(!forceRun){clearTimeout(buttonTxtCropTimeout); buttonTxtCropTimeout=setTimeout(function(){cropTextLines(1,parentEle);},buttonTxtCropDelay); return;}
	parentEle=typeof parentEle == 'undefined'?'':parentEle+' ';
	//crop video play buttons
	$(parentEle+".video-btn").each(function(){
		if(!$(this).data('orig')){$(this).data('orig',$(this).html());}
		$(this).html($(this).data('orig'));	
		refWidth=$(this).parent().width();//$(window).width()
		$(this).outerWidth('');
		//console.log(refWidth+' - '+$(this).outerWidth());
		if(refWidth<$(this).outerWidth()){
			$(this).html($(this).data('orig').split('<span')[0]); //if removing the clip length suffix did not shorten the button enough, begin truncating the title
			if(refWidth<$(this).outerWidth()){
				$(this).html($(this).html().split('&nbsp;').join(' ').split('&amp;').join('and')) //remove and ampersands and non-break spaces as well as any sub-spans
				reduceCharStr=$(this).html(); reduceCt=0;
				while($(this).html()!="" && refWidth<$(this).outerWidth()){
					reduceCt+=1;
					$(this).html(reduceCharStr.substring(0,reduceCharStr.length-reduceCt)+'&hellip;');
				}
				$(this).outerWidth(refWidth); //once the characters have been reduced sufficiently, set the video button to be the full width of the container, which will look better than leaving a sliver of space around it
			}
		}
	});
}

function updateScrollAndResizeElements(){ //called as the page is scrolled
	//if a top-slide or parallax-hero is being used, give the image a slight parallax effect
	if($(".top-slide").length>0||$(".parallax-hero").length>0){
		isTopSlide=$(".top-slide").length>0?1:0;
      headRef="#header-reference"+($("#header").hasClass('header-small')?'-small':'');
		addNavHeight=headerActive && !$("#header").hasClass('header-hide')?$(headRef).height():0;
		pxContainer=isTopSlide?".top-slide-intro":".parallax-hero-img";
		pHeight=$(pxContainer).parent().outerHeight()+addNavHeight;
		pHeightInner=$(pxContainer).parent().height();
		tsOffset=$('.top-slide-text').length>0?$('.top-slide-text').offset().top:pHeight;
		tsCover=$('.top-slide-text').length>0?$('.top-slide-text').offset().top-$('.top-slide-text').outerHeight():0;
		fullCoverRatio=1-(tsOffset-$(document).scrollTop())/pHeight;
		txtCoverRatio=$(document).scrollTop()/(pHeight-tsCover);
		if(fullCoverRatio<1){
			$(pxContainer).css('display','block');
			if(!mobileOrTabletDevice){// TRY THIS ON MOBILE - TOO JANKY?
				bkgdMove=fullCoverRatio*topSlideDisplace;
				if(isTopSlide){
					$(".top-slide-intro").height(pHeightInner-(tsOffset*$(document).scrollTop())/tsOffset);
					$(".top-slide-image").css({transform:'translateY(-'+bkgdMove+'px)'});
					if($(".top-slide-title").length>0){
						txtHeight=$(".top-slide-title").outerHeight()+50; //fetch txtHeight here AFTER setting display:block, otherwise no height will be found
						$(".top-slide-title").css({transform:'translateY(-'+((((tsOffset-tsCover)-txtHeight)*txtCoverRatio)-bkgdMove)+'px)'});
					}
				}else{
					if(pageLayout800){bkgdMove=bkgdMove/2;}
					$(pxContainer).css({top:addNavHeight,transform:'translateY(-'+bkgdMove+'px)'});
				}
				//console.log('tsOffset: '+tsOffset+', fullCoverRatio: '+fullCoverRatio+', txtCoverRatio: '+txtCoverRatio+', bkgdMove: '+bkgdMove+', txtHeight: '+txtHeight+', translateY: '+((txtCoverRatio*(tsOffset-txtHeight))-bkgdMove));
			}
		}else if(fullCoverRatio>=1){
			$(pxContainer).css('display','none');
		} 
	}

	// if any fixedContentScrollParent divs are in use, check for fixedContentScrollChild animation process
	$(".fixedContentScrollContainer").each(function(){
		scrollParent=$(this).find(".fixedContentScrollParent");
		scrollChild=$(this).find(".fixedContentScrollChild");
		scrollSlug=$(this).find(".fixedContentScrollSlug");
		parentFixed=scrollParent.css('position')=='fixed'?1:0;
		
		btmTrigger=($(this).offset().top+scrollParent.outerHeight())-$(window).height();
		btmTrigger2=($(this).offset().top+$(this).outerHeight())-$(window).height();
		btmTrigger3=$(this).offset().top+$(this).outerHeight();
		if($(document).scrollTop() >= btmTrigger){ //console.log('add'); //console.log($(document).scrollTop()+', '+btmTrigger);
			//update the scroll slug height to match the scroll parent height
			scrollSlug.height(scrollParent.outerHeight());
			scrollParent.addClass('scrollParentFixed');
			scrollSlug.addClass('scrollSlugVisible');
			//IF WE WANT THE PARENT TO SCROLL UP ONCE WE HIT THE BOTTOM OF THE CHILD CONTENT, UNCOMMENT THIS
			if(parentFixed && $(document).scrollTop() >= btmTrigger2 && $(document).scrollTop()<=scrollChild.offset().top){//console.log('trigger2');
				parentExposeFull=$(window).height()-scrollChild.outerHeight();
				if(parentExposeFull>0){
					parentExposeRemain=scrollChild.offset().top-$(document).scrollTop();
					parentExposeRatio=parentExposeRemain/parentExposeFull;
					scrollParent.css({opacity:parentExposeRatio});
					//console.log($(document).scrollTop()+', '+scrollChild.offset().top+', '+parentExposeRatio);
				}
			}else{
				//scrollParent.removeClass('scrollParentAbsolute');
				scrollParent.css({opacity:1});
			}
			//IF NOT USING THE CODE ABOVE TO HAVE PARENT RESUME SCROLLING, ADD CODE TO MAKE IS DISPLAY:NONE ONCE THE BOTTOM OF THE CONTAINER HITS THE TOP OF THE VIEWPORT
			if($(document).scrollTop() >= btmTrigger3){//console.log('trigger3');
				scrollParent.addClass('scrollParentHidden');
			}else{
				scrollParent.removeClass('scrollParentHidden');
			}
		}else{ //console.log('remove'); 
			scrollParent.removeClass('scrollParentFixed');
			scrollParent.removeClass('scrollParentHidden');
			scrollSlug.removeClass('scrollSlugVisible');
			scrollParent.css({opacity:1});
		}
	});
	//if a split-static-container is being used, transition elements from fixed to absolute positioning depending on scrolltop position
	//console.log($(".split-static-container .split-static-slides-inner").width()+' , '+$(window).width());
	if($(".split-static-container").length>0 && $(".split-static-container .split-static-slides-inner").width()<$(window).width()/*&& pageLayout800!=1*/){//console.log('test');
		contentHeight=$(".split-static-content").outerHeight()+$(".split-static-content").offset().top;
		scrollHeight=$(document).scrollTop()+(mobileOrTabletDevice?window.innerHeight:$(window).height());
		displaceAmt=0;
		if(scrollHeight > contentHeight){
			$(".split-static-container .linkbar").addClass('linkbar-follow');
			$(".split-static-container .split-static-slides-inner").addClass('slides-follow');
			displaceAmt=((scrollHeight-contentHeight)/$(window).height())*splitSlideDisplace;
		}else{
			$(".split-static-container .linkbar").not(".linkbar-not-fixed").removeClass('linkbar-follow'); 
			$(".split-static-container .split-static-slides-inner").removeClass('slides-follow');
			if(scrollHeight < $(".split-static-content").offset().top){
				$(".split-static-container .split-static-slides-inner").css('display','none');
			}else if($(document).scrollTop() < $(".split-static-content").offset().top){//console.log('less than');
				$(".split-static-container .split-static-slides-inner").css('display','block');
				displaceAmt=(-(($(".split-static-content").offset().top-$(document).scrollTop())/$(".split-static-container .split-static-slides-inner").outerHeight())*splitSlideDisplace);
			}
		}
		//now calculate which static slide should be visible && adjust slide container div to give a slight parallax effect
		slideCt=$(".split-static-container .split-static-slide").length;
		if(slideCt>1){
			$(".split-static-container .split-static-slides-inner").css({bottom:displaceAmt}); //PARALLAX VIA BOTTOM CSS IF SHOWING MULTIPLE IMAGES IN THE SIDEBAR - VERTICAL SLIDESHOW STYLE
			curScrollPerc=$(document).scrollTop()/(contentHeight-$(window).height());
			for(i=1;i<=slideCt;i++){
				curSlidePerc=(i-1)*(1/slideCt); //console.log(i+', '+curScrollPerc+', '+curSlidePerc);
				slideRef=".split-static-slides-inner .split-static-slide:nth-child("+i+")"; //slideRef="#split-static-slide-"+i;
				if((pageLayout800!=1 && curScrollPerc>=curSlidePerc) || (pageLayout800==1 && i==1)){$(slideRef).addClass('slide-show');}
				else{$(slideRef).removeClass('slide-show');}
			}
		}else{
			displaceAmt=(-displaceAmt);
			$(".split-static-container .split-static-slides-inner").css({transform:'translateY('+displaceAmt+'px)','bottom':0}); //PARALLAX VIA TRANSFORM IF ONLY SHOWING A SINGLE IMAGE IN THE SIDEBAR - SMOOTHER ANIMATION
		}
	}
	//if on a page with an article nav bar, update the nav bar if needed - visible once 80px down the page, and change position depending on mobile nav visibility
	if($(".detail-nav").length>0){
		if(headerActive){$(".detail-nav").addClass('detail-nav-mobile');}else{$(".detail-nav").removeClass('detail-nav-mobile');}
		if($(document).scrollTop()>$(".detail-nav").outerHeight()+20){$(".detail-nav").addClass('detail-nav-visible');}else{$(".detail-nav").removeClass('detail-nav-visible');}
	}
	updateGoogleMap();
}

function slideshowMove(dir,tp,grp,step){ //console.log('slideshowMove, '+dir+', '+grp+', '+$(grp).data('curSlide')+', '+$(grp).data('slideCt'));
	if(grp.indexOf('#')==-1){grp='#'+grp;} //group ID shortcut
	if($(grp).data('slideCt')>1){
		if(typeof step=='undefined'){step=1;}
		locSlideAnimSpeed=(tp=='text'?300:400);
		grpContent=$(grp).children('.'+tp+'-slides-content');
		switch(step){
			case 1:
				if(dir=='next'){newSlide=$(grp).data('curSlide')>=$(grp).data('slideCt')?1:$(grp).data('curSlide')+1;}
				if(dir=='prev'){newSlide=$(grp).data('curSlide')<=1?$(grp).data('slideCt'):$(grp).data('curSlide')-1;}
				$(grp).data('curSlide',newSlide);
				//animate the slide change
				grpContent.stop().css({opacity:1,left:0}).animate({opacity:0,left:(dir=='prev'?15:-15)},locSlideAnimSpeed,function(){
					//once fade out is complete, switch in new slide content
					if(tp=='text'){
						grpContent.html($(grp).find('.'+tp+'-slides-storage > div:nth-child('+newSlide+')').html());
						//also resize the newly added text if the current text slides content div has the fixedSizeContent class
						if(grpContent.hasClass('fixedSizeContent')){fixedTextResize(grp+' > .'+tp+'-slides-content');}
						slideshowMove(dir,tp,grp,2);
					}else if(tp=='image'){
						//preload into image then continue when available
						imgSrc=$(grp).find('.'+tp+'-slides-storage > div:nth-child('+newSlide+')').attr('data-src');
						imgRef=$(grp).find('.'+tp+'-slides-storage > img');
						if($(imgRef).attr('src')==imgSrc){
							slideshowMove(dir,tp,grp,2);
						}else{
							$(imgRef).off('load').on('load',function(){slideshowMove(dir,tp,grp,2);}).attr('src',imgSrc);
						}
					}
				});
			break
			case 2:
				if(tp=='image'){
					grpContent.css('background-image','url('+$(grp).find('.'+tp+'-slides-storage > img').attr('src')+')');
					imgCropPos=$(grp).find('.'+tp+'-slides-storage > div:nth-child('+$(grp).data('curSlide')+')').css('background-position');
					grpContent.css('background-position',(imgCropPos=='0% 0%'?'50% 50%':imgCropPos));
					//console.log(imgCropPos+(imgCropPos=='50% 50%'));
				}
				//show new slide content
				grpContent.css({left:(dir=='prev'?-15:15)}).animate({opacity:1,left:0},locSlideAnimSpeed);
				//update the current slide indicator
				$(grp).find('.slides-ct').html($(grp).data('curSlide')+' / '+$(grp).data('slideCt'));
			break;
		}
	}
}

function giveAreaSelectPageNav(){
	giveTbl=$("#giveAreaSelect").val(); 
	pageFade('/give'+(giveTbl!=''?'?tbl='+encodeURIComponent(giveTbl):''));
}	

function toggleSelectFilters(){
	isOpening=$(".filter-bar-selects").css('display')=='block'?0:1;
	$(".filter-bar-selects").animate({opacity:(isOpening?'show':'hide'),height:(isOpening?'show':'hide')},400,'easeInOutQuad');
	$('a.filter-bar-toggle').html('&nbsp;'+(isOpening?'Hide':'')+' Filters&nbsp;');
}

//function to update the current thumbnail or list record set display - DIFFERENT FOR ECFB
function recSetUpdate(grp,act,step){
	if(typeof step=='undefined'){step=1;} //console.log('recSetUpdate, grp:'+grp+', act:'+act+', step:'+step);
	switch(step){
		case 1:
			$("."+grp+"-records .filter-records-results").css('height',$("."+grp+"-records .filter-records-results").height()); //fix height to avoid jumping during content loading
			$("."+grp+"-records .filter-records-loading").stop().css({display:'block',opacity:0}).animate({opacity:.9},200,function(){recSetUpdate(grp,act,2);});
		break;
		case 2:
			//un-instantiate any waypoints in the results
			for(i in ajaxWaypoints){ajaxWaypoints[i].destroy();} ajaxWaypoints={};
			//Waypoint.destroyAll();
			//update layout type indicators if requested
			if(act!='reset' && act!='filter'){
				$("#"+grp+"-grid, #"+grp+"-list").removeClass("filter-icon-live");
				$("#"+grp+"-"+act).addClass("filter-icon-live");
			}
			//capture current layout type
			tp=$("."+grp+"-records .filter-icon-live").length==0?'grid':$("."+grp+"-records .filter-icon-live").attr('id').split(grp+'-')[1];
			//setup recVars object to hold layout and filter values
			recVars={gGroup:grp,gType:tp};
			//add any filter selections to the recVars object 
			$(".filter-select, .filter-hidden").each(function(){
				if(act=='reset' && !$(this).hasClass('filter-hidden')){$(this).val('');}
				else{recVars[$(this).attr('id')]=$(this).val();} //console.log($(this).attr('id')+': '+recVars[$(this).attr('id')]);
			});
			//ajax call to retrieve record set results
			$.post("/content/widgets/grid-records.php",recVars,function(content){
				$("."+grp+"-records .filter-records-results").html(content); //console.log('content applied');												 	
				recSetUpdate(grp,act,3);
			});
		break;
		case 3:
			contentInitSetup("."+grp+"-records .filter-records-results");//fixedFooterCheck
			cropTextLines(1);
			//FIND HEIGHT DIFFERENCES
			fixd=$("."+grp+"-records .filter-records-results").height();
			$("."+grp+"-records .filter-records-results").css('height','');
			nat=$("."+grp+"-records .filter-records-results").height();
			if(nat<fixd && nat<$(window).height()/* && fixd>=$(window).height()*/){
				$("."+grp+"-records .filter-records-results").css('min-height',$(window).height());
			}
			//NOTE - we are not animating this change because it seems the height data we get is not entirely accurate
			//console.log('ease from: '+fixd+', to: '+nat);
			$("."+grp+"-records .filter-records-loading").stop().animate({opacity:0},200,function(){$(this).css({display:'none'});});
		break;
	}
}

function threeColScrollTrigger(scrollDest){
	 //jqueryScroll(scrollDest,1000);
    scrollToNavAware(scrollDest,1000,0);
}

function articleAuthorScroll(){//console.log('articleAuthorScroll');
	gotoScrollTop=$(".article-author-bio").offset().top-($(".detail-nav").outerHeight()+20);
	$.scrollTo(gotoScrollTop,1000,{easing:'easeInOutQuart'/*,interrupt:(mobileOrTabletDevice?false:true)*/});
}

function slideTitleAnim(slideTitleEle,slideTitleInitDelay){ //console.log('slideTitleAnim, slideTitleEle: '+slideTitleEle);
	//run slide title animation - NOTE if the current slideTitleEle object has any children with the slide-title-animate OR lazy-title-animate class, don't proceed - this avoids accidental double animation - NEEDED??
	if($(slideTitleEle).length>0 && !$(slideTitleEle).hasClass('title-animated')/* && $(slideTitleEle).find('.slide-title-animate').length==0 && $(slideTitleEle).find('.lazy-title-animate').length==0*/){ 
		$(slideTitleEle).addClass('title-animated');
		animDelay=slideTitleInitDelay?(slideTitleInitDelay>1?slideTitleInitDelay:slideTitleAnimInitDelay):1; //console.log('continue!');
		cks=['h3','h1','h2','h4'];
		for(ck in cks){
			if($(slideTitleEle+' '+cks[ck]).length>0){
				animDelay=(textAnim(slideTitleEle+" "+cks[ck],'line',animDelay));
				animDelay+=pageAnimProps.animFast;
			}
		}
		if($(slideTitleEle+" p").length>0||$(slideTitleEle+" ul").length>0||$(slideTitleEle+" ol").length>0){
			$(slideTitleEle+" p, "+slideTitleEle+" ul, "+slideTitleEle+" ol").delay(animDelay).animate({opacity:1},pageAnimProps.animFast); animDelay+=pageAnimProps.animFast;
		}
		$(slideTitleEle+" .slide-nav, "+slideTitleEle+" .next-arrow, "+slideTitleEle+" .video-btn").delay(animDelay).animate({opacity:1},pageAnimProps.animFast); animDelay+=pageAnimProps.animFast;
		//setTimeout(function(){$(slideTitleEle+" .animate-item").addClass('item-animated-js-delay');},animDelay); //add a class here to run any css animation that has NO delay - assuming we are relying on JS for the delay
		$(slideTitleEle+" .animate-item").addClass('item-animated'); //add the standard item-animated class to any matching elements - any animation delay is handled via css
	}
}

//sidenav sub-link animation - 2 steps required to get subnavID and parentID not to change during initial setup each() loop 
function animateSubnavItem(step,dir,subnavID,parentID,navSubLinkCt){
	switch(step){
		case 1:
			setTimeout(function(){animateSubnavItem(2,'show',subnavID,parentID);},navSubLinkCt*100);
		break;
		case 2:
			if($("#"+parentID).hasClass("li-subnav-open")){
				$("#"+subnavID).css({zIndex:10});
				$("#"+subnavID).stop().animate({paddingLeft:0,opacity:1},700,'easeOutQuart');
			}
		break;
	}
}

//skrollrUpdate is called on page init via document ready, and also when page dimensions are updated via updatePageLayout - DIFFERENT FOR EFCB
function skrollrUpdate(){
	//set or destroy skrollr as needed - skip this for mobile devices or if skrollr is not active on the current page
	if(mobileOrTabletDevice!=1 && skrollrActive==1){ //the max-height and max-width values here should match those set in the media.css file for switching to mobile nav
		if(headerActive==1 && skrollrObj!=0){/*console.log('down');*/skrollr.init().destroy();skrollrObj=0;$(".parallax-div").each(function(){$(this).removeClass('parallax-active');});}
		else if(headerActive!=1 && skrollrObj==0){/*console.log('up');*/$(".parallax-div").each(function(){$(this).addClass('parallax-active');});skrollrObj = skrollr.init({smoothScrolling:false,forceHeight:false});}
	}
}

function pageAnimation(){//console.log('pageAnimation');
	pageAnimRun=0; 
   if(pageAnimLive!='mobile' && pageLayoutSize=='mobile'){pageAnimRun=1; pageAnimLive='mobile';}
   if(pageAnimLive!='desktop' && pageLayoutSize=='desktop'){pageAnimRun=1; pageAnimLive='desktop';}
   if(pageAnimRun==1){ //console.log('pageAnimRun');//run the animation for the live animation size
      animDelay=pageAnimProps.animDelay; //set initial convenience animation delay variable for use below
      switch(curPage){ //curPage should always be set in header-standard, route according to the page animations being used on the current page
         case 'home':
            if(pageAnimInitDone!=1){
               var home2waypoint = new Waypoint({
                  element: $("#home2")[0],
                  handler: function(direction){ this.destroy();
                  nmDelay=400;
                  nmStart=parseInt($("#home2Anim > span").html());
                  for(nm=nmStart;nm<85;nm++){
                     setTimeout(function(){
                        newNum=parseInt($("#home2Anim > span").html()); newNum+=1; $("#home2Anim > span").html(newNum);
                        perc=newNum/85; perc=((1-perc)/2)+perc; $("#home2Anim").css({'transform':'scale('+perc+','+perc+')',opacity:perc});
                        if(newNum==85){
                           $("#home2 p").animate({opacity:1},pageAnimProps.animFast);
                        }
                     },nmDelay);
                     nmDelay+=1+(nmDelay/90);
                  }
                  },
                  offset: '65%' //"bottom-in-view"//'95%'//
               });
            }
         break;
      } //close page specific animation switch
      //reset animDelay for incremental use below
      animDelay=pageAnimProps.animFast;
      //run standard INIT page animations
      if(pageAnimInitDone!=1){
         initWaypoints={};
         //setup any initial slide animation - there should only be ONE init-anim-container
         if($(".init-anim-container").length>0){slideTitleAnim(".init-anim-container");}
         //setup any slide-title animation waypoints
         $(".slide-title-container, .animate-text-blocks").not('.init-anim-container').each(function(){
            if(typeof $(this).attr('id')!='undefined'){ //console.log('waypoint ID: '+$(this).attr('id'));
               tID=$(this).attr('id');
               initWaypoints[tID]=new Waypoint({
                  element: $("#"+tID)[0], 
                  handler: function(direction){ this.destroy(); //console.log($(this)[0].element.className);
                     if($(this)[0].element.className.indexOf('slide-title-container')!=-1){
                        cks=['h3','h1']; hmSlideDelay=1;//pageAnimProps.animDelay
                        for(ck in cks){
                           hmSlideDelay=textAnim("#"+$(this)[0].element.id+" "+cks[ck],'line',hmSlideDelay);
                           hmSlideDelay+=pageAnimProps.animFast;
                        }
                        $("#"+$(this)[0].element.id+" p").delay(hmSlideDelay).animate({opacity:1},pageAnimProps.animFast);
                     }
                     if($(this)[0].element.className.indexOf('animate-text-blocks')!=-1){
                        $("#"+$(this)[0].element.id+" p").addClass('txtAnimated');
                        $("#"+$(this)[0].element.id+" .credit-line").delay(pageAnimProps.animSlow).queue(function(next){ 
                           $(this).addClass('txtAnimated');
                           next(); 
                        });
                     }
                  },
                  offset: (pageLayoutSize=='mobile'?'85%':'35%') //"bottom-in-view"//'95%'//
               });
            }
         });
      } //console.log('waypoints: '+Object.keys(initWaypoints).length);
   } //end pageAnimRun if/then
	//indicate that any initial page load animations are complete
	pageAnimInitDone=1; 
}

function topSlideScroll(step){
	//gotoScrollTop=step==1?($(".top-slide-text").offset().top+$(".top-slide-text").outerHeight())-(mobileOrTabletDevice?window.innerHeight:$(window).height()):$(".top-slide-follow").offset().top;
	//$.scrollTo(gotoScrollTop,topSlideScrollSpeed,{easing:'easeInOutQuart',onAfter:function(){}});
	if(step==1){
      $.scrollTo(($(".top-slide-text").offset().top+$(".top-slide-text").outerHeight())-(mobileOrTabletDevice?window.innerHeight:$(window).height()),topSlideScrollSpeed,{easing:'easeInOutQuart',onAfter:function(){}});
   }else{
      //autoScrollRun("top-slide-follow",topSlideScrollSpeed);
      scrollToNavAware(".top-slide-follow",topSlideScrollSpeed,0);
   }  
}

function updateGoogleMap(){
	//resize google map if needed - full width for this map is 1024px (zoom level 2)
	if($(".full-world-map #googleLocMap").length>0 && gMapNativeWidth>0){
		
		gMapCurWidth=$(".full-world-map #googleLocMap").width();
		gMapCurHeight=$(".full-world-map #googleLocMap").height();
		
		mapHeight=gMapNativeWidth*.68; //set centered map height crop to exclude antarctica, $gCenterLat=44; $gCenterLong=12;
		
		if(gMapCurZoom>2){ //if zoom is greater than 2, always use full-scale map
			$("#googleLocMapWrapper").addClass("googleLocWrapperNoPad");
			
			scaleRatio=1; 
			
			$(".full-world-map #googleLocMap").css({transform:'scale('+scaleRatio+')',left:0,top:0,width:'100%',height:'100%'});
		}else{
			$("#googleLocMapWrapper").removeClass("googleLocWrapperNoPad");
			
			scaleRatioH=$("#googleLocMapWrapper").width()/gMapNativeWidth;
			scaleRatioV=$("#googleLocMapWrapper").height()/mapHeight;
			scaleRatio=scaleRatioH<=scaleRatioV?scaleRatioH:scaleRatioV;
			if(scaleRatio>1){scaleRatio=1;} //dont allow the map to be larger than its native size
		
			scaledWidth=gMapNativeWidth*scaleRatio;
			leftAdjust=($("#googleLocMapWrapper").width()-scaledWidth)/2;
			
			scaledHeight=mapHeight*scaleRatio;
			topAdjust=($("#googleLocMapWrapper").height()-scaledHeight)/2;
			
			$(".full-world-map #googleLocMap").css({transform:'scale('+scaleRatio+')',left:leftAdjust,top:topAdjust,width:gMapNativeWidth,height:mapHeight});
		}
		
		if(typeof gLocMap.data != 'undefined'){
			//only allow rollovers if the map is at its native size, otherwise offsets get crazy
			gMapRollActive=scaleRatio==1?1:0; 
			//trigger internal map resize if enclosing div has changed sizes
			if(gMapCurWidth!=$(".full-world-map #googleLocMap").width() || gMapCurHeight!=$(".full-world-map #googleLocMap").height()){
				google.maps.event.trigger(gLocMap, 'resize'); //console.log('map div resize');
			}
			//reset map center at the base level zoom
			if(gMapCurZoom==2){
				gLocMap.setCenter(new google.maps.LatLng(gCenterLat,gCenterLong)); //console.log('re-center, gMapCurZoom: '+gMapCurZoom);
			}
		}
	}	
}

//document ready processes
$(document).ready(function() {
	if(typeof adminPanel!='undefined' && adminPanel==1){return;}
	if(typeof isOverlay=='undefined'){isOverlay=0;}
	if(isOverlay==0){ //only run these for non-overlay pages
		//initial content config - this may be called again on ajax loaded content
		contentInitSetup();
		//run the page init function
		updatePageLayout(1);
		//initial page scroll setup 
		updatePageScroll(1); 
		//inital autoscroll setup if used
		autoScrollInit(); 
		//TLC/EFCB - 12-29-20 skrollr init MUST happen during onload step to ensure all other HTML is in place, otherwise parallax images may be setup in bad positioning - especially in FireFox
		//$(window).on('load',function(){ //7-22-22 EFCB - SAFARI seems to sometimes NOT SEE .parallax-div DOM nodes below when reloading a page and using the on(load) jquery trigger
		skrollrUpdate();
	}//end overlay check
}); //end document ready processes

// user account variables and functions

var acctAjax=0;
var acctFocus="";
var acctOptBtn="";
var acctSendVals="";
var acctLoadingTimeout=0;

var openOptID="";

function acctShowOrderDetail(oID,altTitle){
	isOpening=toggleContDiv(oID,(altTitle?'':'-&nbsp; ')+'hide details','',(altTitle?'':'&#x203a;&nbsp; ')+'show details','','',250,0);
	sendEleID=isOpening==1?'id_'+oID:'';
	setTimeout(function(){updateAcctScroll(sendEleID);},300); //update the scroll area after open/close animation is complete
}

function acctShowRecurring(oID,oName){
	toggleContDiv(oID,'cancel '+oName+' modifications','','modify recurring '+oName,'','',250,0);
	setTimeout(function(){updateAcctScroll();},300); //update the scroll area after open/close animation is complete
}

function acctModifyRecurring(oID,oName,noAmtMod,act){
	if(act=='end'){
		confMsg="Please confirm you wish to END this recurring "+oName;
	}else{
		selVal=$("#rpFreq"+oID+" option:selected").text();	
		if(noAmtMod==1){
			confMsg="Please confirm your new "+oName+" frequency of \n* "+selVal+" *";
		}else{
			confMsg="Please confirm your new "+selVal+" "+oName+" of $"+$("#rpAmt"+oID).val();
		}
	}
	if(confirm(confMsg)==true){ //if confirmed, process the recurring update or cancellation
		$("#updateBtns"+oID).css('display','none');
		$("#updatingBtns"+oID).css('display','block');
		//ajax update for this recurring payment, then reload the orders section once the process is complete to update the data display
		modGetStr="rt=recurMod&rID="+oID+"&recurAct="+act+"&pmtFrequency="+$("#rpFreq"+oID).val()+"&pmtFreqTitle="+($("#rpFreqTitle"+oID).length>0?$("#rpFreqTitle"+oID).val():$("#rpFreq"+oID+" option:selected").text())+"&orderTotal="+$("#rpAmt"+oID).val()+"&p=1&ajax=1";
		$.get("/content/pages/account.php?"+modGetStr,{},function(html){
			retData=html.split('|');
			$("#acctAlertMsg").stop().css({'display':'none'}).html(retData[1]).animate({opacity:'show',height:'show'},250,'easeInOutQuad'); 
			openAcctOption('orders',1);
		});
	}
}

function wishListAction(wAct,itmID,itmOpt,wQty){
	itmOpt=itmOpt||""; //set default for itmOpt if not provided
	//wQty=wQty||1; //set default for wQty if not provided
	//check for itmOpt selection and alert the user if no option is selected
	if(itmOpt=="ckOpts"){itmOpt="";
		if($("#item_opt").length>0){if($("#item_opt").val()==''){alert("Please select a "+$("#itemOptsTitle").html()); $("#item_opt").focus(); return;}else{itmOpt=$("#item_opt").val();}}
	}
	if(wQty=='select'){wQty=$("#itmQtyAlertSelect_"+itmID).val();}
	//$.get("/content/pages/account.php?rt=wishList&rID="+itmID+"&rOpt="+itmOpt+"&act="+wAct+"&qty="+wQty+"&p=1&ajax=1",{},function(html){
	$.get("/content/pages/account.php",{rt:'wishList',rID:itmID,rOpt:itmOpt,act:wAct,qty:wQty,p:1,ajax:1},function(html){ //first update the account via ajax, then update the page & cart
		switch(wAct){
			case 'alert-from-item': showPopDiv('ac','','acct','wishList','upr',0); break;
			case 'alert-from-list': $("#wishListStatusBar").removeClass('acctStatusBar').addClass('acctStatusBarAlert').html('Email Alert Preferences Updated'); break;
			case 'add-to-cart': addToCart(itmID,itmOpt,1); break;
			case 'remove-from-list': openAcctOption('wishList',1); break;
			case 'add-from-cart': updateCart('remove',itmID,itmOpt);
			case 'add-from-item': showPopDiv('ac','','acct','wishList','upr',0); break;
		}
	});
}

function acctAjaxLogout(){ //NOTE - no need to update the acctActive variable, since we are reloading the page
	$.get("/content/pages/account.php?ajax=1&p=1&rt=logout",{},function(data){retData=data.split('|'); alert(retData[1]); top.location.href=top.location.pathname+top.location.search; /*window.location.reload(true);*/});
}

function acctLoadingAnim(animShow){//console.log('acctLoadingAnim, animShow: '+animShow);
	if(animShow){
		$("#acPopContentDiv").addClass('acPopContentLoading');
	}else{
		$("#acPopContentDiv").removeClass('acPopContentLoading');
	}
}

function openAcctOption(opt,noReset,args,step){ //console.log('openAcctOption, opt: '+opt+', noReset: '+noReset+', args: '+args+', step: '+step+', openOptID: '+openOptID);
	if(typeof args=='undefined'){args='';}
	if(typeof step=='undefined'){step=1;}
	switch(step){
		case 1:
			//if opening the pmtData account panel, and we're not under SSL, reload here
			if(opt=='pmtData' && liveSite==1 && httpsPg!=1){
				goURL=curURL.split('http').join('https')+(curURL.indexOf('?')==-1?'?':'&')+'https=1'+'#ac.0.acct.'+opt;
				//alert(goURL);
				window.top.location=goURL; return;
			}
			//skip the alert and sync if only a partial update
			if(noReset!=1){
				//reset alert message
				$("#acctAlertMsg").stop().animate({opacity:'hide',height:'hide'},250,'easeInOutQuad'); 
				//sync the signup and login email and password fields
				if(opt=='login'||opt=='signup'){
					$(opt=='signup'?"#signup_eAdd":"#login_eAdd").val($(opt=='signup'?"#login_eAdd":"#signup_eAdd").val());
					$(opt=='signup'?"#signup_pswd":"#login_pswd").val($(opt=='signup'?"#login_pswd":"#signup_pswd").val());
				}
			}
			//close all account control divs except current opt group
			openOptID="";
			$(".acctGroup").each(function(){
				if($(this).css('display')=='block'){openOptID=$(this).attr('id');}
				//$(this).css('display',(opt+'Group')==$(this).attr('id')?'block':'none');
			});
			if(!openOptID||openOptID==opt+"Group"){openAcctOption(opt,noReset,args,2);return;}
			//openOptHeight=$("#"+openOptID).height(); console.log('openOptHeight: '+openOptHeight);
			$("#"+openOptID).animate({'opacity':0},250,function(){openAcctOption(opt,noReset,args,2);});
		break;
		case 2:
			//show loading animation if taking too long to load
         clearTimeout(acctLoadingTimeout);
			acctLoadingTimeout=setTimeout(function(){acctLoadingAnim(1);},1000);
			//clear all form values & load new content
			jqueryFormReset('acctForm',1,0);
			$("#"+opt+"Group").load("/content/pages/account.php?ajax=1&rt="+opt+"&args="+args,function(){openAcctOption(opt,noReset,args,3);});
		break;
		case 3: //console.log('acPopScrollDiv min-height: '+$("#acPopScrollDiv").css('min-height')); //console.log('openAcctOption usractRLO: '+$("#usractRLO").val());
			clearTimeout(acctLoadingTimeout);
			acctLoadingAnim(0);
			if(typeof inputCustomStyle === 'function'){inputCustomStyle('#acPopDiv');} //update input styling if input.js is being used and inputCustomStyle() function is available
			//update account page title - found in newly loaded ajax data
			if($("#"+opt+"Title").length>0){$("#acctGroupTitle").html($("#"+opt+"Title").val());}
			//check for any init content config (setup for TLI)
			if(typeof contentInitSetup!='undefined'){contentInitSetup("#"+opt+"Group");}
			if(openOptID==opt+"Group"){openAcctOption(opt,noReset,args,4);return;}
			$("#"+opt+"Group").css({display:'block',opacity:0});
			startHeight=openOptID?$("#"+openOptID).height():0;
			endHeight=$("#"+opt+"Group").height();
			if(openOptID){$("#"+openOptID).css({display:'none',opacity:1});}
			optContainerMinHeight=parseInt($("#acPopScrollDiv").css('min-height'));
			//console.log('startHeight: '+startHeight+', endHeight: '+endHeight+', optContainerMinHeight: '+optContainerMinHeight);
			if(startHeight<optContainerMinHeight && endHeight<optContainerMinHeight){startHeight=endHeight;} //dont animate height if both start and end heights are already less than the container height
			$("#"+opt+"Group").height(startHeight).animate({opacity:1,height:endHeight},250,'easeInOutQuad',function(){
				if(openOptID){$("#"+openOptID).html('');} //remove HTML from previously open account section
				$("#"+opt+"Group").height('');
				openAcctOption(opt,noReset,args,4);
			});
		break;
		case 4://set input focus
			if(mobileOrTabletDevice!=1){
				switch(opt){
					case 'login': $("#login_eAdd").focus(); break;
					case "signup": $("#signup_firstName").focus(); break;
					case 'reminder': $("#reminder_eAdd").focus(); break;
					case 'profile': $("#profile_firstName").focus(); break;
					case 'corp': 
						if($("#corp_position").length>0){$("#corp_position").focus();}
						else if($("#corp_company").length>0){$("#corp_company").focus();} 
						else if($("#corp_website").length>0){$("#corp_website").focus();} 
						else if($("#corp_bPhone").length>0){$("#corp_bPhone").focus();} 
					break;
				}
			}	
			switch(opt){
				case 'fileDownload':
					$("#fileDownload_fileLink").attr('href',args);
				break;
				case 'pdfFormOutput':
					$("#pdfFormOutput_fileLink").attr('href',args);
				break;
			}
			//update the account logout button visibility if available
			if($("#acHeaderLogout").length>0){
				if("logout login signup reminder".indexOf(opt)==-1){$("#acHeaderLogout").addClass("acLogoutVisible");/*console.log('add');*/}
				else{$("#acHeaderLogout").removeClass("acLogoutVisible");/*console.log('remove');*/}
			}
			//updateAcctScroll(); //scroll & cufon refresh calls are made by the account.php script once the new content fully loaded
			//if(typeof inputCustomStyle === 'function'){inputCustomStyle('#acPopDiv');} //update input styling if input.js is being used and inputCustomStyle() function is available
         if(typeof openAcctOptionCustom === "function"){openAcctOptionCustom(opt,noReset,args,step);} //4-16-23 DBH - custom account option processing if requested
		break;
	}
}

function updateAcctScroll(scrollToID,doScroll){//console.log('updateAcctScroll');
	//if(doScroll!=1){setTimeout(function(){updateAcctScroll(scrollToID,1);},300);return;}
	//update the scroller to accomodate the current account content div if needed
	if(jScrollPaneUsed){
		if($("#acPopScrollDiv").length>0){
			var jScrollPaneObj=$("#acPopScrollDiv").jScrollPane({showArrows:false, animateScroll: true, animateDuration:220, hideFocus:true/*, animateEase:'easeOutQuad'*/});
		}
		//scroll to an anchor if requested 
		if(typeof scrollToID=='undefined' || scrollToID==''){//no scrolling
		}else{
			newTop=parseInt($("#"+scrollToID).position().top);
			var jScrollPaneAPI = jScrollPaneObj.data('jsp'); 
			jScrollPaneAPI.scrollTo(0, newTop); 
		}
	}else{//console.log($("#acPopDiv").offset().top+", "+$(window).scrollTop()+', '+($("#acPopDiv").offset().top-$(window).scrollTop())); //alert($("#acPopDiv").css('display'));
		topOffset=findStaticPopTop(); if(topOffset==0){topOffset=30;} //NOTE that findStaticPopTop() is found in the site.js file along with the other overlay setup functions
		//if overlay has a negative offset top value or is not visible, it may be init animating - so autoscroll based on provided values - 9-16-20
		if($("#acPopDiv").css('display')!='none' && $("#acPopDiv").css('opacity')>0 && $("#acPopDiv").offset().top>=0 && ($("#acPopDiv").offset().top-$(window).scrollTop())<(topOffset-10)){ //if there is LESS than topOffset-10 of space above the account overlay div, scroll up
			$.scrollTo(($("#acPopDiv").offset().top-topOffset),200,{easing:'easeInOutQuad'}); //console.log('scroll');
		}
	}
}

//5-3-23 added for DBH to inject custom handling of account errors for GA tracking
function processAcctOptionError(opt,msg,focus){//console.log('processAcctOptionError');
   alert(msg);
   if(focus){$(focus).focus();}
   if(typeof customProcessAcctOptionError === 'function'){customProcessAcctOptionError(opt,msg,focus);}
   return false;
}

function processAcctOption(opt,args){//console.log('processAcctOption - opt: '+opt+', args: '+args);
	if(typeof args=='undefined'){args='';}
	//reset alert message
	//$("#acctAlertMsg").stop().animate({opacity:'hide',height:'hide'},250,'easeInOutQuad'); 
	$("#acctAlertMsg").stop().animate({opacity:0},250,'easeInOutQuad'); 
	//process according to selected option
	acctSendVals=new Object();
	switch(opt){
      case 'logout':
         //no checks needed to logout
      break;
      case 'login':
         if($("#login_eAdd").val()==""){return processAcctOptionError(opt,"Please enter an email address","#login_eAdd");}else{acctSendVals['login_eAdd']=$("#login_eAdd").val();}
         if($("#login_pswd").val()==""){return processAcctOptionError(opt,"Please enter a password","#login_pswd");}else{acctSendVals['login_pswd']=$("#login_pswd").val();}
      break;
      case 'pwdReset':
         if($("#pwdReset_pswd").val()==""){return processAcctOptionError(opt,"Please enter a new password","#pwdReset_pswd");}
         if($("#pwdReset_pswd2").val()==""){return processAcctOptionError(opt,"Please re-enter your new password","#pwdReset_pswd2");}
         if($("#pwdReset_pswd").val()!=$("#pwdReset_pswd2").val()){return processAcctOptionError(opt,"Your new passwords do not match","#pwdReset_pswd");}
         if($("#pwdReset_saved").val()!="" && $("#pwdReset_saved").val()==$("#pwdReset_pswd").val()){return processAcctOptionError(opt,"You cannot reuse your old password","#pwdReset_pswd");}
         acctSendVals['pwdReset_pswd']=$("#pwdReset_pswd").val();
      break;
      case "signup":
         isCorp=$("#signup_company").length>0?1:0;
         if($("#signup_firstName").val()==""){return processAcctOptionError(opt,"Please enter your first name","#signup_firstName");}else{acctSendVals['signup_firstName']=$("#signup_firstName").val();}
         if($("#signup_lastName").val()==""){return processAcctOptionError(opt,"Please enter your last name","#signup_lastName");}else{acctSendVals['signup_lastName']=$("#signup_lastName").val();}
         if($("#signup_userName").length>0){
            if($("#signup_userName").val()==""){return processAcctOptionError(opt,"Please enter an account username","#signup_userName");}
            else if($("#signup_userName").val().length<7){return processAcctOptionError(opt,"Your username must be at least 7 characters","#signup_userName");}
            else{acctSendVals['signup_userName']=$("#signup_userName").val();}
         }
         if($("#signup_eAdd").val()==""){return processAcctOptionError(opt,"Please enter an email address","#signup_eAdd");}else{acctSendVals['signup_eAdd']=$("#signup_eAdd").val();}
         if($("#signup_company").length>0){if($("#signup_company").val()==""){return processAcctOptionError(opt,"Please enter your company name","#signup_company");}else{acctSendVals['signup_company']=$("#signup_company").val();}}
         if($("#signup_position").length>0){if($("#signup_position").val()==""){return processAcctOptionError(opt,"Please enter your position or title","#signup_position");}else{acctSendVals['signup_position']=$("#signup_position").val();}}
         if($("#signup_phone").length>0){if($("#signup_phone").val()==""){return processAcctOptionError(opt,"Please enter a phone number","#signup_phone");}else{acctSendVals['signup_phone']=$("#signup_phone").val();}}
         if($("#signup_phone_type").length>0){if($("#signup_phone_type").val()==""){return processAcctOptionError(opt,"Please select phone type","#signup_phone_type");}else{acctSendVals['signup_phone_type']=$("#signup_phone_type").val();}}
         if($("#signup_address").length>0){
            if($("#signup_address").val()==""){return processAcctOptionError(opt,"Please enter your"+(isCorp?" company":"")+" address","#signup_address");}
            else{acctSendVals['signup_address']=$("#signup_address").val()+($("#signup_address2").length>0&&$("#signup_address2").val()!=""?"\r\n"+$("#signup_address2").val():"");}
         }
         if($("#signup_city").length>0){if($("#signup_city").val()==""){return processAcctOptionError(opt,"Please enter your"+(isCorp?" company":"")+" city","#signup_city");}else{acctSendVals['signup_city']=$("#signup_city").val();}}
         if($("#signup_state").length>0){if($("#signup_state").val()==""){return processAcctOptionError(opt,"Please select your"+(isCorp?" company":"")+" state/province","#signup_state");}else{acctSendVals['signup_state']=$("#signup_state").val();}}
         if($("#signup_zip").length>0){if($("#signup_zip").val()==""){return processAcctOptionError(opt,"Please enter your"+(isCorp?" company":"")+" zip/postal code","#signup_zip");}else{acctSendVals['signup_zip']=$("#signup_zip").val();}}
         if($("#signup_country").length>0){if($("#signup_country").val()==""){return processAcctOptionError(opt,"Please select your"+(isCorp?" company":"")+" country","#signup_country");}else{acctSendVals['signup_country']=$("#signup_country").val();}}
         if($(".signup_custom").length>0){ //6-6-23 DBH - allow any number of custom inputs
            subOK=1;
            $(".signup_custom").each(function(){
               if(subOK!=0 && $(this).val()==""){subOK=0; return processAcctOptionError(opt,"Please complete all fields","#"+$(this).attr('id'));}else{acctSendVals[$(this).attr('id')]=$("#"+$(this).attr('id')).val();}
            });
            if(!subOK){return;}
         }
         if($("#signup_pswd").val()==""){return processAcctOptionError(opt,"Please enter a password","#signup_pswd");}else{acctSendVals['signup_pswd']=$("#signup_pswd").val();}
         if($("#signup_pswd2").val()==""){return processAcctOptionError(opt,"Please confirm your password","#signup_pswd2");}else{acctSendVals['signup_pswd2']=$("#signup_pswd2").val();}
         if($("#signup_pswd").val()!=$("#signup_pswd2").val()){return processAcctOptionError(opt,"Your passwords do not match","#signup_pswd");}
         if($("#signup_pswd").val().length<7){return processAcctOptionError(opt,"Your password must be at least 7 characters","#signup_pswd");}
         if($("#signup_howFoundUs").length>0){acctSendVals['signup_howFoundUs']=$("#signup_howFoundUs").val();}
         //process subscription selections using subscriptionOpts array if available
         if(typeof subscriptionOpts!='undefined'){
            for(i=0;i<subscriptionOpts.length;i++){
               if($("#signup_"+subscriptionOpts[i]).length>0){acctSendVals["signup_"+subscriptionOpts[i]]=$("#signup_"+subscriptionOpts[i]).prop('checked')==true?1:0;}
            }
         }else{
            if($("#signup_newsletter").length>0){acctSendVals['signup_newsletter']=$("#signup_newsletter").prop('checked')==true?1:0;}
            if($("#signup_blog").length>0){acctSendVals['signup_blog']=$("#signup_blog").prop('checked')==true?1:0;}
         }
         //exisitng customer radio btns
         if($("#signup_existingCustomer_yes").length>0 && $("#signup_existingCustomer_yes").prop('checked')==true){acctSendVals['signup_existingCustomer']='1';}
         if($("#signup_existingCustomer_no").length>0 && $("#signup_existingCustomer_no").prop('checked')==true){acctSendVals['signup_existingCustomer']='0';}
         //make sure an account type is selected, if available
         if($("#acctTypeSelectNew").length>0){
            if($("#acctTypeSelectNew").val()==""){return processAcctOptionError(opt,"Please select a membership level","#acctTypeSelectNew");}else{acctSendVals['acctTypeSelect']=$("#acctTypeSelectNew").val();}
         }
      break;
      case 'reminder':
         if($("#reminder_eAdd").val()==""){return processAcctOptionError(opt,"Please provide an account email address.","#reminder_eAdd");}else{acctSendVals['reminder_eAdd']=$("#reminder_eAdd").val();}
      break;
      case 'profile':
         if($("#profile_firstName").val()==""){return processAcctOptionError(opt,"Please enter your first name","#profile_firstName");}else{acctSendVals['profile_firstName']=$("#profile_firstName").val();}
         if($("#profile_lastName").val()==""){return processAcctOptionError(opt,"Please enter your last name","#profile_lastName");}else{acctSendVals['profile_lastName']=$("#profile_lastName").val();}
         if($("#profile_eAdd").val()==""){return processAcctOptionError(opt,"Please enter an email address","#profile_eAdd");}else{acctSendVals['profile_eAdd']=$("#profile_eAdd").val();}
         if($("#profile_eAdd_alt").length>0){acctSendVals['profile_eAdd_alt']=$("#profile_eAdd_alt").val();}
         if($("#profile_userName").length>0){
            if($("#profile_userName").val()==""){return processAcctOptionError(opt,"Please enter an account username","#profile_userName");}
            else if($("#profile_userName").val().length<7){return processAcctOptionError(opt,"Your username must be at least 7 characters","#profile_userName");}
            else{acctSendVals['profile_userName']=$("#profile_userName").val();}
         }
         if($("#profile_company").length>0){acctSendVals['profile_company']=$("#profile_company").val();}
         if($("#profile_position").length>0){acctSendVals['profile_position']=$("#profile_position").val();}
         if($("#profile_taxID").length>0){acctSendVals['profile_taxID']=$("#profile_taxID").val();}
         if($("#profile_phone").length>0){acctSendVals['profile_phone']=$("#profile_phone").val();}
         if($("#profile_phone_type").length>0){acctSendVals['profile_phone_type']=$("#profile_phone_type").val();}
         if($("#profile_altPhone").length>0){acctSendVals['profile_altPhone']=$("#profile_altPhone").val();}
         if($("#profile_altPhone_type").length>0){acctSendVals['profile_altPhone_type']=$("#profile_altPhone_type").val();}
         //if($("#profile_fax").length>0){acctSendVals['profile_fax']=$("#profile_fax").val();}
         if($("#profile_address").length>0){acctSendVals['profile_address']=$("#profile_address").val()+($("#profile_address2").length>0&&$("#profile_address2").val()!=""?"\r\n"+$("#profile_address2").val():"");}
         if($("#profile_city").length>0){acctSendVals['profile_city']=$("#profile_city").val();}
         if($("#profile_state").length>0){acctSendVals['profile_state']=$("#profile_state").val();}
         if($("#profile_zip").length>0){acctSendVals['profile_zip']=$("#profile_zip").val();}
         if($("#profile_country").length>0){acctSendVals['profile_country']=$("#profile_country").val();}
         if($(".profile_custom").length>0){ //6-6-23 DBH - allow any number of custom inputs
            subOK=1;
            $(".profile_custom").each(function(){
               if(subOK!=0 && $(this).val()==""){subOK=0; return processAcctOptionError(opt,"Please complete all fields","#"+$(this).attr('id'));}else{acctSendVals[$(this).attr('id')]=$("#"+$(this).attr('id')).val();}
            });
            if(!subOK){return;}
         }
         if($("#profile_pswd").val()==""){return processAcctOptionError(opt,"Please enter a password","#profile_pswd");}else{acctSendVals['profile_pswd']=$("#profile_pswd").val();}
         if($("#profile_pswd2").val()==""){return processAcctOptionError(opt,"Please confirm your password","#profile_pswd2");}else{acctSendVals['profile_pswd2']=$("#profile_pswd2").val();}
         if($("#profile_pswd").val()!=$("#profile_pswd2").val()){return processAcctOptionError(opt,"Your passwords do not match","#profile_pswd");}
         if($("#profile_pswd").val().length<7){return processAcctOptionError(opt,"Your password must be at least 7 characters","#profile_pswd");}
         if($("#profile_myimg_1").length>0){acctSendVals['profile_myimg_1']=$("#profile_myimg_1").val();}
         if($("#profile_memEmails").length>0){acctSendVals['profile_memEmails']=$("#profile_memEmails").prop('checked')==true?1:0;}
         
         if($("#profile_ASHA").length>0){acctSendVals['profile_ASHA']=$("#profile_ASHA").val();}
         if($("#profile_HPCSA").length>0){acctSendVals['profile_HPCSA']=$("#profile_HPCSA").val();}
         if($("#profile_AHNA").length>0){acctSendVals['profile_AHNA']=$("#profile_AHNA").val();}
         
         //process subscription selections using subscriptionOpts array if available
         if(typeof subscriptionOpts!='undefined'){
            for(i=0;i<subscriptionOpts.length;i++){
               if($("#profile_"+subscriptionOpts[i]).length>0){acctSendVals["profile_"+subscriptionOpts[i]]=$("#profile_"+subscriptionOpts[i]).prop('checked')==true?1:0;}
            }
         }else{
            if($("#profile_newsletter").length>0){acctSendVals['profile_newsletter']=$("#profile_newsletter").prop('checked')==true?1:0;}
            if($("#profile_blog").length>0){acctSendVals['profile_blog']=$("#profile_blog").prop('checked')==true?1:0;}
         }
      break;
      case 'corp':
         ckLst=new Array('company','position','website','bPhone','beAdd','bAddress','bAddress2','bCity','bState','bZip','bCountry','bio');
         for(i=0;i<ckLst.length;i++){
            if($("#corp_"+ckLst[i]).length>0){acctSendVals["corp_"+ckLst[i]]=$("#corp_"+ckLst[i]).val();}
         }
         if($("#corp_myimg_1").length>0){acctSendVals['corp_myimg_1']=$("#corp_myimg_1").val();}
         if($("#corp_directory").length>0){acctSendVals['corp_directory']=$("#corp_directory").prop('checked')==true?1:0;}
         if($("#corp_memEmails").length>0){acctSendVals['corp_memEmails']=$("#corp_memEmails").prop('checked')==true?1:0;}
      break;
      case 'pmtData':
         if($("#pmtData_pmtMethod").val()==""){return processAcctOptionError(opt,"Please select a payment method");}else{acctSendVals['pmtMethod']=$("#pmtData_pmtMethod").val();}
         //if simply deleting the current payment data, no need to check values below
         if(($("#pmtData_delete").length>0 && $("#pmtData_delete").prop('checked')==true) || ($("#pmtData_memAutoEnd").length>0 && $("#pmtData_memAutoEnd").prop('checked')==true)){ 
            if($("#pmtData_delete").length>0 && $("#pmtData_delete").prop('checked')==true){
               if(confirm("Are you sure you want to permanently delete this payment information?")==false){return false;}
               acctSendVals['pmtDelete']=1;
            }
            if($("#pmtData_memAutoEnd").length>0 && $("#pmtData_memAutoEnd").prop('checked')==true){
               if(confirm("Are you sure you want to cancel your subscription?")==false){return false;}
               acctSendVals['pmtMemAutoEnd']=1;
            }
         }else{
            switch($("#pmtData_pmtMethod").val()){
               case 'ppxpress':
                  top.location.href="https://paypal.com"; return false;
               break;
               case "cc":
                  if($("#pmtData_ccName").length>0){if($("#pmtData_ccName").val()==""){return processAcctOptionError(opt,"Please enter the name on your credit card","#pmtData_ccName");}else{acctSendVals['ccName']=$("#pmtData_ccName").val();}}
                  if($("#pmtData_ccNum").val()==""){return processAcctOptionError(opt,"Please enter your credit card number","#pmtData_ccNum");}
                  if($("#pmtData_ccType").val()==""){return processAcctOptionError(opt,"Please select your credit card type","#pmtData_ccType");}else{acctSendVals['ccType']=$("#pmtData_ccType").val();}
                  if($("#pmtData_ccExpM").val()==""){return processAcctOptionError(opt,"Please enter your credit card expiration month","#pmtData_ccExpM");}else{acctSendVals['ccExpM']=$("#pmtData_ccExpM").val();}
                  if($("#pmtData_ccExpY").val()==""){return processAcctOptionError(opt,"Please enter your credit card expiration year","#pmtData_ccExpY");}else{acctSendVals['ccExpY']=$("#pmtData_ccExpY").val();}
                  if($("#pmtData_ccCVV").length>0){if($("#pmtData_ccCVV").val()==""){return processAcctOptionError(opt,"Please enter your credit card CVV Code","#pmtData_ccCVV");}else{acctSendVals['ccCVV']=$("#pmtData_ccCVV").val();}}
                  if($("#pmtData_ccZip").length>0){if($("#pmtData_ccZip").val()==""){return processAcctOptionError(opt,"Please enter your billing zip code","#pmtData_ccZip");}else{acctSendVals['ccZip']=$("#pmtData_ccZip").val();}}
                  //remove any * or - characters from the credit card number before testing it
                  ccNum=$("#pmtData_ccNum").val().split('*').join('').split('-').join(''); badChars = ccNum.search("[^0-9]");
                  if(badChars>=0){return processAcctOptionError(opt,"please enter a numeric credit card number \n(no spaces)","#pmtData_ccNum");}else{acctSendVals['ccNum']=$("#pmtData_ccNum").val();}
               break;
               case "eft":
                  if($("#pmtData_eftAccount").val()==""){return processAcctOptionError(opt,"Please enter your bank account number","#pmtData_eftAccount");}
                  if($("#pmtData_eftAccount").val().indexOf('*')==-1 && $("#pmtData_eftAccount").val().search("[^0-9]")>=0){ //allow to pass if there are asterisks - assume we're keeping existing number
                     return processAcctOptionError(opt,"Please remove any dashes or spaces in your bank account number","#pmtData_eftAccount");}else{acctSendVals['eftAccount']=$("#pmtData_eftAccount").val();}
                  if($("#pmtData_eftRouting").val()==""){return processAcctOptionError(opt,"Please enter your bank routing number","#pmtData_eftRouting");}
                  if($("#pmtData_eftRouting").val().indexOf('*')==-1 && $("#pmtData_eftRouting").val().search("[^0-9]")>=0){ //allow to pass if there are asterisks - assume we're keeping existing number
                     return processAcctOptionError(opt,"Please remove any dashes or spaces in your bank routing number","#pmtData_eftRouting");}else{acctSendVals['eftRouting']=$("#pmtData_eftRouting").val();}
               break;
            }
         }
      break;
      case 'membership':
         //make sure an account type is selected, if available, or if provided as an argument
         memSel=args!=''?args:'def';
         //if a membership type select list is available, it must have a selection
         if($("#membership_typeSelect").length>0){
            if($("#membership_typeSelect").val()==""){return processAcctOptionError(opt,"Please select a membership level","#membership_typeSelect");}else{memSel=$("#membership_typeSelect").val();}
         }
         //update the account via ajax, then update the page
         $.get("/content/pages/account.php",{rt:opt,memTypeSelect:memSel,p:1,ajax:1},
            function(html){//console.log('post mem: '+html);return;
               goActCk=html.split('|'); goAct=goActCk[0]?goActCk[0]:'payment';
               if(goAct=='page'){top.location.href=goActCk[1];} //if a page is returned, redirect immediately (1-2-24 DBH)
               else{showPopDiv('ac','','acct',goAct,'upr',0);}
            }
         );
         return;
      break;
      case 'memCredOptSelect':
         //update the account via ajax, then update the page
         $.get("/content/pages/account.php",{rt:opt,useCred:args,p:1,ajax:1},
            function(html){
               goActCk=html.split('|'); goAct=goActCk[0]?goActCk[0]:'payment';
               showPopDiv('ac','','acct',goAct,'upr',0);
            }
         );
         return;
      break;
      case 'subscriptions':
         if(!args){alert('Please select a current subscripion record');return;}
         if(!$("#sbEndNow"+args).prop('checked') || confirm('Please confirm you wish to cancel this subscription')){
            $("#sbUpdateBtns"+args).css('display','none');
            $("#sbUpdatingBtns"+args).css('display','block');
            acctSendVals['subscriptions_recID']=args;
            acctSendVals['subscriptions_newFreq']=$("#sbEndNow"+args).prop('checked')?'end_':$("#sbFreq"+args).val();
         }
      break;
      case 'messages':
         if(!$("#messages_question").val()){return processAcctOptionError(opt,"Please enter a question.","#messages_question");}else{acctSendVals['messages_question']=$("#messages_question").val();}
      break;
      case 'workingGroups':
         acctSendVals['subscriptionIDs']="";
         if(subscriptionInputIDs.length>0){
            for(i=0;i<subscriptionInputIDs.length;i++){
               if($("#"+subscriptionInputIDs[i]).prop('checked')){acctSendVals['subscriptionIDs']+=(acctSendVals['subscriptionIDs']?"~":"")+subscriptionInputIDs[i];}
            }
         }
      break;
      case 'tripinfo':
         inpVals=new Array('arrival','departure','insurer','policy');
         for(ii=0;ii<inpVals.length;ii++){acctSendVals[inpVals[ii]]=$("#tripinfo_"+inpVals[ii]).val();}
         acctSendVals['formerRes']=$("#tripinfo_formerRes").prop('checked')==true?1:0;
         acctSendVals['weekPlus']=$("#tripinfo_weekPlus").prop('checked')==true?1:0;
         if($("#tripinfo_cscContactCk").prop('checked')==true&&$("#tripinfo_cscContact").val()==""){
            return processAcctOptionError(opt,"Please enter the name of the CSC employee you've been in contact with.","#tripinfo_cscContact");
         }
         acctSendVals['cscContact']=$("#tripinfo_cscContactCk").prop('checked')==true?$("#tripinfo_cscContact").val():"";
      break;
      case 'infopages':
         acctSendVals['rID']=$("#infopages_rID").val();
      break;
      case 'orderStatus':
         if($("#orderStatus_num").val()==""){return processAcctOptionError(opt,"Please enter an order number","#orderStatus_num");}else{acctSendVals['orderStatus_num']=$("#orderStatus_num").val();}
      break;
      case 'masClient':
         argVals=args.split('|');
         acctSendVals['masClientAction']=argVals[0]?argVals[0]:($("#masClient_action").length>0?$("#masClient_action").val():'');
         acctSendVals['masClientID']=argVals[1]?argVals[1]:($("#masClient_id").length>0?$("#masClient_id").val():'');
         if(acctSendVals['masClientAction']=='add'||acctSendVals['masClientAction']=='update'){
            if($("#masClient_firstName").val()==""){return processAcctOptionError(opt,"Please enter a first name","#masClient_firstName");}else{acctSendVals['masClientFirstName']=$("#masClient_firstName").val();}
            if($("#masClient_lastName").val()==""){return processAcctOptionError(opt,"Please enter a last name","#masClient_lastName");}else{acctSendVals['masClientLastName']=$("#masClient_lastName").val();}
            if($("#masClient_gender").val()==""){return processAcctOptionError(opt,"Please select a gender","#masClient_gender");}else{acctSendVals['masClientGender']=$("#masClient_gender").val();}
            if($("#masClient_dob").val()==""){return processAcctOptionError(opt,"Please enter a birthdate","#masClient_dob");}else{acctSendVals['masClientDob']=$("#masClient_dob").val();}
            if($("#masClient_photo").val()==""){return processAcctOptionError(opt,"Please upload a current photo","#masClient_photo");}else{acctSendVals['masClientPhoto']=$("#masClient_photo").val();}
            if($("#masClient_reloadpg").length>0){acctSendVals['masClientReloadPg']=$("#masClient_reloadpg").val();}
         }
      break;
      case 'masWaitList':
         if($("#masWaitList_regType").val()=='select'){return processAcctOptionError(opt,"Please select a registration type.","#masWaitList_regType");}else{acctSendVals['masWaitListRegType']=$("#masWaitList_regType").val();}
         if($("#masWaitList_eventID").val()==''){return processAcctOptionError(opt,"Unable to find event ID. Please try again.");}else{acctSendVals['masWaitListEventID']=$("#masWaitList_eventID").val();}
         if($("#masWaitList_phone").length>0){
            if($("#masWaitList_phone").val()==''){return processAcctOptionError(opt,"Please enter your phone number.");}else{acctSendVals['masWaitListPhone']=$("#masWaitList_phone").val();}
            if($("#masWaitList_phone_type").val()==''){return processAcctOptionError(opt,"Please select your phone type.");}else{acctSendVals['masWaitListPhoneType']=$("#masWaitList_phone_type").val();}
         }
         acctSendVals['masWaitListPrereqBypass']=$("#masWaitList_prereqBypass").val();
      break;
      case 'masAssessUpload':
         //DUE TO FILE UPLOAD, this must be processed differently using the FormData constructor and completely processed here
         acctSendVals = new FormData();
         if($("#asmt_date").val()==''){return processAcctOptionError(opt,"Please select an assessment date.");}else{acctSendVals.append('asmtDate',$("#asmt_date").val());}
         if($("#asmt_event").val()==''){return processAcctOptionError(opt,"Please select an event name.","#asmt_event");}else{acctSendVals.append('asmtEvent',$("#asmt_event").val());}
         if($("#asmt_event").val()=='offline'&&$("#asmt_eventOffline").val()==''){return processAcctOptionError(opt,"Please enter an 'Offline Event' title.","#asmt_eventOffline");}else{acctSendVals.append('asmtEventOffline',$("#asmt_eventOffline").val());}
         if($("#asmt_client").val()==''){return processAcctOptionError(opt,"Please enter a client name.","#asmt_client");}else{acctSendVals.append('asmtClient',$("#asmt_client").val());}
         /*if($("#asmt_gender").val()==''){return processAcctOptionError(opt,"Please enter the client gender.","#asmt_eAdd");}else{*/acctSendVals.append('asmtGender',$("#asmt_gender").val());//}
         /*if($("#asmt_dob").val()==''){return processAcctOptionError(opt,"Please enter the client date of birth.","#asmt_dob");}else{*/acctSendVals.append('asmtDOB',$("#asmt_dob").val());//}
         if($("#asmt_parent").val()==''){return processAcctOptionError(opt,"Please enter a parent or guardian name.","#asmt_parent");}else{acctSendVals.append('asmtParent',$("#asmt_parent").val());}
         /*if($("#asmt_eAdd").val()==''){return processAcctOptionError(opt,"Please enter a parent or guardian email.","#asmt_eAdd");}else{*/acctSendVals.append('asmtEmail',$("#asmt_eAdd").val());//}
         if($("#asmt_uploadType").val()==''){return processAcctOptionError(opt,"Please select a video source.","#asmt_uploadType");}else{acctSendVals.append('asmtUploadType',$("#asmt_uploadType").val());}
         if($("#asmt_uploadType").val()=='zoom'&&$("#asmt_zoomMtgID").val()==""){return processAcctOptionError(opt,"Please enter a Zoom meeting ID.",'#asmt_zoomMtgID');}else{acctSendVals.append('asmtZoomMtgID',$("#asmt_zoomMtgID").val());}
         if($("#asmt_uploadType").val()=='upload'&&$("#asmt_upload__new").val()==""){return processAcctOptionError(opt,"Please select a video file to upload.",'#asmt_upload__new');}else{acctSendVals.append('asmtUpload__new',$("#asmt_upload__new")[0].files[0]);}
         acctSendVals.append('ajax',1);
         acctSendVals.append('p',1);
         acctSendVals.append('rt',opt);
         //$.post("/content/pages/account.php",acctSendVals,function(data){alert(data);}); //using $.post generates an error
         acctOptBtn=$("#"+opt+"Btn").html(); $("#"+opt+"Btn").html('<div class="acctProcessingBtn">Processing...</div>');
         $.ajax({
            url: "/content/pages/account.php",
            type: 'POST',
            data: acctSendVals,
            success: function(data){
               retData=data.split('|'); 
               populateAlertMsg(retData[0],retData[1]);
               $("#"+opt+"Btn").html(acctOptBtn);
               if(retData[1]){ //reset upload form if success
                  $("#acctForm")[0].reset();
                  $("#asmt_dateDisp").html('');
                  $("#asmt_date").val('');
                  asmtUploadTypeSelect();
               }
            },
            cache: false,
            contentType: false,
            processData: false
        });
         return; //do not continue below for the assessment video upload system
      break;
		case 'whitelabel': //JSD
			acctSendVals['whiteLabelURL']=$("#whitelabel_url").val();
			acctSendVals['whiteLabelImg']=$("#whitelabel_img").val();
			acctSendVals['whiteLabelEml']=$("#whitelabel_email").val();
			acctSendVals['whiteLabelCats']="";
			if($("#whiteLabel_cats").val()=='select'){//alert('here');
				for(c=1;c<40;c++){
					if($("#ucat_"+c).length==0){break;}
					//alert($("#ucat_"+c).prop('checked'));
					if($("#ucat_"+c).prop('checked')==true){//alert($("#ucat_"+c).val());
						acctSendVals['whiteLabelCats']+=(acctSendVals['whiteLabelCats']?',':'')+$("#ucat_"+c).val();
						$("#ucat_"+c+"_subs").find(':checkbox').each(function(){
							if($(this).prop('checked')){
								acctSendVals['whiteLabelCats']+='|'+$(this).val();
							}
						});
					}
				}
			} //alert(acctSendVals['whiteLabelCats']);
			acctSendVals['whiteLabelProds']=$("#whitelabel_prods").val();
		break;
   }
	//if still here, set display, input and variable values and submit the form
	acctOptBtn=$("#"+opt+"Btn").html(); $("#"+opt+"Btn").html('<div class="acctProcessingBtn">Processing...</div>'); $("#p").val(1); $('#rt').val(opt);
	//5-3-23 DBH - check for a custom pre process script is meant to be run
   if(typeof customPreProcessAcctOption === 'function'){customPreProcessAcctOption(opt,args);}
   //process the account action via ajax if requested 
	if(acctAjax==1){
		//add action values to the accSendVals object for ajax submission
		acctSendVals['ajax']=1; acctSendVals['p']=1; acctSendVals['rt']=opt; acctSendVals['usractRLO']=$("#usractRLO").val(); //console.log('acctSendVals: ');console.log(acctSendVals);
		//NOTE that the acctSendVals object should be fully populated from above
		$.post("/content/pages/account.php",acctSendVals,
		function(data){//console.log('data: '+data+', opt: '+opt+', curURL: '+curURL);
         //console.log('processAcctOption return, usractRLO: '+$("#usractRLO").val());
			//parse returned data into an array
			retData=data.split('|'); 
			//if a custom post process script is meant to be run, process that here instead of standard post processing
			if(typeof customPostProcessAcctOption === 'function'){retData=customPostProcessAcctOption(1,opt,retData);if(retData[0]=="exit"){return;}}
			//if an href was returned, go immediately to that page
			if(retData[1]=='href'){
				if(retData[2].indexOf('file_download')!=-1){openAcctOption('fileDownload',1,retData[2]);} //show file download message since window will remain open
				else if(retData[2].indexOf('frmpdf')!=-1){openAcctOption('pdfFormOutput',1,retData[2]);} //show PDF output message since window will remain open
				else{hidePopDiv('ac',1);top.location=retData[2]=='reload'?curURL:retData[2];}
				return;
			}
			//if a login or logout was just processed, update the acctActive variable (in header-standard include)
			if((opt=='login'&&retData[0]!='login')||(opt=='signup'&&retData[0]!='signup'&&retData[0]!='acctPending')){acctActive=1;} if(opt=='logout'){acctActive=0;}//&&retData[2]=='1'
			 //console.log('data: '+data+', opt: '+opt+', retData[0]: '+retData[0]+', acctActive: '+acctActive);
			//update the cart quantity count if needed - similar code exists in the estore content script, which runs when an item is added to the cart via the store
			if(opt=='login'&&data.indexOf('placed back into your cart')!=1&&$(".cart-item-ct").length>0){
				//cartCt=parseInt(data.split('<br />')[1]); if(cartCt>0){$(".cart-item-ct").html('<span>('+cartCt+' item'+(cartCt>1?'s':'')+')</span>');}
				cartCt=parseInt(data.split('<br />')[1]); if(cartCt>0){$(".cart-item-ct").html(cartCt+'<span class="shopAcctCartCtSuffix"> item'+(cartCt>1?'s':'')+'</span>');}
			}
			//if a custom post process script is meant to be run, process that here instead of standard post processing
			if(typeof customPostProcessAcctOption === 'function'){retData=customPostProcessAcctOption(2,opt,retData);if(retData[0]=="exit"){return;}}
			//now act according to route
			//console.log('retData[0]: '+retData[0]);
			switch(retData[0]){
				case 'overview'://alert($("#initRt").val());
					//if this is an initial login, check to see if the loginReloadImmediate variable is set - this would be custom, as the loginReload variable currently only reloads when closing the account window (why again?)
					if($("#initRt").val()=='login' && typeof loginReload!='undefined' && loginReload==1){top.location.href=top.location.pathname+top.location.search;/*top.location.reload();*/ return;}
					//if($("#initRt").val()=='login' && typeof loginReloadImmediate!='undefined' && loginReloadImmediate==1){top.location.href=top.location.pathname+top.location.search;/*top.location.reload();*/ return;}
					//if initial route was cart, exit here - calling cartNav with no arguments will use the previously called argument, which in this case should be the post-login checkout routing
					if($("#initRt").val()=='cart'){cartNav(); return;}
					openAcctOption('overview',1); 
					//also refresh the cart contents IF we're on the cart page
					if(curPage=='estore-cart'){updateCart('refresh');}
				break;
				case 'logout': 
				case 'reminderBack': openAcctOption('login',1); break; /*show the login page*/ 
				case 'pmtData': 
					//if pmt data was successfully deleted, clear input fields 
					//if((($("#pmtData_delete").length>0 && $("#pmtData_delete").prop('checked')==true) || ($("#pmtData_memAutoEnd").length>0 && $("#pmtData_memAutoEnd").prop('checked')==true)) && retData[2]=='1'/*retData[1].indexOf('success')!=-1*/){ 
               //3-11-23 DBH - ALWAYS clear fields on success UNLESS locally storing CC data
               if(retData[2]=='1' && retData[3]=='1'){ 
						switch($("#pmtData_pmtMethod").val()){
							case "cc": pmtClear=new Array('pmtData_ccName','pmtData_ccType','pmtData_ccNum','pmtData_ccExpM','pmtData_ccExpY','pmtData_ccCVV','pmtData_ccZip'); break;
							case "eft":pmtClear=new Array('pmtData_eftAccount','pmtData_eftRouting'); break;
							default: pmtClear=new Array();
						}
						for(i=0;i<pmtClear.length;i++){if($("#"+pmtClear[i]).length>0){$("#"+pmtClear[i]).val('');}}
						if($("#pmtData_delete").length>0 && $("#pmtData_delete").prop('checked')==true){
							$("#pmtDeleteNote").css('display','none'); $("#pmtData_delete").prop('checked',false);
						}
						if($("#pmtData_memAutoEnd").length>0 && $("#pmtData_memAutoEnd").prop('checked')==true){
							$("#pmtMemAutoEndNote").css('display','none'); $("#pmtData_memAutoEnd").prop('checked',false);
						}
					}
				break;
				case 'tripinfo': //CSC - if an args value was sent while processing a tripinfo, then assume the args is an infopage record ID  and direct to info pages
					if(args!=''){retData[0]='infopages';retData[1]='';} openAcctOption(retData[0],1,args); 
				break; 
				case 'masWaitList':
					if(opt=='login'){ //reroute to the masWaitList screen if just coming off the login screen
						openAcctOption(retData[0],1,args);
					}else if(retData[2]=='1'){
						$("#masWaitListDynamic").html('<a href="javascript:void(0);" onclick="hidePopDiv(\'ac\');" class="cssBtn2">Close</a>');
						//alert(retData[1]); hidePopDiv('ac',1);
					}
				break;
				case 'whitelabel': //JSD
					$("#whitelabel_url").val(retData[3]?retData[3]:$("#whitelabelDefURL").val());
					toggleWhiteLabelURL('display',0);
				break;
				case 'orderStatus':
					//if the above ajax order number search was successful, the order record ID will be returned in retData[3] - send that ID as the args to the openAcctOption function to load the requested order details
					//if the search was not successful, break here so no order detail page is loaded in the openAcctOption function and the alert message will be shown
					if(!retData[3]){break;}else{args=retData[3];}
            case 'pwdReset':
            case 'subscriptions': 
				case 'wishList':
				case 'orders':
				case 'infopages':
            case 'payment': 
            case 'memCredOpt':
            case 'messages': 
				case 'acctPending':
            case 'acctError':  
				case 'masReg':  
				case 'masVids':
            case 'masStats':
            case 'masAppts':
				case 'masYumpu': 
				case 'masAsync':
				case 'masClients':
            case 'masExpenses':
				case 'masAttendees':
            case 'masCoursework':
            case 'masCourseAlerts':
            case 'masAssessUpload':
            case 'masInstructorsNeeded':
               //CURRENTLY DEFAULT IS TO NOT HAVE THE CONTENT OF THE OPEN CONTROL PANEL REFRESH AT ALL - EXCEPT TO SHOW THE ALERT
               /*default:*/ openAcctOption(retData[0],1,args); /*show the requested account page - note we are NOT clearing the alert message (second argument == 1) */ 
            break; 
			}
			//show any returned message and reset the form processing variables
         populateAlertMsg(retData[1],retData[2]);
			//show the alert as an alert dialog as well on mobile devices since the alert text area may be offscreen
			if(mobileOrTabletDevice==1&&retData[1]&&retData[0]!='overview'){alrt=retData[1].replaceAll('<br />',"\n"); alert(alrt);}
			$('#p').val(''); $('#rt').val(''); $("#"+opt+"Btn").html(acctOptBtn); acctOptBtn=""; acctSendVals="";
			//reload cufon if needed since button HTML was removed and replaced
			if(cufonUsed==1){Cufon.refresh();}
			//reload the header account status include if available
			if($("#acct-access").length>0){$("#acct-access").load("/content/includes/acct-access.php?page="+curPage);}
			//alert("/content/includes/header-acct.php?page="+curPage);
			//$.get("/content/includes/header-acct.php?page="+curPage,{},function(data){alert(data);$("#headerAcctDiv").html(data);});
		});
	}else{
		$('#acctForm').attr("action","/account");
		$('#acctForm').trigger("submit");
	}
}

function populateAlertMsg(actMsg='',actOK=''){
   if(actOK){$("#acctAlertMsg").addClass('acctAlertOK');}else{$("#acctAlertMsg").removeClass('acctAlertOK');}//console.log(actMsg);
   $("#acctAlertMsg").html(actMsg).stop().css({opacity:'',height:''}).animate({opacity:actMsg?'show':'hide',height:actMsg?'show':'hide'},250,'easeInOutQuad');
}

