// source --> https://sncabinetsandclosets.com/wp-content/plugins/photo-gallery/js/bwg_gallery_box.js?ver=2.2.89 
var isPopUpOpened = false;

function spider_createpopup(url, current_view, width, height, duration, description, lifetime, lightbox_ctrl_btn_pos) {
  url = url.replace(/&#038;/g, '&');
  if (isPopUpOpened) { return };
  isPopUpOpened = true;
  if (spider_hasalreadyreceivedpopup(description) || spider_isunsupporteduseragent()) {
    return;
  }
  jQuery("html").attr("style", "overflow:hidden !important;");
  jQuery("#spider_popup_loading_" + current_view).css({display: "block"});
  jQuery("#spider_popup_overlay_" + current_view).css({display: "block"});

  jQuery.get(url, function(data) {
		var popup = jQuery(
    '<div id="spider_popup_wrap" class="spider_popup_wrap" style="' + 
          ' width:' + width + 'px;' +
          ' height:' + height + 'px;' + 
          ' margin-top:-' + height / 2 + 'px;' + 
          ' margin-left: -' + width / 2 + 'px; ">' +    
    data + 
    '</div>')
			.hide()
			.appendTo("body");
		spider_showpopup(description, lifetime, popup, duration, lightbox_ctrl_btn_pos);
	}).success(function(jqXHR, textStatus, errorThrown) {
    jQuery("#spider_popup_loading_" + current_view).css({display: "none !important;"});
  });
}

function spider_showpopup(description, lifetime, popup, duration, lightbox_ctrl_btn_pos) {
  isPopUpOpened = true;
  popup.show();
	spider_receivedpopup(description, lifetime, lightbox_ctrl_btn_pos);
}

function spider_hasalreadyreceivedpopup(description) {
  if (document.cookie.indexOf(description) > -1) {
    delete document.cookie[document.cookie.indexOf(description)];
  }
	return false; 
}

function spider_receivedpopup(description, lifetime, lightbox_ctrl_btn_pos) { 
	var date = new Date(); 
	date.setDate(date.getDate() + lifetime);
	document.cookie = description + "=true;expires=" + date.toUTCString() + ";path=/"; 
  if (lightbox_ctrl_btn_pos == 'bottom') {
    jQuery(".bwg_toggle_container").css("bottom", jQuery(".bwg_ctrl_btn_container").height() + "px");
  }
  else if (lightbox_ctrl_btn_pos == 'top') {
    jQuery(".bwg_toggle_container").css("top", jQuery(".bwg_ctrl_btn_container").height() + "px");
  }
}

function spider_isunsupporteduseragent() {
	return (!window.XMLHttpRequest);
}

function spider_destroypopup(duration) {
  if (document.getElementById("spider_popup_wrap") != null) {
    if (typeof jQuery().fullscreen !== 'undefined' && jQuery.isFunction(jQuery().fullscreen)) {
      if (jQuery.fullscreen.isFullScreen()) {
        jQuery.fullscreen.exit();
      }
    }
    if (typeof enable_addthis != "undefined" && enable_addthis) {
      jQuery(".at4-share-outer").hide();
    }
    setTimeout(function () {
      jQuery(".spider_popup_wrap").remove();
      jQuery(".spider_popup_loading").css({display: "none"});
      jQuery(".spider_popup_overlay").css({display: "none"});
      jQuery(document).off("keydown");
      jQuery("html").attr("style", "overflow:auto !important");
    }, 20);
  }
  isPopUpOpened = false;
  var isMobile = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
  var viewportmeta = document.querySelector('meta[name="viewport"]');
  if (isMobile && viewportmeta) {
    viewportmeta.content = 'width=device-width, initial-scale=1';
  }
  var scrrr = jQuery(document).scrollTop();
  window.location.hash = "";
  jQuery(document).scrollTop(scrrr);
  clearInterval(bwg_playInterval);
}
function get_ajax_pricelist(){
  var post_data = {};
  jQuery(".add_to_cart_msg").html("");
  post_data["ajax_task"] = "display";
  post_data["image_id"] = jQuery('#bwg_popup_image').attr('image_id');	

  // Loading.
  jQuery("#ecommerce_ajax_loading").css('height', jQuery(".bwg_ecommerce_panel").css('height'));
  jQuery("#ecommerce_opacity_div").css('width', jQuery(".bwg_ecommerce_panel").css('width'));
  jQuery("#ecommerce_opacity_div").css('height', jQuery(".bwg_ecommerce_panel").css('height'));
  jQuery("#ecommerce_loading_div").css('width', jQuery(".bwg_ecommerce_panel").css('width'));
  jQuery("#ecommerce_loading_div").css('height', jQuery(".bwg_ecommerce_panel").css('height'));
  document.getElementById("ecommerce_opacity_div").style.display = '';
  document.getElementById("ecommerce_loading_div").style.display = 'table-cell';	
  jQuery.post(
    jQuery('#bwg_ecommerce_form').attr('action'),
    post_data,

    function (data) {	

      var manual = jQuery(data).find('.manual').html();
      jQuery('.manual').html(manual);
	  
      var downloads = jQuery(data).find('.downloads').html();
      jQuery('.downloads').html(downloads);	
	  
      var pge_options = jQuery(data).find('.pge_options').html();
      jQuery('.pge_options').html(pge_options);	

      var pge_add_to_cart = jQuery(data).find('.pge_add_to_cart').html();
      jQuery('.pge_add_to_cart').html(pge_add_to_cart);		  
  
	  	  
    }
  ).success(function(jqXHR, textStatus, errorThrown) {
    document.getElementById("ecommerce_opacity_div").style.display = 'none';
    document.getElementById("ecommerce_loading_div").style.display = 'none';
    // Update scrollbar.
    //jQuery(".bwg_ecommece_panel").mCustomScrollbar({scrollInertia: 150 });
	//jQuery(".bwg_ecommerce_close_btn").click(bwg_ecommerce);

  });
    return false;
}


// Submit popup.
function spider_ajax_save(form_id) {
  var post_data = {};
  post_data["bwg_name"] = jQuery("#bwg_name").val();
  post_data["bwg_comment"] = jQuery("#bwg_comment").val();
  post_data["bwg_email"] = jQuery("#bwg_email").val();
  post_data["bwg_captcha_input"] = jQuery("#bwg_captcha_input").val();
  post_data["ajax_task"] = jQuery("#ajax_task").val();
  post_data["image_id"] = jQuery("#image_id").val();
  post_data["comment_id"] = jQuery("#comment_id").val();

  // Loading.
  jQuery("#ajax_loading").css('height', jQuery(".bwg_comments").css('height'));
  jQuery("#opacity_div").css('width', jQuery(".bwg_comments").css('width'));
  jQuery("#opacity_div").css('height', jQuery(".bwg_comments").css('height'));
  jQuery("#loading_div").css('width', jQuery(".bwg_comments").css('width'));
  jQuery("#loading_div").css('height', jQuery(".bwg_comments").css('height'));
  document.getElementById("opacity_div").style.display = '';
  document.getElementById("loading_div").style.display = 'table-cell';
  jQuery.post(
    jQuery('#' + form_id).attr('action'),
    post_data,

    function (data) {
      var str = jQuery(data).find('.bwg_comments').html();
      jQuery('.bwg_comments').html(str);
    }
  ).success(function(jqXHR, textStatus, errorThrown) {
    document.getElementById("opacity_div").style.display = 'none';
    document.getElementById("loading_div").style.display = 'none';
    // Update scrollbar.
    jQuery(".bwg_comments").mCustomScrollbar({scrollInertia: 150});
    // Bind comment container close function to close button.
    jQuery(".bwg_comments_close_btn").click(bwg_comment);
  });

  // if (event.preventDefault) {
    // event.preventDefault();
  // }
  // else {
    // event.returnValue = false;
  // }
  return false;
}

// Submit rating.
function spider_rate_ajax_save(form_id) {
  var post_data = {};
  post_data["image_id"] = jQuery("#" + form_id + " input[name='image_id']").val();
  post_data["rate"] = jQuery("#" + form_id + " input[name='score']").val();
  post_data["ajax_task"] = jQuery("#rate_ajax_task").val();
  jQuery.post(
    jQuery('#' + form_id).attr('action'),
    post_data,

    function (data) {
      var str = jQuery(data).find('#' + form_id).html();
      jQuery('#' + form_id).html(str);
    }
  ).success(function(jqXHR, textStatus, errorThrown) {
  });
  // if (event.preventDefault) {
    // event.preventDefault();
  // }
  // else {
    // event.returnValue = false;
  // }
  return false;
}

// Set value by ID.
function spider_set_input_value(input_id, input_value) {
  if (document.getElementById(input_id)) {
    document.getElementById(input_id).value = input_value;
  }
}

// Submit form by ID.
function spider_form_submit(event, form_id) {
  if (document.getElementById(form_id)) {
    document.getElementById(form_id).submit();
  }
  if (event.preventDefault) {
    event.preventDefault();
  }
  else {
    event.returnValue = false;
  }
}

// Check if required field is empty.
function spider_check_required(id, name) {
  if (jQuery('#' + id).val() == '') {
    alert(name + '* ' + bwg_objectL10n.bwg_field_required);
    jQuery('#' + id).attr('style', 'border-color: #FF0000;');
    jQuery('#' + id).focus();
    return true;
  }
  else {
    return false;
  }
}

// Check Email.
function spider_check_email(id) {
  if (jQuery('#' + id).val() != '') {
    var email = jQuery('#' + id).val().replace(/^\s+|\s+$/g, '');
    if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
      alert(bwg_objectL10n.bwg_mail_validation);
      return true;
    }
    return false;
  }
}

// Refresh captcha.
function bwg_captcha_refresh(id) {
	if (document.getElementById(id + "_img") && document.getElementById(id + "_input")) {
		srcArr = document.getElementById(id + "_img").src.split("&r=");
		document.getElementById(id + "_img").src = srcArr[0] + '&r=' + Math.floor(Math.random() * 100);
		document.getElementById(id + "_img").style.display = "inline-block";
		document.getElementById(id + "_input").value = "";
	}
}

function bwg_play_instagram_video(obj,bwg) {
  jQuery(obj).parent().find("video").each(function () {
    if (jQuery(this).get(0).paused) {
      jQuery(this).get(0).play();
      jQuery(obj).children().hide();
    }
    else {
      jQuery(this).get(0).pause();
      jQuery(obj).children().show();
    }
  })
};
// source --> https://sncabinetsandclosets.com/wp-content/plugins/photo-gallery/js/jquery.raty.js?ver=2.5.2 
/*!
 * jQuery Raty - A Star Rating Plugin
 * ------------------------------------------------------------------
 *
 * jQuery Raty is a plugin that generates a customizable star rating.
 *
 * Licensed under The MIT License
 *
 * @version        2.5.2
 * @since          2010.06.11
 * @author         Washington Botelho
 * @documentation  wbotelhos.com/raty
 *
 * ------------------------------------------------------------------
 *
 *  <div id="star"></div>
 *
 *  $('#star').raty();
 *  Changed imges to <i>.
 */

;(function($) {
  var methods = {
    init: function(settings) {
      return this.each(function() {
        methods.destroy.call(this);
        this.opt = $.extend(true, {}, $.fn.raty.defaults, settings);
        var that  = $(this),
            inits = ['number', 'readOnly', 'score', 'scoreName'];
        methods._callback.call(this, inits);
        if (this.opt.precision) {
          methods._adjustPrecision.call(this);
        }
        this.opt.number = methods._between(this.opt.number, 0, this.opt.numberMax)
        this.opt.path = this.opt.path || '';
        if (this.opt.path && this.opt.path.slice(this.opt.path.length - 1, this.opt.path.length) !== '/') {
          this.opt.path += '/';
        }
        this.stars = methods._createStars.call(this);
        this.score = methods._createScore.call(this);
        methods._apply.call(this, this.opt.score);
        var space  = this.opt.space ? 4 : 0,
            width  = this.opt.width || (this.opt.number * this.opt.size + this.opt.number * space);
        if (this.opt.cancel) {
          this.cancel = methods._createCancel.call(this);
          width += (this.opt.size + space);
        }
        if (this.opt.readOnly) {
          methods._lock.call(this);
        } else {
          that.css('cursor', 'pointer');
          methods._binds.call(this);
        }
        if (this.opt.width !== false) {
          that.css('width', width);
          $(".bwg_rate_spun").css('width', width);
        }
        methods._target.call(this, this.opt.score);
        that.data({ 'settings': this.opt, 'raty': true });
      });
    }, _adjustPrecision: function() {
      this.opt.targetType = 'score';
      this.opt.half       = true;
    }, _apply: function(score) {
      if (score && score > 0) {
        score = methods._between(score, 0, this.opt.number);
        this.score.val(score);
      }
      methods._fill.call(this, score);
      if (score) {
        methods._roundStars.call(this, score);
      }
      $("#bwg_star *").removeClass("bwg_rate_hover");
    }, _between: function(value, min, max) {
      return Math.min(Math.max(parseFloat(value), min), max);
    }, _binds: function() {
      if (this.cancel) {
        methods._bindCancel.call(this);
      }
      methods._bindClick.call(this);
      methods._bindOut.call(this);
      methods._bindOver.call(this);
    }, _bindCancel: function() {
      methods._bindClickCancel.call(this);
      methods._bindOutCancel.call(this);
      methods._bindOverCancel.call(this);
    }, _bindClick: function() {
      var self = this,
          that = $(self);
      self.stars.on('click.raty', function(evt) {
        self.score.val((self.opt.half || self.opt.precision) ? that.data('score') : $(this).attr("alt"));
        if (self.opt.click) {
          self.opt.click.call(self, parseFloat(self.score.val()), evt);
        }
      });
    }, _bindClickCancel: function() {
      var self = this;
      self.cancel.on('click.raty', function(evt) {
        self.score.removeAttr('value');
        if (self.opt.click) {
          self.opt.click.call(self, null, evt);
        }
      });
    }, _bindOut: function() {
      var self = this;
      $(this).on('mouseleave.raty', function(evt) {
        var score = parseFloat(self.score.val()) || undefined;
        methods._apply.call(self, score);
        methods._target.call(self, score, evt);
        if (self.opt.mouseout) {
          self.opt.mouseout.call(self, score, evt);
        }
      });
    }, _bindOutCancel: function() {
      var self = this;
      self.cancel.on('mouseleave.raty', function(evt) {
        $(this).attr('class', self.opt.cancelOff);
        if (self.opt.mouseout) {
          self.opt.mouseout.call(self, self.score.val() || null, evt);
        }
      });
    }, _bindOverCancel: function() {
      var self = this;
      self.cancel.on('mouseover.raty', function(evt) {
        $(this).attr('class', self.opt.cancelOn);
        self.stars.attr('class', self.opt.starOff);
        methods._target.call(self, null, evt);
        if (self.opt.mouseover) {
          self.opt.mouseover.call(self, null);
        }
      });
    }, _bindOver: function() {
      var self   = this,
          that   = $(self),
          action = self.opt.half ? 'mousemove.raty' : 'mouseover.raty';
      self.stars.on(action, function(evt) {
        var score = parseInt($(this).attr("alt"), 10);
        if (self.opt.half) {
          var position = parseFloat((evt.pageX - $(this).offset().left) / self.opt.size),
              plus     = (position > .5) ? 1 : .5;
          score = score - 1 + plus;
          methods._fill.call(self, score);
          if (self.opt.precision) {
            score = score - plus + position;
          }
          methods._roundStars.call(self, score);
          that.data('score', score);
        } else {
          methods._fill.call(self, score);
        }
        methods._target.call(self, score, evt);
        if (self.opt.mouseover) {
          self.opt.mouseover.call(self, score, evt);
        }
      });
    }, _callback: function(options) {
      for (i in options) {
        if (typeof this.opt[options[i]] === 'function') {
          this.opt[options[i]] = this.opt[options[i]].call(this);
        }
      }
    }, _createCancel: function() {
      var that   = $(this),
          icon   = this.opt.cancelOff,
          cancel = $('<i />', { 'class': 'raty-cancel ' + icon, 'alt': 'x', 'title': this.opt.cancelHint });
      if (this.opt.cancelPlace == 'left') {
        that.prepend('&#160;').prepend(cancel);
      } else {
        that.append('&#160;').append(cancel);
      }
      return cancel;
    }, _createScore: function() {
      return $('<input />', { type: 'hidden', name: this.opt.scoreName }).appendTo(this);
    }, _createStars: function() {
      var that = $(this);
      for (var i = 1; i <= this.opt.number; i++) {
        var title = methods._getHint.call(this, i),
            icon  = (this.opt.score && this.opt.score >= i) ? 'starOn' : 'starOff';
        icon = this.opt[icon];
        $('<i />', { 'class' : icon, 'alt': i, 'title': title }).appendTo(this);
        if (this.opt.space) {
          that.append((i < this.opt.number) ? '&#160;' : '');
        }
      }
      
      return that.children('i');
    }, _error: function(message) {
      $(this).html(message);
      $.error(message);
    }, _fill: function(score) {
      var self  = this,
          hash  = 0;
      for (var i = 1; i <= self.stars.length; i++) {
        var star   = self.stars.eq(i - 1),
            select = self.opt.single ? (i == score) : (i <= score);
        if (self.opt.iconRange && self.opt.iconRange.length > hash) {
          var irange = self.opt.iconRange[hash],
              on     = irange.on  || "starOn",
              off    = irange.off || "starOff",
              icon   = select ? on : off;
          if (i <= irange.range) {
            star.attr('class', this.opt[icon]);
            if (icon == on) {
              star.addClass("bwg_rate_hover");
            }
          }
          if (i == irange.range) {
            hash++;
          }
        } else {
          var icon = select ? 'starOn' : 'starOff';
          star.attr('class', this.opt[icon]);
          if (icon == "starOn") {
            star.addClass("bwg_rate_hover");
          }
        }
      }
    }, _getHint: function(score) {
      var hint = this.opt.hints[score - 1];
      return (hint === '') ? '' : (hint || score);
    }, _lock: function() {
      var score = parseInt(this.score.val(), 10), // TODO: 3.1 >> [['1'], ['2'], ['3', '.1', '.2']]
          hint  = score ? methods._getHint.call(this, score) : this.opt.noRatedMsg;
      $(this).data('readonly', true).css('cursor', '').attr('title', this.opt.alreadyRatedMsg);
      this.score.attr('readonly', 'readonly');
      this.stars.attr('title', this.opt.alreadyRatedMsg);
      if (this.cancel) {
        this.cancel.hide();
      }
    }, _roundStars: function(score) {
      var rest = (score - Math.floor(score)).toFixed(2);

      if (rest > this.opt.round.down) {
        var icon = 'starOn';                                 // Up:   [x.76 .. x.99]
        if (this.opt.halfShow && rest < this.opt.round.up) { // Half: [x.26 .. x.75]
          icon = 'starHalf';
        } else if (rest < this.opt.round.full) {             // Down: [x.00 .. x.5]
          icon = 'starOff';
        }
        this.stars.eq(Math.ceil(score) - 1).attr('class', this.opt[icon]);
      }                              // Full down: [x.00 .. x.25]
    }, _target: function(score, evt) {
      if (this.opt.target) {
        var target = $(this.opt.target);
        if (target.length === 0) {
          methods._error.call(this, 'Target selector invalid or missing!');
        }
        if (this.opt.targetFormat.indexOf('{score}') < 0) {
          methods._error.call(this, 'Template "{score}" missing!');
        }
        var mouseover = evt && evt.type == 'mouseover';
        if (score === undefined) {
          score = this.opt.targetText;
        } else if (score === null) {
          score = mouseover ? this.opt.cancelHint : this.opt.targetText;
        } else {
          if (this.opt.targetType == 'hint') {
            score = methods._getHint.call(this, Math.ceil(score));
          } else if (this.opt.precision) {
            score = parseFloat(score).toFixed(1);
          }
          if (!mouseover && !this.opt.targetKeep) {
            score = this.opt.targetText;
          }
        }
        if (score) {
          score = this.opt.targetFormat.toString().replace('{score}', score);
        }
        if (target.is(':input')) {
          target.val(score);
        } else {
          target.html(score);
        }
      }
    }, _unlock: function() {
      $(this).data('readonly', false).css('cursor', 'pointer').removeAttr('title');
      this.score.removeAttr('readonly', 'readonly');
      for (var i = 0; i < this.opt.number; i++) {
        this.stars.eq(i).attr('title', methods._getHint.call(this, i + 1));
      }
      if (this.cancel) {
        this.cancel.css('display', '');
      }
    }, cancel: function(click) {
      return this.each(function() {
        if ($(this).data('readonly') !== true) {
          methods[click ? 'click' : 'score'].call(this, null);
          this.score.removeAttr('value');
        }
      });
    }, click: function(score) {
      return $(this).each(function() {
        if ($(this).data('readonly') !== true) {
          methods._apply.call(this, score);
          if (!this.opt.click) {
            methods._error.call(this, 'You must add the "click: function(score, evt) { }" callback.');
          }
          this.opt.click.call(this, score, { type: 'click' });
          methods._target.call(this, score);
        }
      });
    }, destroy: function() {
      return $(this).each(function() {
        var that = $(this),
            raw  = that.data('raw');
        if (raw) {
          that.off('.raty').empty().css({ cursor: raw.style.cursor, width: raw.style.width }).removeData('readonly');
        } else {
          that.data('raw', that.clone()[0]);
        }
      });
    }, getScore: function() {
      var score = [],
          value ;
      $(this).each(function() {
        value = this.score.val();
        score.push(value ? parseFloat(value) : undefined);
      });
      return (score.length > 1) ? score : score[0];
    }, readOnly: function(readonly) {
      return this.each(function() {
        var that = $(this);
        if (that.data('readonly') !== readonly) {
          if (readonly) {
            that.off('.raty').children('i').off('.raty');
            methods._lock.call(this);
          } else {
            methods._binds.call(this);
            methods._unlock.call(this);
          }
          that.data('readonly', readonly);
        }
      });
    }, reload: function() {
      return methods.set.call(this, {});
    }, score: function() {
      return arguments.length ? methods.setScore.apply(this, arguments) : methods.getScore.call(this);
    }, set: function(settings) {
      return this.each(function() {
        var that   = $(this),
            actual = that.data('settings'),
            news   = $.extend({}, actual, settings);
        that.raty(news);
      });
    }, setScore: function(score) {
      return $(this).each(function() {
        if ($(this).data('readonly') !== true) {
          methods._apply.call(this, score);
          methods._target.call(this, score);
        }
      });
    }
  };
  $.fn.raty = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    } else {
      $.error('Method ' + method + ' does not exist!');
    }
  };
  $.fn.raty.defaults = {
    cancel        : false,
    cancelHint    : 'Cancel this rating!',
    cancelOff     : 'fa-minus-square-o',
    cancelOn      : 'fa-minus-square-o',
    cancelPlace   : 'left',
    click         : undefined,
    half          : false,
    halfShow      : true,
    hints         : ['bad', 'poor', 'regular', 'good', 'gorgeous'],
    iconRange     : undefined,
    mouseout      : undefined,
    mouseover     : undefined,
    noRatedMsg    : 'Not rated yet!',
    alreadyRatedMsg : 'Not rated yet!',
    number        : 5,
    numberMax     : 20,
    path          : '',
    precision     : false,
    readOnly      : false,
    round         : { down: .25, full: .6, up: .76 },
    score         : undefined,
    scoreName     : 'score',
    single        : false,
    size          : 16,
    space         : true,
    starHalf      : 'fa fa-star-half',
    starOff       : 'fa fa-star-o',
    starOn        : 'fa fa-star',
    target        : undefined,
    targetFormat  : '{score}',
    targetKeep    : false,
    targetText    : '',
    targetType    : 'hint',
    width         : undefined
  };
})(jQuery);
// source --> https://sncabinetsandclosets.com/wp-content/plugins/photo-gallery/js/jquery.featureCarousel.js?ver=2.2.89 
/*!
 * Feature Carousel 
 */
(function($){

  $.fn.featureCarousel = function (options) {

    // Adds support for multiple carousels on one page
    if (this.length > 1) {
      this.each(function() {
        $(this).featureCarousel(options);
      });
      return this;
    }
    
    // override the default options with user defined options
    options = $.extend({}, $.fn.featureCarousel.defaults, options || {});
 
    /*
    These are univeral values that are used throughout the plugin. Do not modify them
     * unless you know what you're doing. Most of them feed off the options
     * so most customization can be achieved by modifying the options values 

	 */
	    var pluginData = {        
        containerWidth:       0,
        containerHeight:      0,
        largeFeatureWidth:    0,
        largeFeatureHeight:   0,
        smallFeatureHeight:   0,
        smallFeatureWidth:    0,       
        totalFeatureCount:    $(this).children("div").length,       
        featuresContainer:    $(this),
        featuresArray:        [],
        containerIDTag:       "#"+$(this).attr("id"),
        timeoutVar:           null,
        rotationsRemaining:   0,
        itemsToAnimate:       0,
        borderWidth:		      0,     
        autoTime:             0   
      };

    /**
     * Function to preload the images in the carousel if desired.
     * This is not recommended if there are a lot of images in the carousel because
     * it may take a while. Functionality does not depend on preloading the images 

     */  
    var preload = function(callback) {
      // user may not want to preload images
      if (options.preload == true) {
        var $imageElements = pluginData.featuresContainer.find("img");
        var loadedImages = 0;
        var totalImages = $imageElements.length;
        $imageElements.each(function (index, element) {
          // Attempt to load the images			
					var img = new Image();
          $(img).bind('load error', function () {
            // Add to number of images loaded and see if they are all done yet
            loadedImages++;
            if (loadedImages == totalImages) {
              // All done, perform callback
              callback();
            }
          });					
					img.src = element.src;				
        });
		
      } else {
        callback();
        // if user doesn't want preloader, then just go right to callback
      }
    }

    // Gets the feature container based on the number
    var getContainer = function(featureNum) {
      return pluginData.featuresArray[featureNum-1];
    }

    // get a feature given it's set position (the position that doesn't change)
    var getBySetPos = function(position) {
      $.each(pluginData.featuresArray, function () {
        if ($(this).data().setPosition == position)
          return $(this);
      });
    }

    // get previous feature number
    var getPreviousNum = function(num) {
      if ((num - 1) == 0) {
        return pluginData.totalFeatureCount;
      } else {
        return num - 1;
      }
    }

    // get next feature number
    var getNextNum = function(num) {
      if ((num + 1) > pluginData.totalFeatureCount) {
        return 1;
      } else {
        return num + 1;
      }
    }

    /**
     * Because there are several options the user can set for the width and height
     * of the feature images, this function is used to determine which options were set
     * and to set the appropriate dimensions used for a small and large feature	
     */
    var setupFeatureDimensions = function() {
      // Set the height and width of the entire carousel container
      options.containerWidth = pluginData.featuresContainer.width();
      options.containerHeight = pluginData.featuresContainer.height();

      // Grab the first image for reference
      var $firstFeatureImage = $(pluginData.containerIDTag).find(".bwg_carousel-image" + options.bwg_number + ":first");
     
      // Large Feature Width
      if (options.largeFeatureWidth > 1)
     	pluginData.largeFeatureWidth = options.largeFeatureWidth;
	 
      else if (options.largeFeatureWidth > 0 && options.largeFeatureWidth < 1)
        pluginData.largeFeatureWidth = $firstFeatureImage.width() * options.largeFeatureWidth;
      else
        pluginData.largeFeatureWidth = $firstFeatureImage.outerWidth();
      // Large Feature Height
      if (options.largeFeatureHeight > 1)
        pluginData.largeFeatureHeight = options.largeFeatureHeight;
      else if (options.largeFeatureHeight > 0 && options.largeFeatureHeight < 1)
        pluginData.largeFeatureHeight = $firstFeatureImage.height() * options.largeFeatureHeight;
      else
        pluginData.largeFeatureHeight = $firstFeatureImage.outerHeight();
      // Small Feature Width
      if (options.smallFeatureWidth > 1)
        pluginData.smallFeatureWidth = options.smallFeatureWidth;
      else if (options.smallFeatureWidth > 0 && options.smallFeatureWidth < 1)
        pluginData.smallFeatureWidth = $firstFeatureImage.width() * options.smallFeatureWidth;
      else
        pluginData.smallFeatureWidth = $firstFeatureImage.outerWidth() / 2;
      
    }

    /**
     * Function to take care of setting up various aspects of the carousel,
     * most importantly the default positions for the features	
     */
    var setupCarousel = function() {
      // Set the total feature count to the amount the user wanted to cutoff
      if (options.displayCutoff > 0 && options.displayCutoff < pluginData.totalFeatureCount) {
        pluginData.totalFeatureCount = options.displayCutoff;
      }

      // fill in the features array 
      pluginData.featuresContainer.find(".bwg_carousel-feature" + options.bwg_number).each(function (index) {
        if (index < pluginData.totalFeatureCount) {
          pluginData.featuresArray[index] = $(this);
        }
      });

      // Determine the total border width around the feature if there is one
      if (pluginData.featuresContainer.find(".bwg_carousel-feature" + options.bwg_number).first().css("borderLeftWidth") != "medium") {
        pluginData.borderWidth = parseInt(pluginData.featuresContainer.find(".bwg_carousel-feature" + options.bwg_number).first().css("borderLeftWidth"));
      }
      if (options.imagecount != 1) {
      // Place all the features in a center hidden position to start off
        pluginData.featuresContainer
          // Have to make the container relative positioning
          .find(".bwg_carousel-feature" + options.bwg_number).each(function () {
            // Center all the features in the middle and hide them
            $(this).css({
              'left': (options.containerWidth / 2) - (options.largeFeatureWidth * options.smallFeaturePar / 2) - (pluginData.borderWidth / 2)+ options.largeFeatureWidth / 2,           
              'width': options.largeFeatureWidth * options.smallFeaturePar / 100,
              'height': options.largeFeatureHeight * options.smallFeaturePar / 100,
              'top': options.smallFeatureOffset + options.topPadding+options.largeFeatureHeight / 2,
              'opacity': 0,
              'filter': 'Alpha(opacity=100)'
            });
          }) 
      }
      else {
        // Place all the features in a center hidden position to start off
        pluginData.featuresContainer
          // Have to make the container relative positioning
          .find(".bwg_carousel-feature" + options.bwg_number).each(function () {
            // Center all the features in the middle and hide them
            $(this).css({
              'left':0 ,        
              'width': options.largeFeatureWidth * options.smallFeaturePar ,
              'height': options.largeFeatureHeight * options.smallFeaturePar ,
              'top': 0,
              'opacity': 0,
              'filter': 'Alpha(opacity=100)'
            });
          }) 
      }        
        
      // set position to relative of captions if displaying below image
      if (options.captionBelow) {
        pluginData.featuresContainer.find(".bwg_carousel-caption" + options.bwg_number).css('position','absolute');
      }

      // figure out number of items that will rotate each time
      if (pluginData.totalFeatureCount < options.imagecount) {
        pluginData.itemsToAnimate = pluginData.totalFeatureCount;  
      } 
      else {
        pluginData.itemsToAnimate = options.imagecount + 2;
      }       

      // Hide story info and set the proper positioning
         pluginData.featuresContainer.find(".bwg_carousel-caption" + options.bwg_number)
        .hide();
    }

    /**
     * Here all the position data is set for the features.
     * This is an important part of the carousel to keep track of where
     * each feature within the carousel is	 
     */
    var setupFeaturePositions = function() {
      // give all features a set number that won't change so they remember their
      // original order 
      $.each(pluginData.featuresArray, function (i) {
        $(this).data('setPosition',i+1);
      });

      // Go back one - This is done because we call the move function right away, which
      // shifts everything to the right. So we set the current center back one, so that
      // it displays in the center when that happens
      var oneBeforeStarting = getPreviousNum(options.startingFeature);
      window["bwg_currentCenterNum" +options.bwg_number] = oneBeforeStarting;

      // Center feature will be position 1
      var $centerFeature = getContainer(oneBeforeStarting);
      $centerFeature.data('position',1);

      // Everything before that center feature...
      var $prevFeatures = $centerFeature.prevAll();
      $prevFeatures.each(function (i) {
        $(this).data('position',(pluginData.totalFeatureCount - i));
      });

      // And everything after that center feature...
      var $nextFeatures = $centerFeature.nextAll();
      $nextFeatures.each(function (i) {
        if ($(this).data('setPosition') != undefined) {
          $(this).data('position',(i + 2));
        }
      });

      // if the counter style is for including number tags in description...
      if (options.counterStyle == 'caption') {
        $.each(pluginData.featuresArray, function () {
          var pos = getPreviousNum($(this).data('position'));
          var $numberTag = $("<span></span>");
          $numberTag.addClass("numberTag");
          $numberTag.html("("+ pos + " of " + pluginData.totalFeatureCount + ") ");
          $(this).find(".bwg_carousel-caption" + options.bwg_number).prepend($numberTag);
        });
      }
    }
    
    // Update the tracker information with the new centered feature
    var updateTracker = function(oldCenter, newCenter) {
      if (options.trackerIndividual) {
        // get selectors for the two trackers
        var $trackerContainer = pluginData.featuresContainer.find(".tracker-individual-container");
        var $oldCenter = $trackerContainer.find("#tracker-"+oldCenter);
        var $newCenter = $trackerContainer.find("#tracker-"+newCenter);
      
	   // change classes
        
      }
      
      if (options.trackerSummation) {
        var $trackerContainer = pluginData.featuresContainer.find('.tracker-summation-container');
        $trackerContainer.find('.tracker-summation-current').text(newCenter);
      }
	  
    }

    /**
     * This function will set the autoplay for the carousel to
     * automatically rotate it given the time in the options
     * pass in TRUE to just clear the timer
     */
    var setTimer = function(stop) {
      // clear the timeout var if it exists
      clearTimeout(pluginData.timeoutVar);

      // set interval for moving if autoplay is set
      if (!stop && options.autoPlay != 0) {
        var autoTime = (Math.abs(options.autoPlay) < options.carouselSpeed) ? options.carouselSpeed : Math.abs(options.autoPlay);
        pluginData.timeoutVar = setTimeout(function () {
          (options.autoPlay > 0) ? initiateMove(true,1) : initiateMove(false,1);
        }, autoTime);
      }
    }


    // This is a helper function for the animateFeature function that
    // will update the positions of all the features based on the direction
    var rotatePositions = function(direction) {
      $.each(pluginData.featuresArray, function () {
        var newPos;
        if (direction == false) {
          newPos = getNextNum($(this).data().position);
        } else {
          newPos = getPreviousNum($(this).data().position);
        }

        $(this).data('position',newPos);
      });
    }

    /**
     * This function is used to animate the given feature to the given     
     * location. Valid locations are "left", "right", "center", "hidden"
     */
    var animateFeature = function($feature, direction) {
      
       if(window["data_" + options.bwg_number][$feature.attr("image_key")]["is_embed_video"]) {
          jQuery(".bwg_carousel-feature" + options.bwg_number).find("iframe").each(function () {
            jQuery(this)[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
            jQuery(this)[0].contentWindow.postMessage('{ "method": "pause" }', "*");
            jQuery(this)[0].contentWindow.postMessage('pause', '*');
          }); 
        }
       if(window["data_" + options.bwg_number][$feature.attr("image_key")]["is_embed_instagram_post"]) {
        jQuery("#bwg_carousel_play_pause_" + options.bwg_number).hide(); 
       }
      $feature.find(".bwg_video_hide" + options.bwg_number).each(function() {
        jQuery(this).css({display: ''});
      });
      $feature.find(".bwg_carousel_image_container_" + options.bwg_number).each(function() {
        jQuery(this).hide();
      });
      $feature.find(".bwg_carousel_watermark_" + options.bwg_number).each(function() {
        jQuery(this).hide();
      });      
      
      var new_width, new_height, new_top, new_left, new_zindex, new_padding, new_fade,new_fade1,new_f;     
      // Determine the old and new positions of the feature
      var oldPosition = $feature.data('position');
      var newPosition;
      if (direction == true)
        newPosition = getPreviousNum(oldPosition);
      else
        newPosition = getNextNum(oldPosition);     
      // callback for moving out of center pos
      if (oldPosition == 1) {
        options.leavingCenter($feature);
      }
      // Caculate new new css values depending on where the feature will be located
        //center
        if (newPosition == 1) {
          var title = window["data_" + options.bwg_number][$feature.attr("image_key")]["alt"];
          title = title.replace(/^\s+/, '').replace(/\s+$/, '');
          
          if (title === '' || !options.enable_image_title) {
            jQuery(".bwg_carousel_title_text_" + options.bwg_number).css({display: 'none'});
          }
          else {
            jQuery(".bwg_carousel_title_text_" + options.bwg_number).css({display: ''});
          }
          new_width = pluginData.largeFeatureWidth;              
          new_height = pluginData.largeFeatureHeight;
          new_top =(options.containerHeight / 2 - new_height / 2 );
          new_zindex = $feature.css("z-index");
          new_left = (options.containerWidth / 2) - (pluginData.largeFeatureWidth / 2) - (pluginData.borderWidth / 2);       
          new_fade = 1; 
          new_fade1 = 100;          
          if(window["data_" + options.bwg_number][$feature.attr("image_key")]["is_embed_video"]) {
            jQuery(".bwg_carousel_play_pause_" + options.bwg_number).css({display: 'none'});
            jQuery(".bwg_carousel_image_container_" + options.bwg_number).css({display: ''});
            jQuery(".bwg_carousel_watermark_container_" + options.bwg_number).css({display: ''});
            jQuery(".bwg_carousel_watermark_spun_" + options.bwg_number).css({display: ''});
            jQuery(".bwg_carousel_watermark_" + options.bwg_number).css({display: ''});
            $feature.find(".bwg_video_hide" + options.bwg_number).each(function() {
              jQuery(this).hide();
             });
          }
          else {
            $feature.find(".bwg_video_hide" + options.bwg_number).each(function() {
              jQuery(this).hide();
            });
            jQuery(".bwg_carousel_play_pause_" + options.bwg_number).css({display: ''});
            $feature.find(".bwg_carousel_image_container_" + options.bwg_number).each(function() {
              jQuery(this).css({display: ''});          
            });
            $feature.find(".bwg_carousel_watermark_" + options.bwg_number).each(function() {
              jQuery(this).css({display: ''});          
            });
          }
            new_f = "grayscale(0%)";
          if(window["data_" + options.bwg_number][$feature.attr("image_key")]["is_embed_instagram_post"]) {
            $feature.find(".bwg_embed_frame_" + options.bwg_number).css("min-height" ,'');
            $feature.find(".bwg_embed_frame_" + options.bwg_number).css("min-width" ,''); 
          }
          if(window["data_" + options.bwg_number][$feature.attr("image_key")]["is_embed_video"]) {
            $feature.find(".bwg_embed_frame_" + options.bwg_number).css("display" ,'inline-block');
          } 
        }
        else {
          /*left*/
          if (newPosition <= pluginData.totalFeatureCount && newPosition > pluginData.totalFeatureCount - options.imagecount / 2 + 1) {  
            new_width = (pluginData.largeFeatureWidth * Math.pow(options.smallFeaturePar, pluginData.totalFeatureCount - newPosition + 1));      
            new_height = (pluginData.largeFeatureHeight * Math.pow(options.smallFeaturePar, pluginData.totalFeatureCount - newPosition + 1));
            new_top = (options.containerHeight / 2 - new_height / 2 ) ;            
            new_fade = 1;
            new_f = "grayscale(0%)";
            new_fade1 = 100;
            new_width = (pluginData.largeFeatureWidth * Math.pow(options.smallFeaturePar, pluginData.totalFeatureCount - newPosition + 1));      
            new_height = (pluginData.largeFeatureHeight * Math.pow(options.smallFeaturePar, pluginData.totalFeatureCount - newPosition + 1));
            new_top = (options.containerHeight / 2 - new_height / 2 ) ;
            if(window["data_" + options.bwg_number][$feature.attr("image_key")]["is_embed_instagram_post"] ) {
              $feature.find(".bwg_embed_frame_" + options.bwg_number).css("min-height",'100%');
              $feature.find(".bwg_embed_frame_" + options.bwg_number).css("min-width" ,'100%');
            }
            if(options.fit_containerWidth == false && options.smallFeaturePar < 1){
              new_left = (options.containerWidth / 2 - pluginData.largeFeatureWidth / 2)-(pluginData.largeFeatureWidth * (1 - options.smallFeaturePar) * options.smallFeaturePar * (pluginData.totalFeatureCount - newPosition + 1));             
            } else if(options.fit_containerWidth == false && options.smallFeaturePar == 1){
              new_left = (options.containerWidth / 2 - pluginData.largeFeatureWidth / 2)-(pluginData.largeFeatureWidth * ( options.smallFeaturePar) * options.smallFeaturePar * (pluginData.totalFeatureCount - newPosition + 1));             
            }  else {
              new_left1 = (options.containerWidth / 2 - pluginData.largeFeatureWidth / 2) / (options.imagecount / 2 - 0.5);
              new_left =  ((options.containerWidth / 2) - (pluginData.largeFeatureWidth / 2) - (pluginData.borderWidth / 2)) - (new_left1 * (pluginData.totalFeatureCount - newPosition+1  )); 
            }
          }
      /*right*/
          else if (newPosition >= 2 && newPosition <= options.imagecount / 2 + 1) {
            new_width = (pluginData.largeFeatureWidth * Math.pow(options.smallFeaturePar,newPosition-1));        
            new_height =( pluginData.largeFeatureHeight * Math.pow(options.smallFeaturePar, newPosition-1) );         
            new_top = ( options.containerHeight / 2 - new_height / 2 )  ;        
            new_fade = 1; 
            new_f = "grayscale(0%)";
            new_fade1 = 100; 
            if(window["data_" + options.bwg_number][$feature.attr("image_key")]["is_embed_instagram_post"] ) {
              $feature.find(".bwg_embed_frame_" + options.bwg_number).css("min-height" ,'100%');
              $feature.find(".bwg_embed_frame_" + options.bwg_number).css("min-width" ,'100%');
            }   
            if(options.fit_containerWidth == false && options.smallFeaturePar < 1){         
              new_left = (options.containerWidth / 2 + pluginData.largeFeatureWidth / 2)+( pluginData.largeFeatureWidth  * options.smallFeaturePar * (1 - options.smallFeaturePar) * (newPosition - 1)) - new_width;
            } else if(options.fit_containerWidth == false && options.smallFeaturePar ==1){         
            new_left = (options.containerWidth / 2 + pluginData.largeFeatureWidth / 2)+( pluginData.largeFeatureWidth  * options.smallFeaturePar * ( options.smallFeaturePar) * (newPosition - 1)) - new_width;
            } else {
              new_left1 = ( (options.containerWidth / 2 -pluginData.largeFeatureWidth / 2)) / (options.imagecount / 2 - 0.5);
              new_left = (options.containerWidth / 2 + pluginData.largeFeatureWidth / 2 )  - new_width + ( new_left1 * (newPosition - 1));
            }
                     
          }
       //hidden
          else {
             new_left = (options.containerWidth / 2) - (pluginData.largeFeatureWidth*options.smallFeaturePar / 2) - (pluginData.borderWidth / 2);        
             new_fade = 0;
             new_fade1 = 0;
          }
        }        
      // This code block takes care of hiding the feature information if the feature is leaving the center
      if (oldPosition == 1) {
        // Slide up the story information
        $feature.find(".bwg_carousel-caption" + options.bwg_number)
          .hide();
      }     
        
      // Animate the feature div to its new location
      
     $feature.find("div[class^='bwg_carousel-image']").css({filter:new_f, "-webkit-filter":new_f});
      $feature
        .animate(
          {
            width: new_width,
            height: new_height,
            top: new_top,
            left: new_left,           
            opacity: new_fade,
            filter : new_fade1
          },
          options.carouselSpeed,
          options.animationEasing,
          function () {
            // Take feature info out of hiding if new position is center
            if (newPosition == 1) {
              // need to set the height to auto to accomodate caption if displayed below image
              if (options.captionBelow)
               $feature.css('height','auto');
              // fade in the feature information
              $feature.find(".bwg_carousel-caption" + options.bwg_number)
                .fadeTo("fast",0.85);
              // callback for moved to center
              options.movedToCenter($feature);
            }
            // decrement the animation queue
            pluginData.rotationsRemaining = pluginData.rotationsRemaining - 1;
            // have to change the z-index after the animation is done
            $feature.css("z-index", new_zindex);
            // change trackers if using them
            if (options.trackerIndividual || options.trackerSummation) {
              // just update the tracker once; once the new center feature has arrived in center
              if (newPosition == 1) {
                // figure out what item was just in the center, and what item is now in the center
                var newCenterItemNum = pluginData.featuresContainer.find(".bwg_carousel-feature" + options.bwg_number).index($feature) + 1;
                var oldCenterItemNum;
                if (direction == false)
                  oldCenterItemNum = getNextNum(newCenterItemNum);
                else
                  oldCenterItemNum = getPreviousNum(newCenterItemNum);
                // now update the trackers
                updateTracker(oldCenterItemNum, newCenterItemNum);
              }
            }

            // did all the the animations finish yet?
            var divide = pluginData.rotationsRemaining / pluginData.itemsToAnimate;
            if (divide % 1 == 0) {
              // if so, set moving to false...
              window["bwg_currentlyMoving" +options.bwg_number] = false;
              // change positions for all items...
              rotatePositions(direction);

              // and move carousel again if queue is not empty
              if (pluginData.rotationsRemaining > 0)
                move(direction);
            }
            
            // reset timer and auto rotate again
            setTimer(false);
          }
          
        )
       
        .end();
    }

    /**
     * move the carousel to the left or to the right. The features that
     * will move into the four positions are calculated and then animated
     * rotate to the RIGHT when direction is TRUE and
     * rotate to the LEFT when direction is FALSE
	
     */
     
    var move = function(direction)
    {
      // Set the carousel to currently moving
      window["bwg_currentlyMoving" +options.bwg_number] = true;

      // Obtain the new feature positions based on the direction that the carousel is moving
    
    var $newCenter, $newLefts, $newRights, $newHidden,$curNum;

      if (direction == true ) {
        // Shift features to the left
        $newCenter = getContainer(getNextNum(window["bwg_currentCenterNum" +options.bwg_number]));
        $newLefts = [];
        $curNum = window["bwg_currentCenterNum" +options.bwg_number];
        for(var i = 1; i <= options.imagecount / 2 + 1; ++i) {
          $newLefts.push(getContainer($curNum));
          $curNum = getPreviousNum($curNum);
        }
       
        $newRights = [];
        $curNum = getNextNum(window["bwg_currentCenterNum" +options.bwg_number]);
        for(var i = 1; i <= options.imagecount / 2 + 1; ++i) {
          $curNum = getNextNum($curNum);
          $newRights.push(getContainer($curNum));
        }
        
        window["bwg_currentCenterNum" +options.bwg_number] = getNextNum(window["bwg_currentCenterNum" +options.bwg_number]);
      } else  {
        $newCenter = getContainer(getPreviousNum(window["bwg_currentCenterNum" +options.bwg_number]));
        $newLefts = [];
        $curNum = getPreviousNum(window["bwg_currentCenterNum" +options.bwg_number]);
        for (var i = 1; i <= options.imagecount / 2 + 1; ++i){
          $curNum = getPreviousNum($curNum);   
          $newLefts.push(getContainer($curNum));
        }
        $newRights = [];
        $curNum = window["bwg_currentCenterNum" +options.bwg_number];
        for (var i = 1; i <= options.imagecount / 2 + 1; ++i){
          $newRights.push(getContainer($curNum));
          $curNum=getNextNum($curNum);
        }       
        window["bwg_currentCenterNum" +options.bwg_number] = getPreviousNum(window["bwg_currentCenterNum" +options.bwg_number]);
      }
    
// Animate the features into their new positions
        for (i = 0; i < $newLefts.length; i++) {
          $newLefts[i].css("z-index",$newLefts.length - i + 3);
          animateFeature($newLefts[i], direction);
        }
        $newCenter.css("z-index", $newLefts.length + 4);
        animateFeature($newCenter, direction);
        for (i = 0; i < $newRights.length; i++) {
          $newRights[i].css("z-index",$newRights.length - i + 3);
          animateFeature($newRights[i], direction);
        }    
     
      // Only want to animate the "hidden" feature if there are more than three
    }

    // This is used to relegate carousel movement throughout the plugin
    // It will only initiate a move if the carousel isn't currently moving
    // It will set the animation queue to the number of rotations given
    var initiateMove = function(direction, rotations) {
      if (window["bwg_currentlyMoving" +options.bwg_number] == false ) {
        var queue = rotations * pluginData.itemsToAnimate ;
        pluginData.rotationsRemaining = queue ;
        window["bwg_carousel_watermark_" + options.bwg_number]();
        move(direction);
       
      }
    }

    /**
     * This will find the shortest distance to travel the carousel from
     * one position to another position. It will return the shortest distance
     * in number form, and will be positive to go to the right and negative for left	 

     */

  
    // Move to the left if left button clicked
    $(options.leftButtonTag).on('click',function () {
      initiateMove(false,1);
    });

    // Move to right if right button clicked
    $(options.rightButtonTag).on('click',function () {
      initiateMove(true,1);
    });

    // These are the click and hover events for the features
     pluginData.featuresContainer.find(".bwg_carousel-feature" + options.bwg_number)
      
      .mouseover(function () {
        if (window["bwg_currentlyMoving" +options.bwg_number] == false) {
          var position = $(this).data('position');
       
          if (position == 3 || position == pluginData.totalFeatureCount) {
            $(this).css("opacity",1); 
          }
        }
        // pause the rotation?
        if (options.pauseOnHover) setTimer(true);
        // stop the rotation?
        if (options.stopOnHover) options.autoPlay = 0;
      })
      .mouseout(function () {
        if (window["bwg_currentlyMoving" +options.bwg_number] == false) {
          var position = $(this).data('position');
          if (position == 3 || position == pluginData.totalFeatureCount) {
            $(this).css("opacity",1);
          }
        }
        // resume the rotation
        if (options.pauseOnHover) {
          setTimer(false);
        }
      });

    // Add event listener to all clicks within the features container
    // This is done to disable any links that aren't within the center feature
    $("a", pluginData.containerIDTag).on("click", function (event) {
      // travel up to the container
      var $parents = $(this).parentsUntil(pluginData.containerIDTag);
      // now check each of the feature divs within it
      $parents.each(function () {
        var position = $(this).data('position');
        // if there are more than just feature divs within the container, they will
        // not have a position and it may come back as undefined. Throw these out
        if (position != undefined) {
          // if any of the links on a feature OTHER THAN the center feature were clicked,
          // initiate a carousel move but then throw the link action away
          if (position != 1) {
            if (position == pluginData.totalFeatureCount) {
              initiateMove(false,1);
            } else if (position == 2) {
              initiateMove(true,1);
            }
            event.preventDefault();
            return false;
          // if the position WAS the center (i.e. 1), fire callback
          } else {
            options.clickedCenter($(this));
          }
        }
      });
    });

    // Did someone click one of the individual trackers?
   
  
    /****************
     PUBLIC FUNCTIONS 
     ****************/
    this.initialize = function () {
      // Call the preloader and pass in our callback, which is just a slew of function calls
      // that should only be executed after the images have been loaded
      preload(function () {
        setupFeatureDimensions();
        setupCarousel();
        
        if (window["bwg_currentlyMoving" +options.bwg_number] == false ) {
          setupFeaturePositions();        
          initiateMove(true,1);
        }
        
      });
 
      return this;
    };
     this.shift = function (that) {
    
      var position = $(that).data('position');
      if (position == 1) {
        return;
      }
      if (position > pluginData.totalFeatureCount / 2 + 1) {
        initiateMove(false, pluginData.totalFeatureCount - position + 1);
        options.carouselSpeed = 400;
        options.animationEasing;
      }
      else {
        initiateMove(true, position - 1);
        options.carouselSpeed = 400;
        options.animationEasing;
      }
    }
    this.next = function() {
      initiateMove(true, 1);
    }
    this.prev = function () {
      initiateMove(false, 1);
    }
   
    this.pause = function () {
      options.autoPlay = 0;
      setTimer(true);
    }
    this.start = function () {
      options.autoPlay = options.interval;      
      setTimer(false);
    }
 
    // Initialize the plugin
    return this.initialize();
  };
  
  $.fn.featureCarousel.defaults = {
    // If zero, take original width and height of image
    // If between 0 and 1, multiply by original width and height (acts as a percentage)
    // If greater than one, use as a forced width/height for all of the images
    largeFeatureWidth :   0,
    largeFeatureHeight:		0,
    smallFeatureWidth:    .5,
    smallFeatureHeight:		.5,
    containerWidth:       0,
    containerHeight:      0,
    fit_containerWidth:   0,
    bwg_number:           0,   
    // how much to pad the top of the carousel
    topPadding:           20,
    // spacing between the sides of the container
    sidePadding:          50,
    // the additional offset to pad the side features from the top of the carousel
    smallFeatureOffset:		50,
    //smallFeature parameters
    smallFeaturePar:      0,
    // indicates which feature to start the carousel at
    startingFeature:      1,
    // speed in milliseconds it takes to rotate the carousel
    carouselSpeed:        300,
    // time in milliseconds to set interval to autorotate the carousel
    // set to zero to disable it, negative to go left
    autoPlay:             4000,
    //imagecounts
    imagecount:           7,
    enable_image_title:   0,
    // with autoplay enabled, set this option to true to have the carousel pause rotating
    // when a user hovers over any feature
    pauseOnHover:         true,
    // with autoplay enabled, set this option to completely stop the autorotate functionality
    stopOnHover:          false,
    // numbered blips can appear and be used to track the currently centered feature, as well as 
    // allow the user to click a number to move to that feature. Set to false to not process these at all
    // and true to process and display them//and true to process and display them
    trackerIndividual:    true,
    // a summation of the features can also be used to display an "x Of y" style of tracking
    // this can be combined with the above option as well
    trackerSummation:     true,
    // true to preload all images in the carousel before displaying anything. If this is set to false,
    // you will probably need to set a fixed width/height to prevent strangeness
    preload:             false,
    // Will only display this many features in the carousel
    // set to zero to disable
    displayCutoff:        0,
    // an easing can be specified for the animation of the carousel
    animationEasing:      'swing',
    // selector for the left arrow of the carousel
    leftButtonTag:        '#bwg_carousel-left', 
    // selector for the right arrow of the carousel
    rightButtonTag:       '#bwg_carousel-right',
    // display captions below the image instead of on top
    captionBelow:         false,
    // callback function for when a feature has animated to the center
    movedToCenter:        $.noop,
    // callback function for when feature left center
    leavingCenter:        $.noop,
    // callback function for when center feature was clicked
    clickedCenter:        $.noop
  };
  
})(jQuery);
// source --> https://sncabinetsandclosets.com/wp-content/plugins/photo-gallery/js/3DEngine/3DEngine.js?ver=1.0.0 

/*
* DisplayObject3D ----------------------------------------------
*/
var DisplayObject3D = function(){
	return this;
};

DisplayObject3D.prototype._x = 0;
DisplayObject3D.prototype._y = 0;

//Create 3d Points
DisplayObject3D.prototype.make3DPoint = function(x,y,z) {
	var point = {};
	point.x = x;
	point.y = y;
	point.z = z;
	return point;
};

//Create 2d Points
DisplayObject3D.prototype.make2DPoint = function(x, y, depth, scaleFactor){
	var point = {};
	point.x = x;
	point.y = y;
	point.depth = depth;
	point.scaleFactor = scaleFactor;
	return point;
};

DisplayObject3D.prototype.container = undefined;
DisplayObject3D.prototype.pointsArray = [];

DisplayObject3D.prototype.init = function (container){
	
	this.container = container;
	this.containerId = this.container.attr("id");
	
	//if there isn't a ul than it creates a list of +'s
	if (container.has("ul").length === 0){
		for (i=0; i < this.pointsArray.length; i++){
			this.container.append('<b id="tags_cloud_item'+i+'">+</b>');
		}
	}
};	

/*
* DisplayObject3D End ----------------------------------------------
*/


/*
* Camera3D ----------------------------------------------
*/
var Camera3D = function (){};

Camera3D.prototype.x = 0;
Camera3D.prototype.y = 0;
Camera3D.prototype.z = 500;
Camera3D.prototype.focalLength = 1000;

Camera3D.prototype.scaleRatio = function(item){
	return this.focalLength / (this.focalLength + item.z - this.z);
};

Camera3D.prototype.init = function (x, y, z, focalLength){
	this.x = x;
	this.y = y;
	this.z = z;
	this.focalLength = focalLength;
};


/*
* Camera3D End ----------------------------------------------
*/


/*
* Object3D ----------------------------------------------
*/
var Object3D = function (container){
	this.container = container;
};

Object3D.prototype.objects = [];

Object3D.prototype.addChild = function (object3D){		
	this.objects.push(object3D);	
	object3D.init(this.container);	
	return object3D;
};

/*
* Object3D End ----------------------------------------------
*/


/*
* Scene3D ----------------------------------------------
*/

var Scene3D = function (){};

Scene3D.prototype.sceneItems = [];
Scene3D.prototype.addToScene = function (object){
	this.sceneItems.push(object);
};

Scene3D.prototype.Transform3DPointsTo2DPoints = function(points, axisRotations, camera){
	var TransformedPointsArray = [];
	var sx = Math.sin(axisRotations.x);
	var cx = Math.cos(axisRotations.x);
	var sy = Math.sin(axisRotations.y);
	var cy = Math.cos(axisRotations.y);
	var sz = Math.sin(axisRotations.z);
	var cz = Math.cos(axisRotations.z);
	var x,y,z, xy,xz, yx,yz, zx,zy, scaleFactor;

	var i = points.length;
	
	while (i--){
		x = points[i].x;
		y = points[i].y;
		z = points[i].z;

		// rotation around x
		xy = cx * y - sx * z;
		xz = sx * y + cx * z;
		// rotation around y
		yz = cy * xz - sy * x;
		yx = sy * xz + cy * x;
		// rotation around z
		zx = cz * yx - sz * xy;
		zy = sz * yx + cz * xy;
		
		scaleFactor = camera.focalLength / (camera.focalLength + yz);
		x = zx * scaleFactor;
		y = zy * scaleFactor;
		z = yz;
		
		var displayObject = new DisplayObject3D();
		TransformedPointsArray[i] = displayObject.make2DPoint(x, y, -z, scaleFactor);
	}
	
	return TransformedPointsArray;
};

Scene3D.prototype.renderCamera = function (camera){

	for(var i = 0 ; i < this.sceneItems.length; i++){

		var obj = this.sceneItems[i].objects[0];
	
		var screenPoints = this.Transform3DPointsTo2DPoints(obj.pointsArray, axisRotation, camera);
		
		var hasList = (document.getElementById(obj.containerId).getElementsByTagName("ul").length > 0);
		
		for (k=0; k < obj.pointsArray.length; k++){
			var currItem = null;
			
			if (hasList){
				currItem = document.getElementById(obj.containerId).getElementsByTagName("ul")[0].getElementsByTagName("li")[k];
			}else{				
				currItem = document.getElementById(obj.containerId).getElementsByTagName("*")[k];
			}
			
			if(currItem){
        
				currItem._x = screenPoints[k].x;
				currItem._y = screenPoints[k].y;
				currItem.scale = screenPoints[k].scaleFactor;
				
				currItem.style.position = "absolute";
				currItem.style.top = (currItem._y + jQuery("#" + obj.containerId).height() * 0.4)+'px';
				currItem.style.left = (currItem._x + jQuery("#" + obj.containerId).width() * 0.4)+'px';
				currItem.style.fontSize = 100 * currItem.scale + '%';
        
				jQuery(currItem).css({opacity:(currItem.scale-.5)});
        
        curChild = jQuery(currItem).find("#imgg");
        if (curChild) {
          jQuery(currItem).css("zIndex", Math.round(currItem.scale * 100));
          curChild.css({maxWidth:(currItem.scale*50)});
          curChild.css({maxHeight:(currItem.scale*50)});
        }
			}			
		}
	}
};

/*
* Scene3D End ----------------------------------------------
*/


//Center for rotation
var axisRotation = new DisplayObject3D().make3DPoint(0,0,0);
// source --> https://sncabinetsandclosets.com/wp-content/plugins/photo-gallery/js/3DEngine/Sphere.js?ver=1.0.0 
var Sphere = function (radius, sides, numOfItems){
  
	for (var j = sides ; j > 0; j--){	
		for (var i = numOfItems / sides ; i > 0; i--)
		{
      var angle = i * Math.PI / (numOfItems / sides + 1);
      var angleB = j * Math.PI * 2 / (sides);
			
      var x =   Math.sin(angleB) * Math.sin(angle) * radius;
			var y =  Math.cos(angleB) * Math.sin(angle) * radius;
			var z =  Math.cos(angle) * radius;
      
      this.pointsArray.push(this.make3DPoint(x,y,z));
		}	
	};
};

Sphere.prototype = new DisplayObject3D();
// source --> https://sncabinetsandclosets.com/wp-content/themes/executive-pro/js/responsive-menu.js?ver=1.0.0 
jQuery(function( $ ){

	$("header .genesis-nav-menu, .nav-primary .genesis-nav-menu").addClass("responsive-menu").before('<div class="responsive-menu-icon"></div>');

	$(".responsive-menu-icon").click(function(){
		$(this).next("header .genesis-nav-menu, .nav-primary .genesis-nav-menu").slideToggle();
	});

	$(window).resize(function(){
		if(window.innerWidth > 800) {
			$("header .genesis-nav-menu, .nav-primary .genesis-nav-menu, nav .sub-menu").removeAttr("style");
			$(".responsive-menu > .menu-item").removeClass("menu-open");
		}
	});

	$(".responsive-menu > .menu-item").click(function(event){
		if (event.target !== this)
		return;
			$(this).find(".sub-menu:first").slideToggle(function() {
			$(this).parent().toggleClass("menu-open");
		});
	});

});