<commit_before>/**
 *  Setup Pagr
 */
var pagr = (function() {
    function init( config )
    {
        // Init config
        if( typeof config === "undefined" )
            config = { };

        // Set default config values
        initConfig( config );

        // Init pages
        initPages( config );

        // Scroll to initial page
        initialScroll( config );

        // Init links
        $( '.' + config.linkName ).click( function( event ) {
            event.preventDefault();
            goToPage( $( event.target ).attr( 'href' ), config );
        } );

        // On back/forward, scroll to new page
        window.onpopstate = function( event ) {
            if( event.state )
                scrollToPage( event.state.page, config );
        };
    }

    function initPages( config )
    {
        function setupPageContainer( element, sizeFunc )
        {
            // Get child pages
            var pages = $( element ).children( '.page' );

            // Generate container for pages, get it
            var container = $( element ).append( '
' ).children( '.pagecontainer-autogen' );

            // Add child pages, set container width
            container.append( pages );
            container[ sizeFunc ]( ( config.pageSize * pages.length ) + '%' );

            // set page widths appropriately
            pages.each( function( index, element ) {
                $( element )[ sizeFunc ]( ( config.pageSize / pages.length ) + '%' );
            } );
        }

        $( '.pagecontainer-horiz' ).each( function( index, element ) {
            setupPageContainer( element, "width" );
        } );

        $( '.pagecontainer-vert' ).each( function( index, element ) {
            setupPageContainer( element, "height" );
        } );
    }

    /**
     *  Initializes config with default settings
     */
    function initConfig( config )
    {
        if( config.scrollEase === undefined )
            config.scrollEase = "easeOutQuad";

        if( config.linkName === undefined )
            config.linkName = "pagrlink";

        if( config.useHistory === undefined )
            config.useHistory = true;

        if( config.pageSize === undefined )
            config.pageSize = 100;
    }

    function initialScroll( config )
    {
        // Save time, scroll instantly, reload time
        if( config.initialPage !== undefined )
        {
            var time = config.scrollTime;
            config.scrollTime = 0;
            goToPage( config.initialPage, config );
            config.scrollTime = time;
        }
    }

    /**
     *  Scroll to the specified page
     */
    function goToPage( pageName, config )
    {
        // If no pages, just go to home
        if( pageName.length === 0 )
            return;

        // Add current state to history
        if( window.history.pushState && config.useHistory )
            window.history.pushState( { page: pageName }, document.title, pageName );

        // Scroll to the proper page
        scrollToPage( pageName, config );
    }

    /**
     *  Actually start the scroll to the page
     */
    function scrollToPage( pageNames, config )
    {
        /**
         *  Get the index of a jQuery object
         */
        function getPageIndex( page )
        {
            var count = 0;
            for( var elem = page[ 0 ]; ( elem = elem.previousSibling ) !== null; )
                if( $( elem ).hasClass( 'page' ) )
                    ++count;
            return count;
        }

        // Convert pageNames to array
        if( typeof pageNames === "string" )
            pageNames = pageNames.split( '/' ).filter( function( obj ) { return obj.length > 0; } );

        // Get page being scrolled to
        var scrollPage = $( '.pagecontainer-autogen > .page#' + pageNames[ 0 ] ),
            options = { };

        // Set which direction to scroll in, and how far to go
        if( scrollPage.parent().parent().hasClass( 'pagecontainer-horiz' ) )
        {
            options.left = -( getPageIndex( scrollPage ) * scrollPage.width() );
        }
        else if( scrollPage.parent().parent().hasClass( 'pagecontainer-vert' ) )
        {
            options.top = -( getPageIndex( scrollPage ) * scrollPage.height() );
        }

        // Scroll to page
        $( scrollPage.parent() ).animate(
            // Scroll container so that current view is selected
            options,
            // Scroll over 400ms
            config.scrollTime,
            // Easing
            config.scrollEase,
            // If page has special scroll, use that.
            function() {
                scrollToPage( pageNames.splice( 1, 1 ), config );
            }
        );
    }

    return init;
} )();
<commit_msg>Fixed scrolling for non-100% page sizes.<commit_after>/**
 *  Setup Pagr
 */
var pagr = (function() {
    function init( config )
    {
        // Init config
        if( typeof config === "undefined" )
            config = { };

        // Set default config values
        initConfig( config );

        // Init pages
        initPages( config );

        // Scroll to initial page
        initialScroll( config );

        // Init links
        $( '.' + config.linkName ).click( function( event ) {
            event.preventDefault();
            goToPage( $( event.target ).attr( 'href' ), config );
        } );

        // On back/forward, scroll to new page
        window.onpopstate = function( event ) {
            if( event.state )
                scrollToPage( event.state.page, config );
        };
    }

    function initPages( config )
    {
        function setupPageContainer( element, sizeFunc )
        {
            // Get child pages
            var pages = $( element ).children( '.page' );

            // Generate container for pages, get it
            var container = $( element ).append( '
' ).children( '.pagecontainer-autogen' );

            // Add child pages, set container width
            container.append( pages );
            container[ sizeFunc ]( ( config.pageSize * pages.length ) + '%' );

            // set page widths appropriately
            pages.each( function( index, element ) {
                $( element )[ sizeFunc ]( ( config.pageSize / pages.length ) + '%' );
            } );
        }

        $( '.pagecontainer-horiz' ).each( function( index, element ) {
            setupPageContainer( element, "width" );
        } );

        $( '.pagecontainer-vert' ).each( function( index, element ) {
            setupPageContainer( element, "height" );
        } );
    }

    /**
     *  Initializes config with default settings
     */
    function initConfig( config )
    {
        if( config.scrollEase === undefined )
            config.scrollEase = "easeOutQuad";

        if( config.linkName === undefined )
            config.linkName = "pagrlink";

        if( config.useHistory === undefined )
            config.useHistory = true;

        if( config.pageSize === undefined )
            config.pageSize = 100;
    }

    function initialScroll( config )
    {
        // Save time, scroll instantly, reload time
        if( config.initialPage !== undefined )
        {
            var time = config.scrollTime;
            config.scrollTime = 0;
            goToPage( config.initialPage, config );
            config.scrollTime = time;
        }
    }

    /**
     *  Scroll to the specified page
     */
    function goToPage( pageName, config )
    {
        // If no pages, just go to home
        if( pageName.length === 0 )
            return;

        // Add current state to history
        if( window.history.pushState && config.useHistory )
            window.history.pushState( { page: pageName }, document.title, pageName );

        // Scroll to the proper page
        scrollToPage( pageName, config );
    }

    /**
     *  Actually start the scroll to the page
     */
    function scrollToPage( pageNames, config )
    {
        /**
         *  Get the index of a jQuery object
         */
        function getPageIndex( page )
        {
            var count = 0;
            for( var elem = page[ 0 ]; ( elem = elem.previousSibling ) !== null; )
                if( $( elem ).hasClass( 'page' ) )
                    ++count;
            return count;
        }

        // Convert pageNames to array
        if( typeof pageNames === "string" )
            pageNames = pageNames.split( '/' ).filter( function( obj ) { return obj.length > 0; } );

        // Get page being scrolled to
        var scrollPage = $( '.pagecontainer-autogen > .page#' + pageNames[ 0 ] ),
            options = { };

        // Set which direction to scroll in, and how far to go
        if( scrollPage.parent().parent().hasClass( 'pagecontainer-horiz' ) )
        {
            options.left = -( getPageIndex( scrollPage ) * scrollPage.width() * ( config.pageSize / 100 ) );
        }
        else if( scrollPage.parent().parent().hasClass( 'pagecontainer-vert' ) )
        {
            options.top = -( getPageIndex( scrollPage ) * scrollPage.height() * ( config.pageSize / 100 ) );
        }

        // Scroll to page
        $( scrollPage.parent() ).animate(
            // Scroll container so that current view is selected
            options,
            // Scroll over 400ms
            config.scrollTime,
            // Easing
            config.scrollEase,
            // If page has special scroll, use that.
            function() {
                scrollToPage( pageNames.splice( 1, 1 ), config );
            }
        );
    }

    return init;
} )();
<|endoftext|>


<commit_before>/*! wpt - v3.0.1 - 2013-08-01\n* Copyright (c) 2013 Billy Vong <billy@woopra.com>; Licensed  */(function(t,i){"use strict";var e,n,o,a={},s=[],r=!0,c=!0;a.CONSTANTS={VERSION:11,ENDPOINT:"//www.woopra.com/track/"},a.extend=function(t,i){for(var e in i)t[e]=i[e]},a.readCookie=function(e){var n,o,a;return""===e?"":(n=""+i.cookie,o=n.indexOf(e),-1===o?"":(a=n.indexOf(";",o),-1===a&&(a=n.length),t.unescape(n.substring(o+e.length+1,a))))},a.setCookie=function(t,e,n,o,a){var s=[];s.push(t+"="+e),s.push("expires="+n),s.push("path="+a),s.push("domain=."+o),i.cookie=s.join("; ")},a.getCampaignData=function(){for(var t,i,e=a.getUrlParams(),n={},o=["source","medium","content","campaign","term"],s=0;o.length>s;s++)t=o[s],i=e["utm_"+t]||e["woo_"+t],i!==void 0&&(n["campaign_"+("campaign"===t?"name":t)]=i);return n},a.getUrlParams=function(){var i={};return t.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(t,e,n){i[e]=decodeURIComponent(n.split("+").join(" "))}),i},a.buildUrlParams=function(t,i){var e,n=i||"",o=[];if(t===void 0)return t;for(e in t)o.push(n+encodeURIComponent(e)+"="+encodeURIComponent(t[e]));return o.join("&")},a.randomString=function(){var t,i,e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",n="";for(t=0;12>t;t++)i=Math.floor(Math.random()*e.length),n+=e.substring(i,i+1);return n},a.loadScript=function(t,e){var n,o,s=i.createElement("script");s.type="text/javascript",s.src=t,s.async=!0,e&&"function"==typeof e&&(o=e),s.onreadystatechange!==void 0?s.onreadystatechange=function(){(4===this.readyState||"complete"===this.readyState||"loaded"===this.readyState)&&o&&o(),a.removeScript(s)}:(s.onload=function(){o&&o(),a.removeScript(s)},s.onerror=function(){a.removeScript(s)}),n=i.getElementsByTagName("script")[0],n.parentNode.insertBefore(s,n)},a.removeScript=function(t){t.parentNode.removeChild(t)},a.getHost=function(){return t.location.host.replace("www.","")},a.endsWith=function(t,i){return-1!==t.indexOf(i,t.length-i.length)},a.sleep=function(t){for(var i=new Date,e=new Date;t>e-i;)e=new Date},e=a._on=function(t,i){s[t]||(s[t]=[]),s[t].push(i)},a._fire=function(t){var i;if(s[t])for(i=0;s[t].length>i;i++)s[t][i].apply(this,Array.prototype.slice.call(arguments,1))},a.attachEvent=function(i,e,n){var o,a,s;t.document.attachEvent!==void 0?(o="attachEvent",a="on"+e):(o="addEventListener",a=e,s=!1),i[o](a,n,s)},a.attachEvent(i,"mousedown",function(i){var e,s,h,p;for(a._fire("mousemove",i,new Date),e=i.srcElement||i.target;e!==void 0&&null!==e&&(!e.tagName||"a"!==e.tagName.toLowerCase());)e=e.parentNode;e!==void 0&&null!==e&&(s=e,h=s.pathname.match(/(?:doc|dmg|eps|jpg|jpeg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|mp4|m4v)($|\&)/),p=!1,r&&h&&0>(""+s.href).indexOf("woopra-ns.com")&&(a._fire("download",s.href),a.sleep(n)),c&&!h&&s.hostname!==t.location.host&&-1===s.hostname.indexOf("javascript")&&""!==s.hostname&&(a._fire("outgoing",s.href),a.sleep(o)))}),a.attachEvent(i,"mousemove",function(t){a._fire("mousemove",t,new Date)}),a.attachEvent(i,"keydown",function(){a._fire("keydown")});var h=function(i){this.visitorData={},this.sessionData={},this.options={},this.instanceName=i,this.idle=0,this.cookie="",this.last_activity=new Date,this._loaded=!1,this.version=a.CONSTANTS.VERSION,i&&""!==i&&(t[i]=this)};if(h.prototype={init:function(){this._setOptions(),this._processQueue("config"),this._setupCookie(),this._bindEvents(),this._loaded=!0,this._processQueue()},_setOptions:function(){var t=new Date;t.setDate(t.getDate()+365),this.config({domain:a.getHost(),cookie_name:"wooTracker",cookie_domain:null,cookie_path:"/",cookie_expire:t,ping:!0,ping_interval:12e3,idle_timeout:3e5,idle_threshold:1e4,download_pause:200,outgoing_pause:200,download_tracking:!0,outgoing_tracking:!0,ignore_query_url:!0})},_processQueue:function(i){var e,n,o,a=t._w[this.instanceName];if(a&&a._e)for(o=a._e,e=0;o.length>e;e++)n=o[e],void 0===n||!this[n[0]]||void 0!==i&&i!==n[0]||this[n[0]].apply(this,Array.prototype.slice.call(n,1))},_setupCookie:function(){this.cookie=a.readCookie(this.config("cookie_name")),this.cookie&&this.cookie.length>0||(this.cookie=a.randomString()),null===this.config("cookie_domain")&&(a.endsWith(t.location.host,"."+this.config("domain"))?this.config("cookie_domain",this.config("domain")):this.config("cookie_domain",a.getHost())),a.setCookie(this.config("cookie_name"),this.cookie,this.config("cookie_exp"),this.config("cookie_domain"),this.config("cookie_path"))},_bindEvents:function(){var t=this;e("mousemove",function(){t.moved.apply(t,arguments)}),e("keydown",function(){t.typed.apply(t,arguments)}),e("download",function(){t.downloaded.apply(t,arguments)}),e("outgoing",function(){t.outgoing.apply(t,arguments)})},_dataSetter:function(t,i,e){var n;if(i===void 0)return t;if(e===void 0){if("string"==typeof i)return t[i];if("object"==typeof i)for(n in i)t[n]=i[n]}else t[i]=e;return this},_push:function(t){var i,e,n,o,s,r=t||{},c=this.config("protocol"),h=c&&""!==c?c+":":"",p=h+a.CONSTANTS.ENDPOINT+r.endpoint+"/",u="ra="+a.randomString(),l=[["visitorData","cv_"],["eventData","ce_"],["sessionData","cs_"]],g=[];g.push(u),g.push(a.buildUrlParams(this.getOptionParams()));for(s in l)o=l[s],r[o[0]]&&(e=a.buildUrlParams(r[o[0]],o[1]),e&&g.push(e));i="?"+g.join("&"),n=p+i,a.loadScript(n,r.callback)},config:function(t,i){var e=this._dataSetter(this.options,t,i);return e===this&&(6e3>this.options.ping_interval?this.options.ping_interval=6e3:this.options.ping_interval>6e4&&(this.options.ping_interval=6e4),c=c&&this.options.outgoing_tracking,o=o||this.options.outgoing_pause,r=r&&this.options.download_tracking,n=n||this.options.download_pause),e},visit:function(t,i){return this._dataSetter(this.sessionData,t,i)},identify:function(t,i){return this._dataSetter(this.visitorData,t,i)},call:function(t){this[t]&&"function"==typeof this[t]&&this[t].apply(this,Array.prototype.slice.call(arguments,1))},track:function(t,i){var e,n={},o=arguments[arguments.length-1];a.extend(n,a.getCampaignData()),"function"==typeof o&&(e=o),t===void 0||t===e?(n.name="pv",n.url=this.getPageUrl(),n.title=this.getPageTitle()):i===void 0||i===e?("string"==typeof t&&(n.name=t),"object"==typeof t&&this._dataSetter(n,t)):(n.name=t,this._dataSetter(n,i)),this._push({endpoint:"ce",visitorData:this.visitorData,sessionData:this.sessionData,eventData:n,callback:e}),this.startPing()},startPing:function(){var i=this;this.pingInterval===void 0&&(this.pingInterval=t.setInterval(function(){i.ping()},this.config("ping_interval")))},stopPing:function(){this.pingInterval!==void 0&&(t.clearInterval(this.pingInterval),delete this.pingInterval)},ping:function(){var t;return this.config("ping")&&this.idle<this.config("idle_timeout")?this._push({endpoint:"ping"}):this.stopPing(),t=new Date,t-this.last_activity>this.config("idle_threshold")&&(this.idle=t-this.last_activity),this},push:function(t){return this._push({endpoint:"identify",visitorData:this.visitorData,sessionData:this.sessionData,callback:t}),this},sleep:function(t){a.sleep(t)},moved:function(t,i){this.last_activity=i,this.idle=0},typed:function(){this.vs=2},downloaded:function(t){this.track("download",{url:t})},outgoing:function(t){this.track("outgoing",{url:t})},getPageUrl:function(){return this.options.ignore_query_url?t.location.pathname:t.location.pathname+t.location.search},getPageTitle:function(){return 0===i.getElementsByTagName("title").length?"":i.getElementsByTagName("title")[0].innerHTML},getOptionParams:function(){var e={alias:this.config("domain"),instance:this.instanceName,cookie:a.readCookie(this.config("cookie_name")),ka:this.config("keep_alive")||2*this.config("ping_interval"),meta:a.readCookie("wooMeta")||"",screen:t.screen.width+"x"+t.screen.height,language:t.navigator.browserLanguage||t.navigator.language||"",referer:i.referrer,idle:""+parseInt(this.idle/1e3,10),vs:"i"};return 2===this.vs?(e.vs="w",this.vs=0):0===this.idle&&(e.vs="r"),e},dispose:function(){this.stopPing(),t[this.instanceName]!==void 0&&delete t[this.instanceName]}},t._w!==void 0)for(var p in t._w){var u=new h(p);u.init(),void 0===typeof t.woopraTracker&&(t.woopraTracker=u)}t.WoopraTracker=h,t.WoopraLoadScript=a.loadScript,t.exports!==void 0&&(a.Tracker=h,t.exports.Woopra=a)})(window,document);<commit_msg>Update build<commit_after>/*! wpt - v3.0.1 - 2013-08-01\n* Copyright (c) 2013 Billy Vong <billy@woopra.com>; Licensed  */(function(t,i){"use strict";var e,n,o,a={},s=[],r=!0,c=!0;a.CONSTANTS={VERSION:11,ENDPOINT:"//www.woopra.com/track/"},a.extend=function(t,i){for(var e in i)t[e]=i[e]},a.readCookie=function(e){var n,o,a;return""===e?"":(n=""+i.cookie,o=n.indexOf(e),-1===o?"":(a=n.indexOf(";",o),-1===a&&(a=n.length),t.unescape(n.substring(o+e.length+1,a))))},a.setCookie=function(t,e,n,o,a){var s=[];s.push(t+"="+e),s.push("expires="+n),s.push("path="+a),s.push("domain=."+o),i.cookie=s.join("; ")},a.getCampaignData=function(){for(var t,i,e=a.getUrlParams(),n={},o=["source","medium","content","campaign","term"],s=0;o.length>s;s++)t=o[s],i=e["utm_"+t]||e["woo_"+t],i!==void 0&&(n["campaign_"+("campaign"===t?"name":t)]=i);return n},a.getUrlParams=function(){var i={};return t.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(t,e,n){i[e]=decodeURIComponent(n.split("+").join(" "))}),i},a.buildUrlParams=function(t,i){var e,n=i||"",o=[];if(t===void 0)return t;for(e in t)o.push(n+encodeURIComponent(e)+"="+encodeURIComponent(t[e]));return o.join("&")},a.randomString=function(){var t,i,e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",n="";for(t=0;12>t;t++)i=Math.floor(Math.random()*e.length),n+=e.substring(i,i+1);return n},a.loadScript=function(t,e){var n,o,s=i.createElement("script");s.type="text/javascript",s.src=t,s.async=!0,e&&"function"==typeof e&&(o=e),s.onreadystatechange!==void 0?s.onreadystatechange=function(){(4===this.readyState||"complete"===this.readyState||"loaded"===this.readyState)&&o&&o(),a.removeScript(s)}:(s.onload=function(){o&&o(),a.removeScript(s)},s.onerror=function(){a.removeScript(s)}),n=i.getElementsByTagName("script")[0],n.parentNode.insertBefore(s,n)},a.removeScript=function(t){t.parentNode.removeChild(t)},a.getHost=function(){return t.location.host.replace("www.","")},a.endsWith=function(t,i){return-1!==t.indexOf(i,t.length-i.length)},a.sleep=function(t){for(var i=new Date,e=new Date;t>e-i;)e=new Date},e=a._on=function(t,i){s[t]||(s[t]=[]),s[t].push(i)},a._fire=function(t){var i;if(s[t])for(i=0;s[t].length>i;i++)s[t][i].apply(this,Array.prototype.slice.call(arguments,1))},a.attachEvent=function(i,e,n){var o,a,s;t.document.attachEvent!==void 0?(o="attachEvent",a="on"+e):(o="addEventListener",a=e,s=!1),i[o](a,n,s)},a.attachEvent(i,"mousedown",function(i){var e,s,h,p;for(a._fire("mousemove",i,new Date),e=i.srcElement||i.target;e!==void 0&&null!==e&&(!e.tagName||"a"!==e.tagName.toLowerCase());)e=e.parentNode;e!==void 0&&null!==e&&(s=e,h=s.pathname.match(/(?:doc|dmg|eps|jpg|jpeg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|mp4|m4v)($|\&)/),p=!1,r&&h&&0>(""+s.href).indexOf("woopra-ns.com")&&(a._fire("download",s.href),a.sleep(n)),c&&!h&&s.hostname!==t.location.host&&-1===s.hostname.indexOf("javascript")&&""!==s.hostname&&(a._fire("outgoing",s.href),a.sleep(o)))}),a.attachEvent(i,"mousemove",function(t){a._fire("mousemove",t,new Date)}),a.attachEvent(i,"keydown",function(){a._fire("keydown")});var h=function(i){this.visitorData={},this.sessionData={},this.options={},this.instanceName=i,this.idle=0,this.cookie="",this.last_activity=new Date,this._loaded=!1,this.version=a.CONSTANTS.VERSION,i&&""!==i&&(t[i]=this)};if(h.prototype={init:function(){this._setOptions(),this._processQueue("config"),this._setupCookie(),this._bindEvents(),this._loaded=!0,this._processQueue()},_setOptions:function(){var t=new Date;t.setDate(t.getDate()+365),this.config({domain:a.getHost(),cookie_name:"wooTracker",cookie_domain:null,cookie_path:"/",cookie_expire:t,ping:!0,ping_interval:12e3,idle_timeout:3e5,idle_threshold:1e4,download_pause:200,outgoing_pause:200,download_tracking:!0,outgoing_tracking:!0,ignore_query_url:!0})},_processQueue:function(i){var e,n,o,a=t._w[this.instanceName];if(a&&a._e)for(o=a._e,e=0;o.length>e;e++)n=o[e],void 0===n||!this[n[0]]||void 0!==i&&i!==n[0]||this[n[0]].apply(this,Array.prototype.slice.call(n,1))},_setupCookie:function(){this.cookie=a.readCookie(this.config("cookie_name")),this.cookie&&this.cookie.length>0||(this.cookie=a.randomString()),null===this.config("cookie_domain")&&(a.endsWith(t.location.host,"."+this.config("domain"))?this.config("cookie_domain",this.config("domain")):this.config("cookie_domain",a.getHost())),a.setCookie(this.config("cookie_name"),this.cookie,this.config("cookie_expire"),this.config("cookie_domain"),this.config("cookie_path"))},_bindEvents:function(){var t=this;e("mousemove",function(){t.moved.apply(t,arguments)}),e("keydown",function(){t.typed.apply(t,arguments)}),e("download",function(){t.downloaded.apply(t,arguments)}),e("outgoing",function(){t.outgoing.apply(t,arguments)})},_dataSetter:function(t,i,e){var n;if(i===void 0)return t;if(e===void 0){if("string"==typeof i)return t[i];if("object"==typeof i)for(n in i)t[n]=i[n]}else t[i]=e;return this},_push:function(t){var i,e,n,o,s,r=t||{},c=this.config("protocol"),h=c&&""!==c?c+":":"",p=h+a.CONSTANTS.ENDPOINT+r.endpoint+"/",u="ra="+a.randomString(),l=[["visitorData","cv_"],["eventData","ce_"],["sessionData","cs_"]],g=[];g.push(u),g.push(a.buildUrlParams(this.getOptionParams()));for(s in l)o=l[s],r[o[0]]&&(e=a.buildUrlParams(r[o[0]],o[1]),e&&g.push(e));i="?"+g.join("&"),n=p+i,a.loadScript(n,r.callback)},config:function(t,i){var e=this._dataSetter(this.options,t,i);return e===this&&(6e3>this.options.ping_interval?this.options.ping_interval=6e3:this.options.ping_interval>6e4&&(this.options.ping_interval=6e4),c=c&&this.options.outgoing_tracking,o=o||this.options.outgoing_pause,r=r&&this.options.download_tracking,n=n||this.options.download_pause),e},visit:function(t,i){return this._dataSetter(this.sessionData,t,i)},identify:function(t,i){return this._dataSetter(this.visitorData,t,i)},call:function(t){this[t]&&"function"==typeof this[t]&&this[t].apply(this,Array.prototype.slice.call(arguments,1))},track:function(t,i){var e,n={},o=arguments[arguments.length-1];a.extend(n,a.getCampaignData()),"function"==typeof o&&(e=o),t===void 0||t===e?(n.name="pv",n.url=this.getPageUrl(),n.title=this.getPageTitle()):i===void 0||i===e?("string"==typeof t&&(n.name=t),"object"==typeof t&&this._dataSetter(n,t)):(n.name=t,this._dataSetter(n,i)),this._push({endpoint:"ce",visitorData:this.visitorData,sessionData:this.sessionData,eventData:n,callback:e}),this.startPing()},startPing:function(){var i=this;this.pingInterval===void 0&&(this.pingInterval=t.setInterval(function(){i.ping()},this.config("ping_interval")))},stopPing:function(){this.pingInterval!==void 0&&(t.clearInterval(this.pingInterval),delete this.pingInterval)},ping:function(){var t;return this.config("ping")&&this.idle<this.config("idle_timeout")?this._push({endpoint:"ping"}):this.stopPing(),t=new Date,t-this.last_activity>this.config("idle_threshold")&&(this.idle=t-this.last_activity),this},push:function(t){return this._push({endpoint:"identify",visitorData:this.visitorData,sessionData:this.sessionData,callback:t}),this},sleep:function(t){a.sleep(t)},moved:function(t,i){this.last_activity=i,this.idle=0},typed:function(){this.vs=2},downloaded:function(t){this.track("download",{url:t})},outgoing:function(t){this.track("outgoing",{url:t})},getPageUrl:function(){return this.options.ignore_query_url?t.location.pathname:t.location.pathname+t.location.search},getPageTitle:function(){return 0===i.getElementsByTagName("title").length?"":i.getElementsByTagName("title")[0].innerHTML},getOptionParams:function(){var e={alias:this.config("domain"),instance:this.instanceName,cookie:a.readCookie(this.config("cookie_name")),ka:this.config("keep_alive")||2*this.config("ping_interval"),meta:a.readCookie("wooMeta")||"",screen:t.screen.width+"x"+t.screen.height,language:t.navigator.browserLanguage||t.navigator.language||"",referer:i.referrer,idle:""+parseInt(this.idle/1e3,10),vs:"i"};return 2===this.vs?(e.vs="w",this.vs=0):0===this.idle&&(e.vs="r"),e},dispose:function(){this.stopPing(),t[this.instanceName]!==void 0&&delete t[this.instanceName]}},t._w!==void 0)for(var p in t._w){var u=new h(p);u.init(),void 0===typeof t.woopraTracker&&(t.woopraTracker=u)}t.WoopraTracker=h,t.WoopraLoadScript=a.loadScript,t.exports!==void 0&&(a.Tracker=h,t.exports.Woopra=a)})(window,document);<|endoftext|>


<commit_before>console.log(Date.now());
function getTide(){
  var url = "http://www.corsproxy.com/tidesandcurrents.noaa.gov/api/datagetter?product=water_level&application=NOS.COOPS.TAC.WL&begin_date=20140525&end_date=20140525&datum=MLLW&station=8638610&time_zone=GMT&units=english&format=json";
$.getJSON( url, function( data ) {
  // var items = [];
  // $.each( data, function( key, val ) {
  //   items.push( "
" + val + "
" );
  // });
  //
  // $( "
", {
  //   "class": "my-new-list",
  //   html: items.join( "" )
  // }).appendTo( "body" );
  console.log(data);
  time=data;
  });
}
var time =getTide();
<commit_msg>getting today<commit_after> var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //Months are zero based
    var curr_year = d.getFullYear();
    var today = curr_year + "" + curr_month +""+ curr_date;

function getTide(){
  var url = "http://www.corsproxy.com/tidesandcurrents.noaa.gov/api/datagetter?product=water_level&application=NOS.COOPS.TAC.WL&begin_date=20140525&end_date=20140525&datum=MLLW&station=8638610&time_zone=GMT&units=english&format=json";
$.getJSON( url, function( data ) {
  // var items = [];
  // $.each( data, function( key, val ) {
  //   items.push( "
" + val + "
" );
  // });
  //
  // $( "
", {
  //   "class": "my-new-list",
  //   html: items.join( "" )
  // }).appendTo( "body" );
  console.log(data);
  time=data;
  });
}
var time =getTide();
<|endoftext|>


<commit_before>/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function(){
	// count character on keyup
	function counter(event){
		var maxLength = 140;
		var currentLength = $("#notice_data-text").val().length;
		var remaining = maxLength - currentLength;
		var counter = $("#notice_text-count");
		counter.text(remaining);

		if (remaining < 0) {
			$("#form_notice").addClass("warning");
		} else {
			$("#form_notice").removeClass("warning");
		}
	}

	function submitonreturn(event) {
		if (event.keyCode == 13) {
			$("#form_notice").submit();
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		return true;
	}

	if ($("#notice_data-text").length) {
		$("#notice_data-text").bind("keyup", counter);
		$("#notice_data-text").bind("keydown", submitonreturn);

		// run once in case there's something in there
		counter();

        if($('body')[0].id != 'conversation') {
            $("#notice_data-text").focus();
        }
	}

	// XXX: refactor this code

	var favoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var dis = new_form.id;
												var fav = dis.replace('disfavor', 'favor');
												$('form#'+fav).replaceWith(new_form);
												$('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
											  }
					 };

	var disoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var fav = new_form.id;
												var dis = fav.replace('favor', 'disfavor');
												$('form#'+dis).replaceWith(new_form);
												$('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);
											  }
					 };

	var joinoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var leave = new_form.id;
												var join = leave.replace('leave', 'join');
												$('form#'+join).replaceWith(new_form);
												$('form#'+leave).ajaxForm(leaveoptions).each(addAjaxHidden);
											  }
					 };

	var leaveoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var join = new_form.id;
												var leave = join.replace('join', 'leave');
												$('form#'+leave).replaceWith(new_form);
												$('form#'+join).ajaxForm(joinoptions).each(addAjaxHidden);
											  }
					 };

	function addAjaxHidden() {
		var ajax = document.createElement('input');
		ajax.setAttribute('type', 'hidden');
		ajax.setAttribute('name', 'ajax');
		ajax.setAttribute('value', 1);
		this.appendChild(ajax);
	}

	$("form.form_favor").ajaxForm(favoptions);
	$("form.form_disfavor").ajaxForm(disoptions);
	$("form.form_group_join").ajaxForm(joinoptions);
	$("form.form_group_leave").ajaxForm(leaveoptions);
	$("form.form_favor").each(addAjaxHidden);
	$("form.form_disfavor").each(addAjaxHidden);
	$("form.form_group_join").each(addAjaxHidden);
	$("form.form_group_leave").each(addAjaxHidden);

	$("#form_user_nudge").ajaxForm ({ dataType: 'xml',
		beforeSubmit: function(xml) { $("#form_user_nudge input[type=submit]").attr("disabled", "disabled");
									  $("#form_user_nudge input[type=submit]").addClass("disabled");
									},
		success: function(xml) { $("#form_user_nudge").replaceWith(document._importNode($("#nudge_response", xml).get(0),true));
							     $("#form_user_nudge input[type=submit]").removeAttr("disabled");
							     $("#form_user_nudge input[type=submit]").removeClass("disabled");
							   }
	 });
	$("#form_user_nudge").each(addAjaxHidden);

	var Subscribe = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { $(".form_user_subscribe input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_subscribe input[type=submit]").addClass("disabled");
																	    },
					  success: function(xml) { var form_unsubscribe = document._importNode($('form', xml).get(0), true);
										  	   var form_unsubscribe_id = form_unsubscribe.id;
											   var form_subscribe_id = form_unsubscribe_id.replace('unsubscribe', 'subscribe');
											   $("form#"+form_subscribe_id).replaceWith(form_unsubscribe);
											   $("form#"+form_unsubscribe_id).ajaxForm(UnSubscribe).each(addAjaxHidden);
											   $("dd.subscribers").text(parseInt($("dd.subscribers").text())+1);
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled");
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
										     }
					};

	var UnSubscribe = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { $(".form_user_unsubscribe input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unsubscribe input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { var form_subscribe = document._importNode($('form', xml).get(0), true);
										  		 var form_subscribe_id = form_subscribe.id;
												 var form_unsubscribe_id = form_subscribe_id.replace('subscribe', 'unsubscribe');
												 $("form#"+form_unsubscribe_id).replaceWith(form_subscribe);
												 $("form#"+form_subscribe_id).ajaxForm(Subscribe).each(addAjaxHidden);
												 $("#profile_send_a_new_message").remove();
												 $("#profile_nudge").remove();
											     $("dd.subscribers").text(parseInt($("dd.subscribers").text())-1);
												 $(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");
												 $(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
											   }
					  };

	$(".form_user_subscribe").ajaxForm(Subscribe);
	$(".form_user_unsubscribe").ajaxForm(UnSubscribe);
	$(".form_user_subscribe").each(addAjaxHidden);
	$(".form_user_unsubscribe").each(addAjaxHidden);

	var PostNotice = { dataType: 'xml',
					   beforeSubmit: function(formData, jqForm, options) { if ($("#notice_data-text").get(0).value.length == 0) {
																				$("#form_notice").addClass("warning");
																				return false;
																		   }
																		   $("#form_notice").addClass("processing");
																		   $("#notice_action-submit").attr("disabled", "disabled");
																		   $("#notice_action-submit").addClass("disabled");
																		   return true;
												 						 },
					   timeout: '60000',
					   error: function (xhr, textStatus, errorThrown) {	$("#form_notice").removeClass("processing");
																		$("#notice_action-submit").removeAttr("disabled");
																		$("#notice_action-submit").removeClass("disabled");
																		if (textStatus == "timeout") {
																			alert ("Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists");
																		}
																		else {
																			if ($(".error", xhr.responseXML).length > 0) {
																				$('#form_notice').append(document._importNode($(".error", xhr.responseXML).get(0), true));
																			}
																			else {
																				var HTTP20x30x = [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307];
																				if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																					alert("Sorry! We had trouble sending your notice ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
																				}
																				else {
																					$("#notice_data-text").val("");
																					counter();
																				}
																			}
																		}
																	  },
					   success: function(xml) {	if ($("#error", xml).length > 0) {
													var result = document._importNode($("p", xml).get(0), true);
													result = result.textContent || result.innerHTML;
													alert(result);
												}
												else {
												    if ($("#command_result", xml).length > 0) {
													    var result = document._importNode($("p", xml).get(0), true);
													    result = result.textContent || result.innerHTML;
													    alert(result);
                                                    }
                                                    else {
                                                         li = $("li", xml).get(0);
                                                         if ($("#"+li.id).length == 0) {
                                                            var notice_irt_value = $('#notice_in-reply-to').val();
                                                            var notice_irt = '#notices_primary #notice-'+notice_irt_value;
                                                            if($('body')[0].id == 'conversation') {
                                                                if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
                                                                    $(notice_irt).append('

');
                                                                }
                                                                $($(notice_irt+' .notices')[0]).append(document._importNode(li, true));
                                                            }
                                                            else {
                                                                $("#notices_primary .notices").prepend(document._importNode(li, true));
                                                            }
                                                            $('#'+li.id).css({display:'none'});
                                                            $('#'+li.id).fadeIn(2500);
                                                            NoticeReply();
                                                            NoticeAttachments();
                                                         }
													}
													$("#notice_data-text").val("");
    												$("#notice_data-attach").val("");
    												$("#notice_in-reply-to").val("");
                                                    $('#notice_data-attach_selected').remove();
                                                    counter();
												}
												$("#form_notice").removeClass("processing");
												$("#notice_action-submit").removeAttr("disabled");
												$("#notice_action-submit").removeClass("disabled");
											 }
					   };
	$("#form_notice").ajaxForm(PostNotice);
	$("#form_notice").each(addAjaxHidden);
    NoticeReply();
    NoticeAttachments();
    NoticeDataAttach();
});

function NoticeReply() {
    if ($('#notice_data-text').length > 0 && $('#content .notice_reply').length > 0) {
        $('#content .notice').each(function() {
            var notice = $(this)[0];
            $($('.notice_reply', notice)[0]).click(function() {
                var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname');
                NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
                return false;
            });
        });
    }
}

function NoticeReplySet(nick,id) {
	rgx_username = /^[0-9a-zA-Z\-_.]*$/;
	if (nick.match(rgx_username)) {
		replyto = "@" + nick + " ";
		if ($("#notice_data-text").length) {
			$("#notice_data-text").val(replyto + $("#notice_data-text").val());
			$("#form_notice input#notice_in-reply-to").val(id);
			$("#notice_data-text").focus();
			return false;
		}
	}
	return true;
}

function NoticeAttachments() {
    $.fn.jOverlay.options = {
        method : 'GET',
        data : '',
        url : '',
        color : '#000',
        opacity : '0.6',
        zIndex : 99,
        center : false,
        imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
        bgClickToClose : true,
        success : function() {
            $('#jOverlayContent').append('<button>×</button>');
            $('#jOverlayContent button').click($.closeOverlay);
        },
        timeout : 0,
        autoHide : true,
        css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
    };

    $('#content .notice a.attachment').click(function() {
        $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
        return false;
    });

    var t;
    $("body:not(#shownotice) #content .notice a.thumbnail").hover(
        function() {
            var anchor = $(this);
            $("a.thumbnail").children('img').hide();
            anchor.closest(".entry-title").addClass('ov');

            if (anchor.children('img').length == 0) {
                t = setTimeout(function() {
                    $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
                        anchor.append(data);
                    });
                }, 500);
            }
            else {
                anchor.children('img').show();
            }
        },
        function() {
            clearTimeout(t);
            $("a.thumbnail").children('img').hide();
            $(this).closest(".entry-title").removeClass('ov');
        }
    );
}

function NoticeDataAttach() {
    NDA = $('#notice_data-attach');
    NDA.change(function() {
        S = '
'+$(this).val()+' <button>×</button>
';
        NDAS = $('#notice_data-attach_selected');
        (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#form_notice').append(S);
        $('#notice_data-attach_selected button').click(function(){
            $('#notice_data-attach_selected').remove();
            NDA.val('');
        });
    });
}
<commit_msg>Set focus to end of field.<commit_after>/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function(){
	// count character on keyup
	function counter(event){
		var maxLength = 140;
		var currentLength = $("#notice_data-text").val().length;
		var remaining = maxLength - currentLength;
		var counter = $("#notice_text-count");
		counter.text(remaining);

		if (remaining < 0) {
			$("#form_notice").addClass("warning");
		} else {
			$("#form_notice").removeClass("warning");
		}
	}

	function submitonreturn(event) {
		if (event.keyCode == 13) {
			$("#form_notice").submit();
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		return true;
	}

	if ($("#notice_data-text").length) {
		$("#notice_data-text").bind("keyup", counter);
		$("#notice_data-text").bind("keydown", submitonreturn);

		// run once in case there's something in there
		counter();

        if($('body')[0].id != 'conversation') {
            $("#notice_data-text").focus();
        }
	}

	// XXX: refactor this code

	var favoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var dis = new_form.id;
												var fav = dis.replace('disfavor', 'favor');
												$('form#'+fav).replaceWith(new_form);
												$('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
											  }
					 };

	var disoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var fav = new_form.id;
												var dis = fav.replace('favor', 'disfavor');
												$('form#'+dis).replaceWith(new_form);
												$('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);
											  }
					 };

	var joinoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var leave = new_form.id;
												var join = leave.replace('leave', 'join');
												$('form#'+join).replaceWith(new_form);
												$('form#'+leave).ajaxForm(leaveoptions).each(addAjaxHidden);
											  }
					 };

	var leaveoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var join = new_form.id;
												var leave = join.replace('join', 'leave');
												$('form#'+leave).replaceWith(new_form);
												$('form#'+join).ajaxForm(joinoptions).each(addAjaxHidden);
											  }
					 };

	function addAjaxHidden() {
		var ajax = document.createElement('input');
		ajax.setAttribute('type', 'hidden');
		ajax.setAttribute('name', 'ajax');
		ajax.setAttribute('value', 1);
		this.appendChild(ajax);
	}

	$("form.form_favor").ajaxForm(favoptions);
	$("form.form_disfavor").ajaxForm(disoptions);
	$("form.form_group_join").ajaxForm(joinoptions);
	$("form.form_group_leave").ajaxForm(leaveoptions);
	$("form.form_favor").each(addAjaxHidden);
	$("form.form_disfavor").each(addAjaxHidden);
	$("form.form_group_join").each(addAjaxHidden);
	$("form.form_group_leave").each(addAjaxHidden);

	$("#form_user_nudge").ajaxForm ({ dataType: 'xml',
		beforeSubmit: function(xml) { $("#form_user_nudge input[type=submit]").attr("disabled", "disabled");
									  $("#form_user_nudge input[type=submit]").addClass("disabled");
									},
		success: function(xml) { $("#form_user_nudge").replaceWith(document._importNode($("#nudge_response", xml).get(0),true));
							     $("#form_user_nudge input[type=submit]").removeAttr("disabled");
							     $("#form_user_nudge input[type=submit]").removeClass("disabled");
							   }
	 });
	$("#form_user_nudge").each(addAjaxHidden);

	var Subscribe = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { $(".form_user_subscribe input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_subscribe input[type=submit]").addClass("disabled");
																	    },
					  success: function(xml) { var form_unsubscribe = document._importNode($('form', xml).get(0), true);
										  	   var form_unsubscribe_id = form_unsubscribe.id;
											   var form_subscribe_id = form_unsubscribe_id.replace('unsubscribe', 'subscribe');
											   $("form#"+form_subscribe_id).replaceWith(form_unsubscribe);
											   $("form#"+form_unsubscribe_id).ajaxForm(UnSubscribe).each(addAjaxHidden);
											   $("dd.subscribers").text(parseInt($("dd.subscribers").text())+1);
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled");
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
										     }
					};

	var UnSubscribe = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { $(".form_user_unsubscribe input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unsubscribe input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { var form_subscribe = document._importNode($('form', xml).get(0), true);
										  		 var form_subscribe_id = form_subscribe.id;
												 var form_unsubscribe_id = form_subscribe_id.replace('subscribe', 'unsubscribe');
												 $("form#"+form_unsubscribe_id).replaceWith(form_subscribe);
												 $("form#"+form_subscribe_id).ajaxForm(Subscribe).each(addAjaxHidden);
												 $("#profile_send_a_new_message").remove();
												 $("#profile_nudge").remove();
											     $("dd.subscribers").text(parseInt($("dd.subscribers").text())-1);
												 $(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");
												 $(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
											   }
					  };

	$(".form_user_subscribe").ajaxForm(Subscribe);
	$(".form_user_unsubscribe").ajaxForm(UnSubscribe);
	$(".form_user_subscribe").each(addAjaxHidden);
	$(".form_user_unsubscribe").each(addAjaxHidden);

	var PostNotice = { dataType: 'xml',
					   beforeSubmit: function(formData, jqForm, options) { if ($("#notice_data-text").get(0).value.length == 0) {
																				$("#form_notice").addClass("warning");
																				return false;
																		   }
																		   $("#form_notice").addClass("processing");
																		   $("#notice_action-submit").attr("disabled", "disabled");
																		   $("#notice_action-submit").addClass("disabled");
																		   return true;
												 						 },
					   timeout: '60000',
					   error: function (xhr, textStatus, errorThrown) {	$("#form_notice").removeClass("processing");
																		$("#notice_action-submit").removeAttr("disabled");
																		$("#notice_action-submit").removeClass("disabled");
																		if (textStatus == "timeout") {
																			alert ("Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists");
																		}
																		else {
																			if ($(".error", xhr.responseXML).length > 0) {
																				$('#form_notice').append(document._importNode($(".error", xhr.responseXML).get(0), true));
																			}
																			else {
																				var HTTP20x30x = [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307];
																				if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																					alert("Sorry! We had trouble sending your notice ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
																				}
																				else {
																					$("#notice_data-text").val("");
																					counter();
																				}
																			}
																		}
																	  },
					   success: function(xml) {	if ($("#error", xml).length > 0) {
													var result = document._importNode($("p", xml).get(0), true);
													result = result.textContent || result.innerHTML;
													alert(result);
												}
												else {
												    if ($("#command_result", xml).length > 0) {
													    var result = document._importNode($("p", xml).get(0), true);
													    result = result.textContent || result.innerHTML;
													    alert(result);
                                                    }
                                                    else {
                                                         li = $("li", xml).get(0);
                                                         if ($("#"+li.id).length == 0) {
                                                            var notice_irt_value = $('#notice_in-reply-to').val();
                                                            var notice_irt = '#notices_primary #notice-'+notice_irt_value;
                                                            if($('body')[0].id == 'conversation') {
                                                                if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
                                                                    $(notice_irt).append('

');
                                                                }
                                                                $($(notice_irt+' .notices')[0]).append(document._importNode(li, true));
                                                            }
                                                            else {
                                                                $("#notices_primary .notices").prepend(document._importNode(li, true));
                                                            }
                                                            $('#'+li.id).css({display:'none'});
                                                            $('#'+li.id).fadeIn(2500);
                                                            NoticeReply();
                                                            NoticeAttachments();
                                                         }
													}
													$("#notice_data-text").val("");
    												$("#notice_data-attach").val("");
    												$("#notice_in-reply-to").val("");
                                                    $('#notice_data-attach_selected').remove();
                                                    counter();
												}
												$("#form_notice").removeClass("processing");
												$("#notice_action-submit").removeAttr("disabled");
												$("#notice_action-submit").removeClass("disabled");
											 }
					   };
	$("#form_notice").ajaxForm(PostNotice);
	$("#form_notice").each(addAjaxHidden);
    NoticeReply();
    NoticeAttachments();
    NoticeDataAttach();
});

function NoticeReply() {
    if ($('#notice_data-text').length > 0 && $('#content .notice_reply').length > 0) {
        $('#content .notice').each(function() {
            var notice = $(this)[0];
            $($('.notice_reply', notice)[0]).click(function() {
                var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname');
                NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
                return false;
            });
        });
    }
}

function NoticeReplySet(nick,id) {
	rgx_username = /^[0-9a-zA-Z\-_.]*$/;
	if (nick.match(rgx_username)) {
		replyto = "@" + nick + " ";
		var text = $("#notice_data-text");
		if (text.length) {
			text.val(replyto + text.val());
			$("#form_notice input#notice_in-reply-to").val(id);
			if (text.get(0).setSelectionRange) {
				var len = text.val().length;
				text.get(0).setSelectionRange(len,len);
				text.get(0).focus();
			} else if (text.get(0).createTextRange) {
				var range = text.createTextRange();
				range.collapse(false);
				range.select();
			}
			return false;
		}
	}
	return true;
}

function NoticeAttachments() {
    $.fn.jOverlay.options = {
        method : 'GET',
        data : '',
        url : '',
        color : '#000',
        opacity : '0.6',
        zIndex : 99,
        center : false,
        imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
        bgClickToClose : true,
        success : function() {
            $('#jOverlayContent').append('<button>×</button>');
            $('#jOverlayContent button').click($.closeOverlay);
        },
        timeout : 0,
        autoHide : true,
        css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
    };

    $('#content .notice a.attachment').click(function() {
        $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
        return false;
    });

    var t;
    $("body:not(#shownotice) #content .notice a.thumbnail").hover(
        function() {
            var anchor = $(this);
            $("a.thumbnail").children('img').hide();
            anchor.closest(".entry-title").addClass('ov');

            if (anchor.children('img').length == 0) {
                t = setTimeout(function() {
                    $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
                        anchor.append(data);
                    });
                }, 500);
            }
            else {
                anchor.children('img').show();
            }
        },
        function() {
            clearTimeout(t);
            $("a.thumbnail").children('img').hide();
            $(this).closest(".entry-title").removeClass('ov');
        }
    );
}

function NoticeDataAttach() {
    NDA = $('#notice_data-attach');
    NDA.change(function() {
        S = '
'+$(this).val()+' <button>×</button>
';
        NDAS = $('#notice_data-attach_selected');
        (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#form_notice').append(S);
        $('#notice_data-attach_selected button').click(function(){
            $('#notice_data-attach_selected').remove();
            NDA.val('');
        });
    });
}
<|endoftext|>


<commit_before>// Copyright (c) 2009, Scott Ferguson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the software nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SCOTT FERGUSON ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL SCOTT FERGUSON BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/**
 * Returns the current PHP page the user is on
 *
 */
function findCurrentPage() {
    // Substrings out everything after the domain, then splits on the ?
    // and takes the left-side of the result
    return (window.location.href).substr(33).split('?')[0];
}

/**
 * Returns the current forum ID
 *
 */
function findForumID() {
    // Substrings out everything after the domain, then splits on the ?,
    // defaults to the argument list (right), splits on the &, looks at the first
    // parameter in the list, and splits on the = to get the result
    var parameterList = ((window.location.href).substr(33).split('?')[1]).split('&');

    for (var parameter in parameterList) {
        var currentParam = (parameterList[parameter]).split('=');

        if (currentParam[0] == 'threadid' || currentParam[0] == 'forumid') {
            return currentParam[1];
        }
    }
}

/**
 * Count the total number of pages to display in page navigator
 *
 */
function countPages() {

    var index = (findCurrentPage() == 'forumdisplay.php') ? 5 : 3;

    var result;

    jQuery('.pages').each(function() {
        var text = jQuery(this).html();
        var firstIndex = text.indexOf('(');
        var endIndex = text.indexOf(')');

        result = text.substr(firstIndex + 1, endIndex - (firstIndex + 1));
        if (result=='' || isNaN(result)) {
            result = 1;
        }
    });

    return Number(result);
}

function buildUrl(rootPageType, basePageID, page) {
    return 'http://forums.somethingawful.com/' + findCurrentPage() + '?' + rootPageType + '=' + basePageID + '&pagenumber=' + page;
}

/**
 * Jumps the user to the specified page
 *
 * @param rootPageType - forumid or threadid
 * @param basePagID - ID number associated with rootPageType
 * @param page - Page number to jump to
 *
 */
function jumpToPage(url) {
    location.href = url;
}

function findFirstUnreadPost() {
    var index = 0;
    var count = 0;
    var thread_post_size = jQuery('div#thread > table.post').size();

    // Get post number on page from anchor in URL
    var anchor_post = window.location.href.split('#pti')[1];
    if (!isNaN(anchor_post)) {
        return anchor_post-1;
    }

    // Get postid from anchor in URL
    anchor_post = window.location.href.split('#post')[1];
    if (!isNaN(anchor_post)) {
        var pti = jQuery('table#post'+anchor_post+' tr:first').attr('id').split('pti')[1];
        if (!isNaN(pti))
            return pti-1;
    }

    // Check if the user has the "Show an icon next to each post indicating if
    // it has been seen or not" option enabled for the forums
    var use_setseen = (jQuery('td.postdate > a[href*=action=setseen]').length > 0);

    jQuery('div#thread > table.post').each(function() {
        if (use_setseen) {
            // User has setseen icons enabled
            var posticon_img = jQuery('img[src*=posticon]', this);

            count++;
            if (posticon_img.attr('src') == 'http://fi.somethingawful.com/style/posticon-seen.gif') {
                index = count;
            }
        } else {
            // User has read post coloring enabled
            var post = jQuery('tr', this);

            count++;
            if (post.hasClass('seen1') || post.hasClass('seen2')) {
                index = count;
            }
        }
    });

    if (index == thread_post_size) // All posts read
        return index - 1;

    return index;
}
<commit_msg>Added function which always returns the forumid<commit_after>// Copyright (c) 2009, Scott Ferguson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the software nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SCOTT FERGUSON ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL SCOTT FERGUSON BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/**
 * Returns the current PHP page the user is on
 *
 */
function findCurrentPage() {
    // Substrings out everything after the domain, then splits on the ?
    // and takes the left-side of the result
    return (window.location.href).substr(33).split('?')[0];
}

/**
 * Returns the current forum ID
 *
 */
function findForumID() {
    // Substrings out everything after the domain, then splits on the ?,
    // defaults to the argument list (right), splits on the &, looks at the first
    // parameter in the list, and splits on the = to get the result
    var parameterList = ((window.location.href).substr(33).split('?')[1]).split('&');

    for (var parameter in parameterList) {
        var currentParam = (parameterList[parameter]).split('=');

        if (currentParam[0] == 'threadid' || currentParam[0] == 'forumid') {
            return currentParam[1];
        }
    }
}

/**
 * Gets the current forum ID even when inside a thread
 *
 */
function findRealForumID() {
    var crumb = jQuery('div.breadcrumbs:first a[href*=forumid]:last');
    var forumid = crumb.attr('href').split('forumid=')[1];
    alert(forumid);
    return forumid;
}

/**
 * Count the total number of pages to display in page navigator
 *
 */
function countPages() {

    var index = (findCurrentPage() == 'forumdisplay.php') ? 5 : 3;

    var result;

    jQuery('.pages').each(function() {
        var text = jQuery(this).html();
        var firstIndex = text.indexOf('(');
        var endIndex = text.indexOf(')');

        result = text.substr(firstIndex + 1, endIndex - (firstIndex + 1));
        if (result=='' || isNaN(result)) {
            result = 1;
        }
    });

    return Number(result);
}

function buildUrl(rootPageType, basePageID, page) {
    return 'http://forums.somethingawful.com/' + findCurrentPage() + '?' + rootPageType + '=' + basePageID + '&pagenumber=' + page;
}

/**
 * Jumps the user to the specified page
 *
 * @param rootPageType - forumid or threadid
 * @param basePagID - ID number associated with rootPageType
 * @param page - Page number to jump to
 *
 */
function jumpToPage(url) {
    location.href = url;
}

function findFirstUnreadPost() {
    var index = 0;
    var count = 0;
    var thread_post_size = jQuery('div#thread > table.post').size();

    // Get post number on page from anchor in URL
    var anchor_post = window.location.href.split('#pti')[1];
    if (!isNaN(anchor_post)) {
        return anchor_post-1;
    }

    // Get postid from anchor in URL
    anchor_post = window.location.href.split('#post')[1];
    if (!isNaN(anchor_post)) {
        var pti = jQuery('table#post'+anchor_post+' tr:first').attr('id').split('pti')[1];
        if (!isNaN(pti))
            return pti-1;
    }

    // Check if the user has the "Show an icon next to each post indicating if
    // it has been seen or not" option enabled for the forums
    var use_setseen = (jQuery('td.postdate > a[href*=action=setseen]').length > 0);

    jQuery('div#thread > table.post').each(function() {
        if (use_setseen) {
            // User has setseen icons enabled
            var posticon_img = jQuery('img[src*=posticon]', this);

            count++;
            if (posticon_img.attr('src') == 'http://fi.somethingawful.com/style/posticon-seen.gif') {
                index = count;
            }
        } else {
            // User has read post coloring enabled
            var post = jQuery('tr', this);

            count++;
            if (post.hasClass('seen1') || post.hasClass('seen2')) {
                index = count;
            }
        }
    });

    if (index == thread_post_size) // All posts read
        return index - 1;

    return index;
}
<|endoftext|>


<commit_before>App = App || {};
$.extend(App, {
    eventHandlers: {
        '.play-btn, click': 'playPause',
        '.speed-inc, click': 'speedIncrement',
        '.speed-dec, click': 'speedDecrement',
        '.font-inc, click': 'fontIncrement',
        '.font-dec, click': 'fontDecrement',
        '.contrast-toggle, click': 'contrastToggle',
        '.full-screen, click': 'toggleFullScreen',
        'main a, click': 'embeddedLinkClick',
        'main, mouseenter': 'listenFaster',
        'main, mouseleave': 'listenSlower'
    },
    bindEventHandlers: function() {
        var that = this;
        $.each(that.eventHandlers, function(k, v) {
            var split = k.split(","),
                el = $.trim(split[0]),
                trigger = $.trim(split[1]);
            $(document).delegate(el, trigger, that.events[v]);
        });
    },
    events: {
        toggleFullScreen: function() {
            if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
                if (document.documentElement.requestFullscreen) {
                    document.documentElement.requestFullscreen();
                } else if (document.documentElement.msRequestFullscreen) {
                    document.documentElement.msRequestFullscreen();
                } else if (document.documentElement.mozRequestFullScreen) {
                    document.documentElement.mozRequestFullScreen();
                } else if (document.documentElement.webkitRequestFullscreen) {
                    document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
            }
        },
        listenForPageMove: null, // storing setInterval
        listenSlower: function() {
            var that = App;
            if (that.readerData.isScrolling === false) return;
            var intrvl = that.readerData.scrollSpeed * 60; // abstract
            window.clearInterval(that.events.listenForPageMove);
            that.events.listenForPageMove = setInterval(function() {
                that.layout.countPages();
            }, intrvl);
        },
        listenFaster: function() {
            var that = App;
            if (that.readerData.isScrolling === false) return;
            var intrvl = that.readerData.scrollSpeed * 3; // abstract
            window.clearInterval(that.events.listenForPageMove);
            that.events.listenForPageMove = setInterval(function() {
                that.layout.countPages();
            }, intrvl);
        },
        playPause: function() {
            var that = App,
                playBtn = $('.controls').find('.play-btn'),
                state = that.readerData.isScrolling ? 'play' : 'pause';
            playBtn.attr('data-state', state);
            if (that.readerData.isScrolling === false) {
                that.events.startScrolling();
            } else {
                that.events.stopScrolling();
            }
            return that;
        },
        startScrolling: function() {
            var that = App;
            window.clearInterval(that.readerData.scrollInt);
            that.readerData.scrollInt = setInterval(function() {
                that.el.scrollTop(that.el.scrollTop() + 1);
            }, that.readerData.scrollSpeed);
            that.readerData.isScrolling = true;
            that.events.listenSlower();
        },
        stopScrolling: function() {
            var that = App;
            var playBtn = $('.controls').find('.play-btn').attr('data-state', 'play');
            if (App.debug) console.log('Stopped');
            window.clearInterval(that.readerData.scrollInt);
            window.clearInterval(that.events.listenForPageMove);
            that.readerData.isScrolling = false;
        },
        speedIncrement: function() {
            var that = App;
            that.events.stopScrolling();
            that.readerData.scrollSpeed -= 10;
            that.events.startScrolling();
            that.updateUserPreferences();
        },
        speedDecrement: function() {
            var that = App;
            that.events.stopScrolling();
            that.readerData.scrollSpeed += 10;
            that.events.startScrolling();
            that.updateUserPreferences();
        },
        isChapterEnd: function() {
            var that = App;
            that.events.stopScrolling();
            if (App.debug) console.log('Chapter end');
        },
        isBookEnd: function() {
            var that = App;
            that.events.stopScrolling();
            if (App.debug) console.log('Book end');
        },
        fontIncrement: function() {
            var that = App;
            var size = (that.readerData.fSize <= that.readerData.maxFontSize ? that.readerData.fSize + 10 : that.readerData.fSize);
            that.el.css('font-size', that.readerData.fSize + '%');
            that.layout.adjustFramePosition();
            that.updatedReaderData('fSize', size);
            that.updateUserPreferences();
            return that;
        },
        fontDecrement: function() {
            var that = App;
            var size = (that.readerData.fSize >= that.readerData.minFontSize ? that.readerData.fSize - 10 : that.readerData.fSize);
            that.el.css('font-size', that.readerData.fSize + '%');
            that.layout.adjustFramePosition();
            that.updatedReaderData('fSize', size);
            that.updateUserPreferences();
            return that;
        },
        contrastToggle: function(e) {
            var that = App;
            var contrast = e && e.target ? $(e.target).attr('data-contrast') : e,
                html = $('html');

            if (contrast === 'dark') {
                html.addClass('darkCss');
                html.removeClass('lightCss');
            } else if (contrast === 'light') {
                html.addClass('lightCss');
                html.removeClass('darkCss');
            }

            that.updatedReaderData('contrast', contrast);
            that.updateUserPreferences();
            return that;
        },
        embeddedLinkClick: function(e) {
            var that = App;
            var target = $(e.target),
                href = target.attr('href'),
                ext = href.match(/^http/);

            if (ext) {
                routeExternalLink(href);
            } else {
                e.preventDefault();
                routeInternalLink(href);
            }

            function routeInternalLink(url) {
                that.loadChapter(url);
                that.saveLocation();
            }

            function routeExternalLink(url) {
                e.stopPropagation();
                target.attr('target', '_blank');
            }
        }
    }
});
<commit_msg>abstracted page-turn interval<commit_after>App = App || {};
$.extend(App, {
    eventHandlers: {
        '.play-btn, click': 'playPause',
        '.speed-inc, click': 'speedIncrement',
        '.speed-dec, click': 'speedDecrement',
        '.font-inc, click': 'fontIncrement',
        '.font-dec, click': 'fontDecrement',
        '.contrast-toggle, click': 'contrastToggle',
        '.full-screen, click': 'toggleFullScreen',
        'main a, click': 'embeddedLinkClick'
    },
    bindEventHandlers: function() {
        var that = this;
        $.each(that.eventHandlers, function(k, v) {
            var split = k.split(","),
                el = $.trim(split[0]),
                trigger = $.trim(split[1]);
            $(document).delegate(el, trigger, that.events[v]);
        });
    },
    events: {
        toggleFullScreen: function() {
            if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
                if (document.documentElement.requestFullscreen) {
                    document.documentElement.requestFullscreen();
                } else if (document.documentElement.msRequestFullscreen) {
                    document.documentElement.msRequestFullscreen();
                } else if (document.documentElement.mozRequestFullScreen) {
                    document.documentElement.mozRequestFullScreen();
                } else if (document.documentElement.webkitRequestFullscreen) {
                    document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
            }
        },
        listenForPageChangeInterval: null, // storing setInterval
        listenForPageChange: function() {
            var that = App;
            if (that.readerData.isScrolling === false) return;

            var fontSize = $(that.el.first('p')).css('font-size');
            var lineHeight = Math.floor(parseInt(fontSize.replace('px', '')) * 1.5);

            var intrvl = (lineHeight * that.el.height()) * (that.readerData.scrollSpeed / 30);

            window.clearInterval(that.events.listenForPageChangeInterval);
            that.events.listenForPageChangeInterval = setInterval(function() {
                that.layout.countPages();
            }, intrvl);
        },
        playPause: function() {
            var that = App,
                playBtn = $('.controls').find('.play-btn'),
                state = that.readerData.isScrolling ? 'play' : 'pause';
            playBtn.attr('data-state', state);
            if (that.readerData.isScrolling === false) {
                that.events.startScrolling();
            } else if (that.readerData.isScrolling === true) {
                that.events.stopScrolling();
            }
            return that;
        },
        startScrolling: function() {
            var that = App;
            window.clearInterval(that.readerData.scrollInt);
            that.readerData.scrollInt = setInterval(function() {
                that.el.scrollTop(that.el.scrollTop() + 1);
            }, that.readerData.scrollSpeed);
            that.readerData.isScrolling = true;
            that.events.listenForPageChange();
        },
        stopScrolling: function() {
            var that = App;
            var playBtn = $('.controls').find('.play-btn').attr('data-state', 'play');
            if (App.debug) console.log('Stopped');
            window.clearInterval(that.readerData.scrollInt);
            window.clearInterval(that.events.listenForPageChangeInterval);
            that.readerData.isScrolling = false;
        },
        speedIncrement: function() {
            var that = App;
            that.events.stopScrolling();
            that.readerData.scrollSpeed -= 10;
            that.events.startScrolling();
            that.updateUserPreferences();
        },
        speedDecrement: function() {
            var that = App;
            that.events.stopScrolling();
            that.readerData.scrollSpeed += 10;
            that.events.startScrolling();
            that.updateUserPreferences();
        },
        isChapterEnd: function() {
            var that = App;
            that.events.stopScrolling();
            if (App.debug) console.log('Chapter end');
        },
        isBookEnd: function() {
            var that = App;
            that.events.stopScrolling();
            if (App.debug) console.log('Book end');
        },
        fontIncrement: function() {
            var that = App;
            var size = (that.readerData.fSize <= that.readerData.maxFontSize) ? that.readerData.fSize + 10 : that.readerData.fSize;
            that.el.css('font-size', size + '%');
            that.layout.adjustFramePosition();
            that.updatedReaderData('fSize', size);
            console.log(that.readerData.fSize);
            that.updateUserPreferences();
            return that;
        },
        fontDecrement: function() {
            var that = App;
            var size = (that.readerData.fSize >= that.readerData.minFontSize) ? that.readerData.fSize - 10 : that.readerData.fSize;
            that.el.css('font-size', size + '%');
            that.layout.adjustFramePosition();
            that.updatedReaderData('fSize', size);
            that.updateUserPreferences();
            return that;
        },
        contrastToggle: function(e) {
            var that = App;
            var contrast = e && e.target ? $(e.target).attr('data-contrast') : e,
                html = $('html');

            if (contrast === 'dark') {
                html.addClass('darkCss');
                html.removeClass('lightCss');
            } else if (contrast === 'light') {
                html.addClass('lightCss');
                html.removeClass('darkCss');
            }

            that.updatedReaderData('contrast', contrast);
            that.updateUserPreferences();
            return that;
        },
        embeddedLinkClick: function(e) {
            var that = App;
            var target = $(e.target),
                href = target.attr('href'),
                ext = href.match(/^http/);

            if (ext) {
                routeExternalLink(href);
            } else {
                e.preventDefault();
                routeInternalLink(href);
            }

            function routeInternalLink(url) {
                that.loadChapter(url);
                that.saveLocation();
            }

            function routeExternalLink(url) {
                e.stopPropagation();
                target.attr('target', '_blank');
            }
        }
    }
});
<|endoftext|>


<commit_before>(function(factory){
    if(typeof define==='function'&&define.amd){
        define(['jquery'],factory);
    }else if(typeof module==='object'&&module.exports){
        module.exports=factory(require('jquery'));
    }else{
        factory(window.jQuery);
    }
}
(function($){
    $.extend(true,$.summernote.lang,{
        'en-US':{
            cleaner:{
                tooltip:'Cleaner',
                not:'Text has been Cleaned!!!'
            }
        }
    });

    $.extend($.summernote.options,{
        cleaner:{
            notTime:2400, // Time to display Notifications.
            action:'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
            newline:'
', // Summernote's default is to use '

'
            notStyle:'position:absolute;bottom:0;left:2px',
            icon:'<svg xmlns="http://www.w3.org/2000/svg" id="libre-paintbrush" viewBox="0 0 14 14"><path d="m 11.821425,1 q 0.46875,0 0.82031,0.311384 0.35157,0.311384 0.35157,0.780134 0,0.421875 -0.30134,1.01116 -2.22322,4.212054 -3.11384,5.035715 -0.64956,0.609375 -1.45982,0.609375 -0.84375,0 -1.44978,-0.61942 -0.60603,-0.61942 -0.60603,-1.469866 0,-0.857143 0.61608,-1.419643 l 4.27232,-3.877232 Q 11.345985,1 11.821425,1 z m -6.08705,6.924107 q 0.26116,0.508928 0.71317,0.870536 0.45201,0.361607 1.00781,0.508928 l 0.007,0.475447 q 0.0268,1.426339 -0.86719,2.32366 Q 5.700895,13 4.261155,13 q -0.82366,0 -1.45982,-0.311384 -0.63616,-0.311384 -1.0212,-0.853795 -0.38505,-0.54241 -0.57924,-1.225446 -0.1942,-0.683036 -0.1942,-1.473214 0.0469,0.03348 0.27455,0.200893 0.22768,0.16741 0.41518,0.29799 0.1875,0.130581 0.39509,0.24442 0.20759,0.113839 0.30804,0.113839 0.27455,0 0.3683,-0.247767 0.16741,-0.441965 0.38505,-0.753349 0.21763,-0.311383 0.4654,-0.508928 0.24776,-0.197545 0.58928,-0.31808 0.34152,-0.120536 0.68974,-0.170759 0.34821,-0.05022 0.83705,-0.07031 z"/></svg>',
            keepHtml: false, //Remove all Html formats
            badTags: ['style','script','applet','embed','noframes','noscript', 'html'], //Remove full tags with contents
            badAttributes: ['style','start'] //Remove attributes from remaining tags
        }
    });

    $.extend($.summernote.plugins,{
        'cleaner':function(context){
            var self=this;
            var ui=$.summernote.ui;
            var $note=context.layoutInfo.note;
            var $editor=context.layoutInfo.editor;
            var options=context.options;
            var lang=options.langInfo;
            var cleanText=function(txt,nlO){
                if(options.cleaner.keepHtml){
                    var sS=/(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
                    var out=txt.replace(sS,' ');

                    var nL=/(\n)+/g;
                    out=out.replace(nL,nlO);
                    var cS=new RegExp('','gi');
                    out=out.replace(cS,'');
                    var tS=new RegExp('<(/)*(meta|link|span|\\?xml:|st1:|o:|font)(.*?)>','gi');
                    out=out.replace(tS,'');

                    //Remove Bad tags
                    var bT=options.cleaner.badTags;
                    for(var i=0;i<bT.length;i++){
                        tS=new RegExp('<'+bT[i]+'.*?'+bT[i]+'(.*?)>','gi');
                        out=out.replace(tS,'');
                    }

                    //Remove Bad Attributes
                    var bA=options.cleaner.badAttributes;
                    for(var ii=0;ii<bA.length;ii++){
                        //var aS=new RegExp(' ('+bA[ii]+'="(.*?)")|('+bA[ii]+'=\'(.*?)\')','gi');
                        var aS=new RegExp(' '+bA[ii]+'=[\'|"](.*?)[\'|"]','gi');
                        out=out.replace(aS,'');
                    }

                }else{
                    var sS=/(\r| class=(")?Mso[a-zA-Z]+(")?)/g;
                    var out=txt.replace(sS,' ');
                    var nL=/(\n)+/g;
                    out=out.replace(nL,nlO);
                }

                return out;
            };
            if(options.cleaner.action=='both'||options.cleaner.action=='button'){
                context.memo('button.cleaner',function(){
                    var button=ui.button({
                        contents:options.cleaner.icon,
                        tooltip:lang.cleaner.tooltip,
                        click:function(){
                            if($note.summernote('createRange').toString()){
                                var text=cleanText($note.summernote('createRange').toString(),options.cleaner.newline);
                                $note.summernote('pasteHTML',text);
                            }else{
                                var text=cleanText($note.summernote().text(),options.cleaner.newline);
                                var old=$note.summernote('code');
                            }
                            $editor.find('.note-resizebar').append('
'+lang.cleaner.not+'
');
                            setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
                        }
                    });
                    return button.render();
                });
            }
            this.events={
                'summernote.paste':function(we,e){
                    if(options.cleaner.action=='both'||options.cleaner.action=='paste'){
                        e.preventDefault();
                        var ua=window.navigator.userAgent;
                        var msie=ua.indexOf("MSIE ");
                        if (msie>0||!!navigator.userAgent.match(/Trident.*rv\:11\./)){
                            var text=window.clipboardData.getData("Text");
                        }else{
                            var text=e.originalEvent.clipboardData.getData((options.cleaner.keepHtml?'text/html':'text/plain'));
                        }
                        var text=cleanText(text,options.cleaner.newline);
                        if($note.summernote('createRange').toString()){
                            $note.summernote('pasteHTML',text);
                        }else{
                            var old=$note.summernote('code');
                            $note.summernote('pasteHTML',old+text);
                        }
                        $editor.find('.note-resizebar').append('
'+lang.cleaner.not+'
');
                        setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
                    }
                }
            }
        }
    });
}));<commit_msg>:punch:<commit_after>(function(factory){
  if(typeof define==='function'&&define.amd){
    define(['jquery'],factory);
  }else if(typeof module==='object'&&module.exports){
    module.exports=factory(require('jquery'));
  }else{
    factory(window.jQuery);
  }
}
(function($){
  $.extend(true,$.summernote.lang,{
    'en-US':{
      cleaner:{
        tooltip:'Cleaner',
        not:'Text has been Cleaned!!!'
      }
    }
  });
  $.extend($.summernote.options,{
    cleaner:{
      notTime:2400, // Time to display Notifications.
      action:'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
      newline:'
', // Summernote's default is to use '

'
      notStyle:'position:absolute;bottom:0;left:2px',
      icon:'<svg xmlns="http://www.w3.org/2000/svg" id="libre-paintbrush" viewBox="0 0 14 14"><path d="m 11.821425,1 q 0.46875,0 0.82031,0.311384 0.35157,0.311384 0.35157,0.780134 0,0.421875 -0.30134,1.01116 -2.22322,4.212054 -3.11384,5.035715 -0.64956,0.609375 -1.45982,0.609375 -0.84375,0 -1.44978,-0.61942 -0.60603,-0.61942 -0.60603,-1.469866 0,-0.857143 0.61608,-1.419643 l 4.27232,-3.877232 Q 11.345985,1 11.821425,1 z m -6.08705,6.924107 q 0.26116,0.508928 0.71317,0.870536 0.45201,0.361607 1.00781,0.508928 l 0.007,0.475447 q 0.0268,1.426339 -0.86719,2.32366 Q 5.700895,13 4.261155,13 q -0.82366,0 -1.45982,-0.311384 -0.63616,-0.311384 -1.0212,-0.853795 -0.38505,-0.54241 -0.57924,-1.225446 -0.1942,-0.683036 -0.1942,-1.473214 0.0469,0.03348 0.27455,0.200893 0.22768,0.16741 0.41518,0.29799 0.1875,0.130581 0.39509,0.24442 0.20759,0.113839 0.30804,0.113839 0.27455,0 0.3683,-0.247767 0.16741,-0.441965 0.38505,-0.753349 0.21763,-0.311383 0.4654,-0.508928 0.24776,-0.197545 0.58928,-0.31808 0.34152,-0.120536 0.68974,-0.170759 0.34821,-0.05022 0.83705,-0.07031 z"/></svg>',
      keepHtml: false, //Remove all Html formats
      badTags: ['style','script','applet','embed','noframes','noscript', 'html'], //Remove full tags with contents
      badAttributes: ['style','start'] //Remove attributes from remaining tags
    }
  });
  $.extend($.summernote.plugins,{
    'cleaner':function(context){
      var self=this;
      var ui=$.summernote.ui;
      var $note=context.layoutInfo.note;
      var $editor=context.layoutInfo.editor;
      var options=context.options;
      var lang=options.langInfo;
      var cleanText=function(txt,nlO){
        if(options.cleaner.keepHtml){
          var sS=/(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
          var out=txt.replace(sS,' ');
          var nL=/(\n)+/g;
          out=out.replace(nL,nlO);
          var cS=new RegExp('','gi');
          out=out.replace(cS,'');
          var tS=new RegExp('<(/)*(meta|link|span|\\?xml:|st1:|o:|font)(.*?)>','gi');
          out=out.replace(tS,'');
          var bT=options.cleaner.badTags;
          for(var i=0;i<bT.length;i++){
            tS=new RegExp('<'+bT[i]+'.*?'+bT[i]+'(.*?)>','gi');
            out=out.replace(tS,'');
          }
          var bA=options.cleaner.badAttributes;
          for(var ii=0;ii<bA.length;ii++){
            //var aS=new RegExp(' ('+bA[ii]+'="(.*?)")|('+bA[ii]+'=\'(.*?)\')','gi');
            var aS=new RegExp(' '+bA[ii]+'=[\'|"](.*?)[\'|"]','gi');
            out=out.replace(aS,'');
          }
        }else{
          var sS=/(\r| class=(")?Mso[a-zA-Z]+(")?)/g;
          var out=txt.replace(sS,' ');
          var nL=/(\n)+/g;
          out=out.replace(nL,nlO);
        }
        return out;
      };
      if(options.cleaner.action=='both'||options.cleaner.action=='button'){
        context.memo('button.cleaner',function(){
          var button=ui.button({
            contents:options.cleaner.icon,
            tooltip:lang.cleaner.tooltip,
            click:function(){
              if($note.summernote('createRange').toString()){
                var text=cleanText($note.summernote('createRange').toString(),options.cleaner.newline);
                $note.summernote('pasteHTML',text);
              }else{
                var text=cleanText($note.summernote().text(),options.cleaner.newline);
                var old=$note.summernote('code');
              }
              $editor.find('.note-resizebar').append('
'+lang.cleaner.not+'
');
              setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
            }
          });
          return button.render();
        });
      }
      this.events={
        'summernote.paste':function(we,e){
          if(options.cleaner.action=='both'||options.cleaner.action=='paste'){
            e.preventDefault();
            var ua=window.navigator.userAgent;
            var msie=ua.indexOf("MSIE ");
            if(msie>0||!!navigator.userAgent.match(/Trident.*rv\:11\./)){
              var text=window.clipboardData.getData("Text");
            }else{
              var text=e.originalEvent.clipboardData.getData((options.cleaner.keepHtml?'text/html':'text/plain'));
            }
            var text=cleanText(text,options.cleaner.newline);
            if($note.summernote('createRange').toString()){
              $note.summernote('pasteHTML',text);
            }else{
              var old=$note.summernote('code');
              $note.summernote('pasteHTML',old+text);
            }
            $editor.find('.note-resizebar').append('
'+lang.cleaner.not+'
');
            setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
          }
        }
      }
    }
  });
}));
<|endoftext|>


<commit_before>//Two Sum

/*RULES:
  Function takes two arguments
    An array of numbers
    A 'sum' number that we want

  The function should return an array of pairs from inside the number array, that add up to the sum provided

  It's okay for numbers to be used multiple times

  Different ways to solve:
    Nested Loops O(n^2)
    Hash Table O(n)

  Try to solve for both!
*/

/*PSEUDOCODE (NESTED LOOPS SOLUTION):

  1)Loop through provided array
      For each number, add number to each of the other ones individually
        If that == provided sum
          Make a pair, push to new array you will be returning
        else,
          Move on to next pair to try and add
      Return final array
*/

function twoSum(numArr, sum){
  var sumArr = []
  numArr.forEach(function(number){
    for(var i = 0; i < numArr.length; i ++){
      if (number == numArr[i]){
        i++;
      }
      if ((number + numArr[i]) == sum){
        sumArr.push([number, numArr[i]])
      }
    }
  })
  return sumArr;
}

/*PSEUDOCODE (HASH TABLE)
  1)Create object (or array in this case, you just need to see if this number exists even just once)
  2)Make each number in numArr a key, and make the value the number of times they come up
  3)Loop through the numbers, and subtract from sum
      Whatever the remainder is, check the object to see if that number is included.
      If it is, pair those up and push to array
      Else, move on to the next number in the iteration
*/

function twoSum(numArr, sum){
  var sumArr = [];

  numArr.forEach(function(number){
    var diff = sum - number;
    if (numArr.includes(diff)){
      sumArr.push([number, diff])
    }
  })
  return sumArr;
}
<commit_msg>Refactor for a more solid solution<commit_after>//Two Sum

/*RULES:
  Function takes two arguments
    An array of numbers
    A 'sum' number that we want

  The function should return an array of pairs from inside the number array, that add up to the sum provided

  It's okay for numbers to be used multiple times

  Different ways to solve:
    Nested Loops O(n^2)
    Hash Table O(n)

  Try to solve for both!
*/

/*PSEUDOCODE (NESTED LOOPS SOLUTION):

  1)Loop through provided array
      For each number, add number to each of the other ones individually
        If that == provided sum
          Make a pair, push to new array you will be returning
        else,
          Move on to next pair to try and add
      Return final array
*/

function twoSum(numArr, sum){
  var sumArr = []
  numArr.forEach(function(number){
    for(var i = 0; i < numArr.length; i ++){
      if (number == numArr[i]){
        i++;
      }
      if ((number + numArr[i]) == sum){
        sumArr.push([number, numArr[i]])
      }
    }
  })
  return sumArr;
}

/*PSEUDOCODE (HASH TABLE)
  1)Create object (or array in this case, you just need to see if this number exists even just once)
  2)Make each number in numArr a key, and make the value the number of times they come up
  3)Loop through the numbers, and subtract from sum
      Whatever the remainder is, check the object to see if that number is included.
      If it is, pair those up and push to array
      Else, move on to the next number in the iteration
*/

function twoSum(numArr, sum){
  var sumArr = [];
  var diffArr = [];

  for (var i = 0; i < numArr.length; i++){
    var currNum = numArr[i];
    var diff =  sum - currNum;

    if (diffArr.indexOf(diff) !== -1){
      sumArr.push([currNum, diff]);
    }
    diffArr.push(currNum)
  }

  return sumArr;
}
<|endoftext|>


<commit_before>var util = require("../lib/util");
var track = util.track;
var regex = util.regex;
var excludeBefore = util.excludeBefore;

track("vegano", "vegana");

var negations = ["no"]

module.exports = [
  excludeBefore(regex( "(quisiera|quiero|debería|debe|pensando .*) (ser|hacerme|hacerse|convertirse en) ?(un|una)? vegan(a|o|os)" ), negations),
  // "Ya no quiero comer animales"
];
<commit_msg>Update spanish.js<commit_after>var util = require("../lib/util");
var track = util.track;
var regex = util.regex;
var excludeBefore = util.excludeBefore;

track("vegano", "vegana");

var negations = ["no"]

module.exports = [
  excludeBefore(regex( "(quisiera|quiero|debería|debe|pensando .*) (ser|hacerme|hacerse|convertirse en) ?(un|una)? vegan(a|o)" ), negations),
  // "Ya no quiero comer animales"
];
<|endoftext|>