/*
KVR Plugins+Extras
lightBox 0.6 (kvr mod)
Star Rating (no ver)
blockUI 2.70
Sparklines 2.1.2
qsort (no ver)
History 1.7.1
SoundManager 2.97a.20150601
Sticky 1.0.4 (+Jun 8, 2016; 6c27d52)
Scrollstop 1.2.0
Visible Jul 10 2014
*/

/*
  jQuery blockUI 2.70.0-2014.11.23 malsup.com/jquery/block (C) 2007-2014 M. Alsup.
  Dual license (MIT/GPL): opensource.org/licenses/mit-license.php gnu.org/licenses/gpl.html
*/
(function(){
"use strict";
	function setup($) {
		$.fn._fadeIn = $.fn.fadeIn;
		var noOp = $.noop || function() {};
		var msie = /MSIE/.test(navigator.userAgent);
		var ie6  = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent);
		var mode = document.documentMode || 0;
		var setExpr = $.isFunction( document.createElement('div').style.setExpression );
		$.blockUI   = function(opts) { install(window, opts); };
		$.unblockUI = function(opts) { remove(window, opts); };
		$.growlUI = function(title, message, timeout, onClose) {
			var $m = $('<div class="growlUI"></div>');
			if (title) $m.append('<h1>'+title+'</h1>');
			if (message) $m.append('<h2>'+message+'</h2>');
			if (timeout === undefined) timeout = 3000;

			var callBlock = function(opts) {
				opts = opts || {};
				$.blockUI({
					message: $m,
					fadeIn : typeof opts.fadeIn  !== 'undefined' ? opts.fadeIn  : 700,
					fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000,
					timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout,
					centerY: false,
					showOverlay: false,
					onUnblock: onClose,
					css: $.blockUI.defaults.growlCSS
				});
			};

			callBlock();
			var nonmousedOpacity = $m.css('opacity');
			$m.mouseover(function() {
				callBlock({
					fadeIn: 0,
					timeout: 30000
				});

				var displayBlock = $('.blockMsg');
				displayBlock.stop();
				displayBlock.fadeTo(300, 1);
			}).mouseout(function() {
				$('.blockMsg').fadeOut(1000);
			});
		};

		$.fn.block = function(opts) {
			if ( this[0] === window ) {
				$.blockUI( opts );
				return this;
			}
			var fullOpts = $.extend({}, $.blockUI.defaults, opts || {});
			this.each(function() {
				var $el = $(this);
				if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked'))
					return;
				$el.unblock({ fadeOut: 0 });
			});

			return this.each(function() {
				if ($.css(this,'position') == 'static') {
					this.style.position = 'relative';
					$(this).data('blockUI.static', true);
				}
				this.style.zoom = 1;
				install(this, opts);
			});
		};

		$.fn.unblock = function(opts) {
			if ( this[0] === window ) {
				$.unblockUI( opts );
				return this;
			}
			return this.each(function() {
				remove(this, opts);
			});
		};

		$.blockUI.version = 2.70;
		$.blockUI.defaults = {
			message:  '<h1>Please wait...</h1>',
			title: null,
			draggable: true,
			theme: false,
			css: {
				padding:	0,
				margin:		0,
				width:		'30%',
				top:		'40%',
				left:		'35%',
				textAlign:	'center',
				color:		'#000',
				border:		'3px solid #aaa',
				backgroundColor:'#fff',
				cursor:		'wait'
			},
			themedCSS: {
				width:	'30%',
				top:	'40%',
				left:	'35%'
			},
			overlayCSS:  {
				backgroundColor:	'#000',
				opacity:			0.6,
				cursor:				'wait'
			},
			cursorReset: 'default',
			growlCSS: {
				width:		'350px',
				top:		'10px',
				left:		'',
				right:		'10px',
				border:		'none',
				padding:	'5px',
				opacity:	0.6,
				cursor:		'default',
				color:		'#fff',
				backgroundColor: '#000',
				'-webkit-border-radius':'10px',
				'-moz-border-radius':	'10px',
				'border-radius':		'10px'
			},
			iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
			forceIframe: false,
			baseZ: 1000,
			centerX: true,
			centerY: true,
			allowBodyStretch: true,
			bindEvents: true,
			constrainTabKey: true,
			fadeIn:  200,
			fadeOut:  400,
			timeout: 0,
			showOverlay: true,
			focusInput: true,
      focusableElements: ':input:enabled:visible',
			onBlock: null,
			onUnblock: null,
			onOverlayClick: null,
			quirksmodeOffsetHack: 4,
			blockMsgClass: 'blockMsg',
			ignoreIfBlocked: false
		};

		var pageBlock = null;
		var pageBlockEls = [];

		function install(el, opts) {
			var css, themedCSS;
			var full = (el == window);
			var msg = (opts && opts.message !== undefined ? opts.message : undefined);
			opts = $.extend({}, $.blockUI.defaults, opts || {});

			if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked'))
				return;

			opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
			css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
			if (opts.onOverlayClick)
				opts.overlayCSS.cursor = 'pointer';

			themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
			msg = msg === undefined ? opts.message : msg;

			if (full && pageBlock)
				remove(window, {fadeOut:0});

			if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
				var node = msg.jquery ? msg[0] : msg;
				var data = {};
				$(el).data('blockUI.history', data);
				data.el = node;
				data.parent = node.parentNode;
				data.display = node.style.display;
				data.position = node.style.position;
				if (data.parent)
					data.parent.removeChild(node);
			}

			$(el).data('blockUI.onUnblock', opts.onUnblock);
			var z = opts.baseZ;

			var lyr1, lyr2, lyr3, s;
			if (msie || opts.forceIframe)
				lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>');
			else
				lyr1 = $('<div class="blockUI" style="display:none"></div>');

			if (opts.theme)
				lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>');
			else
				lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');

			if (opts.theme && full) {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">';
				if ( opts.title ) {
					s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
				}
				s += '<div class="ui-widget-content ui-dialog-content"></div>';
				s += '</div>';
			}
			else if (opts.theme) {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">';
				if ( opts.title ) {
					s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>';
				}
				s += '<div class="ui-widget-content ui-dialog-content"></div>';
				s += '</div>';
			}
			else if (full) {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>';
			}
			else {
				s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>';
			}
			lyr3 = $(s);

			if (msg) {
				if (opts.theme) {
					lyr3.css(themedCSS);
					lyr3.addClass('ui-widget-content');
				}
				else
					lyr3.css(css);
			}

			if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/)
				lyr2.css(opts.overlayCSS);
			lyr2.css('position', full ? 'fixed' : 'absolute');

			if (msie || opts.forceIframe)
				lyr1.css('opacity',0.0);

			var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
			$.each(layers, function() {
				this.appendTo($par);
			});

			if (opts.theme && opts.draggable && $.fn.draggable) {
				lyr3.draggable({
					handle: '.ui-dialog-titlebar',
					cancel: 'li'
				});
			}

			var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0);
			if (ie6 || expr) {
				if (full && opts.allowBodyStretch && $.support.boxModel)
					$('html,body').css('height','100%');

				if ((ie6 || !$.support.boxModel) && !full) {
					var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
					var fixT = t ? '(0 - '+t+')' : 0;
					var fixL = l ? '(0 - '+l+')' : 0;
				}

				$.each(layers, function(i,o) {
					var s = o[0].style;
					s.position = 'absolute';
					if (i < 2) {
						if (full)
							s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"');
						else
							s.setExpression('height','this.parentNode.offsetHeight + "px"');
						if (full)
							s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"');
						else
							s.setExpression('width','this.parentNode.offsetWidth + "px"');
						if (fixL) s.setExpression('left', fixL);
						if (fixT) s.setExpression('top', fixT);
					}
					else if (opts.centerY) {
						if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
						s.marginTop = 0;
					}
					else if (!opts.centerY && full) {
						var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0;
						var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
						s.setExpression('top',expression);
					}
				});
			}

			if (msg) {
				if (opts.theme)
					lyr3.find('.ui-widget-content').append(msg);
				else
					lyr3.append(msg);
				if (msg.jquery || msg.nodeType)
					$(msg).show();
			}

			if ((msie || opts.forceIframe) && opts.showOverlay)
				lyr1.show();
			if (opts.fadeIn) {
				var cb = opts.onBlock ? opts.onBlock : noOp;
				var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
				var cb2 = msg ? cb : noOp;
				if (opts.showOverlay)
					lyr2._fadeIn(opts.fadeIn, cb1);
				if (msg)
					lyr3._fadeIn(opts.fadeIn, cb2);
			}
			else {
				if (opts.showOverlay)
					lyr2.show();
				if (msg)
					lyr3.show();
				if (opts.onBlock)
					opts.onBlock.bind(lyr3)();
			}

			bind(1, el, opts);

			if (full) {
				pageBlock = lyr3[0];
				pageBlockEls = $(opts.focusableElements,pageBlock);
				if (opts.focusInput)
					setTimeout(focus, 20);
			}
			else
				center(lyr3[0], opts.centerX, opts.centerY);

			if (opts.timeout) {
				var to = setTimeout(function() {
					if (full)
						$.unblockUI(opts);
					else
						$(el).unblock(opts);
				}, opts.timeout);
				$(el).data('blockUI.timeout', to);
			}
		}

		function remove(el, opts) {
			var count;
			var full = (el == window);
			var $el = $(el);
			var data = $el.data('blockUI.history');
			var to = $el.data('blockUI.timeout');
			if (to) {
				clearTimeout(to);
				$el.removeData('blockUI.timeout');
			}
			opts = $.extend({}, $.blockUI.defaults, opts || {});
			bind(0, el, opts);

			if (opts.onUnblock === null) {
				opts.onUnblock = $el.data('blockUI.onUnblock');
				$el.removeData('blockUI.onUnblock');
			}

			var els;
			if (full)
				els = $('body').children().filter('.blockUI').add('body > .blockUI');
			else
				els = $el.find('>.blockUI');

			if ( opts.cursorReset ) {
				if ( els.length > 1 )
					els[1].style.cursor = opts.cursorReset;
				if ( els.length > 2 )
					els[2].style.cursor = opts.cursorReset;
			}

			if (full)
				pageBlock = pageBlockEls = null;

			if (opts.fadeOut) {
				count = els.length;
				els.stop().fadeOut(opts.fadeOut, function() {
					if ( --count === 0)
						reset(els,data,opts,el);
				});
			}
			else
				reset(els, data, opts, el);
		}

		function reset(els,data,opts,el) {
			var $el = $(el);
			if ( $el.data('blockUI.isBlocked') )
				return;

			els.each(function(i,o) {
				if (this.parentNode)
					this.parentNode.removeChild(this);
			});

			if (data && data.el) {
				data.el.style.display = data.display;
				data.el.style.position = data.position;
				data.el.style.cursor = 'default';
				if (data.parent)
					data.parent.appendChild(data.el);
				$el.removeData('blockUI.history');
			}

			if ($el.data('blockUI.static')) {
				$el.css('position', 'static');
			}

			if (typeof opts.onUnblock == 'function')
				opts.onUnblock(el,opts);

			var body = $(document.body), w = body.width(), cssW = body[0].style.width;
			body.width(w-1).width(w);
			body[0].style.width = cssW;
		}

		function bind(b, el, opts) {
			var full = el == window, $el = $(el);

			if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
				return;

			$el.data('blockUI.isBlocked', b);

			if (!full || !opts.bindEvents || (b && !opts.showOverlay))
				return;

			var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove';
			if (b)
				$(document).bind(events, opts, handler);
			else
				$(document).unbind(events, handler);

		}

		function handler(e) {
			if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) {
				if (pageBlock && e.data.constrainTabKey) {
					var els = pageBlockEls;
					var fwd = !e.shiftKey && e.target === els[els.length-1];
					var back = e.shiftKey && e.target === els[0];
					if (fwd || back) {
						setTimeout(function(){focus(back);},10);
						return false;
					}
				}
			}
			var opts = e.data;
			var target = $(e.target);
			if (target.hasClass('blockOverlay') && opts.onOverlayClick)
				opts.onOverlayClick(e);

			if (target.parents('div.' + opts.blockMsgClass).length > 0)
				return true;

			return target.parents().children().filter('div.blockUI').length === 0;
		}

		function focus(back) {
			if (!pageBlockEls)
				return;
			var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
			if (e)
				e.focus();
		}

		function center(el, x, y) {
			var p = el.parentNode, s = el.style;
			var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
			var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
			if (x) s.left = l > 0 ? (l+'px') : '0';
			if (y) s.top  = t > 0 ? (t+'px') : '0';
		}

		function sz(el, p) {
			return parseInt($.css(el,p),10)||0;
		}

	}

	if (typeof define === 'function' && define.amd && define.amd.jQuery) {
		define(['jquery'], setup);
	} else {
		setup(jQuery);
	}

})();

/*
  jQuery lightBox 0.5 (kvr mod) (11-Apr-2008)
  Inspired+based on Lightbox 2 by Lokesh Dhakar huddletogether.com/projects/lightbox2
  (C)2008 Leandro Vieira Pinho - leandrovieira.com/projects/jquery/lightbox
  License CC Attribution-No Derivative Works 2.5 Brazil - creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
*/
(function($){
  $.fn.lightBox = function(settings) {
    settings = jQuery.extend({
      overlayBgColor: '#000',
      overlayOpacity: 0.5,
      fixedNavigation: false,
      imageLoading: '//static.kvraudio.com/inc/lightbox/lightbox-ico-loading.gif',
      imageBtnPrev: '//static.kvraudio.com/inc/lightbox/lightbox-btn-prev.gif',
      imageBtnNext: '//static.kvraudio.com/inc/lightbox/lightbox-btn-next.gif',
      imageBtnClose:'//static.kvraudio.com/inc/lightbox/lightbox-btn-close.gif',
      imageBlank:   '//static.kvraudio.com/inc/lightbox/lightbox-blank.gif',
      containerBorderSize:  10,
      containerResizeSpeed: 400,
      txtImage:   'Image',
      txtOf:      'of',
      keyToClose: 'c',
      keyToPrev:  'p',
      keyToNext:  'n',
      imageArray: [],
      activeImage:0
    },settings);
    var jQueryMatchedObj = this;
    function _initialize() {
      _start(this,jQueryMatchedObj);
      return false;
    }

    function _start(objClicked,jQueryMatchedObj) {
      $('embed, object, select').css({ 'visibility' : 'hidden' });
      _set_interface();
      settings.imageArray.length = 0;
      settings.activeImage = 0;
      if ( jQueryMatchedObj.length == 1 ) {
        settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title'),objClicked.getAttribute('class')));
      } else {
        for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
          settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title'),jQueryMatchedObj[i].getAttribute('class')));
        }
      }
      while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
        settings.activeImage++;
      }
      _set_image_to_view();
    }

    function _set_interface() {
      $('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><span class="kvrloadingcss3an1" style="margin: 0 auto;"></span></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');
      var arrPageSizes = ___getPageSize();
      $('#jquery-overlay').css({
        backgroundColor:  settings.overlayBgColor,
        opacity:      settings.overlayOpacity,
        width:        arrPageSizes[0],
        height:       arrPageSizes[1]
      }).fadeIn();
      var arrPageScroll = ___getPageScroll();
      $('#jquery-lightbox').css({
        top:  arrPageScroll[1] + (arrPageSizes[3] / 10),
        left: arrPageScroll[0]
      }).show();
      $('#jquery-overlay,#jquery-lightbox').click(function() {
        _finish();
      });
      $('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
        _finish();
        return false;
      });
      $(window).resize(function() {
        var arrPageSizes = ___getPageSize();
        $('#jquery-overlay').css({
          width:    arrPageSizes[0],
          height:   arrPageSizes[1]
        });
        var arrPageScroll = ___getPageScroll();
        $('#jquery-lightbox').css({
          top:  arrPageScroll[1] + (arrPageSizes[3] / 10),
          left: arrPageScroll[0]
        });
      });
    }

    function _set_image_to_view() {
      $('#lightbox-loading').show();
      if ( settings.fixedNavigation ) {
        $('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
      } else {
        $('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
      }
      var objImagePreloader = new Image();
      objImagePreloader.onload = function() {

        // retina / hidpi so half display size
        if(settings.imageArray[settings.activeImage][2].search(/kvrhidpi/) > 0)
        {
          objImagePreloader.width = objImagePreloader.width / 2;
          objImagePreloader.height = objImagePreloader.height / 2;
        }

        // if bigger than window shrink it
        var kvrWinHeight = $(window).height() - 200;

        if(kvrWinHeight < objImagePreloader.height)
        {
          var kvrMaxHeight = kvrWinHeight;
          var kvrRatio = objImagePreloader.height / kvrMaxHeight;
          objImagePreloader.width = objImagePreloader.width / kvrRatio;
          objImagePreloader.height = kvrMaxHeight;
        }else{
          var kvrMaxHeight = 'auto';
        }

        $('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]).css("max-height",kvrMaxHeight);
        _resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
        objImagePreloader.onload=function(){};
      };
      objImagePreloader.src = settings.imageArray[settings.activeImage][0];
    };

    function _resize_container_image_box(intImageWidth,intImageHeight) {
      var intCurrentWidth = $('#lightbox-container-image-box').width();
      var intCurrentHeight = $('#lightbox-container-image-box').height();
      var intWidth = (intImageWidth + (settings.containerBorderSize * 2));
      var intHeight = (intImageHeight + (settings.containerBorderSize * 2));
      var intDiffW = intCurrentWidth - intWidth;
      var intDiffH = intCurrentHeight - intHeight;
      $('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
      if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
        ___pause(100);
      }
      $('#lightbox-container-image-data-box').css({ width: intImageWidth });
      $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
    };

    function _show_image() {
      $('#lightbox-loading').hide();
      $('#lightbox-image').fadeIn(function() {
        _show_image_data();
        _set_navigation();
      });
      _preload_neighbor_images();
    };

    function _show_image_data() {
      $('#lightbox-container-image-data-box').slideDown('fast');
      $('#lightbox-image-details-caption').hide();
      if ( settings.imageArray[settings.activeImage][1] ) {
        $('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
      }
      if ( settings.imageArray.length > 1 ) {
        $('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
      }
    }

    function _set_navigation() {
      $('#lightbox-nav').show();
      $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
      if ( settings.activeImage != 0 ) {
        if ( settings.fixedNavigation ) {
          $('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' })
            .unbind()
            .bind('click',function() {
              settings.activeImage = settings.activeImage - 1;
              _set_image_to_view();
              return false;
            });
        } else {
          $('#lightbox-nav-btnPrev').unbind().hover(function() {
            $(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
          },function() {
            $(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
          }).show().bind('click',function() {
            settings.activeImage = settings.activeImage - 1;
            _set_image_to_view();
            return false;
          });
        }
      } else {
        $('#lightbox-nav-btnPrev').unbind().click(function() {
          _finish();
          return false;
        });
      }

      if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
        if ( settings.fixedNavigation ) {
          $('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' })
            .unbind()
            .bind('click',function() {
              settings.activeImage = settings.activeImage + 1;
              _set_image_to_view();
              return false;
            });
        } else {
          $('#lightbox-nav-btnNext').unbind().hover(function() {
            $(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' });
          },function() {
            $(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
          }).show().bind('click',function() {
            settings.activeImage = settings.activeImage + 1;
            _set_image_to_view();
            return false;
          });
        }
      } else {
        $('#lightbox-nav-btnNext').unbind().click(function(){
          _finish();
          return false;
        });
      }
      _enable_keyboard_navigation();
    }

    function _enable_keyboard_navigation() {
      $(document).keydown(function(objEvent) {
        _keyboard_action(objEvent);
      });
    }

    function _disable_keyboard_navigation() {
      $(document).unbind();
    }

    function _keyboard_action(objEvent) {
      if ( objEvent == null ) {
        keycode = event.keyCode;
        escapeKey = 27;
      } else {
        keycode = objEvent.keyCode;
        escapeKey = objEvent.DOM_VK_ESCAPE;
      }
      key = String.fromCharCode(keycode).toLowerCase();
      if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
        _finish();
      }
      if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
        if ( settings.activeImage != 0 ) {
          settings.activeImage = settings.activeImage - 1;
          _set_image_to_view();
          _disable_keyboard_navigation();
        }
      }
      if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
        if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
          settings.activeImage = settings.activeImage + 1;
          _set_image_to_view();
          _disable_keyboard_navigation();
        }
      }
    }

    function _preload_neighbor_images() {
      if ( (settings.imageArray.length -1) > settings.activeImage ) {
        objNext = new Image();
        objNext.src = settings.imageArray[settings.activeImage + 1][0];
      }
      if ( settings.activeImage > 0 ) {
        objPrev = new Image();
        objPrev.src = settings.imageArray[settings.activeImage -1][0];
      }
    }

    function _finish() {
      $('#jquery-lightbox').remove();
      $('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
      $('embed, object, select').css({ 'visibility' : 'visible' });
    }

    function ___getPageSize() {
      var xScroll, yScroll;
      if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
      } else if (document.body.scrollHeight > document.body.offsetHeight){
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
      } else {
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
      }
      var windowWidth, windowHeight;
      if (self.innerHeight) {
        if(document.documentElement.clientWidth){
          windowWidth = document.documentElement.clientWidth;
        } else {
          windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientHeight) {
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
      } else if (document.body) {
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
      }

      if(yScroll < windowHeight){
        pageHeight = windowHeight;
      } else {
        pageHeight = yScroll;
      }

      if(xScroll < windowWidth){
        pageWidth = xScroll;
      } else {
        pageWidth = windowWidth;
      }
      arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
      return arrayPageSize;
    };

    function ___getPageScroll() {
      var xScroll, yScroll;
      if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
      } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
      } else if (document.body) {
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;
      }
      arrayPageScroll = new Array(xScroll,yScroll);
      return arrayPageScroll;
    };

     function ___pause(ms) {
      var date = new Date();
      curDate = null;
      do { var curDate = new Date(); }
      while ( curDate - date < ms);
     };

    return this.unbind('click').click(_initialize);
  };
})(jQuery);

/*
  jQuery Star Rating System by Ritesh Agrawal (21-Nov-2006)
  Inspiration: Will Stuckey's star rating sandbox.wilstuckey.com/jquery-ratings
  php.scripts.psu.edu/rja171/widgets/rating.php
*/
(function($){
  jQuery.fn.rating = function(url,options){
    if(url == null) return;
    var settings = {
      url       : url,
      maxvalue  : 5,
      curvalue  : 0
    };

    if(options){
      jQuery.extend(settings, options);
    };
    jQuery.extend(settings, {cancel: (settings.maxvalue > 1) ? true : false});
    var container = jQuery(this);
    jQuery.extend(container,{
      averageRating: settings.curvalue,
      url: settings.url
    });

    for(var i= 0; i <= settings.maxvalue ; i++){
      var size = i
      if (i == 0) {
        if(settings.cancel == true){
          var div = '<div class="cancel"><a href="#0" title="Cancel Rating">Cancel Rating</a></div>';
          container.append(div);
        }
      }else{
        var div = '<div class="star"><a href="#'+i+'" title="Give it '+i+'/'+size+'">'+i+'</a></div>';
        container.append(div);
      }
    }

    var stars = jQuery(container).children('.star');
    var cancel = jQuery(container).children('.cancel');

    stars.mouseover(function(){
      event.drain();
      event.fill(this);
    }).mouseout(function(){
      event.drain();
      event.reset();
    }).focus(function(){
      event.drain();
      event.fill(this)
    }).blur(function(){
      event.drain();
      event.reset();
    });

    stars.click(function(){
      $("#bratemessage").empty().remove();
      if(settings.cancel == true){
        settings.curvalue = stars.index(this) + 1;
        jQuery.post(container.url, {
          "rating": jQuery(this).children('a')[0].href.split('#')[1]
        },
        function(data){
          var div = '<div id="bratemessage" style="clear: both;">'+data+'</div>';
          container.append(div);
        });
        return false;
      }else if(settings.maxvalue == 1){
        settings.curvalue = (settings.curvalue == 0) ? 1 : 0;
        $(this).toggleClass('on');
        jQuery.post(container.url, {
          "rating": jQuery(this).children('a')[0].href.split('#')[1]
        });
        return false;
      }
      return true;
    });

    if(cancel){
      cancel.mouseover(function(){
        event.drain();
        jQuery(this).addClass('on')
      }).mouseout(function(){
        event.reset();
        jQuery(this).removeClass('on')
      }).focus(function(){
        event.drain();
        jQuery(this).addClass('on')
      }).blur(function(){
        event.reset();
        jQuery(this).removeClass('on')
      });

      cancel.click(function(){
        $("#bratemessage").empty().remove();
        var div = '<div id="bratemessage" style="clear: both;">Ratings must be between 1 and 5</div>';
        container.append(div);
        return false;
      });
    }

    var event = {
      fill: function(el){
        var index = stars.index(el) + 1;
        stars
        .children('a').css('width', '100%').end()
        .slice(0,index).addClass('hover').end();
      },
      drain: function() {
        stars
        .filter('.on').removeClass('on').end()
        .filter('.hover').removeClass('hover').end();
      },
      reset: function(){
        stars.slice(0,settings.curvalue).addClass('on').end();
      }
    }
    event.reset();
    return(this);
  }
})(jQuery);

// jquery.sparkline 2.1.2 - omnipotent.net/jquery.sparkline - New BSD License
(function(a,b,c){(function(a){typeof define=="function"&&define.amd?define(["jquery"],a):jQuery&&!jQuery.fn.sparkline&&a(jQuery)})(function(d){"use strict";var e={},f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L=0;f=function(){return{common:{type:"line",lineColor:"#00f",fillColor:"#cdf",defaultPixelsPerValue:3,width:"auto",height:"auto",composite:!1,tagValuesAttribute:"values",tagOptionsPrefix:"spark",enableTagOptions:!1,enableHighlight:!0,highlightLighten:1.4,tooltipSkipNull:!0,tooltipPrefix:"",tooltipSuffix:"",disableHiddenCheck:!1,numberFormatter:!1,numberDigitGroupCount:3,numberDigitGroupSep:",",numberDecimalMark:".",disableTooltips:!1,disableInteraction:!1},line:{spotColor:"#f80",highlightSpotColor:"#5f5",highlightLineColor:"#f22",spotRadius:1.5,minSpotColor:"#f80",maxSpotColor:"#f80",lineWidth:1,normalRangeMin:c,normalRangeMax:c,normalRangeColor:"#ccc",drawNormalOnTop:!1,chartRangeMin:c,chartRangeMax:c,chartRangeMinX:c,chartRangeMaxX:c,tooltipFormat:new h('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{y}}{{suffix}}')},bar:{barColor:"#3366cc",negBarColor:"#f44",stackedBarColor:["#3366cc","#dc3912","#ff9900","#109618","#66aa00","#dd4477","#0099c6","#990099"],zeroColor:c,nullColor:c,zeroAxis:!0,barWidth:4,barSpacing:1,chartRangeMax:c,chartRangeMin:c,chartRangeClip:!1,colorMap:c,tooltipFormat:new h('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{value}}{{suffix}}')},tristate:{barWidth:4,barSpacing:1,posBarColor:"#6f6",negBarColor:"#f44",zeroBarColor:"#999",colorMap:{},tooltipFormat:new h('<span style="color: {{color}}">&#9679;</span> {{value:map}}'),tooltipValueLookups:{map:{"-1":"Loss",0:"Draw",1:"Win"}}},discrete:{lineHeight:"auto",thresholdColor:c,thresholdValue:0,chartRangeMax:c,chartRangeMin:c,chartRangeClip:!1,tooltipFormat:new h("{{prefix}}{{value}}{{suffix}}")},bullet:{targetColor:"#f33",targetWidth:3,performanceColor:"#33f",rangeColors:["#d3dafe","#a8b6ff","#7f94ff"],base:c,tooltipFormat:new h("{{fieldkey:fields}} - {{value}}"),tooltipValueLookups:{fields:{r:"Range",p:"Performance",t:"Target"}}},pie:{offset:0,sliceColors:["#3366cc","#dc3912","#ff9900","#109618","#66aa00","#dd4477","#0099c6","#990099"],borderWidth:0,borderColor:"#000",tooltipFormat:new h('<span style="color: {{color}}">&#9679;</span> {{value}} ({{percent.1}}%)')},box:{raw:!1,boxLineColor:"#000",boxFillColor:"#cdf",whiskerColor:"#000",outlierLineColor:"#333",outlierFillColor:"#fff",medianColor:"#f00",showOutliers:!0,outlierIQR:1.5,spotRadius:1.5,target:c,targetColor:"#4a2",chartRangeMax:c,chartRangeMin:c,tooltipFormat:new h("{{field:fields}}: {{value}}"),tooltipFormatFieldlistKey:"field",tooltipValueLookups:{fields:{lq:"Lower Quartile",med:"Median",uq:"Upper Quartile",lo:"Left Outlier",ro:"Right Outlier",lw:"Left Whisker",rw:"Right Whisker"}}}}},E='.jqstooltip { position: absolute;left: 0px;top: 0px;visibility: hidden;background: rgb(0, 0, 0) transparent;background-color: rgba(0,0,0,0.6);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";color: white;font: 10px arial, san serif;text-align: left;white-space: nowrap;padding: 5px;border: 1px solid white;z-index: 10000;}.jqsfield { color: white;font: 10px arial, san serif;text-align: left;}',g=function(){var a,b;return a=function(){this.init.apply(this,arguments)},arguments.length>1?(arguments[0]?(a.prototype=d.extend(new arguments[0],arguments[arguments.length-1]),a._super=arguments[0].prototype):a.prototype=arguments[arguments.length-1],arguments.length>2&&(b=Array.prototype.slice.call(arguments,1,-1),b.unshift(a.prototype),d.extend.apply(d,b))):a.prototype=arguments[0],a.prototype.cls=a,a},d.SPFormatClass=h=g({fre:/\{\{([\w.]+?)(:(.+?))?\}\}/g,precre:/(\w+)\.(\d+)/,init:function(a,b){this.format=a,this.fclass=b},render:function(a,b,d){var e=this,f=a,g,h,i,j,k;return this.format.replace(this.fre,function(){var a;return h=arguments[1],i=arguments[3],g=e.precre.exec(h),g?(k=g[2],h=g[1]):k=!1,j=f[h],j===c?"":i&&b&&b[i]?(a=b[i],a.get?b[i].get(j)||j:b[i][j]||j):(n(j)&&(d.get("numberFormatter")?j=d.get("numberFormatter")(j):j=s(j,k,d.get("numberDigitGroupCount"),d.get("numberDigitGroupSep"),d.get("numberDecimalMark"))),j)})}}),d.spformat=function(a,b){return new h(a,b)},i=function(a,b,c){return a<b?b:a>c?c:a},j=function(a,c){var d;return c===2?(d=b.floor(a.length/2),a.length%2?a[d]:(a[d-1]+a[d])/2):a.length%2?(d=(a.length*c+c)/4,d%1?(a[b.floor(d)]+a[b.floor(d)-1])/2:a[d-1]):(d=(a.length*c+2)/4,d%1?(a[b.floor(d)]+a[b.floor(d)-1])/2:a[d-1])},k=function(a){var b;switch(a){case"undefined":a=c;break;case"null":a=null;break;case"true":a=!0;break;case"false":a=!1;break;default:b=parseFloat(a),a==b&&(a=b)}return a},l=function(a){var b,c=[];for(b=a.length;b--;)c[b]=k(a[b]);return c},m=function(a,b){var c,d,e=[];for(c=0,d=a.length;c<d;c++)a[c]!==b&&e.push(a[c]);return e},n=function(a){return!isNaN(parseFloat(a))&&isFinite(a)},s=function(a,b,c,e,f){var g,h;a=(b===!1?parseFloat(a).toString():a.toFixed(b)).split(""),g=(g=d.inArray(".",a))<0?a.length:g,g<a.length&&(a[g]=f);for(h=g-c;h>0;h-=c)a.splice(h,0,e);return a.join("")},o=function(a,b,c){var d;for(d=b.length;d--;){if(c&&b[d]===null)continue;if(b[d]!==a)return!1}return!0},p=function(a){var b=0,c;for(c=a.length;c--;)b+=typeof a[c]=="number"?a[c]:0;return b},r=function(a){return d.isArray(a)?a:[a]},q=function(b){var c;a.createStyleSheet?a.createStyleSheet().cssText=b:(c=a.createElement("style"),c.type="text/css",a.getElementsByTagName("head")[0].appendChild(c),c[typeof a.body.style.WebkitAppearance=="string"?"innerText":"innerHTML"]=b)},d.fn.simpledraw=function(b,e,f,g){var h,i;if(f&&(h=this.data("_jqs_vcanvas")))return h;if(d.fn.sparkline.canvas===!1)return!1;if(d.fn.sparkline.canvas===c){var j=a.createElement("canvas");if(!j.getContext||!j.getContext("2d")){if(!a.namespaces||!!a.namespaces.v)return d.fn.sparkline.canvas=!1,!1;a.namespaces.add("v","urn:schemas-microsoft-com:vml","#default#VML"),d.fn.sparkline.canvas=function(a,b,c,d){return new J(a,b,c)}}else d.fn.sparkline.canvas=function(a,b,c,d){return new I(a,b,c,d)}}return b===c&&(b=d(this).innerWidth()),e===c&&(e=d(this).innerHeight()),h=d.fn.sparkline.canvas(b,e,this,g),i=d(this).data("_jqs_mhandler"),i&&i.registerCanvas(h),h},d.fn.cleardraw=function(){var a=this.data("_jqs_vcanvas");a&&a.reset()},d.RangeMapClass=t=g({init:function(a){var b,c,d=[];for(b in a)a.hasOwnProperty(b)&&typeof b=="string"&&b.indexOf(":")>-1&&(c=b.split(":"),c[0]=c[0].length===0?-Infinity:parseFloat(c[0]),c[1]=c[1].length===0?Infinity:parseFloat(c[1]),c[2]=a[b],d.push(c));this.map=a,this.rangelist=d||!1},get:function(a){var b=this.rangelist,d,e,f;if((f=this.map[a])!==c)return f;if(b)for(d=b.length;d--;){e=b[d];if(e[0]<=a&&e[1]>=a)return e[2]}return c}}),d.range_map=function(a){return new t(a)},u=g({init:function(a,b){var c=d(a);this.$el=c,this.options=b,this.currentPageX=0,this.currentPageY=0,this.el=a,this.splist=[],this.tooltip=null,this.over=!1,this.displayTooltips=!b.get("disableTooltips"),this.highlightEnabled=!b.get("disableHighlight")},registerSparkline:function(a){this.splist.push(a),this.over&&this.updateDisplay()},registerCanvas:function(a){var b=d(a.canvas);this.canvas=a,this.$canvas=b,b.mouseenter(d.proxy(this.mouseenter,this)),b.mouseleave(d.proxy(this.mouseleave,this)),b.click(d.proxy(this.mouseclick,this))},reset:function(a){this.splist=[],this.tooltip&&a&&(this.tooltip.remove(),this.tooltip=c)},mouseclick:function(a){var b=d.Event("sparklineClick");b.originalEvent=a,b.sparklines=this.splist,this.$el.trigger(b)},mouseenter:function(b){d(a.body).unbind("mousemove.jqs"),d(a.body).bind("mousemove.jqs",d.proxy(this.mousemove,this)),this.over=!0,this.currentPageX=b.pageX,this.currentPageY=b.pageY,this.currentEl=b.target,!this.tooltip&&this.displayTooltips&&(this.tooltip=new v(this.options),this.tooltip.updatePosition(b.pageX,b.pageY)),this.updateDisplay()},mouseleave:function(){d(a.body).unbind("mousemove.jqs");var b=this.splist,c=b.length,e=!1,f,g;this.over=!1,this.currentEl=null,this.tooltip&&(this.tooltip.remove(),this.tooltip=null);for(g=0;g<c;g++)f=b[g],f.clearRegionHighlight()&&(e=!0);e&&this.canvas.render()},mousemove:function(a){this.currentPageX=a.pageX,this.currentPageY=a.pageY,this.currentEl=a.target,this.tooltip&&this.tooltip.updatePosition(a.pageX,a.pageY),this.updateDisplay()},updateDisplay:function(){var a=this.splist,b=a.length,c=!1,e=this.$canvas.offset(),f=this.currentPageX-e.left,g=this.currentPageY-e.top,h,i,j,k,l;if(!this.over)return;for(j=0;j<b;j++)i=a[j],k=i.setRegionHighlight(this.currentEl,f,g),k&&(c=!0);if(c){l=d.Event("sparklineRegionChange"),l.sparklines=this.splist,this.$el.trigger(l);if(this.tooltip){h="";for(j=0;j<b;j++)i=a[j],h+=i.getCurrentRegionTooltip();this.tooltip.setContent(h)}this.disableHighlight||this.canvas.render()}k===null&&this.mouseleave()}}),v=g({sizeStyle:"position: static !important;display: block !important;visibility: hidden !important;float: left !important;",init:function(b){var c=b.get("tooltipClassname","jqstooltip"),e=this.sizeStyle,f;this.container=b.get("tooltipContainer")||a.body,this.tooltipOffsetX=b.get("tooltipOffsetX",10),this.tooltipOffsetY=b.get("tooltipOffsetY",12),d("#jqssizetip").remove(),d("#jqstooltip").remove(),this.sizetip=d("<div/>",{id:"jqssizetip",style:e,"class":c}),this.tooltip=d("<div/>",{id:"jqstooltip","class":c}).appendTo(this.container),f=this.tooltip.offset(),this.offsetLeft=f.left,this.offsetTop=f.top,this.hidden=!0,d(window).unbind("resize.jqs scroll.jqs"),d(window).bind("resize.jqs scroll.jqs",d.proxy(this.updateWindowDims,this)),this.updateWindowDims()},updateWindowDims:function(){this.scrollTop=d(window).scrollTop(),this.scrollLeft=d(window).scrollLeft(),this.scrollRight=this.scrollLeft+d(window).width(),this.updatePosition()},getSize:function(a){this.sizetip.html(a).appendTo(this.container),this.width=this.sizetip.width()+1,this.height=this.sizetip.height(),this.sizetip.remove()},setContent:function(a){if(!a){this.tooltip.css("visibility","hidden"),this.hidden=!0;return}this.getSize(a),this.tooltip.html(a).css({width:this.width,height:this.height,visibility:"visible"}),this.hidden&&(this.hidden=!1,this.updatePosition())},updatePosition:function(a,b){if(a===c){if(this.mousex===c)return;a=this.mousex-this.offsetLeft,b=this.mousey-this.offsetTop}else this.mousex=a-=this.offsetLeft,this.mousey=b-=this.offsetTop;if(!this.height||!this.width||this.hidden)return;b-=this.height+this.tooltipOffsetY,a+=this.tooltipOffsetX,b<this.scrollTop&&(b=this.scrollTop),a<this.scrollLeft?a=this.scrollLeft:a+this.width>this.scrollRight&&(a=this.scrollRight-this.width),this.tooltip.css({left:a,top:b})},remove:function(){this.tooltip.remove(),this.sizetip.remove(),this.sizetip=this.tooltip=c,d(window).unbind("resize.jqs scroll.jqs")}}),F=function(){q(E)},d(F),K=[],d.fn.sparkline=function(b,e){return this.each(function(){var f=new d.fn.sparkline.options(this,e),g=d(this),h,i;h=function(){var e,h,i,j,k,l,m;if(b==="html"||b===c){m=this.getAttribute(f.get("tagValuesAttribute"));if(m===c||m===null)m=g.html();e=m.replace(/(^\s*<!--)|(-->\s*$)|\s+/g,"").split(",")}else e=b;h=f.get("width")==="auto"?e.length*f.get("defaultPixelsPerValue"):f.get("width");if(f.get("height")==="auto"){if(!f.get("composite")||!d.data(this,"_jqs_vcanvas"))j=a.createElement("span"),j.innerHTML="a",g.html(j),i=d(j).innerHeight()||d(j).height(),d(j).remove(),j=null}else i=f.get("height");f.get("disableInteraction")?k=!1:(k=d.data(this,"_jqs_mhandler"),k?f.get("composite")||k.reset():(k=new u(this,f),d.data(this,"_jqs_mhandler",k)));if(f.get("composite")&&!d.data(this,"_jqs_vcanvas")){d.data(this,"_jqs_errnotify")||(alert("Attempted to attach a composite sparkline to an element with no existing sparkline"),d.data(this,"_jqs_errnotify",!0));return}l=new(d.fn.sparkline[f.get("type")])(this,e,f,h,i),l.render(),k&&k.registerSparkline(l)};if(d(this).html()&&!f.get("disableHiddenCheck")&&d(this).is(":hidden")||!d(this).parents("body").length){if(!f.get("composite")&&d.data(this,"_jqs_pending"))for(i=K.length;i;i--)K[i-1][0]==this&&K.splice(i-1,1);K.push([this,h]),d.data(this,"_jqs_pending",!0)}else h.call(this)})},d.fn.sparkline.defaults=f(),d.sparkline_display_visible=function(){var a,b,c,e=[];for(b=0,c=K.length;b<c;b++)a=K[b][0],d(a).is(":visible")&&!d(a).parents().is(":hidden")?(K[b][1].call(a),d.data(K[b][0],"_jqs_pending",!1),e.push(b)):!d(a).closest("html").length&&!d.data(a,"_jqs_pending")&&(d.data(K[b][0],"_jqs_pending",!1),e.push(b));for(b=e.length;b;b--)K.splice(e[b-1],1)},d.fn.sparkline.options=g({init:function(a,b){var c,f,g,h;this.userOptions=b=b||{},this.tag=a,this.tagValCache={},f=d.fn.sparkline.defaults,g=f.common,this.tagOptionsPrefix=b.enableTagOptions&&(b.tagOptionsPrefix||g.tagOptionsPrefix),h=this.getTagSetting("type"),h===e?c=f[b.type||g.type]:c=f[h],this.mergedOptions=d.extend({},g,c,b)},getTagSetting:function(a){var b=this.tagOptionsPrefix,d,f,g,h;if(b===!1||b===c)return e;if(this.tagValCache.hasOwnProperty(a))d=this.tagValCache.key;else{d=this.tag.getAttribute(b+a);if(d===c||d===null)d=e;else if(d.substr(0,1)==="["){d=d.substr(1,d.length-2).split(",");for(f=d.length;f--;)d[f]=k(d[f].replace(/(^\s*)|(\s*$)/g,""))}else if(d.substr(0,1)==="{"){g=d.substr(1,d.length-2).split(","),d={};for(f=g.length;f--;)h=g[f].split(":",2),d[h[0].replace(/(^\s*)|(\s*$)/g,"")]=k(h[1].replace(/(^\s*)|(\s*$)/g,""))}else d=k(d);this.tagValCache.key=d}return d},get:function(a,b){var d=this.getTagSetting(a),f;return d!==e?d:(f=this.mergedOptions[a])===c?b:f}}),d.fn.sparkline._base=g({disabled:!1,init:function(a,b,e,f,g){this.el=a,this.$el=d(a),this.values=b,this.options=e,this.width=f,this.height=g,this.currentRegion=c},initTarget:function(){var a=!this.options.get("disableInteraction");(this.target=this.$el.simpledraw(this.width,this.height,this.options.get("composite"),a))?(this.canvasWidth=this.target.pixelWidth,this.canvasHeight=this.target.pixelHeight):this.disabled=!0},render:function(){return this.disabled?(this.el.innerHTML="",!1):!0},getRegion:function(a,b){},setRegionHighlight:function(a,b,d){var e=this.currentRegion,f=!this.options.get("disableHighlight"),g;return b>this.canvasWidth||d>this.canvasHeight||b<0||d<0?null:(g=this.getRegion(a,b,d),e!==g?(e!==c&&f&&this.removeHighlight(),this.currentRegion=g,g!==c&&f&&this.renderHighlight(),!0):!1)},clearRegionHighlight:function(){return this.currentRegion!==c?(this.removeHighlight(),this.currentRegion=c,!0):!1},renderHighlight:function(){this.changeHighlight(!0)},removeHighlight:function(){this.changeHighlight(!1)},changeHighlight:function(a){},getCurrentRegionTooltip:function(){var a=this.options,b="",e=[],f,g,i,j,k,l,m,n,o,p,q,r,s,t;if(this.currentRegion===c)return"";f=this.getCurrentRegionFields(),q=a.get("tooltipFormatter");if(q)return q(this,a,f);a.get("tooltipChartTitle")&&(b+='<div class="jqs jqstitle">'+a.get("tooltipChartTitle")+"</div>\n"),g=this.options.get("tooltipFormat");if(!g)return"";d.isArray(g)||(g=[g]),d.isArray(f)||(f=[f]),m=this.options.get("tooltipFormatFieldlist"),n=this.options.get("tooltipFormatFieldlistKey");if(m&&n){o=[];for(l=f.length;l--;)p=f[l][n],(t=d.inArray(p,m))!=-1&&(o[t]=f[l]);f=o}i=g.length,s=f.length;for(l=0;l<i;l++){r=g[l],typeof r=="string"&&(r=new h(r)),j=r.fclass||"jqsfield";for(t=0;t<s;t++)if(!f[t].isNull||!a.get("tooltipSkipNull"))d.extend(f[t],{prefix:a.get("tooltipPrefix"),suffix:a.get("tooltipSuffix")}),k=r.render(f[t],a.get("tooltipValueLookups"),a),e.push('<div class="'+j+'">'+k+"</div>")}return e.length?b+e.join("\n"):""},getCurrentRegionFields:function(){},calcHighlightColor:function(a,c){var d=c.get("highlightColor"),e=c.get("highlightLighten"),f,g,h,j;if(d)return d;if(e){f=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(a)||/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(a);if(f){h=[],g=a.length===4?16:1;for(j=0;j<3;j++)h[j]=i(b.round(parseInt(f[j+1],16)*g*e),0,255);return"rgb("+h.join(",")+")"}}return a}}),w={changeHighlight:function(a){var b=this.currentRegion,c=this.target,e=this.regionShapes[b],f;e&&(f=this.renderRegion(b,a),d.isArray(f)||d.isArray(e)?(c.replaceWithShapes(e,f),this.regionShapes[b]=d.map(f,function(a){return a.id})):(c.replaceWithShape(e,f),this.regionShapes[b]=f.id))},render:function(){var a=this.values,b=this.target,c=this.regionShapes,e,f,g,h;if(!this.cls._super.render.call(this))return;for(g=a.length;g--;){e=this.renderRegion(g);if(e)if(d.isArray(e)){f=[];for(h=e.length;h--;)e[h].append(),f.push(e[h].id);c[g]=f}else e.append(),c[g]=e.id;else c[g]=null}b.render()}},d.fn.sparkline.line=x=g(d.fn.sparkline._base,{type:"line",init:function(a,b,c,d,e){x._super.init.call(this,a,b,c,d,e),this.vertices=[],this.regionMap=[],this.xvalues=[],this.yvalues=[],this.yminmax=[],this.hightlightSpotId=null,this.lastShapeId=null,this.initTarget()},getRegion:function(a,b,d){var e,f=this.regionMap;for(e=f.length;e--;)if(f[e]!==null&&b>=f[e][0]&&b<=f[e][1])return f[e][2];return c},getCurrentRegionFields:function(){var a=this.currentRegion;return{isNull:this.yvalues[a]===null,x:this.xvalues[a],y:this.yvalues[a],color:this.options.get("lineColor"),fillColor:this.options.get("fillColor"),offset:a}},renderHighlight:function(){var a=this.currentRegion,b=this.target,d=this.vertices[a],e=this.options,f=e.get("spotRadius"),g=e.get("highlightSpotColor"),h=e.get("highlightLineColor"),i,j;if(!d)return;f&&g&&(i=b.drawCircle(d[0],d[1],f,c,g),this.highlightSpotId=i.id,b.insertAfterShape(this.lastShapeId,i)),h&&(j=b.drawLine(d[0],this.canvasTop,d[0],this.canvasTop+this.canvasHeight,h),this.highlightLineId=j.id,b.insertAfterShape(this.lastShapeId,j))},removeHighlight:function(){var a=this.target;this.highlightSpotId&&(a.removeShapeId(this.highlightSpotId),this.highlightSpotId=null),this.highlightLineId&&(a.removeShapeId(this.highlightLineId),this.highlightLineId=null)},scanValues:function(){var a=this.values,c=a.length,d=this.xvalues,e=this.yvalues,f=this.yminmax,g,h,i,j,k;for(g=0;g<c;g++)h=a[g],i=typeof a[g]=="string",j=typeof a[g]=="object"&&a[g]instanceof Array,k=i&&a[g].split(":"),i&&k.length===2?(d.push(Number(k[0])),e.push(Number(k[1])),f.push(Number(k[1]))):j?(d.push(h[0]),e.push(h[1]),f.push(h[1])):(d.push(g),a[g]===null||a[g]==="null"?e.push(null):(e.push(Number(h)),f.push(Number(h))));this.options.get("xvalues")&&(d=this.options.get("xvalues")),this.maxy=this.maxyorg=b.max.apply(b,f),this.miny=this.minyorg=b.min.apply(b,f),this.maxx=b.max.apply(b,d),this.minx=b.min.apply(b,d),this.xvalues=d,this.yvalues=e,this.yminmax=f},processRangeOptions:function(){var a=this.options,b=a.get("normalRangeMin"),d=a.get("normalRangeMax");b!==c&&(b<this.miny&&(this.miny=b),d>this.maxy&&(this.maxy=d)),a.get("chartRangeMin")!==c&&(a.get("chartRangeClip")||a.get("chartRangeMin")<this.miny)&&(this.miny=a.get("chartRangeMin")),a.get("chartRangeMax")!==c&&(a.get("chartRangeClip")||a.get("chartRangeMax")>this.maxy)&&(this.maxy=a.get("chartRangeMax")),a.get("chartRangeMinX")!==c&&(a.get("chartRangeClipX")||a.get("chartRangeMinX")<this.minx)&&(this.minx=a.get("chartRangeMinX")),a.get("chartRangeMaxX")!==c&&(a.get("chartRangeClipX")||a.get("chartRangeMaxX")>this.maxx)&&(this.maxx=a.get("chartRangeMaxX"))},drawNormalRange:function(a,d,e,f,g){var h=this.options.get("normalRangeMin"),i=this.options.get("normalRangeMax"),j=d+b.round(e-e*((i-this.miny)/g)),k=b.round(e*(i-h)/g);this.target.drawRect(a,j,f,k,c,this.options.get("normalRangeColor")).append()},render:function(){var a=this.options,e=this.target,f=this.canvasWidth,g=this.canvasHeight,h=this.vertices,i=a.get("spotRadius"),j=this.regionMap,k,l,m,n,o,p,q,r,s,u,v,w,y,z,A,B,C,D,E,F,G,H,I,J,K;if(!x._super.render.call(this))return;this.scanValues(),this.processRangeOptions(),I=this.xvalues,J=this.yvalues;if(!this.yminmax.length||this.yvalues.length<2)return;n=o=0,k=this.maxx-this.minx===0?1:this.maxx-this.minx,l=this.maxy-this.miny===0?1:this.maxy-this.miny,m=this.yvalues.length-1,i&&(f<i*4||g<i*4)&&(i=0);if(i){G=a.get("highlightSpotColor")&&!a.get("disableInteraction");if(G||a.get("minSpotColor")||a.get("spotColor")&&J[m]===this.miny)g-=b.ceil(i);if(G||a.get("maxSpotColor")||a.get("spotColor")&&J[m]===this.maxy)g-=b.ceil(i),n+=b.ceil(i);if(G||(a.get("minSpotColor")||a.get("maxSpotColor"))&&(J[0]===this.miny||J[0]===this.maxy))o+=b.ceil(i),f-=b.ceil(i);if(G||a.get("spotColor")||a.get("minSpotColor")||a.get("maxSpotColor")&&(J[m]===this.miny||J[m]===this.maxy))f-=b.ceil(i)}g--,a.get("normalRangeMin")!==c&&!a.get("drawNormalOnTop")&&this.drawNormalRange(o,n,g,f,l),q=[],r=[q],z=A=null,B=J.length;for(K=0;K<B;K++)s=I[K],v=I[K+1],u=J[K],w=o+b.round((s-this.minx)*(f/k)),y=K<B-1?o+b.round((v-this.minx)*(f/k)):f,A=w+(y-w)/2,j[K]=[z||0,A,K],z=A,u===null?K&&(J[K-1]!==null&&(q=[],r.push(q)),h.push(null)):(u<this.miny&&(u=this.miny),u>this.maxy&&(u=this.maxy),q.length||q.push([w,n+g]),p=[w,n+b.round(g-g*((u-this.miny)/l))],q.push(p),h.push(p));C=[],D=[],E=r.length;for(K=0;K<E;K++)q=r[K],q.length&&(a.get("fillColor")&&(q.push([q[q.length-1][0],n+g]),D.push(q.slice(0)),q.pop()),q.length>2&&(q[0]=[q[0][0],q[1][1]]),C.push(q));E=D.length;for(K=0;K<E;K++)e.drawShape(D[K],a.get("fillColor"),a.get("fillColor")).append();a.get("normalRangeMin")!==c&&a.get("drawNormalOnTop")&&this.drawNormalRange(o,n,g,f,l),E=C.length;for(K=0;K<E;K++)e.drawShape(C[K],a.get("lineColor"),c,a.get("lineWidth")).append();if(i&&a.get("valueSpots")){F=a.get("valueSpots"),F.get===c&&(F=new t(F));for(K=0;K<B;K++)H=F.get(J[K]),H&&e.drawCircle(o+b.round((I[K]-this.minx)*(f/k)),n+b.round(g-g*((J[K]-this.miny)/l)),i,c,H).append()}i&&a.get("spotColor")&&J[m]!==null&&e.drawCircle(o+b.round((I[I.length-1]-this.minx)*(f/k)),n+b.round(g-g*((J[m]-this.miny)/l)),i,c,a.get("spotColor")).append(),this.maxy!==this.minyorg&&(i&&a.get("minSpotColor")&&(s=I[d.inArray(this.minyorg,J)],e.drawCircle(o+b.round((s-this.minx)*(f/k)),n+b.round(g-g*((this.minyorg-this.miny)/l)),i,c,a.get("minSpotColor")).append()),i&&a.get("maxSpotColor")&&(s=I[d.inArray(this.maxyorg,J)],e.drawCircle(o+b.round((s-this.minx)*(f/k)),n+b.round(g-g*((this.maxyorg-this.miny)/l)),i,c,a.get("maxSpotColor")).append())),this.lastShapeId=e.getLastShapeId(),this.canvasTop=n,e.render()}}),d.fn.sparkline.bar=y=g(d.fn.sparkline._base,w,{type:"bar",init:function(a,e,f,g,h){var j=parseInt(f.get("barWidth"),10),n=parseInt(f.get("barSpacing"),10),o=f.get("chartRangeMin"),p=f.get("chartRangeMax"),q=f.get("chartRangeClip"),r=Infinity,s=-Infinity,u,v,w,x,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R;y._super.init.call(this,a,e,f,g,h);for(A=0,B=e.length;A<B;A++){O=e[A],u=typeof O=="string"&&O.indexOf(":")>-1;if(u||d.isArray(O))J=!0,u&&(O=e[A]=l(O.split(":"))),O=m(O,null),v=b.min.apply(b,O),w=b.max.apply(b,O),v<r&&(r=v),w>s&&(s=w)}this.stacked=J,this.regionShapes={},this.barWidth=j,this.barSpacing=n,this.totalBarWidth=j+n,this.width=g=e.length*j+(e.length-1)*n,this.initTarget(),q&&(H=o===c?-Infinity:o,I=p===c?Infinity:p),z=[],x=J?[]:z;var S=[],T=[];for(A=0,B=e.length;A<B;A++)if(J){K=e[A],e[A]=N=[],S[A]=0,x[A]=T[A]=0;for(L=0,M=K.length;L<M;L++)O=N[L]=q?i(K[L],H,I):K[L],O!==null&&(O>0&&(S[A]+=O),r<0&&s>0?O<0?T[A]+=b.abs(O):x[A]+=O:x[A]+=b.abs(O-(O<0?s:r)),z.push(O))}else O=q?i(e[A],H,I):e[A],O=e[A]=k(O),O!==null&&z.push(O);this.max=G=b.max.apply(b,z),this.min=F=b.min.apply(b,z),this.stackMax=s=J?b.max.apply(b,S):G,this.stackMin=r=J?b.min.apply(b,z):F,f.get("chartRangeMin")!==c&&(f.get("chartRangeClip")||f.get("chartRangeMin")<F)&&(F=f.get("chartRangeMin")),f.get("chartRangeMax")!==c&&(f.get("chartRangeClip")||f.get("chartRangeMax")>G)&&(G=f.get("chartRangeMax")),this.zeroAxis=D=f.get("zeroAxis",!0),F<=0&&G>=0&&D?E=0:D==0?E=F:F>0?E=F:E=G,this.xaxisOffset=E,C=J?b.max.apply(b,x)+b.max.apply(b,T):G-F,this.canvasHeightEf=D&&F<0?this.canvasHeight-2:this.canvasHeight-1,F<E?(Q=J&&G>=0?s:G,P=(Q-E)/C*this.canvasHeight,P!==b.ceil(P)&&(this.canvasHeightEf-=2,P=b.ceil(P))):P=this.canvasHeight,this.yoffset=P,d.isArray(f.get("colorMap"))?(this.colorMapByIndex=f.get("colorMap"),this.colorMapByValue=null):(this.colorMapByIndex=null,this.colorMapByValue=f.get("colorMap"),this.colorMapByValue&&this.colorMapByValue.get===c&&(this.colorMapByValue=new t(this.colorMapByValue))),this.range=C},getRegion:function(a,d,e){var f=b.floor(d/this.totalBarWidth);return f<0||f>=this.values.length?c:f},getCurrentRegionFields:function(){var a=this.currentRegion,b=r(this.values[a]),c=[],d,e;for(e=b.length;e--;)d=b[e],c.push({isNull:d===null,value:d,color:this.calcColor(e,d,a),offset:a});return c},calcColor:function(a,b,e){var f=this.colorMapByIndex,g=this.colorMapByValue,h=this.options,i,j;return this.stacked?i=h.get("stackedBarColor"):i=b<0?h.get("negBarColor"):h.get("barColor"),b===0&&h.get("zeroColor")!==c&&(i=h.get("zeroColor")),g&&(j=g.get(b))?i=j:f&&f.length>e&&(i=f[e]),d.isArray(i)?i[a%i.length]:i},renderRegion:function(a,e){var f=this.values[a],g=this.options,h=this.xaxisOffset,i=[],j=this.range,k=this.stacked,l=this.target,m=a*this.totalBarWidth,n=this.canvasHeightEf,p=this.yoffset,q,r,s,t,u,v,w,x,y,z;f=d.isArray(f)?f:[f],w=f.length,x=f[0],t=o(null,f),z=o(h,f,!0);if(t)return g.get("nullColor")?(s=e?g.get("nullColor"):this.calcHighlightColor(g.get("nullColor"),g),q=p>0?p-1:p,l.drawRect(m,q,this.barWidth-1,0,s,s)):c;u=p;for(v=0;v<w;v++){x=f[v];if(k&&x===h){if(!z||y)continue;y=!0}j>0?r=b.floor(n*(b.abs(x-h)/j))+1:r=1,x<h||x===h&&p===0?(q=u,u+=r):(q=p-r,p-=r),s=this.calcColor(v,x,a),e&&(s=this.calcHighlightColor(s,g)),i.push(l.drawRect(m,q,this.barWidth-1,r-1,s,s))}return i.length===1?i[0]:i}}),d.fn.sparkline.tristate=z=g(d.fn.sparkline._base,w,{type:"tristate",init:function(a,b,e,f,g){var h=parseInt(e.get("barWidth"),10),i=parseInt(e.get("barSpacing"),10);z._super.init.call(this,a,b,e,f,g),this.regionShapes={},this.barWidth=h,this.barSpacing=i,this.totalBarWidth=h+i,this.values=d.map(b,Number),this.width=f=b.length*h+(b.length-1)*i,d.isArray(e.get("colorMap"))?(this.colorMapByIndex=e.get("colorMap"),this.colorMapByValue=null):(this.colorMapByIndex=null,this.colorMapByValue=e.get("colorMap"),this.colorMapByValue&&this.colorMapByValue.get===c&&(this.colorMapByValue=new t(this.colorMapByValue))),this.initTarget()},getRegion:function(a,c,d){return b.floor(c/this.totalBarWidth)},getCurrentRegionFields:function(){var a=this.currentRegion;return{isNull:this.values[a]===c,value:this.values[a],color:this.calcColor(this.values[a],a),offset:a}},calcColor:function(a,b){var c=this.values,d=this.options,e=this.colorMapByIndex,f=this.colorMapByValue,g,h;return f&&(h=f.get(a))?g=h:e&&e.length>b?g=e[b]:c[b]<0?g=d.get("negBarColor"):c[b]>0?g=d.get("posBarColor"):g=d.get("zeroBarColor"),g},renderRegion:function(a,c){var d=this.values,e=this.options,f=this.target,g,h,i,j,k,l;g=f.pixelHeight,i=b.round(g/2),j=a*this.totalBarWidth,d[a]<0?(k=i,h=i-1):d[a]>0?(k=0,h=i-1):(k=i-1,h=2),l=this.calcColor(d[a],a);if(l===null)return;return c&&(l=this.calcHighlightColor(l,e)),f.drawRect(j,k,this.barWidth-1,h-1,l,l)}}),d.fn.sparkline.discrete=A=g(d.fn.sparkline._base,w,{type:"discrete",init:function(a,e,f,g,h){A._super.init.call(this,a,e,f,g,h),this.regionShapes={},this.values=e=d.map(e,Number),this.min=b.min.apply(b,e),this.max=b.max.apply(b,e),this.range=this.max-this.min,this.width=g=f.get("width")==="auto"?e.length*2:this.width,this.interval=b.floor(g/e.length),this.itemWidth=g/e.length,f.get("chartRangeMin")!==c&&(f.get("chartRangeClip")||f.get("chartRangeMin")<this.min)&&(this.min=f.get("chartRangeMin")),f.get("chartRangeMax")!==c&&(f.get("chartRangeClip")||f.get("chartRangeMax")>this.max)&&(this.max=f.get("chartRangeMax")),this.initTarget(),this.target&&(this.lineHeight=f.get("lineHeight")==="auto"?b.round(this.canvasHeight*.3):f.get("lineHeight"))},getRegion:function(a,c,d){return b.floor(c/this.itemWidth)},getCurrentRegionFields:function(){var a=this.currentRegion;return{isNull:this.values[a]===c,value:this.values[a],offset:a}},renderRegion:function(a,c){var d=this.values,e=this.options,f=this.min,g=this.max,h=this.range,j=this.interval,k=this.target,l=this.canvasHeight,m=this.lineHeight,n=l-m,o,p,q,r;return p=i(d[a],f,g),r=a*j,o=b.round(n-n*((p-f)/h)),q=e.get("thresholdColor")&&p<e.get("thresholdValue")?e.get("thresholdColor"):e.get("lineColor"),c&&(q=this.calcHighlightColor(q,e)),k.drawLine(r,o,r,o+m,q)}}),d.fn.sparkline.bullet=B=g(d.fn.sparkline._base,{type:"bullet",init:function(a,d,e,f,g){var h,i,j;B._super.init.call(this,a,d,e,f,g),this.values=d=l(d),j=d.slice(),j[0]=j[0]===null?j[2]:j[0],j[1]=d[1]===null?j[2]:j[1],h=b.min.apply(b,d),i=b.max.apply(b,d),e.get("base")===c?h=h<0?h:0:h=e.get("base"),this.min=h,this.max=i,this.range=i-h,this.shapes={},this.valueShapes={},this.regiondata={},this.width=f=e.get("width")==="auto"?"4.0em":f,this.target=this.$el.simpledraw(f,g,e.get("composite")),d.length||(this.disabled=!0),this.initTarget()},getRegion:function(a,b,d){var e=this.target.getShapeAt(a,b,d);return e!==c&&this.shapes[e]!==c?this.shapes[e]:c},getCurrentRegionFields:function(){var a=this.currentRegion;return{fieldkey:a.substr(0,1),value:this.values[a.substr(1)],region:a}},changeHighlight:function(a){var b=this.currentRegion,c=this.valueShapes[b],d;delete this.shapes[c];switch(b.substr(0,1)){case"r":d=this.renderRange(b.substr(1),a);break;case"p":d=this.renderPerformance(a);break;case"t":d=this.renderTarget(a)}this.valueShapes[b]=d.id,this.shapes[d.id]=b,this.target.replaceWithShape(c,d)},renderRange:function(a,c){var d=this.values[a],e=b.round(this.canvasWidth*((d-this.min)/this.range)),f=this.options.get("rangeColors")[a-2];return c&&(f=this.calcHighlightColor(f,this.options)),this.target.drawRect(0,0,e-1,this.canvasHeight-1,f,f)},renderPerformance:function(a){var c=this.values[1],d=b.round(this.canvasWidth*((c-this.min)/this.range)),e=this.options.get("performanceColor");return a&&(e=this.calcHighlightColor(e,this.options)),this.target.drawRect(0,b.round(this.canvasHeight*.3),d-1,b.round(this.canvasHeight*.4)-1,e,e)},renderTarget:function(a){var c=this.values[0],d=b.round(this.canvasWidth*((c-this.min)/this.range)-this.options.get("targetWidth")/2),e=b.round(this.canvasHeight*.1),f=this.canvasHeight-e*2,g=this.options.get("targetColor");return a&&(g=this.calcHighlightColor(g,this.options)),this.target.drawRect(d,e,this.options.get("targetWidth")-1,f-1,g,g)},render:function(){var a=this.values.length,b=this.target,c,d;if(!B._super.render.call(this))return;for(c=2;c<a;c++)d=this.renderRange(c).append(),this.shapes[d.id]="r"+c,this.valueShapes["r"+c]=d.id;this.values[1]!==null&&(d=this.renderPerformance().append(),this.shapes[d.id]="p1",this.valueShapes.p1=d.id),this.values[0]!==null&&(d=this.renderTarget().append(),this.shapes[d.id]="t0",this.valueShapes.t0=d.id),b.render()}}),d.fn.sparkline.pie=C=g(d.fn.sparkline._base,{type:"pie",init:function(a,c,e,f,g){var h=0,i;C._super.init.call(this,a,c,e,f,g),this.shapes={},this.valueShapes={},this.values=c=d.map(c,Number),e.get("width")==="auto"&&(this.width=this.height);if(c.length>0)for(i=c.length;i--;)h+=c[i];this.total=h,this.initTarget(),this.radius=b.floor(b.min(this.canvasWidth,this.canvasHeight)/2)},getRegion:function(a,b,d){var e=this.target.getShapeAt(a,b,d);return e!==c&&this.shapes[e]!==c?this.shapes[e]:c},getCurrentRegionFields:function(){var a=this.currentRegion;return{isNull:this.values[a]===c,value:this.values[a],percent:this.values[a]/this.total*100,color:this.options.get("sliceColors")[a%this.options.get("sliceColors").length],offset:a}},changeHighlight:function(a){var b=this.currentRegion,c=this.renderSlice(b,a),d=this.valueShapes[b];delete this.shapes[d],this.target.replaceWithShape(d,c),this.valueShapes[b]=c.id,this.shapes[c.id]=b},renderSlice:function(a,d){var e=this.target,f=this.options,g=this.radius,h=f.get("borderWidth"),i=f.get("offset"),j=2*b.PI,k=this.values,l=this.total,m=i?2*b.PI*(i/360):0,n,o,p,q,r;q=k.length;for(p=0;p<q;p++){n=m,o=m,l>0&&(o=m+j*(k[p]/l));if(a===p)return r=f.get("sliceColors")[p%f.get("sliceColors").length],d&&(r=this.calcHighlightColor(r,f)),e.drawPieSlice(g,g,g-h,n,o,c,r);m=o}},render:function(){var a=this.target,d=this.values,e=this.options,f=this.radius,g=e.get("borderWidth"),h,i;if(!C._super.render.call(this))return;g&&a.drawCircle(f,f,b.floor(f-g/2),e.get("borderColor"),c,g).append();for(i=d.length;i--;)d[i]&&(h=this.renderSlice(i).append(),this.valueShapes[i]=h.id,this.shapes[h.id]=i);a.render()}}),d.fn.sparkline.box=D=g(d.fn.sparkline._base,{type:"box",init:function(a,b,c,e,f){D._super.init.call(this,a,b,c,e,f),this.values=d.map(b,Number),this.width=c.get("width")==="auto"?"4.0em":e,this.initTarget(),this.values.length||(this.disabled=1)},getRegion:function(){return 1},getCurrentRegionFields:function(){var a=[{field:"lq",value:this.quartiles[0]},{field:"med",value:this.quartiles
[1]},{field:"uq",value:this.quartiles[2]}];return this.loutlier!==c&&a.push({field:"lo",value:this.loutlier}),this.routlier!==c&&a.push({field:"ro",value:this.routlier}),this.lwhisker!==c&&a.push({field:"lw",value:this.lwhisker}),this.rwhisker!==c&&a.push({field:"rw",value:this.rwhisker}),a},render:function(){var a=this.target,d=this.values,e=d.length,f=this.options,g=this.canvasWidth,h=this.canvasHeight,i=f.get("chartRangeMin")===c?b.min.apply(b,d):f.get("chartRangeMin"),k=f.get("chartRangeMax")===c?b.max.apply(b,d):f.get("chartRangeMax"),l=0,m,n,o,p,q,r,s,t,u,v,w;if(!D._super.render.call(this))return;if(f.get("raw"))f.get("showOutliers")&&d.length>5?(n=d[0],m=d[1],p=d[2],q=d[3],r=d[4],s=d[5],t=d[6]):(m=d[0],p=d[1],q=d[2],r=d[3],s=d[4]);else{d.sort(function(a,b){return a-b}),p=j(d,1),q=j(d,2),r=j(d,3),o=r-p;if(f.get("showOutliers")){m=s=c;for(u=0;u<e;u++)m===c&&d[u]>p-o*f.get("outlierIQR")&&(m=d[u]),d[u]<r+o*f.get("outlierIQR")&&(s=d[u]);n=d[0],t=d[e-1]}else m=d[0],s=d[e-1]}this.quartiles=[p,q,r],this.lwhisker=m,this.rwhisker=s,this.loutlier=n,this.routlier=t,w=g/(k-i+1),f.get("showOutliers")&&(l=b.ceil(f.get("spotRadius")),g-=2*b.ceil(f.get("spotRadius")),w=g/(k-i+1),n<m&&a.drawCircle((n-i)*w+l,h/2,f.get("spotRadius"),f.get("outlierLineColor"),f.get("outlierFillColor")).append(),t>s&&a.drawCircle((t-i)*w+l,h/2,f.get("spotRadius"),f.get("outlierLineColor"),f.get("outlierFillColor")).append()),a.drawRect(b.round((p-i)*w+l),b.round(h*.1),b.round((r-p)*w),b.round(h*.8),f.get("boxLineColor"),f.get("boxFillColor")).append(),a.drawLine(b.round((m-i)*w+l),b.round(h/2),b.round((p-i)*w+l),b.round(h/2),f.get("lineColor")).append(),a.drawLine(b.round((m-i)*w+l),b.round(h/4),b.round((m-i)*w+l),b.round(h-h/4),f.get("whiskerColor")).append(),a.drawLine(b.round((s-i)*w+l),b.round(h/2),b.round((r-i)*w+l),b.round(h/2),f.get("lineColor")).append(),a.drawLine(b.round((s-i)*w+l),b.round(h/4),b.round((s-i)*w+l),b.round(h-h/4),f.get("whiskerColor")).append(),a.drawLine(b.round((q-i)*w+l),b.round(h*.1),b.round((q-i)*w+l),b.round(h*.9),f.get("medianColor")).append(),f.get("target")&&(v=b.ceil(f.get("spotRadius")),a.drawLine(b.round((f.get("target")-i)*w+l),b.round(h/2-v),b.round((f.get("target")-i)*w+l),b.round(h/2+v),f.get("targetColor")).append(),a.drawLine(b.round((f.get("target")-i)*w+l-v),b.round(h/2),b.round((f.get("target")-i)*w+l+v),b.round(h/2),f.get("targetColor")).append()),a.render()}}),G=g({init:function(a,b,c,d){this.target=a,this.id=b,this.type=c,this.args=d},append:function(){return this.target.appendShape(this),this}}),H=g({_pxregex:/(\d+)(px)?\s*$/i,init:function(a,b,c){if(!a)return;this.width=a,this.height=b,this.target=c,this.lastShapeId=null,c[0]&&(c=c[0]),d.data(c,"_jqs_vcanvas",this)},drawLine:function(a,b,c,d,e,f){return this.drawShape([[a,b],[c,d]],e,f)},drawShape:function(a,b,c,d){return this._genShape("Shape",[a,b,c,d])},drawCircle:function(a,b,c,d,e,f){return this._genShape("Circle",[a,b,c,d,e,f])},drawPieSlice:function(a,b,c,d,e,f,g){return this._genShape("PieSlice",[a,b,c,d,e,f,g])},drawRect:function(a,b,c,d,e,f){return this._genShape("Rect",[a,b,c,d,e,f])},getElement:function(){return this.canvas},getLastShapeId:function(){return this.lastShapeId},reset:function(){alert("reset not implemented")},_insert:function(a,b){d(b).html(a)},_calculatePixelDims:function(a,b,c){var e;e=this._pxregex.exec(b),e?this.pixelHeight=e[1]:this.pixelHeight=d(c).height(),e=this._pxregex.exec(a),e?this.pixelWidth=e[1]:this.pixelWidth=d(c).width()},_genShape:function(a,b){var c=L++;return b.unshift(c),new G(this,c,a,b)},appendShape:function(a){alert("appendShape not implemented")},replaceWithShape:function(a,b){alert("replaceWithShape not implemented")},insertAfterShape:function(a,b){alert("insertAfterShape not implemented")},removeShapeId:function(a){alert("removeShapeId not implemented")},getShapeAt:function(a,b,c){alert("getShapeAt not implemented")},render:function(){alert("render not implemented")}}),I=g(H,{init:function(b,e,f,g){I._super.init.call(this,b,e,f),this.canvas=a.createElement("canvas"),f[0]&&(f=f[0]),d.data(f,"_jqs_vcanvas",this),d(this.canvas).css({display:"inline-block",width:b,height:e,verticalAlign:"top"}),this._insert(this.canvas,f),this._calculatePixelDims(b,e,this.canvas),this.canvas.width=this.pixelWidth,this.canvas.height=this.pixelHeight,this.interact=g,this.shapes={},this.shapeseq=[],this.currentTargetShapeId=c,d(this.canvas).css({width:this.pixelWidth,height:this.pixelHeight})},_getContext:function(a,b,d){var e=this.canvas.getContext("2d");return a!==c&&(e.strokeStyle=a),e.lineWidth=d===c?1:d,b!==c&&(e.fillStyle=b),e},reset:function(){var a=this._getContext();a.clearRect(0,0,this.pixelWidth,this.pixelHeight),this.shapes={},this.shapeseq=[],this.currentTargetShapeId=c},_drawShape:function(a,b,d,e,f){var g=this._getContext(d,e,f),h,i;g.beginPath(),g.moveTo(b[0][0]+.5,b[0][1]+.5);for(h=1,i=b.length;h<i;h++)g.lineTo(b[h][0]+.5,b[h][1]+.5);d!==c&&g.stroke(),e!==c&&g.fill(),this.targetX!==c&&this.targetY!==c&&g.isPointInPath(this.targetX,this.targetY)&&(this.currentTargetShapeId=a)},_drawCircle:function(a,d,e,f,g,h,i){var j=this._getContext(g,h,i);j.beginPath(),j.arc(d,e,f,0,2*b.PI,!1),this.targetX!==c&&this.targetY!==c&&j.isPointInPath(this.targetX,this.targetY)&&(this.currentTargetShapeId=a),g!==c&&j.stroke(),h!==c&&j.fill()},_drawPieSlice:function(a,b,d,e,f,g,h,i){var j=this._getContext(h,i);j.beginPath(),j.moveTo(b,d),j.arc(b,d,e,f,g,!1),j.lineTo(b,d),j.closePath(),h!==c&&j.stroke(),i&&j.fill(),this.targetX!==c&&this.targetY!==c&&j.isPointInPath(this.targetX,this.targetY)&&(this.currentTargetShapeId=a)},_drawRect:function(a,b,c,d,e,f,g){return this._drawShape(a,[[b,c],[b+d,c],[b+d,c+e],[b,c+e],[b,c]],f,g)},appendShape:function(a){return this.shapes[a.id]=a,this.shapeseq.push(a.id),this.lastShapeId=a.id,a.id},replaceWithShape:function(a,b){var c=this.shapeseq,d;this.shapes[b.id]=b;for(d=c.length;d--;)c[d]==a&&(c[d]=b.id);delete this.shapes[a]},replaceWithShapes:function(a,b){var c=this.shapeseq,d={},e,f,g;for(f=a.length;f--;)d[a[f]]=!0;for(f=c.length;f--;)e=c[f],d[e]&&(c.splice(f,1),delete this.shapes[e],g=f);for(f=b.length;f--;)c.splice(g,0,b[f].id),this.shapes[b[f].id]=b[f]},insertAfterShape:function(a,b){var c=this.shapeseq,d;for(d=c.length;d--;)if(c[d]===a){c.splice(d+1,0,b.id),this.shapes[b.id]=b;return}},removeShapeId:function(a){var b=this.shapeseq,c;for(c=b.length;c--;)if(b[c]===a){b.splice(c,1);break}delete this.shapes[a]},getShapeAt:function(a,b,c){return this.targetX=b,this.targetY=c,this.render(),this.currentTargetShapeId},render:function(){var a=this.shapeseq,b=this.shapes,c=a.length,d=this._getContext(),e,f,g;d.clearRect(0,0,this.pixelWidth,this.pixelHeight);for(g=0;g<c;g++)e=a[g],f=b[e],this["_draw"+f.type].apply(this,f.args);this.interact||(this.shapes={},this.shapeseq=[])}}),J=g(H,{init:function(b,c,e){var f;J._super.init.call(this,b,c,e),e[0]&&(e=e[0]),d.data(e,"_jqs_vcanvas",this),this.canvas=a.createElement("span"),d(this.canvas).css({display:"inline-block",position:"relative",overflow:"hidden",width:b,height:c,margin:"0px",padding:"0px",verticalAlign:"top"}),this._insert(this.canvas,e),this._calculatePixelDims(b,c,this.canvas),this.canvas.width=this.pixelWidth,this.canvas.height=this.pixelHeight,f='<v:group coordorigin="0 0" coordsize="'+this.pixelWidth+" "+this.pixelHeight+'"'+' style="position:absolute;top:0;left:0;width:'+this.pixelWidth+"px;height="+this.pixelHeight+'px;"></v:group>',this.canvas.insertAdjacentHTML("beforeEnd",f),this.group=d(this.canvas).children()[0],this.rendered=!1,this.prerender=""},_drawShape:function(a,b,d,e,f){var g=[],h,i,j,k,l,m,n;for(n=0,m=b.length;n<m;n++)g[n]=""+b[n][0]+","+b[n][1];return h=g.splice(0,1),f=f===c?1:f,i=d===c?' stroked="false" ':' strokeWeight="'+f+'px" strokeColor="'+d+'" ',j=e===c?' filled="false"':' fillColor="'+e+'" filled="true" ',k=g[0]===g[g.length-1]?"x ":"",l='<v:shape coordorigin="0 0" coordsize="'+this.pixelWidth+" "+this.pixelHeight+'" '+' id="jqsshape'+a+'" '+i+j+' style="position:absolute;left:0px;top:0px;height:'+this.pixelHeight+"px;width:"+this.pixelWidth+'px;padding:0px;margin:0px;" '+' path="m '+h+" l "+g.join(", ")+" "+k+'e">'+" </v:shape>",l},_drawCircle:function(a,b,d,e,f,g,h){var i,j,k;return b-=e,d-=e,i=f===c?' stroked="false" ':' strokeWeight="'+h+'px" strokeColor="'+f+'" ',j=g===c?' filled="false"':' fillColor="'+g+'" filled="true" ',k='<v:oval  id="jqsshape'+a+'" '+i+j+' style="position:absolute;top:'+d+"px; left:"+b+"px; width:"+e*2+"px; height:"+e*2+'px"></v:oval>',k},_drawPieSlice:function(a,d,e,f,g,h,i,j){var k,l,m,n,o,p,q,r;if(g===h)return"";h-g===2*b.PI&&(g=0,h=2*b.PI),l=d+b.round(b.cos(g)*f),m=e+b.round(b.sin(g)*f),n=d+b.round(b.cos(h)*f),o=e+b.round(b.sin(h)*f);if(l===n&&m===o){if(h-g<b.PI)return"";l=n=d+f,m=o=e}return l===n&&m===o&&h-g<b.PI?"":(k=[d-f,e-f,d+f,e+f,l,m,n,o],p=i===c?' stroked="false" ':' strokeWeight="1px" strokeColor="'+i+'" ',q=j===c?' filled="false"':' fillColor="'+j+'" filled="true" ',r='<v:shape coordorigin="0 0" coordsize="'+this.pixelWidth+" "+this.pixelHeight+'" '+' id="jqsshape'+a+'" '+p+q+' style="position:absolute;left:0px;top:0px;height:'+this.pixelHeight+"px;width:"+this.pixelWidth+'px;padding:0px;margin:0px;" '+' path="m '+d+","+e+" wa "+k.join(", ")+' x e">'+" </v:shape>",r)},_drawRect:function(a,b,c,d,e,f,g){return this._drawShape(a,[[b,c],[b,c+e],[b+d,c+e],[b+d,c],[b,c]],f,g)},reset:function(){this.group.innerHTML=""},appendShape:function(a){var b=this["_draw"+a.type].apply(this,a.args);return this.rendered?this.group.insertAdjacentHTML("beforeEnd",b):this.prerender+=b,this.lastShapeId=a.id,a.id},replaceWithShape:function(a,b){var c=d("#jqsshape"+a),e=this["_draw"+b.type].apply(this,b.args);c[0].outerHTML=e},replaceWithShapes:function(a,b){var c=d("#jqsshape"+a[0]),e="",f=b.length,g;for(g=0;g<f;g++)e+=this["_draw"+b[g].type].apply(this,b[g].args);c[0].outerHTML=e;for(g=1;g<a.length;g++)d("#jqsshape"+a[g]).remove()},insertAfterShape:function(a,b){var c=d("#jqsshape"+a),e=this["_draw"+b.type].apply(this,b.args);c[0].insertAdjacentHTML("afterEnd",e)},removeShapeId:function(a){var b=d("#jqsshape"+a);this.group.removeChild(b[0])},getShapeAt:function(a,b,c){var d=a.id.substr(8);return d},render:function(){this.rendered||(this.group.innerHTML=this.prerender,this.rendered=!0)}})})})(document,Math);

// jQuery qsort niteshandbhavya.110mb.com/qsort
(function($){
  $.fn.qsort = function(o){
    qlog = function(m){
      if(window.console && console.log){
        console.log(m);
      }else{
        alert(m);
      }
    };
    function partition(array, begin, end, pivot)
    {
      var pvt=array[pivot];
      array = swap(array, pivot, end-1);
      var store=begin;
      var ptr;
      for(ptr=begin; ptr<end-1; ++ptr){
        if(array[ptr]<=pvt){
          array = swap(array, store, ptr);
          ++store;
        }
      }
      array = swap(array, end-1, store);
      return store;
    };
    function qsort(array, begin, end)
    {
      if(end-1>begin){
        var pivot=begin+Math.floor(Math.random()*(end-begin));
        pivot=partition(array, begin, end, pivot);
        qsort(array, begin, pivot);
        qsort(array, pivot+1, end);
      }
    };
    function quick_sort(array)
    {
      qsort(array, 0, array.length);
    };
    function swap(array, a, b){
      var tmp=array[a];
      array[a]=array[b];
      array[b]=tmp;
      return array;
    };
    function convertToLower(arr){
      var igAr = new Array();
      $(arr).each(function(i){
        igAr.push(this.toString().toLowerCase());
      });
      return igAr;
    };
    var defaults = {
        order: "asc",
        attr: "value",
        ignoreCase: false,
        digits: false
      };
    o = $.extend(defaults, o);
    try{
      var values = new Array();
      var oldValues = new Array();
      var elems = new Array();
      var i = 0;
      $(this).each(function(){
        elems.push($(this));
        var v = $(this).attr(o.attr);
        if(o.digits == true) {
          v = parseInt(v);
        }
        oldValues.push(v);
        values.push(v);
      });
      if(o.ignoreCase == true){
        values = convertToLower(values);
        oldValues = convertToLower(oldValues);
      }
      quick_sort(values);
      var sortedElems = new Array();
      $(values).each(function(){
        var loc = -1;
        if(o.digits==true){
          loc = $.inArray(parseInt(this.toString()), oldValues);
        }else{
          loc = $.inArray(this.toString(), oldValues);
        }
        sortedElems.push(elems[loc]);
        oldValues[loc] = null;
      });
      if(o.order == "desc"){
        for(i = 0; i < oldValues.length - 1; i++) {
          $(sortedElems[i]).before($(sortedElems[i+1]));
        }
      }else{
        for(i = 0; i < oldValues.length - 1; i++) {
          $(sortedElems[i]).after($(sortedElems[i+1]));
        }
      }
      return $(this);
    }catch(e){
      qlog("qsort: There was an error while selecting elements or the options.");
    }
  }
})(jQuery);

// Sticky 1.0.4 stickyjs.com
(function($){
  var slice = Array.prototype.slice;
  var splice = Array.prototype.splice;
  var defaults = {
      topSpacing: 0,
      bottomSpacing: 0,
      className: 'is-sticky',
      wrapperClassName: 'sticky-wrapper',
      center: false,
      getWidthFrom: '',
      widthFromWrapper: true,
      responsiveWidth: false,
      zIndex: 'auto'
    },
    $window = $(window),
    $document = $(document),
    sticked = [],
    windowHeight = $window.height(),
    scroller = function() {
      var scrollTop = $window.scrollTop(),
        documentHeight = $document.height(),
        dwh = documentHeight - windowHeight,
        extra = (scrollTop > dwh) ? dwh - scrollTop : 0;

      for (var i = 0, l = sticked.length; i < l; i++) {
        var s = sticked[i],
          elementTop = s.stickyWrapper.offset().top,
          etse = elementTop - s.topSpacing - extra;

        s.stickyWrapper.css('height', s.stickyElement.outerHeight());

        if (scrollTop <= etse) {
          if (s.currentTop !== null) {
            s.stickyElement
              .css({
                'width': '',
                'position': '',
                'top': '',
                'z-index': ''
              });
            s.stickyElement.parent().removeClass(s.className);
            s.stickyElement.trigger('sticky-end', [s]);
            s.currentTop = null;
          }
        }
        else {
          var newTop = documentHeight - s.stickyElement.outerHeight()
            - s.topSpacing - s.bottomSpacing - scrollTop - extra;
          if (newTop < 0) {
            newTop = newTop + s.topSpacing;
          } else {
            newTop = s.topSpacing;
          }
          if (s.currentTop !== newTop) {
            var newWidth;
            if (s.getWidthFrom) {
                newWidth = $(s.getWidthFrom).width() || null;
            } else if (s.widthFromWrapper) {
                newWidth = s.stickyWrapper.width();
            }
            if (newWidth == null) {
                newWidth = s.stickyElement.width();
            }
            s.stickyElement
              .css('width', newWidth)
              .css('position', 'fixed')
              .css('top', newTop)
              .css('z-index', s.zIndex);

            s.stickyElement.parent().addClass(s.className);

            if (s.currentTop === null) {
              s.stickyElement.trigger('sticky-start', [s]);
            } else {
              s.stickyElement.trigger('sticky-update', [s]);
            }

            if (s.currentTop === s.topSpacing && s.currentTop > newTop || s.currentTop === null && newTop < s.topSpacing) {
              s.stickyElement.trigger('sticky-bottom-reached', [s]);
            } else if(s.currentTop !== null && newTop === s.topSpacing && s.currentTop < newTop) {
              s.stickyElement.trigger('sticky-bottom-unreached', [s]);
            }

            s.currentTop = newTop;
          }

          var stickyWrapperContainer = s.stickyWrapper.parent();
          var unstick = (s.stickyElement.offset().top + s.stickyElement.outerHeight() >= stickyWrapperContainer.offset().top + stickyWrapperContainer.outerHeight()) && (s.stickyElement.offset().top <= s.topSpacing);

          if( unstick ) {
            s.stickyElement
              .css('position', 'absolute')
              .css('top', '')
              .css('bottom', 0)
              .css('z-index', '');
          } else {
            s.stickyElement
              .css('position', 'fixed')
              .css('top', newTop)
              .css('bottom', '')
              .css('z-index', s.zIndex);
          }
        }
      }
    },
    resizer = function() {
      windowHeight = $window.height();

      for (var i = 0, l = sticked.length; i < l; i++) {
        var s = sticked[i];
        var newWidth = null;
        if (s.getWidthFrom) {
            if (s.responsiveWidth) {
                newWidth = $(s.getWidthFrom).width();
            }
        } else if(s.widthFromWrapper) {
            newWidth = s.stickyWrapper.width();
        }
        if (newWidth != null) {
            s.stickyElement.css('width', newWidth);
        }
      }
    },
    methods = {
      init: function(options) {
        var o = $.extend({}, defaults, options);
        return this.each(function() {
          var stickyElement = $(this);

          var stickyId = stickyElement.attr('id');
          var wrapperId = stickyId ? stickyId + '-' + defaults.wrapperClassName : defaults.wrapperClassName;
          var wrapper = $('<div></div>')
            .attr('id', wrapperId)
            .addClass(o.wrapperClassName);

          stickyElement.wrapAll(function() {
            if ($(this).parent("#" + wrapperId).length == 0) {
                    return wrapper;
            }
          });

          var stickyWrapper = stickyElement.parent();

          if (o.center) {
            stickyWrapper.css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"});
          }

          if (stickyElement.css("float") === "right") {
            stickyElement.css({"float":"none"}).parent().css({"float":"right"});
          }

          o.stickyElement = stickyElement;
          o.stickyWrapper = stickyWrapper;
          o.currentTop    = null;

          sticked.push(o);

          methods.setWrapperHeight(this);
          methods.setupChangeListeners(this);
        });
      },

      setWrapperHeight: function(stickyElement) {
        var element = $(stickyElement);
        var stickyWrapper = element.parent();
        if (stickyWrapper) {
          stickyWrapper.css('height', element.outerHeight());
        }
      },

      setupChangeListeners: function(stickyElement) {
        if (window.MutationObserver) {
          var mutationObserver = new window.MutationObserver(function(mutations) {
            if (mutations[0].addedNodes.length || mutations[0].removedNodes.length) {
              methods.setWrapperHeight(stickyElement);
            }
          });
          mutationObserver.observe(stickyElement, {subtree: true, childList: true});
        } else {
          stickyElement.addEventListener('DOMNodeInserted', function() {
            methods.setWrapperHeight(stickyElement);
          }, false);
          stickyElement.addEventListener('DOMNodeRemoved', function() {
            methods.setWrapperHeight(stickyElement);
          }, false);
        }
      },
      update: scroller,
      unstick: function(options) {
        return this.each(function() {
          var that = this;
          var unstickyElement = $(that);

          var removeIdx = -1;
          var i = sticked.length;
          while (i-- > 0) {
            if (sticked[i].stickyElement.get(0) === that) {
                splice.call(sticked,i,1);
                removeIdx = i;
            }
          }
          if(removeIdx !== -1) {
            unstickyElement.unwrap();
            unstickyElement
              .css({
                'width': '',
                'position': '',
                'top': '',
                'float': '',
                'z-index': ''
              })
            ;
          }
        });
      }
    };

  if (window.addEventListener) {
    window.addEventListener('scroll', scroller, false);
    window.addEventListener('resize', resizer, false);
  } else if (window.attachEvent) {
    window.attachEvent('onscroll', scroller);
    window.attachEvent('onresize', resizer);
  }

  $.fn.sticky = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.sticky');
    }
  };

  $.fn.unstick = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method ) {
      return methods.unstick.apply( this, arguments );
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.sticky');
    }
  };
  $(function() {
    setTimeout(scroller, 0);
  });
})(jQuery);

// Visible - (c)2012, Digital Fusion, Sam Sehnert, MIT license, github.com/customd/jquery-visible
(function($){
  var $w = $(window);
  $.fn.visible = function(partial,hidden,direction){

      if (this.length < 1)
          return;

      var $t        = this.length > 1 ? this.eq(0) : this,
          t         = $t.get(0),
          vpWidth   = $w.width(),
          vpHeight  = $w.height(),
          direction = (direction) ? direction : 'both',
          clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

      if (typeof t.getBoundingClientRect === 'function'){

          var rec = t.getBoundingClientRect(),
              tViz = rec.top    >= 0 && rec.top    <  vpHeight,
              bViz = rec.bottom >  0 && rec.bottom <= vpHeight,
              lViz = rec.left   >= 0 && rec.left   <  vpWidth,
              rViz = rec.right  >  0 && rec.right  <= vpWidth,
              vVisible   = partial ? tViz || bViz : tViz && bViz,
              hVisible   = partial ? lViz || rViz : lViz && rViz;

          if(direction === 'both')
              return clientSize && vVisible && hVisible;
          else if(direction === 'vertical')
              return clientSize && vVisible;
          else if(direction === 'horizontal')
              return clientSize && hVisible;
      } else {

          var viewTop         = $w.scrollTop(),
              viewBottom      = viewTop + vpHeight,
              viewLeft        = $w.scrollLeft(),
              viewRight       = viewLeft + vpWidth,
              offset          = $t.offset(),
              _top            = offset.top,
              _bottom         = _top + $t.height(),
              _left           = offset.left,
              _right          = _left + $t.width(),
              compareTop      = partial === true ? _bottom : _top,
              compareBottom   = partial === true ? _top : _bottom,
              compareLeft     = partial === true ? _right : _left,
              compareRight    = partial === true ? _left : _right;

          if(direction === 'both')
              return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
          else if(direction === 'vertical')
              return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
          else if(direction === 'horizontal')
              return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
      }
  };
})(jQuery);

// Scrollstop 1.2.0 github.com/ssorallen/jquery-scrollstop
!function(factory){"function"==typeof define&&define.amd?define(["jquery"],factory):"object"==typeof exports?module.exports=factory(require("jquery")):factory(jQuery)}(function($){var dispatch=$.event.dispatch||$.event.handle,special=$.event.special,uid1="D"+ +new Date,uid2="D"+(+new Date+1);special.scrollstart={setup:function(data){var timer,_data=$.extend({latency:special.scrollstop.latency},data),handler=function(evt){var _self=this,_args=arguments;timer?clearTimeout(timer):(evt.type="scrollstart",dispatch.apply(_self,_args)),timer=setTimeout(function(){timer=null},_data.latency)};$(this).bind("scroll",handler).data(uid1,handler)},teardown:function(){$(this).unbind("scroll",$(this).data(uid1))}},special.scrollstop={latency:250,setup:function(data){var timer,_data=$.extend({latency:special.scrollstop.latency},data),handler=function(evt){var _self=this,_args=arguments;timer&&clearTimeout(timer),timer=setTimeout(function(){timer=null,evt.type="scrollstop",dispatch.apply(_self,_args)},_data.latency)};$(this).bind("scroll",handler).data(uid2,handler)},teardown:function(){$(this).unbind("scroll",$(this).data(uid2))}}});

// History.js 1.7.1 github.com/balupton/history.js
(function(a,b){"use strict";var c=a.History=a.History||{},d=a.jQuery;if(typeof c.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");c.Adapter={bind:function(a,b,c){d(a).bind(b,c)},trigger:function(a,b,c){d(a).trigger(b,c)},extractEventData:function(a,c,d){var e=c&&c.originalEvent&&c.originalEvent[a]||d&&d[a]||b;return e},onDomLoad:function(a){d(a)}},typeof c.init!="undefined"&&c.init()})(window),function(a,b){"use strict";var c=a.console||b,d=a.document,e=a.navigator,f=a.sessionStorage||!1,g=a.setTimeout,h=a.clearTimeout,i=a.setInterval,j=a.clearInterval,k=a.JSON,l=a.alert,m=a.History=a.History||{},n=a.history;k.stringify=k.stringify||k.encode,k.parse=k.parse||k.decode;if(typeof m.init!="undefined")throw new Error("History.js Core has already been loaded...");m.init=function(){if(typeof m.Adapter=="undefined")return!1;typeof m.initCore!="undefined"&&m.initCore(),typeof m.initHtml4!="undefined"&&m.initHtml4();return!0},m.initCore=function(){if(typeof m.initCore.initialized!="undefined")return!1;m.initCore.initialized=!0,m.options=m.options||{},m.options.hashChangeInterval=m.options.hashChangeInterval||100,m.options.safariPollInterval=m.options.safariPollInterval||500,m.options.doubleCheckInterval=m.options.doubleCheckInterval||500,m.options.storeInterval=m.options.storeInterval||1e3,m.options.busyDelay=m.options.busyDelay||250,m.options.debug=m.options.debug||!1,m.options.initialTitle=m.options.initialTitle||d.title,m.intervalList=[],m.clearAllIntervals=function(){var a,b=m.intervalList;if(typeof b!="undefined"&&b!==null){for(a=0;a<b.length;a++)j(b[a]);m.intervalList=null}},m.debug=function(){(m.options.debug||!1)&&m.log.apply(m,arguments)},m.log=function(){var a=typeof c!="undefined"&&typeof c.log!="undefined"&&typeof c.log.apply!="undefined",b=d.getElementById("log"),e,f,g,h,i;a?(h=Array.prototype.slice.call(arguments),e=h.shift(),typeof c.debug!="undefined"?c.debug.apply(c,[e,h]):c.log.apply(c,[e,h])):e="\n"+arguments[0]+"\n";for(f=1,g=arguments.length;f<g;++f){i=arguments[f];if(typeof i=="object"&&typeof k!="undefined")try{i=k.stringify(i)}catch(j){}e+="\n"+i+"\n"}b?(b.value+=e+"\n-----\n",b.scrollTop=b.scrollHeight-b.clientHeight):a||l(e);return!0},m.getInternetExplorerMajorVersion=function(){var a=m.getInternetExplorerMajorVersion.cached=typeof m.getInternetExplorerMajorVersion.cached!="undefined"?m.getInternetExplorerMajorVersion.cached:function(){var a=3,b=d.createElement("div"),c=b.getElementsByTagName("i");while((b.innerHTML="<!--[if gt IE "+ ++a+"]><i></i><![endif]-->")&&c[0]);return a>4?a:!1}();return a},m.isInternetExplorer=function(){var a=m.isInternetExplorer.cached=typeof m.isInternetExplorer.cached!="undefined"?m.isInternetExplorer.cached:Boolean(m.getInternetExplorerMajorVersion());return a},m.emulated={pushState:!Boolean(a.history&&a.history.pushState&&a.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(e.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(e.userAgent)),hashChange:Boolean(!("onhashchange"in a||"onhashchange"in d)||m.isInternetExplorer()&&m.getInternetExplorerMajorVersion()<8)},m.enabled=!m.emulated.pushState,m.bugs={setHash:Boolean(!m.emulated.pushState&&e.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(e.userAgent)),safariPoll:Boolean(!m.emulated.pushState&&e.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(e.userAgent)),ieDoubleCheck:Boolean(m.isInternetExplorer()&&m.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(m.isInternetExplorer()&&m.getInternetExplorerMajorVersion()<7)},m.isEmptyObject=function(a){for(var b in a)return!1;return!0},m.cloneObject=function(a){var b,c;a?(b=k.stringify(a),c=k.parse(b)):c={};return c},m.getRootUrl=function(){var a=d.location.protocol+"//"+(d.location.hostname||d.location.host);if(d.location.port||!1)a+=":"+d.location.port;a+="/";return a},m.getBaseHref=function(){var a=d.getElementsByTagName("base"),b=null,c="";a.length===1&&(b=a[0],c=b.href.replace(/[^\/]+$/,"")),c=c.replace(/\/+$/,""),c&&(c+="/");return c},m.getBaseUrl=function(){var a=m.getBaseHref()||m.getBasePageUrl()||m.getRootUrl();return a},m.getPageUrl=function(){var a=m.getState(!1,!1),b=(a||{}).url||d.location.href,c;c=b.replace(/\/+$/,"").replace(/[^\/]+$/,function(a,b,c){return/\./.test(a)?a:a+"/"});return c},m.getBasePageUrl=function(){var a=d.location.href.replace(/[#\?].*/,"").replace(/[^\/]+$/,function(a,b,c){return/[^\/]$/.test(a)?"":a}).replace(/\/+$/,"")+"/";return a},m.getFullUrl=function(a,b){var c=a,d=a.substring(0,1);b=typeof b=="undefined"?!0:b,/[a-z]+\:\/\//.test(a)||(d==="/"?c=m.getRootUrl()+a.replace(/^\/+/,""):d==="#"?c=m.getPageUrl().replace(/#.*/,"")+a:d==="?"?c=m.getPageUrl().replace(/[\?#].*/,"")+a:b?c=m.getBaseUrl()+a.replace(/^(\.\/)+/,""):c=m.getBasePageUrl()+a.replace(/^(\.\/)+/,""));return c.replace(/\#$/,"")},m.getShortUrl=function(a){var b=a,c=m.getBaseUrl(),d=m.getRootUrl();m.emulated.pushState&&(b=b.replace(c,"")),b=b.replace(d,"/"),m.isTraditionalAnchor(b)&&(b="./"+b),b=b.replace(/^(\.\/)+/g,"./").replace(/\#$/,"");return b},m.store={},m.idToState=m.idToState||{},m.stateToId=m.stateToId||{},m.urlToId=m.urlToId||{},m.storedStates=m.storedStates||[],m.savedStates=m.savedStates||[],m.normalizeStore=function(){m.store.idToState=m.store.idToState||{},m.store.urlToId=m.store.urlToId||{},m.store.stateToId=m.store.stateToId||{}},m.getState=function(a,b){typeof a=="undefined"&&(a=!0),typeof b=="undefined"&&(b=!0);var c=m.getLastSavedState();!c&&b&&(c=m.createStateObject()),a&&(c=m.cloneObject(c),c.url=c.cleanUrl||c.url);return c},m.getIdByState=function(a){var b=m.extractId(a.url),c;if(!b){c=m.getStateString(a);if(typeof m.stateToId[c]!="undefined")b=m.stateToId[c];else if(typeof m.store.stateToId[c]!="undefined")b=m.store.stateToId[c];else{for(;;){b=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof m.idToState[b]=="undefined"&&typeof m.store.idToState[b]=="undefined")break}m.stateToId[c]=b,m.idToState[b]=a}}return b},m.normalizeState=function(a){var b,c;if(!a||typeof a!="object")a={};if(typeof a.normalized!="undefined")return a;if(!a.data||typeof a.data!="object")a.data={};b={},b.normalized=!0,b.title=a.title||"",b.url=m.getFullUrl(m.unescapeString(a.url||d.location.href)),b.hash=m.getShortUrl(b.url),b.data=m.cloneObject(a.data),b.id=m.getIdByState(b),b.cleanUrl=b.url.replace(/\??\&_suid.*/,""),b.url=b.cleanUrl,c=!m.isEmptyObject(b.data);if(b.title||c)b.hash=m.getShortUrl(b.url).replace(/\??\&_suid.*/,""),/\?/.test(b.hash)||(b.hash+="?"),b.hash+="&_suid="+b.id;b.hashedUrl=m.getFullUrl(b.hash),(m.emulated.pushState||m.bugs.safariPoll)&&m.hasUrlDuplicate(b)&&(b.url=b.hashedUrl);return b},m.createStateObject=function(a,b,c){var d={data:a,title:b,url:c};d=m.normalizeState(d);return d},m.getStateById=function(a){a=String(a);var c=m.idToState[a]||m.store.idToState[a]||b;return c},m.getStateString=function(a){var b,c,d;b=m.normalizeState(a),c={data:b.data,title:a.title,url:a.url},d=k.stringify(c);return d},m.getStateId=function(a){var b,c;b=m.normalizeState(a),c=b.id;return c},m.getHashByState=function(a){var b,c;b=m.normalizeState(a),c=b.hash;return c},m.extractId=function(a){var b,c,d;c=/(.*)\&_suid=([0-9]+)$/.exec(a),d=c?c[1]||a:a,b=c?String(c[2]||""):"";return b||!1},m.isTraditionalAnchor=function(a){var b=!/[\/\?\.]/.test(a);return b},m.extractState=function(a,b){var c=null,d,e;b=b||!1,d=m.extractId(a),d&&(c=m.getStateById(d)),c||(e=m.getFullUrl(a),d=m.getIdByUrl(e)||!1,d&&(c=m.getStateById(d)),!c&&b&&!m.isTraditionalAnchor(a)&&(c=m.createStateObject(null,null,e)));return c},m.getIdByUrl=function(a){var c=m.urlToId[a]||m.store.urlToId[a]||b;return c},m.getLastSavedState=function(){return m.savedStates[m.savedStates.length-1]||b},m.getLastStoredState=function(){return m.storedStates[m.storedStates.length-1]||b},m.hasUrlDuplicate=function(a){var b=!1,c;c=m.extractState(a.url),b=c&&c.id!==a.id;return b},m.storeState=function(a){m.urlToId[a.url]=a.id,m.storedStates.push(m.cloneObject(a));return a},m.isLastSavedState=function(a){var b=!1,c,d,e;m.savedStates.length&&(c=a.id,d=m.getLastSavedState(),e=d.id,b=c===e);return b},m.saveState=function(a){if(m.isLastSavedState(a))return!1;m.savedStates.push(m.cloneObject(a));return!0},m.getStateByIndex=function(a){var b=null;typeof a=="undefined"?b=m.savedStates[m.savedStates.length-1]:a<0?b=m.savedStates[m.savedStates.length+a]:b=m.savedStates[a];return b},m.getHash=function(){var a=m.unescapeHash(d.location.hash);return a},m.unescapeString=function(b){var c=b,d;for(;;){d=a.unescape(c);if(d===c)break;c=d}return c},m.unescapeHash=function(a){var b=m.normalizeHash(a);b=m.unescapeString(b);return b},m.normalizeHash=function(a){var b=a.replace(/[^#]*#/,"").replace(/#.*/,"");return b},m.setHash=function(a,b){var c,e,f;if(b!==!1&&m.busy()){m.pushQueue({scope:m,callback:m.setHash,args:arguments,queue:b});return!1}c=m.escapeHash(a),m.busy(!0),e=m.extractState(a,!0),e&&!m.emulated.pushState?m.pushState(e.data,e.title,e.url,!1):d.location.hash!==c&&(m.bugs.setHash?(f=m.getPageUrl(),m.pushState(null,null,f+"#"+c,!1)):d.location.hash=c);return m},m.escapeHash=function(b){var c=m.normalizeHash(b);c=a.escape(c),m.bugs.hashEscape||(c=c.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?"));return c},m.getHashByUrl=function(a){var b=String(a).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");b=m.unescapeHash(b);return b},m.setTitle=function(a){var b=a.title,c;b||(c=m.getStateByIndex(0),c&&c.url===a.url&&(b=c.title||m.options.initialTitle));try{d.getElementsByTagName("title")[0].innerHTML=b.replace("<","&lt;").replace(">","&gt;").replace(" & "," &amp; ")}catch(e){}d.title=b;return m},m.queues=[],m.busy=function(a){typeof a!="undefined"?m.busy.flag=a:typeof m.busy.flag=="undefined"&&(m.busy.flag=!1);if(!m.busy.flag){h(m.busy.timeout);var b=function(){var a,c,d;if(!m.busy.flag)for(a=m.queues.length-1;a>=0;--a){c=m.queues[a];if(c.length===0)continue;d=c.shift(),m.fireQueueItem(d),m.busy.timeout=g(b,m.options.busyDelay)}};m.busy.timeout=g(b,m.options.busyDelay)}return m.busy.flag},m.busy.flag=!1,m.fireQueueItem=function(a){return a.callback.apply(a.scope||m,a.args||[])},m.pushQueue=function(a){m.queues[a.queue||0]=m.queues[a.queue||0]||[],m.queues[a.queue||0].push(a);return m},m.queue=function(a,b){typeof a=="function"&&(a={callback:a}),typeof b!="undefined"&&(a.queue=b),m.busy()?m.pushQueue(a):m.fireQueueItem(a);return m},m.clearQueue=function(){m.busy.flag=!1,m.queues=[];return m},m.stateChanged=!1,m.doubleChecker=!1,m.doubleCheckComplete=function(){m.stateChanged=!0,m.doubleCheckClear();return m},m.doubleCheckClear=function(){m.doubleChecker&&(h(m.doubleChecker),m.doubleChecker=!1);return m},m.doubleCheck=function(a){m.stateChanged=!1,m.doubleCheckClear(),m.bugs.ieDoubleCheck&&(m.doubleChecker=g(function(){m.doubleCheckClear(),m.stateChanged||a();return!0},m.options.doubleCheckInterval));return m},m.safariStatePoll=function(){var b=m.extractState(d.location.href),c;if(!m.isLastSavedState(b))c=b;else return;c||(c=m.createStateObject()),m.Adapter.trigger(a,"popstate");return m},m.back=function(a){if(a!==!1&&m.busy()){m.pushQueue({scope:m,callback:m.back,args:arguments,queue:a});return!1}m.busy(!0),m.doubleCheck(function(){m.back(!1)}),n.go(-1);return!0},m.forward=function(a){if(a!==!1&&m.busy()){m.pushQueue({scope:m,callback:m.forward,args:arguments,queue:a});return!1}m.busy(!0),m.doubleCheck(function(){m.forward(!1)}),n.go(1);return!0},m.go=function(a,b){var c;if(a>0)for(c=1;c<=a;++c)m.forward(b);else{if(!(a<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(c=-1;c>=a;--c)m.back(b)}return m};if(m.emulated.pushState){var o=function(){};m.pushState=m.pushState||o,m.replaceState=m.replaceState||o}else m.onPopState=function(b,c){var e=!1,f=!1,g,h;m.doubleCheckComplete(),g=m.getHash();if(g){h=m.extractState(g||d.location.href,!0),h?m.replaceState(h.data,h.title,h.url,!1):(m.Adapter.trigger(a,"anchorchange"),m.busy(!1)),m.expectedStateId=!1;return!1}e=m.Adapter.extractEventData("state",b,c)||!1,e?f=m.getStateById(e):m.expectedStateId?f=m.getStateById(m.expectedStateId):f=m.extractState(d.location.href),f||(f=m.createStateObject(null,null,d.location.href)),m.expectedStateId=!1;if(m.isLastSavedState(f)){m.busy(!1);return!1}m.storeState(f),m.saveState(f),m.setTitle(f),m.Adapter.trigger(a,"statechange"),m.busy(!1);return!0},m.Adapter.bind(a,"popstate",m.onPopState),m.pushState=function(b,c,d,e){if(m.getHashByUrl(d)&&m.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(e!==!1&&m.busy()){m.pushQueue({scope:m,callback:m.pushState,args:arguments,queue:e});return!1}m.busy(!0);var f=m.createStateObject(b,c,d);m.isLastSavedState(f)?m.busy(!1):(m.storeState(f),m.expectedStateId=f.id,n.pushState(f.id,f.title,f.url),m.Adapter.trigger(a,"popstate"));return!0},m.replaceState=function(b,c,d,e){if(m.getHashByUrl(d)&&m.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(e!==!1&&m.busy()){m.pushQueue({scope:m,callback:m.replaceState,args:arguments,queue:e});return!1}m.busy(!0);var f=m.createStateObject(b,c,d);m.isLastSavedState(f)?m.busy(!1):(m.storeState(f),m.expectedStateId=f.id,n.replaceState(f.id,f.title,f.url),m.Adapter.trigger(a,"popstate"));return!0};if(f){try{m.store=k.parse(f.getItem("History.store"))||{}}catch(p){m.store={}}m.normalizeStore()}else m.store={},m.normalizeStore();m.Adapter.bind(a,"beforeunload",m.clearAllIntervals),m.Adapter.bind(a,"unload",m.clearAllIntervals),m.saveState(m.storeState(m.extractState(d.location.href,!0))),f&&(m.onUnload=function(){var a,b;try{a=k.parse(f.getItem("History.store"))||{}}catch(c){a={}}a.idToState=a.idToState||{},a.urlToId=a.urlToId||{},a.stateToId=a.stateToId||{};for(b in m.idToState){if(!m.idToState.hasOwnProperty(b))continue;a.idToState[b]=m.idToState[b]}for(b in m.urlToId){if(!m.urlToId.hasOwnProperty(b))continue;a.urlToId[b]=m.urlToId[b]}for(b in m.stateToId){if(!m.stateToId.hasOwnProperty(b))continue;a.stateToId[b]=m.stateToId[b]}m.store=a,m.normalizeStore(),f.setItem("History.store",k.stringify(a))},m.intervalList.push(i(m.onUnload,m.options.storeInterval)),m.Adapter.bind(a,"beforeunload",m.onUnload),m.Adapter.bind(a,"unload",m.onUnload));if(!m.emulated.pushState){m.bugs.safariPoll&&m.intervalList.push(i(m.safariStatePoll,m.options.safariPollInterval));if(e.vendor==="Apple Computer, Inc."||(e.appCodeName||"")==="Mozilla")m.Adapter.bind(a,"hashchange",function(){m.Adapter.trigger(a,"popstate")}),m.getHash()&&m.Adapter.onDomLoad(function(){m.Adapter.trigger(a,"hashchange")})}},m.init()}(window);

/*
  SoundManager KVR:
  images in /static/inc/sm2/
  swf in new each update to prevent caching
*/
/*
 SoundManager 2.97a.20150601
 schillmania.com/projects/soundmanager2
 (C)2007 Scott Schiller All rights reserved
 Code provided under the BSD License: schillmania.com/projects/soundmanager2/license.txt
*/
(function(h,g){function w(gb,w){function Z(b){return c.preferFlash&&A&&!c.ignoreFlash&&c.flash[b]!==g&&c.flash[b]}function r(b){return function(c){var d=this._s;return d&&d._a?b.call(this,c):null}}this.setupOptions={url:gb||null,flashVersion:8,debugMode:!0,debugFlash:!1,useConsole:!0,consoleOnly:!0,waitForWindowLoad:!1,bgColor:"#ffffff",useHighPerformance:!1,flashPollingInterval:null,html5PollingInterval:null,flashLoadTimeout:1E3,wmode:null,allowScriptAccess:"always",useFlashBlock:!1,useHTML5Audio:!0,
forceUseGlobalHTML5Audio:!1,ignoreMobileRestrictions:!1,html5Test:/^(probably|maybe)$/i,preferFlash:!1,noSWFCache:!1,idPrefix:"sound"};this.defaultOptions={autoLoad:!1,autoPlay:!1,from:null,loops:1,onid3:null,onload:null,whileloading:null,onplay:null,onpause:null,onresume:null,whileplaying:null,onposition:null,onstop:null,onfailure:null,onfinish:null,multiShot:!0,multiShotEvents:!1,position:null,pan:0,stream:!0,to:null,type:null,usePolicyFile:!1,volume:100};this.flash9Options={isMovieStar:null,usePeakData:!1,
useWaveformData:!1,useEQData:!1,onbufferchange:null,ondataerror:null};this.movieStarOptions={bufferTime:3,serverURL:null,onconnect:null,duration:null};this.audioFormats={mp3:{type:['audio/mpeg; codecs="mp3"',"audio/mpeg","audio/mp3","audio/MPA","audio/mpa-robust"],required:!0},mp4:{related:["aac","m4a","m4b"],type:['audio/mp4; codecs="mp4a.40.2"',"audio/aac","audio/x-m4a","audio/MP4A-LATM","audio/mpeg4-generic"],required:!1},ogg:{type:["audio/ogg; codecs=vorbis"],required:!1},opus:{type:["audio/ogg; codecs=opus",
"audio/opus"],required:!1},wav:{type:['audio/wav; codecs="1"',"audio/wav","audio/wave","audio/x-wav"],required:!1}};this.movieID="sm2-container";this.id=w||"sm2movie";this.debugID="soundmanager-debug";this.debugURLParam=/([#?&])debug=1/i;this.versionNumber="V2.97a.20150601";this.altURL=this.movieURL=this.version=null;this.enabled=this.swfLoaded=!1;this.oMC=null;this.sounds={};this.soundIDs=[];this.didFlashBlock=this.muted=!1;this.filePattern=null;this.filePatterns={flash8:/\.mp3(\?.*)?$/i,flash9:/\.mp3(\?.*)?$/i};
this.features={buffering:!1,peakData:!1,waveformData:!1,eqData:!1,movieStar:!1};this.sandbox={};this.html5={usingFlash:null};this.flash={};this.ignoreFlash=this.html5Only=!1;var N,c=this,Oa=null,k=null,aa,u=navigator.userAgent,Pa=h.location.href.toString(),p=document,pa,Qa,qa,m,y=[],O=!1,P=!1,l=!1,B=!1,ra=!1,Q,x,sa,ba,ta,F,H,I,Ra,ua,va,ca,J,da,G,wa,R,xa,ea,K,Sa,ya,Ta,za,Ua,S=null,Aa=null,T,Ba,L,fa,ga,q,U=!1,Ca=!1,Va,Wa,Xa,ha=0,V=null,ia,W=[],X,v=null,Ya,ja,Y,D,ka,Da,Za,t,hb=Array.prototype.slice,
z=!1,Ea,A,Fa,$a,C,la,ab=0,Ga,Ha=u.match(/(ipad|iphone|ipod)/i),Ia=u.match(/android/i),E=u.match(/msie/i),ib=u.match(/webkit/i),ma=u.match(/safari/i)&&!u.match(/chrome/i),Ja=u.match(/opera/i),na=u.match(/(mobile|pre\/|xoom)/i)||Ha||Ia,bb=!Pa.match(/usehtml5audio/i)&&!Pa.match(/sm2\-ignorebadua/i)&&ma&&!u.match(/silk/i)&&u.match(/OS X 10_6_([3-7])/i),Ka=p.hasFocus!==g?p.hasFocus():null,oa=ma&&(p.hasFocus===g||!p.hasFocus()),cb=!oa,db=/(mp3|mp4|mpa|m4a|m4b)/i,La=p.location?p.location.protocol.match(/http/i):
null,jb=La?"":"http://",eb=/^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|m4b|mp4v|3gp|3g2)\s*(?:$|;)/i,fb="mpeg4 aac flv mov mp4 m4v f4v m4a m4b mp4v 3gp 3g2".split(" "),kb=new RegExp("\\.("+fb.join("|")+")(\\?.*)?$","i");this.mimePattern=/^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i;this.useAltURL=!La;var Ma;try{Ma=Audio!==g&&(Ja&&opera!==g&&10>opera.version()?new Audio(null):new Audio).canPlayType!==g}catch(lb){Ma=!1}this.hasHTML5=Ma;this.setup=function(b){var e=!c.url;b!==g&&l&&v&&c.ok();
sa(b);if(!z)if(na){if(!c.setupOptions.ignoreMobileRestrictions||c.setupOptions.forceUseGlobalHTML5Audio)W.push(J.globalHTML5),z=!0}else c.setupOptions.forceUseGlobalHTML5Audio&&(W.push(J.globalHTML5),z=!0);if(!Ga&&na)if(c.setupOptions.ignoreMobileRestrictions)W.push(J.ignoreMobile);else if(c.setupOptions.useHTML5Audio=!0,c.setupOptions.preferFlash=!1,Ha)c.ignoreFlash=!0;else if(Ia&&!u.match(/android\s2\.3/i)||!Ia)z=!0;b&&(e&&R&&b.url!==g&&c.beginDelayedInit(),R||b.url===g||"complete"!==p.readyState||
setTimeout(G,1));Ga=!0;return c};this.supported=this.ok=function(){return v?l&&!B:c.useHTML5Audio&&c.hasHTML5};this.getMovie=function(b){return aa(b)||p[b]||h[b]};this.createSound=function(b,e){function d(){a=fa(a);c.sounds[a.id]=new N(a);c.soundIDs.push(a.id);return c.sounds[a.id]}var a,f=null;if(!l||!c.ok())return!1;e!==g&&(b={id:b,url:e});a=x(b);a.url=ia(a.url);a.id===g&&(a.id=c.setupOptions.idPrefix+ab++);if(q(a.id,!0))return c.sounds[a.id];if(ja(a))f=d(),f._setup_html5(a);else{if(c.html5Only||
c.html5.usingFlash&&a.url&&a.url.match(/data\:/i))return d();8<m&&null===a.isMovieStar&&(a.isMovieStar=!!(a.serverURL||a.type&&a.type.match(eb)||a.url&&a.url.match(kb)));a=ga(a,void 0);f=d();8===m?k._createSound(a.id,a.loops||1,a.usePolicyFile):(k._createSound(a.id,a.url,a.usePeakData,a.useWaveformData,a.useEQData,a.isMovieStar,a.isMovieStar?a.bufferTime:!1,a.loops||1,a.serverURL,a.duration||null,a.autoPlay,!0,a.autoLoad,a.usePolicyFile),a.serverURL||(f.connected=!0,a.onconnect&&a.onconnect.apply(f)));
a.serverURL||!a.autoLoad&&!a.autoPlay||f.load(a)}!a.serverURL&&a.autoPlay&&f.play();return f};this.destroySound=function(b,e){if(!q(b))return!1;var d=c.sounds[b],a;d.stop();d._iO={};d.unload();for(a=0;a<c.soundIDs.length;a++)if(c.soundIDs[a]===b){c.soundIDs.splice(a,1);break}e||d.destruct(!0);delete c.sounds[b];return!0};this.load=function(b,e){return q(b)?c.sounds[b].load(e):!1};this.unload=function(b){return q(b)?c.sounds[b].unload():!1};this.onposition=this.onPosition=function(b,e,d,a){return q(b)?
c.sounds[b].onposition(e,d,a):!1};this.clearOnPosition=function(b,e,d){return q(b)?c.sounds[b].clearOnPosition(e,d):!1};this.start=this.play=function(b,e){var d=null,a=e&&!(e instanceof Object);if(!l||!c.ok())return!1;if(q(b,a))a&&(e={url:e});else{if(!a)return!1;a&&(e={url:e});e&&e.url&&(e.id=b,d=c.createSound(e).play())}null===d&&(d=c.sounds[b].play(e));return d};this.setPosition=function(b,e){return q(b)?c.sounds[b].setPosition(e):!1};this.stop=function(b){return q(b)?c.sounds[b].stop():!1};this.stopAll=
function(){for(var b in c.sounds)c.sounds.hasOwnProperty(b)&&c.sounds[b].stop()};this.pause=function(b){return q(b)?c.sounds[b].pause():!1};this.pauseAll=function(){var b;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].pause()};this.resume=function(b){return q(b)?c.sounds[b].resume():!1};this.resumeAll=function(){var b;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].resume()};this.togglePause=function(b){return q(b)?c.sounds[b].togglePause():!1};this.setPan=function(b,e){return q(b)?
c.sounds[b].setPan(e):!1};this.setVolume=function(b,e){var d,a;if(b===g||isNaN(b)||e!==g)return q(b)?c.sounds[b].setVolume(e):!1;d=0;for(a=c.soundIDs.length;d<a;d++)c.sounds[c.soundIDs[d]].setVolume(b)};this.mute=function(b){var e=0;b instanceof String&&(b=null);if(b)return q(b)?c.sounds[b].mute():!1;for(e=c.soundIDs.length-1;0<=e;e--)c.sounds[c.soundIDs[e]].mute();return c.muted=!0};this.muteAll=function(){c.mute()};this.unmute=function(b){b instanceof String&&(b=null);if(b)return q(b)?c.sounds[b].unmute():
!1;for(b=c.soundIDs.length-1;0<=b;b--)c.sounds[c.soundIDs[b]].unmute();c.muted=!1;return!0};this.unmuteAll=function(){c.unmute()};this.toggleMute=function(b){return q(b)?c.sounds[b].toggleMute():!1};this.getMemoryUse=function(){var b=0;k&&8!==m&&(b=parseInt(k._getMemoryUse(),10));return b};this.disable=function(b){var e;b===g&&(b=!1);if(B)return!1;B=!0;for(e=c.soundIDs.length-1;0<=e;e--)Ta(c.sounds[c.soundIDs[e]]);Q(b);t.remove(h,"load",H);return!0};this.canPlayMIME=function(b){var e;c.hasHTML5&&
(e=Y({type:b}));!e&&v&&(e=b&&c.ok()?!!(8<m&&b.match(eb)||b.match(c.mimePattern)):null);return e};this.canPlayURL=function(b){var e;c.hasHTML5&&(e=Y({url:b}));!e&&v&&(e=b&&c.ok()?!!b.match(c.filePattern):null);return e};this.canPlayLink=function(b){return b.type!==g&&b.type&&c.canPlayMIME(b.type)?!0:c.canPlayURL(b.href)};this.getSoundById=function(b,e){return b?c.sounds[b]:null};this.onready=function(b,c){if("function"===typeof b)c||(c=h),ta("onready",b,c),F();else throw T("needFunction","onready");
return!0};this.ontimeout=function(b,c){if("function"===typeof b)c||(c=h),ta("ontimeout",b,c),F({type:"ontimeout"});else throw T("needFunction","ontimeout");return!0};this._wD=this._writeDebug=function(b,c){return!0};this._debug=function(){};this.reboot=function(b,e){var d,a,f;for(d=c.soundIDs.length-1;0<=d;d--)c.sounds[c.soundIDs[d]].destruct();if(k)try{E&&(Aa=k.innerHTML),S=k.parentNode.removeChild(k)}catch(g){}Aa=S=v=k=null;c.enabled=R=l=U=Ca=O=P=B=z=c.swfLoaded=!1;c.soundIDs=[];c.sounds={};ab=
0;Ga=!1;if(b)y=[];else for(d in y)if(y.hasOwnProperty(d))for(a=0,f=y[d].length;a<f;a++)y[d][a].fired=!1;c.html5={usingFlash:null};c.flash={};c.html5Only=!1;c.ignoreFlash=!1;h.setTimeout(function(){e||c.beginDelayedInit()},20);return c};this.reset=function(){return c.reboot(!0,!0)};this.getMoviePercent=function(){return k&&"PercentLoaded"in k?k.PercentLoaded():null};this.beginDelayedInit=function(){ra=!0;G();setTimeout(function(){if(Ca)return!1;ea();da();return Ca=!0},20);I()};this.destruct=function(){c.disable(!0)};
N=function(b){var e,d,a=this,f,n,h,M,p,r,u=!1,l=[],v=0,y,B,w=null,A;d=e=null;this.sID=this.id=b.id;this.url=b.url;this._iO=this.instanceOptions=this.options=x(b);this.pan=this.options.pan;this.volume=this.options.volume;this.isHTML5=!1;this._a=null;A=this.url?!1:!0;this.id3={};this._debug=function(){};this.load=function(b){var e=null,d;b!==g?a._iO=x(b,a.options):(b=a.options,a._iO=b,w&&w!==a.url&&(a._iO.url=a.url,a.url=null));a._iO.url||(a._iO.url=a.url);a._iO.url=ia(a._iO.url);d=a.instanceOptions=
a._iO;if(!d.url&&!a.url)return a;if(d.url===a.url&&0!==a.readyState&&2!==a.readyState)return 3===a.readyState&&d.onload&&la(a,function(){d.onload.apply(a,[!!a.duration])}),a;a.loaded=!1;a.readyState=1;a.playState=0;a.id3={};if(ja(d))e=a._setup_html5(d),e._called_load||(a._html5_canplay=!1,a.url!==d.url&&(a._a.src=d.url,a.setPosition(0)),a._a.autobuffer="auto",a._a.preload="auto",a._a._called_load=!0);else{if(c.html5Only||a._iO.url&&a._iO.url.match(/data\:/i))return a;try{a.isHTML5=!1,a._iO=ga(fa(d)),
a._iO.autoPlay&&(a._iO.position||a._iO.from)&&(a._iO.autoPlay=!1),d=a._iO,8===m?k._load(a.id,d.url,d.stream,d.autoPlay,d.usePolicyFile):k._load(a.id,d.url,!!d.stream,!!d.autoPlay,d.loops||1,!!d.autoLoad,d.usePolicyFile)}catch(f){K({type:"SMSOUND_LOAD_JS_EXCEPTION",fatal:!0})}}a.url=d.url;return a};this.unload=function(){0!==a.readyState&&(a.isHTML5?(M(),a._a&&(a._a.pause(),w=ka(a._a))):8===m?k._unload(a.id,"about:blank"):k._unload(a.id),f());return a};this.destruct=function(b){a.isHTML5?(M(),a._a&&
(a._a.pause(),ka(a._a),z||h(),a._a._s=null,a._a=null)):(a._iO.onfailure=null,k._destroySound(a.id));b||c.destroySound(a.id,!0)};this.start=this.play=function(b,e){var d,f,n,h,Na;f=!0;f=null;e=e===g?!0:e;b||(b={});a.url&&(a._iO.url=a.url);a._iO=x(a._iO,a.options);a._iO=x(b,a._iO);a._iO.url=ia(a._iO.url);a.instanceOptions=a._iO;if(!a.isHTML5&&a._iO.serverURL&&!a.connected)return a.getAutoPlay()||a.setAutoPlay(!0),a;ja(a._iO)&&(a._setup_html5(a._iO),p());1!==a.playState||a.paused||(d=a._iO.multiShot,
d||(a.isHTML5&&a.setPosition(a._iO.position),f=a));if(null!==f)return f;b.url&&b.url!==a.url&&(a.readyState||a.isHTML5||8!==m||!A?a.load(a._iO):A=!1);a.loaded||(0===a.readyState?(a.isHTML5||c.html5Only?a.isHTML5?a.load(a._iO):f=a:(a._iO.autoPlay=!0,a.load(a._iO)),a.instanceOptions=a._iO):2===a.readyState&&(f=a));if(null!==f)return f;!a.isHTML5&&9===m&&0<a.position&&a.position===a.duration&&(b.position=0);if(a.paused&&0<=a.position&&(!a._iO.serverURL||0<a.position))a.resume();else{a._iO=x(b,a._iO);
if((!a.isHTML5&&null!==a._iO.position&&0<a._iO.position||null!==a._iO.from&&0<a._iO.from||null!==a._iO.to)&&0===a.instanceCount&&0===a.playState&&!a._iO.serverURL){d=function(){a._iO=x(b,a._iO);a.play(a._iO)};a.isHTML5&&!a._html5_canplay?(a.load({_oncanplay:d}),f=!1):a.isHTML5||a.loaded||a.readyState&&2===a.readyState||(a.load({onload:d}),f=!1);if(null!==f)return f;a._iO=B()}(!a.instanceCount||a._iO.multiShotEvents||a.isHTML5&&a._iO.multiShot&&!z||!a.isHTML5&&8<m&&!a.getAutoPlay())&&a.instanceCount++;
a._iO.onposition&&0===a.playState&&r(a);a.playState=1;a.paused=!1;a.position=a._iO.position===g||isNaN(a._iO.position)?0:a._iO.position;a.isHTML5||(a._iO=ga(fa(a._iO)));a._iO.onplay&&e&&(a._iO.onplay.apply(a),u=!0);a.setVolume(a._iO.volume,!0);a.setPan(a._iO.pan,!0);a.isHTML5?2>a.instanceCount?(p(),f=a._setup_html5(),a.setPosition(a._iO.position),f.play()):(n=new Audio(a._iO.url),h=function(){t.remove(n,"ended",h);a._onfinish(a);ka(n);n=null},Na=function(){t.remove(n,"canplay",Na);try{n.currentTime=
a._iO.position/1E3}catch(b){}n.play()},t.add(n,"ended",h),a._iO.volume!==g&&(n.volume=Math.max(0,Math.min(1,a._iO.volume/100))),a.muted&&(n.muted=!0),a._iO.position?t.add(n,"canplay",Na):n.play()):(f=k._start(a.id,a._iO.loops||1,9===m?a.position:a.position/1E3,a._iO.multiShot||!1),9!==m||f||a._iO.onplayerror&&a._iO.onplayerror.apply(a))}return a};this.stop=function(b){var c=a._iO;1===a.playState&&(a._onbufferchange(0),a._resetOnPosition(0),a.paused=!1,a.isHTML5||(a.playState=0),y(),c.to&&a.clearOnPosition(c.to),
a.isHTML5?a._a&&(b=a.position,a.setPosition(0),a.position=b,a._a.pause(),a.playState=0,a._onTimer(),M()):(k._stop(a.id,b),c.serverURL&&a.unload()),a.instanceCount=0,a._iO={},c.onstop&&c.onstop.apply(a));return a};this.setAutoPlay=function(b){a._iO.autoPlay=b;a.isHTML5||(k._setAutoPlay(a.id,b),b&&(a.instanceCount||1!==a.readyState||a.instanceCount++))};this.getAutoPlay=function(){return a._iO.autoPlay};this.setPosition=function(b){b===g&&(b=0);var c=a.isHTML5?Math.max(b,0):Math.min(a.duration||a._iO.duration,
Math.max(b,0));a.position=c;b=a.position/1E3;a._resetOnPosition(a.position);a._iO.position=c;if(!a.isHTML5)b=9===m?a.position:b,a.readyState&&2!==a.readyState&&k._setPosition(a.id,b,a.paused||!a.playState,a._iO.multiShot);else if(a._a){if(a._html5_canplay){if(a._a.currentTime!==b)try{a._a.currentTime=b,(0===a.playState||a.paused)&&a._a.pause()}catch(e){}}else if(b)return a;a.paused&&a._onTimer(!0)}return a};this.pause=function(b){if(a.paused||0===a.playState&&1!==a.readyState)return a;a.paused=!0;
a.isHTML5?(a._setup_html5().pause(),M()):(b||b===g)&&k._pause(a.id,a._iO.multiShot);a._iO.onpause&&a._iO.onpause.apply(a);return a};this.resume=function(){var b=a._iO;if(!a.paused)return a;a.paused=!1;a.playState=1;a.isHTML5?(a._setup_html5().play(),p()):(b.isMovieStar&&!b.serverURL&&a.setPosition(a.position),k._pause(a.id,b.multiShot));!u&&b.onplay?(b.onplay.apply(a),u=!0):b.onresume&&b.onresume.apply(a);return a};this.togglePause=function(){if(0===a.playState)return a.play({position:9!==m||a.isHTML5?
a.position/1E3:a.position}),a;a.paused?a.resume():a.pause();return a};this.setPan=function(b,c){b===g&&(b=0);c===g&&(c=!1);a.isHTML5||k._setPan(a.id,b);a._iO.pan=b;c||(a.pan=b,a.options.pan=b);return a};this.setVolume=function(b,e){b===g&&(b=100);e===g&&(e=!1);a.isHTML5?a._a&&(c.muted&&!a.muted&&(a.muted=!0,a._a.muted=!0),a._a.volume=Math.max(0,Math.min(1,b/100))):k._setVolume(a.id,c.muted&&!a.muted||a.muted?0:b);a._iO.volume=b;e||(a.volume=b,a.options.volume=b);return a};this.mute=function(){a.muted=
!0;a.isHTML5?a._a&&(a._a.muted=!0):k._setVolume(a.id,0);return a};this.unmute=function(){a.muted=!1;var b=a._iO.volume!==g;a.isHTML5?a._a&&(a._a.muted=!1):k._setVolume(a.id,b?a._iO.volume:a.options.volume);return a};this.toggleMute=function(){return a.muted?a.unmute():a.mute()};this.onposition=this.onPosition=function(b,c,e){l.push({position:parseInt(b,10),method:c,scope:e!==g?e:a,fired:!1});return a};this.clearOnPosition=function(a,b){var c;a=parseInt(a,10);if(isNaN(a))return!1;for(c=0;c<l.length;c++)a!==
l[c].position||b&&b!==l[c].method||(l[c].fired&&v--,l.splice(c,1))};this._processOnPosition=function(){var b,c;b=l.length;if(!b||!a.playState||v>=b)return!1;for(--b;0<=b;b--)c=l[b],!c.fired&&a.position>=c.position&&(c.fired=!0,v++,c.method.apply(c.scope,[c.position]));return!0};this._resetOnPosition=function(a){var b,c;b=l.length;if(!b)return!1;for(--b;0<=b;b--)c=l[b],c.fired&&a<=c.position&&(c.fired=!1,v--);return!0};B=function(){var b=a._iO,c=b.from,e=b.to,d,f;f=function(){a.clearOnPosition(e,f);
a.stop()};d=function(){if(null!==e&&!isNaN(e))a.onPosition(e,f)};null===c||isNaN(c)||(b.position=c,b.multiShot=!1,d());return b};r=function(){var b,c=a._iO.onposition;if(c)for(b in c)if(c.hasOwnProperty(b))a.onPosition(parseInt(b,10),c[b])};y=function(){var b,c=a._iO.onposition;if(c)for(b in c)c.hasOwnProperty(b)&&a.clearOnPosition(parseInt(b,10))};p=function(){a.isHTML5&&Va(a)};M=function(){a.isHTML5&&Wa(a)};f=function(b){b||(l=[],v=0);u=!1;a._hasTimer=null;a._a=null;a._html5_canplay=!1;a.bytesLoaded=
null;a.bytesTotal=null;a.duration=a._iO&&a._iO.duration?a._iO.duration:null;a.durationEstimate=null;a.buffered=[];a.eqData=[];a.eqData.left=[];a.eqData.right=[];a.failures=0;a.isBuffering=!1;a.instanceOptions={};a.instanceCount=0;a.loaded=!1;a.metadata={};a.readyState=0;a.muted=!1;a.paused=!1;a.peakData={left:0,right:0};a.waveformData={left:[],right:[]};a.playState=0;a.position=null;a.id3={}};f();this._onTimer=function(b){var c,f=!1,g={};if(a._hasTimer||b)return a._a&&(b||(0<a.playState||1===a.readyState)&&
!a.paused)&&(c=a._get_html5_duration(),c!==e&&(e=c,a.duration=c,f=!0),a.durationEstimate=a.duration,c=1E3*a._a.currentTime||0,c!==d&&(d=c,f=!0),(f||b)&&a._whileplaying(c,g,g,g,g)),f};this._get_html5_duration=function(){var b=a._iO;return(b=a._a&&a._a.duration?1E3*a._a.duration:b&&b.duration?b.duration:null)&&!isNaN(b)&&Infinity!==b?b:null};this._apply_loop=function(a,b){a.loop=1<b?"loop":""};this._setup_html5=function(b){b=x(a._iO,b);var c=z?Oa:a._a,e=decodeURI(b.url),d;z?e===decodeURI(Ea)&&(d=!0):
e===decodeURI(w)&&(d=!0);if(c){if(c._s)if(z)c._s&&c._s.playState&&!d&&c._s.stop();else if(!z&&e===decodeURI(w))return a._apply_loop(c,b.loops),c;d||(w&&f(!1),c.src=b.url,Ea=w=a.url=b.url,c._called_load=!1)}else b.autoLoad||b.autoPlay?(a._a=new Audio(b.url),a._a.load()):a._a=Ja&&10>opera.version()?new Audio(null):new Audio,c=a._a,c._called_load=!1,z&&(Oa=c);a.isHTML5=!0;a._a=c;c._s=a;n();a._apply_loop(c,b.loops);b.autoLoad||b.autoPlay?a.load():(c.autobuffer=!1,c.preload="auto");return c};n=function(){if(a._a._added_events)return!1;
var b;a._a._added_events=!0;for(b in C)C.hasOwnProperty(b)&&a._a&&a._a.addEventListener(b,C[b],!1);return!0};h=function(){var b;a._a._added_events=!1;for(b in C)C.hasOwnProperty(b)&&a._a&&a._a.removeEventListener(b,C[b],!1)};this._onload=function(b){var c=!!b||!a.isHTML5&&8===m&&a.duration;a.loaded=c;a.readyState=c?3:2;a._onbufferchange(0);a._iO.onload&&la(a,function(){a._iO.onload.apply(a,[c])});return!0};this._onbufferchange=function(b){if(0===a.playState||b&&a.isBuffering||!b&&!a.isBuffering)return!1;
a.isBuffering=1===b;a._iO.onbufferchange&&a._iO.onbufferchange.apply(a,[b]);return!0};this._onsuspend=function(){a._iO.onsuspend&&a._iO.onsuspend.apply(a);return!0};this._onfailure=function(b,c,e){a.failures++;if(a._iO.onfailure&&1===a.failures)a._iO.onfailure(b,c,e)};this._onwarning=function(b,c,e){if(a._iO.onwarning)a._iO.onwarning(b,c,e)};this._onfinish=function(){var b=a._iO.onfinish;a._onbufferchange(0);a._resetOnPosition(0);a.instanceCount&&(a.instanceCount--,a.instanceCount||(y(),a.playState=
0,a.paused=!1,a.instanceCount=0,a.instanceOptions={},a._iO={},M(),a.isHTML5&&(a.position=0)),(!a.instanceCount||a._iO.multiShotEvents)&&b&&la(a,function(){b.apply(a)}))};this._whileloading=function(b,c,e,d){var f=a._iO;a.bytesLoaded=b;a.bytesTotal=c;a.duration=Math.floor(e);a.bufferLength=d;a.durationEstimate=a.isHTML5||f.isMovieStar?a.duration:f.duration?a.duration>f.duration?a.duration:f.duration:parseInt(a.bytesTotal/a.bytesLoaded*a.duration,10);a.isHTML5||(a.buffered=[{start:0,end:a.duration}]);
(3!==a.readyState||a.isHTML5)&&f.whileloading&&f.whileloading.apply(a)};this._whileplaying=function(b,c,e,d,f){var n=a._iO;if(isNaN(b)||null===b)return!1;a.position=Math.max(0,b);a._processOnPosition();!a.isHTML5&&8<m&&(n.usePeakData&&c!==g&&c&&(a.peakData={left:c.leftPeak,right:c.rightPeak}),n.useWaveformData&&e!==g&&e&&(a.waveformData={left:e.split(","),right:d.split(",")}),n.useEQData&&f!==g&&f&&f.leftEQ&&(b=f.leftEQ.split(","),a.eqData=b,a.eqData.left=b,f.rightEQ!==g&&f.rightEQ&&(a.eqData.right=
f.rightEQ.split(","))));1===a.playState&&(a.isHTML5||8!==m||a.position||!a.isBuffering||a._onbufferchange(0),n.whileplaying&&n.whileplaying.apply(a));return!0};this._oncaptiondata=function(b){a.captiondata=b;a._iO.oncaptiondata&&a._iO.oncaptiondata.apply(a,[b])};this._onmetadata=function(b,c){var e={},d,f;d=0;for(f=b.length;d<f;d++)e[b[d]]=c[d];a.metadata=e;a._iO.onmetadata&&a._iO.onmetadata.call(a,a.metadata)};this._onid3=function(b,c){var e=[],d,f;d=0;for(f=b.length;d<f;d++)e[b[d]]=c[d];a.id3=x(a.id3,
e);a._iO.onid3&&a._iO.onid3.apply(a)};this._onconnect=function(b){b=1===b;if(a.connected=b)a.failures=0,q(a.id)&&(a.getAutoPlay()?a.play(g,a.getAutoPlay()):a._iO.autoLoad&&a.load()),a._iO.onconnect&&a._iO.onconnect.apply(a,[b])};this._ondataerror=function(b){0<a.playState&&a._iO.ondataerror&&a._iO.ondataerror.apply(a)}};xa=function(){return p.body||p.getElementsByTagName("div")[0]};aa=function(b){return p.getElementById(b)};x=function(b,e){var d=b||{},a,f;a=e===g?c.defaultOptions:e;for(f in a)a.hasOwnProperty(f)&&
d[f]===g&&(d[f]="object"!==typeof a[f]||null===a[f]?a[f]:x(d[f],a[f]));return d};la=function(b,c){b.isHTML5||8!==m?c():h.setTimeout(c,0)};ba={onready:1,ontimeout:1,defaultOptions:1,flash9Options:1,movieStarOptions:1};sa=function(b,e){var d,a=!0,f=e!==g,n=c.setupOptions;for(d in b)if(b.hasOwnProperty(d))if("object"!==typeof b[d]||null===b[d]||b[d]instanceof Array||b[d]instanceof RegExp)f&&ba[e]!==g?c[e][d]=b[d]:n[d]!==g?(c.setupOptions[d]=b[d],c[d]=b[d]):ba[d]===g?a=!1:c[d]instanceof Function?c[d].apply(c,
b[d]instanceof Array?b[d]:[b[d]]):c[d]=b[d];else if(ba[d]===g)a=!1;else return sa(b[d],d);return a};t=function(){function b(a){a=hb.call(a);var b=a.length;d?(a[1]="on"+a[1],3<b&&a.pop()):3===b&&a.push(!1);return a}function c(b,e){var g=b.shift(),h=[a[e]];if(d)g[h](b[0],b[1]);else g[h].apply(g,b)}var d=h.attachEvent,a={add:d?"attachEvent":"addEventListener",remove:d?"detachEvent":"removeEventListener"};return{add:function(){c(b(arguments),"add")},remove:function(){c(b(arguments),"remove")}}}();C={abort:r(function(){}),
canplay:r(function(){var b=this._s,c;if(b._html5_canplay)return!0;b._html5_canplay=!0;b._onbufferchange(0);c=b._iO.position===g||isNaN(b._iO.position)?null:b._iO.position/1E3;if(this.currentTime!==c)try{this.currentTime=c}catch(d){}b._iO._oncanplay&&b._iO._oncanplay()}),canplaythrough:r(function(){var b=this._s;b.loaded||(b._onbufferchange(0),b._whileloading(b.bytesLoaded,b.bytesTotal,b._get_html5_duration()),b._onload(!0))}),durationchange:r(function(){var b=this._s,c;c=b._get_html5_duration();isNaN(c)||
c===b.duration||(b.durationEstimate=b.duration=c)}),ended:r(function(){this._s._onfinish()}),error:r(function(){this._s._onload(!1)}),loadeddata:r(function(){var b=this._s;b._loaded||ma||(b.duration=b._get_html5_duration())}),loadedmetadata:r(function(){}),loadstart:r(function(){this._s._onbufferchange(1)}),play:r(function(){this._s._onbufferchange(0)}),playing:r(function(){this._s._onbufferchange(0)}),progress:r(function(b){var c=this._s,d,a,f=0,f=b.target.buffered;d=b.loaded||0;var g=b.total||1;
c.buffered=[];if(f&&f.length){d=0;for(a=f.length;d<a;d++)c.buffered.push({start:1E3*f.start(d),end:1E3*f.end(d)});f=1E3*(f.end(0)-f.start(0));d=Math.min(1,f/(1E3*b.target.duration))}isNaN(d)||(c._whileloading(d,g,c._get_html5_duration()),d&&g&&d===g&&C.canplaythrough.call(this,b))}),ratechange:r(function(){}),suspend:r(function(b){var c=this._s;C.progress.call(this,b);c._onsuspend()}),stalled:r(function(){}),timeupdate:r(function(){this._s._onTimer()}),waiting:r(function(){this._s._onbufferchange(1)})};
ja=function(b){return b&&(b.type||b.url||b.serverURL)?b.serverURL||b.type&&Z(b.type)?!1:b.type?Y({type:b.type}):Y({url:b.url})||c.html5Only||b.url.match(/data\:/i):!1};ka=function(b){var e;b&&(e=ma?"about:blank":c.html5.canPlayType("audio/wav")?"data:audio/wave;base64,/UklGRiYAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQIAAAD//w==":"about:blank",b.src=e,b._called_unload!==g&&(b._called_load=!1));z&&(Ea=null);return e};Y=function(b){if(!c.useHTML5Audio||!c.hasHTML5)return!1;var e=b.url||null;b=b.type||
null;var d=c.audioFormats,a;if(b&&c.html5[b]!==g)return c.html5[b]&&!Z(b);if(!D){D=[];for(a in d)d.hasOwnProperty(a)&&(D.push(a),d[a].related&&(D=D.concat(d[a].related)));D=new RegExp("\\.("+D.join("|")+")(\\?.*)?$","i")}(a=e?e.toLowerCase().match(D):null)&&a.length?a=a[1]:b&&(e=b.indexOf(";"),a=(-1!==e?b.substr(0,e):b).substr(6));a&&c.html5[a]!==g?e=c.html5[a]&&!Z(a):(b="audio/"+a,e=c.html5.canPlayType({type:b}),e=(c.html5[a]=e)&&c.html5[b]&&!Z(b));return e};Za=function(){function b(a){var b,d=b=
!1;if(!e||"function"!==typeof e.canPlayType)return b;if(a instanceof Array){h=0;for(b=a.length;h<b;h++)if(c.html5[a[h]]||e.canPlayType(a[h]).match(c.html5Test))d=!0,c.html5[a[h]]=!0,c.flash[a[h]]=!!a[h].match(db);b=d}else a=e&&"function"===typeof e.canPlayType?e.canPlayType(a):!1,b=!(!a||!a.match(c.html5Test));return b}if(!c.useHTML5Audio||!c.hasHTML5)return v=c.html5.usingFlash=!0,!1;var e=Audio!==g?Ja&&10>opera.version()?new Audio(null):new Audio:null,d,a,f={},n,h;n=c.audioFormats;for(d in n)if(n.hasOwnProperty(d)&&
(a="audio/"+d,f[d]=b(n[d].type),f[a]=f[d],d.match(db)?(c.flash[d]=!0,c.flash[a]=!0):(c.flash[d]=!1,c.flash[a]=!1),n[d]&&n[d].related))for(h=n[d].related.length-1;0<=h;h--)f["audio/"+n[d].related[h]]=f[d],c.html5[n[d].related[h]]=f[d],c.flash[n[d].related[h]]=f[d];f.canPlayType=e?b:null;c.html5=x(c.html5,f);c.html5.usingFlash=Ya();v=c.html5.usingFlash;return!0};J={};T=function(){};fa=function(b){8===m&&1<b.loops&&b.stream&&(b.stream=!1);return b};ga=function(b,c){b&&!b.usePolicyFile&&(b.onid3||b.usePeakData||
b.useWaveformData||b.useEQData)&&(b.usePolicyFile=!0);return b};pa=function(){return!1};Ta=function(b){for(var c in b)b.hasOwnProperty(c)&&"function"===typeof b[c]&&(b[c]=pa)};za=function(b){b===g&&(b=!1);(B||b)&&c.disable(b)};Ua=function(b){var e=null;if(b)if(b.match(/\.swf(\?.*)?$/i)){if(e=b.substr(b.toLowerCase().lastIndexOf(".swf?")+4))return b}else b.lastIndexOf("/")!==b.length-1&&(b+="/");b=(b&&-1!==b.lastIndexOf("/")?b.substr(0,b.lastIndexOf("/")+1):"./")+c.movieURL;c.noSWFCache&&(b+="?ts="+
(new Date).getTime());return b};va=function(){m=parseInt(c.flashVersion,10);8!==m&&9!==m&&(c.flashVersion=m=8);var b=c.debugMode||c.debugFlash?"_debug.swf":".swf";c.useHTML5Audio&&!c.html5Only&&c.audioFormats.mp4.required&&9>m&&(c.flashVersion=m=9);c.version=c.versionNumber+(c.html5Only?" (HTML5-only mode)":9===m?" (AS3/Flash 9)":" (AS2/Flash 8)");8<m?(c.defaultOptions=x(c.defaultOptions,c.flash9Options),c.features.buffering=!0,c.defaultOptions=x(c.defaultOptions,c.movieStarOptions),c.filePatterns.flash9=
new RegExp("\\.(mp3|"+fb.join("|")+")(\\?.*)?$","i"),c.features.movieStar=!0):c.features.movieStar=!1;c.filePattern=c.filePatterns[8!==m?"flash9":"flash8"];c.movieURL=(8===m?"soundmanager2.swf":"soundmanager2_flash9.swf").replace(".swf",b);c.features.peakData=c.features.waveformData=c.features.eqData=8<m};Sa=function(b,c){if(!k)return!1;k._setPolling(b,c)};ya=function(){};q=this.getSoundById;L=function(){var b=[];c.debugMode&&b.push("sm2_debug");c.debugFlash&&b.push("flash_debug");c.useHighPerformance&&
b.push("high_performance");return b.join(" ")};Ba=function(){T("fbHandler");var b=c.getMoviePercent(),e={type:"FLASHBLOCK"};if(c.html5Only)return!1;c.ok()?c.oMC&&(c.oMC.className=[L(),"movieContainer","swf_loaded"+(c.didFlashBlock?" swf_unblocked":"")].join(" ")):(v&&(c.oMC.className=L()+" movieContainer "+(null===b?"swf_timedout":"swf_error")),c.didFlashBlock=!0,F({type:"ontimeout",ignoreInit:!0,error:e}),K(e))};ta=function(b,c,d){y[b]===g&&(y[b]=[]);y[b].push({method:c,scope:d||null,fired:!1})};
F=function(b){b||(b={type:c.ok()?"onready":"ontimeout"});if(!l&&b&&!b.ignoreInit||"ontimeout"===b.type&&(c.ok()||B&&!b.ignoreInit))return!1;var e={success:b&&b.ignoreInit?c.ok():!B},d=b&&b.type?y[b.type]||[]:[],a=[],f,e=[e],g=v&&!c.ok();b.error&&(e[0].error=b.error);b=0;for(f=d.length;b<f;b++)!0!==d[b].fired&&a.push(d[b]);if(a.length)for(b=0,f=a.length;b<f;b++)a[b].scope?a[b].method.apply(a[b].scope,e):a[b].method.apply(this,e),g||(a[b].fired=!0);return!0};H=function(){h.setTimeout(function(){c.useFlashBlock&&
Ba();F();"function"===typeof c.onload&&c.onload.apply(h);c.waitForWindowLoad&&t.add(h,"load",H)},1)};Fa=function(){if(A!==g)return A;var b=!1,c=navigator,d=c.plugins,a,f=h.ActiveXObject;if(d&&d.length)(c=c.mimeTypes)&&c["application/x-shockwave-flash"]&&c["application/x-shockwave-flash"].enabledPlugin&&c["application/x-shockwave-flash"].enabledPlugin.description&&(b=!0);else if(f!==g&&!u.match(/MSAppHost/i)){try{a=new f("ShockwaveFlash.ShockwaveFlash")}catch(n){a=null}b=!!a}return A=b};Ya=function(){var b,
e,d=c.audioFormats;Ha&&u.match(/os (1|2|3_0|3_1)\s/i)?(c.hasHTML5=!1,c.html5Only=!0,c.oMC&&(c.oMC.style.display="none")):!c.useHTML5Audio||c.html5&&c.html5.canPlayType||(c.hasHTML5=!1);if(c.useHTML5Audio&&c.hasHTML5)for(e in X=!0,d)d.hasOwnProperty(e)&&d[e].required&&(c.html5.canPlayType(d[e].type)?c.preferFlash&&(c.flash[e]||c.flash[d[e].type])&&(b=!0):(X=!1,b=!0));c.ignoreFlash&&(b=!1,X=!0);c.html5Only=c.hasHTML5&&c.useHTML5Audio&&!b;return!c.html5Only};ia=function(b){var e,d,a=0;if(b instanceof
Array){e=0;for(d=b.length;e<d;e++)if(b[e]instanceof Object){if(c.canPlayMIME(b[e].type)){a=e;break}}else if(c.canPlayURL(b[e])){a=e;break}b[a].url&&(b[a]=b[a].url);b=b[a]}return b};Va=function(b){b._hasTimer||(b._hasTimer=!0,!na&&c.html5PollingInterval&&(null===V&&0===ha&&(V=setInterval(Xa,c.html5PollingInterval)),ha++))};Wa=function(b){b._hasTimer&&(b._hasTimer=!1,!na&&c.html5PollingInterval&&ha--)};Xa=function(){var b;if(null!==V&&!ha)return clearInterval(V),V=null,!1;for(b=c.soundIDs.length-1;0<=
b;b--)c.sounds[c.soundIDs[b]].isHTML5&&c.sounds[c.soundIDs[b]]._hasTimer&&c.sounds[c.soundIDs[b]]._onTimer()};K=function(b){b=b!==g?b:{};"function"===typeof c.onerror&&c.onerror.apply(h,[{type:b.type!==g?b.type:null}]);b.fatal!==g&&b.fatal&&c.disable()};$a=function(){if(!bb||!Fa())return!1;var b=c.audioFormats,e,d;for(d in b)if(b.hasOwnProperty(d)&&("mp3"===d||"mp4"===d)&&(c.html5[d]=!1,b[d]&&b[d].related))for(e=b[d].related.length-1;0<=e;e--)c.html5[b[d].related[e]]=!1};this._setSandboxType=function(b){};
this._externalInterfaceOK=function(b){if(c.swfLoaded)return!1;c.swfLoaded=!0;oa=!1;bb&&$a();setTimeout(qa,E?100:1)};ea=function(b,e){function d(a,b){return'<param name="'+a+'" value="'+b+'" />'}if(O&&P)return!1;if(c.html5Only)return va(),c.oMC=aa(c.movieID),qa(),P=O=!0,!1;var a=e||c.url,f=c.altURL||a,h=xa(),k=L(),m=null,m=p.getElementsByTagName("html")[0],l,r,q,m=m&&m.dir&&m.dir.match(/rtl/i);b=b===g?c.id:b;va();c.url=Ua(La?a:f);e=c.url;c.wmode=!c.wmode&&c.useHighPerformance?"transparent":c.wmode;
null!==c.wmode&&(u.match(/msie 8/i)||!E&&!c.useHighPerformance)&&navigator.platform.match(/win32|win64/i)&&(W.push(J.spcWmode),c.wmode=null);h={name:b,id:b,src:e,quality:"high",allowScriptAccess:c.allowScriptAccess,bgcolor:c.bgColor,pluginspage:jb+"www.macromedia.com/go/getflashplayer",title:"JS/Flash audio component (SoundManager 2)",type:"application/x-shockwave-flash",wmode:c.wmode,hasPriority:"true"};c.debugFlash&&(h.FlashVars="debug=1");c.wmode||delete h.wmode;if(E)a=p.createElement("div"),r=
['<object id="'+b+'" data="'+e+'" type="'+h.type+'" title="'+h.title+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">',d("movie",e),d("AllowScriptAccess",c.allowScriptAccess),d("quality",h.quality),c.wmode?d("wmode",c.wmode):"",d("bgcolor",c.bgColor),d("hasPriority","true"),c.debugFlash?d("FlashVars",h.FlashVars):"","</object>"].join("");else for(l in a=p.createElement("embed"),h)h.hasOwnProperty(l)&&
a.setAttribute(l,h[l]);ya();k=L();if(h=xa())if(c.oMC=aa(c.movieID)||p.createElement("div"),c.oMC.id)q=c.oMC.className,c.oMC.className=(q?q+" ":"movieContainer")+(k?" "+k:""),c.oMC.appendChild(a),E&&(l=c.oMC.appendChild(p.createElement("div")),l.className="sm2-object-box",l.innerHTML=r),P=!0;else{c.oMC.id=c.movieID;c.oMC.className="movieContainer "+k;l=k=null;c.useFlashBlock||(c.useHighPerformance?k={position:"fixed",width:"8px",height:"8px",bottom:"0px",left:"0px",overflow:"hidden"}:(k={position:"absolute",
width:"6px",height:"6px",top:"-9999px",left:"-9999px"},m&&(k.left=Math.abs(parseInt(k.left,10))+"px")));ib&&(c.oMC.style.zIndex=1E4);if(!c.debugFlash)for(q in k)k.hasOwnProperty(q)&&(c.oMC.style[q]=k[q]);try{E||c.oMC.appendChild(a),h.appendChild(c.oMC),E&&(l=c.oMC.appendChild(p.createElement("div")),l.className="sm2-object-box",l.innerHTML=r),P=!0}catch(t){throw Error(T("domError")+" \n"+t.toString());}}return O=!0};da=function(){if(c.html5Only)return ea(),!1;if(k||!c.url)return!1;k=c.getMovie(c.id);
k||(S?(E?c.oMC.innerHTML=Aa:c.oMC.appendChild(S),S=null,O=!0):ea(c.id,c.url),k=c.getMovie(c.id));"function"===typeof c.oninitmovie&&setTimeout(c.oninitmovie,1);return!0};I=function(){setTimeout(Ra,1E3)};ua=function(){h.setTimeout(function(){c.setup({preferFlash:!1}).reboot();c.didFlashBlock=!0;c.beginDelayedInit()},1)};Ra=function(){var b,e=!1;if(!c.url||U)return!1;U=!0;t.remove(h,"load",I);if(A&&oa&&!Ka)return!1;l||(b=c.getMoviePercent(),0<b&&100>b&&(e=!0));setTimeout(function(){b=c.getMoviePercent();
if(e)return U=!1,h.setTimeout(I,1),!1;!l&&cb&&(null===b?c.useFlashBlock||0===c.flashLoadTimeout?c.useFlashBlock&&Ba():!c.useFlashBlock&&X?ua():F({type:"ontimeout",ignoreInit:!0,error:{type:"INIT_FLASHBLOCK"}}):0!==c.flashLoadTimeout&&(!c.useFlashBlock&&X?ua():za(!0)))},c.flashLoadTimeout)};ca=function(){if(Ka||!oa)return t.remove(h,"focus",ca),!0;Ka=cb=!0;U=!1;I();t.remove(h,"focus",ca);return!0};Q=function(b){if(l)return!1;if(c.html5Only)return l=!0,H(),!0;var e=!0,d;c.useFlashBlock&&c.flashLoadTimeout&&
!c.getMoviePercent()||(l=!0);d={type:!A&&v?"NO_FLASH":"INIT_TIMEOUT"};if(B||b)c.useFlashBlock&&c.oMC&&(c.oMC.className=L()+" "+(null===c.getMoviePercent()?"swf_timedout":"swf_error")),F({type:"ontimeout",error:d,ignoreInit:!0}),K(d),e=!1;B||(c.waitForWindowLoad&&!ra?t.add(h,"load",H):H());return e};Qa=function(){var b,e=c.setupOptions;for(b in e)e.hasOwnProperty(b)&&(c[b]===g?c[b]=e[b]:c[b]!==e[b]&&(c.setupOptions[b]=c[b]))};qa=function(){if(l)return!1;if(c.html5Only)return l||(t.remove(h,"load",
c.beginDelayedInit),c.enabled=!0,Q()),!0;da();try{k._externalInterfaceTest(!1),Sa(!0,c.flashPollingInterval||(c.useHighPerformance?10:50)),c.debugMode||k._disableDebug(),c.enabled=!0,c.html5Only||t.add(h,"unload",pa)}catch(b){return K({type:"JS_TO_FLASH_EXCEPTION",fatal:!0}),za(!0),Q(),!1}Q();t.remove(h,"load",c.beginDelayedInit);return!0};G=function(){if(R)return!1;R=!0;Qa();ya();!A&&c.hasHTML5&&c.setup({useHTML5Audio:!0,preferFlash:!1});Za();!A&&v&&(W.push(J.needFlash),c.setup({flashLoadTimeout:1}));
p.removeEventListener&&p.removeEventListener("DOMContentLoaded",G,!1);da();return!0};Da=function(){"complete"===p.readyState&&(G(),p.detachEvent("onreadystatechange",Da));return!0};wa=function(){ra=!0;G();t.remove(h,"load",wa)};Fa();t.add(h,"focus",ca);t.add(h,"load",I);t.add(h,"load",wa);p.addEventListener?p.addEventListener("DOMContentLoaded",G,!1):p.attachEvent?p.attachEvent("onreadystatechange",Da):K({type:"NO_DOM2_EVENTS",fatal:!0})}if(!h||!h.document)throw Error("SoundManager requires a browser with window and document objects.");
var N=null;h.SM2_DEFER!==g&&SM2_DEFER||(N=new w);"object"===typeof module&&module&&"object"===typeof module.exports?(module.exports.SoundManager=w,module.exports.soundManager=N):"function"===typeof define&&define.amd&&define(function(){return{constructor:w,getInstance:function(g){!h.soundManager&&g instanceof Function&&(g=g(w),g instanceof w&&(h.soundManager=g));return h.soundManager}}});h.SoundManager=w;h.soundManager=N})(window);

/* SoundManager 2: Play MP3 links "in-place" */
function InlinePlayer(){
  var self = this;
  var pl = this;
  var sm = soundManager;
  var isIE = (navigator.userAgent.match(/msie/i));
  this.playableClass = 'inline-playable';
  this.excludeClass = 'inline-exclude';
  this.links = [];
  this.sounds = [];
  this.soundsByURL = [];
  this.indexByURL = [];
  this.lastSound = null;
  this.soundCount = 0;

  this.config = {
    playNext: true,
    autoPlay: false
  }

  this.css = {
    sDefault: 'sm2_link',
    sLoading: 'sm2_loading',
    sPlaying: 'sm2_playing',
    sPaused: 'sm2_paused'
  }

  this.addEventHandler = (typeof window.addEventListener !== 'undefined' ? function(o, evtName, evtHandler) {
    return o.addEventListener(evtName,evtHandler,false);
  } : function(o, evtName, evtHandler) {
    o.attachEvent('on'+evtName,evtHandler);
  });

  this.removeEventHandler = (typeof window.removeEventListener !== 'undefined' ? function(o, evtName, evtHandler) {
    return o.removeEventListener(evtName,evtHandler,false);
  } : function(o, evtName, evtHandler) {
    return o.detachEvent('on'+evtName,evtHandler);
  });

  this.classContains = function(o,cStr) {
    return (typeof(o.className)!='undefined'?o.className.match(new RegExp('(\\s|^)'+cStr+'(\\s|$)')):false);
  }

  this.addClass = function(o,cStr) {
    if (!o || !cStr || self.classContains(o,cStr)) return false;
    o.className = (o.className?o.className+' ':'')+cStr;
  }

  this.removeClass = function(o,cStr) {
    if (!o || !cStr || !self.classContains(o,cStr)) return false;
    o.className = o.className.replace(new RegExp('( '+cStr+')|('+cStr+')','g'),'');
  }

  this.getSoundByURL = function(sURL) {
    return (typeof self.soundsByURL[sURL] != 'undefined'?self.soundsByURL[sURL]:null);
  }

  this.isChildOfNode = function(o,sNodeName) {
    if (!o || !o.parentNode) {
      return false;
    }
    sNodeName = sNodeName.toLowerCase();
    do {
      o = o.parentNode;
    } while (o && o.parentNode && o.nodeName.toLowerCase() != sNodeName);
    return (o.nodeName.toLowerCase() == sNodeName?o:null);
  }

  this.events = {
    play: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = pl.css.sPlaying;
      pl.addClass(this._data.oLink,this._data.className);
    },
    stop: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = '';
    },
    pause: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = pl.css.sPaused;
      pl.addClass(this._data.oLink,this._data.className);
    },
    resume: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = pl.css.sPlaying;
      pl.addClass(this._data.oLink,this._data.className);
    },
    finish: function() {
      pl.removeClass(this._data.oLink,this._data.className);
      this._data.className = '';
      if (pl.config.playNext) {
        var nextLink = (pl.indexByURL[this._data.oLink.href]+1);
        if (nextLink<pl.links.length) {
          pl.handleClick({'target':pl.links[nextLink]});
        }
      }
    }
  }

  this.stopEvent = function(e) {
   if (typeof e != 'undefined' && typeof e.preventDefault != 'undefined') {
      e.preventDefault();
    } else if (typeof event != 'undefined' && typeof event.returnValue != 'undefined') {
      event.returnValue = false;
    }
    return false;
  }

  this.getTheDamnLink = (isIE)?function(e) {
    return (e && e.target?e.target:window.event.srcElement);
  }:function(e) {
    return e.target;
  }

  this.handleClick = function(e) {
    if (typeof e.button != 'undefined' && e.button>1) {
      return true;
    }
    var o = self.getTheDamnLink(e);
    if (o.nodeName.toLowerCase() != 'a') {
      o = self.isChildOfNode(o,'a');
      if (!o) return true;
    }
    var sURL = o.getAttribute('href');
    if (!o.href || (!sm.canPlayLink(o) && !self.classContains(o,self.playableClass)) || self.classContains(o,self.excludeClass)) {
      return true;
    }
    var soundURL = (o.href);
    var thisSound = self.getSoundByURL(soundURL);
    if (thisSound) {
      if (thisSound == self.lastSound) {
        thisSound.togglePause();
      } else {
        sm._writeDebug('sound different than last sound: '+self.lastSound.id);
        if (self.lastSound) {
          self.stopSound(self.lastSound);
        }
        thisSound.togglePause();
      }
    } else {
      if (self.lastSound) {
        self.stopSound(self.lastSound);
      }
      thisSound = sm.createSound({
       id:'inlineMP3Sound'+(self.soundCount++),
       url:soundURL,
       onplay:self.events.play,
       onstop:self.events.stop,
       onpause:self.events.pause,
       onresume:self.events.resume,
       onfinish:self.events.finish,
       type:(o.type||null)
      });
      thisSound._data = {
        oLink: o,
        className: self.css.sPlaying
      };
      self.soundsByURL[soundURL] = thisSound;
      self.sounds.push(thisSound);
      thisSound.play();
    }

    self.lastSound = thisSound;

    if (typeof e != 'undefined' && typeof e.preventDefault != 'undefined') {
      e.preventDefault();
    } else {
      event.returnValue = false;
    }
    return false;
  }

  this.stopSound = function(oSound) {
    soundManager.stop(oSound.id);
    soundManager.unload(oSound.id);
  }

  this.init = function() {
    sm._writeDebug('inlinePlayer.init()');
    var oLinks = document.getElementsByTagName('a');
    var foundItems = 0;
    for (var i=0, j=oLinks.length; i<j; i++) {
      if ((sm.canPlayLink(oLinks[i]) || self.classContains(oLinks[i],self.playableClass)) && !self.classContains(oLinks[i],self.excludeClass)) {
        self.addClass(oLinks[i],self.css.sDefault);
        self.links[foundItems] = (oLinks[i]);
        self.indexByURL[oLinks[i].href] = foundItems;
        foundItems++;
      }
    }
    if (foundItems>0) {
      self.addEventHandler(document,'click',self.handleClick);
      if (self.config.autoPlay) {
        self.handleClick({target:self.links[0],preventDefault:function(){}});
      }
    }
    sm._writeDebug('inlinePlayer.init(): Found '+foundItems+' relevant items.');
  }

  this.init();
}

var inlinePlayer = null;
soundManager.setup({
  url: '/static/inc/sm2swf8/',
  debugMode: false,
  preferFlash: false,
  useFlashBlock: true,
  flashVersion: 9,
  useHTML5Audio: true
});

/* KVR */
var kvrckeditor        = '462',
    kvrloadingimg1     = '<img src="//static.kvraudio.com/i/loading16.gif" width="16" height="16">',
    kvrloadingimg1wht  = '<span class="kvrloadingimg1wht"><img src="//static.kvraudio.com/i/loading16.gif" width="16" height="16" alt="please wait..."></span>',
    kvrloadingimg1div  = '<div id="kvrloadingimg1div"><img src="//static.kvraudio.com/i/loading16.gif" width="16" height="16"></div>',
    kvrloadingimg2div  = '<div id="kvrloadingimg2div"><img src="//static.kvraudio.com/i/loading16.gif" width="16" height="16"></div>',
    kvrloadingimg16x11 = '<img src="//static.kvraudio.com/i/loader-16x11.gif" width="16" height="11" alt="">',
    kvrloadingcss3an1  = '<span class="kvrloadingcss3an1"></span>',
    kvrloadingcss3an2  = '<span class="kvrloadingcss3an2"></span>',
    kvrloadingcss3an3  = '<span class="kvrloadingcss3an3"></span>',
    kvrmyup2dclass     = ["kvrhasupds","kvrisuptd","kvrnotsync"],
    kvrmyicons         = {"ign":"<span class=\"mylimi\" title=\"Ignore Versions\">I</span>","uni":"<span class=\"mylimi\" title=\"Unique Versions\">U</span>","pub":"<span class=\"mylimi\" title=\"Public\">P</span>"},
    kvrajax            = "", // facilitates aborting
    mykvr              = "",
    mykvrisdirty       = false,
    mykvrtr            = {},                            // {"trid":[pid,grp,os,cls,[grps]]}; master tr list [grps = quick arr of all grps in if global]
    mykvrtrs           = [],                            // array of all tr ids - only used for lazy loading/appending, then emptied
    mykvrtab           = {"0":[],"1":[],"2":[],"3":[]}, // "All Prods" Tabs {0=hasupds, 1=uptd, 2=notsync,3=ignored}
    mykvrtabbyg        = {},                            // [grp]:{"0":[],"1":[],"2":[],"3":[],"4":[]}; specific grp tab cache (3=ignored; 4=nomatchos)
    mykvr_stopsnappy   = 5,                             // control snappy
    mykvr_insnappy     = false;                         // snappy

function kvr_cleanse_string(id, numonly)
{
  var str = $("#"+id).val();
  if(numonly)
  {
    $("#"+id).val(str.replace(/[^0-9]/g,'').trim());
  }else{
    $("#"+id).val(str.replace(/ {2,}/g,' ').replace(/[^a-zA-Z0-9 \.\'\-]/g,'').trim());
  }
  return true;
}

function kvr_frmshp_reset(){
  $("#frmshp")[0].reset();
  $("#frmshp input[type=radio]:checked").trigger("change");
  $("#frmshp .kvrselmenreset").click();
}

function kvr_kart_is_in()
{
  $(".inkvrshop").each(function(){
    var i = $(this).data("i");
    var s = $(this).find(".kartinmy");
    if(kvrkart.indexOf(i) != -1)
    {
      s.show().removeClass("flexnoneimp");
      $("a[data-id='"+i+"']").addClass("active");
    }else{
      s.hide().addClass("flexnoneimp");
      $("a[data-id='"+i+"']").removeClass("active");
    }
  });

  if(kvrkart.length > 0)
  {
    $("#kvrcartsummary").addClass("kartnotempty");
  }else{
    $("#kvrcartsummary").removeClass("kartnotempty");
  }
}

function kvr_version_compare(v1, v2, operator)
{
  // phpjs.org/functions/version_compare - JS of PHP version_compare
  var i = 0,
      x = 0,
      compare = 0,
      vm = {
        'dev': -6,
        'alpha': -5,
        'a': -5,
        'beta': -4,
        'b': -4,
        'RC': -3,
        'rc': -3,
        '#': -2,
        'p': 1,
        'pl': 1
      },
      prepVersion = function(v) {
        v = ('' + v)
          .replace(/[_\-+]/g, '.');
        v = v.replace(/([^.\d]+)/g, '.$1.')
          .replace(/\.{2,}/g, '.');
        return (!v.length ? [-8] : v.split('.'));
      };

  numVersion = function(v) {
    return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10));
  };

  v1 = prepVersion(v1);
  v2 = prepVersion(v2);
  x = Math.max(v1.length, v2.length);

  for (i = 0; i < x; i++) {
    if (v1[i] == v2[i]) {
      continue;
    }
    v1[i] = numVersion(v1[i]);
    v2[i] = numVersion(v2[i]);
    if (v1[i] < v2[i]) {
      compare = -1;
      break;
    } else if (v1[i] > v2[i]) {
      compare = 1;
      break;
    }
  }

  if (!operator) {
    return compare;
  }

  switch (operator) {
    case '>':
    case 'gt':
      return (compare > 0);
    case '>=':
    case 'ge':
      return (compare >= 0);
    case '<=':
    case 'le':
      return (compare <= 0);
    case '==':
    case '=':
    case 'eq':
      return (compare === 0);
    case '<>':
    case '!=':
    case 'ne':
      return (compare !== 0);
    case '':
    case '<':
    case 'lt':
      return (compare < 0);
    default:
      return null;
  }
}

function kvr_array_pushnsplice(arr,k,val,act)
{
  arr = eval(arr);
  val = parseInt(val,10);
  var ind;

  if(k)
  {
    if(act == "1") // add to
    {
      arr[k] = (typeof arr[k] != 'undefined' && arr[k] instanceof Array) ? arr[k] : [];
      arr[k].push(val);
    }else{ // delete from
      ind = arr[k].indexOf(val);
      if(ind != -1)
      {
        arr[k].splice(ind, 1);
      }
    }
  }else{
    if(act == "1") // add to
    {
      arr = (typeof arr != 'undefined' && arr instanceof Array) ? arr : [];
      arr.push(val);
    }else{ // delete from
      ind = arr.indexOf(val);
      if(ind != -1)
      {
        arr.splice(ind, 1);
      }
    }
  }
  return false;
}

function kvr_az90(str)
{
  return str.replace(/[^a-zA-Z0-9]/g,'').toLowerCase();
}

function kvr_destroy_ck(editorname)
{
  if(window.CKEDITOR){if(CKEDITOR.instances[editorname]){CKEDITOR.instances[editorname].destroy(true);}}
}

function kvr_ckeditor_create(func,obj)
{
  if(!window.CKEDITOR)
  {
    if(obj)
    {
      var curbut = $(obj);
      var curtext = $(obj).html();
      $(obj).html(kvrloadingcss3an2);
    }
    $.ajax({
      url: "//static.kvraudio.com/inc/ckeditor"+kvrckeditor+"/ckeditor.js",
      cache: true,
      dataType: "script"
    }).done(function(){
      $.ajax({
        url: "//static.kvraudio.com/inc/ckeditor"+kvrckeditor+"/adapters/jquery.js",
        cache: true,
        dataType: "script"
      }).done(function(){
        if(obj)
        {
          $(curbut).html(curtext);
          func(curbut);
        }else{
          func();
        }
      });
    }).fail(function(){
      if(obj)
      {
        $(curbut).html(curtext);
        alert("An error occurred!");
      }
    });
  }else{
    if(obj)
    {
      func($(obj));
    }else{
      func();
    }
  }
  return false;
}

function kvr_gabbleform(ths)
{
  var div = $(ths).closest("div");
  $(div).after($("#gabbleform"));
  $("#gabblr").val($(div).data("gid"));
  $("#gabbli").val($(div).data("i"));
  $("#gabblit").ckeditor({
    toolbar: [["Bold","Italic","Underline","-","NumberedList","BulletedList","-","Link","Unlink","-","SpecialChar"],["About"]],
    height: "200px",
    forcePasteAsPlainText: true,
    resize_enabled: false,
    disableObjectResizing: true,
    entities_additional: '',
    forceEnterMode: true,
    removePlugins: "tabletools,contextmenu,liststyle,elementspath",
    disableNativeSpellChecker: false
  });
  $("#gabbleform").slideDown();
}

function kvr_revieweditor(ths)
{
  $("#revieweditor").ckeditor({
    toolbar :[["Bold", "Italic", "Underline", "-", "NumberedList", "BulletedList", "-", "Link", "Unlink", "-", "SpecialChar"],["About"]],
    height: "1000px",
    forcePasteAsPlainText: true,
    resize_enabled : false,
    disableObjectResizing: true,
    removePlugins : "tabletools,contextmenu,liststyle,elementspath",
    disableNativeSpellChecker: false
  });
  return false;
}

function mykvr_summary_counts()
{
  var i = $("#mymessages .msginbox").length;
  var s = $("#mymessages .msgsent").length;
  var st = $("#mymessages .msgstarred").length;
  var a = $("#mymessages .msgarchived").length;
  var u = $(".mymessage[data-r='0']").length;
  $("#mymsgsum0").text(s);
  $("#mymsgsum1").text(i);
  $("#mymsgsum2").text(a);
  $("#mymsgsum3").text(st);
  $("#mymsgsum4").text(i+s+a);
  $(".myunread").text(u);
  return false;
}

function mykvr_set_productorder()
{
  var s = Object.keys(mykvr.products);
  s.sort(function(a,b){return mykvr.products[a][0].localeCompare(mykvr.products[b][0]);});
  var o = [];
  for(i in s)
  {
    o.push(parseInt(s[i],10));
  }
  mykvr.p = o;
  return true;
}

function mykvr_refresh_lims()
{
  var g, o, t;
  if($("#filtergrps1").length > 0)
  {
    $("#filtergrps1 .mylims").empty().removeClass("mylims1");
    $("#mykvrgrpsreader .mylims").empty().removeClass("mylims1");

    // separate appends ARE faster
    $.each(mykvr.ignored,function(k,v){
      $("#filtergrps1 a[data-val="+v+"] span.mylims").append(kvrmyicons["ign"]);
      $("#mykvrgrpsreader a[data-val="+v+"] span.mylims").append(kvrmyicons["ign"]);
    });
    $.each(mykvr.unique,function(k,v){
      $("#filtergrps1 a[data-val="+v+"] span.mylims").append(kvrmyicons["uni"]);
      $("#mykvrgrpsreader a[data-val="+v+"] span.mylims").append(kvrmyicons["uni"]);
    });
    $.each(mykvr.publish,function(k,v){
      $("#filtergrps1 a[data-val="+v+"] span.mylims").append(kvrmyicons["pub"]);
      $("#mykvrgrpsreader a[data-val="+v+"] span.mylims").append(kvrmyicons["pub"]);
    });

    for(g in mykvr.osbygroup)
    {
      t = "";
      for(o in mykvr.osbygroup[g])
      {
        t = mykvr.os[mykvr.osbygroup[g][o]][3] + t;
      }
      $("#filtergrps1 a[data-val="+g+"] span.mylims").prepend(t).addClass("mylims1");
      $("#mykvrgrpsreader a[data-val="+g+"] span.mylims").prepend(t).addClass("mylims1");
    }
    $("#filtergrps0").html($("#filtergrps1 a.active").html());
  }
  return false;
}

function mykvr_product_versions(os,id,grp,ver)
{
  var p = mykvr.products[id];
  var p3 = p[3];
  var p3os = p3[os];
  if(typeof p3os == 'undefined')
  {
    return 'There is a problem with this product\'s database entry and it cannot be versioned for the selected OS.';
  }

  var o = '';
  o += '<span class="kvrversion">';
  o += '<span class="kvrver"><span class="spit sp'+mykvr.os[os][1]+'s" title="'+mykvr.os[os][0]+'">&nbsp;</span></span>';
  o += '<span class="kvrverlatest elliptit">'+(p3os[0]?p3os[0]:'?')+'</span>';
  o += '<span class="kvrsyncmyversion"><a href="#" data-id="'+id+'" data-os="'+os+'" data-group="'+grp+'" title="Update mine to '+p3os[0]+'" class="kvrbutton">&raquo;</a></span>';
  o += '<span class="kvrvermy elliptit"><a href="#" class="kvrveredit" id="kvredit_'+os+'_'+id+'_'+grp+'_'+Date.now()+'" data-id="'+id+'" data-os="'+os+'" data-group="'+grp+'" title="Edit my version">'+ver[0]+'</a></span>';
  o += '<span class="kvrmydl">'+(p3os[3]?'<a href="'+p3os[3]+'" class="kvrbutton" title="Download"><span class="spit spdl">&nbsp;</span>Download</a>':'')+'</span>';
  o += '</span>';
  return o;
}

function mykvr_refresh_display(sortit,grp,shownow)
{
  if($("#mykvrmykvrpage").length == 0)
  {
    return false;
  }

  $("#mykvrpageisloading").show();

  var create_trs = $("#mykvrtable tr").length == 0 ? true : false; // page load lazy load uses obj of trs, added in batches

  var k, o, i1, i2, i2i, i3, ind, mykvrversionsk, mykvrproductsk, mykvrversionski2, mykvrallgroupsi2, mykvrversionski2i3, mykvrbyprodk, mykvrproductsk3i3, tblrow = '';
  var mykvrp = mykvr.p;
  var tblrow = shownow ? ' tblrow' : '';

  for(i1 in mykvrp)
  {
    k = mykvrp[i1];
    mykvrversionsk = mykvr.versions[k];
    mykvrproductsk = mykvr.products[k];

    if(mykvrversionsk)
    {
      for(i2 in mykvrversionsk) // Group Level i2 = grpid
      {
        mykvrversionski2 = mykvrversionsk[i2];
        mykvrallgroupsi2 = mykvr.allgroups[i2];
        i2i = parseInt(i2,10);
        for(i3 in mykvrversionski2) // OS Level i3 = osid
        {
          if($('#my_'+k+'_'+i2+'_'+i3).length == 0) // my_pid_grp_os
          {
            mykvrversionski2i3 = mykvrversionski2[i3];
            mykvrproductsk3i3 = mykvrproductsk[3][i3];
            mykvrtr['my_'+k+'_'+i2+'_'+i3] = [k,i2i,parseInt(i3,10),parseInt(mykvrversionski2i3[1],10),[]];
            mykvrtab[mykvrversionski2i3[1]].push('my_'+k+'_'+i2+'_'+i3);

            o += '<tr id="my_'+k+'_'+i2+'_'+i3+'" data-pid="'+k+'" data-grp="'+i2+'" data-p="'+mykvrproductsk[2]+'" data-os="'+i3+'" class="'+kvrmyup2dclass[mykvrversionski2i3[1]]+tblrow+'">' + "\n";
            o += '<td class="tdmyimg"><div style="background-image: url(//static.kvraudio.com/i/t/'+mykvrproductsk[1]+');"></div></td>';
            o += '<td class="tdmyprod"><div class="posrelit"><span class="mykvr pid'+k+' activeblue" data-id="'+k+'">My KVR<span class="spit spdarr"></span></span><a href="/product/'+k+'"><b>'+mykvrproductsk[0]+'</b></a><span class="kvrsmltxt">'+(i2!=0?'in: '+mykvrallgroupsi2:'<em>global</em>')+'</span></div></td>';
            o += '<td class="tdmyver"><div class="posrelit">'+mykvr_product_versions(i3,k,i2,mykvrversionski2i3)+'<div class="tdmydate">'+(typeof mykvrproductsk3i3 != 'undefined' ? (mykvrproductsk3i3[1]?mykvrproductsk3i3[1]:''):'')+'</div></div></td>';
            o += '</tr>';

            if(create_trs)
            {
              mykvrtrs['my_'+k+'_'+i2+'_'+i3] = o;
              o = ''; // reset
            }
          }
        }
      }
    }

    if(mykvr.ignored.length)
    {
      mykvrbyprodk = mykvr.byprod[k];
      for(i2 in mykvrbyprodk) // Group Level i2 = grpid
      {
        i2i = parseInt(mykvrbyprodk[i2],10);
        if(mykvr.ignored.indexOf(i2i) != -1 && mykvr.hidden.indexOf(i2i) == -1)
        {
          i3 = 0; // don't create unecessary os rows for ignored products
          if($('#my_'+k+'_'+i2i+'_'+i3+'_ignored').length == 0) // my_pid_grp_os_ignored
          {
            mykvrtr['my_'+k+'_'+i2i+'_'+i3+'_ignored'] = [k,i2i,i3,4,[]];

            o += '<tr id="my_'+k+'_'+i2i+'_'+i3+'_ignored" data-pid="'+k+'" data-grp="'+i2i+'" data-p="'+mykvrproductsk[2]+'" data-os="'+i3+'" class="kvrignore'+tblrow+'">' + "\n";
            o += '<td class="tdmyimg"><div style="background-image: url(//static.kvraudio.com/i/t/'+mykvrproductsk[1]+');"></div></td>';
            o += '<td class="tdmyprod"><div class="posrelit"><span class="mykvr pid'+k+' activeblue" data-id="'+k+'">My KVR<span class="spit spdarr"></span></span><a href="/product/'+k+'"><b>'+mykvrproductsk[0]+'</b></a><span class="kvrsmltxt">'+(i2i!=0?'in: '+mykvr.allgroups[i2i]:'<em>global</em>')+'</span></div></td>';
            o += '<td class="tdmyver">In a group ignored from versioning</td>';
            o += '</tr>';

            if(create_trs)
            {
              mykvrtrs['my_'+k+'_'+i2i+'_'+i3+'_ignored'] = o;
              o = ''; // reset
            }
          }
        }
      }
    }
  }

  if(!create_trs && o) // added new rows so append them
  {
    $("#mykvrtable tbody").append(o);
    if(sortit)
    {
      setTimeout(function(){mykvr_sort_table("mykvrtable","data-p");},0);
    }
  }

  if(grp)
  {
    mykvr_tabbyg_build(false,grp); // rebuild
  }

  $("#mykvrpageisloading").hide();

  if(mykvr_group_summary())
  {
    mykvr_update_mysums($("#filtergrps1 a.active").data("val"));
  }

  if(!create_trs && (o || grp))
  {
    return true; // means mykvr_tabbyg_build has already run
  }
  return false;
}

function mykvr_group_swaps(id)
{
  var i = '', o = '', a = '', x = '';

  $.each(mykvr.groups,function(k,v){
    x = ''; // reset
    if(typeof mykvr.osbygroup[v] != 'undefined')
    {
      $.each(mykvr.osbygroup[v],function(k1,v1){x += mykvr.os[v1][3];});
    }
    if(mykvr.ignored.indexOf(v) != -1){x += kvrmyicons["ign"];}
    if(mykvr.unique.indexOf(v)  != -1){x += kvrmyicons["uni"];}
    if(mykvr.publish.indexOf(v) != -1){x += kvrmyicons["pub"];}

    a = '<a href="" data-g="'+v+'" class="kvrgrad5 elliptit">'+mykvr.allgroups[v]+'<span class="mylims">'+x+'</span></a>';

    if(typeof mykvr.bygroup[v] != 'undefined')
    {
      if(mykvr.bygroup[v].indexOf(id) != -1)
      {
        i += a;
      }else{
        o += a;
      }
    }else{
      o += a;
    }
  });

  $("#mykvrg").html('<div class="mykvri"><div class="kvrgrad5hov mykvrgr1 elliptit"><div class="myclkinfo kvrhidetiny">click to remove from</div><span class="kvrsuccess">IS In</span></div>'+i+'</div><div class="switchc"></div><div class="mykvro"><div class="kvrgrad5hov mykvrgr1 elliptit"><div class="myclkinfo kvrhidetiny">click to add to</div><span class="kvrerror">Is NOT In</span></div>'+o+'</div><div class="clearit"></div>');
}

function mykvr_product_page(id)
{
  if(mykvrisdirty && $("#mykvrproductpage").length)
  {
  	if($("#mykvrproductpage").data("id") == id) // ensure it's not from something in a tab
  	{
	    $("#mykvrproductpage").height($("#mykvrproductpage").height()).html('<div style="padding: 20px;">'+kvrloadingcss3an2+'</div>');
	    $.get("/a/",{"s":"12","id":id},function(data){
	      $("#mykvrproductpage").html(data).css("height","auto");
	      mykvrisdirty = false;
	      var pg = mykvr.byprod[id];
	      $(".myppgrps .mykvrinpgrpswp").each(function(){ // prod page ticks
	        if(pg.indexOf($(this).data("g")) == -1)
	        {
	        	$(this).closest(".myppgn").removeClass("mykvri").addClass("mykvro");
	        }else{
	        	$(this).closest(".myppgn").removeClass("mykvro").addClass("mykvri");
	        }
	      });
	    });
    }
  }
}

function mykvr_highlight_myver(obj)
{
  if($(obj).length)
  {
    var o = $(obj);
    var m = $.trim(o.text());
    var l = $.trim(o.closest(".kvrversion").find(".kvrverlatest").text());
    var t = o.closest("tr");
    var c = '';

    if(!$.isEmptyObject(mykvrtr))
    {
      var c0 = '';
      if(t.hasClass("kvrhasupds")){
        c0 = 0;
      }else if(t.hasClass("kvrisuptd")){
        c0 = 1;
      }else if(t.hasClass("kvrnotsync")){
        c0 = 2;
      }
    }

    t.removeClass("kvrhasupds kvrisuptd kvrnotsync");
    if(m == "" || m == "?")
    {
      o.text("?");
      t.addClass("kvrnotsync");
      c = 2;
    }else if(m == l || kvr_version_compare(m, l, '>')){ // very basic check - should cover most
      t.addClass("kvrisuptd");
      c = 1;
    }else{
      t.addClass("kvrhasupds");
      c = 0;
    }

    if(!$.isEmptyObject(mykvrtr))
    {
      var i = t.attr("id"), ind;
      if(typeof mykvrtr[i] !== 'undefined')
      {
        mykvrtr[i][3] = c;

        var g = t.data("grp");
        var pid = t.data("pid");

        // all cache
        ind = mykvrtab[c0].indexOf(i);
        if(ind != -1)
        {
          mykvrtab[c0].splice(ind, 1);
        }
        mykvrtab[c].push(i);

        if(g == "0") // global
        {
          // per group cache
          for(p in mykvr.byprod[pid])
          {
            ind = mykvrtabbyg[mykvr.byprod[pid][p]][c0].indexOf(i);
            if(ind != -1)
            {
              mykvrtabbyg[mykvr.byprod[pid][p]][c0].splice(ind, 1);
            }
            mykvrtabbyg[mykvr.byprod[pid][p]][c].push(i);
          }

        }else{ // unique
          ind = mykvrtabbyg[g][c0].indexOf(i);
          if(ind != -1)
          {
            mykvrtabbyg[g][c0].splice(ind, 1);
          }
          mykvrtabbyg[g][c].push(i);
        }
      }
    }
  }
  return false;
}

function mykvr_update_version_array(id,grp,os,v)
{
  if(typeof mykvr.versions != 'undefined')
  {
    mykvr.versions[id][grp][os][0] = v;

    if(v == "" || v == "?")
    {
      mykvr.versions[id][grp][os][1] = "2";
    }else if(v == mykvr.products[id][3][os][0] || v > mykvr.products[id][3][os][0]){
      mykvr.versions[id][grp][os][1] = "1";
    }else{
      mykvr.versions[id][grp][os][1] = "0";
    }

    if(mykvr_group_summary())
    {
      mykvr_update_mysums($("#filtergrps1 a.active").data("val"));
    }
  }
}

function mykvr_tab_build()
{
  mykvrtab = {"0":[],"1":[],"2":[],"3":[]};
  for(g in mykvrtabbyg)
  {
    var i = 3;
    do{
      mykvrtab[i] = mykvrtab[i].concat(mykvrtabbyg[g][i].filter(function(id){return !(mykvrtab[i].indexOf(id) > -1);}));
    }while(i--);
  }
}

function mykvr_tabbyg_build(emptytr4,gids)
{
  if($.isEmptyObject(mykvrtr))
  {
    return false;
  }

  var g1, g2, g3, grp, g2v, g3v, g3v0, g3v1, g3v2, g3v3, g3v4, g3v4_add, mykvrbygroupgrp, osbygroupgrpg1 = false, isignored = false, isunique = false;
  var osignorelength = mykvr.osignore.length > 0 ? true : false;
  var tmp = [];

  if(emptytr4) // reset grps cache ready for rebuild
  {
    for(g3 in mykvrtr)
    {
      mykvrtr[g3][4] = [];
    }
  }

  // array of grps : single grp : all groups
  var groups = (typeof gids != 'undefined' && gids instanceof Array) ? gids : (gids > 0 ? [gids] : mykvr.groups);

  for(g1 in groups)
  {
    grp = groups[g1];
    mykvrtabbyg[grp] = {"0":[],"1":[],"2":[],"3":[],"4":[]};
    if(typeof mykvr.bygroup[grp] != 'undefined')
    {
      // reset vars
      isignored = false;
      isunique = false;
      tmp = [];

      if(mykvr.ignored.indexOf(grp) != -1)
      {
        isignored = true;
      }else if(mykvr.unique.indexOf(grp) != -1){
        isunique = true;
      }

      // Check once per grp loop
      osbygroupgrpg1 = typeof mykvr.osbygroup[grp] != 'undefined' ? true : false;
      mykvrbygroupgrp = mykvr.bygroup[grp];

      for(g2 in mykvrbygroupgrp)
      {
        g2v = mykvrbygroupgrp[g2]; // pid
        for(g3 in mykvrtr)
        {
          g3v  = mykvrtr[g3]; // tr#id
          g3v0 = g3v[0]; // pid
          g3v1 = g3v[1]; // grp
          g3v2 = g3v[2]; // os
          g3v3 = g3v[3]; // cls
          g3v4 = g3v[4]; // array of grps it's in

          if(g3v0 == g2v)
          {
            g3v4_add = g3v4.indexOf(grp) == -1 ? true : false; // do the array scan
            if(isignored)
            {
              if(g3v3 == 4 && g3v1 == grp) // only check _ignored rows
              {
                mykvrtabbyg[grp][3].push(g3);
                tmp.push(g3v0);
                g3v4_add ? mykvrtr[g3][4].push(grp) : '';
              }
              continue;
            }

            if(isunique)
            {
              if(g3v1 == grp) // only include products explicitly in this group
              {
                mykvrtabbyg[grp][g3v3].push(g3);
                tmp.push(g3v0);
                g3v4_add ? mykvrtr[g3][4].push(grp) : '';
              }
              continue;
            }

            if(g3v1 === 0) // global rows
            {
              // Restricted to OS
              if(osbygroupgrpg1){
                if(mykvr.osbygroup[grp].indexOf(g3v2) != -1){
                  mykvrtabbyg[grp][g3v3].push(g3);
                  tmp.push(g3v0);
                  g3v4_add ? mykvrtr[g3][4].push(grp) : '';
                }
              }
              // Global OS Ignoring
              else if(osignorelength){
                if(mykvr.osignore.indexOf(g3v2) == -1){
                  mykvrtabbyg[grp][g3v3].push(g3);
                  tmp.push(g3v0);
                  g3v4_add ? mykvrtr[g3][4].push(grp) : '';
                }
              }
              // all valid global + grp rows
              else{
                mykvrtabbyg[grp][g3v3].push(g3);
                tmp.push(g3v0);
                g3v4_add ? mykvrtr[g3][4].push(grp) : '';
              }
            }
          }
        }
      }
      mykvrtabbyg[grp][4] = mykvrbygroupgrp.filter(function(i){return !(tmp.indexOf(i) > -1);});
    }
  }

  if(mykvr_group_summary())
  {
    mykvr_update_mysums($("#filtergrps1 a.active").data("val"));
  }
  mykvr_tab_build();
}

function mykvr_tab_delete_from(i)
{
  var grp, ind, v, v2;

  $("#"+i).remove();

  if(typeof mykvrtr[i] !== 'undefined')
  {
    if(mykvrtr[i].length)
    {
      // delete from tabbyg
      for(v in mykvrtr[i][4]) // grp cache for tr#id
      {
        grp = mykvrtabbyg[mykvrtr[i][4][v]];
        for(v2 in grp) // cycle thru grp tab cache
        {
          ind = grp[v2].indexOf(i);
          if(ind != -1)
          {
            mykvrtabbyg[mykvrtr[i][4][v]][v2].splice(ind, 1); // found, delete
          }
        }
      }

      // delete from mykvrtr
      delete mykvrtr[i];
    }

    // delete from alltab
    for(v in mykvrtab) // cycle thru all tab cache
    {
      ind = mykvrtab[v].indexOf(i);
      if(ind != -1)
      {
        mykvrtab[v].splice(ind, 1); // found, delete
      }
    }
  }
}

function mykvr_sort_table(id,attr)
{
  // tbl must have tbody
  var t = document.getElementById(id).tBodies[0];
  var o = [];

  for(var i=0, l=t.rows.length; i<l; i++)
  {
    var r = t.rows[i];
    var p = r.getAttribute(attr);
    o.push([p, r]);
  }
  o.sort(function(x,y){return x[0].localeCompare(y[0]);});
  for(var i=0, l=o.length; i<l; i++){t.appendChild(o[i][1]);}
  o = null;
  return true;
}

function mykvr_toggle_has(leavequickedit)
{
  if($("#mykvrmykvrpage").length == 0)
  {
    return false;
  }

  $("#nothinghere,#nomatchos").hide();
  var dv = $("#filtergrps1 a.active").data("val");

  if(dv == "devs" || dv == "-1" || dv == "-2")
  {
    $("#mykvrtable").hide();
    $("#blockwhendev").block({message: null, baseZ: 2, ignoreIfBlocked: true});
    return false;
  }

  if(!leavequickedit)
  {
    $(".mykvrinlineedit,#mykvrinlineaddrem").remove();
  }

  $("#blockwhendev").unblock();
  $("#mykvrprogress2").text("processing: ...");

  var g = parseInt(dv,10);
  var c = $("#filtermykvrtbl a.kvrbutblk").data("c");
  var trclass1id, nonesection = 'Nothing found ';

  if(c == "u")
  {
    trclass1id = 0;
    nonesection += 'in &quot;With Updates&quot;';
  }else if(c == "s"){
    trclass1id = 1;
    nonesection += 'in &quot;Up To Date&quot;';
  }else if(c == "q"){
    trclass1id = 2;
    nonesection += 'in &quot;Never Synced&quot;';
  }else if(c == "a"){
    trclass1id = 4;
    nonesection += 'in &quot;All Products&quot;';
  }else if(c == "i"){
    nonesection += 'in &quot;Issues&quot;';
    $("#mykvrtable").css("display","none");

    if(typeof mykvrtabbyg[g] == 'undefined' && g != 0)
    {
      $("#nothinghere").html(nonesection).show();
      $("#mykvrprogress2").empty();
      return false;
    }

    mykvr_update_mysums(g);
    mykvr_stopsnappy = 5;
    var o = '', i, iv, pv, grp, grps = {};
    if(g == 0)
    {
      grps = mykvrtabbyg;
    }else{
      grps[g] = mykvrtabbyg[g];
    }

    for(grp in grps)
    {
      if(grps[grp][4].length)
      {
        o += '<div class="mykvri" style="padding: 20px; color: #555;"><p style="padding-left: 10px;"><b>'+mykvr.allgroups[grp]+'</b>: Products that don\'t meet the requirements for group but are in it:</p>';
        for(i in grps[grp][4])
        {
          iv = grps[grp][4][i];
          pv = mykvr.products[iv];
          o += '<p data-p="'+pv[2]+'" class="qsortthis"><a href="#" class="kvrbutton mykvrinpgrpswp" data-id="'+iv+'" data-g="'+grp+'" title="Delete from this group"><span class="spit spdel">&nbsp;</span></a> <span class="mykvr pid'+iv+' activeblue" data-id="'+iv+'" style="margin-left: 0;">My KVR<span class="spit spdarr"></span></span> <a href="/product/'+iv+'" style="color: #555;"><b>' + pv[0] + '</b></a></p>';
        }
        o += '</div>';
      }
    }

    if(o != '')
    {
      if($("#nomatchos").html(o))
      {
        $("#nomatchos").show();
        setTimeout(function(){$("#nomatchos .mykvri").each(function(){$(this).find("p.qsortthis").qsort({attr: "data-p"});});},50);
      }
    }else{
      $("#nothinghere").html(nonesection).show();
    }
    $("#mykvrprogress2").empty();
    return false;
  }else if(c == "sum"){
    trclass1id = 5;
    nonesection += 'in &quot;All Products Summary&quot;';
    $("#mykvrgrpinfo").show();
  }else{
    $("#nothinghere").html(nonesection).show();
    $("#mykvrprogress2").empty();
    return false;
  }

  mykvr_stopsnappy = trclass1id;

  var z = [], snappy;

  if(g == 0) // All Groups / Products
  {
    if(trclass1id == 4) // ALL tab
    {
      z = mykvrtab[0].concat(mykvrtab[1],mykvrtab[2],mykvrtab[3]);
    }else if(trclass1id == 5){ // Summary

    }else{
      z = mykvrtab[trclass1id];
    }
  }else{ // Specific Group

    if(typeof mykvrtabbyg[g] == 'undefined')
    {
      $("#nothinghere").html(nonesection).show();
      $("#mykvrprogress2").empty();
      return false;
    }

    var mykvrtabbygg = mykvrtabbyg[g];
    if(trclass1id == 4) // ALL tab
    {
      z = mykvrtabbygg[0].concat(mykvrtabbygg[1],mykvrtabbygg[2],mykvrtabbygg[3]);
    }else if(trclass1id == 5){ // Summary

    }else{
      z = mykvrtabbygg[trclass1id];
    }
  }

  if(z.length > 200)
  {
    kvr_blockonprocess();
  }

  setTimeout(function(){
    if(trclass1id == 4) // all tab; may use existing rows; only hide and show as necessary
    {
      var visibleids = [];
      $("#mykvrtable tr:visible").each(function(){visibleids.push(this.id);});
      var need2hide = visibleids.filter(function(i){return !(z.indexOf(i) > -1);});
      var need2show = z.filter(function(i){return !(visibleids.indexOf(i) > -1);});
      z = need2show;
      need2show = null;
      visibleids = null;

      if(need2hide.length)
      {
        setTimeout(function(){
        $("#"+need2hide.join(",#")).removeClass("tblrow");
        need2hide = null;
        },0);
      }

    }else{ // always
      $("#mykvrtable tr").removeClass("tblrow");
    }
  },0);

  if(trclass1id == 5)
  {
    $("#mykvrtable").css("display","none");
  }else{
    $("#mykvrtable").css("display","table"); // show in case it's been hidden elsewhere
  }

  if(z.length)
  {
    setTimeout(function(){
      snappy = function(c){
        var block = 200;
        // chk user hasn't clicked away from currently being processed
        if((g != parseInt($("#filtergrps1 a.active").data("val"),10)) || (mykvr_stopsnappy != trclass1id))
        {
          $("#mykvrprogress2").empty();
          return false;
        }

        mykvr_insnappy = true;

        var c1 = c+block;
        var finish = (z.length-1);

        for(; c <= c1; c++)
        {
          $("#"+z[c]).addClass("tblrow").css("display",""); // "display","" resets any fadeouts
          if(c >= finish)
          {
            $("#mykvrprogress2").empty();
            kvr_blockonprocess(true);
            mykvr_insnappy = false;
            return false;
          }

          if(c == c1)
          {
            $("#mykvrprogress2,.blockMsg").text("processing: "+c1);
            setTimeout(function(){snappy(c);},20);
            return false;
          }
        }
      };
      snappy(0);
    },0);
  }else{
    if(trclass1id == 5) // summary
    {
      var ps = g == 0 ? mykvr.p : mykvr.bygroup[g];
      var tmp = '';
      if(typeof ps != 'undefined')
      {
        for(o in ps)
        {
          tmp += '<div class="myprodsummary kvrgrad5 posrelit" data-pid="'+ps[o]+'" data-p="'+kvr_az90(mykvr.products[ps[o]][0])+'" style="padding: 10px; min-height: 30px; border-top: 1px solid #ddd;">';
          if(g > 0)
          {
            tmp += '<div class="mykvri" style="position: absolute;"><a style="display: none; margin: -3px; padding: 10px 0; width: 52px;" data-g="'+g+'" data-id="'+ps[o]+'" class="kvrbutton mykvrinpgrpswp" href="#"><span class="spit spdel">&nbsp;</span></a></div>';
          }
          tmp += '<div style="width: 50px; height: 30px; float: left; margin-right: 10px; background: url(//static.kvraudio.com/i/t/'+mykvr.products[ps[o]][1]+') 0 0 transparent;"></div>';
          tmp += mykvr_button(ps[o],0,false);
          tmp += ' <a href="/product/'+ps[o]+'" style="font-weight: bold;">'+mykvr.products[ps[o]][0]+'</a>';
          tmp += ' by '+mykvr.devs[mykvr.products[ps[o]][4]][0];
          tmp += '<br><span style="font-size: 90%; color: #666;">In: '+mykvr.byprod[ps[o]].length+' group'+(mykvr.byprod[ps[o]].length!=1?'s':'') + ': ';
          for(ing in mykvr.byprod[ps[o]])
          {
            tmp += mykvr.allgroups[mykvr.byprod[ps[o]][ing]] + '; ';
          }

          tmp += '</span></div>';
        }
        setTimeout(function(){mykvr_highlight_all();},0);
        setTimeout(function(){$("#mykvrfavedevs .myprodsummary").qsort({attr: "data-p"});},50);
        $("#mykvrfavedevs").html(tmp).show();
      }else{
        $("#nothinghere").html(nonesection).show();
      }
    }
    $("#mykvrprogress2").empty();
    kvr_blockonprocess(true);

    if(trclass1id != 5)
    {
      setTimeout(function(){
        if($("#mykvrtable tr:visible").length == 0)
        {
          $("#nothinghere").html(nonesection).show();
        }
      },0);
    }
  }

  mykvr_update_mysums(g);
  return false;
}

function mykvr_process_mykvrtrs(c1,showit)
{
  if(!domykvrtrs)
  {
    return false;
  }

  var c = 0, x = '', z;

  for(z in mykvrtrs)
  {
    c++;
    c1++;
    x += mykvrtrs[z];
    delete mykvrtrs[z];

    if(c == 500)
    {
      break;
    }
  }

  if(x)
  {
    $("#mykvrprogress2").text("building: "+c1);
    $("#mykvrtable tbody").append(x);
    setTimeout(function(){mykvr_process_mykvrtrs(c1,showit);}, 50);
  }else{
    domykvrtrs = false;
    $("#mykvrprogress2").empty();
    if(showit)
    {
      var dv = $("#mykvrgrpsreader a.activeblue").data("val");

      if(dv != "-1" && dv != "-2")
      {
        if($("#filtermykvrtbl .kvrbutblk span").text() != $("#mykvrtable tr:visible").length)
        {
          $("#mykvrgrpsreader a.activeblue").click(); // refresh rows if user clicked b4 mykvr_process_mykvrtrs() finished
        }
      }
    }
    return false;
  }
  return false;
}

function mykvr_update_mysums(g)
{
  if(typeof mykvr.groupsummary[g] != 'undefined')
  {
    var gs = mykvr.groupsummary[g];
    $("#mysum3,#mygrpmen"+g+" .mygrptotal,#mygrpmenr"+g+" .mygrptotal").text(gs[3]);
    $("#mysum0").text(gs[0]);
    $("#mysum1").text(gs[1]);
    $("#mysum2").text(gs[2]);
    $("#mysum4").text(gs[4]);
    $("#mysum5").text((g == 0 ? mykvr.p.length : mykvr.bygroup[g].length));
    if($("#mygrpmen"+g).hasClass("active"))
    {
      $("#filtergrps0 .mygrptotal").text(gs[3]);
    }
  }else{
    $("#mysum3,#mysum0,#mysum1,#mysum2,#mysum4,#mysum5,#mygrpmen"+g+" .mygrptotal,#mygrpmenr"+g+" .mygrptotal").text("0");
  }
}

function mykvr_group_menu_totals()
{
  var g;
  for(g in mykvr.allgroups)
  {
    $("#mygrpmen"+g+" .mygrptotal,#mygrpmenr"+g+" .mygrptotal").text(typeof mykvr.groupsummary[g] != 'undefined' ? mykvr.groupsummary[g][3] : "0");
  }
}

function mykvr_group_summary()
{
  var g,p,o;
  mykvr.groupsummary = {};
  mykvr.groupsummary[0] = [0,0,0,0,0]; // All Groups

  var tmp = {"1":{},"2":{},"3":{},"4":{},"5":{},"6":{}};

  for(g in mykvr.bygroup)
  {
    g = parseInt(g,10);
    if(mykvr.hidden.indexOf(g) != -1)
    {
      continue;
    }
    mykvr.groupsummary[g] = [0,0,0,0,0]; // kvrhasupds; kvrisuptd; kvrnotsync; total; issues;

    if(typeof mykvrtabbyg[g] != 'undefined')
    {
      mykvr.groupsummary[g][4] = mykvrtabbyg[g][4].length;
      mykvr.groupsummary[0][4] += mykvrtabbyg[g][4].length;
    }

    var isignored = false;
    if(mykvr.ignored.indexOf(g) != -1)
    {
      mykvr.groupsummary[g] = ['N/A','N/A','N/A',mykvr.bygroup[g].length,'N/A'];
      isignored = true;
      mykvr.groupsummary[0][3]+=mykvr.bygroup[g].length;
      continue;
    }

    var grp = (mykvr.unique.indexOf(g) != -1) ? g : 0; // specific group i.e. requires unique version : else 0 (global version)

    for(p in mykvr.bygroup[g])
    {
      if(typeof mykvr.osbygroup[g] != 'undefined') // Restricted to OS
      {
        for(o in mykvr.osbygroup[g])
        {
          if(typeof mykvr.products[mykvr.bygroup[g][p]][3][mykvr.osbygroup[g][o]] != 'undefined')
          {
            mykvr.groupsummary[g][mykvr.versions[mykvr.bygroup[g][p]][grp][mykvr.osbygroup[g][o]][1]]++;
            if(grp != 0)
            {
              mykvr.groupsummary[0][3]++; // up All Groups ALL total for unique
              mykvr.groupsummary[0][mykvr.versions[mykvr.bygroup[g][p]][grp][mykvr.osbygroup[g][o]][1]]++; // up All Groups total
            }else if(typeof tmp[mykvr.osbygroup[g][o]][mykvr.bygroup[g][p]] == 'undefined'){
              mykvr.groupsummary[0][mykvr.versions[mykvr.bygroup[g][p]][grp][mykvr.osbygroup[g][o]][1]]++; // up All Groups total
              tmp[mykvr.osbygroup[g][o]][mykvr.bygroup[g][p]] = "1";
              mykvr.groupsummary[0][3]++;
            }
            mykvr.groupsummary[g][3]++;
          }
        }
      }else if(mykvr.osignore.length > 0){ // Global OS Ignoring
        for(o in mykvr.products[mykvr.bygroup[g][p]][3])
        {
          if($.inArray(parseInt(o,10),mykvr.osignore) == -1)
          {
            mykvr.groupsummary[g][mykvr.versions[mykvr.bygroup[g][p]][grp][o][1]]++;
            if(grp != 0)
            {
              mykvr.groupsummary[0][3]++; // up All Groups ALL total for unique
              mykvr.groupsummary[0][mykvr.versions[mykvr.bygroup[g][p]][grp][o][1]]++; // up All Groups total
            }else if(typeof tmp[o][mykvr.bygroup[g][p]] == 'undefined'){
              mykvr.groupsummary[0][mykvr.versions[mykvr.bygroup[g][p]][grp][o][1]]++; // up All Groups total
              tmp[o][mykvr.bygroup[g][p]] = "1";
              mykvr.groupsummary[0][3]++;
            }
            mykvr.groupsummary[g][3]++;
          }
        }

      }else{ // all valid global + grp rows
        for(o in mykvr.products[mykvr.bygroup[g][p]][3])
        {
          mykvr.groupsummary[g][mykvr.versions[mykvr.bygroup[g][p]][grp][o][1]]++;
          if(grp != 0)
          {
            mykvr.groupsummary[0][3]++; // up All Groups ALL total for unique
            mykvr.groupsummary[0][mykvr.versions[mykvr.bygroup[g][p]][grp][o][1]]++; // up All Groups total
          }else if(typeof tmp[o][mykvr.bygroup[g][p]] == 'undefined'){
            mykvr.groupsummary[0][mykvr.versions[mykvr.bygroup[g][p]][grp][o][1]]++; // up All Groups total
            tmp[o][mykvr.bygroup[g][p]] = "1";
            mykvr.groupsummary[0][3]++; // up All Groups ALL total
          }
          mykvr.groupsummary[g][3]++;
        }
      }
    }
  }
  tmp = null;
  return true;
}

function mykvr_process_group_change(l,a,i,g,t,inpage)
{
  var ind, tabbyg, bados = false;
  var innomatchos = $("#nomatchos").length ? $.contains(document.getElementById("nomatchos"), l.get(0)) : false;

  if(a == "1") // adding - chk if grp is os restricted
  {
	  if(typeof mykvr.osbygroup[g] !== 'undefined') // grp is os restricted
	  {
	  	var oses = '', osg;
	  	if(typeof mykvr.products[i] !== 'undefined') // product is in prod obj
	    {
	    	oses = mykvr.products[i][3]
	    }else if($("#mykvrpopprod").length){ // get os data from popup
	    	oses = $("#mykvrpopprod").data("product")[3];
	    }

	    if(oses != '') // prod has OSes
	    {
	    	bados = true; // assume bad
	   	  for(osg in mykvr.osbygroup[g])
	   	  {
	   		  if(typeof oses[mykvr.osbygroup[g][osg]] != 'undefined')
	   		  {
	   			  bados = false;
	   		  }
	   		}
	   	}
	  }
  }

  if(bados)
  {
  	$("#myloading").empty();
  	if(inpage)
    {
      if(inpage == 'mykvrp')
      {
        l.removeClass('kvrloadingcss3an2');
      }else{
        l.find("span").removeClass('kvrloadingcss3an2');
      }
    }
  	alert("This product is not available for any of the Operating Systems that the chosen group is restricted to.");
  	return false;
  }

  $.get("/a/",{"s":"2","a":a,"i":i,"g":g},function(data){
    if(data.m == "100") // success
    {
      mykvrisdirty = true;
      if(!inpage)
      {
        l.slideUp("slow",function(){l.appendTo("."+t).slideDown();});
      }

      if(a == "1") // added to
      {
        if(inpage && (inpage != 'mykvrp'))
        {
          l.closest("div").removeClass("mykvro").addClass("mykvri");
        }
        mykvr.bygroup[g] = (typeof mykvr.bygroup[g] != 'undefined' && mykvr.bygroup[g] instanceof Array) ? mykvr.bygroup[g] : [];
        mykvr.bygroup[g].push(i);
        mykvr.byprod[i] = (typeof mykvr.byprod[i] != 'undefined' && mykvr.byprod[i] instanceof Array) ? mykvr.byprod[i] : [];
        mykvr.byprod[i].push(g);
        if(mykvr.p.indexOf(i) == -1)
        {
          mykvr.p.push(i);
        }
        if(g == 1)
        {
          if(mykvr.f.indexOf(i) == -1)
          {
            mykvr.f.push(i);
          }
        }
        if(typeof mykvr.products[i] == 'undefined')
        {
          mykvr.products[i] = data.product;
          mykvr_set_productorder();
        }

        if(typeof mykvr.versions[i] == 'undefined')
        {
          mykvr.versions[i] = {};
        }

        var vgrp = mykvr.unique.indexOf(g) != -1 ? g : 0; //check if unique versioning required

        if(typeof mykvr.versions[i][vgrp] == 'undefined' || $.isEmptyObject(mykvr.versions[i][vgrp]))
        {
          if(mykvr.ignored.indexOf(g) == -1)
          {
            mykvr.versions[i][vgrp] = {};
            for(os in mykvr.products[i][3])
            {
              if(typeof mykvr.osbygroup[g] != 'undefined') // use g because ACTUAL grp is important
              {
                if($.inArray(parseInt(os,10),mykvr.osbygroup[g]) == -1)
                {
                  continue;
                }
              }
              mykvr.versions[i][vgrp][os] = ["?","2"];
            }
          }
        }

        // Dev array
        if(typeof mykvr.devs[mykvr.products[i][4]] == 'undefined')
        {
          mykvr.devs[mykvr.products[i][4]] = data.dev;
        }

        if(mykvr.devs[mykvr.products[i][4]][6].indexOf(i) == -1)
        {
          mykvr.devs[mykvr.products[i][4]][6].push(i);
          mykvr.devs[mykvr.products[i][4]][5] = mykvr.devs[mykvr.products[i][4]][6].length;
        }

        tabbyg = mykvr_refresh_display(true,g);

      }else{ // deleted from
        if(inpage && !innomatchos && (inpage != 'mykvrp'))
        {
          l.closest("div").removeClass("mykvri").addClass("mykvro");
        }
        ind = mykvr.bygroup[g].indexOf(i);
        mykvr.bygroup[g].splice(ind, 1);
        ind = mykvr.byprod[i].indexOf(g);
        mykvr.byprod[i].splice(ind, 1);

        if(g == 1)
        {
          ind = mykvr.f.indexOf(i) // fave prods
          if(ind != -1)
          {
            mykvr.f.splice(ind, 1);
          }
        }

        if(mykvr.byprod[i].length === 0) // no longer in any grp so remove it
        {
          delete mykvr.versions[i];
          ind = mykvr.devs[mykvr.products[i][4]][6].indexOf(i);
          mykvr.devs[mykvr.products[i][4]][6].splice(ind, 1);
          $("#mykvrtable tr[data-pid="+i+"]").fadeOut(function(){mykvr_tab_delete_from($(this).attr("id"));});
          $("#mykvrsb2 .kvrgroupsync tr[data-pid="+i+"]").fadeOut(function(){$(this).remove();});
          ind = mykvr.p.indexOf(i);
          mykvr.p.splice(ind, 1);
          mykvr.devs[mykvr.products[i][4]][5] = mykvr.devs[mykvr.products[i][4]][6].length;
        }else{
          if(mykvr.unique.indexOf(g) != -1){
            $("#mykvrtable tr[data-pid="+i+"][data-grp="+g+"]").fadeOut(function(){mykvr_tab_delete_from($(this).attr("id"));});
            $("#mykvrsb2 .kvrgroupsync tr[data-pid="+i+"][data-grp="+g+"]").fadeOut(function(){$(this).remove();});
            if(typeof mykvr.versions[i] != 'undefined')
            {
              mykvr.versions[i][g]={};
            }
          }
          if(mykvr.ignored.indexOf(g) != -1){
            $("#mykvrtable tr[data-pid="+i+"][data-grp="+g+"]").fadeOut(function(){mykvr_tab_delete_from($(this).attr("id"));});
            $("#mykvrsb2 .kvrgroupsync tr[data-pid="+i+"][data-grp="+g+"]").fadeOut(function(){$(this).remove();});
          }
        }

        if($("#mykvrsb2 .kvrgroupsync tr[data-grp='0'][data-pid="+i+"]").length && mykvr.byprod[i].length) // still global trs remaining in upd dropdown
        {
          var unig = mykvr.unique.concat(mykvr.ignored);
          if(unig.length)
          {
            var keep = mykvr.byprod[i].filter(function(id){return !(unig.indexOf(id) > -1);});
            if(!keep.length) // not in any global grps
            {
              $("#mykvrsb2 .kvrgroupsync tr[data-grp='0'][data-pid="+i+"]").fadeOut(function(){$(this).remove()});
            }
          }
        }

        if($("#nomatchos").length) // in nomatchos tab
        {
          $("#nomatchos p.qsortthis").each(function(){
            if($(this).find(".mykvrinpgrpswp").data("id") == i && $(this).find(".mykvrinpgrpswp").data("g") == g)
            {
              $(this).css("background-color","red").fadeOut(function(){$(this).remove();});
            }
          });
        }

        if(mykvr_group_summary())
        {
          mykvr_update_mysums($("#filtergrps1 a.active").data("val"));
        }
      }

      mykvr_highlight(i);
      if(inpage)
      {
        mykvr_product_page(i);
      }
    }
    $("#myloading").empty();
    if(inpage)
    {
      if(inpage == 'mykvrp')
      {
        l.removeClass('kvrloadingcss3an2');
      }else{
        l.find("span").removeClass('kvrloadingcss3an2');
      }
      if($("#mykvrproductpage").length == 0 && (inpage != 'mykvrp'))
      {
        if(data.m == "100")
        {
          var tr, trrem = false;
          if(innomatchos)
          {
            tr = l.closest("p");
            trrem = true;
          }else if(l.closest(".myprodsummary").length){
            tr = l.closest(".myprodsummary");
            trrem = true;
          }else{
            tr = l.closest("tr");
          }
          tr.fadeOut(function(){
            if(a == "1") // added to
            {
              var mykvrtabbygg = mykvrtabbyg[g];
              z = mykvrtabbygg[0].concat(mykvrtabbygg[1],mykvrtabbygg[2],mykvrtabbygg[3]);
              $("#"+z.join(",#")).addClass("tblrow");
            }else{
              if(trrem)
              {
                tr.remove();
              }else{
                $("#mykvrtable tr[data-pid='"+i+"']").removeClass("tblrow");
              }
            }
          });
        }
      }
    }

    setTimeout(function(){
      if(!tabbyg)
      {
        mykvr_tabbyg_build(false,g); // rebuild
      }
    },1000);

  },"json");
  return false;
}

function mykvr_button(i,p,r)
{
  return '<span data-pg="'+p+'" class="mykvr pid'+i+(r?' inrelblock':'')+'" data-id="'+i+'"><span class="spit mykvrp spstarg" data-id="'+i+'" data-a="1" title="My KVR Favourite Product">&nbsp;</span>My KVR<span class="spit spdarr"></span></span>';
}

function mykvr_highlight(pid)
{
  if(mykvr.logged == "in" && mykvr.active == "1")
  {
    if(mykvr.p.length > 0)
    {
      if(mykvr.p.indexOf(pid) != -1) // in a grp
      {
        $(".pid"+pid).addClass("activeblue");
        var myppgn = false;
        if($("#mykvrproductpage").length)
        {
          if($("#mykvrproductpage").data("id") == pid) // ensure it's not from something in a tab
          {
            myppgn = true;
          }
        }
        if(mykvr.f.indexOf(pid) != -1) // is in faves
        {
          $(".pid"+pid).find(".mykvrp").removeClass("spstarg").addClass("spstar").data("a","2");
          if($(".myppgrps").length && myppgn){ // prod page ticks
        	  $(".myppgrps a.mykvrinpgrpswp[data-g=\'1\']").closest(".myppgn").removeClass("mykvro").addClass("mykvri");
          }
        }else{
          $(".pid"+pid).find(".mykvrp").removeClass("spstar").addClass("spstarg").data("a","1");
          if($(".myppgrps").length && myppgn){ // prod page ticks
		        $(".myppgrps a.mykvrinpgrpswp[data-g=\'1\']").closest(".myppgn").removeClass("mykvri").addClass("mykvro");
		      }
        }
      }else{ // not in any grps
        $(".pid"+pid).removeClass("activeblue");
        if(mykvr.f.indexOf(pid) == -1)
        {
          $(".pid"+pid).find(".mykvrp").removeClass("spstar").addClass("spstarg").data("a","1");
          if($(".myppgrps").length && myppgn){ // prod page ticks
		        $(".myppgrps a.mykvrinpgrpswp[data-g=\'1\']").closest(".myppgn").removeClass("mykvri").addClass("mykvro");
		      }
        }
      }
    }
  }
}

function mykvrd_highlight(id)
{
  if(mykvr.logged == "in" && mykvr.active == "1")
  {
    if(mykvr.d.length > 0)
    {
      if(mykvr.d.indexOf(id) != -1)
      {
        $(".mykvrd[data-d='"+id+"']").removeClass("spstarg").addClass("spstar").data("a","2");
      }else{
        $(".mykvrd[data-d='"+id+"']").removeClass("spstar").addClass("spstarg").data("a","1");
      }
    }
  }
}

function mykvrp_highlight(id)
{
  if(mykvr.logged == "in" && mykvr.active == "1")
  {
    if(mykvr.f.length > 0)
    {
      if(mykvr.f.indexOf(id) != -1)
      {
        $(".mykvrp[data-id='"+id+"']").removeClass("spstarg").addClass("spstar").data("a","2");
      }else{
        $(".mykvrp[data-id='"+id+"']").removeClass("spstar").addClass("spstarg").data("a","1");
      }
    }
  }
}

function mykvr_highlight_all()
{
  if(mykvr.logged == "in" && mykvr.active == "1")
  {
    if(mykvr.p.length > 0)
    {
      $(".mykvr").not(".activeblue").each(function(){
        var i = $(this).data("id");
        if(mykvr.p.indexOf(i) != -1)
        {
          $(this).addClass("activeblue");
          if(mykvr.f.indexOf(i) != -1)
          {
            $(this).find(".mykvrp").removeClass("spstarg").addClass("spstar").data("a","2");
          }
        }
      });
    }

    if(mykvr.d.length > 0)
    {
      $(".mykvrd").each(function(){
        var i = $(this).data("d");
        if(mykvr.d.indexOf(i) != -1)
        {
          $(this).removeClass("spstarg").addClass("spstar").data("a","2");
        }
      });
    }
  }
  return false;
}

function kvr_product_box(id,prod,img,dev)
{
  return '<div class="kvrsearchresbox">'+(img?'<div style="position: absolute; top: 5px; right: 5px; width: 50px; max-height: 50px; overflow: hidden;"><img src="//static.kvraudio.com/i/t/'+img+'" alt=""></div>':'')+'<span data-id="'+id+'" class="mykvr pid'+id+'" data-pg="0" style="bottom: 5px; right: 4px; top: auto;"><span class="spit mykvrp spstarg" data-id="'+id+'" data-a="1" title="My KVR Favourite Product">&nbsp;</span>My KVR<span class="spit spdarr"></span></span><a href="/product/'+id+'" style="display: block; padding: 10px;'+(img?'padding-right: 60px;':'')+'min-height: 40px;" class="kvrgrad5"><b>'+prod+'</b><br>'+dev+'</a></div>';
}

function kvr_dev_box(id,dev,img,p)
{
   var o = '<div class="kvrsearchresbox"><div style="position: absolute; top: 5px; right: 5px; width: 50px; max-height: 50px; overflow: hidden;"><img src="//static.kvraudio.com/i/news/50/'+(img?img:'nodevlogo.png')+'" alt=""></div><a href="/developer/'+id+'" style="display: block; padding: 10px; padding-right: 60px; min-height: 40px;" class="kvrgrad10"><b>'+dev+'</b> <span class="spit mykvrd spstarg" data-a="1" data-d="'+id+'">&nbsp;</span></a>';

  if(p.length)
  {
    $(p).each(function(i,v){
      o += '<div class="posrelit" style="min-height: 24px;">'+mykvr_button(v.id,0,false)+'<a href="/product/'+v.id+'" style="display: block; padding: 6px 74px 6px 10px; border-top: 1px solid #ddd;">'+v.p+'</a></div>';
      if(p.length > 4)
      {
        if(i == 3)
        {
          o += '<a href="#" class="srchdeva" style="display: block; color: #777; text-align: center; padding: 5px;">+'+(p.length-4)+' more <span style="height: 8px; vertical-align: text-bottom;" class="spit spdarcl">&nbsp;</span></a><div class="srchdevmore" style="display: none;">';
        }
      }
    });
    if(p.length > 4)
    {
      o += '</div>';
    }
  }

  o += '</div>';
  return o;
}

function kvr_news_box(id,news,img)
{
  return '<div class="kvrsearchresbox"><a href="/news/'+id+'" style="display: block; padding: 10px; min-height: 50px; font-weight: bold;" class="kvrgrad5">'+(img?'<img src="//static.kvraudio.com/i/news/50/'+img+'" alt="" style="float: right; margin: 0 0 10px 10px;">':'')+news+'</a></div>';
}

function kvr_main_search()
{
  var q = $("#searchkvrq").val();
  var none = 'None';

  if(!q || q == '*'){return false;}

  $("#kvrsearchloading").removeClass("hideflex").html(kvrloadingcss3an1);
  $("#kvrsearchresults").addClass("hideflex");

  if(kvrajax){kvrajax.abort();}

  kvrajax = $.ajax({
    url: "/static/q3.php?my=2&"+$("#searchkvrfrm").serialize(),
    dataType: "jsonp",
    error: function(a,b,c){
      if(b != "abort")
      {
        $("#kvrsearchloading").addClass("hideflex").empty();
        alert('An error occurred. Please try again!');
      }
    }
  }).done(function(data){
    var o = '';

    if(data.p.length)
    {
      $("#s2sp").text(data.p.length);
	    $(data.p).each(function(i,v){o += kvr_product_box(v.id,v.p,v.i,v.d);});
	    $("#s2products").html(o);
	  }else{
	    $("#s2sp").text("0");
      $("#s2products").text(none);
    }

    o = '';
    if(data.d.length)
    {
      $("#s2sd").text(data.d.length);
      $(data.d).each(function(i,v){o += kvr_dev_box(v.id,v.d,v.i,v.p);});
      $("#s2devs").html(o);
    }else{
      $("#s2sd").text("0");
      $("#s2devs").text(none);
    }

    o = '';
    if(data.n.length)
    {
      $("#s2sn").text(data.n.length);
      $(data.n).each(function(i,v){o += kvr_news_box(v.id,v.n,v.i);});
      $("#s2news").html(o);
    }else{
      $("#s2sn").text("0");
      $("#s2news").text(none);
    }

    o = '';
	  if(data.f.length)
    {
      $("#s2sf").text(data.f.length);
      $(data.f).each(function(i,v){o += '<div class="kvrsearchresbox"><a href="/forum/viewtopic.php?t='+v.id+'" class="kvrgrad5" style="display: block; padding: 10px; font-weight: bold;">'+v.t+'</a></div>';});
      $("#s2forum").html(o);
    }else{
       $("#s2sf").text("0");
      $("#s2forum").text(none);
    }

    o = '';
    if(data.v.length)
    {
      $("#s2sv").text(data.v.length);
      $(data.v).each(function(i,v){o += '<div class="kvrsearchresbox" style="font-weight: bold;"><a href="/video/'+v.id+'" class="kvrgrad5" style="display: block; padding: 10px;">'+v.n+'</a></div>';});
      $("#s2vids").html(o);
    }else{
      $("#s2sv").text("0");
      $("#s2vids").text(none);
    }

    $("#kvrsearchloading").addClass("hideflex").empty();
    $("#kvrsearchresults").removeClass("hideflex");
    ga('send', 'pageview', {'page': '/static/q3.php?my=2&'+$("#searchkvrfrm").serialize(), 'title': 'KVR: Quick Search KVR Results'});
	});
  return false;
}

function kvr_nav_collapse()
{
  if($(".kvrnavcollapse").length)
  {
    $(".kvrnavcollapse").each(function(){

      var pw = 0;
      var pd = 0;
      var last, heightit = false;

      var par = $(this).closest(".collapseinthis");

      if(par.hasClass("collapseinthis"))
      {
        if(par.hasClass("collapsetripleheight"))
        {
          heightit = true;
        }
        pw = par.width();

        par.find("> div:visible").each(function(){
          pd+=$(this).outerWidth(true);
        });

        if(pw < pd)
        {
          var wi = 30;
          last = par.find("div.kvrnavcollapse").not(".done").last();
          last.find("> a.nocollapse").each(function(){
            wi+=$(this).outerWidth(true);
          });
          if(wi == 30)
          {
            wi += last.find("> a:first").outerWidth(true);
          }
          last.width(wi).addClass("done");
        }
      }

      el = $(this);
      var l = el.width();
      var m, p, c = 10;

      el.find(".elliptit").hide().css("maxWidth","100%");

      if(el.find("> .kvrnavcollapsed").length == 0)
      {
        if(el.find("> .collapseb4this").length == 0)
        {
          el.append('<div class="kvrnavcollapsed navmore kvrddb addedauto"><a title="More..." href="#">'+(heightit?'&nbsp;<br>':'')+'<span class="kvrcircle"><span class="spit spdarc">&nbsp;</span></span>'+(heightit?'<br>&nbsp;':'')+'</a><div class="kvrnavcollapsed2 navmoremenu kvrddm shaditdrk"></div></div>');
        }else{
          el.find("> .collapseb4this").before('<div class="kvrnavcollapsed navmore kvrddb addedauto" style="margin-right: 5px;"><a title="More..." href="#">'+(heightit?'&nbsp;<br>':'')+'<span class="kvrcircle"><span class="spit spdarc">&nbsp;</span></span>'+(heightit?'<br>&nbsp;':'')+'</a><div class="kvrnavcollapsed2 navmoremenu kvrddm shaditdrk"></div></div>');
        }
      }

      p = el.find(".kvrnavcollapsed");
      m = el.find(".kvrnavcollapsed2");

      if(el.find("> div:visible,> .nocollapse").length)
      {
        el.find("> div:visible,> .nocollapse").not(".nomeasure").each(function(){
          if($(this).css("position") != "absolute")
          {
            c+=$(this).outerWidth(true);
          }
        });
      }

      el.find(".elliptit").show();

      el.find("> a").not(".nocollapse").each(function(){
        var t = $(this).outerWidth(true);

        if((t+c) > l)
        {
          if($(this).hasClass("elliptit"))
          {
            var t100 = (l-c)-40;
            if(t100 > 50)
            {
              $(this).css("maxWidth",(t100));
            }else{
              m.prepend($(this));
            }
          }else{
            m.prepend($(this));
          }
        }else{
          c+=t;
        }
      });

      if(el.find(".kvrnavcollapsed2 > a").length)
      {
        p.css("display","inline-block");
      }

      var spare = l-c;
      if(spare > 40)
      {
        el.find(".kvrnavcollapsed2 > a").each(function(){
          spare = l-c;
          if(spare > 40)
          {
            p.before($(this));
            t = $(this).outerWidth(true);
            if((t+c) < l)
            {
              c+=t;
            }else{
              m.prepend($(this));
              return false;
            }
          }else{
            return false;
          }
        });
      }

      if(!el.find(".kvrnavcollapsed2 > a").length)
      {
        p.css("display","none");
      }
    });
  }
}

function kvr_createCookie(name,value,days)
{
	if(days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function kvr_readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function kvr_eraseCookie(name)
{
	kvr_createCookie(name,"",-1);
}

function kvr_base64_encode(data)
{
  // http://phpjs.org/functions/base64_encode
  var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = '',
    tmp_arr = [];

  if (!data) {
    return data;
  }

  data = unescape(encodeURIComponent(data));

  do {
    o1 = data.charCodeAt(i++);
    o2 = data.charCodeAt(i++);
    o3 = data.charCodeAt(i++);

    bits = o1 << 16 | o2 << 8 | o3;

    h1 = bits >> 18 & 0x3f;
    h2 = bits >> 12 & 0x3f;
    h3 = bits >> 6 & 0x3f;
    h4 = bits & 0x3f;

    tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  } while (i < data.length);

  enc = tmp_arr.join('');

  var r = data.length % 3;

  return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}

function kvr_check_for_vids(el)
{
  if($(el+" a[href^='http://www.youtube.com/watch?v='],"+el+" a[href^='https://www.youtube.com/watch?v=']").length > 0)
  {
    $(el+" a[href^='http://www.youtube.com/watch?v='],"+el+" a[href^='https://www.youtube.com/watch?v=']").each(function(){
      var href = $(this).attr("href");
      var src = href.substr((href.indexOf('=')+1),11);
      $(this).addClass("checkforvis").data({"s":"y","i":src});
    });
  }

  if($(el+" a[href^='http://youtu.be/'],"+el+" a[href^='https://youtu.be/']").length > 0)
  {
    $(el+" a[href^='http://youtu.be/'],"+el+" a[href^='https://youtu.be/']").each(function(){
      var href = $(this).attr("href");
      var src = href.substr((href.indexOf('.be/')+4),11);
      $(this).addClass("checkforvis").data({"s":"y","i":src});
    });
  }

  if($(el+" a[href^='http://vimeo.com/'],"+el+" a[href^='https://vimeo.com/']").length > 0)
  {
    $(el+" a[href^='http://vimeo.com'],"+el+" a[href^='https://vimeo.com/']").each(function(){
      var href = $(this).attr("href");
      var src = href.substr((href.indexOf('m/')+2),11);
      $(this).addClass("checkforvis").data({"s":"v","i":src});
    });
  }

  if($(el+" a[href^='http://soundcloud.com/'],"+el+" a[href^='https://soundcloud.com/']").length > 0)
  {
    $(el+" a[href^='http://soundcloud.com/'],"+el+" a[href^='https://soundcloud.com/']").addClass("checkforvis").data("s","s");
  }
}

function kvr_load_vids_and_audios()
{
  if(!$(".checkforvis").length)
  {
    return false;
  }

  var w, h, f, url;
  if($(".newsbodycon").length) // news pages
  {
    w = $(".newsbodycon").width();
    h = Math.round(w*0.5625); // 16:9
    f = true;
  }else if($(".prodbodycon").length){ // product pages
    w = $(".prodbodycon").width();
    h = Math.round(w*0.5625);
    f = true;
  }

  $(".checkforvis").each(function(){
    if($(this).visible(true))
    {
      url = '';
      if($(this).data("s") == "y") // youtube
      {
        url = 'https://www.youtube.com/embed/'+$(this).data("i");
      }else if($(this).data("s") == "v"){ // vimeo
        url = 'https://player.vimeo.com/video/'+$(this).data("i")+'?title=0&amp;byline=0&amp;portrait=0';
      }

      if(url) // video
      {
        if(!f)
        {
          w = $(this).parent().width();
          h = Math.round(w*0.5625);
        }
        $(this).removeClass("checkforvis").after(function(){
          return '<span class="youetubed" style="display: block; margin: 10px 0;"><iframe width="'+w+'" height="'+h+'" src="'+url+'" frameborder="0" scrolling="no" allowfullscreen></iframe></span>';
        });
        return false;
      }else{
        if($(this).data("s") == "s") // soundcloud
        {
          var a = $(this);
          a.removeClass("checkforvis");
          $.get("https://soundcloud.com/oembed",{"format":"json","iframe":"true","url":a.attr("href")},function(data){
            if(data.html)
            {
              if(data.height == "400")
              {
                data.html = data.html.replace("\"400\"","\"166\"");
              }
              a.after(data.html.replace("visual=true","visual=false"));
            }
          },"json");
          return false;
        }
      }
    }
  });
}

function kvr_cart_remove(id)
{
  $.get("/marketplace/",{"a":"2","id":id},function(data){
    if(data.items)
    {
      $("#kvrcartsumitems").text(data.items+" item"+(data.items!="1"?"s":""));
      $("#kvrcartsumtotal").text(data.total);
      $("#kvrcartsummary").addClass("cartchanged");
      $(".kvrcartsummaryblock").html(data.h);
      kvrkart = data.k;
      kvr_kart_is_in();
      return true;
    }
    $(".kvrcartsummaryblock").html(data.h);
    kvrkart = data.k;
    kvr_kart_is_in();
  },"json");
  return false;
}

function kvr_get_query_var(v)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for(var i=0;i<vars.length;i++)
  {
    var pair = vars[i].split("=");
    if(pair[0] == v){return pair[1];}
  }
  return(false);
}

function kvr_countdown_clock(id, endtime){
  var el = document.getElementById(id);
  var sd = el.querySelector('.days');
  var sh = el.querySelector('.hours');
  var sm = el.querySelector('.minutes');
  var ss = el.querySelector('.seconds');

  function kvr_update_clock(){
    var t = Date.parse(endtime) - Date.parse(new Date());
    var s = Math.floor((t / 1000) % 60);
    var m = Math.floor((t / 1000 / 60) % 60);
    var h = Math.floor((t / (1000 * 60 * 60)) % 24);
    var d = Math.floor(t / (1000 * 60 * 60 * 24));

    sd.textContent = d;
    sh.textContent = ('0' + h).slice(-2);
    sm.textContent = ('0' + m).slice(-2);
    ss.textContent = ('0' + s).slice(-2);

    if(t <= 0){
      clearInterval(timeinterval);
    }
  }

  kvr_update_clock();
  var timeinterval = setInterval(kvr_update_clock, 1000);
}

function kvr_compare_sort(a,b) {
  if (a[0] < b[0])
    return -1;
  else if (a[0] > b[0])
    return 1;
  else
    return 0;
}

function kvr_side_scroller(what)
{
  if(!$(what).length)
  {
    return false;
  }

  $(what).each(function(){
    if(!$(this).find(".kvr_side_scroller_inner").length)
    {
      if($(this).get(0).scrollWidth > $(this).outerWidth() || $(this).hasClass('alwaysscroll'))
      {
        $(this).wrapInner('<div class="kvr_side_scroller_outer"><div class="kvr_side_scroller_inner"></div></div>').prepend('<a href="#" class="kvr_scroller_link kvr_scroller_left flex flexcontentcenter flexcenter"><span class="spit sparrowleft">&nbsp;</span></a>').append('<a href="#" class="kvr_scroller_link kvr_scroller_right flex flexcontentcenter flexcenter"><span class="spit sparrowright">&nbsp;</span></a>');
      }else{
        $(this).wrapInner('<div class="kvr_side_scroller_outer"><div class="kvr_side_scroller_inner"></div></div>');
      }
    }
  });
  return true;
}

$(function(){
  $.ajaxSetup({cache: false}); // force ajax request to get new

  $(".kvrloginrequired").click(function(e){
    e.preventDefault();
    kvr_log_in();
    return false;
  });

  $("a.kvrlb").lightBox({fixedNavigation:false});

  $(document).on('touchstart click', ".kvrddb a", function(e){
    if(e.type == "touchstart")
    {
      var m = $(this).next(".kvrddm");
      if(m.length) // this is the first a
      {
        if(m.is(":visible"))
        {
          e.stopPropagation();
        }
      }else{
        e.stopPropagation();
      }
    }else{
      e.stopPropagation();
    }
  });

  $(document).on("click",".kvrddm,.kvrhideblur",function(e){e.stopPropagation();});

  $(document).on("click","div.kvrddb, .kvrddb > a", function(e){
    if($(this).hasClass("letitgo"))
    {
      return true;
    }
    e.preventDefault();
    e.stopPropagation();
    var t = $(this).hasClass("kvrddb") ? $(this) : $(this).parent();
    var m = t.find(".kvrddm");
    var a = t.find("a:eq(0)");

    $(".kvrddm").not(m).hide();
    $("#mykvrsb2,#kvrmenuc,#kvrmenu").hide();
    $(".kvrddb > a").removeClass("active");

    if(m.is(":visible"))
    {
      a ? a.removeClass("active").blur() : '';
      m.stop(true, true).hide();
      return false;
    }

    a ? a.addClass("active") : '';
    m.stop(true, true).show();

    if(a.hasClass("kvrddget"))
    {
      if(a.hasClass("kvrchkloggedin") && mykvr.logged == "out")
      {
        kvr_log_in();
        return false;
      }
      if(m.find("a").length < 1)
      {
        m.html('<div style="text-align: center; padding: 10px;">'+kvrloadingcss3an2+'</div>');
        $.get(a.attr("href"), function(data){
          m.html(data);
          if(a.data("focus"))
          {
            $("#"+a.data("focus")).focus();
            if(a.data("focus") == "searchkvrq")
            {
              $(".kvrsearchddm").height($(window).height()-20).css({"width":"100%","max-width":$("#kvrblock").outerWidth(),"left":$("#kvrblock").offset().left});
              $("#searchkvrfrm").height($(window).height()-60);
            }
          }
        });
      }else{
        if(a.data("focus"))
        {
          $("#"+a.data("focus")).focus();
        }
      }
    }else{
      if(m.find("input[type='text']").length)
      {
        m.find("input[type='text']").eq(0).focus();
      }
    }

    $(document).on("click",".kvrddclose", function(e){
      e.preventDefault();
      e.stopPropagation();
      $(".kvrddm").hide();
      $(".kvrddb > a").removeClass("active");
      return false;
    });

    return false;
  });

  $("#scxtabs a").click(function(){
    $("#scxbox").html('<div style="padding: 20px; text-align: center;">'+kvrloadingcss3an2+'</div>');
    $("#scxtabs a").removeClass("active");
    $(this).addClass("active");
    $.get(this.href,function(data){
      $("#scxbox").html(data);
    });
    return false;
  });

  $(document).on("change",".stylelabs input, .stylelabs2 input",function(){
    if($(this).is("input[type='checkbox']"))
    {
      $(this).closest("label").removeClass("kvrselected");
    }else{
      $("input[name='"+this.name+"']").closest("label").removeClass("kvrselected");
    }
    if($(this).is(":checked"))
    {
      $(this).closest("label").addClass("kvrselected");
    }
  });

  $(document).on("click","#gabblenav a",function(){
    var href = this.href;
    $("#gabblenav").empty();
    $("#gabbleform").hide();
    kvr_destroy_ck("gabblit");
    $("#gabblenewdiv").append($("#gabbleform"));
    $("html,body").animate({scrollTop: $("#gabblehead").offset().top}, function(){
      $("#gabbles").html('<div style="padding: 20px;">'+kvrloadingimg1div+"</div>");
      $.get(href,function(data){
        $("#gabbles").fadeOut(function(){
          $(this).html(data.g).fadeIn();
        });
        $("#gabblenav").html(data.n);
      },"json");
    });
    return false;
  });

  $(document).on("click","a.gabblepost",function(){
    var div = $(this).closest("div");
    if($(div).next().is("#gabbleform:visible"))
    {
      $("#gabbleform").slideUp("fast");
    }else{
      $("#gabbleform").hide();
      kvr_destroy_ck("gabblit");
      kvr_ckeditor_create(kvr_gabbleform,$(this));
    }
    return false;
  });

  $(document).on("click","a.gabbleremove",function(){
    var l = $(this);
    var d = l.closest("div");
    $("#gabbleform").slideUp();
    kvr_destroy_ck("gabblit");
    $.get("/inc/a.php",{w:"gabbleremove",s:$("#gabbles").data("sid"),id:$("#gabbles").data("iid"),g:$(l).closest("div").data("gid")},function(data){
      l.text("please wait...");
      if(data.x == 1)
      {
        d.html('<p class="kvrnomes">THIS POST HAS BEEN REMOVED</p>');
      }else{
        alert("Error: You do not have permission to remove posts");
      }
    },"json");
    return false;
  });

  $(document).on("click",".kvrveredit",function(e){
    var t = $(this);
    if(t.next().is(".tmpkvrver"))
    {
      $(".tmpkvrver").remove();
      return false;
    }
    $(".tmpkvrver").remove();
    t.after('<div class="kvrgrad5 tmpkvrver shaditdrk"><a href="#" class="kvrupdatever" data-os="'+t.data("os")+'" data-id="'+t.data("id")+'" data-upd="'+t.attr("id")+'" data-group="'+t.data("group")+'"><span class="spit spsave">&nbsp;</span></a><input type="text" name="version" id="kvrmyversion" maxlength="10" value="'+(t.text()!='?'?t.text():'')+'"></div>');
    $("#kvrmyversion").focus();
    e.preventDefault();
    return false;
  });

  $(document).on("click","a.kvrupdatever, .kvrsyncmyversion a",function(){
    var t = $(this), a, v;

    if(t.hasClass("kvrupdatever")) // ver popup button
    {
      a = $("#"+t.data("upd"));
      v = $("#kvrmyversion").val();
    }else{ // sync latest button
      $(".tmpkvrver").remove();
      a = t.closest(".kvrversion").find(".kvrvermy").find("a");
      v = t.closest(".kvrversion").find(".kvrverlatest").text();
    }

    var oldv = a.text();

    if(oldv == v || (oldv == "?" && v == ""))
    {
      $(".tmpkvrver").remove();
      return false;
    }
    a.html(kvrloadingcss3an3);
    var o = t.data("os");
    var i = t.data("id");
    var g = t.data("group");
    mykvrisdirty = true;
    $.get("/a/",{"s":"8","os":o,"id":i,"group":g,"version":v},function(data){
      if(data.x == "100")
      {
        a.text(v);
        if($("#mysbupdc").length)
        {
          $("#mysbupdc").text(data.u);
          data.u == "0" ? $("#mysbupdc").removeClass("kvrgrad8") : $("#mysbupdc").addClass("kvrgrad8");
        }
        $("a[id^='kvredit_"+o+"_"+i+"_"+g+"_']").text(v);
        mykvr_highlight_myver(a); // do visible first
        mykvr_highlight_myver($("a[id^='kvredit_"+o+"_"+i+"_"+g+"_']").not(a)); // other (i.e. if set in mykvrpopup)
        mykvr_update_version_array(i,g,o,v);
      }else{
        a.text(oldv);
      }
      $(".tmpkvrver").remove();
    },"json");
    return false;
  });

  $(document).on("keyup","#kvrmyversion",function(e){
    if(e.keyCode == 13) // enter
    {
      $("a.kvrupdatever").click();
    }else if(e.keyCode == 27){ // esc
      $(".tmpkvrver").remove();
      return false;
    }
    return false;
  });

  $(document).on("click","#kvrsmicons a,.kvrsmicons a, .kvrsmicon",function(){
    window.open(this.href,"","menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=500,width=670");
    return false;
  });

  $(document).on("click",".kvrpopabove",function(){
    if($("#tmpkvrpop").length == 0)
    {
      $("body").append('<div class="kvrgrad5 shaditpopup kvrhideblur" id="tmpkvrpop" style="position: absolute; border: 1px solid #CCC; z-index: 2; min-width: 200px; max-width: 400px; text-align: left;"></div>');
    }else{
      if($("#tmpkvrpop").is(":visible"))
      {
        $("#tmpkvrpop").hide();
        return false;
      }
    }
    var t = $(this);
    $.get(this.href,function(data){
      $("#tmpkvrpop").html(data).show().position({
        of: t,
        my: "center bottom",
        at: "center top-20px",
        collision: "fit none"
      });
    });
    return false;
  });

  $("#pollotd").click(function(){
    if($("#kvrpoll").length)
    {
      $("#kvrpoll").remove();
    }else{
      $(this).append('<div id="tmploader" style="position: absolute; right: 7px; top: 7px;">'+kvrloadingimg1div+'</div>').before('<div id="kvrpoll" class="shaditpopup" style="display: none; width: 98%; position: absolute; margin: 25px 1% 0 1%; box-sizing: border-box; background-color: #fff; z-index: 1; padding: 20px;"></div>');
      $.get(this.href,function(d){
        $("#kvrpoll").html(d).fadeIn();
        $("#tmploader").remove();
      });
    }
    return false;
  });

  // My KVR Fave DEV Button
  $(document).on("click",".mykvrd",function(e){
    e.preventDefault();

    if(mykvr.logged == "out")
    {
      kvr_log_in();
      return false;
    }

    if(mykvr.logged == "in" && mykvr.active == "0")
    {
      window.location = '/mykvr';
      return true;
    }

    var t = $(this);
    var ind;
    var d = t.data("d");
    var a = t.data("a");
    t.addClass('kvrloadingcss3an2');
    $.get("/a/",{"s":"24","d":d,"a":a},function(data){
      if(data.x == "100")
      {
        t.data("a",data.a);
        if(data.a == "2")
        {
          t.removeClass("spstarg").addClass("spstar");
          if(typeof mykvr.devs != 'undefined')
          {
            if(typeof mykvr.devs[d] == 'undefined')
            {
              mykvr.devs[d] = data.dev;
            }else{
              mykvr.devs[d][7] = "1";
              mykvr.devs[d][9] = data.dev[9];
            }
          }

          ind = mykvr.d.indexOf(d);
          if(ind == -1)
          {
            mykvr.d.push(d);
          }
        }else{
          t.removeClass("spstar").addClass("spstarg");
          if(typeof mykvr.devs != 'undefined')
          {
            if(typeof mykvr.devs[d] != 'undefined')
            {
              mykvr.devs[d][7] = "0";
              mykvr.devs[d][9] = [0,0,0,0,0];
            }
          }
          ind = mykvr.d.indexOf(d);
          if(ind != -1)
          {
            mykvr.d.splice(ind, 1);
          }
        }
        mykvrd_highlight(d);
      }else{
        alert(data.m);
      }
      t.removeClass("kvrloadingcss3an2");
    },"json");
    return false;
  });

  // My KVR Button
  $(document).on("click",".mykvr",function(e){
    e.preventDefault();
    e.stopPropagation();

    if(mykvr.logged == "out")
    {
      kvr_log_in();
      return false;
    }

    if(mykvr.logged == "in" && mykvr.active == "0")
    {
      window.location = '/mykvr';
      return true;
    }

    if(mykvr_insnappy)
    {
      mykvr_wait_for_snappy($(this),true);
      return false;
    }

    $("#mykvrpopver").unblock();
    $("#mykvraddgrpfield").remove();
    $(".mykvr").removeClass("myactive");
    var pg = $(this).data("pg") ? $(this).data("pg") : "0";

    if($("#mykvr").length == 0)
    {
      $("body").append('<div id="mykvr" class="shaditpopup" style="max-width: 800px;position: fixed; top: 20px; z-index: 1001; overflow: auto;"><div id="mykvrpopimg"><div id="mykvrxd"><a href="#" id="mykvrx"><span class="spit spclose">&nbsp;</span></a></div><div id="myloading"></div><div id="mykvrpophead" class="kvrgrad5hov mykvrpopsub posrelit"><span id="mykvrpopprod"></span><div id="mykvrpopdetails" style="line-height: 16px;"></div></div></div><div class="mykvrlio"><div class="mykvrpopcols"><div class="kvrgrad5hov mykvrpopsub">Group Memberships</div><div id="mykvrg" class="flex"></div></div><div class="mykvrpopcols"><div class="kvrgrad5hov mykvrpopsub">Latest Versions</div><div id="mykvrpopver"></div></div><div class="mykvrpopcols"><div class="kvrgrad5 mykvrpopsub kvrbuttonizea"><input type="text" value="" name="g" id="mykvraddgrpfieldg"> <a href="#" id="mykvraddgrpfielda">Add Group</a> | <a href="#" id="mykvrextrareviewlnk">Rate &amp; Review</a></div></div></div><div id="mykvrinfobar" class="mykvrpopcols">You can <a href="/mykvr/?s=options">edit, ignore, delete, rename and re-order groups</a> from the <a href="/mykvr/">full My KVR</a> area. You can also choose to ignore OSes from version update notifications.</div></div>');
    }

    $("#mykvrbg").css("zIndex","1000").fadeIn();
    $("#mykvrpopver,#mykvrpopprod").hide().empty();
    $("#mykvrpopdetails").empty();

    $(this).addClass("myactive");
    var id = $(this).data("id");
    var pos = "left";

    var h = $(window).height();
    var w = $(window).width();
    var mw, mh;
    if(w > 800)
    {
      mw = 800;
    }else{
      mw = w;
    }

    $("#mykvr").data("id",id).data("pg",pg).css({"left": "calc(50% - "+(mw/2)+"px)"}).show();

    if(mykvr.logged == "out")
    {
      $(".mykvrlio").hide();
      $("#mykvrpopprod").html("Please log in to use My KVR").show();
      return true;
    }

    $(".mykvrlio").show();

    var getcomp = true;
    var jqp = false;
    if(typeof mykvr.groups == 'undefined')
    {
      $(".mykvrlio").hide();
      $("#myloading").html(kvrloadingcss3an2);
      jqp = $.get("/a/",{"s":"1"},function(data){
        if(data.message)
        {
          $("#mykvrg").html('<p class="kvrnomes" style="padding: 10px; border-radius: 0 0 4px 4px"><b>'+data.message+"</b></p>");
          getcomp = false;
        }else{
          $(".mykvrlio").show();
          mykvr = data;
          mykvr_group_swaps(id);
        }
        $("#myloading").empty();
        return false;
      },"json");
    }else{
      mykvr_group_swaps(id);
    }

    if(getcomp)
    {
      if(jqp)
      {
        jqp.always(function(){
          $("#myloading").html(kvrloadingcss3an2);
          $.get("/a/",{"s":"14","id":id},function(data){$("#mykvrpopver").html(data).fadeIn();$("#myloading").empty();});
        });
      }else{
        $("#myloading").html(kvrloadingcss3an2);
        $.get("/a/",{"s":"14","id":id},function(data){$("#mykvrpopver").html(data).fadeIn();$("#myloading").empty();});
      }
    }

    $("#mykvrextrareviewlnk").attr("href","/product/"+id+"/review");

    if(jqp)
    {
      jqp.always(function(){
        if(mykvr.products[id])
        {
          $("#mykvrpopprod").data("product",mykvr.products[id]).html('<a href="/product/'+id+'">'+mykvr.products[id][0]+'</a>').fadeIn();
          $("#mykvrpopdetails").html(function(){
            var o = '<a href="/developer/'+mykvr.products[id][4]+'">'+mykvr.devs[mykvr.products[id][4]][0] +'</a> <span class="spit mykvrd '+(mykvr.devs[mykvr.products[id][4]][7]=="1"?"spstar":"spstarg")+'" data-d="'+mykvr.products[id][4]+'" data-a="'+(mykvr.devs[mykvr.products[id][4]][7]=="1"?"2":"1")+'" style="display: inline-block;">&nbsp;</span><br>';
            for(k in mykvr.products[id][3])
            {
              o += mykvr.os[k][3];
            }
            return o;
          });
          $("#mykvrextrareviewlnk").html((mykvr.products[id][5]=="1"?"Edit My Review":"Rate &amp; Review"));
        }else{
          $.get("/a/",{"s":"18","id":id},function(data){
            $("#mykvrpopprod").data("product",data.product).html('<a href="/product/'+id+'">'+data.product[0]+'</a>').fadeIn();
            $("#mykvrpopdetails").html(function(){
              var o = '<a href="/developer/'+data.product[4]+'">'+data.dev[0] +'</a><br>';
              for(k in data.product[3])
              {
                o += mykvr.os[k][3];
              }
              return o;
            });
            $("#mykvrextrareviewlnk").html("Rate &amp; Review");
          },"json");
        }
      });
    }else{
      if(mykvr.products[id])
      {
        $("#mykvrpopprod").data("product",mykvr.products[id]).html('<a href="/product/'+id+'">'+mykvr.products[id][0]+'</a>').fadeIn();
        $("#mykvrpopdetails").html(function(){
            var o = '<a href="/developer/'+mykvr.products[id][4]+'">'+mykvr.devs[mykvr.products[id][4]][0] +'</a> <span class="spit mykvrd '+(mykvr.devs[mykvr.products[id][4]][7]=="1"?"spstar":"spstarg")+'" data-d="'+mykvr.products[id][4]+'" data-a="'+(mykvr.devs[mykvr.products[id][4]][7]=="1"?"2":"1")+'" style="display: inline-block;">&nbsp;</span><br>';
            for(k in mykvr.products[id][3])
            {
              o += mykvr.os[k][3];
            }
            return o;
          });
        $("#mykvrextrareviewlnk").html((mykvr.products[id][5]=="1"?"Edit My Review":"Rate &amp; Review"));
      }else{
        $.get("/a/",{"s":"18","id":id},function(data){
          $("#mykvrpopprod").data("product",data.product).html('<a href="/product/'+id+'">'+data.product[0]+'</a>').fadeIn();
          $("#mykvrpopdetails").html(function(){
              var o = '<a href="/developer/'+data.product[4]+'">'+data.dev[0] +'</a><br>';
              for(k in data.product[3])
              {
                o += mykvr.os[k][3];
              }
              return o;
            });
          $("#mykvrextrareviewlnk").html("Rate &amp; Review");
        },"json");
      }
    }
  });

  // My KVR Close
  $(document).on("click","#mykvrx,#mykvrbg",function(){
    $("#mykvrbg,#mykvr,#tmpkvrpop").fadeOut();

    if($("#mykvr").data("pg") == "mybydev")
    {
      $(".mykvr.myactive").closest(".mydevdiv").find(".rfrshsrchdevmy").click();
    }

    $(".mykvr").removeClass("myactive");
    if($("#mykvr").data("pg") == "p")
    {
      mykvr_product_page($("#mykvr").data("id"));
    }
    return false;
  });

  // My KVR Pop Up Group Membership Interface (+In Page buttons)
  $(document).on("click","#mykvrg a, a.mykvrinpgrpswp, .mykvrp",function(e){
    e.preventDefault();
    e.stopPropagation();

    if(mykvr.logged == "out")
    {
      kvr_log_in();
      return false;
    }

    if(mykvr.logged == "in" && mykvr.active == "0")
    {
      window.location = '/mykvr';
      return true;
    }

    var inpage = $(this).hasClass("mykvrinpgrpswp") ? true : false;
    var intr = $(this).hasClass("mykvrusetr") ? true : false;
    if($(this).hasClass("mykvrp"))
    {
      inpage = 'mykvrp';
    }
    var a,t,jqp;
    var l = $(this);
    var g = inpage == 'mykvrp' ? 1 : $(this).data("g");
    var i = intr ? l.closest("tr").data("pid") : (inpage ? $(this).data("id") : $("#mykvr").data("id"));

    if(inpage == 'mykvrp')
    {
      t = '';
      a = l.data("a");
    }else{
      if(l.closest("div").hasClass("mykvri"))
      {
        t = 'mykvro';
        a = '2';
      }else{
        t = 'mykvri';
        a = '1';
      }
    }

    if(inpage)
    {
      if(inpage == 'mykvrp')
      {
        l.addClass('kvrloadingcss3an2');
      }else{
        l.find("span").addClass('kvrloadingcss3an2');
      }
      if(typeof mykvr.groups == 'undefined')
      {
        jqp = $.get("/a/",{"s":"1"},function(data){
          if(data.message)
          {
            if(inpage == 'mykvrp')
            {
              l.removeClass('kvrloadingcss3an2');
            }else{
              l.find("span").removeClass('kvrloadingcss3an2');
            }
            return false;
          }else{
            mykvr = data;
          }
          return false;
        },"json");
      }

      if(a == "2" && (inpage != 'mykvrp'))
      {
        if(jqp)
        {
          jqp.always(function(){
            if(!confirm('Are you sure you want to delete "'+mykvr.products[i][0]+'" from "'+mykvr.allgroups[g]+'"?'))
            {
              a = 1;
            }
          });
        }else{
          if(!confirm('Are you sure you want to delete "'+mykvr.products[i][0]+'" from "'+mykvr.allgroups[g]+'"?'))
          {
            a = 1;
          }
        }
      }
    }else{
      $("#myloading").html(kvrloadingcss3an2);
      $("#mykvrpopver").block({
        ignoreIfBlocked: true,
        message: 'Click to refresh versions...',
        css: {
          padding: '5px',
          width: '50%',
          top: '40%',
          left: '25%',
          color: '#333',
          border: '0',
          borderRadius: '5px',
          cursor: 'pointer'
        },
        onBlock: function(){
          $(".blockMsg,.blockOverlay").click(function(){
            $("#mykvrpopver").html('<p style="text-align: center; padding-top: 20px;">'+kvrloadingcss3an2+'</p>');
            $.get("/a/",{"s":"14","id":i},function(data){$("#mykvrpopver").html(data);});
            $("#mykvrpopver").unblock();
          });
        },
        onOverlayClick: function(){}
      });
    }

    if(jqp)
    {
      jqp.always(function(){
        mykvr_process_group_change(l,a,i,g,t,inpage);
      });
    }else{
      mykvr_process_group_change(l,a,i,g,t,inpage);
    }
    return false;
  });

  // My KVR Add A Group Button
  $(".mykvraddgrp").click(function(e){
    if(mykvr.logged == "out")
    {
      e.preventDefault();
      kvr_log_in();
      return false;
    }

    if(mykvr.logged == "in" && mykvr.active == "0")
    {
      window.location = '/mykvr';
      return true;
    }

    if($("#mykvraddgrpfield").length)
    {
      $("#mykvraddgrpfield").remove();
      return false;
    }
    $("#mykvraddgrpfield,#mykvr").remove();
    $('<div id="mykvraddgrpfield" class="shaditdrk"><input type="text" value="" name="g" id="mykvraddgrpfieldg"> <a href="#" id="mykvraddgrpfielda" class="kvrbuttonizea">Add Group</a></div>').appendTo("body").position({
      of: $(this).parent(),
      my: "left top",
      at: "left bottom",
      collision: "fit none",
      within: $("#kvrblock")
    }).animate({opacity:1.0},1000);
    $("#mykvraddgrpfieldg").focus();
    return false;
  });

  // My KVR Add A Group Submit
  $(document).on("click","#mykvraddgrpfielda",function(){
    if($("#mykvraddgrpfieldg").val())
    {
      var t   = $(this);
      var txt = t.text();
      $("#myloading").html(kvrloadingcss3an2);
      t.html(kvrloadingimg16x11);
      $.get("/a/",{"s":"4","g":$("#mykvraddgrpfieldg").val()},function(data){
        if(data.x == "100")
        {
          mykvr.groups = (typeof mykvr.groups != 'undefined' && mykvr.groups instanceof Array) ? mykvr.groups : [];
          mykvr.groups.push(data.g);
          mykvr.allgroups[data.g] = data.n;
          if(!$.isEmptyObject(mykvrtabbyg))
          {
            mykvrtabbyg[data.g] = {"0":[],"1":[],"2":[],"3":[],"4":[]};
          }
          if(typeof mykvr.grpdesc != 'undefined' && mykvr.grpdesc instanceof Array)
          {
            mykvr.grpdesc[data.g] = "";
          }
          $("#mykvraddgrpfield").fadeOut();
          if($("#kvrmysortable").length > 0)
          {
            mykvr_addgrpto_kvrmysortable(data.g, data.n);
          }else if($("#filtergrps1").length > 0){
            mykvr_addgrpto_mykvrpage(data.g, data.n);
          }
          if($("#mykvr").is(":visible"))
          {
            mykvr_group_swaps($("#mykvr").data("id"));
          }
        }else{
          alert("Error: "+data.m);
        }
        t.text(txt);
        $("#myloading").empty();
      },"json");
    }
    return false;
  });

  $(document).on("keyup","#mykvraddgrpfieldg",function(e){
    if(e.keyCode == 13)
    {
      $("#mykvraddgrpfielda").click();
    }
    return false;
  });

  $("a.memdropit").click(function(e){
    if(mykvr.logged == "out")
    {
      e.preventDefault();
      kvr_log_in();
      return false;
    }
    var t = $(this);
    var d = t.data("d");
    var kbar = $("#kvrbar #kvrcartsummary").length ? true : false;

    $(".kvrddm").hide();

    if(d == "999")
    {
      $("#mykvrsb2").hide();
      if($("#kvrmenuc .kvrcartsummaryblock").length)
      {
        if($("#kvrmenuc").is(":visible"))
        {
          $("#kvrmenuc").hide();
        }else{
          $("#kvrmenuc").show().position({
            of: t,
            my: "right top",
            at: "right bottom",
            collision: "fit none",
          });
        }
        return false;
      }
    }else{
      $("#kvrmenuc").hide();
    }

    var h = $("#mykvrsb2").data("h");

    if(d == h)
    {
      $("#mykvrsb2").toggle();
      return false;
    }

    if(d != "999")
    {
      $("#mykvrsb2").data("h",d).html('<div style="padding: 20px; text-align: center;">'+kvrloadingcss3an2+'</div>').show().position({
        of: t,
        my: "top",
        at: "bottom",
        collision: "fit none",
      });
    }

    var jqp = false;
    if(d == "9" && typeof mykvr.groups == 'undefined')
    {
      jqp = $.get("/a/",{"s":"1"},function(data){
        if(data.message)
        {

        }else{
          mykvr = data;
        }
        return false;
      },"json");
    }
    if(jqp)
    {
      jqp.always(function(){$.get("/a/",{"s":d},function(data){$("#mykvrsb2").html(data);});});
    }else{
      if(d == "999")
      {
        $("#kvrmenuc").html('<div style="padding: 20px; text-align: center;">'+kvrloadingcss3an2+'</div>').show().position({
            of: t,
            my: "right top",
            at: "right bottom",
            collision: "fit none",
          });
        $.get("/marketplace/",{"a":"10"},function(data){
          $("#kvrmenuc").html(data);
          $("#kvrcartsummary").removeClass("cartchanged");
        });
      }else{
        $.get("/a/",{"s":d},function(data){$("#mykvrsb2").html(data);});
      }
    }

    return false;
  });

  $(document).on("click",".mygrpsb",function(){
    var div = $(this).closest("div");

    if(div.find("div.mysidebar").length)
    {
      div.find("div.mysidebar").remove();
    }else{
      div.append('<div id="tmpsb" style="padding: 10px; text-align: center;">'+kvrloadingimg16x11+'</div>');
      $.get("/a/",{"s":"11","g":$(this).data("g")},function(data){
        div.append(data);
        $("#tmpsb").remove();
      });
    }
    return false;
  });

  $(document).on("submit","#searchkvrfrm",function(){
    kvr_main_search();
    return false;
  });

  $(document).on("click","#searchkvrbut",function(){
    $("#searchkvrfrm").submit();
    return false;
  });

  var kvrsrch;
  $(document).on("keyup","#searchkvrq",function(e){
    clearTimeout(kvrsrch);
    if(e.keyCode != 13) // enter
    {
      var x11 = new Date();
      kvrsrch = setTimeout(function(){
        var x2 = new Date();
        if(x2 - x11 > 490)
        {
          $("#searchkvrfrm").submit();
        }
      },1000);
    }
    return false;
  });

  $(document).on("click",".srchdeva",function(){
    $(this).next(".srchdevmore").toggle();
    return false;
  });

    $(document).on("click",".washelpful",function(){
    var i = $(this).closest(".phelpful").find(".helpmes");
    i.html(kvrloadingimg16x11);
    $.get(this.href,function(data){
      i.html(data);
    });
    return false;
  });

  $(document).on("click",".addareview",function(){
    var b = $(this).closest("p");
    if($(b).next().is("#addareviewdiv"))
    {
      if($("#addareviewdiv").is(":visible"))
      {
        $("#addareviewdiv").hide();
      }else{
        $("#addareviewdiv").show();
      }
      return false;
    }
    kvr_destroy_ck("revieweditor");
    $("#addareviewdiv").remove();
    $(b).after('<div id="addareviewdiv" class="clearit">'+kvrloadingcss3an1+'</div>');
    $.get("/product/"+$(this).data("pid")+"/review",function(data){$("#addareviewdiv").html(data);});
    return false;
  });

  $(document).on("click",".editthisreview",function(){
    kvr_destroy_ck("revieweditor");
    $("#paddareview").html('<p style="text-align: center; padding: 100px;">'+kvrloadingcss3an1+'</p>');
    $.get(this.href,function(data){
      $("#paddareview").html(data);
    });
    $(".prodreview").remove();
    return false;
  });

  $(document).on("click",".reportthisreview",function(){
    var m  = '<form name="frmreprev" id="frmreprev" method="post" action="#">';
        m += '<input name="revid" type="hidden" value="'+$(this).data("revid")+'">';
        m += '<input name="t" type="hidden" value="reportreview">';
        m += '<input name="id" type="hidden" value="'+$(this).data("pid")+'">';
        m += '<p style="text-align: center;"><b>Report Review</b></p>';
        m += '<p style="line-height: 150%;">Please use this to inform us of any review that you feel to be inappropriate for KVR, you MUST include a comment as to why you feel the review is inappropriate. Please note that this doesn\'t mean the review will be edited or removed but we will take a look, we may contact you regarding this report.</p>';
        m += '<p style="text-align: center"><strong>Your reason for reporting this review:</strong></p>';
        m += '<p style="text-align: center"><textarea name="comment" cols="50" rows="10" id="comment" style="width: 90%"></textarea></p>';
        m += '<p style="text-align: center"><input type="submit" name="submit" value="Send Report"></p>';
        m += '<div id="reportreviewmessage" style="text-align: center"><span class="kvrerror">Please add your reason<br>for reporting this review</span></div>';
        m += '</form>';
    $.blockUI({
      message: '<a href="#" class="unblockui" style="position: absolute; top: 15px; right: 15px; cursor: pointer;"><span class="spit spclose">&nbsp;</span></a>' + m,
      css: {
        padding: "20px",
        marginLeft: "-20px",
        top: "25%",
        textAlign: "left"
      },
      onBlock: function(){
        $(".blockOverlay,.unblockui").css("cursor","pointer").click(function(){$.unblockUI();return false;});
        $("#frmreprev").submit(function(){
          if($("#comment").val().length > 5)
          {
            $("#reportreviewmessage").html(kvrloadingcss3an1);
            $.post("/product.php", $(this).serialize(), function(data){$("#reportreviewmessage").html(data);});
          }
          return false;
        });
      }
    });
    return false;
  });

  $(document).on("click",".deletethisreview",function(){
    $.blockUI({
      message: kvrloadingcss3an1,
      css: {
        padding: "20px",
        marginLeft: "-20px",
        top: "25%"
      },
      onBlock: function(){
          $(".blockOverlay,.unblockui").css("cursor","pointer").click(function(){$.unblockUI();return false;});
      }
    });
    $.get(this.href,function(data){
      $.blockUI({
        fadeIn: 0,
        message: '<a href="#" class="unblockui" style="position: absolute; top: 15px; right: 15px; cursor: pointer;"><span class="spit spclose">&nbsp;</span></a>' + data,
        css: {
          padding: "20px",
          marginLeft: "-20px",
          top: "25%",
          textAlign: "left",
          cursor: "default"
        },
        onBlock: function(){
          $(".blockOverlay,.unblockui").css("cursor","pointer").click(function(){$.unblockUI();return false;});
          $("#frmdelrev").submit(function(){
            $("#deletereviewmessage").html(kvrloadingcss3an1);
            $.post("/product.php", $(this).serialize(), function(data){$("#deletereviewmessage").html(data);});
            return false;
          });
        }
      });
    });
    return false;
  });

  $(document).ajaxComplete(function(event, xhr, settings){
    var chk = 'http://www.kvraudio.com';
    var chks = 'https://www.kvraudio.com';
    if(settings.url.substring(0,chk.length) == chk || settings.url.substring(0,chks.length) == chks || settings.url.substring(0,1) == "/"){
      setTimeout(function(){mykvr_highlight_all();},100);
    }
    return false;
  });

  $("#wnakvrlnk").click(function(){
    if($("#wnakvr").is(":visible"))
    {
      $("#wnaside").html($("#sidecolx"));
      $("#wnakvr").hide();
    }else{
      $("#wnakvr").html($("#sidecolx")).show();
    }
    return false;
  });

  $(document).on("click",".buyatkvr",function(e){
    if(mykvr.logged == "out")
    {
      e.preventDefault();
      kvr_log_in();
      return false;
    }
    var bnt = $(this).find(".buynowtext");
    var txt = bnt.text();
    bnt.html(kvrloadingcss3an2);

    $(".kvrcartsummaryblock").block({
      "message":"Updating",
      css: {
        padding: '10px',
        width: '50%',
        color: '#333',
        border: '0',
        opacity: '0.7'
      }
    });

    $.get("/marketplace/",{"a":"1","id":$(this).data("id")},function(data, textStatus, jqXHR){
      if(data.items)
      {
        $("#kvrcartsumitems").text(data.items+" item"+(data.items!="1"?"s":""));
        $("#kvrcartsumtotal").text(data.total);
        $("#kvrcartsummary").addClass("cartchanged");
        $(".kvrcartsummaryblock").html(data.h);
        kvrkart = data.k;
        kvr_kart_is_in();
      }else if(data.x == "99" && data.login){
        kvr_log_in(data.login);
      }else if(data.x == "99" && data.m){
        alert(data.m);
      }else{
        $.blockUI({
          message: '<div><a href="#" class="unblockui" style="position: absolute; top: 15px; right: 15px; cursor: pointer;"><span class="spit spclose">&nbsp;</span></a><p>An error occurred and the product was not added to your cart.</p><p>The server returned this:</p><hr>Request IP Address: ' + kvr_ip_address + '<hr>' +  jqXHR.responseText + '</div>',
          css: {
            cursor: 'default',
            padding: "50px",
            borderWidth: "0",
            width: "400px",
            fontSize: "150%",
            left: "calc(50% - 250px)",
            top: "20px",
            textAlign: "left"
          },
          onBlock: function(){
            $(".blockOverlay,.unblockui").css("cursor","pointer").click(function(){$.unblockUI();return false;});
          }
        });
      }
    },"json").done(function(data){
      bnt.text(txt);
      return true;
    }).fail(function(data){
      bnt.text(txt);
      $.blockUI({
        message: '<div><a href="#" class="unblockui" style="position: absolute; top: 15px; right: 15px; cursor: pointer;"><span class="spit spclose">&nbsp;</span></a><p>An error occurred and the product was not added to your cart.</p><p>The server returned this:</p><hr>Request IP Address: ' + kvr_ip_address + '<hr>' + data.responseText + '</div>',
        css: {
          cursor: 'default',
          padding: "50px",
          borderWidth: "0",
          width: "400px",
          fontSize: "150%",
          left: "calc(50% - 250px)",
          top: "20px",
          textAlign: "left"
        },
        onBlock: function(){
          $(".blockOverlay,.unblockui").css("cursor","pointer").click(function(){$.unblockUI();return false;});
        }
      });
    });

    $(this).blur();
    return false;
  });

  $(document).on("click",".kvrdelfromcart",function(){
    var a = $(this);
    var ca = a.closest("a");
    ca.blur();
    $(".kvrcartsummaryblock").block({
      "message":"Updating",
      css: {
        padding: '10px',
        width: '50%',
        color: '#333',
        border: '0',
        opacity: '0.7'
      }
    });
    $.get("/marketplace/",{"a":"2","id":a.data("id"),"b":(($("#shopbox").length||$("#kvrcartsummary").length)?1:0)},function(data){
      if($("#kvrcartsummary").length)
      {
        if(data.items)
        {
          $("#kvrcartsumitems").text(data.items+" item"+(data.items!="1"?"s":""));
          $("#kvrcartsumtotal").text(data.total);
          $("#kvrcartsummary").addClass("cartchanged");
        }
      }
      $(".kvrcartsummaryblock").html(data.h);
      kvrkart = data.k;
      kvr_kart_is_in();
    },"json");
    return false;
  });

  $(document).on("change","select[name=cartquantity]",function(e){
    var a = $(this);
    var newq = parseInt(a.val(),10);

    if(isNaN(newq))
    {
      newq = 0;
    }

    a.val(newq);

    if(newq === a.data("quantity"))
    {
      return false;
    }
    $(".kvrcartsummaryblock").block({
      "message":"Updating",
      css: {
        padding: '10px',
        width: '50%',
        color: '#333',
        border: '0',
        opacity: '0.7'
      }
    });

    $.get("/marketplace/",{"a":"3","id":a.data("id"),"quantity":newq,"b":(($("#shopbox").length||$("#kvrcartsummary").length)?1:0)},function(data){
      if($("#kvrcartsummary").length)
      {
        if(data.items)
        {
          $("#kvrcartsumitems").text(data.items+" item"+(data.items!="1"?"s":""));
          $("#kvrcartsumtotal").text(data.total);
          $("#kvrcartsummary").addClass("cartchanged");
        }
      }
      $(".kvrcartsummaryblock").html(data.h);
      kvrkart = data.k;
      kvr_kart_is_in();
    },"json");
    return false;
  });

  $(document).on("click",".kvrshopmifql",function(){
    if($("#shopbox").length)
    {
      var offsticky = $("#kvrstorenavholder").height()+$("#superheader").outerHeight();
      $("#kvrstoreblock").css("min-height",($(window).height()+offsticky));
      var topscroll = $("#kvrstoreproducts").offset().top-offsticky;
      $(".kvrshopmifql").removeClass("active");
      var id = $(this).data("i");
      $(".kvrshopmifql[data-i='"+id+"']").addClass("active");
      $("html,body").animate({scrollTop: topscroll});
      $("#qpline,#kvrshopbb").show();
      if($("#shopbox .kvrpbox").length) // in case entered from iwt or cart
      {
        kvrshopbb = $("#shopbox").html();
      }

      var inscroller = $("#qpline .kvr_side_scroller_inner").length ? '#qpline .kvr_side_scroller_inner' : '#qpline';
      var qpw = $("#qpline").width();
      var p100 = $("#qpline a.kvrshopmifql[data-i='"+id+"']");

      if(p100)
      {
        var tw  = p100.position();

        if(tw)
        {
          if(tw.left > qpw)
          {
            $(inscroller).prepend(p100);
          }
          kvr_side_scroller(".kvr_side_scroller");
        }
      }

      $("#shopbox").html(kvrloadingcss3an1);
      $.get("/marketplace/",{"id":id,"a":998},function(data){
        $("#shopbox").html(data);
        kvr_side_scroller(".kvr_side_scroller");
      });

      if(History.enabled){
        History.pushState(null,"KVR",this.href);
      }
      return false;
    }
  });

  $(document).on("click",function(e){
    if(e.which != 2 && e.which != 3)
    {
      $(".kvrddm,.kvrhideblur").hide();
      $(".kvrddb > a.active").removeClass("active");
    }
  });

  $(document).on("click",".unblockui",function(){
    $.unblockUI();
    return false;
  });

  $(document).on("click",".svkpopit",function(){
    var h = $(window).height();
    var w = $(window).width();
    var mw, mh;
    if(w > 1000)
    {
      mw = 900;
    }else{
      mw = w-100;
    }

    $.blockUI({
      message: kvrloadingcss3an1,
      css: {
        cursor: "default",
        boxSizing: "border-box",
        overflow: "auto",
        padding: "50px",
        borderWidth: "0",
        width: mw+"px",
        height: (h-40)+"px",
        fontSize: "150%",
        left: "calc(50% - "+(mw/2)+"px)",
        top: "20px",
        textAlign: "left"
      },
      onBlock: function(){
        $(".blockOverlay,.unblockui").css("cursor","pointer").click(function(){$.unblockUI();return false;});
      }
    });
    var url = $(this).data("url");
    if(url.substr(0,1)==="#")
    {
      $(".blockUI.blockMsg.blockPage").html('<div><a href="#" class="unblockui" style="position: absolute; top: 15px; right: 15px; cursor: pointer;"><span class="spit spclose">&nbsp;</span></a>'+$(url).html()+'</div>');
    }else{
      $.get(url,function(data){
        $(".blockUI.blockMsg.blockPage").html('<div><a href="#" class="unblockui" style="position: absolute; top: 15px; right: 15px; cursor: pointer;"><span class="spit spclose">&nbsp;</span></a>'+data+'</div>');
      },"html");
    }
    return false;
  });

  $(document).on('click','.kvr_scroller_left,.kvr_scroller_right',function(){
    var p = $(this).closest(".kvr_side_scroller").find(".kvr_side_scroller_inner");
    var a = p.find("a").eq(0);
    var b = p.find("a").eq(-1);
    var w = a.outerWidth()+5;
    var doap = false, i = 0;
    if($(this).hasClass("kvr_scroller_left"))
    {
      p.prepend(b).css({'left':'-'+w+'px'});
    }else{
      doap = true;
      i = -w;
    }
    p.stop(true, true).animate({left: i},{queue:false, duration:500, complete: function(){
      if(doap)
      {
        p.css({'left':'0'}).append(a);
        a.show();
      }
    }});
    return false;
  });

  $(window).resize(function(){kvr_nav_collapse();});

  setTimeout(function(){
    mykvr_highlight_all();
    kvr_nav_collapse();
  },0);
});