<commit_before>const Command = require("../base/slashCommand");
const { ApplicationCommandOptionType } = require("discord.js");
const {inspect} = require("util"); // eslint-disable-line no-unused-vars

// To get the player's arena info (Adapted from shittybill#3024's Scorpio)
class MyArena extends Command {
    constructor(Bot) {
        super(Bot, {
            name: "myarena",
            guildOnly: false,
            description: "Show your current ranking in the character & fleet arenas",
            options: [
                {
                    name: "allycode",
                    description: "The ally code of the user you want to see",
                    type: ApplicationCommandOptionType.String
                },
                {
                    name: "stats",
                    type: ApplicationCommandOptionType.Boolean,
                    description: "Show some general stats for your arena team"
                }
            ]
        });
    }

    async run(Bot, interaction) { // eslint-disable-line no-unused-vars
        let allycode = interaction.options.getString("allycode");
        const showStats    = interaction.options.getBoolean("stats");

        allycode = await Bot.getAllyCode(interaction, allycode);

        if (!allycode) {
            return super.error(interaction, "Invalid user ID, you need to use either the `me` keyword if you have a registered ally code, an ally code, or mention a Discord user");
        }

        const cooldown = await Bot.getPlayerCooldown(interaction.user.id);
        let player;
        try {
            player = await Bot.swgohAPI.unitStats(allycode, cooldown);
            if (Array.isArray(player)) player = player[0];
        } catch (e) {
            Bot.logger.error("Broke getting player in myarena: " + e);
            return super.error(interaction, "Something broke, please try again in a bit");
        }

        if (!player || !player.arena) {
            return super.error(interaction, "Something broke when getting your info, please try again in a bit.");
        }

        const fields = [];
        const positions = [ "L|", "2|", "3|", "4|", "5|" ];
        const sPositions = [ "L|", "2|", "3|", "4|", "B|", "B|", "B|", "B|" ];

        let desc = "";
        if (!showStats) {
            // Grab the arena info
            const shipArena = await getArenaStrings(player, "ship");
            console.log(shipArena);
            if (shipArena) fields.push(shipArena);

            const charArena = await getArenaStrings(player, "char");
            console.log(charArena);
            if (charArena) fields.push(charArena);
        } else {
            // If it's set to show stats, grab all the stats for each unit in the character arena team
            let playerStats = null;
            try {
                playerStats = await Bot.swgohAPI.unitStats(allycode, cooldown);
                if (Array.isArray(playerStats)) playerStats = playerStats[0];
            } catch (e) {
                console.log("[ERROR MyArena]");
                console.error(e);
                return super.error(interaction, Bot.codeBlock(e.interaction), {
                    title: interaction.language.get("BASE_SOMETHING_BROKE"),
                    footer: "Please try again in a bit."
                });
            }

            const chars = [];
            for (let ix = 0; ix < player.arena.char.squad.length; ix++) {
                const charId = player.arena.char.squad[ix].defId;
                const unitName = await getUnitName(player, charId);

                const thisChar = playerStats.roster.find(c => c.defId === charId);
                const speed    = thisChar.stats.final.Speed.toLocaleString();
                const health   = thisChar.stats.final.Health.toLocaleString();
                const prot     = thisChar.stats.final.Protection.toLocaleString();
                chars.push({
                    pos: positions[ix],
                    speed: speed,
                    health: health,
                    prot: prot,
                    name: unitName
                });
            }
            desc = Bot.makeTable({
                pos:    {value: "",    startWith: "`"},
                speed:  {value: "Spd", startWith: "[",  endWith: "|"},
                health: {value: "HP",                    endWith: "|"},
                prot:   {value: "Prot",                  endWith: "]`"},
                name:   {value: "",    align: "left"}
            }, chars).join("\n");
        }

        if (player.warnings) {
            fields.push({
                name: "Warnings",
                value: player.warnings.join("\n")
            });
        }

        const footer = Bot.updatedFooter(player.updated, interaction, "player", cooldown);
        return interaction.reply({
            embeds: [{
                author: {
                    name: interaction.language.get("COMMAND_MYARENA_EMBED_HEADER", player.name)
                },
                description: desc,
                fields: fields,
                footer: footer
            }]
        });

        async function getArenaStrings(player, type="char") {
            if (!player.arena?.[type]?.squad?.length) return null;
            const arenaArr = [];
            for (let ix = 0; ix < player.arena[type].squad.length; ix++) {
                const unitId = player.arena[type].squad[ix].defId;
                const unitName = await getUnitName(player, unitId);
                arenaArr.push(`\`${type === "char" ? positions[ix] : sPositions[ix]}\` ${unitName}`);
            }
            return {
                name: interaction.language.get(`COMMAND_MYARENA_${type === "char" ? "ARENA": "FLEET"}`, player.arena[type].rank),
                value: arenaArr.join("\n") + "\n`------------------------------`",
                inline: true
            };
        }

        async function getUnitName(player, defId) {
            console.log(defId);
            const thisChar = player.roster.find(c => c.defId === defId);
            const thisLangChar = await Bot.swgohAPI.langChar(thisChar, interaction.guildSettings.swgohLanguage);
            const thisZ = thisLangChar.skills.filter(s => (s.isZeta && s.tier === s.tiers) || (s.isOmicron && s.tier >= s.tiers-1));
            if (thisLangChar.name && !thisLangChar.nameKey) thisLangChar.nameKey = thisLangChar.name;
            return `${"z".repeat(thisZ.length)}${thisLangChar.nameKey}`;
        }
    }
}

module.exports = MyArena;
<commit_msg>Forgot some logs<commit_after>const Command = require("../base/slashCommand");
const { ApplicationCommandOptionType } = require("discord.js");
const {inspect} = require("util"); // eslint-disable-line no-unused-vars

// To get the player's arena info (Adapted from shittybill#3024's Scorpio)
class MyArena extends Command {
    constructor(Bot) {
        super(Bot, {
            name: "myarena",
            guildOnly: false,
            description: "Show your current ranking in the character & fleet arenas",
            options: [
                {
                    name: "allycode",
                    description: "The ally code of the user you want to see",
                    type: ApplicationCommandOptionType.String
                },
                {
                    name: "stats",
                    type: ApplicationCommandOptionType.Boolean,
                    description: "Show some general stats for your arena team"
                }
            ]
        });
    }

    async run(Bot, interaction) { // eslint-disable-line no-unused-vars
        let allycode = interaction.options.getString("allycode");
        const showStats    = interaction.options.getBoolean("stats");

        allycode = await Bot.getAllyCode(interaction, allycode);

        if (!allycode) {
            return super.error(interaction, "Invalid user ID, you need to use either the `me` keyword if you have a registered ally code, an ally code, or mention a Discord user");
        }

        const cooldown = await Bot.getPlayerCooldown(interaction.user.id);
        let player;
        try {
            player = await Bot.swgohAPI.unitStats(allycode, cooldown);
            if (Array.isArray(player)) player = player[0];
        } catch (e) {
            Bot.logger.error("Broke getting player in myarena: " + e);
            return super.error(interaction, "Something broke, please try again in a bit");
        }

        if (!player || !player.arena) {
            return super.error(interaction, "Something broke when getting your info, please try again in a bit.");
        }

        const fields = [];
        const positions = [ "L|", "2|", "3|", "4|", "5|" ];
        const sPositions = [ "L|", "2|", "3|", "4|", "B|", "B|", "B|", "B|" ];

        let desc = "";
        if (!showStats) {
            // Grab the arena info
            const shipArena = await getArenaStrings(player, "ship");
            if (shipArena) fields.push(shipArena);

            const charArena = await getArenaStrings(player, "char");
            if (charArena) fields.push(charArena);
        } else {
            // If it's set to show stats, grab all the stats for each unit in the character arena team
            let playerStats = null;
            try {
                playerStats = await Bot.swgohAPI.unitStats(allycode, cooldown);
                if (Array.isArray(playerStats)) playerStats = playerStats[0];
            } catch (e) {
                console.log("[ERROR MyArena]");
                console.error(e);
                return super.error(interaction, Bot.codeBlock(e.interaction), {
                    title: interaction.language.get("BASE_SOMETHING_BROKE"),
                    footer: "Please try again in a bit."
                });
            }

            const chars = [];
            for (let ix = 0; ix < player.arena.char.squad.length; ix++) {
                const charId = player.arena.char.squad[ix].defId;
                const unitName = await getUnitName(player, charId);

                const thisChar = playerStats.roster.find(c => c.defId === charId);
                const speed    = thisChar.stats.final.Speed.toLocaleString();
                const health   = thisChar.stats.final.Health.toLocaleString();
                const prot     = thisChar.stats.final.Protection.toLocaleString();
                chars.push({
                    pos: positions[ix],
                    speed: speed,
                    health: health,
                    prot: prot,
                    name: unitName
                });
            }
            desc = Bot.makeTable({
                pos:    {value: "",    startWith: "`"},
                speed:  {value: "Spd", startWith: "[",  endWith: "|"},
                health: {value: "HP",                    endWith: "|"},
                prot:   {value: "Prot",                  endWith: "]`"},
                name:   {value: "",    align: "left"}
            }, chars).join("\n");
        }

        if (player.warnings) {
            fields.push({
                name: "Warnings",
                value: player.warnings.join("\n")
            });
        }

        const footer = Bot.updatedFooter(player.updated, interaction, "player", cooldown);
        return interaction.reply({
            embeds: [{
                author: {
                    name: interaction.language.get("COMMAND_MYARENA_EMBED_HEADER", player.name)
                },
                description: desc,
                fields: fields,
                footer: footer
            }]
        });

        async function getArenaStrings(player, type="char") {
            if (!player.arena?.[type]?.squad?.length) return null;
            const arenaArr = [];
            for (let ix = 0; ix < player.arena[type].squad.length; ix++) {
                const unitId = player.arena[type].squad[ix].defId;
                const unitName = await getUnitName(player, unitId);
                arenaArr.push(`\`${type === "char" ? positions[ix] : sPositions[ix]}\` ${unitName}`);
            }
            return {
                name: interaction.language.get(`COMMAND_MYARENA_${type === "char" ? "ARENA": "FLEET"}`, player.arena[type].rank),
                value: arenaArr.join("\n") + "\n`------------------------------`",
                inline: true
            };
        }

        async function getUnitName(player, defId) {
            const thisChar = player.roster.find(c => c.defId === defId);
            const thisLangChar = await Bot.swgohAPI.langChar(thisChar, interaction.guildSettings.swgohLanguage);
            const thisZ = thisLangChar.skills.filter(s => (s.isZeta && s.tier === s.tiers) || (s.isOmicron && s.tier >= s.tiers-1));
            if (thisLangChar.name && !thisLangChar.nameKey) thisLangChar.nameKey = thisLangChar.name;
            return `${"z".repeat(thisZ.length)}${thisLangChar.nameKey}`;
        }
    }
}

module.exports = MyArena;
<|endoftext|>


<commit_before>/**
 * Created by babich on 12/19/14.
 */
define(['jquery', 'fury.notify', 'bootstrap'], function ($, notify) {
    $(function () {
        $("[rel='tooltip']").tooltip();
    });
    $('body')
        .on('click', '.submit-ajax-button', function () {
            $(this).closest('.modal').find('form.form-ajax').trigger('submit.ajax');
        })
        .on('submit.ajax', '.form-ajax', function (e) {
            e.preventDefault();
            var $this = $(this);
            var formData = $this.serializeArray();
            $.ajax({
                url: $this.attr('action'),
                type: 'POST',
                beforeSend: function () {
                    $('.modal').find('a, .btn').addClass('disabled');
                    $this.find('input[type=submit]').addClass('disabled');
                    $('.error-form-field').each(function (i, element) {
                        $(element).removeClass('error-form-field');
                    });
                    $('.error-form-message').each(function (i, element) {
                        $(element).html('');
                    });
                },
                success: function (jsonData) {
                    $('.modal').find('a, .btn').removeClass('disabled');
                    $this.find('input[type=submit]').removeClass('disabled');
                    if (jsonData !== undefined && jsonData.errors !== undefined && !$.isEmptyObject(jsonData.errors)) {
                        for (var key in jsonData.errors) {
                            var field = $this.find('.form-group .form-control[name="' + key + '"]');
                            field.addClass('form-control error-form-field');
                            field.attr("rel", "tooltip");
                            field.tooltip({
                                html: true,
                                title: jsonData.errors[key].join('
'),
                                trigger: 'manual',
                                // change position for long messages, and for hidden fields
                                placement: (field.width() < 220) || field.is('label') ? 'right' : 'top',
                                animation: true
                            });
                            field.tooltip('show');
                            field.click(function () {
                                $(this).removeClass('error-form-field');
                                $(this).tooltip('destroy');
                            });
                        }
                    } else {
                        $this.trigger('success.form.fury', []);
                        $('.close-form-button').trigger('click');
                        jsonData.success.forEach(function (entry) {
                            notify.addSuccess(entry);
                        });
                    }
                },
                data: formData,
                dataType: 'json'
            });
            return false;
        });
});<commit_msg>fury.form handle 400 response now<commit_after>/**
 * Created by babich on 12/19/14.
 */
define(['jquery', 'fury.notify', 'bootstrap'], function ($, notify) {
    $(function () {
        $("[rel='tooltip']").tooltip();
    });
    $('body')
        .on('click', '.submit-ajax-button', function () {
            $(this).closest('.modal').find('form.form-ajax').trigger('submit.ajax');
        })
        .on('submit.ajax', '.form-ajax', function (e) {
            e.preventDefault();
            var $this = $(this);
            var formData = $this.serializeArray();
            $.ajax({
                url: $this.attr('action'),
                type: 'POST',
                beforeSend: function () {
                    $('.modal').find('a, .btn').addClass('disabled');
                    $this.find('input[type=submit]').addClass('disabled');
                    $('.error-form-field').each(function (i, element) {
                        $(element).removeClass('error-form-field');
                    });
                    $('.error-form-message').each(function (i, element) {
                        $(element).html('');
                    });
                },
                error: function (response) {
                    handler($this, response.responseJSON);
                },
                success: function (jsonData) {
                    handler($this, jsonData);
                },
                data: formData,
                dataType: 'json'
            });
            return false;
        });

    function handler(form, jsonData) {
        $('.modal').find('a, .btn').removeClass('disabled');
        form.find('input[type=submit]').removeClass('disabled');
        if (typeof(jsonData) == "undefined") {
            return false;
        }
        if (jsonData !== undefined && jsonData.errors !== undefined && !$.isEmptyObject(jsonData.errors)) {
            for (var key in jsonData.errors) {
                var field = form.find('.form-group .form-control[name="' + key + '"]');
                field.addClass('form-control error-form-field');
                field.attr("rel", "tooltip");
                field.tooltip({
                    html: true,
                    title: jsonData.errors[key].join('
'),
                    trigger: 'manual',
                    // change position for long messages, and for hidden fields
                    placement: (field.width() < 220) || field.is('label') ? 'right' : 'top',
                    animation: true
                });
                field.tooltip('show');
                field.click(function () {
                    $(this).removeClass('error-form-field');
                    $(this).tooltip('destroy');
                });
            }
        } else {
            form.trigger('success.form.fury', []);
            $('.close-form-button').trigger('click');
            jsonData.success.forEach(function (entry) {
                notify.addSuccess(entry);
            });
        }
    }
});<|endoftext|>


<commit_before>var RTCPeerConnection = null;
var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var brightstreamDetectedBrowser = null;
var brightstreamDetectedVersion = null;

function trace(text) {
  // This function is used for logging.
  if (text[text.length - 1] == '\n') {
    text = text.substring(0, text.length - 1);
  }
  console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

if (navigator.mozGetUserMedia) {
  console.log("This appears to be Firefox");

  brightstreamDetectedBrowser = "firefox";

  brightstreamDetectedVersion =
                  parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]);

  // The RTCPeerConnection object.
  RTCPeerConnection = mozRTCPeerConnection;

  // The RTCSessionDescription object.
  RTCSessionDescription = mozRTCSessionDescription;

  // The RTCIceCandidate object.
  RTCIceCandidate = mozRTCIceCandidate;

  // Get UserMedia (only difference is the prefix).
  // Code from Adam Barth.
  getUserMedia = navigator.mozGetUserMedia.bind(navigator);

  // Creates iceServer from the url for FF.
  createIceServer = function(url, username, password) {
    var iceServer = null;
    var url_parts = url.split(':');
    if (url_parts[0].indexOf('stun') === 0) {
      // Create iceServer with stun url.
      iceServer = { 'url': url };
    } else if (url_parts[0].indexOf('turn') === 0 &&
               (url.indexOf('transport=udp') !== -1 ||
                url.indexOf('?transport') === -1)) {
      // Create iceServer with turn url.
      // Ignore the transport parameter from TURN url.
      var turn_url_parts = url.split("?");
      iceServer = { 'url': turn_url_parts[0],
                    'credential': password,
                    'username': username };
    }
    return iceServer;
  };

  // Attach a media stream to an element.
  attachMediaStream = function(element, stream) {
    console.log("Attaching media stream");
    element.mozSrcObject = stream;
    element.play();
  };

  reattachMediaStream = function(to, from) {
    console.log("Reattaching media stream");
    to.mozSrcObject = from.mozSrcObject;
    to.play();
  };

  // Fake get{Video,Audio}Tracks
  MediaStream.prototype.getVideoTracks = function() {
    return [];
  };

  MediaStream.prototype.getAudioTracks = function() {
    return [];
  };
} else if (navigator.webkitGetUserMedia) {
  console.log("This appears to be Chrome");

  brightstreamDetectedBrowser = "chrome";
  brightstreamDetectedVersion =
             parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]);

  // Creates iceServer from the url for Chrome.
  createIceServer = function(url, username, password) {
    var iceServer = null;
    var url_parts = url.split(':');
    if (url_parts[0].indexOf('stun') === 0) {
      // Create iceServer with stun url.
      iceServer = { 'url': url };
    } else if (url_parts[0].indexOf('turn') === 0) {
      if (brightstreamDetectedVersion < 28) {
        // For pre-M28 chrome versions use old TURN format.
        var url_turn_parts = url.split("turn:");
        iceServer = { 'url': 'turn:' + username + '@' + url_turn_parts[1],
                      'credential': password };
      } else {
        // For Chrome M28 & above use new TURN format.
        iceServer = { 'url': url,
                      'credential': password,
                      'username': username };
      }
    }
    return iceServer;
  };

  // The RTCPeerConnection object.
  RTCPeerConnection = webkitRTCPeerConnection;

  // Get UserMedia (only difference is the prefix).
  // Code from Adam Barth.
  getUserMedia = navigator.webkitGetUserMedia.bind(navigator);

  // Attach a media stream to an element.
  attachMediaStream = function(element, stream) {
    if (typeof element.srcObject !== 'undefined') {
      element.srcObject = stream;
    } else if (typeof element.mozSrcObject !== 'undefined') {
      element.mozSrcObject = stream;
    } else if (typeof element.src !== 'undefined') {
      element.src = URL.createObjectURL(stream);
    } else {
      console.log('Error attaching stream to element.');
    }
  };

  reattachMediaStream = function(to, from) {
    to.src = from.src;
  };

  // The representation of tracks in a stream is changed in M26.
  // Unify them for earlier Chrome versions in the coexisting period.
  if (!webkitMediaStream.prototype.getVideoTracks) {
    webkitMediaStream.prototype.getVideoTracks = function() {
      return this.videoTracks;
    };
    webkitMediaStream.prototype.getAudioTracks = function() {
      return this.audioTracks;
    };
  }

  // New syntax of getXXXStreams method in M26.
  if (!webkitRTCPeerConnection.prototype.getLocalStreams) {
    webkitRTCPeerConnection.prototype.getLocalStreams = function() {
      return this.localStreams;
    };
    webkitRTCPeerConnection.prototype.getRemoteStreams = function() {
      return this.remoteStreams;
    };
  }
} else {
  console.log("Browser does not appear to be WebRTC-capable");
}
<commit_msg>Update adapter.js.<commit_after>var RTCPeerConnection = null;
var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
var webrtcDetectedVersion = null;

function trace(text) {
  // This function is used for logging.
  if (text[text.length - 1] == '\n') {
    text = text.substring(0, text.length - 1);
  }
  console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

if (navigator.mozGetUserMedia) {
  console.log("This appears to be Firefox");

  webrtcDetectedBrowser = "firefox";

  webrtcDetectedVersion =
           parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);

  // The RTCPeerConnection object.
  RTCPeerConnection = mozRTCPeerConnection;

  // The RTCSessionDescription object.
  RTCSessionDescription = mozRTCSessionDescription;

  // The RTCIceCandidate object.
  RTCIceCandidate = mozRTCIceCandidate;

  // Get UserMedia (only difference is the prefix).
  // Code from Adam Barth.
  getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  navigator.getUserMedia = getUserMedia;

  // Creates iceServer from the url for FF.
  createIceServer = function(url, username, password) {
    var iceServer = null;
    var url_parts = url.split(':');
    if (url_parts[0].indexOf('stun') === 0) {
      // Create iceServer with stun url.
      iceServer = { 'url': url };
    } else if (url_parts[0].indexOf('turn') === 0) {
      if (webrtcDetectedVersion < 27) {
        // Create iceServer with turn url.
        // Ignore the transport parameter from TURN url for FF version <=27.
        var turn_url_parts = url.split("?");
        // Return null for createIceServer if transport=tcp.
        if (turn_url_parts.length === 1 ||
            turn_url_parts[1].indexOf('transport=udp') === 0) {
          iceServer = { 'url': turn_url_parts[0],
                        'credential': password,
                        'username': username };
        }
      } else {
        // FF 27 and above supports transport parameters in TURN url,
        // So passing in the full url to create iceServer.
        iceServer = { 'url': url,
                      'credential': password,
                      'username': username };
      }
    }
    return iceServer;
  };

  // Attach a media stream to an element.
  attachMediaStream = function(element, stream) {
    console.log("Attaching media stream");
    element.mozSrcObject = stream;
    element.play();
  };

  reattachMediaStream = function(to, from) {
    console.log("Reattaching media stream");
    to.mozSrcObject = from.mozSrcObject;
    to.play();
  };

  // Fake get{Video,Audio}Tracks
  if (!MediaStream.prototype.getVideoTracks) {
    MediaStream.prototype.getVideoTracks = function() {
      return [];
    };
  }

  if (!MediaStream.prototype.getAudioTracks) {
    MediaStream.prototype.getAudioTracks = function() {
      return [];
    };
  }
} else if (navigator.webkitGetUserMedia) {
  console.log("This appears to be Chrome");

  webrtcDetectedBrowser = "chrome";
  webrtcDetectedVersion =
         parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);

  // Creates iceServer from the url for Chrome.
  createIceServer = function(url, username, password) {
    var iceServer = null;
    var url_parts = url.split(':');
    if (url_parts[0].indexOf('stun') === 0) {
      // Create iceServer with stun url.
      iceServer = { 'url': url };
    } else if (url_parts[0].indexOf('turn') === 0) {
      // Chrome M28 & above uses below TURN format.
      iceServer = { 'url': url,
                    'credential': password,
                    'username': username };
    }
    return iceServer;
  };

  // The RTCPeerConnection object.
  RTCPeerConnection = webkitRTCPeerConnection;

  // Get UserMedia (only difference is the prefix).
  // Code from Adam Barth.
  getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  navigator.getUserMedia = getUserMedia;

  // Attach a media stream to an element.
  attachMediaStream = function(element, stream) {
    if (typeof element.srcObject !== 'undefined') {
      element.srcObject = stream;
    } else if (typeof element.mozSrcObject !== 'undefined') {
      element.mozSrcObject = stream;
    } else if (typeof element.src !== 'undefined') {
      element.src = URL.createObjectURL(stream);
    } else {
      console.log('Error attaching stream to element.');
    }
  };

  reattachMediaStream = function(to, from) {
    to.src = from.src;
  };
} else {
  console.log("Browser does not appear to be WebRTC-capable");
}
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var Swipeout = require('react-native-swipeout')

var swipeoutExample = React.createClass({
  renderRow: function (item){
    return  <Listitem swipeout={true} text={item.name} onPress={this.props.nextPage.bind(null, item)}/>
  }
, render: function() {
    var btnsDefault = [
      {
        text: 'Button'
      }
    ]
    var btnsOnPress = [
      {
        text: 'onPress'
      , onPress: function(){alert('button pressed')}
      }
    ]
    var btnsTypes = [
      {
        text: 'Primary'
      , type: 'primary'
      }, {
        text: 'Secondary'
      , type: 'secondary'
      }, {
        text: 'Delete'
      , type: 'delete'
      }
    ]
    var btnsCustomStyles = [
      {
        backgroundColor: '#4fba8a'
      , color: '#17807a'
      , text: 'Button'
      }
    ]
    var btnsFive = [
      {
        text: 'One'
      }, {
        text: 'Two'
      }, {
        text: 'Three'
      }, {
        text: 'Four'
      }, {
        text: 'Five'
      }
    ]
    return (
      <View style={styles.container}>
        <View style={styles.liContainer}>
          <Swipeout btns={btnsDefault}>
            <Listitem text="Basic example"/>
          </Swipeout>
          <Swipeout btns={btnsOnPress}>
            <Listitem text="onPress callback"/>
          </Swipeout>
          <Swipeout btns={btnsTypes}>
            <Listitem text="Button types"/>
          </Swipeout>
          <Swipeout btns={btnsCustomStyles}>
            <Listitem text="Custom button background and text color"/>
          </Swipeout>
          <Swipeout btns={btnsDefault} backgroundColor="#006fff">
            <Listitem text="Custom background color (drag me far)"/>
          </Swipeout>
          <Swipeout btns={btnsDefault} autoClose={true}>
            <Listitem text="autoClose={true}"/>
          </Swipeout>
          <Swipeout btns={btnsFive} autoClose={true}>
            <Listitem text="Five buttons (full-width) and autoClose={true}"/>
          </Swipeout>
        </View>
      </View>
    );
  }
});

var Listitem = React.createClass({
  render: function() {
    return (
      <View style={styles.li}>
        <Text style={styles.liText}>{this.props.text}</Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: '#f2f2f2',
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
  },
  li: {
    backgroundColor: '#fff',
    borderBottomColor: '#eee',
    borderColor: 'transparent',
    borderWidth: 1,
    paddingLeft: 16,
    paddingTop: 14,
    paddingBottom: 16,
  },
  liContainer: {
    flex: 1,
  },
  liText: {
    color: '#333',
    fontSize: 16,
  },
});

AppRegistry.registerComponent('swipeoutExample', () => swipeoutExample);
<commit_msg>remove unneeded function<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var Swipeout = require('react-native-swipeout')

var swipeoutExample = React.createClass({
  render: function() {
    var btnsDefault = [
      {
        text: 'Button'
      }
    ]
    var btnsOnPress = [
      {
        text: 'onPress'
      , onPress: function(){alert('button pressed')}
      , type: 'primary'
      }
    ]
    var btnsTypes = [
      {
        text: 'Primary'
      , type: 'primary'
      }, {
        text: 'Secondary'
      , type: 'secondary'
      }, {
        text: 'Delete'
      , type: 'delete'
      }
    ]
    var btnsCustomStyles = [
      {
        backgroundColor: '#4fba8a'
      , color: '#17807a'
      , text: 'Button'
      }
    ]
    var btnsFive = [
      {
        text: 'One'
      }, {
        text: 'Two'
      }, {
        text: 'Three'
      }, {
        text: 'Four'
      }, {
        text: 'Five'
      }
    ]
    return (
      <View style={styles.container}>
        <View style={styles.liContainer}>
          <Swipeout btns={btnsDefault}>
            <Listitem text="Basic example"/>
          </Swipeout>
          <Swipeout btns={btnsOnPress}>
            <Listitem text="onPress callback"/>
          </Swipeout>
          <Swipeout btns={btnsTypes}>
            <Listitem text="Button types"/>
          </Swipeout>
          <Swipeout btns={btnsCustomStyles}>
            <Listitem text="Custom button background and text color"/>
          </Swipeout>
          <Swipeout btns={btnsDefault} backgroundColor="#006fff">
            <Listitem text="Custom background color (drag me far)"/>
          </Swipeout>
          <Swipeout btns={btnsDefault} autoClose={true}>
            <Listitem text="autoClose={true}"/>
          </Swipeout>
          <Swipeout btns={btnsFive} autoClose={true}>
            <Listitem text="Five buttons (full-width) and autoClose={true}"/>
          </Swipeout>
        </View>
      </View>
    );
  }
});

var Listitem = React.createClass({
  render: function() {
    return (
      <View style={styles.li}>
        <Text style={styles.liText}>{this.props.text}</Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: '#f2f2f2',
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
  },
  li: {
    backgroundColor: '#fff',
    borderBottomColor: '#eee',
    borderColor: 'transparent',
    borderWidth: 1,
    paddingLeft: 16,
    paddingTop: 14,
    paddingBottom: 16,
  },
  liContainer: {
    flex: 1,
  },
  liText: {
    color: '#333',
    fontSize: 16,
  },
});

AppRegistry.registerComponent('swipeoutExample', () => swipeoutExample);
<|endoftext|>


<commit_before>'use strict';
var lastEmojiId = 0;
$(document).ready(function() {
 	// Home: calendar function
    $("#datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
            onSelect: function() {
            var dateObject = $(this).datepicker('getDate');
            console.log('Month: '+ dateObject.getMonth()+ ', Date: '+ dateObject.getDate()+ ', Year: '+ dateObject.getFullYear());
            var target = 3;
            $('html, body').animate({
                scrollTop: $('#'+target).offset().top
            }, 500);
        }
    })
    .hide();
    /*.click(function() {
      $(this).hide();
    });*/

    $("#calendar-button").click(function() {
       $("#datepicker").toggle();
       var calendarHeight = $('#datepicker').height();
       if ($('#datepicker').is(':visible')) {
            $('body').css('padding-top', calendarHeight+72+'px');
        }
        else {
            $('body').css('padding-top', 72+'px');
        }
    });
});<commit_msg>scroll to selected date<commit_after>'use strict';
var lastEmojiId = 0;
$(document).ready(function() {
 	// Home: calendar function
    $("#datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
            onSelect: function() {
            var dateObject = $(this).datepicker('getDate');
            console.log('Month: '+ dateObject.getMonth()+ ', Date: '+ dateObject.getDate()+ ', Year: '+ dateObject.getFullYear());

            var dateText = weekday(dateObject.getDay()) + ' ' + monthToString(dateObject.getMonth()) + ' ' +
                        dateObject.getDate() + ', ' + dateObject.getFullYear();
            console.log(dateText);
            var ele = $("p:contains("+ dateText +")");
            //console.log('divID found: ' + ele.offset().top);
            if (ele.length) {
                $('html, body').animate({
                    scrollTop: ele.offset().top - 282
                }, 500);
            }
        }
    })
    .hide();
    /*.click(function() {
      $(this).hide();
    });*/

    $("#calendar-button").click(function() {
       $("#datepicker").toggle();
       var calendarHeight = $('#datepicker').height();
       if ($('#datepicker').is(':visible')) {
            $('body').css('padding-top', calendarHeight+72+'px');
        }
        else {
            $('body').css('padding-top', 72+'px');
        }
    });
});

function weekday(day) {
    //console.log(day.getDay());
    var d;
    switch(day) {
        case 1:
            d = "Mon.";
            break;
        case 2:
            d = "Tue.";
            break;
        case 3:
            d = "Wed.";
            break;
        case 4:
            d = "Thu.";
            break;
        case 5:
            d = "Fri.";
            break;
        case 6:
            d = "Sat.";
            break;
        case 0:
            d = "Sun.";
            break;
    }
    return d;
}

function monthToString(m) {
    var monthText;
    switch(m) {
        case 0:
            monthText = "Jan";
            break;
        case 1:
            monthText = "Feb";
            break;
        case 2:
            monthText = "Mar";
            break;
        case 3:
            monthText = "Apr";
            break;
        case 4:
            monthText = "May";
            break;
        case 5:
            monthText = "Jun";
            break;
        case 6:
            monthText = "Jul";
            break;
        case 7:
            monthText = "Aug";
            break;
        case 8:
            monthText = "Sep";
            break;
        case 9:
            monthText = "Oct";
            break;
        case 10:
            monthText = "Nov";
            break;
        case 11:
            monthText = "Dec";
            break;
    }
    return monthText;
}<|endoftext|>


<commit_before>/***
 * Contains basic SlickGrid editors.
 * @module Editors
 * @namespace Slick
 */

(function ($) {
  // register namespace
  $.extend(true, window, {
    "Slick": {
      "Editors": {
        "Text": TextEditor,
        "Integer": IntegerEditor,
		"Float": FloatEditor,
        "Date": DateEditor,
        "YesNoSelect": YesNoSelectEditor,
        "Checkbox": CheckboxEditor,
        "PercentComplete": PercentCompleteEditor,
        "LongText": LongTextEditor
      }
    }
  });

  function TextEditor(args) {
    var $input;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-text' />")
          .appendTo(args.container)
          .bind("keydown.nav", function (e) {
            if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
              e.stopImmediatePropagation();
            }
          })
          .focus()
          .select();
    };

    this.destroy = function () {
      $input.remove();
    };

    this.focus = function () {
      $input.focus();
    };

    this.getValue = function () {
      return $input.val();
    };

    this.setValue = function (val) {
      $input.val(val);
    };

    this.loadValue = function (item) {
      defaultValue = item[args.column.field] || "";
      $input.val(defaultValue);
      $input[0].defaultValue = defaultValue;
      $input.select();
    };

    this.serializeValue = function () {
      return $input.val();
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      if (args.column.validator) {
        var validationResults = args.column.validator($input.val());
        if (!validationResults.valid) {
          return validationResults;
        }
      }

      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function IntegerEditor(args) {
    var $input;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-text' />");

      $input.bind("keydown.nav", function (e) {
        if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
          e.stopImmediatePropagation();
        }
      });

      $input.appendTo(args.container);
      $input.focus().select();
    };

    this.destroy = function () {
      $input.remove();
    };

    this.focus = function () {
      $input.focus();
    };

    this.loadValue = function (item) {
      defaultValue = item[args.column.field];
      $input.val(defaultValue);
      $input[0].defaultValue = defaultValue;
      $input.select();
    };

    this.serializeValue = function () {
      return parseInt($input.val(), 10) || 0;
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      if (isNaN($input.val())) {
        return {
          valid: false,
          msg: "Please enter a valid integer"
        };
      }

      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function FloatEditor(args) {
    var $input;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-text' />");

      $input.bind("keydown.nav", function (e) {
        if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
          e.stopImmediatePropagation();
        }
      });

      $input.appendTo(args.container);
      $input.focus().select();
    };

    this.destroy = function () {
      $input.remove();
    };

    this.focus = function () {
      $input.focus();
    };

	function getDecimalPlaces() {
		// returns the number of fixed decimal places or null
		var rtn = args.column.editorFixedDecimalPlaces;
		if (!rtn && rtn!==0) {
			rtn = FloatEditor.DefaultDecimalPlaces;
		}
		return (!rtn && rtn!==0 ? null : rtn);
	}

    this.loadValue = function (item) {
      defaultValue = item[args.column.field];

	  var decPlaces = getDecimalPlaces();
	  if (decPlaces !== null
	  && (defaultValue || defaultValue===0)
	  && defaultValue.toFixed) {
		defaultValue = defaultValue.toFixed(decPlaces);
	  }

      $input.val(defaultValue);
      $input[0].defaultValue = defaultValue;
      $input.select();
    };

    this.serializeValue = function () {
	  var rtn = parseFloat($input.val()) || 0;

	  var decPlaces = getDecimalPlaces();
	  if (decPlaces !== null
	  && (rtn || rtn===0)
	  && rtn.toFixed) {
		rtn = parseFloat(rtn.toFixed(decPlaces));
	  }

      return rtn;
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      if (isNaN($input.val())) {
        return {
          valid: false,
          msg: "Please enter a valid number"
        };
      }

      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  FloatEditor.DefaultDecimalPlaces = null;

  function DateEditor(args) {
    var $input;
    var defaultValue;
    var scope = this;
    var calendarOpen = false;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-text' />");
      $input.appendTo(args.container);
      $input.focus().select();
      $input.datepicker({
        showOn: "button",
        buttonImageOnly: true,
        buttonImage: "../images/calendar.gif",
        beforeShow: function () {
          calendarOpen = true
        },
        onClose: function () {
          calendarOpen = false
        }
      });
      $input.width($input.width() - 18);
    };

    this.destroy = function () {
      $.datepicker.dpDiv.stop(true, true);
      $input.datepicker("hide");
      $input.datepicker("destroy");
      $input.remove();
    };

    this.show = function () {
      if (calendarOpen) {
        $.datepicker.dpDiv.stop(true, true).show();
      }
    };

    this.hide = function () {
      if (calendarOpen) {
        $.datepicker.dpDiv.stop(true, true).hide();
      }
    };

    this.position = function (position) {
      if (!calendarOpen) {
        return;
      }
      $.datepicker.dpDiv
          .css("top", position.top + 30)
          .css("left", position.left);
    };

    this.focus = function () {
      $input.focus();
    };

    this.loadValue = function (item) {
      defaultValue = item[args.column.field];
      $input.val(defaultValue);
      $input[0].defaultValue = defaultValue;
      $input.select();
    };

    this.serializeValue = function () {
      return $input.val();
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function YesNoSelectEditor(args) {
    var $select;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $select = $("<SELECT tabIndex='0' class='editor-yesno'><OPTION value='yes'>Yes</OPTION><OPTION value='no'>No</OPTION></SELECT>");
      $select.appendTo(args.container);
      $select.focus();
    };

    this.destroy = function () {
      $select.remove();
    };

    this.focus = function () {
      $select.focus();
    };

    this.loadValue = function (item) {
      $select.val((defaultValue = item[args.column.field]) ? "yes" : "no");
      $select.select();
    };

    this.serializeValue = function () {
      return ($select.val() == "yes");
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return ($select.val() != defaultValue);
    };

    this.validate = function () {
      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function CheckboxEditor(args) {
    var $select;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $select = $("<INPUT type=checkbox value='true' class='editor-checkbox' hideFocus>");
      $select.appendTo(args.container);
      $select.focus();
    };

    this.destroy = function () {
      $select.remove();
    };

    this.focus = function () {
      $select.focus();
    };

    this.loadValue = function (item) {
      defaultValue = !!item[args.column.field];
      if (defaultValue) {
        $select.prop('checked', true);
      } else {
        $select.prop('checked', false);
      }
    };

    this.serializeValue = function () {
      return $select.prop('checked');
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (this.serializeValue() !== defaultValue);
    };

    this.validate = function () {
      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function PercentCompleteEditor(args) {
    var $input, $picker;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-percentcomplete' />");
      $input.width($(args.container).innerWidth() - 25);
      $input.appendTo(args.container);

      $picker = $("
").appendTo(args.container);
      $picker.append("

");

      $picker.find(".editor-percentcomplete-buttons").append("<button val=0>Not started</button>
<button val=50>In Progress</button>
<button val=100>Complete</button>");

      $input.focus().select();

      $picker.find(".editor-percentcomplete-slider").slider({
        orientation: "vertical",
        range: "min",
        value: defaultValue,
        slide: function (event, ui) {
          $input.val(ui.value)
        }
      });

      $picker.find(".editor-percentcomplete-buttons button").bind("click", function (e) {
        $input.val($(this).attr("val"));
        $picker.find(".editor-percentcomplete-slider").slider("value", $(this).attr("val"));
      })
    };

    this.destroy = function () {
      $input.remove();
      $picker.remove();
    };

    this.focus = function () {
      $input.focus();
    };

    this.loadValue = function (item) {
      $input.val(defaultValue = item[args.column.field]);
      $input.select();
    };

    this.serializeValue = function () {
      return parseInt($input.val(), 10) || 0;
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ((parseInt($input.val(), 10) || 0) != defaultValue);
    };

    this.validate = function () {
      if (isNaN(parseInt($input.val(), 10))) {
        return {
          valid: false,
          msg: "Please enter a valid positive number"
        };
      }

      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  /*
   * An example of a "detached" editor.
   * The UI is added onto document BODY and .position(), .show() and .hide() are implemented.
   * KeyDown events are also handled to provide handling for Tab, Shift-Tab, Esc and Ctrl-Enter.
   */
  function LongTextEditor(args) {
    var $input, $wrapper;
    var defaultValue;
    var scope = this;

    this.init = function () {
      var $container = $("body");

      $wrapper = $("
")
          .appendTo($container);

      $input = $("<TEXTAREA hidefocus rows=5 style='backround:white;width:250px;height:80px;border:0;outline:0'>")
          .appendTo($wrapper);

      $("
<BUTTON>Save</BUTTON><BUTTON>Cancel</BUTTON>
")
          .appendTo($wrapper);

      $wrapper.find("button:first").bind("click", this.save);
      $wrapper.find("button:last").bind("click", this.cancel);
      $input.bind("keydown", this.handleKeyDown);

      scope.position(args.position);
      $input.focus().select();
    };

    this.handleKeyDown = function (e) {
      if (e.which == $.ui.keyCode.ENTER && e.ctrlKey) {
        scope.save();
      } else if (e.which == $.ui.keyCode.ESCAPE) {
        e.preventDefault();
        scope.cancel();
      } else if (e.which == $.ui.keyCode.TAB && e.shiftKey) {
        e.preventDefault();
        args.grid.navigatePrev();
      } else if (e.which == $.ui.keyCode.TAB) {
        e.preventDefault();
        args.grid.navigateNext();
      }
    };

    this.save = function () {
      args.commitChanges();
    };

    this.cancel = function () {
      $input.val(defaultValue);
      args.cancelChanges();
    };

    this.hide = function () {
      $wrapper.hide();
    };

    this.show = function () {
      $wrapper.show();
    };

    this.position = function (position) {
      $wrapper
          .css("top", position.top - 5)
          .css("left", position.left - 5)
    };

    this.destroy = function () {
      $wrapper.remove();
    };

    this.focus = function () {
      $input.focus();
    };

    this.loadValue = function (item) {
      $input.val(defaultValue = item[args.column.field]);
      $input.select();
    };

    this.serializeValue = function () {
      return $input.val();
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }
})(jQuery);
<commit_msg>allow null column setting to override editor default<commit_after>/***
 * Contains basic SlickGrid editors.
 * @module Editors
 * @namespace Slick
 */

(function ($) {
  // register namespace
  $.extend(true, window, {
    "Slick": {
      "Editors": {
        "Text": TextEditor,
        "Integer": IntegerEditor,
		"Float": FloatEditor,
        "Date": DateEditor,
        "YesNoSelect": YesNoSelectEditor,
        "Checkbox": CheckboxEditor,
        "PercentComplete": PercentCompleteEditor,
        "LongText": LongTextEditor
      }
    }
  });

  function TextEditor(args) {
    var $input;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-text' />")
          .appendTo(args.container)
          .bind("keydown.nav", function (e) {
            if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
              e.stopImmediatePropagation();
            }
          })
          .focus()
          .select();
    };

    this.destroy = function () {
      $input.remove();
    };

    this.focus = function () {
      $input.focus();
    };

    this.getValue = function () {
      return $input.val();
    };

    this.setValue = function (val) {
      $input.val(val);
    };

    this.loadValue = function (item) {
      defaultValue = item[args.column.field] || "";
      $input.val(defaultValue);
      $input[0].defaultValue = defaultValue;
      $input.select();
    };

    this.serializeValue = function () {
      return $input.val();
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      if (args.column.validator) {
        var validationResults = args.column.validator($input.val());
        if (!validationResults.valid) {
          return validationResults;
        }
      }

      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function IntegerEditor(args) {
    var $input;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-text' />");

      $input.bind("keydown.nav", function (e) {
        if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
          e.stopImmediatePropagation();
        }
      });

      $input.appendTo(args.container);
      $input.focus().select();
    };

    this.destroy = function () {
      $input.remove();
    };

    this.focus = function () {
      $input.focus();
    };

    this.loadValue = function (item) {
      defaultValue = item[args.column.field];
      $input.val(defaultValue);
      $input[0].defaultValue = defaultValue;
      $input.select();
    };

    this.serializeValue = function () {
      return parseInt($input.val(), 10) || 0;
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      if (isNaN($input.val())) {
        return {
          valid: false,
          msg: "Please enter a valid integer"
        };
      }

      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function FloatEditor(args) {
    var $input;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-text' />");

      $input.bind("keydown.nav", function (e) {
        if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
          e.stopImmediatePropagation();
        }
      });

      $input.appendTo(args.container);
      $input.focus().select();
    };

    this.destroy = function () {
      $input.remove();
    };

    this.focus = function () {
      $input.focus();
    };

	function getDecimalPlaces() {
		// returns the number of fixed decimal places or null
		var rtn = args.column.editorFixedDecimalPlaces;
		if (typeof rtn == 'undefined') {
			rtn = FloatEditor.DefaultDecimalPlaces;
		}
		return (!rtn && rtn!==0 ? null : rtn);
	}

    this.loadValue = function (item) {
      defaultValue = item[args.column.field];

	  var decPlaces = getDecimalPlaces();
	  if (decPlaces !== null
	  && (defaultValue || defaultValue===0)
	  && defaultValue.toFixed) {
		defaultValue = defaultValue.toFixed(decPlaces);
	  }

      $input.val(defaultValue);
      $input[0].defaultValue = defaultValue;
      $input.select();
    };

    this.serializeValue = function () {
	  var rtn = parseFloat($input.val()) || 0;

	  var decPlaces = getDecimalPlaces();
	  if (decPlaces !== null
	  && (rtn || rtn===0)
	  && rtn.toFixed) {
		rtn = parseFloat(rtn.toFixed(decPlaces));
	  }

      return rtn;
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      if (isNaN($input.val())) {
        return {
          valid: false,
          msg: "Please enter a valid number"
        };
      }

      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  FloatEditor.DefaultDecimalPlaces = null;

  function DateEditor(args) {
    var $input;
    var defaultValue;
    var scope = this;
    var calendarOpen = false;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-text' />");
      $input.appendTo(args.container);
      $input.focus().select();
      $input.datepicker({
        showOn: "button",
        buttonImageOnly: true,
        buttonImage: "../images/calendar.gif",
        beforeShow: function () {
          calendarOpen = true
        },
        onClose: function () {
          calendarOpen = false
        }
      });
      $input.width($input.width() - 18);
    };

    this.destroy = function () {
      $.datepicker.dpDiv.stop(true, true);
      $input.datepicker("hide");
      $input.datepicker("destroy");
      $input.remove();
    };

    this.show = function () {
      if (calendarOpen) {
        $.datepicker.dpDiv.stop(true, true).show();
      }
    };

    this.hide = function () {
      if (calendarOpen) {
        $.datepicker.dpDiv.stop(true, true).hide();
      }
    };

    this.position = function (position) {
      if (!calendarOpen) {
        return;
      }
      $.datepicker.dpDiv
          .css("top", position.top + 30)
          .css("left", position.left);
    };

    this.focus = function () {
      $input.focus();
    };

    this.loadValue = function (item) {
      defaultValue = item[args.column.field];
      $input.val(defaultValue);
      $input[0].defaultValue = defaultValue;
      $input.select();
    };

    this.serializeValue = function () {
      return $input.val();
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function YesNoSelectEditor(args) {
    var $select;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $select = $("<SELECT tabIndex='0' class='editor-yesno'><OPTION value='yes'>Yes</OPTION><OPTION value='no'>No</OPTION></SELECT>");
      $select.appendTo(args.container);
      $select.focus();
    };

    this.destroy = function () {
      $select.remove();
    };

    this.focus = function () {
      $select.focus();
    };

    this.loadValue = function (item) {
      $select.val((defaultValue = item[args.column.field]) ? "yes" : "no");
      $select.select();
    };

    this.serializeValue = function () {
      return ($select.val() == "yes");
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return ($select.val() != defaultValue);
    };

    this.validate = function () {
      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function CheckboxEditor(args) {
    var $select;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $select = $("<INPUT type=checkbox value='true' class='editor-checkbox' hideFocus>");
      $select.appendTo(args.container);
      $select.focus();
    };

    this.destroy = function () {
      $select.remove();
    };

    this.focus = function () {
      $select.focus();
    };

    this.loadValue = function (item) {
      defaultValue = !!item[args.column.field];
      if (defaultValue) {
        $select.prop('checked', true);
      } else {
        $select.prop('checked', false);
      }
    };

    this.serializeValue = function () {
      return $select.prop('checked');
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (this.serializeValue() !== defaultValue);
    };

    this.validate = function () {
      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  function PercentCompleteEditor(args) {
    var $input, $picker;
    var defaultValue;
    var scope = this;

    this.init = function () {
      $input = $("<INPUT type=text class='editor-percentcomplete' />");
      $input.width($(args.container).innerWidth() - 25);
      $input.appendTo(args.container);

      $picker = $("
").appendTo(args.container);
      $picker.append("

");

      $picker.find(".editor-percentcomplete-buttons").append("<button val=0>Not started</button>
<button val=50>In Progress</button>
<button val=100>Complete</button>");

      $input.focus().select();

      $picker.find(".editor-percentcomplete-slider").slider({
        orientation: "vertical",
        range: "min",
        value: defaultValue,
        slide: function (event, ui) {
          $input.val(ui.value)
        }
      });

      $picker.find(".editor-percentcomplete-buttons button").bind("click", function (e) {
        $input.val($(this).attr("val"));
        $picker.find(".editor-percentcomplete-slider").slider("value", $(this).attr("val"));
      })
    };

    this.destroy = function () {
      $input.remove();
      $picker.remove();
    };

    this.focus = function () {
      $input.focus();
    };

    this.loadValue = function (item) {
      $input.val(defaultValue = item[args.column.field]);
      $input.select();
    };

    this.serializeValue = function () {
      return parseInt($input.val(), 10) || 0;
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ((parseInt($input.val(), 10) || 0) != defaultValue);
    };

    this.validate = function () {
      if (isNaN(parseInt($input.val(), 10))) {
        return {
          valid: false,
          msg: "Please enter a valid positive number"
        };
      }

      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }

  /*
   * An example of a "detached" editor.
   * The UI is added onto document BODY and .position(), .show() and .hide() are implemented.
   * KeyDown events are also handled to provide handling for Tab, Shift-Tab, Esc and Ctrl-Enter.
   */
  function LongTextEditor(args) {
    var $input, $wrapper;
    var defaultValue;
    var scope = this;

    this.init = function () {
      var $container = $("body");

      $wrapper = $("
")
          .appendTo($container);

      $input = $("<TEXTAREA hidefocus rows=5 style='backround:white;width:250px;height:80px;border:0;outline:0'>")
          .appendTo($wrapper);

      $("
<BUTTON>Save</BUTTON><BUTTON>Cancel</BUTTON>
")
          .appendTo($wrapper);

      $wrapper.find("button:first").bind("click", this.save);
      $wrapper.find("button:last").bind("click", this.cancel);
      $input.bind("keydown", this.handleKeyDown);

      scope.position(args.position);
      $input.focus().select();
    };

    this.handleKeyDown = function (e) {
      if (e.which == $.ui.keyCode.ENTER && e.ctrlKey) {
        scope.save();
      } else if (e.which == $.ui.keyCode.ESCAPE) {
        e.preventDefault();
        scope.cancel();
      } else if (e.which == $.ui.keyCode.TAB && e.shiftKey) {
        e.preventDefault();
        args.grid.navigatePrev();
      } else if (e.which == $.ui.keyCode.TAB) {
        e.preventDefault();
        args.grid.navigateNext();
      }
    };

    this.save = function () {
      args.commitChanges();
    };

    this.cancel = function () {
      $input.val(defaultValue);
      args.cancelChanges();
    };

    this.hide = function () {
      $wrapper.hide();
    };

    this.show = function () {
      $wrapper.show();
    };

    this.position = function (position) {
      $wrapper
          .css("top", position.top - 5)
          .css("left", position.left - 5)
    };

    this.destroy = function () {
      $wrapper.remove();
    };

    this.focus = function () {
      $input.focus();
    };

    this.loadValue = function (item) {
      $input.val(defaultValue = item[args.column.field]);
      $input.select();
    };

    this.serializeValue = function () {
      return $input.val();
    };

    this.applyValue = function (item, state) {
      item[args.column.field] = state;
    };

    this.isValueChanged = function () {
      return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
    };

    this.validate = function () {
      return {
        valid: true,
        msg: null
      };
    };

    this.init();
  }
})(jQuery);
<|endoftext|>


<commit_before>var Tessy = window.Tessy || {};

var Helper =  {

  setDropDownText : function(){

    var params = window.location.pathname.split("/").slice(2,5);
    if( params.length > 0){
      var dropDowns = document.querySelectorAll(".span10 button");
      params.map(function(param, index){
        dropDowns[index].innerHTML = param + '';
      });
    }

  },

  highlightTblRow  : function(tblSelector, highlightClass){

   $(tblSelector).on("click", function(evt){
     var row = evt.target.parentNode;
     if(row.className == highlightClass){

      $(row).removeClass(highlightClass)
    }else{

      $(row).addClass(highlightClass);
    }
   });

  }

};

var TestCases = Backbone.Model.extend({

  getSteps : function(stepIds){

   return $.ajax({
           type: "GET",
           url: "/api/steps/getById",
           data: { stepIds : stepIds }
        });
  },

  saveSteps : function(steps){

   return $.ajax({
            type: "POST",
            url: "/api/steps/updateById",
            data: { steps: steps }
          });
  }
});

var Modal = Backbone.Model.extend({

  initialize: function(modal){
   this.modal = modal;
  },

  setTitle: function(newTitle){
    $(this.modal + " .modal-title").html(newTitle);
  },

  setStatus: function(type, msg){
    $(this.modal + " .modal-body-status").addClass('alert-'+type).html(msg);
  },

  clearStatus: function(){
    $(this.modal + " .modal-body-status").removeClass('alert-danger').removeClass('alert-success').html('');
  },

  setBody: function(content){
    $(this.modal + " .modal-body").html(content);
  },

  editStep: function(evt){
    var stepId         = evt.target.dataset.id;
    var stepText       = evt.target.innerHTML
    var row            = evt.target;
    var rowInput       = document.createElement("input");
    rowInput.name      = stepId;
    rowInput.value     = stepText;
    rowInput.className = 'steps-input';
    row.innerHTML      = '';
    row.appendChild(rowInput);
  },

  addStep: function(){

  },

  setFooter: function(data){
   $(this.modal + " .modal-footer");
  },

  toggle: function(toggle, delay){

     var delay = delay || 0;
     if(toggle === 'hide'){
      var that = this;
      window.setTimeout(function(){
        $(that.modal).modal(toggle)
        that.setTitle('');
        that.setBody('');
        that.clearStatus();
      }, delay);

     }else{
        $(this.modal).modal(toggle);
  }  }

});

<commit_msg>bug fix: this condition would not return true if there are more than 1 class on the element<commit_after>var Tessy = window.Tessy || {};

var Helper =  {

  setDropDownText : function(){

    var params = window.location.pathname.split("/").slice(2,5);
    if( params.length > 0){
      var dropDowns = document.querySelectorAll(".span10 button");
      params.map(function(param, index){
        dropDowns[index].innerHTML = param + '';
      });
    }

  },

  highlightTblRow  : function(tblSelector, highlightClass){

   $(tblSelector).on("click", function(evt){
     var row = evt.target.parentNode;
     if($(row).hasClass(highlightClass)){

      $(row).removeClass(highlightClass)
    }else{

      $(row).addClass(highlightClass);
    }
   });

  }

};

var TestCases = Backbone.Model.extend({

  getSteps : function(stepIds){

   return $.ajax({
           type: "GET",
           url: "/api/steps/getById",
           data: { stepIds : stepIds }
        });
  },

  saveSteps : function(steps){

   return $.ajax({
            type: "POST",
            url: "/api/steps/updateById",
            data: { steps: steps }
          });
  }
});

var Modal = Backbone.Model.extend({

  initialize: function(modal){
   this.modal = modal;
  },

  setTitle: function(newTitle){
    $(this.modal + " .modal-title").html(newTitle);
  },

  setStatus: function(type, msg){
    $(this.modal + " .modal-body-status").addClass('alert-'+type).html(msg);
  },

  clearStatus: function(){
    $(this.modal + " .modal-body-status").removeClass('alert-danger').removeClass('alert-success').html('');
  },

  setBody: function(content){
    $(this.modal + " .modal-body").html(content);
  },

  editStep: function(evt){
    var stepId         = evt.target.dataset.id;
    var stepText       = evt.target.innerHTML
    var row            = evt.target;
    var rowInput       = document.createElement("input");
    rowInput.name      = stepId;
    rowInput.value     = stepText;
    rowInput.className = 'steps-input';
    row.innerHTML      = '';
    row.appendChild(rowInput);
  },

  addStep: function(){

  },

  setFooter: function(data){
   $(this.modal + " .modal-footer");
  },

  toggle: function(toggle, delay){

     var delay = delay || 0;
     if(toggle === 'hide'){
      var that = this;
      window.setTimeout(function(){
        $(that.modal).modal(toggle)
        that.setTitle('');
        that.setBody('');
        that.clearStatus();
      }, delay);

     }else{
        $(this.modal).modal(toggle);
  }  }

});

<|endoftext|>


<commit_before>
angular.module('umbraco')
.controller('DigitalMomentum.Videolizer.Search',
		function ($http, $scope) {
			$scope.hideLabel = "true"; //Hides the modal Dialog label at the top of the page

	$scope.model = {
		searchTerm: "",
		ytApi: $scope.dialogData.ytApi,
		ytChannelId: $scope.dialogData.ytChannelId,
		vimeoApi: $scope.dialogData.vimeoApi,
		searchType: $scope.dialogData.defaultSearchType
	}

	$scope.results = {
		yt: [],
		vimeo: []
	}

	function init() {
		$scope.search(); //Run defaut search to get list of latest videos

		//Select the appropriate Default Radio
		//if ($scope.model.ytApi) {
		//	if ($scope.model.ytChannelId) {
		//		$scope.searchType = "ytChannel";
		//	} else {
		//		$scope.searchType = "ytAll";
		//	}

		//}
	}

	function searchYouTube(searchTerm) {
		var ApiUrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&key=' + $scope.dialogData.ytApi
		var hasASearch = false;

		var req = {
			method: 'GET',
			url: ApiUrl,
			headers: {
				'Content-Type': "json",

			},
			umbIgnoreErrors:true
			//data: { test: 'test' }
		}

		if (searchTerm) {

			req.url += '&q=' + searchTerm;

			hasASearch = true;
		}

		if ($scope.model.searchType == "ytChannel") {
			req.url += "&channelId=" + $scope.model.ytChannelId
			if (searchTerm == "") {
				//We are getting the latest from our channel
				req.url += "&order=date";
			}
			hasASearch = true;
		}

		$http(req).then(function successCallback(response) {
			// this callback will be called asynchronously
			// when the response is available
			//console.log(response);
			$scope.results.yt = response.data.items;
		}, function errorCallback(response) {
			// called asynchronously if an error occurs
			// or server returns response with an error status.
		});

	}

	function searchVimeo(searchTerm) {
		var ApiUrl = 'https://api.vimeo.com/';
		if ($scope.model.searchType == "vimeoChannel"){
			//Get from my channel
			ApiUrl += "me/";
			hasASearch = true; //Auto load my videos
		}
		ApiUrl += "videos?per_page=8&access_token=" + $scope.dialogData.vimeoApi;

		var req = {
			method: 'GET',
			url: ApiUrl,
			headers: {
				'Content-Type': "json",

			},
			umbIgnoreErrors: true
			//data: { test: 'test' }
		}

		if (searchTerm) {
			req.url += '&query=' + searchTerm;
			hasASearch = true;
		}

		$http(req).then(function successCallback(response) {
			// this callback will be called asynchronously
			// when the response is available
			console.log(response);

			var regExp = /\/(\d+)($|\/)/;

			angular.forEach(response.data.data, function (video, key) {
				var match = video.uri.match(regExp);
				if (match) {
					video.kind = "Vimeo";
					video.id = match[1];
				}
			});

			$scope.results.vimeo = response.data.data;
		}, function errorCallback(response) {
			// called asynchronously if an error occurs
			// or server returns response with an error status.
		});
	}

	$scope.search = function () {
		console.log($scope.model.searchType)
		$scope.results.yt = [];
		$scope.results.vimeo = [];
		var hasASearch = false;
		var searchTerm = $scope.model.searchTerm;
		if ($scope.model.searchType == "ytChannel" || $scope.model.searchType == "ytAll") {
			searchYouTube(searchTerm);
			return;
		} else {
			searchVimeo(searchTerm);
			return;
		}
	}

	$scope.selectVideo = function (video) {
		console.log(video);
		var videoInfo = {};
		if (video.kind == "Vimeo") {
			videoInfo.id = video.id;
			videoInfo.type = "Vimeo";
			videoInfo.url = "https://vimeo.com/" + video.id;
			videoInfo.embedUrl = "https://player.vimeo.com/video/" + video.id;
		} else {
			//YouTube
			videoInfo.id = video.id.videoId;
			videoInfo.type = "YouTube";
			videoInfo.url = "https://www.youtube.com/watch?v=" + video.id.videoId;
			videoInfo.embedUrl = "https://www.youtube.com/embed/" + video.id.videoId;
		}
		console.log(videoInfo);
		$scope.submit(videoInfo);
	}

	init();

});<commit_msg>Ad some comments so I know what I'm doing!<commit_after>
angular.module('umbraco')
.controller('DigitalMomentum.Videolizer.Search',
		function ($http, $scope) {
			$scope.hideLabel = "true"; //Hides the modal Dialog label at the top of the page

	$scope.model = {
		searchTerm: "",
		ytApi: $scope.dialogData.ytApi,
		ytChannelId: $scope.dialogData.ytChannelId,
		vimeoApi: $scope.dialogData.vimeoApi,
		searchType: $scope.dialogData.defaultSearchType
	}

	$scope.results = {
		yt: [],
		vimeo: []
	}

	function init() {
		$scope.search(); //Run defaut search to get list of latest videos

		//Select the appropriate Default Radio
		//if ($scope.model.ytApi) {
		//	if ($scope.model.ytChannelId) {
		//		$scope.searchType = "ytChannel";
		//	} else {
		//		$scope.searchType = "ytAll";
		//	}

		//}
	}

	function searchYouTube(searchTerm) {
		var ApiUrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&key=' + $scope.dialogData.ytApi
		var hasASearch = false;

		var req = {
			method: 'GET',
			url: ApiUrl,
			headers: {
				'Content-Type': "json",

			},
			umbIgnoreErrors: true //Tell Umbraco to ignore the errors - http://issues.umbraco.org/issue/U4-5588
			//data: { test: 'test' }
		}

		if (searchTerm) {

			req.url += '&q=' + searchTerm;

			hasASearch = true;
		}

		if ($scope.model.searchType == "ytChannel") {
			req.url += "&channelId=" + $scope.model.ytChannelId
			if (searchTerm == "") {
				//We are getting the latest from our channel
				req.url += "&order=date";
			}
			hasASearch = true;
		}

		$http(req).then(function successCallback(response) {
			// this callback will be called asynchronously
			// when the response is available
			//console.log(response);
			$scope.results.yt = response.data.items;
		}, function errorCallback(response) {
			// called asynchronously if an error occurs
			// or server returns response with an error status.
		});

	}

	function searchVimeo(searchTerm) {
		var ApiUrl = 'https://api.vimeo.com/';
		if ($scope.model.searchType == "vimeoChannel"){
			//Get from my channel
			ApiUrl += "me/";
			hasASearch = true; //Auto load my videos
		}
		ApiUrl += "videos?per_page=8&access_token=" + $scope.dialogData.vimeoApi;

		var req = {
			method: 'GET',
			url: ApiUrl,
			headers: {
				'Content-Type': "json",

			},
			umbIgnoreErrors: true //Tell Umbraco to ignore the errors - http://issues.umbraco.org/issue/U4-5588
			//data: { test: 'test' }
		}

		if (searchTerm) {
			req.url += '&query=' + searchTerm;
			hasASearch = true;
		}

		$http(req).then(function successCallback(response) {
			// this callback will be called asynchronously
			// when the response is available
			console.log(response);

			var regExp = /\/(\d+)($|\/)/;

			angular.forEach(response.data.data, function (video, key) {
				var match = video.uri.match(regExp);
				if (match) {
					video.kind = "Vimeo";
					video.id = match[1];
				}
			});

			$scope.results.vimeo = response.data.data;
		}, function errorCallback(response) {
			// called asynchronously if an error occurs
			// or server returns response with an error status.
		});
	}

	$scope.search = function () {
		console.log($scope.model.searchType)
		$scope.results.yt = [];
		$scope.results.vimeo = [];
		var hasASearch = false;
		var searchTerm = $scope.model.searchTerm;
		if ($scope.model.searchType == "ytChannel" || $scope.model.searchType == "ytAll") {
			searchYouTube(searchTerm);
			return;
		} else {
			searchVimeo(searchTerm);
			return;
		}
	}

	$scope.selectVideo = function (video) {
		console.log(video);
		var videoInfo = {};
		if (video.kind == "Vimeo") {
			videoInfo.id = video.id;
			videoInfo.type = "Vimeo";
			videoInfo.url = "https://vimeo.com/" + video.id;
			videoInfo.embedUrl = "https://player.vimeo.com/video/" + video.id;
		} else {
			//YouTube
			videoInfo.id = video.id.videoId;
			videoInfo.type = "YouTube";
			videoInfo.url = "https://www.youtube.com/watch?v=" + video.id.videoId;
			videoInfo.embedUrl = "https://www.youtube.com/embed/" + video.id.videoId;
		}
		console.log(videoInfo);
		$scope.submit(videoInfo);
	}

	init();

});<|endoftext|>


<commit_before>import React from 'react';
import { Route, IndexRoute } from 'react-router';
import { LOGIN_ROUTE, ADMIN_ROUTE } from '../constants/routeConstants';

import loginStore from '../stores/LoginStore';

import NoMatch from '../components/NoMatch';
import NoMatchAdmin from '../components/NoMatchAdmin';

import App from '../components/App';

import LandingPage from '../components/Landing/LandingPage';
import BasketSummaryPage from '../components/Checkout/BasketSummaryPage';
import GiverDetailsPage from '../components/Checkout/GiverDetailsPage';
import ConfirmationPage from '../components/Checkout/ConfirmationPage';

import LoginPage from '../components/Login/LoginPage';
import ProfilePage from '../components/Profile/ProfilePage';
import SetupPage from '../components/Setup/SetupPage';
import Admin from '../components/Admin';
import AuthenticatedLanding from '../components/AuthenticatedLanding';
import CoverPage from '../components/Cover/CoverPage';
import AboutUsPage from '../components/AboutUs/AboutUsPage';
import RsvpPage from '../components/Rsvp/RsvpPage';
import AboutOurDayPage from '../components/AboutOurDay/AboutOurDayPage';
import LocalFlavourPage from '../components/LocalFlavour/LocalFlavourPage';
import OnTheDayPage from '../components/OnTheDay/OnTheDayPage';
import WeddingPlaylistPage from '../components/WeddingPlaylist/WeddingPlaylistPage';
import AboutOurHoneymoonPage from '../components/AboutOurHoneymoon/AboutOurHoneymoonPage';
import HoneymoonGiftListItemPage from '../components/HoneymoonGiftListItem/HoneymoonGiftListItemPage';
import HoneymoonGiftListPage from '../components/HoneymoonGiftList/HoneymoonGiftListPage';
import UsersPage from '../components/Users/UsersPage';
import GiftSetsPage from '../components/GiftSet/GiftSetsPage';
import GiftSetPage from '../components/GiftSet/GiftSetPage';
import ResetPage from '../components/Reset/ResetPage';
import WeddingPartyMembersPage from '../components/WeddingPartyMembers/WeddingPartyMembersPage';
import CreateWeddingPartyMemberPage from '../components/WeddingPartyMembers/CreateWeddingPartyMemberPage';
import UpdateWeddingPartyMemberPage from '../components/WeddingPartyMembers/UpdateWeddingPartyMemberPage';

function requireAuth(nextState, replace) {
    const { isLoggedIn } = loginStore.getState();

    if (!isLoggedIn) {
        replace(LOGIN_ROUTE);
    }
}

function ifLoggedInRedirectToAdmin(nextState, replace) {
    const { isLoggedIn } = loginStore.getState();

    if (isLoggedIn) {
        replace(ADMIN_ROUTE);
    }
}

export default (
    <Route path="/" component={App}>
        <IndexRoute component={LandingPage} />
        <Route path="basket" component={BasketSummaryPage} />
        <Route path="giver" component={GiverDetailsPage} />
        <Route path="confirmation/:giftSetId" component={ConfirmationPage} />
        <Route path="admin" component={Admin}>
            <IndexRoute component={AuthenticatedLanding} onEnter={requireAuth} />
            <Route path="login" component={LoginPage} onEnter={ifLoggedInRedirectToAdmin} />
            <Route path="setup" component={SetupPage} onEnter={ifLoggedInRedirectToAdmin} />
            <Route path="reset/:token" component={ResetPage} onEnter={ifLoggedInRedirectToAdmin} />
            <Route path="profile" component={ProfilePage} onEnter={requireAuth} />
            <Route path="cover" component={CoverPage} onEnter={requireAuth} />
            <Route path="aboutUs" component={AboutUsPage} onEnter={requireAuth} />
            <Route path="rsvp" component={RsvpPage} onEnter={requireAuth} />
            <Route path="aboutOurDay" component={AboutOurDayPage} onEnter={requireAuth} />
            <Route path="localFlavour" component={LocalFlavourPage} onEnter={requireAuth} />
            <Route path="onTheDay" component={OnTheDayPage} onEnter={requireAuth} />
            <Route path="weddingPlaylist" component={WeddingPlaylistPage} onEnter={requireAuth} />
            <Route path="aboutOurHoneymoon" component={AboutOurHoneymoonPage} onEnter={requireAuth} />
            <Route path="honeymoonGiftList" component={HoneymoonGiftListPage} onEnter={requireAuth} />
            <Route path="honeymoonGiftListItem" component={HoneymoonGiftListItemPage} onEnter={requireAuth} />
            <Route path="users" component={UsersPage} onEnter={requireAuth} />
            <Route path="giftSet" component={GiftSetsPage} onEnter={requireAuth} />
            <Route path="giftSet/:giftSetId" component={GiftSetPage} onEnter={requireAuth} />
            <Route path="weddingPartyMember" component={WeddingPartyMembersPage} onEnter={requireAuth} />
            <Route path="weddingPartyMember/create" component={CreateWeddingPartyMemberPage} onEnter={requireAuth} />
            <Route path="weddingPartyMember/:id" component={UpdateWeddingPartyMemberPage} onEnter={requireAuth} />
            <Route path="*" component={NoMatchAdmin} />
        </Route>
        <Route path="*" component={NoMatch} />
    </Route>
);
<commit_msg>tidy up routes<commit_after>import React from 'react';
import { Route, IndexRoute } from 'react-router';
import { LOGIN_ROUTE, ADMIN_ROUTE } from '../constants/routeConstants';

import loginStore from '../stores/LoginStore';

import NoMatch from '../components/NoMatch';
import NoMatchAdmin from '../components/NoMatchAdmin';

import App from '../components/App';

import LandingPage from '../components/Landing/LandingPage';
import BasketSummaryPage from '../components/Checkout/BasketSummaryPage';
import GiverDetailsPage from '../components/Checkout/GiverDetailsPage';
import ConfirmationPage from '../components/Checkout/ConfirmationPage';

import LoginPage from '../components/Login/LoginPage';
import ProfilePage from '../components/Profile/ProfilePage';
import SetupPage from '../components/Setup/SetupPage';
import Admin from '../components/Admin';
import AuthenticatedLanding from '../components/AuthenticatedLanding';
import CoverPage from '../components/Cover/CoverPage';
import AboutUsPage from '../components/AboutUs/AboutUsPage';
import RsvpPage from '../components/Rsvp/RsvpPage';
import AboutOurDayPage from '../components/AboutOurDay/AboutOurDayPage';
import LocalFlavourPage from '../components/LocalFlavour/LocalFlavourPage';
import OnTheDayPage from '../components/OnTheDay/OnTheDayPage';
import WeddingPlaylistPage from '../components/WeddingPlaylist/WeddingPlaylistPage';
import AboutOurHoneymoonPage from '../components/AboutOurHoneymoon/AboutOurHoneymoonPage';
import HoneymoonGiftListItemPage from '../components/HoneymoonGiftListItem/HoneymoonGiftListItemPage';
import HoneymoonGiftListPage from '../components/HoneymoonGiftList/HoneymoonGiftListPage';
import UsersPage from '../components/Users/UsersPage';
import GiftSetsPage from '../components/GiftSet/GiftSetsPage';
import GiftSetPage from '../components/GiftSet/GiftSetPage';
import ResetPage from '../components/Reset/ResetPage';
import WeddingPartyMembersPage from '../components/WeddingPartyMembers/WeddingPartyMembersPage';
import CreateWeddingPartyMemberPage from '../components/WeddingPartyMembers/CreateWeddingPartyMemberPage';
import UpdateWeddingPartyMemberPage from '../components/WeddingPartyMembers/UpdateWeddingPartyMemberPage';

function requireAuth(nextState, replace) {
    const { isLoggedIn } = loginStore.getState();

    if (!isLoggedIn) {
        replace(LOGIN_ROUTE);
    }
}

function ifLoggedInRedirectToAdmin(nextState, replace) {
    const { isLoggedIn } = loginStore.getState();

    if (isLoggedIn) {
        replace(ADMIN_ROUTE);
    }
}

export default (
    <Route path="/" component={App}>
        <IndexRoute component={LandingPage} />
        <Route path="basket" component={BasketSummaryPage} />
        <Route path="giver" component={GiverDetailsPage} />
        <Route path="confirmation/:giftSetId" component={ConfirmationPage} />
        <Route path="admin" component={Admin}>
            <IndexRoute component={AuthenticatedLanding} onEnter={requireAuth} />

            <Route onEnter={ifLoggedInRedirectToAdmin}>
                <Route path="login" component={LoginPage} />
                <Route path="setup" component={SetupPage} />
                <Route path="reset/:token" component={ResetPage} />
            </Route>

            <Route onEnter={requireAuth}>
                <Route path="profile" component={ProfilePage} />
                <Route path="cover" component={CoverPage} />
                <Route path="aboutUs" component={AboutUsPage} />
                <Route path="rsvp" component={RsvpPage} />
                <Route path="aboutOurDay" component={AboutOurDayPage} />
                <Route path="localFlavour" component={LocalFlavourPage} />
                <Route path="onTheDay" component={OnTheDayPage} />
                <Route path="weddingPlaylist" component={WeddingPlaylistPage} />
                <Route path="aboutOurHoneymoon" component={AboutOurHoneymoonPage} />
                <Route path="honeymoonGiftList" component={HoneymoonGiftListPage} />
                <Route path="honeymoonGiftListItem" component={HoneymoonGiftListItemPage} />
                <Route path="users" component={UsersPage} />
                <Route path="giftSet" component={GiftSetsPage} />
                <Route path="giftSet/:giftSetId" component={GiftSetPage} />
                <Route path="weddingPartyMember" component={WeddingPartyMembersPage} />
                <Route path="weddingPartyMember/create" component={CreateWeddingPartyMemberPage} />
                <Route path="weddingPartyMember/:id" component={UpdateWeddingPartyMemberPage} />
            </Route>

            <Route path="*" component={NoMatchAdmin} />
        </Route>
        <Route path="*" component={NoMatch} />
    </Route>
);
<|endoftext|>