<commit_before>import React from 'react';
import { StyleSheet, View, Text } from 'react-native'
import { connect } from 'react-redux';

import * as session from '../../actions/session';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 20,
  },
});

class SessionScreen extends React.Component {
  static propTypes = {

  };

  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      allSessions: []
    }
  }

  componentWillReceiveProps(nextProps) {
  }

  componentDidMount() {

  }
  render() {
    let output = [];

    return (
      <View>
        <Text>Sessions will be here...</Text>
      </View>
    )
  }
}

//const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

const mapStateToProps = (state) => {
  return {
    sessionsData: state.sessions
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    fetchAllSessions : () => {

    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(SessionScreen);

<commit_msg>fixed faulty ListView<commit_after>import React from 'react';
import { StyleSheet, View, Text } from 'react-native'
import { connect } from 'react-redux';

import * as session from '../../actions/session';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 20,
  },
});

class SessionScreen extends React.Component {
  static propTypes = {

  };

  constructor(props) {
    super(props);
    // const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      allSessions: []
    }
  }

  componentWillReceiveProps(nextProps) {
  }

  componentDidMount() {

  }
  render() {
    let output = [];

    return (
      <View>
        <Text>Sessions will be here...</Text>
      </View>
    )
  }
}

//const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

const mapStateToProps = (state) => {
  return {
    sessionsData: state.sessions
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    fetchAllSessions : () => {

    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(SessionScreen);

<|endoftext|>


<commit_before>
function fetch(regex, data)
{
	var array = [];
	while(item = regex.exec(data))
		array.push(item[1]);
	return array;
}

function append_td(tr, value) {
	append(tr, 'td').innerHTML = value ? value : "?";
}

function wifi_scan()
{
	var s = $('wifiscan_selection');
	var device = s.options[s.selectedIndex].value;

	send("/cgi-bin/misc", {func:'wifiscan', device:device}, function(data) {
		var ssids = fetch(/SSID: (.*)\n/g, data);
		var channels = fetch(/channel (.*)\n/g, data);
		var signals = fetch(/signal: (.*)\n/g, data);
		var capabilities = fetch(/capability: (.*)\n/g, data);

		var tbody = $("wifiscan_tbody");
		removeChilds(tbody);

		for(var i = 0; i < ssids.length; ++i)
		{
			var tr = append(tbody, 'tr');
			append_td(tr, ssids[i]);
			append_td(tr, channels[i]);
			append_td(tr, signals[i]);
			append_td(tr, /IBSS/.test(capabilities[i]) ? "  adhoc" : "  ap");
		}

		var table = $('wifiscan_table');
		show(table);
	});
}

/*
* Create a selection of wireless devices
* represented as the first interface found.
*/
function init() {
	send("/cgi-bin/misc", {func:'wifiscan_info'}, function(data) {
		var uci = fromUCI(data);
		var list = $('wifiscan_selection');

		config_foreach(uci.wireless, "wifi-device", function(device, sobj) {
			config_foreach(uci.wireless, "wifi-iface", function(sid, sobj) {
				if(sobj.device == device)
				{
					var o = append(list, 'option');
					o.innerHTML = device;
					o.value = sobj.ifname;
					return 1;
				}
			});
		});
	});
}
<commit_msg>add some padding to the wifi device option list<commit_after>
function fetch(regex, data)
{
	var array = [];
	while(item = regex.exec(data))
		array.push(item[1]);
	return array;
}

function append_td(tr, value) {
	append(tr, 'td').innerHTML = value ? value : "?";
}

function wifi_scan()
{
	var s = $('wifiscan_selection');
	var device = s.options[s.selectedIndex].value;

	send("/cgi-bin/misc", {func:'wifiscan', device:device}, function(data) {
		var ssids = fetch(/SSID: (.*)\n/g, data);
		var channels = fetch(/channel (.*)\n/g, data);
		var signals = fetch(/signal: (.*)\n/g, data);
		var capabilities = fetch(/capability: (.*)\n/g, data);

		var tbody = $("wifiscan_tbody");
		removeChilds(tbody);

		for(var i = 0; i < ssids.length; ++i)
		{
			var tr = append(tbody, 'tr');
			append_td(tr, ssids[i]);
			append_td(tr, channels[i]);
			append_td(tr, signals[i]);
			append_td(tr, /IBSS/.test(capabilities[i]) ? "  adhoc" : "  ap");
		}

		var table = $('wifiscan_table');
		show(table);
	});
}

/*
* Create a selection of wireless devices
* represented as the first interface found.
*/
function init() {
	send("/cgi-bin/misc", {func:'wifiscan_info'}, function(data) {
		var uci = fromUCI(data);
		var list = $('wifiscan_selection');

		config_foreach(uci.wireless, "wifi-device", function(device, sobj) {
			config_foreach(uci.wireless, "wifi-iface", function(sid, sobj) {
				if(sobj.device == device)
				{
					var o = append(list, 'option');
					o.style.paddingRight = "1em";
					o.innerHTML = device;
					o.value = sobj.ifname;
					return 1;
				}
			});
		});
	});
}
<|endoftext|>


<commit_before>/**
    入驻小区
**/
(function(vc){
    vc.extends({
        data:{
            addStaffStepInfo:{
                $step:{},
                index:0,
                infos:[],
                branchOrgInfo:{
                        orgId:'',
                         componentName:'分公司信息',
                         buttonName:'选择分公司',
                         orgName:'',
                         orgLevel:'2',
                         parentOrgId:'',
                         description:'',
                },
                departmemtOrgInfo:{
                         orgId:'',
                         componentName:'部门信息',
                         buttonName:'选择部门',
                         orgName:'',
                         orgLevel:'3',
                         parentOrgId:'',
                         description:'',
                },
                staffInfo:{
                    orgId:'',
                    username:'',
                    sex:'',
                    email:'',
                    tel:'',
                    address:'',
                }
            }
        },
        _initMethod:function(){
            vc.component._initStep();
        },
        _initEvent:function(){
            vc.on("addStaffStep", "notify", function(_info){
                if(vc.component.addStaffStepInfo.index == 0){
                    vc.copyObject(_info,vc.component.addStaffStepInfo.branchOrgInfo);
                    vc.component.addStaffStepInfo.infos[0] = vc.component.addStaffStepInfo.branchOrgInfo;
                }else if(vc.component.addStaffStepInfo.index == 1){
                    vc.copyObject(_info,vc.component.addStaffStepInfo.departmemtOrgInfo);
                    vc.component.addStaffStepInfo.staffInfo.orgId = _info.orgId
                    vc.component.addStaffStepInfo.infos[1] = vc.component.addStaffStepInfo.departmemtOrgInfo;

                }else{
                    vc.copyObject(_info, vc.component.addStaffStepInfo.staffInfo);
                    vc.component.addStaffStepInfo.infos[2] = vc.component.addStaffStepInfo.staffInfo;
                }

            });

        },
        methods:{
            _initStep:function(){
                vc.component.addStaffStepInfo.$step = $("#step");
                vc.component.addStaffStepInfo.$step.step({
                    index: 0,
                    time: 500,
                    title: ["选择分公司","选择部门","员工信息"]
                });
                vc.component.addStaffStepInfo.index = vc.component.addStaffStepInfo.$step.getIndex();
                vc.component._notifyViewOrgInfoComponentData();
            },
            _prevStep:function(){
                vc.component.addStaffStepInfo.$step.prevStep();
                vc.component.addStaffStepInfo.index = vc.component.addStaffStepInfo.$step.getIndex();

                vc.emit('viewOrgInfo', 'onIndex', vc.component.addStaffStepInfo.index);
                vc.emit('addStaffView', 'onIndex', vc.component.addStaffStepInfo.index);

                vc.component._notifyViewOrgInfoComponentData();

            },
            _nextStep:function(){
                var _currentData = vc.component.addStaffStepInfo.infos[vc.component.addStaffStepInfo.index];
                if( _currentData == null || _currentData == undefined){
                    vc.message("请选择或填写必选信息");
                    return ;
                }
                vc.component.addStaffStepInfo.$step.nextStep();
                vc.component.addStaffStepInfo.index = vc.component.addStaffStepInfo.$step.getIndex();

                 vc.emit('viewOrgInfo', 'onIndex', vc.component.addStaffStepInfo.index);
                vc.emit('addStaffView', 'onIndex', vc.component.addStaffStepInfo.index);
                vc.component._notifyViewOrgInfoComponentData();

            },
            _finishStep:function(){

                //vc.component.addStaffStepInfo.staffInfo.departmentOrgId = vc.component.addStaffStepInfo.infos[1].orgId;
               vc.http.post(
                   'addStaffStepBinding',
                   'binding',
                   JSON.stringify(vc.component.addStaffStepInfo.staffInfo),
                   {
                       emulateJSON:true
                    },
                    function(json,res){
                       if(res.status == 200){

                           vc.message('处理成功',true);
                           //关闭model
                           vc.jumpToPage("/flow/staff?" + vc.objToGetParam(JSON.parse(json)));
                           return ;
                       }
                       vc.message(json);
                    },
                    function(errInfo,error){
                       console.log('请求失败处理');

                       vc.message(errInfo);
                    });
            },
            _notifyViewOrgInfoComponentData:function(){

                if(vc.component.addStaffStepInfo.index == 0){
                    vc.emit('viewOrgInfo', '_initInfo',vc.component.addStaffStepInfo.branchOrgInfo);
                }else if(vc.component.addStaffStepInfo.index == 1){
                    vc.component.addStaffStepInfo.departmemtOrgInfo.parentOrgId = c.component.addStaffStepInfo.branchOrgInfo.orgId;
                    vc.emit('viewOrgInfo', '_initInfo',vc.component.addStaffStepInfo.departmemtOrgInfo);
                }
            }
        }
    });
})(window.vc);
<commit_msg>解决vc 瓶邪错误问题<commit_after>/**
    入驻小区
**/
(function(vc){
    vc.extends({
        data:{
            addStaffStepInfo:{
                $step:{},
                index:0,
                infos:[],
                branchOrgInfo:{
                        orgId:'',
                         componentName:'分公司信息',
                         buttonName:'选择分公司',
                         orgName:'',
                         orgLevel:'2',
                         parentOrgId:'',
                         description:'',
                },
                departmemtOrgInfo:{
                         orgId:'',
                         componentName:'部门信息',
                         buttonName:'选择部门',
                         orgName:'',
                         orgLevel:'3',
                         parentOrgId:'',
                         description:'',
                },
                staffInfo:{
                    orgId:'',
                    username:'',
                    sex:'',
                    email:'',
                    tel:'',
                    address:'',
                }
            }
        },
        _initMethod:function(){
            vc.component._initStep();
        },
        _initEvent:function(){
            vc.on("addStaffStep", "notify", function(_info){
                if(vc.component.addStaffStepInfo.index == 0){
                    vc.copyObject(_info,vc.component.addStaffStepInfo.branchOrgInfo);
                    vc.component.addStaffStepInfo.infos[0] = vc.component.addStaffStepInfo.branchOrgInfo;
                }else if(vc.component.addStaffStepInfo.index == 1){
                    vc.copyObject(_info,vc.component.addStaffStepInfo.departmemtOrgInfo);
                    vc.component.addStaffStepInfo.staffInfo.orgId = _info.orgId
                    vc.component.addStaffStepInfo.infos[1] = vc.component.addStaffStepInfo.departmemtOrgInfo;

                }else{
                    vc.copyObject(_info, vc.component.addStaffStepInfo.staffInfo);
                    vc.component.addStaffStepInfo.infos[2] = vc.component.addStaffStepInfo.staffInfo;
                }

            });

        },
        methods:{
            _initStep:function(){
                vc.component.addStaffStepInfo.$step = $("#step");
                vc.component.addStaffStepInfo.$step.step({
                    index: 0,
                    time: 500,
                    title: ["选择分公司","选择部门","员工信息"]
                });
                vc.component.addStaffStepInfo.index = vc.component.addStaffStepInfo.$step.getIndex();
                vc.component._notifyViewOrgInfoComponentData();
            },
            _prevStep:function(){
                vc.component.addStaffStepInfo.$step.prevStep();
                vc.component.addStaffStepInfo.index = vc.component.addStaffStepInfo.$step.getIndex();

                vc.emit('viewOrgInfo', 'onIndex', vc.component.addStaffStepInfo.index);
                vc.emit('addStaffView', 'onIndex', vc.component.addStaffStepInfo.index);

                vc.component._notifyViewOrgInfoComponentData();

            },
            _nextStep:function(){
                var _currentData = vc.component.addStaffStepInfo.infos[vc.component.addStaffStepInfo.index];
                if( _currentData == null || _currentData == undefined){
                    vc.message("请选择或填写必选信息");
                    return ;
                }
                vc.component.addStaffStepInfo.$step.nextStep();
                vc.component.addStaffStepInfo.index = vc.component.addStaffStepInfo.$step.getIndex();

                 vc.emit('viewOrgInfo', 'onIndex', vc.component.addStaffStepInfo.index);
                vc.emit('addStaffView', 'onIndex', vc.component.addStaffStepInfo.index);
                vc.component._notifyViewOrgInfoComponentData();

            },
            _finishStep:function(){

                //vc.component.addStaffStepInfo.staffInfo.departmentOrgId = vc.component.addStaffStepInfo.infos[1].orgId;
               vc.http.post(
                   'addStaffStepBinding',
                   'binding',
                   JSON.stringify(vc.component.addStaffStepInfo.staffInfo),
                   {
                       emulateJSON:true
                    },
                    function(json,res){
                       if(res.status == 200){

                           vc.message('处理成功',true);
                           //关闭model
                           vc.jumpToPage("/flow/staff?" + vc.objToGetParam(JSON.parse(json)));
                           return ;
                       }
                       vc.message(json);
                    },
                    function(errInfo,error){
                       console.log('请求失败处理');

                       vc.message(errInfo);
                    });
            },
            _notifyViewOrgInfoComponentData:function(){

                if(vc.component.addStaffStepInfo.index == 0){
                    vc.emit('viewOrgInfo', '_initInfo',vc.component.addStaffStepInfo.branchOrgInfo);
                }else if(vc.component.addStaffStepInfo.index == 1){
                    vc.component.addStaffStepInfo.departmemtOrgInfo.parentOrgId = vc.component.addStaffStepInfo.branchOrgInfo.orgId;
                    vc.emit('viewOrgInfo', '_initInfo',vc.component.addStaffStepInfo.departmemtOrgInfo);
                }
            }
        }
    });
})(window.vc);
<|endoftext|>


<commit_before>/* global bible, time */
/* global READING_PLANS */
/* exported planner */

/**
 * Planner creates the bible reading plan.
 */

var planner = {
    'sequence': null,
    'sequenceName': null,
    'begin': null,
    'end': null,
    'skip': null,
    'amount': null,
    'type': null,
    'duration': null,
    'plan': null,

    /**
     * Determines type of plan to create
     * @param  {object} sequence Bible reading sequence
     * @param  {string|int} amount   Amount to read
     * @param  {string} type     Sequence type
     * @return {object}          Bible reading plan
     */
    'create': function () {
        'use strict';

        if(this.type === 'verses') {
            var amount = (Number(this.amount) > 0) ? Number(this.amount) : 1;
            this.plan = this.createVersesPlan(this.sequence, amount);
        }
        if(this.type === 'specified') {
            this.plan = this.createSpecifiedPlan(this.sequence, this.amount);
        }
        // if(type === 'chapters') {
        //     return this.createChaptersPlan(sequence, Number(amount));
        // }
    },

    /**
     * Create plan using the sequence plan
     * @param  {object} sequence Bible reading sequence
     * @param  {string|int} amount   Amount to read
     * @return {object}          Bible reading plan
     */
    'createSpecifiedPlan': function (sequence, amount) {
        'use strict';

        var items = Math.floor(sequence.data2.length / this.duration.length);
        // If duration is longer than the sequence, adjust to ouput everything
        items = (items === 0) ? 1 : items;
        var mod = sequence.data2.length % this.duration.length;
        var results = [];
        var sequenceKey = 0;

        /**
         * Whole sequence
         * For each day of the sequence and each item in the day's sequence, add the day's items.
         * If the number of days to read is not the same as the days in the sequence, read more in the beginning since people give up less right away.
         */
        if (amount === 'whole'){

            for (var day = 0; day < this.duration.length; day++) {
                var refs = [];

                for (var x = 0; x < items; x++) {
                    if(sequenceKey < sequence.data2.length) {
                        for (var a = 0; a < sequence.data2[sequenceKey].length; a++) {
                            refs.push(bible.parseReference(sequence.data2[sequenceKey][a]).toString());
                        }
                        sequenceKey++;
                        if (mod > 0) {
                            for (var b = 0; b < sequence.data2[sequenceKey].length; b++) {
                                refs.push(bible.parseReference(sequence.data2[sequenceKey][b]).toString());
                            }
                            sequenceKey++;
                            mod--;
                        }
                    }
                }

                results.push({'day': this.duration[day].toString(), 'refs': refs});
                if (sequenceKey === sequence.data2.length) { break; }
            }
        }

        /**
         * Partial sequence
         * For each day in the sequence, read the amount
         */
        if (amount === 'partial') {
            var sequenceLength = (this.duration.length < sequence.data2.length) ? this.duration.length : sequence.data2.length;
            for (var i = 0; i < sequenceLength; i++) {
                var ref = '';
                for (var n = 0; n < sequence.data2[i].length; n++) {
                    var comma = (n > 0) ? ', ' : '';
                    ref += comma + bible.parseReference(sequence.data2[i][n]).toString();
                }
                results.push({'day': this.duration[i].toString(), 'refs': [ref.trim()]});
            }

        }

        return results;
    },

    /**
     * Create plan using a set number of verses
     * @param  {object} sequence Bible reading sequence
     * @param  {int} amount   Amount to read
     * @return {object}          Bible reading plan
     */
    'createVersesPlan': function (sequence, amount) {
        'use strict';

        var sequenceKey = 0;
        var partialReferenceString = '';
        var results = [];
        var refs = [];
        var ref;

        /**
         * Determine references per day
         * Loop through the sequence data and parse each item to get a bible reference.
         * If the reference is valid, determine the amount to read relative to the reference.
         *     If the sequence specifies to read more than the amount desired to read, split the sequence reference up into readable parts.
         *     Else add the sequence reference.
         * Else the reference is invalid. Notify the user and move on in the sequence.
         * Finally if a partial reference remains from spliting a sequence reference, add that also.
         */

        while(sequenceKey < sequence.data.length) {
            if (ref === undefined) {
                ref = bible.parseReference(sequence.data[sequenceKey]);
                // console.info(ref.toString());
            }

            if (ref.isValid()) {
                // amount to read
                var distance = (ref !== undefined) ? bible.distance(ref).verses : undefined;
                var tmpDistance = (partialReferenceString !== '') ? bible.distance(bible.parseReference(partialReferenceString)).verses : '';
                var amt = (partialReferenceString !== '') ? amount - tmpDistance : amount;

                if(distance >= amt) {
                    var startRef = bible.Reference(ref.bookIndex, ref.chapter1, ((ref.verse1 === -1) ? 1 : ref.verse1)); // start ref
                    var startRefString = startRef.toString();
                    var endRef = bible.add(startRef, amt - 1).toString(); // end ref

                    var referenceString = (partialReferenceString !== '') ? partialReferenceString + '; ' + startRefString + '-' + endRef : startRefString + '-' + endRef;
                    refs.push(referenceString);
                    bible.add(ref, amt);
                    partialReferenceString = '';
                }
                else {
                    partialReferenceString = (partialReferenceString === '') ? ref.toString() : partialReferenceString + '; ' + ref.toString();
                    ref = undefined;
                    sequenceKey++;
                }
            }
            else {
                if (sequence.data[sequenceKey] !== undefined) {
                    console.error('invalid reference: ' + sequence.data[sequenceKey] + ' key: ' + sequenceKey + ' sequence: ' + sequence.name);
                    refs.push('Sorry there was an error parsing ' + sequence.data[sequenceKey] + '.');
                    ref = undefined;
                    sequenceKey++;
                }
            }
        }

        // add any remaining partials
        if (partialReferenceString !== '') {
            refs.push(partialReferenceString);
        }

        // Add references and date to results
        for (var i = 0; i < this.duration.length; i++) {
            if (refs[i] !== undefined) {
                results.push({'day': this.duration[i], 'refs': [refs[i]]});
            }
        }

        return results;
    },

    /** not implemented yet **/
    // 'createChaptersPlan': function (sequence, amount) {

    //     return;
    // },

    /**
     * Loads bible reading sequence
     * @param  {string} Bible reading sequence name
     */
    'load': function () {
        'use strict';

        var sequenceName = (arguments.length >= 1) ? arguments[0] : this.sequenceName;
        var readingPlans = (arguments.length >= 2) ? arguments[1] : READING_PLANS;
        var result = null;
        if(sequenceName) {
            $.ajax({
                dataType: 'json',
                url: readingPlans + '/' + sequenceName,
                async: false,
                success: function(json) { result = json; },
                error: function(e) { throw e; }
            });
        }
        this.sequence = result;
    },

    /**
     * Sets the planner data
     * @param  {object} data Data from user
     */
    'set': function (data) {
        'use strict';

        this.sequenceName = data.sequenceName;
        this.begin = data.begin;
        this.end = data.end;
        this.skip = data.skip;
        this.amount = data.amount;
        this.type = data.type;
        this.duration = time(this.begin, this.end, this.skip);
        this.load();
    }
};

//sdg
<commit_msg>Fix planning algorithm<commit_after>/* global bible, time */
/* global READING_PLANS */
/* exported planner */

/**
 * Planner creates the bible reading plan.
 */

var planner = {
    'sequence': null,
    'sequenceName': null,
    'begin': null,
    'end': null,
    'skip': null,
    'amount': null,
    'type': null,
    'duration': null,
    'plan': null,

    /**
     * Determines type of plan to create
     * @param  {object} sequence Bible reading sequence
     * @param  {string|int} amount   Amount to read
     * @param  {string} type     Sequence type
     * @return {object}          Bible reading plan
     */
    'create': function () {
        'use strict';

        if(this.type === 'verses') {
            var amount = (Number(this.amount) > 0) ? Number(this.amount) : 1;
            this.plan = this.createVersesPlan(this.sequence, amount);
        }
        if(this.type === 'specified') {
            this.plan = this.createSpecifiedPlan(this.sequence, this.amount);
        }
        // if(type === 'chapters') {
        //     return this.createChaptersPlan(sequence, Number(amount));
        // }
    },

    /**
     * Create plan using the sequence plan
     * @param  {object} sequence Bible reading sequence
     * @param  {string|int} amount   Amount to read
     * @return {object}          Bible reading plan
     */
    'createSpecifiedPlan': function (sequence, amount) {
        'use strict';

        var items = Math.floor(sequence.data2.length / this.duration.length);
        // If duration is longer than the sequence, adjust to ouput everything
        items = (items === 0) ? 1 : items;
        var mod = sequence.data2.length % this.duration.length;
        var results = [];
        var sequenceKey = 0;

        /**
         * Whole sequence
         * For each day of the sequence and each item in the day's sequence, add the day's items.
         * If the number of days to read is not the same as the days in the sequence, read more in the beginning since people give up less right away.
         */
        if (amount === 'whole'){

            for (var day = 0; day < this.duration.length; day++) {
                var refs = [];

                for (var x = 0; x < items; x++) {
                    if(sequenceKey < sequence.data2.length) {
                        for (var a = 0; a < sequence.data2[sequenceKey].length; a++) {
                            refs.push(bible.parseReference(sequence.data2[sequenceKey][a]).toString());
                        }
                        sequenceKey++;
                        if (mod > 0) {
                            for (var b = 0; b < sequence.data2[sequenceKey].length; b++) {
                                refs.push(bible.parseReference(sequence.data2[sequenceKey][b]).toString());
                            }
                            sequenceKey++;
                            mod--;
                        }
                    }
                }

                results.push({'day': this.duration[day].toString(), 'refs': refs});
                if (sequenceKey === sequence.data2.length) { break; }
            }
        }

        /**
         * Partial sequence
         * For each day in the sequence, read the amount
         */
        if (amount === 'partial') {
            var sequenceLength = (this.duration.length < sequence.data2.length) ? this.duration.length : sequence.data2.length;
            for (var i = 0; i < sequenceLength; i++) {
                var ref = '';
                for (var n = 0; n < sequence.data2[i].length; n++) {
                    var comma = (n > 0) ? ', ' : '';
                    ref += comma + bible.parseReference(sequence.data2[i][n]).toString();
                }
                results.push({'day': this.duration[i].toString(), 'refs': [ref.trim()]});
            }

        }

        return results;
    },

    /**
     * Create plan using a set number of verses
     * @param  {object} sequence Bible reading sequence
     * @param  {int} amount   Amount to read
     * @return {object}          Bible reading plan
     */
    'createVersesPlan': function (sequence, amount) {
        'use strict';

        var sequenceKey = 0;
        var partialReferenceString = '';
        var results = [];
        var refs = [];
        var dayRefs = [];
        var ref;
        var remainder = 0;

        /**
         * Determine references per day
         * Loop through the sequence data and parse each item to get a bible reference.
         * If the reference is valid, determine the amount to read relative to the reference.
         *     If the sequence specifies to read more than the amount desired to read, split the sequence reference up into readable parts.
         *     Else add the sequence reference.
         * Else the reference is invalid. Notify the user and move on in the sequence.
         * Finally if a partial reference remains from spliting a sequence reference, add that also.
         */

        while(sequenceKey < sequence.data.length) {
            if (ref === null || ref === undefined) {
                ref = bible.parseReference(sequence.data[sequenceKey]);

                // account for single and multi chapter ref
                if (ref.chapter1 >= 0 && ref.verse1 === -1 && ref.verse2 === -1) {
                    ref.chapter2 = (ref.chapter2 === -1) ? ref.chapter1 : ref.chapter2;
                    var ch = (ref.chapter2 === -1) ? ref.chapter1 - 1 : ref.chapter2 -1; // 0 based index
                    ref.verse2 = bible.Books[ref.bookIndex].verses[ch];
                    ref.verse1 = 1;
                }
            }

            if (ref.isValid()) {
                var distance = (ref !== null) ? bible.distance(ref).verses : 0; // distance of reference
                var amt = (remainder > 0) ? remainder : amount; // amount to read

                // the amount to read is less than the distance of the reference
                if(distance >= amt) {
                    var verse1 = (ref.verse1 === -1) ? 1 : ref.verse1; // multiple chapter ref
                    var startRef = bible.Reference(ref.bookIndex, ref.chapter1, verse1); // start ref
                    var startRefString = startRef.toString();
                    var endRefString = bible.add(startRef, amt - 1).toString();

                    var referenceString = (startRefString !== endRefString) ? startRefString + '-' + endRefString : startRefString;

                    dayRefs.push(referenceString);
                    refs.push(dayRefs);
                    dayRefs = [];

                    bible.add(ref, amt);

                    // add past end ref
                    if (ref.chapter1 > ref.chapter2 || (ref.chapter1 === ref.chapter2 && ref.verse1 > ref.verse2)) {
                        console.error('Reversed: ' + ref);
                        ref = null;
                        sequenceKey++;
                    }

                    remainder = 0;
                }
                // amount to read is greater than the reference, so add it and go to the next reference for more verses
                else {
                    dayRefs.push(ref.toString());
                    remainder = amt - distance;
                    ref = null;
                    sequenceKey++;
                }
            }
            // not a valid reference, log it and move on
            else {
                if (sequence.data[sequenceKey] !== undefined) {
                    console.error('invalid reference: ' + sequence.data[sequenceKey] + ' key: ' + sequenceKey + ' sequence: ' + sequence.name);
                    refs.push('Sorry there was an error parsing ' + sequence.data[sequenceKey] + '.');
                    ref = null;
                    sequenceKey++;
                }
            }
        }

        // add any remaining partials
        if (partialReferenceString !== '') {
            refs.push(partialReferenceString);
        }

        // Add references and date to results
        for (var i = 0; i < this.duration.length; i++) {
            if (refs[i] !== undefined) {
                results.push({'day': this.duration[i], 'refs': [refs[i]]});
            }
        }

        return results;
    },

    /** not implemented yet **/
    // 'createChaptersPlan': function (sequence, amount) {

    //     return;
    // },

    /**
     * Loads bible reading sequence
     * @param  {string} Bible reading sequence name
     */
    'load': function () {
        'use strict';

        var sequenceName = (arguments.length >= 1) ? arguments[0] : this.sequenceName;
        var readingPlans = (arguments.length >= 2) ? arguments[1] : READING_PLANS;
        var result = null;
        if(sequenceName) {
            $.ajax({
                dataType: 'json',
                url: readingPlans + '/' + sequenceName,
                async: false,
                success: function(json) { result = json; },
                error: function(e) { throw e; }
            });
        }
        this.sequence = result;
    },

    /**
     * Sets the planner data
     * @param  {object} data Data from user
     */
    'set': function (data) {
        'use strict';

        this.sequenceName = data.sequenceName;
        this.begin = data.begin;
        this.end = data.end;
        this.skip = data.skip;
        this.amount = data.amount;
        this.type = data.type;
        this.duration = time(this.begin, this.end, this.skip);
        this.load();
    }
};

//sdg
<|endoftext|>


<commit_before>/*
SelectFilter2 - Turns a multiple-select box into a filter interface.

Different than SelectFilter because this is coupled to the admin framework.

Requires core.js, SelectBox.js and addevent.js.
*/

function findForm(node) {
    // returns the node of the form containing the given node
    if (node.tagName.toLowerCase() != 'form') {
        return findForm(node.parentNode);
    }
    return node;
}

var SelectFilter = {
    init: function(field_id, field_name, is_stacked, admin_media_prefix) {
        if (field_id.match(/__prefix__/)){
            // Don't intialize on empty forms.
            return;
        }
        var from_box = document.getElementById(field_id);
        from_box.id += '_from'; // change its ID
        from_box.className = 'filtered';

        var ps = from_box.parentNode.getElementsByTagName('p');
        for (var i=0; i<ps.length; i++) {
            if (ps[i].className.indexOf("info") != -1) {
                // Remove
, because it just gets in the way.
                from_box.parentNode.removeChild(ps[i]);
            } else if (ps[i].className.indexOf("help") != -1) {
                // Move help text up to the top so it isn't below the select
                // boxes or wrapped off on the side to the right of the add
                // button:
                from_box.parentNode.insertBefore(ps[i], from_box.parentNode.firstChild);
            }
        }

        //
 or

        var selector_div = quickElement('div', from_box.parentNode);
        selector_div.className = is_stacked ? 'selector stacked' : 'selector';

        //

        var selector_available = quickElement('div', selector_div, '');
        selector_available.className = 'selector-available';
        quickElement('h2', selector_available, interpolate(gettext('Available %s'), [field_name]));
        var filter_p = quickElement('p', selector_available, '');
        filter_p.className = 'selector-filter';
        quickElement('img', filter_p, '', 'src', admin_media_prefix + 'img/admin/selector-search.gif');
        filter_p.appendChild(document.createTextNode(' '));
        var filter_input = quickElement('input', filter_p, '', 'type', 'text');
        filter_input.id = field_id + '_input';
        selector_available.appendChild(from_box);
        var choose_all = quickElement('a', selector_available, gettext('Choose all'), 'href', 'javascript: (function(){ SelectBox.move_all("' + field_id + '_from", "' + field_id + '_to"); })()');
        choose_all.className = 'selector-chooseall';

        //

        var selector_chooser = quickElement('ul', selector_div, '');
        selector_chooser.className = 'selector-chooser';
        var add_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Add'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_from","' + field_id + '_to");})()');
        add_link.className = 'selector-add';
        var remove_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Remove'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_to","' + field_id + '_from");})()');
        remove_link.className = 'selector-remove';

        //

        var selector_chosen = quickElement('div', selector_div, '');
        selector_chosen.className = 'selector-chosen';
        quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s'), [field_name]));
        var selector_filter = quickElement('p', selector_chosen, gettext('Select your choice(s) and click '));
        selector_filter.className = 'selector-filter';
        quickElement('img', selector_filter, '', 'src', admin_media_prefix + (is_stacked ? 'img/admin/selector_stacked-add.gif':'img/admin/selector-add.gif'), 'alt', 'Add');
        var to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', 'multiple', 'size', from_box.size, 'name', from_box.getAttribute('name'));
        to_box.className = 'filtered';
        var clear_all = quickElement('a', selector_chosen, gettext('Clear all'), 'href', 'javascript: (function() { SelectBox.move_all("' + field_id + '_to", "' + field_id + '_from");})()');
        clear_all.className = 'selector-clearall';

        from_box.setAttribute('name', from_box.getAttribute('name') + '_old');

        // Set up the JavaScript event handlers for the select box filter interface
        addEvent(filter_input, 'keyup', function(e) { SelectFilter.filter_key_up(e, field_id); });
        addEvent(filter_input, 'keydown', function(e) { SelectFilter.filter_key_down(e, field_id); });
        addEvent(from_box, 'dblclick', function() { SelectBox.move(field_id + '_from', field_id + '_to'); });
        addEvent(to_box, 'dblclick', function() { SelectBox.move(field_id + '_to', field_id + '_from'); });
        addEvent(findForm(from_box), 'submit', function() { SelectBox.select_all(field_id + '_to'); });
        SelectBox.init(field_id + '_from');
        SelectBox.init(field_id + '_to');
        // Move selected from_box options to to_box
        SelectBox.move(field_id + '_from', field_id + '_to');
    },
    filter_key_up: function(event, field_id) {
        from = document.getElementById(field_id + '_from');
        // don't submit form if user pressed Enter
        if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
            from.selectedIndex = 0;
            SelectBox.move(field_id + '_from', field_id + '_to');
            from.selectedIndex = 0;
            return false;
        }
        var temp = from.selectedIndex;
        SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value);
        from.selectedIndex = temp;
        return true;
    },
    filter_key_down: function(event, field_id) {
        from = document.getElementById(field_id + '_from');
        // right arrow -- move across
        if ((event.which && event.which == 39) || (event.keyCode && event.keyCode == 39)) {
            var old_index = from.selectedIndex;
            SelectBox.move(field_id + '_from', field_id + '_to');
            from.selectedIndex = (old_index == from.length) ? from.length - 1 : old_index;
            return false;
        }
        // down arrow -- wrap around
        if ((event.which && event.which == 40) || (event.keyCode && event.keyCode == 40)) {
            from.selectedIndex = (from.length == from.selectedIndex + 1) ? 0 : from.selectedIndex + 1;
        }
        // up arrow -- wrap around
        if ((event.which && event.which == 38) || (event.keyCode && event.keyCode == 38)) {
            from.selectedIndex = (from.selectedIndex == 0) ? from.length - 1 : from.selectedIndex - 1;
        }
        return true;
    }
}
<commit_msg>Fixed #12959 -- Added alt text to SelectFilter filter button. Thanks, acdha.<commit_after>/*
SelectFilter2 - Turns a multiple-select box into a filter interface.

Different than SelectFilter because this is coupled to the admin framework.

Requires core.js, SelectBox.js and addevent.js.
*/

function findForm(node) {
    // returns the node of the form containing the given node
    if (node.tagName.toLowerCase() != 'form') {
        return findForm(node.parentNode);
    }
    return node;
}

var SelectFilter = {
    init: function(field_id, field_name, is_stacked, admin_media_prefix) {
        if (field_id.match(/__prefix__/)){
            // Don't intialize on empty forms.
            return;
        }
        var from_box = document.getElementById(field_id);
        from_box.id += '_from'; // change its ID
        from_box.className = 'filtered';

        var ps = from_box.parentNode.getElementsByTagName('p');
        for (var i=0; i<ps.length; i++) {
            if (ps[i].className.indexOf("info") != -1) {
                // Remove
, because it just gets in the way.
                from_box.parentNode.removeChild(ps[i]);
            } else if (ps[i].className.indexOf("help") != -1) {
                // Move help text up to the top so it isn't below the select
                // boxes or wrapped off on the side to the right of the add
                // button:
                from_box.parentNode.insertBefore(ps[i], from_box.parentNode.firstChild);
            }
        }

        //
 or

        var selector_div = quickElement('div', from_box.parentNode);
        selector_div.className = is_stacked ? 'selector stacked' : 'selector';

        //

        var selector_available = quickElement('div', selector_div, '');
        selector_available.className = 'selector-available';
        quickElement('h2', selector_available, interpolate(gettext('Available %s'), [field_name]));
        var filter_p = quickElement('p', selector_available, '');
        filter_p.className = 'selector-filter';

        var search_filter_label = quickElement('label', filter_p, '', 'for', field_id + "_input", 'style', 'width:16px;padding:2px');

        var search_selector_img = quickElement('img', search_filter_label, '', 'src', admin_media_prefix + 'img/admin/selector-search.gif');
        search_selector_img.alt = gettext("Filter");

        filter_p.appendChild(document.createTextNode(' '));

        var filter_input = quickElement('input', filter_p, '', 'type', 'text');
        filter_input.id = field_id + '_input';
        selector_available.appendChild(from_box);
        var choose_all = quickElement('a', selector_available, gettext('Choose all'), 'href', 'javascript: (function(){ SelectBox.move_all("' + field_id + '_from", "' + field_id + '_to"); })()');
        choose_all.className = 'selector-chooseall';

        //

        var selector_chooser = quickElement('ul', selector_div, '');
        selector_chooser.className = 'selector-chooser';
        var add_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Add'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_from","' + field_id + '_to");})()');
        add_link.className = 'selector-add';
        var remove_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Remove'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_to","' + field_id + '_from");})()');
        remove_link.className = 'selector-remove';

        //

        var selector_chosen = quickElement('div', selector_div, '');
        selector_chosen.className = 'selector-chosen';
        quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s'), [field_name]));
        var selector_filter = quickElement('p', selector_chosen, gettext('Select your choice(s) and click '));
        selector_filter.className = 'selector-filter';
        quickElement('img', selector_filter, '', 'src', admin_media_prefix + (is_stacked ? 'img/admin/selector_stacked-add.gif':'img/admin/selector-add.gif'), 'alt', 'Add');
        var to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', 'multiple', 'size', from_box.size, 'name', from_box.getAttribute('name'));
        to_box.className = 'filtered';
        var clear_all = quickElement('a', selector_chosen, gettext('Clear all'), 'href', 'javascript: (function() { SelectBox.move_all("' + field_id + '_to", "' + field_id + '_from");})()');
        clear_all.className = 'selector-clearall';

        from_box.setAttribute('name', from_box.getAttribute('name') + '_old');

        // Set up the JavaScript event handlers for the select box filter interface
        addEvent(filter_input, 'keyup', function(e) { SelectFilter.filter_key_up(e, field_id); });
        addEvent(filter_input, 'keydown', function(e) { SelectFilter.filter_key_down(e, field_id); });
        addEvent(from_box, 'dblclick', function() { SelectBox.move(field_id + '_from', field_id + '_to'); });
        addEvent(to_box, 'dblclick', function() { SelectBox.move(field_id + '_to', field_id + '_from'); });
        addEvent(findForm(from_box), 'submit', function() { SelectBox.select_all(field_id + '_to'); });
        SelectBox.init(field_id + '_from');
        SelectBox.init(field_id + '_to');
        // Move selected from_box options to to_box
        SelectBox.move(field_id + '_from', field_id + '_to');
    },
    filter_key_up: function(event, field_id) {
        from = document.getElementById(field_id + '_from');
        // don't submit form if user pressed Enter
        if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
            from.selectedIndex = 0;
            SelectBox.move(field_id + '_from', field_id + '_to');
            from.selectedIndex = 0;
            return false;
        }
        var temp = from.selectedIndex;
        SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value);
        from.selectedIndex = temp;
        return true;
    },
    filter_key_down: function(event, field_id) {
        from = document.getElementById(field_id + '_from');
        // right arrow -- move across
        if ((event.which && event.which == 39) || (event.keyCode && event.keyCode == 39)) {
            var old_index = from.selectedIndex;
            SelectBox.move(field_id + '_from', field_id + '_to');
            from.selectedIndex = (old_index == from.length) ? from.length - 1 : old_index;
            return false;
        }
        // down arrow -- wrap around
        if ((event.which && event.which == 40) || (event.keyCode && event.keyCode == 40)) {
            from.selectedIndex = (from.length == from.selectedIndex + 1) ? 0 : from.selectedIndex + 1;
        }
        // up arrow -- wrap around
        if ((event.which && event.which == 38) || (event.keyCode && event.keyCode == 38)) {
            from.selectedIndex = (from.selectedIndex == 0) ? from.length - 1 : from.selectedIndex - 1;
        }
        return true;
    }
}
<|endoftext|>


<commit_before>$.cssHooks.backgroundColor = {
    get: function(elem) {
        if (elem.currentStyle)
            var bg = elem.currentStyle["backgroundColor"];
        else if (window.getComputedStyle)
            var bg = document.defaultView.getComputedStyle(elem,
                null).getPropertyValue("background-color");
        if (bg.search("rgb") == -1)
            return bg;
        else {
            bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
        }
    }
};

$.fn.dataTableExt.oSort['numeric_ignore_nan-asc']  = function(x,y) {
    if (isNaN(x) && isNaN(y)) return ((x < y) ? 1 : ((x > y) ?  -1 : 0));

    if (isNaN(x)) return 1;
    if (isNaN(y)) return -1;

    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

$.fn.dataTableExt.oSort['numeric_ignore_nan-desc'] = function(x,y) {
    if (isNaN(x) && isNaN(y)) return ((x < y) ? 1 : ((x > y) ?  -1 : 0));

    if (isNaN(x)) return 1;
    if (isNaN(y)) return -1;

    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};

$.fn.dataTableExt.afnFiltering.push(
    function(oSettings, aData, iDataIndex) {
        var selected_tags = $('.filter_labels h3 span.tag-checked').map(function(k, v) {
                return $(this).text();
            }).get(),
            row_tags = aData[9].split(',');

        if (!selected_tags.length) { // nothing to filter out
            return true;
        } else {
            if (!row_tags.length || (row_tags.length === 1 && row_tags[0] === "")) {
                return false;
            }
            for (var i = 0; i < selected_tags.length; i++) {
                for (var j = 0; j < row_tags.length; j++) {
                    if (selected_tags[i] === row_tags[j]) {
                        return true;
                    }
                }
            }
            return false;
        }
    }
);

$.fn.dataTableExt.afnFiltering.push(
    function(oSettings, aData, iDataIndex) {
        var selected_categories = $('.category_labels h2 span.tag-checked').map(function(k, v) {
                return $(this).css('background-color');
            }).get(),
            row_color = aData[10];
        if (!selected_categories.length) { // nothing to filter out
            return true;
        } else {
            for (var i = 0; i < selected_categories.length; i++) {
                if (selected_categories[i] === row_color) {
                    return true;
                }
            }
        }
        return false;
    }
);

var genomeData = $('#genomeData');
var reset_checkboxes = function(checkbox_settings) {
    var checkboxes = $(".checkbox-row input");
    checkbox_settings.forEach(function(element, index) {
        var checkbox = $(checkboxes[index]);
        checkbox.prop('checked', element).trigger('change');
    });

};
$(document).ready(function() {
    var genome_url = genomeData.data('genome_url');
    var genomeTable = genomeData.dataTable({
        "ajax": genome_url,
        "columns": [
            {"data": "rsid" },
            {"data": "chromosome_position" },
            {"data": "risk_allele" },
            {"data": "genotype" },
            {"data": "disease_trait" },
            {"data": "p_value" },
            {"data": "or_or_beta" },
            {"data": "risk" },
            {"data": "priority", "defaultContent": "0" },
            {"data": "tags", "defaultContent": " "},
            {"data": "color", "defaultContent": ""}
        ],
        "pageLength": 100,
        'bSort': false,
        "aoColumnDefs": [
            { "sType": "numeric_ignore_nan", "aTargets": [ 5, 6 ] },
            { "bSearchable": false, "bVisible": false, "aTargets": [ 8 ] }
        ],
        "columnDefs": [{"targets": [ 8 ], "visible": false, "searchable": false}],
        "order": [[ 8, "desc" ]],
        "processing": true,
        "rowCallback": function(row, data, index) {
            var $row = $(row);
            $row.data('url', encodeURI(data['link'] + '?allele=' + data['genotype']));
            $('td:not(.color-marked)', row).prepend(' ').addClass('color-marked');
        },
        "drawCallback": function( settings ) {
            var rows = $('#genomeData tbody tr');

            // Remove existing event handlers;
            rows.off('click');

            rows.click(function(e) {
                e.preventDefault();
                var row = $(this);
                var destination = $('#genomeDataDestination');
                destination.text('Loading...').data('original_top', $(document).scrollTop()+100);
                $(window).scroll();
                $.get(row.data('url'), {'ajax':'1'})
                .fail(function(data) {
                    destination.text('error\n'+data.statusCode()+' '+data.statusText+'\n\n'+data.responseText);
                    $(window).scroll();
                })
                .done(function(data) {
                    destination.html(data);
                    $(window).scroll();
                });
                return false;
                window.open(row.data('url'), 'Your genome', "height=" + window.screen.height +",width=" + window.screen.width);
            });
            // Fix datatable for fluid container
            genomeData.css('width', '');

            // Ugly way to make table columns show/hide on init as requested
            var checkbox_settings = [
                false, // RSID
                false, // CHROMOSOME POS
                false, // RISK ALLELE
                true, // GENOTYPE
                true, // DISEASE TRAIT
                false, // P VALUE
                false, // OR
                false, // RISK
                false, // PRIORITY
                false, // TAGS
                false  // CATEGORY COLOR
            ];
            $('.table-settings').data('default-values', checkbox_settings);
            reset_checkboxes($('.table-settings').data('default-values'));

        }
    }).columnFilter({ sPlaceHolder: "head:after",
        aoColumns: [
            { type: "number-range" },
            { type: "number-range" },
            { type: "select" },
            { type: "select" },
            { type: "select" },
            { type: "number-range" },
            { type: "number-range" },
            { type: "select" },
            { type: "number-range" },
            { type: "select" },
            { type: "select" },
            { type: "select" }
        ]
    });
});

var progressbar = $('.progress-bar');
var interval;

function updateBar(values) {
    var l = values.received;
    var tot = values.size;

    var perc = (l / tot) * (100.00);
    progressbar.css('width', perc + '%');
    progressbar.text(perc + '%');
    if (values.status === 'done') {
        window.clearInterval(interval);
    }
}

$("form#upload_form").submit(function(e){
    $('form#upload_form input[type=submit]').hide();
    progressbar.parent().show();
    var getProgress = function() {
        $.ajax({
            url: "/progress",
            headers: {"X-Progress-ID": $('#progress-bar').data('upload_id')},
            dataType: 'json',
            success: function(data) {
                updateBar(data);
            }
        });
    };
    interval = window.setInterval(getProgress, 1000);
});

$('.genomeData_advanced').click(function(e) {
    $('#genomeData thead tr.filter-visiblity, .dataTables_length, .dataTables_filter, .table-settings').toggle();
});

$(".checkbox-row input").change(function() {
    var checked = $(this).is(":checked");
    var index = $(this).parent().parent().index();
    $('#genomeData tbody tr').each(function() {
        var $cell = $(this).find("td").eq(index);
        if(checked) {
            $cell.show();
        } else {
            $cell.hide();
        }
        $('td.first', this).removeClass('first');
        $('td:visible:first', this).addClass('first');
    });
    $('#genomeData thead tr').each(function() {
        if(checked) {
            $(this).find("th").eq(index).show();
        } else {
            $(this).find("th").eq(index).hide();
        }
    });
    $('#genomeData tfoot tr').each(function() {
        if(checked) {
            $(this).find("th").eq(index).show();
        } else {
            $(this).find("th").eq(index).hide();
        }
    });
});
$(".table-settings .defaultbutton").click(function() {
    reset_checkboxes($('.table-settings').data('default-values'));
    return false;
});

$('.filter_labels h3 span.label').on('click', function(e) {
    var label = $(e.delegateTarget),
        labelColorOff = label.data('color-off'),
        labelColorOn = label.data('color-on');
    label.toggleClass('tag-checked');
    if (label.hasClass('tag-checked')) {
        label.css('background-color', labelColorOn);
    } else {
        label.css('background-color', labelColorOff);
    }
    genomeData.DataTable().draw();
});

$('.category_labels h2 span.label').on('click', function(e) {
    var category = $(e.delegateTarget);
    category.toggleClass('tag-checked');
    genomeData.DataTable().draw();
});

/**
 * Layout expand
 */
function setLayout() {
    if(window.localStorage['expand'] == 'true') {
        $('.layout').removeClass('container container-fluid').addClass('container-fluid')
        $('[data-toggle=layout-fluid] .glyphicon.glyphicon-resize-full').removeClass('glyphicon-resize-full').addClass('glyphicon-resize-small')
    } else {
        $('.layout').removeClass('container container-fluid').addClass('container')
        $('[data-toggle=layout-fluid] .glyphicon.glyphicon-resize-small').removeClass('glyphicon-resize-small').addClass('glyphicon-resize-full')
    }
}

//setLayout();

$('[data-toggle=layout-fluid]').click(function() {
    window.localStorage['expand'] = String(!(window.localStorage['expand'] == 'true'));
    setLayout();
    return false;
});

if (window.location.href === '/disease/browse/') {
    (function poll(){
        setTimeout(function(){
            if ($('.alert.alert-info').length) {
                location.reload();
                poll();
            }
        }, 1000);
    })();
}

$(function() {
    $(window).scroll(function() {
        var doc_top = $(document).scrollTop();
        var doc_height = $(window).height();
        $('.stay-visible').each(function() {
            var $this = $(this);
            if (!$this.data('original_top')) {
                var elem_offset = $this.offset()
                $this.data('original_top', elem_offset.top);
                $this.css('position', 'absolute').css('top', elem_offset.top).css('left', elem_offset.left);
            }
            var elem_top = $this.data('original_top');
            var elem_bottom = elem_top + $this.height();
            var computed_top;
            if (doc_top + doc_height > elem_bottom) {
                computed_top = doc_top + doc_height - $this.height();
                console.log('2 doc_top + doc_height - this.height %o', computed_top);
            } else {
                computed_top = elem_top;
                console.log('3 elem_top %o', computed_top);
            }
            $this.css('top', computed_top);
        });
    });
});
<commit_msg> Floating right pane genome description #1<commit_after>$.cssHooks.backgroundColor = {
    get: function(elem) {
        if (elem.currentStyle)
            var bg = elem.currentStyle["backgroundColor"];
        else if (window.getComputedStyle)
            var bg = document.defaultView.getComputedStyle(elem,
                null).getPropertyValue("background-color");
        if (bg.search("rgb") == -1)
            return bg;
        else {
            bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
        }
    }
};

$.fn.dataTableExt.oSort['numeric_ignore_nan-asc']  = function(x,y) {
    if (isNaN(x) && isNaN(y)) return ((x < y) ? 1 : ((x > y) ?  -1 : 0));

    if (isNaN(x)) return 1;
    if (isNaN(y)) return -1;

    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

$.fn.dataTableExt.oSort['numeric_ignore_nan-desc'] = function(x,y) {
    if (isNaN(x) && isNaN(y)) return ((x < y) ? 1 : ((x > y) ?  -1 : 0));

    if (isNaN(x)) return 1;
    if (isNaN(y)) return -1;

    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};

$.fn.dataTableExt.afnFiltering.push(
    function(oSettings, aData, iDataIndex) {
        var selected_tags = $('.filter_labels h3 span.tag-checked').map(function(k, v) {
                return $(this).text();
            }).get(),
            row_tags = aData[9].split(',');

        if (!selected_tags.length) { // nothing to filter out
            return true;
        } else {
            if (!row_tags.length || (row_tags.length === 1 && row_tags[0] === "")) {
                return false;
            }
            for (var i = 0; i < selected_tags.length; i++) {
                for (var j = 0; j < row_tags.length; j++) {
                    if (selected_tags[i] === row_tags[j]) {
                        return true;
                    }
                }
            }
            return false;
        }
    }
);

$.fn.dataTableExt.afnFiltering.push(
    function(oSettings, aData, iDataIndex) {
        var selected_categories = $('.category_labels h2 span.tag-checked').map(function(k, v) {
                return $(this).css('background-color');
            }).get(),
            row_color = aData[10];
        if (!selected_categories.length) { // nothing to filter out
            return true;
        } else {
            for (var i = 0; i < selected_categories.length; i++) {
                if (selected_categories[i] === row_color) {
                    return true;
                }
            }
        }
        return false;
    }
);

var genomeData = $('#genomeData');
var reset_checkboxes = function(checkbox_settings) {
    var checkboxes = $(".checkbox-row input");
    checkbox_settings.forEach(function(element, index) {
        var checkbox = $(checkboxes[index]);
        checkbox.prop('checked', element).trigger('change');
    });

};
$(document).ready(function() {
    var genome_url = genomeData.data('genome_url');
    var genomeTable = genomeData.dataTable({
        "ajax": genome_url,
        "columns": [
            {"data": "rsid" },
            {"data": "chromosome_position" },
            {"data": "risk_allele" },
            {"data": "genotype" },
            {"data": "disease_trait" },
            {"data": "p_value" },
            {"data": "or_or_beta" },
            {"data": "risk" },
            {"data": "priority", "defaultContent": "0" },
            {"data": "tags", "defaultContent": " "},
            {"data": "color", "defaultContent": ""}
        ],
        "pageLength": 100,
        'bSort': false,
        "aoColumnDefs": [
            { "sType": "numeric_ignore_nan", "aTargets": [ 5, 6 ] },
            { "bSearchable": false, "bVisible": false, "aTargets": [ 8 ] }
        ],
        "columnDefs": [{"targets": [ 8 ], "visible": false, "searchable": false}],
        "order": [[ 8, "desc" ]],
        "processing": true,
        "rowCallback": function(row, data, index) {
            var $row = $(row);
            $row.data('url', encodeURI(data['link'] + '?allele=' + data['genotype']));
            $('td:not(.color-marked)', row).prepend(' ').addClass('color-marked');
        },
        "drawCallback": function( settings ) {
            var rows = $('#genomeData tbody tr');

            // Remove existing event handlers;
            rows.off('click');

            rows.click(function(e) {
                e.preventDefault();
                var row = $(this);
                var destination = $('#genomeDataDestination');
                var doc_top = $(document).scrollTop()+100;
                var table_top = $('#genomeData tbody').offset().top;
                var computed_top;
                if (doc_top > table_top) {
                    computed_top = doc_top;
                } else {
                    computed_top = table_top;
                }
                destination.text('Loading...').data('original_top', computed_top);
                $(window).scroll();
                $.get(row.data('url'), {'ajax':'1'})
                .fail(function(data) {
                    destination.text('error\n'+data.statusCode()+' '+data.statusText+'\n\n'+data.responseText);
                    $(window).scroll();
                })
                .done(function(data) {
                    destination.html(data);
                    $(window).scroll();
                });
                return false;
                window.open(row.data('url'), 'Your genome', "height=" + window.screen.height +",width=" + window.screen.width);
            });
            // Fix datatable for fluid container
            genomeData.css('width', '');

            // Ugly way to make table columns show/hide on init as requested
            var checkbox_settings = [
                false, // RSID
                false, // CHROMOSOME POS
                false, // RISK ALLELE
                true, // GENOTYPE
                true, // DISEASE TRAIT
                false, // P VALUE
                false, // OR
                false, // RISK
                false, // PRIORITY
                false, // TAGS
                false  // CATEGORY COLOR
            ];
            $('.table-settings').data('default-values', checkbox_settings);
            reset_checkboxes($('.table-settings').data('default-values'));

        }
    }).columnFilter({ sPlaceHolder: "head:after",
        aoColumns: [
            { type: "number-range" },
            { type: "number-range" },
            { type: "select" },
            { type: "select" },
            { type: "select" },
            { type: "number-range" },
            { type: "number-range" },
            { type: "select" },
            { type: "number-range" },
            { type: "select" },
            { type: "select" },
            { type: "select" }
        ]
    });
});

var progressbar = $('.progress-bar');
var interval;

function updateBar(values) {
    var l = values.received;
    var tot = values.size;

    var perc = (l / tot) * (100.00);
    progressbar.css('width', perc + '%');
    progressbar.text(perc + '%');
    if (values.status === 'done') {
        window.clearInterval(interval);
    }
}

$("form#upload_form").submit(function(e){
    $('form#upload_form input[type=submit]').hide();
    progressbar.parent().show();
    var getProgress = function() {
        $.ajax({
            url: "/progress",
            headers: {"X-Progress-ID": $('#progress-bar').data('upload_id')},
            dataType: 'json',
            success: function(data) {
                updateBar(data);
            }
        });
    };
    interval = window.setInterval(getProgress, 1000);
});

$('.genomeData_advanced').click(function(e) {
    $('#genomeData thead tr.filter-visiblity, .dataTables_length, .dataTables_filter, .table-settings').toggle();
});

$(".checkbox-row input").change(function() {
    var checked = $(this).is(":checked");
    var index = $(this).parent().parent().index();
    $('#genomeData tbody tr').each(function() {
        var $cell = $(this).find("td").eq(index);
        if(checked) {
            $cell.show();
        } else {
            $cell.hide();
        }
        $('td.first', this).removeClass('first');
        $('td:visible:first', this).addClass('first');
    });
    $('#genomeData thead tr').each(function() {
        if(checked) {
            $(this).find("th").eq(index).show();
        } else {
            $(this).find("th").eq(index).hide();
        }
    });
    $('#genomeData tfoot tr').each(function() {
        if(checked) {
            $(this).find("th").eq(index).show();
        } else {
            $(this).find("th").eq(index).hide();
        }
    });
});
$(".table-settings .defaultbutton").click(function() {
    reset_checkboxes($('.table-settings').data('default-values'));
    return false;
});

$('.filter_labels h3 span.label').on('click', function(e) {
    var label = $(e.delegateTarget),
        labelColorOff = label.data('color-off'),
        labelColorOn = label.data('color-on');
    label.toggleClass('tag-checked');
    if (label.hasClass('tag-checked')) {
        label.css('background-color', labelColorOn);
    } else {
        label.css('background-color', labelColorOff);
    }
    genomeData.DataTable().draw();
});

$('.category_labels h2 span.label').on('click', function(e) {
    var category = $(e.delegateTarget);
    category.toggleClass('tag-checked');
    genomeData.DataTable().draw();
});

/**
 * Layout expand
 */
function setLayout() {
    if(window.localStorage['expand'] == 'true') {
        $('.layout').removeClass('container container-fluid').addClass('container-fluid')
        $('[data-toggle=layout-fluid] .glyphicon.glyphicon-resize-full').removeClass('glyphicon-resize-full').addClass('glyphicon-resize-small')
    } else {
        $('.layout').removeClass('container container-fluid').addClass('container')
        $('[data-toggle=layout-fluid] .glyphicon.glyphicon-resize-small').removeClass('glyphicon-resize-small').addClass('glyphicon-resize-full')
    }
}

//setLayout();

$('[data-toggle=layout-fluid]').click(function() {
    window.localStorage['expand'] = String(!(window.localStorage['expand'] == 'true'));
    setLayout();
    return false;
});

if (window.location.href === '/disease/browse/') {
    (function poll(){
        setTimeout(function(){
            if ($('.alert.alert-info').length) {
                location.reload();
                poll();
            }
        }, 1000);
    })();
}

$(function() {
    $(window).scroll(function() {
        var doc_top = $(document).scrollTop();
        var doc_height = $(window).height();
        $('.stay-visible').each(function() {
            var $this = $(this);
            if (!$this.data('original_top')) {
                var elem_offset = $this.offset()
                $this.data('original_top', elem_offset.top);
                $this.css('position', 'absolute').css('top', elem_offset.top).css('left', elem_offset.left);
            }
            var elem_top = $this.data('original_top');
            var elem_bottom = elem_top + $this.height();
            var computed_top;
            if (doc_top + doc_height > elem_bottom) {
                computed_top = doc_top + doc_height - $this.height();
            } else {
                computed_top = elem_top;
            }
            $this.css('top', computed_top);
        });
    });
});
<|endoftext|>


<commit_before>//v1.0 as Starting Point
//v2.0 Cleaning up code. Setting up Menu Structure and Initial Settings.

var version = '2.0 Beta';
var SCBversion = '3.021'; //Last SandCastle Builder version tested

//Declare and Initialize Variables
var AudioAlertsStatus = 3;
var audio_Bell = new Audio("http://xenko.comxa.com/Ship_Bell.mp3");
	audio_Bell.volume = 1;
var audio_Chime = new Audio("http://xenko.comxa.com/Chime.mp3");
	audio_Chime.volume = 1;
var BorderAlertStatus = 1;
var description = "Error";
var i = 0;
var IdleStatus = 0;
var incoming_ONG = 0;
var Logicat = 0;
var LCAutoClickStatus = 0;
var LCSolution = 'blank';
var NinjaAutoClickStatus = 1;
var RKAutoClickStatus = 0;
var RKAlertFrequency = 8;
var Time_to_ONG = 1800000;

var start = -1;
var content = "empty";
var length = 0;
var RKLevel = 'abc123';

//Ninja AutoClicker and Border Warnings
function Ninja() {
    if (Molpy.ninjad == 0) {
        if (Molpy.npbONG == 0 && BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid red");
        }
        else {
            incoming_ONG = 0;
            if (NinjaAutoClickStatus == 1) {
                Molpy.ClickBeach();
				if (BorderAlertStatus == 1) {
					$("#beach").css("border","1px solid white");
				}
            }
            else if (BorderAlertStatus == 1) {
            $("#beach").css("border","4px solid green");
            }

        }
	}
    else if (Time_to_ONG <= 15000) {
		if (BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid yellow");
		}
        if (incoming_ONG == 0 && (AudioAlertsStatus == 3 || AudioAlertsStatus == 4)) {
			audio_Chime.play();
			incoming_ONG = 1;
        }
    }
    else if (BorderAlertStatus == 1) {
        $("#beach").css("border","1px solid white");
	}
}

function RedundaKitty() {
	//Refresh Timer Variable
	i = Molpy.redactedToggle - Molpy.redactedCountup;

	if (Molpy.redactedVisible > 0) {
		Molpy.Notify('Redacted Visible: ' + Molpy.redactedVisible, 1);
		/*
		RV of 1 is Sand Tools
		RV of 2 is Castle Tools
		RV of 3 is Boosts Main Page
		RV of 4 is Boosts Menu, Hill People Tech
		RV of 5 is Badges Earned?
		RV of 6 is Badges Available?
		*/

		if (Molpy.redactedVisible == 1 || Molpy.redactedVisible == 2 || Molpy.redactedVisible == 3) {
			//Do Nothing
		}
		else if (Molpy.redactedVisible == 5) {
			//showhideToggle('badges');
		}

		//Determines if it is a Logicat. It it is, Logicat = 1, otherwise 0
		var content = $('#redacteditem').html();
		if (content.indexOf("statement") !== -1) {
			Logicat = 1;
			Molpy.Notify("Logicat Found",0);
		}
		else {
			Logicat = 0;
			Molpy.Notify("Redundakitty Found",0);
			start = content.indexOf("ClickRedacted");
			content = content.substring(start,start+17);
			content = content.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'');
			var length = content.length;
			RKLevel = content.substring(13,length);
			Molpy.Notify('RedundaKitty Level is: ' + RKLevel,0);
		}

		//Highlight Redundakitty Border to make it easier to find
		$('#redacteditem').css("border","2px solid red");

		//Clicks if RedundaKitty AutoClicker Enabled and Not a Logicat
		if (RKAutoClickStatus == 1 && Logicat == 0) {
			Molpy.ClickRedacted(RKLevel);
			//$(":button").click();
		}
		else if (LCAutoClickStatus == 1 && Logicat == 1) {
			Logicat();
		}
		else {
			//Redundakitty Notifications (Title Bar and Audio)
			document.title = "! kitten !";
			if (Math.floor(i % RKAlertFrequency) == 0 && (AudioAlertsStatus == 1 || AudioAlertsStatus == 3)) {
				audio_Bell.play();
			}
		}
	}
	else {
		document.title = Molpy.redactedToggle-Molpy.redactedCountup;
		if (i != 0) { i = 0; }
	}
}

function Logicat() {
	i = 65;
	do
		{LCSolution = String.fromCharCode(i);
		i++;}
	while (Molpy.redactedPuzzleTarget != Molpy.redactedSGen.StatementValue(LCSolution));
	Molpy.ClickRedactedPuzzle(LCSolution);
	Molpy.redactedPuzzleTarget = undefined;

	/*while (Molpy.redactedPuzzleTarget != undefined) {
		LCSolution = String.fromCharCode(i);
		if (Molpy.redactedPuzzleTarget == Molpy.redactedSGen.StatementValue(LCSolution)) {
			Molpy.ClickRedactedPuzzle(LCSolution);
			Molpy.redactedPuzzleTarget = undefined;
		}
		else {i++;}
	}*/
}

function SwitchOption(option) {
	switch (option) {
		case 'RKAutoClick':
			RKAutoClickStatus++;
			if (RKAutoClickStatus > 1) {RKAutoClickStatus = 0;}
			status = RKAutoClickStatus;
			break;
		case 'LCAutoClick':
			LCAutoClickStatus++;
			if (LCAutoClickStatus > 1) {LCAutoClickStatus = 0;}
			status = LCAutoClickStatus;
			break;
		case 'NinjaAutoClick':
			NinjaAutoClickStatus++;
			if (NinjaAutoClickStatus > 1) {NinjaAutoClickStatus = 0;}
			status = NinjaAutoClickStatus;
			break;
		case 'BorderAlert':
			BorderAlertStatus++;
			if (BorderAlertStatus > 1) {
				BorderAlertStatus = 0;
				$("#beach").css("border","1px solid white");
			}
			status = BorderAlertStatus;
			break;
		case 'AudioAlerts':
			AudioAlertsStatus++;
			if (AudioAlertsStatus > 3) {AudioAlertsStatus = 0;}
			status = AudioAlertsStatus;
			break;
	}
	DisplayDescription(option, status);
}

function DisplayDescription(option, status) {
	error = 0;
	if (option == 'RKAutoClick' || option == 'LCAutoClick' || option == 'NinjaAutoClick' || option == 'BorderAlert') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'On';}
		else {Molpy.Notify('Display Description Error',1);}
	}
	else if (option == 'AudioAlerts') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'RK Only';}
		else if (status == 2) {description = 'ONG Only';}
		else if (status == 3) {description = 'RK and ONG';}
		else {Molpy.Notify('Display Description Error - Audio Alerts: ' + status,1);}
	}
	else {
		Molpy.Notify(option + ' is not a valid option', 1);
		error = 1;
	}

	if (error == 0) {g(option + 'Desc').innerHTML = '
' + description;}
}

//Beach Ball Startup
//Set Settings
if (Molpy.Got('Kitnip') == 1){RKAlertFrequency = 10;}

//Create Menu
$('#optionsItems').append('

BeachBall Settings

');
$('#optionsItems').append('

Redundakitty Auto Click

');
$('#optionsItems').append('

Logicat Auto Click

');
$('#optionsItems').append('

Ninja Auto Click

');
$('#optionsItems').append('

Ninja Visual Alert

');
$('#optionsItems').append('

Audio Alerts

');
DisplayDescription('RKAutoClick', RKAutoClickStatus);
DisplayDescription('LCAutoClick', LCAutoClickStatus);
DisplayDescription('NinjaAutoClick', NinjaAutoClickStatus);
DisplayDescription('BorderAlert', BorderAlertStatus);
DisplayDescription('AudioAlerts', AudioAlertsStatus);

Molpy.Notify('BeachBall version ' + version + ' loaded for SandCastle Builder version ' + SCBversion, 1)

function MainLoop() {
	setInterval(function() {
		Molpy.Notify('1 mNP', 0);
		Time_to_ONG = (Molpy.NPlength * 1000) - Molpy.ONGelapsed;
		RedundaKitty();
		Ninja();
	}, 1800);
}

//Run Main Loop after 5 second startup delay
setTimeout(MainLoop(), 5000);

<commit_msg>Continuing testing RK vs LC<commit_after>//v1.0 as Starting Point
//v2.0 Cleaning up code. Setting up Menu Structure and Initial Settings.

var version = '2.0 Beta';
var SCBversion = '3.021'; //Last SandCastle Builder version tested

//Declare and Initialize Variables
var AudioAlertsStatus = 3;
var audio_Bell = new Audio("http://xenko.comxa.com/Ship_Bell.mp3");
	audio_Bell.volume = 1;
var audio_Chime = new Audio("http://xenko.comxa.com/Chime.mp3");
	audio_Chime.volume = 1;
var BorderAlertStatus = 1;
var description = "Error";
var i = 0;
var IdleStatus = 0;
var incoming_ONG = 0;
var Logicat = 0;
var LCAutoClickStatus = 0;
var LCSolution = 'blank';
var NinjaAutoClickStatus = 1;
var RKAutoClickStatus = 0;
var RKAlertFrequency = 8;
var Time_to_ONG = 1800000;

var start = -1;
var content = "empty";
var length = 0;
var RKLevel = 'abc123';

//Ninja AutoClicker and Border Warnings
function Ninja() {
    if (Molpy.ninjad == 0) {
        if (Molpy.npbONG == 0 && BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid red");
        }
        else {
            incoming_ONG = 0;
            if (NinjaAutoClickStatus == 1) {
                Molpy.ClickBeach();
				Molpy.Notify('Ninja Auto Click', 1);
				if (BorderAlertStatus == 1) {
					$("#beach").css("border","1px solid white");
				}
            }
            else if (BorderAlertStatus == 1) {
            $("#beach").css("border","4px solid green");
            }

        }
	}
    else if (Time_to_ONG <= 15000) {
		if (BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid yellow");
		}
        if (incoming_ONG == 0 && (AudioAlertsStatus == 3 || AudioAlertsStatus == 4)) {
			audio_Chime.play();
			incoming_ONG = 1;
        }
    }
    else if (BorderAlertStatus == 1) {
        $("#beach").css("border","1px solid white");
	}
}

function RedundaKitty() {
	//Refresh Timer Variable
	i = Molpy.redactedToggle - Molpy.redactedCountup;

	if (Molpy.redactedVisible > 0) {
		Molpy.Notify('Redacted Visible: ' + Molpy.redactedVisible, 1);
		/*
		RV of 1 is Sand Tools
		RV of 2 is Castle Tools
		RV of 3 is Boosts Main Page
		RV of 4 is Boosts Menu, Hill People Tech
		RV of 5 is Badges Earned?
		RV of 6 is Badges Available?
		*/

		if (Molpy.redactedVisible == 1 || Molpy.redactedVisible == 2 || Molpy.redactedVisible == 3) {
			//Do Nothing
		}
		else if (Molpy.redactedVisible == 5) {
			//showhideToggle('badges');
		}

		//Determines if it is a Logicat. It it is, Logicat = 1, otherwise 0
		var content = $('#redacteditem').html();
		if (content.indexOf("statement") !== -1) {
			Logicat = 1;
			Molpy.Notify("Logicat Found",0);
		}
		else {
			Logicat = 0;
			Molpy.Notify("Redundakitty Found",0);
			start = content.indexOf("ClickRedacted");
			content = content.substring(start,start+17);
			content = content.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'');
			var length = content.length;
			RKLevel = content.substring(13,length);
			Molpy.Notify('RedundaKitty Level is: ' + RKLevel,0);
		}

		//Highlight Redundakitty Border to make it easier to find
		$('#redacteditem').css("border","2px solid red");

		//Clicks if RedundaKitty AutoClicker Enabled and Not a Logicat
		if (RKAutoClickStatus == 1 && Logicat == 0) {
			Molpy.ClickRedacted(RKLevel);
			//$(":button").click();
		}
		else if (LCAutoClickStatus == 1 && Logicat == 1) {
			Logicat();
		}
		else {
			//Redundakitty Notifications (Title Bar and Audio)
			document.title = "! kitten !";
			if (Math.floor(i % RKAlertFrequency) == 0 && (AudioAlertsStatus == 1 || AudioAlertsStatus == 3)) {
				audio_Bell.play();
			}
		}
	}
	else {
		document.title = Molpy.redactedToggle-Molpy.redactedCountup;
		if (i != 0) { i = 0; }
	}
}

function Logicat() {
	i = 65;
	do
		{LCSolution = String.fromCharCode(i);
		i++;}
	while (Molpy.redactedPuzzleTarget != Molpy.redactedSGen.StatementValue(LCSolution));
	Molpy.ClickRedactedPuzzle(LCSolution);
	Molpy.redactedPuzzleTarget = undefined;

	/*while (Molpy.redactedPuzzleTarget != undefined) {
		LCSolution = String.fromCharCode(i);
		if (Molpy.redactedPuzzleTarget == Molpy.redactedSGen.StatementValue(LCSolution)) {
			Molpy.ClickRedactedPuzzle(LCSolution);
			Molpy.redactedPuzzleTarget = undefined;
		}
		else {i++;}
	}*/
}

function SwitchOption(option) {
	switch (option) {
		case 'RKAutoClick':
			RKAutoClickStatus++;
			if (RKAutoClickStatus > 1) {RKAutoClickStatus = 0;}
			status = RKAutoClickStatus;
			break;
		case 'LCAutoClick':
			LCAutoClickStatus++;
			if (LCAutoClickStatus > 1) {LCAutoClickStatus = 0;}
			status = LCAutoClickStatus;
			break;
		case 'NinjaAutoClick':
			NinjaAutoClickStatus++;
			if (NinjaAutoClickStatus > 1) {NinjaAutoClickStatus = 0;}
			status = NinjaAutoClickStatus;
			break;
		case 'BorderAlert':
			BorderAlertStatus++;
			if (BorderAlertStatus > 1) {
				BorderAlertStatus = 0;
				$("#beach").css("border","1px solid white");
			}
			status = BorderAlertStatus;
			break;
		case 'AudioAlerts':
			AudioAlertsStatus++;
			if (AudioAlertsStatus > 3) {AudioAlertsStatus = 0;}
			status = AudioAlertsStatus;
			break;
	}
	DisplayDescription(option, status);
}

function DisplayDescription(option, status) {
	error = 0;
	if (option == 'RKAutoClick' || option == 'LCAutoClick' || option == 'NinjaAutoClick' || option == 'BorderAlert') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'On';}
		else {Molpy.Notify('Display Description Error',1);}
	}
	else if (option == 'AudioAlerts') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'RK Only';}
		else if (status == 2) {description = 'ONG Only';}
		else if (status == 3) {description = 'RK and ONG';}
		else {Molpy.Notify('Display Description Error - Audio Alerts: ' + status,1);}
	}
	else {
		Molpy.Notify(option + ' is not a valid option', 1);
		error = 1;
	}

	if (error == 0) {g(option + 'Desc').innerHTML = '
' + description;}
}

//Beach Ball Startup
//Set Settings
if (Molpy.Got('Kitnip') == 1){RKAlertFrequency = 10;}

//Create Menu
$('#optionsItems').append('

BeachBall Settings

');
$('#optionsItems').append('

Redundakitty Auto Click

');
$('#optionsItems').append('

Logicat Auto Click

');
$('#optionsItems').append('

Ninja Auto Click

');
$('#optionsItems').append('

Ninja Visual Alert

');
$('#optionsItems').append('

Audio Alerts

');
DisplayDescription('RKAutoClick', RKAutoClickStatus);
DisplayDescription('LCAutoClick', LCAutoClickStatus);
DisplayDescription('NinjaAutoClick', NinjaAutoClickStatus);
DisplayDescription('BorderAlert', BorderAlertStatus);
DisplayDescription('AudioAlerts', AudioAlertsStatus);

Molpy.Notify('BeachBall version ' + version + ' loaded for SandCastle Builder version ' + SCBversion, 1)

function MainLoop() {
	setInterval(function() {
		Molpy.Notify('1 mNP', 0);
		Time_to_ONG = (Molpy.NPlength * 1000) - Molpy.ONGelapsed;
		RedundaKitty();
		Ninja();
	}, 1800);
}

//Run Main Loop after 5 second startup delay
setTimeout(MainLoop(), 20000);

<|endoftext|>


<commit_before>/**
 * @namespace ajax
 * @summary module to make ajax requests
 */
var ajax = (function() {
    "use strict";
    /**
     * @summary loader HTML element injected into loaderTarget when ajax is running
     * @private
     * @type {Element}
     */
    var loader = document.createElement("div");
    loader.className = "ajax-loader";

    /**
     * @memberof ajax
     * @summary injects the loader element into loaderTarget
     * @private
     * @param target {Element}
     */
    function startLoader(target) {
        target.appendChild(loader);
    }

    /**
     * @memberof ajax
     * @summary removes the loader from loaderTarget
     * @private
     * @param target {Element}
     */
    function stopLoader(target) {
        target.removeChild(loader);
    }

    /**
     * @memberof ajax
     * @summary executes the XMLHttpRequest
     * @private
     * @param c {object} request configuration hash
     */
    function sendRequest(c) {
        var req = new XMLHttpRequest();

        if (c.loaderTarget) {
            startLoader(c.loaderTarget);
        }

        // start XMLHttpRequest
        req.open(c.method, c.url, c.async);
        setRequestHeaders(req, c.setHeaders);

        // request now going through
        req.onreadystatechange = function() {
            // Headers & status are received
            if (req.readyState === 2) {
                if (c.onHeaders) {
                    c.onHeaders(req.getAllResponseHeaders());
                }
            }

            // request is complete and successful
            if (req.readyState === 4) {
                // loader needs to be removed BEFORE callbacks
                if (c.loaderTarget) {
                    stopLoader(c.loaderTarget);
                }

                // process sucess or failure callbacks
                if (req.status.toString().charAt(0) === "2" && c.onSuccess) {
                    c.onSuccess(getResponse(req, c), req.status);
                } else if (c.onFailure) {
                    c.onFailure(getResponse(req, c), req.status);
                }
            }
        };
        req.send(c.data);
    }

    /**
     * @memberof ajax
     * @summary sets basic headers for the request and sets the additional ones provided by the configuration
     * @private
     * @param req {object} XMLHttpRequest object
     * @param headers {object} additional headers to be injected
     */
    function setRequestHeaders(req, headers) {
        // set default values
        if (!headers["Content-Type"]) {
            headers["Content-Type"] = "application/json;charset=utf-8";
        }

        if (!headers.Accept) {
            headers.Accept = "application/json";
        }

        if (!headers["X-Requested-With"]) {
            headers["X-Requested-With"] = "XMLHttpRequest";
        }

        // get all object (t) keys from own properties
        // inject them as request headers
        Object.keys(headers).forEach(function(header) {
            req.setRequestHeader(header, headers[header]);
        });

        // xhr2 spec
        if (req.responseType) {
            req.responseType = c.responseType; // "arraybuffer", "blob", "document", "json", "text"
        }
    }

    /**
     * @memberof ajax
     * @summary parses the response data based on provided responseType
     * @private
     * @param req {object} XMLHttpRequest object
     * @param c {object} configuration hash
     * @returns the parsed data
     */
    function getResponse(req, c) {
        var r = req.response;

        if (c.responseType && c.responseType === "json" && r !== "") {
            r = JSON.parse(r);
        }

        return r;
    }

    /**
     * @memberof ajax
     * @private
     * @summary verifies content provided by configuration object
     * @param c {object} configuration hash
     * @returns {boolean} result of validation (true|false)
     */
    function validateConfig(c) {
        if (Object.prototype.toString.call(c.url) !== "[object String]") {
            throw new TypeError("ajax: requires a URL string");
        }

        if (c.loaderTarget && c.loaderTarget.nodeType !== 1) {
            throw new TypeError("ajax: 'loaderTarget' is not an HTML element");
        }

        if (Object.prototype.toString.call(c.method) === "[object String]") {
            c.method = c.method.toUpperCase();
            if (!["GET","POST","PUT","DELETE"].some(function(method) {
                return method === c.method;
            })) {
                throw new TypeError("ajax: 'method' must have one of the following values:\nGET\nPOST\nPUT\nDelete");
            }
        } else {
            throw Error("ajax: query 'method' is required");
        }

        if (c.setHeaders && Object.prototype.toString.call(c.setHeaders) !== "[object Object]") {
            throw new TypeError("ajax: 'setHeaders' is not an object");
        }

        if (c.onFailure && Object.prototype.toString.call(c.onFailure) !== "[object Function]") {
            throw new TypeError("ajax: onFailure must be a function");
        }
        if (c.onSuccess && Object.prototype.toString.call(c.onFailure) !== "[object Function]") {
            throw new TypeError("ajax: onFailure must be a function");
        }
        if (c.onHeaders && Object.prototype.toString.call(c.onFailure) !== "[object Function]") {
            throw new TypeError("ajax: onFailure must be a function");
        }

        if (c.responseType) {
            if (!["json","text","arraybuffer","document","blob"].some(function(value) {
                    return value === c.responseType;
                })) {
                throw new Error("ajax: responseType must have one of the following value:\njson\ntext\ndocument\nblob\narraybuffer");
            }
        }

        return true;
    }

    /**
     * @memberof ajax
     * @private
     * @summary builds the final request configuration object
     * @param c {object} configuration hash
     * @returns {
     *  {
     *   async: boolean,
     *   data: (object|null),
     *   setHeaders: (object|{}),
     *   method: string,
     *   onFailure: (function|null),
     *   onHeaders: (function|null),
     *   onSuccess: (function|null),
     *   responseType: (string),
     *   url: string,
     *   loaderTarget: (Element|null)
     *   }
     *  }
     */
    function finalizeConfig(c) {
        return {
            async: !!c.async,
            data: c.data || null,
            setHeaders: c.setHeaders || {},
            method: c.method,
            onFailure: c.onFailure || null,
            onHeaders: c.onHeaders || null,
            onSuccess: c.onSuccess || null,
            responseType: c.responseType || "text",
            url: encodeURI(c.url).replace(/%5B/g, "[").replace(/%5D/g, "]"),
            loaderTarget: c.loadTarget || null
        };
    }

    function query(c) {
        if (validateConfig(c)) {
            sendRequest(finalizeConfig(c));
        }
    }

    return query;
}());
<commit_msg>fixed callback validations<commit_after>/**
 * @namespace ajax
 * @summary module to make ajax requests
 */
var ajax = (function() {
    "use strict";
    /**
     * @summary loader HTML element injected into loaderTarget when ajax is running
     * @private
     * @type {Element}
     */
    var loader = document.createElement("div");
    loader.className = "ajax-loader";

    /**
     * @memberof ajax
     * @summary injects the loader element into loaderTarget
     * @private
     * @param target {Element}
     */
    function startLoader(target) {
        target.appendChild(loader);
    }

    /**
     * @memberof ajax
     * @summary removes the loader from loaderTarget
     * @private
     * @param target {Element}
     */
    function stopLoader(target) {
        target.removeChild(loader);
    }

    /**
     * @memberof ajax
     * @summary executes the XMLHttpRequest
     * @private
     * @param c {object} request configuration hash
     */
    function sendRequest(c) {
        var req = new XMLHttpRequest();

        if (c.loaderTarget) {
            startLoader(c.loaderTarget);
        }

        // start XMLHttpRequest
        req.open(c.method, c.url, c.async);
        setRequestHeaders(req, c.setHeaders);

        // request now going through
        req.onreadystatechange = function() {
            // Headers & status are received
            if (req.readyState === 2) {
                if (c.onHeaders) {
                    c.onHeaders(req.getAllResponseHeaders());
                }
            }

            // request is complete and successful
            if (req.readyState === 4) {
                // loader needs to be removed BEFORE callbacks
                if (c.loaderTarget) {
                    stopLoader(c.loaderTarget);
                }

                // process sucess or failure callbacks
                if (req.status.toString().charAt(0) === "2" && c.onSuccess) {
                    c.onSuccess(getResponse(req, c), req.status);
                } else if (c.onFailure) {
                    c.onFailure(getResponse(req, c), req.status);
                }
            }
        };
        req.send(c.data);
    }

    /**
     * @memberof ajax
     * @summary sets basic headers for the request and sets the additional ones provided by the configuration
     * @private
     * @param req {object} XMLHttpRequest object
     * @param headers {object} additional headers to be injected
     */
    function setRequestHeaders(req, headers) {
        // set default values
        if (!headers["Content-Type"]) {
            headers["Content-Type"] = "application/json;charset=utf-8";
        }

        if (!headers.Accept) {
            headers.Accept = "application/json";
        }

        if (!headers["X-Requested-With"]) {
            headers["X-Requested-With"] = "XMLHttpRequest";
        }

        // get all object (t) keys from own properties
        // inject them as request headers
        Object.keys(headers).forEach(function(header) {
            req.setRequestHeader(header, headers[header]);
        });

        // xhr2 spec
        if (req.responseType) {
            req.responseType = c.responseType; // "arraybuffer", "blob", "document", "json", "text"
        }
    }

    /**
     * @memberof ajax
     * @summary parses the response data based on provided responseType
     * @private
     * @param req {object} XMLHttpRequest object
     * @param c {object} configuration hash
     * @returns the parsed data
     */
    function getResponse(req, c) {
        var r = req.response;

        if (c.responseType && c.responseType === "json" && r !== "") {
            r = JSON.parse(r);
        }

        return r;
    }

    /**
     * @memberof ajax
     * @private
     * @summary verifies content provided by configuration object
     * @param c {object} configuration hash
     * @returns {boolean} result of validation (true|false)
     */
    function validateConfig(c) {
        if (Object.prototype.toString.call(c.url) !== "[object String]") {
            throw new TypeError("ajax: requires a URL string");
        }

        if (c.loaderTarget && c.loaderTarget.nodeType !== 1) {
            throw new TypeError("ajax: 'loaderTarget' is not an HTML element");
        }

        if (Object.prototype.toString.call(c.method) === "[object String]") {
            c.method = c.method.toUpperCase();
            if (!["GET","POST","PUT","DELETE"].some(function(method) {
                return method === c.method;
            })) {
                throw new TypeError("ajax: 'method' must have one of the following values:\nGET\nPOST\nPUT\nDelete");
            }
        } else {
            throw Error("ajax: query 'method' is required");
        }

        if (c.setHeaders && Object.prototype.toString.call(c.setHeaders) !== "[object Object]") {
            throw new TypeError("ajax: 'setHeaders' is not an object");
        }

        if (c.onFailure && Object.prototype.toString.call(c.onFailure) !== "[object Function]") {
            throw new TypeError("ajax: onFailure must be a function");
        }
        if (c.onSuccess && Object.prototype.toString.call(c.onSuccess) !== "[object Function]") {
            throw new TypeError("ajax: onFailure must be a function");
        }
        if (c.onHeaders && Object.prototype.toString.call(c.onHEaders) !== "[object Function]") {
            throw new TypeError("ajax: onFailure must be a function");
        }

        if (c.responseType) {
            if (!["json","text","arraybuffer","document","blob"].some(function(value) {
                    return value === c.responseType;
                })) {
                throw new Error("ajax: responseType must have one of the following value:\njson\ntext\ndocument\nblob\narraybuffer");
            }
        }

        return true;
    }

    /**
     * @memberof ajax
     * @private
     * @summary builds the final request configuration object
     * @param c {object} configuration hash
     * @returns {
     *  {
     *   async: boolean,
     *   data: (object|null),
     *   setHeaders: (object|{}),
     *   method: string,
     *   onFailure: (function|null),
     *   onHeaders: (function|null),
     *   onSuccess: (function|null),
     *   responseType: (string),
     *   url: string,
     *   loaderTarget: (Element|null)
     *   }
     *  }
     */
    function finalizeConfig(c) {
        return {
            async: !!c.async,
            data: c.data || null,
            setHeaders: c.setHeaders || {},
            method: c.method,
            onFailure: c.onFailure || null,
            onHeaders: c.onHeaders || null,
            onSuccess: c.onSuccess || null,
            responseType: c.responseType || "text",
            url: encodeURI(c.url).replace(/%5B/g, "[").replace(/%5D/g, "]"),
            loaderTarget: c.loadTarget || null
        };
    }

    function query(c) {
        if (validateConfig(c)) {
            sendRequest(finalizeConfig(c));
        }
    }

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