<commit_before>/**
 * Created with JetBrains WebStorm.
 * User: jepicard
 * Date: 21/05/13
 * Time: 10:45
 * This script enables specific device actions through phoneGap
 */

(function () {
    "use strict";
    //Init contactWidget
    $(document).ready(function(){
        document.addEventListener("deviceready", findContacts , false);
        var $eventInvitedPeople = $( "#eventInvitedPeople" );
        var $contactsListView = $( "#contactsListView" );
        $( "#buttonEventInvitedPeople").on( "tap", function(){
            $eventInvitedPeople.css("display", "block");
            $contactsListView.css("display", "none");
        });
        $( "#buttonContactsListView").on( "tap", function(){
            $eventInvitedPeople.css("display", "none");
            $contactsListView.css("display", "block");
        });

        function onSuccess(contacts) {
            $.each(contacts,function(){
                var contact = $( "
" + this.name.givenName
                    + " " + this.name.middleName + " " + this.name.familyName + "
" );
                $( "#contactsListView" ).append(contact);
            });
        };

        function onError(contactError) {
            alert('Could not retrieve contacts. Error: ' + contactError);
        };
        // find all contacts with any name field
        function findContacts() {
            var options = new ContactFindOptions();
            options.multiple  = true;
            var fields = ["name"];
            try{
                navigator.contacts.find(fields, onSuccess, onError, options);
            }catch (e){
                alert("Could not use phoneGap contacts search: " + e.message);
            }
        };
    });

    function displayMap(lat, lng, $eventPlace) {
        var map;
        var directionsDisplay = new google.maps.DirectionsRenderer();
        var directionsService = new google.maps.DirectionsService();

        var origin = new google.maps.LatLng(lat,lng);
        var destination = $eventPlace;

        var mapOptions = {
            zoom: 7,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: origin
        };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

        // Bind the renderer to the map and the panel to display directions
        directionsDisplay.setMap(map);
        $("#directionsPanel").empty();

        directionsDisplay.setPanel(document.getElementById("directionsPanel"));

        var request = {
            origin: origin,
            destination: destination,
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
            else{
                $("#map-canvas").html("an error occurred: " + status);
            }
        });
    }

    $( "#eventEdit" ).on( "pagebeforeshow", function() {
        //Clear invitedListView and Display invited people for the selectedEvent
        var $eventInvitedPeople = $( "#eventInvitedPeople").empty();
        $eventInvitedPeople.css("display", "block");
        $( "#contactsListView").css("display", "none");

        var selectedEvent = agenda42.selections.selectedEvent;
        if(selectedEvent !== undefined){
            $.each(selectedEvent.invited,function(){
                var contact = $( "
" + this.firstName + " " + this.lastName + "
" );
                $eventInvitedPeople.append(contact);
            });
            $eventInvitedPeople.listview("refresh");
        }
    });

    $( "#eventEdit" ).on( "pageinit", function() {
        //Init the click handler on event image
        $( "#eventImage" ).on( "tap" ,function(){
            $( "#eventImagePanel" ).panel( "open" );
        });

        //Init the click handler on selectPictureButton
        $( "#selectPictureButton" ).on( "tap", function(){
            //browse image directory
            alert ("Unsupported feature");
        });
        //Init the click handler on TakeNewPictureButton
        $( "#takeNewPictureButton" ).on( "tap", function(){
            //open photo Task
            if(navigator.camera !== undefined){
                navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
                    destinationType: Camera.DestinationType.FILE_URI });
            }
            else {
                alert ("Unsupported feature on this platform");
            }
        });
        function onSuccess(imageURI) {
            $( "#eventImage" ).attr("src", imageURI);
        }
        function onFail(message) {
            alert( 'Failed because: ' + message);
        }

        //Setting up the navigationPage with directions
        $( "#directionsMap" ).on( "pagebeforeshow", function(){
            //Get geolocation info
            var lat;
            var lng;
            //success callback
            var onSuccess = function(position) {
                lat = position.coords.latitude;
                lng = position.coords.longitude;
                displayMap(lat, lng, $( "#eventPlace").val());
            };
            // onError Callback receives a PositionError object
            function onError(error) {
                alert('code: '    + error.code    + '\n' +
                    'message: ' + error.message + '\n');
            }
            navigator.geolocation.getCurrentPosition(onSuccess, onError);
        });
    });

})();<commit_msg>Formating contacts names<commit_after>/**
 * Created with JetBrains WebStorm.
 * User: jepicard
 * Date: 21/05/13
 * Time: 10:45
 * This script enables specific device actions through phoneGap
 */

(function () {
    "use strict";
    //Init contactWidget
    $(document).ready(function(){
        document.addEventListener("deviceready", findContacts , false);
        var $eventInvitedPeople = $( "#eventInvitedPeople" );
        var $contactsListView = $( "#contactsListView" );
        $( "#buttonEventInvitedPeople").on( "tap", function(){
            $eventInvitedPeople.css("display", "block");
            $contactsListView.css("display", "none");
        });
        $( "#buttonContactsListView").on( "tap", function(){
            $eventInvitedPeople.css("display", "none");
            $contactsListView.css("display", "block");
        });

        function onSuccess(contacts) {
            $.each(contacts,function(){
                var givenName = "";
                if(this.name.givenName !== undefined){
                    givenName = this.name.givenName;
                }
                var middleName = "";
                if(this.name.middleName !== undefined){
                    middleName = this.name.middleName;
                }
                var familyName = "";
                if(this.name.familyName !== undefined){
                    familyName = this.name.familyName;
                }
                var contact = $( "
" + givenName + " "
                    + middleName + " " + familyName + "
" );
                $( "#contactsListView" ).append(contact);
            });
        };

        function onError(contactError) {
            alert('Could not retrieve contacts. Error: ' + contactError);
        };
        // find all contacts with any name field
        function findContacts() {
            var options = new ContactFindOptions();
            options.multiple  = true;
            var fields = ["name"];
            try{
                navigator.contacts.find(fields, onSuccess, onError, options);
            }catch (e){
                alert("Could not use phoneGap contacts search: " + e.message);
            }
        };
    });

    function displayMap(lat, lng, $eventPlace) {
        var map;
        var directionsDisplay = new google.maps.DirectionsRenderer();
        var directionsService = new google.maps.DirectionsService();

        var origin = new google.maps.LatLng(lat,lng);
        var destination = $eventPlace;

        var mapOptions = {
            zoom: 7,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: origin
        };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

        // Bind the renderer to the map and the panel to display directions
        directionsDisplay.setMap(map);
        $("#directionsPanel").empty();

        directionsDisplay.setPanel(document.getElementById("directionsPanel"));

        var request = {
            origin: origin,
            destination: destination,
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
            else{
                $("#map-canvas").html("an error occurred: " + status);
            }
        });
    }

    $( "#eventEdit" ).on( "pagebeforeshow", function() {
        //Clear invitedListView and Display invited people for the selectedEvent
        var $eventInvitedPeople = $( "#eventInvitedPeople").empty();
        $eventInvitedPeople.css("display", "block");
        $( "#contactsListView").css("display", "none");

        var selectedEvent = agenda42.selections.selectedEvent;
        if(selectedEvent !== undefined){
            $.each(selectedEvent.invited,function(){
                var contact = $( "
" + this.firstName + " " + this.lastName + "
" );
                $eventInvitedPeople.append(contact);
            });
            $eventInvitedPeople.listview("refresh");
        }
    });

    $( "#eventEdit" ).on( "pageinit", function() {
        //Init the click handler on event image
        $( "#eventImage" ).on( "tap" ,function(){
            $( "#eventImagePanel" ).panel( "open" );
        });

        //Init the click handler on selectPictureButton
        $( "#selectPictureButton" ).on( "tap", function(){
            //browse image directory
            alert ("Unsupported feature");
        });
        //Init the click handler on TakeNewPictureButton
        $( "#takeNewPictureButton" ).on( "tap", function(){
            //open photo Task
            if(navigator.camera !== undefined){
                navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
                    destinationType: Camera.DestinationType.FILE_URI });
            }
            else {
                alert ("Unsupported feature on this platform");
            }
        });
        function onSuccess(imageURI) {
            $( "#eventImage" ).attr("src", imageURI);
        }
        function onFail(message) {
            alert( 'Failed because: ' + message);
        }

        //Setting up the navigationPage with directions
        $( "#directionsMap" ).on( "pagebeforeshow", function(){
            //Get geolocation info
            var lat;
            var lng;
            //success callback
            var onSuccess = function(position) {
                lat = position.coords.latitude;
                lng = position.coords.longitude;
                displayMap(lat, lng, $( "#eventPlace").val());
            };
            // onError Callback receives a PositionError object
            function onError(error) {
                alert('code: '    + error.code    + '\n' +
                    'message: ' + error.message + '\n');
            }
            navigator.geolocation.getCurrentPosition(onSuccess, onError);
        });
    });

})();<|endoftext|>


<commit_before>---
---
var sponsorOverride = {
  '41853-ergodox-ez': {
    url: 'http://www.ergodox-ez.com',
    frontImageUrl: '/images/sponsors/ergodox-ez-logo.png'
  },
  '37206-ganwell': {
    url: 'http://ganwell.github.io/neovim.html',
    frontImageUrl: '/images/sponsors/ganwell.png',
  },
  '32537-hautelook': {
    url: 'http://hautelook.github.io/',
    frontImageUrl: '/images/sponsors/hautelook-logo.png',
  },
  '32681-namely-labs-namelyhr-namely-com': {
    url: 'http://www.namely.com/',
    frontImageUrl: '/images/sponsors/Namely_logo.jpg',
  },
  '39969-blumenversand': {
    url: 'https://blumenversender.com',
  },
  '34279-pygeek': {
    url: 'http://pygeek.com',
  },
  '34942-madis-nomme': {
    url: 'https://mad.is',
    name: 'Madis Nõmme'
  },
  '347-stefanpenner': {
    url: 'http://iamstef.net/',
  },
  '32451-twokul': {
    url: 'http://twokul.io',
  },
  '26545-kvannotten': {
    url: 'https://kristof.io',
  },
  '32345-jtinsky': {
    url: 'http://rutherstone.net/wp/',
  },
  '32362-vagmi': {
    url: 'http://coderwall.com/vagmi',
  },
  '23966-wbinnssmith': {
    url: 'http://wbinnssmith.com',
  },
  '30557-nemith': {
    url: 'http://inetpro.org',
  },
  '32395-apskim': {
    url: 'http://alexpolozov.com',
  },
  '24658-ndj': {
    url: 'dejonghenico.be',
  },
  '24164-mikl': {
    url: 'http://mikkel.hoegh.org/',
  },
  '32439-lsocrate': {
    url: 'http://www.socrate.com.br/',
  },
  '23889-dphase': {
    url: 'http://dphase.net',
  },
  '20492-victorbjelkholm': {
    url: 'http://twitter.com/VictorBjelkholm',
  },
  '24103-demizer': {
    url: 'www.demizerone.com',
  },
  '30137-ianks': {
    url: 'http://ianks.com',
  },
  '32359-jwhear': {
    url: 'www.economicmodeling.com',
  },
  '32367-dhruvasagar': {
    url: 'http://dhruvasagar.com/',
  },
  '24566-bruno': {
    url: 'http://greenbackyard.net',
  },
  '24014-tarrant': {
    url: 'http://daemonomicon.com',
  },
  '32394-tim': {
    url: 'http://tfletcher.com/',
  },
  '24354-wezm': {
    url: 'http://www.wezm.net/',
  },
  '32398-dshills': {
    url: 'http://dsgeek.blogspot.com/',
  },
  '32399-bwells': {
    url: 'www.altalang.com',
  },
  '32427-okaythree': {
    url: 'http://okaythree.com',
  },
  '26081-eglimi': {
    url: 'http://wisol.ch',
  },
  '32480-igort': {
    url: 'http://terzicigor.com/',
  },
  '24120-xvilka': {
    url: 'http://www.xvilka.me/',
  },
  '24042-macat': {
    url: 'https://twitter.com/macat',
  },
  '24386-drodger': {
    url: 'devslant.com',
  },
  '32584-zefei': {
    url: 'http://zef.io/',
  },
  '26581-gotgenes': {
    url: 'http://www.gotgenes.com/',
  },
  '25130-jwoudenberg': {
    url: 'http://jasperwoudenberg.com',
  },
  '32617-musically-ut': {
    url: 'http://musicallyut.in',
  },
  '32629-jhchabran': {
    url: 'http://jhchabran.com',
  },
  '32644-tchak': {
    url: 'http://capitainetrain.com',
  },
  '23874-leon-barrett': {
    url: 'http://leon.barrettnexus.com/',
  },
  '24543-jamesaoverton': {
    url: 'http://james.overton.ca',
  },
  '24499-jochen': {
    url: 'http://www.zerties.org',
  },
  '24721-tmandry': {
    url: 'https://www.linkedin.com/profile/view?id=79377885',
  },
  '25052-jwhitley': {
    url: 'http://bangpath.org/',
  },
  '33151-m42e': {
    url: 'https://bilger.info',
  },
  '32833-velrok': {
    url: 'velrok.github.io',
  },
  '32311-rach': {
    url: 'http://lostpropertyhq.com',
  },
  '20347-derickbailey': {
    url: 'http://derickbailey.com',
  },
  '17979-thejspr': {
    url: 'https://thejspr.com',
  },
  '32315-jthomas': {
    url: 'http://jamesthom.as',
  },
  '32317-mikker': {
    url: 'http://mikker.github.io',
  },
  '27722-dictvm': {
    url: 'https://blog.dictvm.org',
  },
  '22105-brunohenrique': {
    url: 'http://garulab.com/',
  },
  '24693-xsb': {
    url: 'http://xavisb.com',
  },
  '24401-dirkr': {
    url: 'http://niebegeg.net',
  },
  '32328-skattyadz': {
    url: 'imakesh.it',
  },
  '29586-davidosomething': {
    url: 'http://davidosomething.com/',
  },
  '32332-kennykaye': {
    url: 'http://kaye.us',
  },
  '32334-lerrua': {
    url: 'http://www.lerrua.com',
  },
  '24125-beloglazov': {
    url: 'http://beloglazov.info',
  },
  '32340-rillian': {
    url: 'http://advogato.org/person/rillian',
  },
  '28042-justinnhli': {
    url: 'http://justinnhli.com/',
  },
  '23870-fortes': {
    url: 'http://www.fortes.com/',
  },
  '32342-badeip': {
    url: 'https://www.twitter.com/badeip',
  },
  '32348-udp': {
    url: 'fieryclock.com',
  },
  '32352-adambiggs': {
    url: 'lightmaker.com',
  },
  '24970-hallettj': {
    url: 'http://sitr.us/',
  },
  '32363-apenney': {
    url: 'http://www.ntoggle.com',
  },
  '24148-alxndr': {
    url: 'http://eleven-twelve.net',
  },
  '24338-adri': {
    url: 'http://adrian-philipp.com',
  },
  '27129-pipeep': {
    url: 'http://benjam.info/',
  },
  '24937-bilalq': {
    url: 'http://bilalquadri.com',
  },
  '32381-kkuchta': {
    url: 'http://www.kevinkuchta.com',
  },
  '23998-rolisz': {
    url: 'https://rolisz.ro',
  },
  '32383-objectivetruth': {
    url: 'http://www.objectivetruth.ca',
  },
  '32388-norcalli': {
    url: 'norcalli.com',
  },
  '23915-joebadmo': {
    url: 'https://joe.xoxomoon.com',
  },
  '32389-faun': {
    url: 'http://www.faun.me',
  },
  '32403-stanimir-mladenov': {
    url: 'www.zoneprojects.com',
  },
  '32404-phlip9': {
    url: 'phlip9.com',
  },
  '24003-kopischke': {
    url: 'http://martin.kopischke.net',
  },
  '32417-azp': {
    url: 'http://volatileint.blogspot.com',
  },
  '32385-actionshrimp': {
    url: 'www.actionshrimp.com',
  },
  '18449-brainopia': {
    url: 'http://twitter.com/brainopia',
  },
  '32432-davidlowryduda': {
    url: 'http://davidlowryduda.com',
  },
  '24062-grahams': {
    url: 'http://sean-graham.com/',
  },
  '31425-bertocq': {
    url: 'http://www.bertocq.es',
  },
  '24163-linduxed': {
    url: 'http://www.linduxed.se',
  },
  '20659-jakesjews': {
    url: 'http://www.immersiveapplications.com',
  },
  '32445-joesfer': {
    url: 'http://www.joesfer.com',
  },
  '32415-p8952': {
    url: 'https://p8952.info',
  },
  '24655-tejo': {
    url: 'http://www.parmi.it',
  },
  '32477-neh': {
    url: 'http://nathanhowell.net',
  },
  '32479-topaxi': {
    url: 'http://topaxi.ch/',
  },
  '30935-danthecoloradan': {
    url: 'http://www.blazingaddles.com',
  },
  '32521-gypsydave5': {
    url: 'http://gypsydave5.com',
  },
  '25643-seebi': {
    url: 'http://sebastian.tramp.name',
  },
  '22048-ugtastic': {
    url: 'http://www.ugtastic.com',
  },
  '32550-luctus': {
    url: 'http://dailytics.com',
  },
  '23866-jimhester': {
    url: 'http://www.jimhester.com',
  },
  '32554-mmacia': {
    url: 'http://codeup.net',
  },
  '26466-jbuedel': {
    url: 'landofjosh.com',
  },
  '24835-henry4k': {
    url: 'henry4k.de',
  },
  '24318-jherdman': {
    url: 'http://jherdman.ca',
  },
  '24713-dsummersl': {
    url: 'viming.blogspot.com',
  },
  '25207-huftis': {
    url: 'http://huftis.org/',
  },
  '32575-palexander': {
    url: 'http://bioportal.bioontology.org',
  },
  '23994-dpc': {
    url: 'http://dpc.pw',
  },
  '31875-zardus': {
    url: 'http://blog.yancomm.net',
  },
  '21537-padde': {
    url: 'http://patrickoscity.de',
  },
  '32594-jaredmcateer': {
    url: 'jaredmcateer.com',
  },
  '26030-lovek323': {
    url: 'http://oconal.id.au/',
  },
  '32597-bugeats': {
    url: 'http://discoautomatic.com/',
  },
  '24780-lightningdb': {
    url: 'http://davidbolton.net',
  },
  '32622-dev0x': {
    url: 'http://dev0x.com',
  },
  '29935-benjohnson': {
    url: 'http://benjohnson.ca',
  },
  '32668-greyblake': {
    url: 'http://greyblake.com',
  },
  '31218-mstyles': {
    url: 'http://mstyles.github.io',
  },
  '32678-krampstudio': {
    url: 'http://krampstudio.com',
  },
  '32749-whabash090': {
    url: 'blog.whabash.com',
  },
  '32764-lexun': {
    url: 'https://plus.google.com/+LukeBarbuto/posts',
  },
  '32776-jcamp748': {
    url: 'http://www.jordancamp.net',
  },
  '32818-jordwest': {
    url: 'http://west.io/',
  },
  '18647-s0undt3ch': {
    url: 'https://github.com/s0undt3ch'
  },
  '25127-peter-edge': {
    url: 'https://github.com/peter-edge'
  },
  '20486-beau': {
    url: 'https://beaugunderson.com/'
  },
  '25255-mmikowski': {
    url: 'http://michaelmikowski.com'
  },
  '47915-wojtek-kruszewski': {
    url: 'http://www.kruszewski.com'
  }
};
<commit_msg>Update sponsors-override.js (#150)<commit_after>---
---
var sponsorOverride = {
  '41853-ergodox-ez': {
    url: 'http://www.ergodox-ez.com',
    frontImageUrl: '/images/sponsors/ergodox-ez-logo.png'
  },
  '37206-ganwell': {
    url: 'http://ganwell.github.io/neovim.html',
    frontImageUrl: '/images/sponsors/ganwell.png',
  },
  '32537-hautelook': {
    url: 'http://hautelook.github.io/',
    frontImageUrl: '/images/sponsors/hautelook-logo.png',
  },
  '32681-namely-labs-namelyhr-namely-com': {
    url: 'http://www.namely.com/',
    frontImageUrl: '/images/sponsors/Namely_logo.jpg',
  },
  '39969-blumenversand': {
    url: 'https://blumenversender.com',
  },
  '34279-pygeek': {
    url: 'http://pygeek.com',
  },
  '34942-madis-nomme': {
    url: 'https://mad.is',
    name: 'Madis Nõmme'
  },
  '347-stefanpenner': {
    url: 'http://iamstef.net/',
  },
  '32451-twokul': {
    url: 'http://twokul.io',
  },
  '26545-kvannotten': {
    url: 'https://kristof.io',
  },
  '32345-jtinsky': {
    url: 'http://rutherstone.net/wp/',
  },
  '32362-vagmi': {
    url: 'http://coderwall.com/vagmi',
  },
  '23966-wbinnssmith': {
    url: 'http://wbinnssmith.com',
  },
  '30557-nemith': {
    url: 'http://inetpro.org',
  },
  '32395-apskim': {
    url: 'http://alexpolozov.com',
  },
  '24658-ndj': {
    url: 'dejonghenico.be',
  },
  '24164-mikl': {
    url: 'http://mikkel.hoegh.org/',
  },
  '32439-lsocrate': {
    url: 'http://www.socrate.com.br/',
  },
  '23889-dphase': {
    url: 'http://dphase.net',
  },
  '20492-victorbjelkholm': {
    url: 'http://twitter.com/VictorBjelkholm',
  },
  '24103-demizer': {
    url: 'www.demizerone.com',
  },
  '30137-ianks': {
    url: 'http://ianks.com',
  },
  '32359-jwhear': {
    url: 'www.economicmodeling.com',
  },
  '32367-dhruvasagar': {
    url: 'http://dhruvasagar.com/',
  },
  '24566-bruno': {
    url: 'http://greenbackyard.net',
  },
  '24014-tarrant': {
    url: 'http://daemonomicon.com',
  },
  '32394-tim': {
    url: 'http://tfletcher.com/',
  },
  '24354-wezm': {
    url: 'http://www.wezm.net/',
  },
  '32398-dshills': {
    url: 'http://dsgeek.blogspot.com/',
  },
  '32399-bwells': {
    url: 'www.altalang.com',
  },
  '32427-okaythree': {
    url: 'http://okaythree.com',
  },
  '26081-eglimi': {
    url: 'http://wisol.ch',
  },
  '32480-igort': {
    url: 'http://terzicigor.com/',
  },
  '24120-xvilka': {
    url: 'http://www.xvilka.me/',
  },
  '24042-macat': {
    url: 'https://twitter.com/macat',
  },
  '24386-drodger': {
    url: 'devslant.com',
  },
  '32584-zefei': {
    url: 'http://zef.io/',
  },
  '26581-gotgenes': {
    url: 'http://www.gotgenes.com/',
  },
  '25130-jwoudenberg': {
    url: 'http://jasperwoudenberg.com',
  },
  '32617-musically-ut': {
    url: 'http://musicallyut.in',
  },
  '32629-jhchabran': {
    url: 'http://jhchabran.com',
  },
  '32644-tchak': {
    url: 'http://capitainetrain.com',
  },
  '23874-leon-barrett': {
    url: 'http://leon.barrettnexus.com/',
  },
  '24543-jamesaoverton': {
    url: 'http://james.overton.ca',
  },
  '24499-jochen': {
    url: 'http://www.zerties.org',
  },
  '24721-tmandry': {
    url: 'https://www.linkedin.com/profile/view?id=79377885',
  },
  '25052-jwhitley': {
    url: 'http://bangpath.org/',
  },
  '33151-m42e': {
    url: 'https://bilger.info',
  },
  '32833-velrok': {
    url: 'velrok.github.io',
  },
  '32311-rach': {
    url: 'http://lostpropertyhq.com',
  },
  '20347-derickbailey': {
    url: 'http://derickbailey.com',
  },
  '17979-thejspr': {
    url: 'https://thejspr.com',
  },
  '32315-jthomas': {
    url: 'http://jamesthom.as',
  },
  '32317-mikker': {
    url: 'http://mikker.github.io',
  },
  '27722-dictvm': {
    url: 'https://blog.dictvm.org',
  },
  '22105-brunohenrique': {
    url: 'http://garulab.com/',
  },
  '24693-xsb': {
    url: 'http://xavisb.com',
  },
  '24401-dirkr': {
    url: 'http://niebegeg.net',
  },
  '32328-skattyadz': {
    url: 'imakesh.it',
  },
  '29586-davidosomething': {
    url: 'http://davidosomething.com/',
  },
  '32332-kennykaye': {
    url: 'http://kaye.us',
  },
  '32334-lerrua': {
    url: 'http://www.lerrua.com',
  },
  '24125-beloglazov': {
    url: 'http://beloglazov.info',
  },
  '32340-rillian': {
    url: 'http://advogato.org/person/rillian',
  },
  '28042-justinnhli': {
    url: 'http://justinnhli.com/',
  },
  '23870-fortes': {
    url: 'http://www.fortes.com/',
  },
  '32342-badeip': {
    url: 'https://www.twitter.com/badeip',
  },
  '32348-udp': {
    url: 'fieryclock.com',
  },
  '32352-adambiggs': {
    url: 'lightmaker.com',
  },
  '24970-hallettj': {
    url: 'http://sitr.us/',
  },
  '32363-apenney': {
    url: 'http://www.ntoggle.com',
  },
  '24148-alxndr': {
    url: 'http://eleven-twelve.net',
  },
  '24338-adri': {
    url: 'http://adrian-philipp.com',
  },
  '27129-pipeep': {
    url: 'http://benjam.info/',
  },
  '24937-bilalq': {
    url: 'http://bilalquadri.com',
  },
  '32381-kkuchta': {
    url: 'http://www.kevinkuchta.com',
  },
  '23998-rolisz': {
    url: 'https://rolisz.ro',
  },
  '32383-objectivetruth': {
    url: 'http://www.objectivetruth.ca',
  },
  '32388-norcalli': {
    url: 'norcalli.com',
  },
  '23915-joebadmo': {
    url: 'https://joe.xoxomoon.com',
  },
  '32389-faun': {
    url: 'http://www.faun.me',
  },
  '32403-stanimir-mladenov': {
    url: 'www.zoneprojects.com',
  },
  '32404-phlip9': {
    url: 'phlip9.com',
  },
  '24003-kopischke': {
    url: 'http://martin.kopischke.net',
  },
  '32417-azp': {
    url: 'http://volatileint.blogspot.com',
  },
  '32385-actionshrimp': {
    url: 'www.actionshrimp.com',
  },
  '18449-brainopia': {
    url: 'http://twitter.com/brainopia',
  },
  '32432-davidlowryduda': {
    url: 'http://davidlowryduda.com',
  },
  '24062-grahams': {
    url: 'http://sean-graham.com/',
  },
  '31425-bertocq': {
    url: 'http://www.bertocq.es',
  },
  '24163-linduxed': {
    url: 'http://www.linduxed.se',
  },
  '20659-jakesjews': {
    url: 'http://www.immersiveapplications.com',
  },
  '32445-joesfer': {
    url: 'http://www.joesfer.com',
  },
  '32415-p8952': {
    url: 'https://p8952.info',
  },
  '24655-tejo': {
    url: 'http://www.parmi.it',
  },
  '32477-neh': {
    url: 'http://nathanhowell.net',
  },
  '32479-topaxi': {
    url: 'http://topaxi.ch/',
  },
  '30935-danthecoloradan': {
    url: 'http://www.blazingaddles.com',
  },
  '32521-gypsydave5': {
    url: 'http://gypsydave5.com',
  },
  '25643-seebi': {
    url: 'http://sebastian.tramp.name',
  },
  '22048-ugtastic': {
    url: 'http://www.ugtastic.com',
  },
  '32550-luctus': {
    url: 'http://dailytics.com',
  },
  '23866-jimhester': {
    url: 'http://www.jimhester.com',
  },
  '32554-mmacia': {
    url: 'http://codeup.net',
  },
  '26466-jbuedel': {
    url: 'landofjosh.com',
  },
  '24835-henry4k': {
    url: 'henry4k.de',
  },
  '24318-jherdman': {
    url: 'http://jherdman.ca',
  },
  '24713-dsummersl': {
    url: 'viming.blogspot.com',
  },
  '25207-huftis': {
    url: 'http://huftis.org/',
  },
  '32575-palexander': {
    url: 'http://bioportal.bioontology.org',
  },
  '23994-dpc': {
    url: 'http://dpc.pw',
  },
  '31875-zardus': {
    url: 'http://blog.yancomm.net',
  },
  '21537-padde': {
    url: 'http://patrickoscity.de',
  },
  '32594-jaredmcateer': {
    url: 'jaredmcateer.com',
  },
  '26030-lovek323': {
    url: 'http://oconal.id.au/',
  },
  '32597-bugeats': {
    url: 'http://discoautomatic.com/',
  },
  '24780-lightningdb': {
    url: 'http://davidbolton.net',
  },
  '32622-dev0x': {
    url: 'http://dev0x.com',
  },
  '29935-benjohnson': {
    url: 'http://benjohnson.ca',
  },
  '32668-greyblake': {
    url: 'http://greyblake.com',
  },
  '31218-mstyles': {
    url: 'http://mstyles.github.io',
  },
  '32678-krampstudio': {
    url: 'http://krampstudio.com',
  },
  '32749-whabash090': {
    url: 'blog.whabash.com',
  },
  '32764-lexun': {
    url: 'https://plus.google.com/+LukeBarbuto/posts',
  },
  '32776-jcamp748': {
    url: 'http://www.jordancamp.net',
  },
  '32818-jordwest': {
    url: 'http://west.io/',
  },
  '18647-s0undt3ch': {
    url: 'https://github.com/s0undt3ch'
  },
  '25127-peter-edge': {
    url: 'https://github.com/peter-edge'
  },
  '20486-beau': {
    url: 'https://beaugunderson.com/'
  },
  '25255-mmikowski': {
    url: 'http://michaelmikowski.com'
  },
  '47915-wojtek-kruszewski': {
    url: 'http://www.kruszewski.com'
  },
  '49943-sleekwristbands-com': {
    url: 'https://www.sleekwristbands.com'
  }
};
<|endoftext|>


<commit_before>/**
 * this javascript is for the admin application
 */
var mainApp = angular.module("adminApp", ["ngRoute"]);

        /* ng routing configuration */
        mainApp.config(['$routeProvider', function($routeProvider) {
            $routeProvider.

            when('/stock', {
                templateUrl: 'stockAdmin.html',
                controller: 'stockAdminCtrl'
            }).

            when('/transaction', {
            	templateUrl: 'transactionAdmin.html',
            	controller: 'transactionAdminCtrl'
            }).

            when('/history', {
            	templateUrl: 'historyAdmin.html',
            	controller: 'historyAdminCtrl'
            }).

            otherwise({
                redirectTo: '/'
            });
        }]);

        mainApp.controller("adminCtrl", function($scope, $http, $interval){

        	$scope.stockPool = [];
        	$scope.active = [];
        	$scope.newStock = {};
        	var updateStock = function(){
        		$http.get("admin/allStock")
        		.success(function(data) {
        			console.log(data);
        			$scope.stockPool = data;
        		}).error(function(data) {
        			console.log("AJAX ERROR");
        		});
        	}

        	updateStock();
        	$interval(updateStock, 3000);

        	$scope.addNewStock = function(){
        		console.log("click add new stock into stock pool");
        		console.log("new stock is:", $scope.newStock);
        		$http({
        			url: "admin/addStock/"+$scope.newStock.symbol+"/"+$scope.newStock.stockDesc,
        			method: "GET"
        		}).success(function(data){
        			$scope.stockPool.push($scope.newStock);
        			$scope.newStock = {};
        		});
        	}

        });

        mainApp.controller("transactionCtrl", function($scope, $http, $interval){

        	$scope.pendingTran = [];
        	$scope.committedTran = [];
        	$scope.active = ["checked", null]

        	/* Show Pending Transaction Table */
        	var showPendingTran = function(){
        		$http.get("admin/allPendingHistory")
        		.success(function(data){
        			console.log(data);
        			$scope.pendingTran = data;
        		}).error(function(data){
        			console.log("Ajax Error");
        		});
        	};
        	showPendingTran();
        	$interval(showPendingTran, 3000);

        	/* Show Committed Transaction Table */
        	var showCommittedTran = function(){
        		$http.get("admin/allCommittedHistory")
        		.success(function(data){
        			console.log(data);
        			$scope.committedTran = data;
        		}).error(function(data){
        			console.log("Ajax Error");
        		});
        	};
        	showCommittedTran();
        	$interval(showCommittedTran, 3000);

        	/* Submit a pending Transaction */
        	$scope.submitPending = function(index){
        		console.log("submit pending, index: ", index);
        		$http({
        			url: "admin/commitTran/"+index,
        			method: "GET"
        		}).success(function(data){
        			$scope.pendingTran.splice(index, 1);
        		}).error(function(data){
        			console.log("Ajax Error");
        		});
        	}

        	/* Drop a pending Transaction */
        	$scope.dropPending = function(index){
        		console.log("Dropping pending, index: ", index);
        		$http({
        			url: "admin/dropTran/"+index,
        			method: "GET"
        		}).success(function(data){
        			$scope.pendingTran.splice(index, 1);
        		})
        	}
        });

        <commit_msg>convert unix time into datetime.<commit_after>/**
 * this javascript is for the admin application
 */
var mainApp = angular.module("adminApp", ["ngRoute"]);

        /* ng routing configuration */
        mainApp.config(['$routeProvider', function($routeProvider) {
            $routeProvider.

            when('/stock', {
                templateUrl: 'stockAdmin.html',
                controller: 'stockAdminCtrl'
            }).

            when('/transaction', {
            	templateUrl: 'transactionAdmin.html',
            	controller: 'transactionAdminCtrl'
            }).

            when('/history', {
            	templateUrl: 'historyAdmin.html',
            	controller: 'historyAdminCtrl'
            }).

            otherwise({
                redirectTo: '/'
            });
        }]);

        mainApp.controller("adminCtrl", function($scope, $http, $interval){

        	$scope.stockPool = [];
        	$scope.active = [];
        	$scope.newStock = {};
        	var updateStock = function(){
        		$http.get("admin/allStock")
        		.success(function(data) {
        			console.log(data);
        			$scope.stockPool = data;
        		}).error(function(data) {
        			console.log("AJAX ERROR");
        		});
        	}

        	updateStock();
        	$interval(updateStock, 3000);

        	$scope.addNewStock = function(){
        		console.log("click add new stock into stock pool");
        		console.log("new stock is:", $scope.newStock);
        		$http({
        			url: "admin/addStock/"+$scope.newStock.symbol+"/"+$scope.newStock.stockDesc,
        			method: "GET"
        		}).success(function(data){
        			$scope.stockPool.push($scope.newStock);
        			$scope.newStock = {};
        		});
        	}

        });

        mainApp.controller("transactionCtrl", function($scope, $http, $interval){

        	$scope.pendingTran = [];
        	$scope.committedTran = [];

        	/* formate unix time into date time */
        	var format = function(old){
        		var d = new Date(old);
        		var formattedDate = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();
        		var hours = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
        		var minutes = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
        		var formattedTime = hours + ":" + minutes;

        		formattedDate = formattedDate + " " + formattedTime;
        		console.log(formattedDate);
        		return formattedDate;
        	}

        	/* Show Pending Transaction Table */
        	var showPendingTran = function(){
        		$http.get("admin/allPendingHistory")
        		.success(function(data){
        			console.log(data);
        			for(var i = 0; i < data.length; i++){
        				data[i].date = format(data[i].date);
        			}
        			$scope.pendingTran = data;
        		}).error(function(data){
        			console.log("Ajax Error");
        		});
        	};
        	showPendingTran();
        	$interval(showPendingTran, 3000);

        	/* Show Committed Transaction Table */
        	var showCommittedTran = function(){
        		$http.get("admin/allCommittedHistory")
        		.success(function(data){
        			console.log(data);
        			$scope.committedTran = data;
        		}).error(function(data){
        			console.log("Ajax Error");
        		});
        	};
        	showCommittedTran();
        	$interval(showCommittedTran, 3000);

        	/* Submit a pending Transaction */
        	$scope.submitPending = function(index){
        		console.log("submit pending, index: ", index);
        		$http({
        			url: "admin/commitTran/"+index,
        			method: "GET"
        		}).success(function(data){
        			$scope.pendingTran.splice(index, 1);
        		}).error(function(data){
        			console.log("Ajax Error");
        		});
        	}

        	/* Drop a pending Transaction */
        	$scope.dropPending = function(index){
        		console.log("Dropping pending, index: ", index);
        		$http({
        			url: "admin/dropTran/"+index,
        			method: "GET"
        		}).success(function(data){
        			$scope.pendingTran.splice(index, 1);
        		})
        	}
        });

        <|endoftext|>


<commit_before>// Tigra Calendar v5.2 (11/20/2011)
// http://www.softcomplex.com/products/tigra_calendar/
// License: Public Domain... You're welcome.

var cal_A_TCALTOKENS = [
	 // A full numeric representation of a year, 4 digits
	{'t': 'Y', 'r': '19\\d{2}|20\\d{2}', 'p': function (d_date, n_value) { d_date.setFullYear(Number(n_value)); return d_date; }, 'g': function (d_date) { var n_year = d_date.getFullYear(); return n_year; }},
	 // Numeric representation of a month, with leading zeros
	{'t': 'm', 'r': '0?[1-9]|1[0-2]', 'p': function (d_date, n_value) { d_date.setMonth(Number(n_value) - 1); return d_date; }, 'g': function (d_date) { var n_month = d_date.getMonth() + 1; return (n_month < 10 ? '0' : '') + n_month; }},
	 // Day of the month, 2 digits with leading zeros
	{'t': 'd', 'r': '0?[1-9]|[12][0-9]|3[01]', 'p': function (d_date, n_value) { d_date.setDate(Number(n_value)); if (d_date.getDate() != n_value) d_date.setDate(0); return d_date; }, 'g': function (d_date) { var n_date = d_date.getDate(); return (n_date < 10 ? '0' : '') + n_date; }},
	// Day of the month without leading zeros
	{'t': 'j', 'r': '0?[1-9]|[12][0-9]|3[01]', 'p': function (d_date, n_value) { d_date.setDate(Number(n_value)); if (d_date.getDate() != n_value) d_date.setDate(0); return d_date; }, 'g': function (d_date) { var n_date = d_date.getDate(); return n_date; }},
	// English ordinal suffix for the day of the month, 2 characters
	{'t': 'S', 'r': 'st|nd|rd|th', 'p': function (d_date, s_value) { return d_date; }, 'g': function (d_date) { n_date = d_date.getDate(); if (n_date % 10 == 1 && n_date != 11) return 'st'; if (n_date % 10 == 2 && n_date != 12) return 'nd'; if (n_date % 10 == 3 && n_date != 13) return 'rd'; return 'th'; }}
];

function cal_f_tcalResetTime (d_date) {
	d_date.setMilliseconds(0);
	d_date.setSeconds(0);
	d_date.setMinutes(0);
	d_date.setHours(12);
	return d_date;
}

function cal_f_tcalParseDate (s_date, s_format) {

	if (!s_date) return;

	if (typeof(window.cal_A_TCALTOKENS_IDX) === "undefined") {
		window.cal_A_TCALTOKENS_IDX = {};
		for (var n = 0; n < cal_A_TCALTOKENS.length; n++) cal_A_TCALTOKENS_IDX[cal_A_TCALTOKENS[n]['t']] = cal_A_TCALTOKENS[n];
	}

	var s_char, s_regexp = '^', a_tokens = {}, a_options, n_token = 0;
	for (var n = 0; n < s_format.length; n++) {
		s_char = s_format.charAt(n);
		if (cal_A_TCALTOKENS_IDX[s_char]) {
			a_tokens[s_char] = ++n_token;
			s_regexp += '(' + cal_A_TCALTOKENS_IDX[s_char]['r'] + ')';
		}
		else if (s_char == ' ')
			s_regexp += '\\s';
		else
			s_regexp += (s_char.match(/[\w\d]/) ? '' : '\\') + s_char;
	}
	var r_date = new RegExp(s_regexp + '$');
	if (!s_date.match(r_date)) return;

	var s_val, d_date = cal_f_tcalResetTime(new Date());
	d_date.setDate(1);

	for (n = 0; n < cal_A_TCALTOKENS.length; n++) {
		s_char = cal_A_TCALTOKENS[n]['t'];
		if (!a_tokens[s_char])
			continue;
		s_val = RegExp['$' + a_tokens[s_char]];
		d_date = cal_A_TCALTOKENS[n]['p'](d_date, s_val);
	}

	return d_date;
}

function cal_f_tcalGenerateDate (d_date, s_format) {

	if (typeof(window.cal_A_TCALTOKENS_IDX) === "undefined") {
		window.cal_A_TCALTOKENS_IDX = {};
		for (var n = 0; n < cal_A_TCALTOKENS.length; n++) cal_A_TCALTOKENS_IDX[cal_A_TCALTOKENS[n]['t']] = cal_A_TCALTOKENS[n];
	}

	var s_char, s_date = '';
	for (var n = 0; n < s_format.length; n++) {
		s_char = s_format.charAt(n);
		s_date += cal_A_TCALTOKENS_IDX[s_char] ? cal_A_TCALTOKENS_IDX[s_char]['g'](d_date) : s_char;
	}
	return s_date;
}

/*

Copyright (C) 2014 - Gareth Edwards / Rapid Information Systems

gareth.edwards@rapid-is.co.uk

This file is part of the Rapid Application Platform

Rapid is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. The terms require you to include
the original copyright, and the license notice in all redistributions.

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 General Public License for more details.

You should have received a copy of the GNU General Public License
in a file named "COPYING".  If not, see <http://www.gnu.org/licenses/>.

 */

var _calendarWeeks = ["Su","Mo","Tu","We","Th","Fr","Sa"];
var _calendarMonths = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var _calendarMonthDays = [31,28,31,30,31,30,31,31,30,31,30,31];

function calendarGetMonthDays(year, month) {
	var monthDays = _calendarMonthDays[month];
	// if feb in normal leap year but not divisble by 100 exluding divisible by 400
	if (month == 1 && year % 4 == 0 && !(year % 100 == 0 && year % 400 != 0)) monthDays++;
	return monthDays;
}

function calendarSetDate(id, date) {
	var calendar = $("#" + id);
	if (date) {
		var month = date.getMonth() + 1;
		if (month.length == 1) month = "0" + month;
		var day = date.getDate();
		if (day.length == 1) day = "0" + day;
		calendar.attr("data-date",date.getFullYear() + "-" + month + "-" + day);
	} else {
		calendar.removeAttr("data-date");
	}
}

function calendarUpdate(id) {

	var calendar = $("#" + id);

	var year = calendar.attr("data-year");
	var month = calendar.attr("data-month");
	var date = new Date(calendar.attr("data-date"));
	var today = new Date();

	var monthStartDate = new Date(year, month, 1);
	var monthDays = calendarGetMonthDays(year, month);

	var header = calendar.find("div.calendarHeader");
	var label = header.find(".calendarLabel");
	label.html(_calendarMonths[month] + " " + year);

	var table = calendar.find("table.calendarTable");
	var daysBody = table.find("tbody");
	var days = daysBody.find("td");
	days.removeClass("calendarToday").removeClass("calendarSelectedDay");

	var day = 1 - monthStartDate.getDay();

	days.each(function() {
		var dayCell = $(this);
		if (day > 0 && day <= monthDays) {
			dayCell.html(day).removeClass("calendarNonDay").addClass("calendarDay");
			if (day == today.getDate() && month == today.getMonth() && year == today.getFullYear()) dayCell.addClass("calendarToday");
			if (day == date.getDate() && month == date.getMonth() && year == date.getFullYear()) dayCell.addClass("calendarSelectedDay");
		} else {
			dayCell.html("").removeClass("calendarDay").addClass("calendarNonDay");
		}
		day++;
	});

	var rows = daysBody.find("tr").filter( function(idx) { return idx > 0; });
	rows.each(function() {
		var row = $(this);
		if (row.children().first().html()) {
			row.show();
		} else {
			row.hide();
		}
	});

}

function calendarMove(from, type, amount) {
	var calendar = $(from).closest("div.calendar");
	var id = calendar.attr("id");
	var year = calendar.attr("data-year")*1;
	var month = calendar.attr("data-month")*1;
	switch (type) {
	case ("y") :
		calendar.attr("data-year", year + amount);
		break;
	case ("m") :
		month += amount;
		if (month < 0) {
			month = 11;
			year -= 1;
		}
		if (month > 11) {
			month = 0;
			year += 1;
		}
		calendar.attr("data-year", year);
		calendar.attr("data-month", month);
		break;
	}
	calendarUpdate(id);
}

function calendarSelectDay(from) {
	var dayCell = $(from);
	var calendar = dayCell.closest("div.calendar");
	var id = calendar.attr("id");
	var year = calendar.attr("data-year")*1;
	var month = calendar.attr("data-month")*1;
	var day = dayCell.html();
	var date = new Date(year, month, day);
	calendarSetDate(id, date);
	calendarUpdate(id);
	if (dayCell.hasClass("calendarDay") && window["Event_selectDay_" + id]) window["Event_selectDay_" + id]($.Event('selectDay'));
}

function calendarInit(id, details) {

	var date = new Date();
	if (details.date) date = new Date(details.date);

	calendarSetDate(id, date);

	var calendar = $("#" + id);
	calendar.attr("data-year", date.getFullYear());
	calendar.attr("data-month", date.getMonth());

	var table = calendar.find("table.calendarTable");

	var weeks = table.find("thead");
	var weeksHtml = "
";
	for (var i = 0; i < 7; i++) {
		weeksHtml += "" + _calendarWeeks[i] + "	";
	}
	weeksHtml += "
";
	weeks.html(weeksHtml);

	var days = table.find("tbody");
	var daysHtml = "";
	for (var i = 0; i < 5; i++) {
		daysHtml += "
";
		for (var j = 0; j < 7; j++) {
			daysHtml += "	";
		}
		daysHtml += "
";
	}
	days.html(daysHtml);

	calendarUpdate(id);
}<commit_msg>IE fix for dates<commit_after>// Tigra Calendar v5.2 (11/20/2011)
// http://www.softcomplex.com/products/tigra_calendar/
// License: Public Domain... You're welcome.

var cal_A_TCALTOKENS = [
	 // A full numeric representation of a year, 4 digits
	{'t': 'Y', 'r': '19\\d{2}|20\\d{2}', 'p': function (d_date, n_value) { d_date.setFullYear(Number(n_value)); return d_date; }, 'g': function (d_date) { var n_year = d_date.getFullYear(); return n_year; }},
	 // Numeric representation of a month, with leading zeros
	{'t': 'm', 'r': '0?[1-9]|1[0-2]', 'p': function (d_date, n_value) { d_date.setMonth(Number(n_value) - 1); return d_date; }, 'g': function (d_date) { var n_month = d_date.getMonth() + 1; return (n_month < 10 ? '0' : '') + n_month; }},
	 // Day of the month, 2 digits with leading zeros
	{'t': 'd', 'r': '0?[1-9]|[12][0-9]|3[01]', 'p': function (d_date, n_value) { d_date.setDate(Number(n_value)); if (d_date.getDate() != n_value) d_date.setDate(0); return d_date; }, 'g': function (d_date) { var n_date = d_date.getDate(); return (n_date < 10 ? '0' : '') + n_date; }},
	// Day of the month without leading zeros
	{'t': 'j', 'r': '0?[1-9]|[12][0-9]|3[01]', 'p': function (d_date, n_value) { d_date.setDate(Number(n_value)); if (d_date.getDate() != n_value) d_date.setDate(0); return d_date; }, 'g': function (d_date) { var n_date = d_date.getDate(); return n_date; }},
	// English ordinal suffix for the day of the month, 2 characters
	{'t': 'S', 'r': 'st|nd|rd|th', 'p': function (d_date, s_value) { return d_date; }, 'g': function (d_date) { n_date = d_date.getDate(); if (n_date % 10 == 1 && n_date != 11) return 'st'; if (n_date % 10 == 2 && n_date != 12) return 'nd'; if (n_date % 10 == 3 && n_date != 13) return 'rd'; return 'th'; }}
];

function cal_f_tcalResetTime (d_date) {
	d_date.setMilliseconds(0);
	d_date.setSeconds(0);
	d_date.setMinutes(0);
	d_date.setHours(12);
	return d_date;
}

function cal_f_tcalParseDate (s_date, s_format) {

	if (!s_date) return;

	if (typeof(window.cal_A_TCALTOKENS_IDX) === "undefined") {
		window.cal_A_TCALTOKENS_IDX = {};
		for (var n = 0; n < cal_A_TCALTOKENS.length; n++) cal_A_TCALTOKENS_IDX[cal_A_TCALTOKENS[n]['t']] = cal_A_TCALTOKENS[n];
	}

	var s_char, s_regexp = '^', a_tokens = {}, a_options, n_token = 0;
	for (var n = 0; n < s_format.length; n++) {
		s_char = s_format.charAt(n);
		if (cal_A_TCALTOKENS_IDX[s_char]) {
			a_tokens[s_char] = ++n_token;
			s_regexp += '(' + cal_A_TCALTOKENS_IDX[s_char]['r'] + ')';
		}
		else if (s_char == ' ')
			s_regexp += '\\s';
		else
			s_regexp += (s_char.match(/[\w\d]/) ? '' : '\\') + s_char;
	}
	var r_date = new RegExp(s_regexp + '$');
	if (!s_date.match(r_date)) return;

	var s_val, d_date = cal_f_tcalResetTime(new Date());
	d_date.setDate(1);

	for (n = 0; n < cal_A_TCALTOKENS.length; n++) {
		s_char = cal_A_TCALTOKENS[n]['t'];
		if (!a_tokens[s_char])
			continue;
		s_val = RegExp['$' + a_tokens[s_char]];
		d_date = cal_A_TCALTOKENS[n]['p'](d_date, s_val);
	}

	return d_date;
}

function cal_f_tcalGenerateDate (d_date, s_format) {

	if (typeof(window.cal_A_TCALTOKENS_IDX) === "undefined") {
		window.cal_A_TCALTOKENS_IDX = {};
		for (var n = 0; n < cal_A_TCALTOKENS.length; n++) cal_A_TCALTOKENS_IDX[cal_A_TCALTOKENS[n]['t']] = cal_A_TCALTOKENS[n];
	}

	var s_char, s_date = '';
	for (var n = 0; n < s_format.length; n++) {
		s_char = s_format.charAt(n);
		s_date += cal_A_TCALTOKENS_IDX[s_char] ? cal_A_TCALTOKENS_IDX[s_char]['g'](d_date) : s_char;
	}
	return s_date;
}

/*

Copyright (C) 2014 - Gareth Edwards / Rapid Information Systems

gareth.edwards@rapid-is.co.uk

This file is part of the Rapid Application Platform

Rapid is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. The terms require you to include
the original copyright, and the license notice in all redistributions.

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 General Public License for more details.

You should have received a copy of the GNU General Public License
in a file named "COPYING".  If not, see <http://www.gnu.org/licenses/>.

 */

var _calendarWeeks = ["Su","Mo","Tu","We","Th","Fr","Sa"];
var _calendarMonths = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var _calendarMonthDays = [31,28,31,30,31,30,31,31,30,31,30,31];

function calendarGetMonthDays(year, month) {
	var monthDays = _calendarMonthDays[month];
	// if feb in normal leap year but not divisble by 100 exluding divisible by 400
	if (month == 1 && year % 4 == 0 && !(year % 100 == 0 && year % 400 != 0)) monthDays++;
	return monthDays;
}

function calendarSetDate(id, date) {
	var calendar = $("#" + id);
	if (date) {
		var month = date.getMonth() + 1;
		if (month < 10) month = "0" + month;
		var day = date.getDate();
		if (day < 10) day = "0" + day;
		calendar.attr("data-date",date.getFullYear() + "-" + month + "-" + day);
	} else {
		calendar.removeAttr("data-date");
	}
}

function calendarUpdate(id) {

	var calendar = $("#" + id);

	var year = calendar.attr("data-year");
	var month = calendar.attr("data-month");
	var date = new Date(calendar.attr("data-date"));
	var today = new Date();

	var monthStartDate = new Date(year, month, 1);
	var monthDays = calendarGetMonthDays(year, month);

	var header = calendar.find("div.calendarHeader");
	var label = header.find(".calendarLabel");
	label.html(_calendarMonths[month] + " " + year);

	var table = calendar.find("table.calendarTable");
	var daysBody = table.find("tbody");
	var days = daysBody.find("td");
	days.removeClass("calendarToday").removeClass("calendarSelectedDay");

	var day = 1 - monthStartDate.getDay();

	days.each(function() {
		var dayCell = $(this);
		if (day > 0 && day <= monthDays) {
			dayCell.html(day).removeClass("calendarNonDay").addClass("calendarDay");
			if (day == today.getDate() && month == today.getMonth() && year == today.getFullYear()) dayCell.addClass("calendarToday");
			if (day == date.getDate() && month == date.getMonth() && year == date.getFullYear()) dayCell.addClass("calendarSelectedDay");
		} else {
			dayCell.html("").removeClass("calendarDay").addClass("calendarNonDay");
		}
		day++;
	});

	var rows = daysBody.find("tr").filter( function(idx) { return idx > 0; });
	rows.each(function() {
		var row = $(this);
		if (row.children().first().html()) {
			row.show();
		} else {
			row.hide();
		}
	});

}

function calendarMove(from, type, amount) {
	var calendar = $(from).closest("div.calendar");
	var id = calendar.attr("id");
	var year = calendar.attr("data-year")*1;
	var month = calendar.attr("data-month")*1;
	switch (type) {
	case ("y") :
		calendar.attr("data-year", year + amount);
		break;
	case ("m") :
		month += amount;
		if (month < 0) {
			month = 11;
			year -= 1;
		}
		if (month > 11) {
			month = 0;
			year += 1;
		}
		calendar.attr("data-year", year);
		calendar.attr("data-month", month);
		break;
	}
	calendarUpdate(id);
}

function calendarSelectDay(from) {
	var dayCell = $(from);
	var calendar = dayCell.closest("div.calendar");
	var id = calendar.attr("id");
	var year = calendar.attr("data-year")*1;
	var month = calendar.attr("data-month")*1;
	var day = dayCell.html();
	var date = new Date(year, month, day);
	calendarSetDate(id, date);
	calendarUpdate(id);
	if (dayCell.hasClass("calendarDay") && window["Event_selectDay_" + id]) window["Event_selectDay_" + id]($.Event('selectDay'));
}

function calendarInit(id, details) {

	var date = new Date();
	if (details.date) date = new Date(details.date);

	calendarSetDate(id, date);

	var calendar = $("#" + id);
	calendar.attr("data-year", date.getFullYear());
	calendar.attr("data-month", date.getMonth());

	var table = calendar.find("table.calendarTable");

	var weeks = table.find("thead");
	var weeksHtml = "
";
	for (var i = 0; i < 7; i++) {
		weeksHtml += "" + _calendarWeeks[i] + "	";
	}
	weeksHtml += "
";
	weeks.html(weeksHtml);

	var days = table.find("tbody");
	var daysHtml = "";
	for (var i = 0; i < 5; i++) {
		daysHtml += "
";
		for (var j = 0; j < 7; j++) {
			daysHtml += "	";
		}
		daysHtml += "
";
	}
	days.html(daysHtml);

	calendarUpdate(id);
}<|endoftext|>


<commit_before>	describe('DynamicLoader', function () {

		var World = require('src/goo/entities/World');
		var TransformSystem = require('src/goo/entities/systems/TransformSystem');
		var CameraSystem = require('src/goo/entities/systems/CameraSystem');
		var ParticlesSystem = require('src/goo/entities/systems/ParticlesSystem');
		var DynamicLoader = require('src/goo/loaders/DynamicLoader');
		var Configs = require('test/unit/loaders/Configs');

		require('src/goo/loaders/handlers/EntityHandler');

		var loader;

		var entityRef = 'aaaabbbbaaaabbbbaaaabbbbaaaabbbb.entity';
		var materialRef = 'ccccddddccccddddccccddddccccdddd.material';
		var imageRef = 'ccccddddccccddddccccddddccccddddccccdddd.jpg';

		beforeEach(function () {
			var world = new World();
			world.setSystem(new TransformSystem());
			world.setSystem(new CameraSystem());
			world.setSystem(new ParticlesSystem());
			world.setSystem(new BoundingUpdateSystem());
			world.setSystem(new LightingSystem());
			world.setSystem(new AnimationSystem());
			if (AudioContext) {
				world.setSystem(new SoundSystem());
			}

			world.setSystem(new RenderSystem());

			loader = new DynamicLoader({
				world: world,
				rootPath: './'
			});
		});

		it('loads bundle', function (done) {
			// Create a bundlewrapper to preload and skip ajax
			var config = Configs.entity();
			var bundleRef = Configs.randomRef('bundle');

			loader.update(bundleRef, Configs.get());
			// Load bundle
			loader.load(bundleRef).then(function (/* bundle */) {
				var keys = Object.keys(loader._ajax._cache); // this needs to change when _cache becomes a map

				expect(keys).toContain(config.id);
				expect(loader._ajax._cache[config.id].components).toBeDefined();
				done();
			}, function () {
				expect('').toEqual('Should never get here');
				done();
			});
		});

		it('clears the engine', function (done) {
			var config = Configs.project(true);
			var world = loader._world;
			loader.preload(Configs.get());
			loader.load(config.id).then(function () {
				world.process();
				// We have some entities
				expect(world.entityManager.getEntities().length).toBeGreaterThan(0);
				expect(world.getSystem('TransformSystem')._activeEntities.length).toBeGreaterThan(0);

				// Someloaders are populated
				expect(loader._handlers.entity._objects.size).toBeGreaterThan(0);

				// Ajax has some cache
				expect(Object.keys(loader._ajax._cache).length).toBeGreaterThan(0);

				return loader.clear();
			}).then(function () {
				world.process();
				// Process loop is empty
				expect(world._addedEntities.length).toBe(0);
				expect(world._removedEntities.length).toBe(0);
				expect(world._changedEntities.length).toBe(0);

				// No entities in world
				expect(world.entityManager.getEntities().length).toBe(0);

				// No entities in systems
				expect(world._systems.length).toBeGreaterThan(0);
				for (var i = 0; i < world._systems.length; i++) {
					var entities = world._systems[i]._activeEntities;
					expect(entities.length).toBe(0);
				}

				// No objects in handlers
				for (var key in loader._handlers) {
					expect(loader._handlers[key]._objects.size).toBe(0);
				}

				// No configs in ajax
				var cacheCount = Object.keys(loader._ajax._cache);
				expect(cacheCount.length).toBe(0);
				done();
			}, function () {
				expect('').toEqual('Should never get here');
				done();
			});
		});

		it('preloads all binaries in json structure', function (done) {
			var entities = [];
			for (var i = 0; i < 4; i++) {
				entities[i] = Configs.entity(['transform', 'meshData']);
				if (i > 0) {
					Configs.attachChild(entities[i - 1], entities[i]);
				}
			}

			var bundleRef = Configs.randomRef('bundle');
			loader.update(bundleRef, Configs.get());

			var progress = jasmine.createSpy('progress');
			loader.load(bundleRef).then(function () {
				return loader.load(entities[0].id, {
					preloadBinaries: true,
					progressCallback: progress
				});
			}).then(function () {
				var l = entities.length;
				expect(progress).toHaveBeenCalledWith(l, l);
				done();
			}, function () {
				expect('').toEqual('Should never get here');
				done();
			});
		});

		describe('_getRefsFromConfig', function () {
			it('gets individual references', function () {
				var config = {
					aref: entityRef,
					bref: materialRef
				};

				expect(DynamicLoader._getRefsFromConfig(config))
					.toEqual([entityRef, materialRef]);
			});

			it('gets individual references several levels deep', function () {
				var config = {
					a: {
						b: {
							c: {
								aref: entityRef,
								bref: materialRef
							}
						}
					}
				};

				expect(DynamicLoader._getRefsFromConfig(config))
					.toEqual([entityRef, materialRef]);
			});

			it('gets packed references', function () {
				var config = {
					arefs: {
						aref: entityRef,
						bref: materialRef
					}
				};

				expect(DynamicLoader._getRefsFromConfig(config))
					.toEqual([entityRef, materialRef]);
			});

			it('ignores thumbnailRef', function () {
				var config = {
					aref: entityRef,
					bref: materialRef,
					thumbnailRef: imageRef
				};

				expect(DynamicLoader._getRefsFromConfig(config))
					.toEqual([entityRef, materialRef]);
			});
		});
	});
<commit_msg>fixed last test<commit_after>	describe('DynamicLoader', function () {

		var World = require('src/goo/entities/World');
		var TransformSystem = require('src/goo/entities/systems/TransformSystem');
		var CameraSystem = require('src/goo/entities/systems/CameraSystem');
		var ParticlesSystem = require('src/goo/entities/systems/ParticlesSystem');
		var BoundingUpdateSystem = require('src/goo/entities/systems/BoundingUpdateSystem');
		var LightingSystem = require('src/goo/entities/systems/LightingSystem');
		var AnimationSystem = require('src/goo/animationpack/systems/AnimationSystem');
		var DynamicLoader = require('src/goo/loaders/DynamicLoader');
		var AudioContext = require('src/goo/sound/AudioContext');
		var SoundSystem = require('src/goo/entities/systems/SoundSystem');
		var RenderSystem = require('src/goo/entities/systems/RenderSystem');
		var Configs = require('test/unit/loaders/Configs');

		require('src/goo/loaders/handlers/EntityHandler');
		require('src/goo/animationpack/handlers/AnimationHandlers');

		var loader;

		var entityRef = 'aaaabbbbaaaabbbbaaaabbbbaaaabbbb.entity';
		var materialRef = 'ccccddddccccddddccccddddccccdddd.material';
		var imageRef = 'ccccddddccccddddccccddddccccddddccccdddd.jpg';

		beforeEach(function () {
			var world = new World();
			world.setSystem(new TransformSystem());
			world.setSystem(new CameraSystem());
			world.setSystem(new ParticlesSystem());
			world.setSystem(new BoundingUpdateSystem());
			world.setSystem(new LightingSystem());
			world.setSystem(new AnimationSystem());
			if (AudioContext) {
				world.setSystem(new SoundSystem());
			}

			world.setSystem(new RenderSystem());

			loader = new DynamicLoader({
				world: world,
				rootPath: './'
			});
		});

		it('loads bundle', function (done) {
			// Create a bundlewrapper to preload and skip ajax
			var config = Configs.entity();
			var bundleRef = Configs.randomRef('bundle');

			loader.update(bundleRef, Configs.get());
			// Load bundle
			loader.load(bundleRef).then(function (/* bundle */) {
				var keys = Object.keys(loader._ajax._cache); // this needs to change when _cache becomes a map

				expect(keys).toContain(config.id);
				expect(loader._ajax._cache[config.id].components).toBeDefined();
				done();
			}, function () {
				expect('').toEqual('Should never get here');
				done();
			});
		});

		it('clears the engine', function (done) {
			var config = Configs.project(true);
			var world = loader._world;
			loader.preload(Configs.get());
			loader.load(config.id).then(function () {
				world.process();
				// We have some entities
				expect(world.entityManager.getEntities().length).toBeGreaterThan(0);
				expect(world.getSystem('TransformSystem')._activeEntities.length).toBeGreaterThan(0);

				// Someloaders are populated
				expect(loader._handlers.entity._objects.size).toBeGreaterThan(0);

				// Ajax has some cache
				expect(Object.keys(loader._ajax._cache).length).toBeGreaterThan(0);

				return loader.clear();
			}).then(function () {
				world.process();
				// Process loop is empty
				expect(world._addedEntities.length).toBe(0);
				expect(world._removedEntities.length).toBe(0);
				expect(world._changedEntities.length).toBe(0);

				// No entities in world
				expect(world.entityManager.getEntities().length).toBe(0);

				// No entities in systems
				expect(world._systems.length).toBeGreaterThan(0);
				for (var i = 0; i < world._systems.length; i++) {
					var entities = world._systems[i]._activeEntities;
					expect(entities.length).toBe(0);
				}

				// No objects in handlers
				for (var key in loader._handlers) {
					expect(loader._handlers[key]._objects.size).toBe(0);
				}

				// No configs in ajax
				var cacheCount = Object.keys(loader._ajax._cache);
				expect(cacheCount.length).toBe(0);
				done();
			}, function () {
				expect('').toEqual('Should never get here');
				done();
			});
		});

		it('preloads all binaries in json structure', function (done) {
			var entities = [];
			for (var i = 0; i < 4; i++) {
				entities[i] = Configs.entity(['transform', 'meshData']);
				if (i > 0) {
					Configs.attachChild(entities[i - 1], entities[i]);
				}
			}

			var bundleRef = Configs.randomRef('bundle');
			loader.update(bundleRef, Configs.get());

			var progress = jasmine.createSpy('progress');
			loader.load(bundleRef).then(function () {
				return loader.load(entities[0].id, {
					preloadBinaries: true,
					progressCallback: progress
				});
			}).then(function () {
				var l = entities.length;
				expect(progress).toHaveBeenCalledWith(l, l);
				done();
			}, function () {
				expect('').toEqual('Should never get here');
				done();
			});
		});

		describe('_getRefsFromConfig', function () {
			it('gets individual references', function () {
				var config = {
					aref: entityRef,
					bref: materialRef
				};

				expect(DynamicLoader._getRefsFromConfig(config))
					.toEqual([entityRef, materialRef]);
			});

			it('gets individual references several levels deep', function () {
				var config = {
					a: {
						b: {
							c: {
								aref: entityRef,
								bref: materialRef
							}
						}
					}
				};

				expect(DynamicLoader._getRefsFromConfig(config))
					.toEqual([entityRef, materialRef]);
			});

			it('gets packed references', function () {
				var config = {
					arefs: {
						aref: entityRef,
						bref: materialRef
					}
				};

				expect(DynamicLoader._getRefsFromConfig(config))
					.toEqual([entityRef, materialRef]);
			});

			it('ignores thumbnailRef', function () {
				var config = {
					aref: entityRef,
					bref: materialRef,
					thumbnailRef: imageRef
				};

				expect(DynamicLoader._getRefsFromConfig(config))
					.toEqual([entityRef, materialRef]);
			});
		});
	});
<|endoftext|>


<commit_before>import Vue from 'vue/dist/vue.common.js';
import InfiniteLoading from '../../../src/components/InfiniteLoading';

function isShow(elm) {
  const styles = getComputedStyle(elm);

  return styles.getPropertyValue('display') !== 'none';
}

describe('InfiniteLoading.vue', () => {
  let vm;
  const initConf = {
    data() {
      return {
        list: [],
        distance: 50,
        isLoadedAll: false,
        isDivScroll: true,
        isCustomSpinner: false,
        listContainerHeight: 200,
        listItemHeight: 20,
        direction: 'bottom',
      };
    },
    template: `

        <infinite-loading :distance="distance"
                          :direction="direction"
                          :on-infinite="onInfinite"
                          v-if="!isLoadedAll"
                          ref="infiniteLoading">

        </infinite-loading>

    `,
    components: { InfiniteLoading },
    methods: {
      onInfinite() {},
    },
  };

  // create new Vue instance for every test case
  beforeEach(() => {
    const container = document.createElement('div');
    container.setAttribute('id', 'app');
    document.body.appendChild(container);

    vm = new Vue(initConf);
  });

  afterEach(() => {
    /**
     * because of call the $destroy method of parent cannot trigger
     * destroy event for child component in Vue.js 2.0.0-rc6
     */
    vm.$refs.infiniteLoading && vm.$refs.infiniteLoading.$destroy();
    vm.$destroy(true);
    /**
     * because of pass true as the argument for destroy method cannot
     * remove element from DOM in Vue.js 2.0.0-rc6
     */
    vm.$el && vm.$el.remove();
  });

  it('should render a basic template', (done) => {
    vm.isDivScroll = false;
    setTimeout(() => {
      vm.$mount('#app');
      expect(vm.$el.querySelector('.loading-default')).to.be.ok;
      done();
    }, 1);
  });

  it('should execute callback and display a spinner immediately after initialize', (done) => {
    vm.onInfinite = function test() {
      Vue.nextTick(() => {
        expect(isShow(vm.$el.querySelector('.loading-default'))).to.be.true;
        done();
      });
    };

    vm.$mount('#app');
  });

  it('should not to execute callback if the previous loading has not be completed', (done) => {
    vm.onInfinite = function test() {
      const len = this.list.length + 1;
      const infiniteWrapper = this.$refs.infiniteLoading.scrollParent;

      for (let i = len; i < len + 20; i++) {
        this.list.push(i);
      }

      Vue.nextTick(() => {
        if (this.list.length === 20) {
          infiniteWrapper.addEventListener('scroll', () => {
            expect(this.list).to.have.lengthOf(20);
            done();
          });

          // trigger scroll event manually
          infiniteWrapper.scrollTop = infiniteWrapper.scrollHeight;
        }
      });
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should be destroyed completely by v-if', (done) => {
    vm.onInfinite = function test() {
      this.isLoadedAll = true;
      Vue.nextTick(() => {
        expect(vm.$el.querySelector('.loading-default')).to.not.be.ok;
        done();
      });
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should display no results prompt', (done) => {
    vm.onInfinite = function test() {
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
      Vue.nextTick(() => {
        expect(isShow(vm.$el.querySelectorAll('.infinite-status-prompt')[0])).to.be.true;
        done();
      });
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should display no more data prompt', (done) => {
    vm.onInfinite = function test() {
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
      // test for whether trigger again after complete
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
      Vue.nextTick(() => {
        expect(isShow(vm.$el.querySelectorAll('.infinite-status-prompt')[1])).to.be.true;
        done();
      });
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should load results to fill up the container', (done) => {
    const expectedCount = Math.floor(vm.listContainerHeight / vm.listItemHeight);
    let i = 0;
    let timer;

    vm.onInfinite = function test() {
      setTimeout(() => {
        this.list.push(++i);
        this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
        clearTimeout(timer);
        timer = setTimeout(() => {
          if (i >= expectedCount) {
            done();
          } else {
            done(new Error('List not be fill up!'));
          }
        }, 100);
      }, 1);
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should reset component and call onInfinite again', (done) => {
    let callCount = 0;
    vm.onInfinite = function test() {
      if (!callCount++) {
        this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset');
      } else {
        done();
      }
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should display the custom spinner if customize it with slot', (done) => {
    vm.isCustomSpinner = true;
    vm.distance = 100;
    vm.$mount('#app');

    Vue.nextTick(() => {
      expect(vm.$el.querySelector('.custom-spinner')).to.be.ok;
      done();
    });
  });

  it('should load data when scroll top (direction attribute)', (done) => {
    vm.direction = 'top';
    vm.onInfinite = function test() {
      Vue.nextTick(() => {
        expect(isShow(vm.$el.querySelector('.loading-default'))).to.be.true;
        done();
      });
    };

    vm.$mount('#app');
  });

  it('should load data once when deactivated by keep-alive feature', (done) => {
    let callCount = 0;
    let app;

    const InfiniteComponent = {
      data: initConf.data,
      template: initConf.template,
      components: initConf.components,
      methods: {
        onInfinite() {
          callCount++;
          if (callCount === 1) {
            this.$parent.currentView = null;
            Vue.nextTick(() => {
              this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
              setTimeout(() => {
                expect(callCount).to.equal(1);
                app.$destroy(true);
                app.$el && app.$el.remove();
                done();
              }, 1000);
            });
          }
        },
      },
    };

    app = new Vue({
      data() {
        return {
          currentView: 'InfiniteComponent',
        };
      },
      template: `
        <keep-alive>
          <component :is="currentView"></component>
        </keep-alive>
      `,
      components: {
        InfiniteComponent,
      },
    });

    app.$mount('#app');
  });

  it('should work with customize scroll plugin like iScroll', (done) => {
    const infiniteWrapper = document.createElement('div');
    const wrapper = document.createElement('div');

    vm.isDivScroll = false;
    infiniteWrapper.setAttribute('infinite-wrapper', '');
    document.getElementById('app').appendChild(infiniteWrapper);
    infiniteWrapper.appendChild(wrapper);

    vm.$mount(wrapper);

    Vue.nextTick(() => {
      expect(vm.$refs.infiniteLoading.scrollParent).to.equal(infiniteWrapper);
      done();
    }, 1);
  });
});
<commit_msg>Modify description for the unit test<commit_after>import Vue from 'vue/dist/vue.common.js';
import InfiniteLoading from '../../../src/components/InfiniteLoading';

function isShow(elm) {
  const styles = getComputedStyle(elm);

  return styles.getPropertyValue('display') !== 'none';
}

describe('InfiniteLoading.vue', () => {
  let vm;
  const initConf = {
    data() {
      return {
        list: [],
        distance: 50,
        isLoadedAll: false,
        isDivScroll: true,
        isCustomSpinner: false,
        listContainerHeight: 200,
        listItemHeight: 20,
        direction: 'bottom',
      };
    },
    template: `

        <infinite-loading :distance="distance"
                          :direction="direction"
                          :on-infinite="onInfinite"
                          v-if="!isLoadedAll"
                          ref="infiniteLoading">

        </infinite-loading>

    `,
    components: { InfiniteLoading },
    methods: {
      onInfinite() {},
    },
  };

  // create new Vue instance for every test case
  beforeEach(() => {
    const container = document.createElement('div');
    container.setAttribute('id', 'app');
    document.body.appendChild(container);

    vm = new Vue(initConf);
  });

  afterEach(() => {
    /**
     * because of call the $destroy method of parent cannot trigger
     * destroy event for child component in Vue.js 2.0.0-rc6
     */
    vm.$refs.infiniteLoading && vm.$refs.infiniteLoading.$destroy();
    vm.$destroy(true);
    /**
     * because of pass true as the argument for destroy method cannot
     * remove element from DOM in Vue.js 2.0.0-rc6
     */
    vm.$el && vm.$el.remove();
  });

  it('should render a basic template', (done) => {
    vm.isDivScroll = false;
    setTimeout(() => {
      vm.$mount('#app');
      expect(vm.$el.querySelector('.loading-default')).to.be.ok;
      done();
    }, 1);
  });

  it('should execute callback and display a spinner immediately after initialize', (done) => {
    vm.onInfinite = function test() {
      Vue.nextTick(() => {
        expect(isShow(vm.$el.querySelector('.loading-default'))).to.be.true;
        done();
      });
    };

    vm.$mount('#app');
  });

  it('should not to execute callback if the previous loading has not be completed', (done) => {
    vm.onInfinite = function test() {
      const len = this.list.length + 1;
      const infiniteWrapper = this.$refs.infiniteLoading.scrollParent;

      for (let i = len; i < len + 20; i++) {
        this.list.push(i);
      }

      Vue.nextTick(() => {
        if (this.list.length === 20) {
          infiniteWrapper.addEventListener('scroll', () => {
            expect(this.list).to.have.lengthOf(20);
            done();
          });

          // trigger scroll event manually
          infiniteWrapper.scrollTop = infiniteWrapper.scrollHeight;
        }
      });
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should be destroyed completely by v-if', (done) => {
    vm.onInfinite = function test() {
      this.isLoadedAll = true;
      Vue.nextTick(() => {
        expect(vm.$el.querySelector('.loading-default')).to.not.be.ok;
        done();
      });
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should display no results prompt', (done) => {
    vm.onInfinite = function test() {
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
      Vue.nextTick(() => {
        expect(isShow(vm.$el.querySelectorAll('.infinite-status-prompt')[0])).to.be.true;
        done();
      });
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should display no more data prompt', (done) => {
    vm.onInfinite = function test() {
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
      // test for whether trigger again after complete
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
      Vue.nextTick(() => {
        expect(isShow(vm.$el.querySelectorAll('.infinite-status-prompt')[1])).to.be.true;
        done();
      });
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should load results to fill up the container', (done) => {
    const expectedCount = Math.floor(vm.listContainerHeight / vm.listItemHeight);
    let i = 0;
    let timer;

    vm.onInfinite = function test() {
      setTimeout(() => {
        this.list.push(++i);
        this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
        clearTimeout(timer);
        timer = setTimeout(() => {
          if (i >= expectedCount) {
            done();
          } else {
            done(new Error('List not be fill up!'));
          }
        }, 100);
      }, 1);
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should reset component and call onInfinite again', (done) => {
    let callCount = 0;
    vm.onInfinite = function test() {
      if (!callCount++) {
        this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset');
      } else {
        done();
      }
    }.bind(vm);

    vm.$mount('#app');
  });

  it('should display the custom spinner if customize it with slot', (done) => {
    vm.isCustomSpinner = true;
    vm.distance = 100;
    vm.$mount('#app');

    Vue.nextTick(() => {
      expect(vm.$el.querySelector('.custom-spinner')).to.be.ok;
      done();
    });
  });

  it('should load data when scroll top (direction attribute)', (done) => {
    vm.direction = 'top';
    vm.onInfinite = function test() {
      Vue.nextTick(() => {
        expect(isShow(vm.$el.querySelector('.loading-default'))).to.be.true;
        done();
      });
    };

    vm.$mount('#app');
  });

  it('should load data once when deactivated by keep-alive feature', (done) => {
    let callCount = 0;
    let app;

    const InfiniteComponent = {
      data: initConf.data,
      template: initConf.template,
      components: initConf.components,
      methods: {
        onInfinite() {
          callCount++;
          if (callCount === 1) {
            this.$parent.currentView = null;
            Vue.nextTick(() => {
              this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
              setTimeout(() => {
                expect(callCount).to.equal(1);
                app.$destroy(true);
                app.$el && app.$el.remove();
                done();
              }, 1000);
            });
          }
        },
      },
    };

    app = new Vue({
      data() {
        return {
          currentView: 'InfiniteComponent',
        };
      },
      template: `
        <keep-alive>
          <component :is="currentView"></component>
        </keep-alive>
      `,
      components: {
        InfiniteComponent,
      },
    });

    app.$mount('#app');
  });

  it('should work with customize scroll plugin like perfect-scroll', (done) => {
    const infiniteWrapper = document.createElement('div');
    const wrapper = document.createElement('div');

    vm.isDivScroll = false;
    infiniteWrapper.setAttribute('infinite-wrapper', '');
    document.getElementById('app').appendChild(infiniteWrapper);
    infiniteWrapper.appendChild(wrapper);

    vm.$mount(wrapper);

    Vue.nextTick(() => {
      expect(vm.$refs.infiniteLoading.scrollParent).to.equal(infiniteWrapper);
      done();
    }, 1);
  });
});
<|endoftext|>