/*
KVR Plugins+Extras
lightBox 0.5 (kvr mod)
Star Rating (no ver)
blockUI 2.70
Sparklines 2.1.2
qsort (no ver)
History 1.7.1
SoundManager 2.97a.20140901
Sticky 1.0.0
Scrollstop 1.1.0
Visible Jul 10 2014
*/

/*
  jQuery blockUI 2.70.0-2014.11.23 malsup.com/jquery/block Copyright 2007-2014 M. Alsup.
  Dual licensed (MIT/GPL): www.opensource.org/licenses/mit-license.php www.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 www.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: 'http://static.kvraudio.com/inc/lightbox/lightbox-ico-loading.gif',
      imageBtnPrev: 'http://static.kvraudio.com/inc/lightbox/lightbox-btn-prev.gif',
      imageBtnNext: 'http://static.kvraudio.com/inc/lightbox/lightbox-btn-next.gif',
      imageBtnClose:'http://static.kvraudio.com/inc/lightbox/lightbox-btn-close.gif',
      imageBlank:   'http://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')));
      } else {
        for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
          settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
        }
      }
      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"><img src="' + settings.imageLoading + '"></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() {
        $('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
        _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 ) ) {
//        if ( $.browser.msie ) {
//          ___pause(250);
//        } else {
          ___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;
        event.drain();
        settings.curvalue = 0;
        jQuery.post(container.url, {
          "rating": jQuery(this).children('a')[0].href.split('#')[1]
        });
        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 says: There was an error while selecting elements or the options.");
    }
  }
})(jQuery);

/* Sticky v1.0.0 stickyjs.com */
(function($){
  var defaults = {
      topSpacing: 0,
      bottomSpacing: 0,
      className: 'is-sticky',
      wrapperClassName: 'sticky-wrapper',
      center: false,
      getWidthFrom: '',
      responsiveWidth: false
    },
    $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; i < sticked.length; i++) {
        var s = sticked[i],
          elementTop = s.stickyWrapper.offset().top,
          etse = elementTop - s.topSpacing - extra;

        if (scrollTop <= etse) {
          if (s.currentTop !== null) {
            s.stickyElement
              .css('position', '')
              .css('top', '');
            s.stickyElement.trigger('sticky-end', [s]).parent().removeClass(s.className);
            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) {
            s.stickyElement
              .css('position', 'fixed')
              .css('top', newTop);

            if (typeof s.getWidthFrom !== 'undefined') {
              s.stickyElement.css('width', $(s.getWidthFrom).width());
            }

            s.stickyElement.trigger('sticky-start', [s]).parent().addClass(s.className);
            s.currentTop = newTop;
          }
        }
      }
    },
    resizer = function() {
      windowHeight = $window.height();

      for (var i = 0; i < sticked.length; i++) {
        var s = sticked[i];
        if (typeof s.getWidthFrom !== 'undefined' && s.responsiveWidth === true) {
          s.stickyElement.css('width', $(s.getWidthFrom).width());
        }
      }
    },
    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', stickyId + '-sticky-wrapper')
            .addClass(o.wrapperClassName);
          stickyElement.wrapAll(wrapper);

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

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

          var stickyWrapper = stickyElement.parent();
          stickyWrapper.css('height', stickyElement.outerHeight());
          sticked.push({
            topSpacing: o.topSpacing,
            bottomSpacing: o.bottomSpacing,
            stickyElement: stickyElement,
            currentTop: null,
            stickyWrapper: stickyWrapper,
            className: o.className,
            getWidthFrom: o.getWidthFrom,
            responsiveWidth: o.responsiveWidth
          });
        });
      },
      update: scroller,
      unstick: function(options) {
        return this.each(function() {
          var unstickyElement = $(this);

          var removeIdx = -1;
          for (var i = 0; i < sticked.length; i++)
          {
            if (sticked[i].stickyElement.get(0) == unstickyElement.get(0))
            {
                removeIdx = i;
            }
          }
          if(removeIdx != -1)
          {
            sticked.splice(removeIdx,1);
            unstickyElement.unwrap();
            unstickyElement.removeAttr('style');
          }
        });
      }
    };

  // should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
  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, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.sticky');
    }
  };

  $.fn.unstick = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.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 - Copyright 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'){

          // Use this native browser method, if available.
          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 v1.1.0 github.com/ssorallen/jquery-scrollstop */
(function($){
  var dispatch = $.event.handle;
  var special = $.event.special,
      uid1 = 'D' + (+new Date()),
      uid2 = 'D' + (+new Date() + 1);

  special.scrollstart = {
    setup: function(data) {
      var _data = $.extend({
        latency: special.scrollstop.latency
      }, data);

      var timer,
          handler = function(evt) {
            var _self = this,
                _args = arguments;

            if (timer) {
              clearTimeout(timer);
            } else {
              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 _data = $.extend({
        latency: special.scrollstop.latency
      }, data);

      var timer,
          handler = function(evt) {
            var _self = this,
                _args = arguments;

            if (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));
    }
  };

})(jQuery);

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

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

if(!Object.keys)
{
  Object.keys = function(o)
  {
    if (o !== Object(o))
      throw new TypeError('Object.keys called on a non-object');
    var k=[],p;
    for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
    return k;
  };
}

if(!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

if(!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function (searchElement /*, fromIndex */ )
  {
    "use strict";
    if (this == null) {
      throw new TypeError();
    }
    var t = Object(this);
    var len = t.length >>> 0;

    if (len === 0) {
      return -1;
    }
    var n = 0;
    if (arguments.length > 1) {
      n = Number(arguments[1]);
      if (n != n) { // shortcut for verifying if it's NaN
        n = 0;
      } else if (n != 0 && n != Infinity && n != -Infinity) {
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
      }
    }
    if (n >= len) {
      return -1;
    }
    var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
    for (; k < len; k++) {
      if (k in t && t[k] === searchElement) {
        return k;
      }
    }
    return -1;
  };
}

function kvr_version_compare(v1, v2, operator) {
  // From http://phpjs.org/functions/version_compare/
  // JS implmentation of PHP's 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(kvrloadingimg1div);
    }
    $.ajax({
      url: "http://static.kvraudio.com/inc/ckeditor"+kvrckeditor+"/ckeditor.js",
      cache: true,
      dataType: "script"
    }).done(function(){
      $.ajax({
        url: "http://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(http://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(http://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="switchc"></div><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="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());
	    $("#mykvrproductpage").html(kvrloadingimg1wht);
	    $.get("/a/",{"s":"12","id":id},function(data){
	      $("#mykvrproductpage").html(data);
	      mykvrisdirty = false;
	      if($("#mykvrproductpage table").length)
	      {
	        $("#mykvrproductpage").height($("#mykvrproductpage table").height());
	      }else{
	        $("#mykvrproductpage").height($("#mykvrproductpage div").height()+20);
	      }

	      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 || m > l){ // very basic check - should cover most
    }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();
    //return false;
  }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(http://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('sploading');
      }else{
        l.find("span").html("&nbsp;");
      }
    }
  	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('sploading');
      }else{
        l.find("span").html("&nbsp;");
      }
      if($("#mykvrproductpage").length == 0 && (inpage != 'mykvrp'))
      {
        if(data.m == "100")
        {
          //var tr = innomatchos ? l.closest("p") : l.closest("tr");
          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="http://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="http://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="http://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").show();
  $("#kvrsearchresults").hide();

  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").hide();
        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").hide();
    $("#kvrsearchresults").show();
    ga('send', 'pageview', {'page': '/static/q3.php?my=2&'+$("#searchkvrfrm").serialize(), 'title': 'KVR: Quick Search KVR Results'});
	}).fail(function(){
//	  $("#kvrsearchloading").hide();
//    alert('An error occurred. Please try again!');
  });
  return false;
}

function kvr_navline_collapse()
{
  if($("#kvrnavline").length)
  {
    var l = $("#kvrnavline").outerWidth();

    if(l < 694)
    {
      var c = 0;

      if($("#kvrnavline > div.navmore").length)
      {
        $("#kvrnavline > div.navmore").each(function(){c+=$(this).outerWidth();});
      }

      if($("#newsnavmore2").length)
      {
        var m = $("#newsnavmore2");
      }else if($("#kvrnavcollapsed").length == 0){
        $("#kvrnavline").prepend('<div id="kvrnavcollapsed" class="navmore kvrddb"><a title="More..." href="#"><span><span class="spit spdarc"></span></span></a><div id="kvrnavcollapsed2" class="navmoremenu kvrddm shaditdrk"></div></div>');
        var m = $("#kvrnavcollapsed2");
      }

      $("#kvrnavline > a").each(function(){
        var t = $(this).outerWidth();
        if((t+c) > l)
        {
          m.append($(this));
        }else{
          c+=t;
        }
      });

      if($("#kvrnavcollapsed2 a").length)
      {
        $("#kvrnavcollapsed").show();
      }
    }
  }
}

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/']").length > 0)
  {
    $(el+" a[href^='http://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 = 'http://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("http://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(){
  $.ajaxSetup({cache: false}); // force ajax request to get new
  $("#shloginreg").click(function(){
    $("#mykvrsb2").hide();
    if($("#shmenu").is(":visible"))
    {
      $("#shmenu").fadeOut("fast");
      if($("#kvruserpop").length){$("#kvruserpop").blur();}
    }else{
      $("#shmenu").fadeIn("fast");
      if($("#kvruserpop").length){$("#kvruserpop").focus();}
    }
    return false;
  });

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

  $(document).on("click","#newsheadlines a.nhl",function(){
    var t = $(this);
    $("a.livenav").removeClass("livenav").addClass("readnav");
    $("span.newsintro").removeClass("newsintro1");
    $("#gabbleform").hide();
    kvr_destroy_ck("gabblit");
    $("#newsheadlines").css('min-height','600px');
    if(t.next().is("#tempjaxy"))
    {
      $("#tempjaxy").slideUp("fast").empty().remove();
      $("html,body").animate({scrollTop: t.offset().top});
    }else{
      $("#tempjaxy").slideUp("fast").empty().remove();
      $("html,body").animate({scrollTop: t.offset().top});
      t.find("span.newsintro").addClass("newsintro1");
      var n = t.next();
      var nt = n.find(".nhh1").text();
      t.removeClass("readnav").addClass("livenav").after('<div id="tempjaxy"><div id="tempjaxy2"><div style="padding: 20px; text-align: center;">'+kvrloadingimg16x11+'</div></div><div id="tempjaxy3" style="display:none;"></div></div>');
      var xtra = t.data("xtra") ? '/' + t.data("xtra") : '';
      var ytra = t.data("ytra") ? '/' + t.data("ytra") : '';
      ga('send', 'event', 'newsitem', 'click', 'kvr news item on front page', 1);
      $.get(this.href+xtra+ytra, function(data){
        $("#tempjaxy2").fadeOut("fast",function(){
          $("#tempjaxy3").html(data+'<div style="padding: 20px; background-color: #aaa; text-align: center;"><a href="#" class="kvrbutton kvrnextitem">Read Next Item<br><span style="background-color: #ddd; border-radius: 50%; padding: 0 4px;"><span style="margin: 0; height: 6px;" class="spit spdarc"></span></span><br>'+nt+'</a></div>').fadeIn("slow",function(){
            $("#newsheadlines").css('min-height',($("#newsheadlines").height()+$("#tempjaxy3").height()));
            $("html,body").animate({scrollTop: t.offset().top});
            setTimeout(function(){mykvr_highlight_all();},100);
            $('#tempjaxy a.kvrlb').lightBox();
            $(".kvrnextitem").click(function(){
              if(nt)
              {
                n.click();
              }else if($("#kvrvnp").length){
                window.location = $("#kvrvnp").attr("href");
              }else{
                t.click();
              }
              return false;
            });
          });
        });
      },"html");
    }
    return false;
  });

  $("#kvrmtrig").click(function(){
    $("#kvrmenuf,#mykvrsb2").hide();
    if($("#kvrmenu strong").length < 1)
    {
      var s = $(this).find(".spkvrm");
      s.html(kvrloadingimg16x11);
      $.get("/inc/a.php?w=kvrmarks", function(data){
        $("#kvrmenu").html(data).fadeIn();
        s.html("&nbsp;");
      });
    }else{
      $("#kvrmenu").fadeToggle();
    }
    return false;
  });

  $("#kvrmtrigf").click(function(){
    $("#kvrmenu,#mykvrsb2").hide();
    if($("#kvrmenuf a").length < 1)
    {
      $(this).prepend('<span id="tmpload16" style="background-color: #555; left: 0; right: 0;">'+kvrloadingimg16x11+'</span>');
      $.get("/inc/a.php?w=kvrforums", function(data){
        $("#kvrmenuf").html(data).show();
        $("#tmpload16").remove();
      });
    }else{
      $("#kvrmenuf").fadeToggle();
    }
    return 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('touchstart', ".kvrddb", function(e){
    e.preventDefault();
    $(".kvrddb a.activenav").removeClass("activenav");
    $(".kvrddm").hide();
    $(this).trigger('click');
    return false;
  });

  $(document).on("mouseenter mouseleave click",".kvrddb", function(e){
    var t = $(this);
    var m = t.find(".kvrddm");
    var a = '';
    if($.contains(document.getElementById("kvrbar"), this) || $.contains(document.getElementById("kvrnavline"), this))
    {
      a = $(this).find("a:eq(0)");
    }

    if(e.type == "mouseenter" || e.type == "click")
    {
      if(e.type == "click" && m.is(":visible"))
      {
        a ? a.removeClass("activenav") : '';
        m.stop(true, true).hide();
        return false;
      }
      a ? a.addClass("activenav") : '';
      m.stop(true, true).delay(200).slideDown(100);
    }else{
      a ? a.removeClass("activenav") : '';
      m.stop(true, true).hide();
    }
    return false;
  });

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

  $(".stylelabs input, .stylelabs2 input").change(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(kvrloadingimg16x11);
    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(event){
    if(event.keyCode == 13) // enter
    {
      $("a.kvrupdatever").click();
    }else if(event.keyCode == 27){ // esc
      $(".tmpkvrver").remove();
      return false;
    }
    return false;
  });

  $(document).on("click","#kvrsmicons a,.kvrsmicons a","click",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" 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 != "in")
    {
      alert("Please log in to use My KVR");
      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('sploading');
    $.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("sploading");
    },"json");
    return false;
  });

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

    if(mykvr.logged != "in")
    {
      alert("Please log in to use My KVR");
      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"><div id="mykvrpopimg"><div id="mykvrxd"><a class="kvrbuttonizea" href="#" id="mykvrx">X</a></div><div id="myloading"></div><div id="mykvrpophead" class="kvrgrad5hov mykvrpopsub posrelit"><span id="mykvrpopprod"></span><div id="mykvrpopdetails"></div></div></div><div class="mykvrlio"><div class="mykvrpopcols"><div class="kvrgrad5hov mykvrpopsub">Group Memberships</div><div id="mykvrg"></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";
    $("#mykvr").data("id",id).data("pg",pg).css("opacity","0.00").show().position({
      of: $(this),
      my: pos+" top",
      at: pos+" bottom",
      collision: "fit none",
      within: $("#kvrblock")
    }).animate({opacity:1.0},1000);

    $("html,body").animate({scrollTop: ($("#mykvr").offset().top-30)});

    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(kvrloadingimg1wht);
      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.complete(function(){
          $("#myloading").html(kvrloadingimg1wht);
          $.get("/a/",{"s":"14","id":id},function(data){$("#mykvrpopver").html(data).fadeIn();$("#myloading").empty();});
        });
      }else{
        $("#myloading").html(kvrloadingimg1wht);
        $.get("/a/",{"s":"14","id":id},function(data){$("#mykvrpopver").html(data).fadeIn();$("#myloading").empty();});
      }
    }

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

    if(jqp)
    {
      jqp.complete(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")+'">&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")+'">&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(){
    if($("#searchkvrdiv").is(":visible") && $("#mykvr").is(":visible"))
    {
      $("#mykvr").fadeOut();
      $(".mykvr").removeClass("myactive");
      $("#mykvrbg").css("zIndex","200");
    }else if($("#searchkvrdiv").is(":visible")){
      $("#searchkvr").click();
    }else{
      $("#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 != "in")
    {
      alert("Please log in to use My KVR");
      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(a == "2" && (inpage != 'mykvrp'))
      {
        if(!confirm('Are you sure you want to delete "'+mykvr.products[i][0]+'" from "'+mykvr.allgroups[g]+'"?'))
        {
          return false;
        }
      }

      if(inpage == 'mykvrp')
      {
        l.addClass('sploading');
      }else{
        l.find("span").html(kvrloadingimg1wht);
      }
      if(typeof mykvr.groups == 'undefined')
      {
        jqp = $.get("/a/",{"s":"1"},function(data){
          if(data.message)
          {
            //alert(data.message);
            if(inpage == 'mykvrp')
            {
              l.removeClass('sploading');
            }else{
              l.find("span").html("&nbsp;");
            }
            return false;
          }else{
            mykvr = data;
          }
          return false;
        },"json");
      }
    }else{
      $("#myloading").html(kvrloadingimg1wht);
      $("#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;">'+kvrloadingimg16x11+'</p>');
            $.get("/a/",{"s":"14","id":i},function(data){$("#mykvrpopver").html(data);});
            $("#mykvrpopver").unblock();
          });
        },
        onOverlayClick: function(){}
      });
    }

    if(jqp)
    {
      jqp.complete(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(){
    if(mykvr.logged != "in")
    {
      alert("Please log in to use My KVR");
      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(kvrloadingimg1wht);
      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(event){
    if(event.keyCode == 13)
    {
      $("#mykvraddgrpfielda").click();
    }
    return false;
  });

  $("a.memdropit").click(function(){
    var d = $(this).data("d");
    var h = $("#mykvrsb2").data("h");

    if(d == "999")
    {
      $("#mykvrsb2").addClass("lowerize");
    }else{
      $("#mykvrsb2").removeClass("lowerize");
    }

    if(d == h)
    {
      //if(d == "999" && $("#kvrcartsummary").hasClass("cartchanged"))
      //{
        // Nada
      //}else{
        $("#mykvrsb2").toggle();
        return false;
      //}
    }

    $("#mykvrsb2").data("h",d).html('<div style="padding: 20px; text-align: center;">'+kvrloadingimg16x11+'</div>').show();
    var jqp = false;
    if(d == "9" && typeof mykvr.groups == 'undefined')
    {
      jqp = $.get("/a/",{"s":"1"},function(data){
        if(data.message)
        {
          //alert(data.message);
        }else{
          mykvr = data;
        }
        return false;
      },"json");
    }
    if(jqp)
    {
      jqp.complete(function(){$.get("/a/",{"s":d},function(data){$("#mykvrsb2").html(data);});});
    }else{
      if(d == "999")
      {
        $.get("/shop/",{"a":"10"},function(data){
          $("#mykvrsb2").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;
  });

  $(".searchkvr").click(function(){
    if($("#searchkvrdiv").is(":visible"))
    {
      $("#searchkvrdiv").stop(true, true).fadeOut();
      $("#mykvrbg").fadeOut();
    }else{
      $("#searchkvrdiv").stop(true, true).fadeIn();
      $("#mykvrbg").css("zIndex","200").fadeIn();
      $("#searchkvrq").focus();
      ga('send', 'event', 'searchfield', 'click', 'kvr search field', 1);
    }
    return false;
  });

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

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

  var kvrsrch;
  $("#searchkvrq").keyup(function(event){
    clearTimeout(kvrsrch);
    if(event.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">'+kvrloadingimg16x11+'</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;"><img src="/i/loading.gif"></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: m+'<p style="text-align: center; margin-top: 10px; padding-top: 10px; border-top: 1px solid #EEE;" class="kvrbutton"><a class="unblockui">Cancel</a></p>',
      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('<img src="/i/loading.gif">');
            $.post("/product.php", $(this).serialize(), function(data){$("#reportreviewmessage").html(data);});
          }
          return false;
        });
      }
    });
    return false;
  });

  $(document).on("click",".deletethisreview",function(){
    $.blockUI({
      message: '<img src="/i/loading.gif">',
      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: data+'<p style="text-align: center" class="kvrbutton"><a class="unblockui">Cancel</a></p>',
        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('<img src="/i/loading.gif">');
            $.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';
    if(settings.url.substring(0,chk.length) == chk || 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;
  });

  if(navigator.userAgent.match(/MSIE 8/i))
  {
    $(".stylelabs label").click(function(){
      var thisinp = $(this).find("input");
      var ischecked = $(thisinp).is(":checked");
      if($(thisinp).attr("type") == "radio")
      {
        $("input[name='"+$(thisinp).attr("name")+"']").not(thisinp).removeAttr("checked").closest("label").removeClass("kvrselected");
      }else{
        $(thisinp).removeAttr("checked").closest("label").removeClass("kvrselected");
      }

      if(!ischecked)
      {
        $(this).addClass("kvrselected");
        $(thisinp).attr("checked","checked");
        $(thisinp).change();
      }
    });
  }else if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i)){
    $('label').click(function (){
      var el = $(this).find('input');
      if($(el+'[type=radio],'+el+'[type=checkbox]').attr('selected',!$(el).attr('selected')))
      {
        return;
      }else{
        $(el).focus();
      }
    });
  }

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

  kvr_navline_collapse();
});