<commit_before>const commonModal = require('client/components/modal_common/index');
const config = require('./config.json');
const request = require('../../request');
const networkType = require('./network_type');
const __ = require('locale/client/dashboard.lang.json');
const getErrorMessage = require('../../../../utils/error_message');

function chooseVlan(refs, vlanState, testMin, testMax, testAddr, netVlanstate, subnetChecked, vlanLength){
  let vlanNumber = parseInt(vlanState.value, 10);
  if (/^[0-9]*$/.test(vlanState.value)) {
    if (!(vlanNumber >= testMin && vlanNumber <= testMax)) {
      refs.btn.setState({
        disabled: true
      });
      refs.vlan_id.setState({
        error: vlanState.value !== ''
      });
    } else if (subnetChecked) {
      refs.vlan_id.setState({
        error: false
      });
      if (vlanState.value !== '' && netVlanstate.value === ''){
        refs.btn.setState({
          disabled: true
        });
      } else {
        if(testAddr.test(netVlanstate.value, 10) && (vlanNumber > testMin && vlanNumber < testMax)) {
          refs.btn.setState({
            disabled: false
          });
        }
      }
    } else if (!subnetChecked) {
      refs.vlan_id.setState({
        error: false
      });
      refs.btn.setState({
        disabled: vlanState.value === ''
      });
    }
  } else {
    refs.vlan_id.setState({
      error: true
    });
  }
  if (vlanLength === 1) {
    refs.select_physical_network.setState({
      hide: true
    });
  }
}

function chooseFlat(refs, subnetChecked, netVlanstate, testFlat, flatState, testAddr) {
  if (!testFlat.test(flatState.value)) {
    refs.btn.setState({
      disabled: true
    });
    refs.physical_network.setState({
      error: flatState.value !== ''
    });
  } else if (subnetChecked) {
    refs.physical_network.setState({
      error: false
    });
    if (flatState.value !== '' && netVlanstate.value === ''){
      refs.btn.setState({
        disabled: true
      });
    } else {
      if(testAddr.test(netVlanstate.value) && flatState) {
        refs.btn.setState({
          disabled: false
        });
      }
    }
  } else if (!subnetChecked) {
    refs.physical_network.setState({
      error: false
    });
    refs.btn.setState({
      disabled: flatState.value === ''
    });
  }
}

function pop(parent, callback) {
  if (!HALO.settings.is_show_vlan) {
    config.fields[2].hide = true;
  }

  let props = {
    __: __,
    parent: parent,
    config: config,
    onInitialize: function(refs, field) {
      refs.enable_vlan.setState({
        renderer: networkType
      });
      let phyNet = HALO.configs.neutron_network_vlanranges;
      let phyItem;
      let item = phyNet.map((items, index) => {
        phyItem = items.split(':');
        return {
          id: phyItem[0],
          name: phyItem[0]
        };
      });
      refs.select_physical_network.setState({
        data: item,
        value: item[0].id
      });
    },
    onConfirm: function(refs, cb) {
      let data = {
        name: refs.network_name.state.value
      };
      let netType = refs.enable_vlan.refs.enable_type.state.selectedValue;
      switch(netType) {
        case 'vlan':
          data['provider:network_type'] = 'vlan';
          refs.vlan_id.setState({
            hide: false
          });
          let v = HALO.configs.neutron_network_vlanranges;
          let vId = refs.vlan_id.state.value;
          let physicalNetwork = refs.select_physical_network.state.value;
          if(v.length === 1) {
            data['provider:physical_network'] = v[0].split(':')[0];
          }
          data['provider:segmentation_id'] = vId;
          data['provider:physical_network'] = physicalNetwork;
          refs.btn.setState({
            disabled: true
          });
          break;
        case 'vxlan':
          data['provider:network_type'] = 'vxlan';
          break;
        case 'flat':
          data['provider:network_type'] = 'flat';
          let physical = refs.physical_network.state.value;
          if(physical !== '') {
            data['provider:physical_network'] = physical;
          }
          break;
        default:
          break;
      }
      if (!refs.enable_security.state.checked) {
        data.port_security_enabled = false;
      }

      if(refs.create_subnet.state.checked) {
        request.createNetwork(data).then((res) => {
          data = {
            ip_version: 4,
            name: refs.subnet_name.state.value,
            network_id: res.network.id,
            cidr: refs.net_address.state.value,
            enable_dhcp: true
          };
          request.createSubnet(data).then(() => {
            callback && callback(res.network);
            cb(true);
          });
        });
      } else {
        request.createNetwork(data).then((res) => {
          callback && callback(res.network);
          cb(true);
        }).catch(err => {
          cb(false, getErrorMessage(err));
        });
      }
    },
    onAction: function(field, status, refs) {
      let subnetChecked = refs.create_subnet.state.checked,
        netVlanstate = refs.net_address.state,
        testAddr = /^(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\/(\d|1\d|2\d|3[0-2])$/,
        vlanState = refs.vlan_id.state,
        flatState = refs.physical_network.state,
        enableType = refs.enable_vlan.refs.enable_type.state.selectedValue,
        testFlat = /^\w+$/;
      let phyiscalNet = refs.select_physical_network.state.value;
      let vlanLength = HALO.configs.neutron_network_vlanranges.length;

      let vlanRanges = HALO.configs.neutron_network_vlanranges;
      let vlanItem = [];
      let testMin, testMax;
      vlanRanges.forEach(item => {
        vlanItem.push(item.split(':'));
      });
      switch (field) {
        case 'create_subnet':
          refs.subnet_name.setState({
            hide: !subnetChecked
          });
          refs.net_address.setState({
            hide: !subnetChecked
          });
          refs.btn.setState({
            disabled: vlanState.value === ''
          });
          break;
        case 'vlan_id':
          if (enableType === 'vlan') {
            vlanItem.forEach((m) => {
              if (m[0] === phyiscalNet) {
                testMin = m[1];
                testMax = m[2];
                chooseVlan(refs, vlanState, testMin, testMax, testAddr, netVlanstate, subnetChecked, vlanLength);
              }
            });
            refs.select_physical_network.setState({
              hide: false
            });
            if (vlanLength === 1) {
              refs.select_physical_network.setState({
                hide: true
              });
            }
          }
          break;
        case 'physical_network':
          if (enableType === 'flat') {
            chooseFlat(refs, subnetChecked, netVlanstate, testFlat, flatState, testAddr);
            refs.select_physical_network.setState({
              hide: true
            });
          }
          break;
        case 'enable_vlan':
          switch (enableType) {
            case 'vlan':
              refs.vlan_id.setState({
                hide: false
              });
              refs.physical_network.setState({
                hide: true
              });
              vlanItem.forEach((m) => {
                if (m[0] === phyiscalNet) {
                  testMin = m[1];
                  testMax = m[2];
                  chooseVlan(refs, vlanState, testMin, testMax, testAddr, netVlanstate, subnetChecked);
                }
              });
              if (!subnetChecked) {
                refs.vlan_id.setState({
                  error: false
                });
                refs.btn.setState({
                  disabled: vlanState.value === ''
                });
              }
              break;
            case 'vxlan':
              if (subnetChecked && testAddr.test(netVlanstate.value)) {
                refs.btn.setState({
                  disabled: netVlanstate.value === ''
                });
              } else if (!subnetChecked) {
                refs.btn.setState({
                  disabled: false
                });
              }
              refs.vlan_id.setState({
                hide: true
              });
              refs.physical_network.setState({
                hide: true
              });
              refs.select_physical_network.setState({
                hide: true
              });
              break;
            case 'flat':
              if (enableType === 'flat') {
                chooseFlat(refs, subnetChecked, netVlanstate, testFlat, flatState, testAddr);
              }
              refs.vlan_id.setState({
                hide: true
              });
              refs.physical_network.setState({
                hide: false
              });
              refs.select_physical_network.setState({
                hide: true
              });
              break;
            default:
              break;
          }
          break;
        case 'select_physical_network':
          vlanItem.forEach((m) => {
            if (m[0] === phyiscalNet) {
              testMin = m[1];
              testMax = m[2];
              refs.vlan_id.setState({
                tip_info: __.vlan_tip.replace('{0}', testMin).replace('{1}', testMax)
              });
              chooseVlan(refs, vlanState, testMin, testMax, testAddr, netVlanstate, subnetChecked);
            }
          });
          break;
        case 'net_address':
          if(refs.create_subnet.state.checked) {
            if (!testAddr.test(netVlanstate.value)) {
              if(netVlanstate.value !== '') {
                refs.net_address.setState({
                  error: true
                });
                refs.btn.setState({
                  disabled: true
                });
              } else {
                refs.net_address.setState({
                  error: false
                });
                refs.btn.setState({
                  disabled: true
                });
              }
            } else {
              refs.net_address.setState({
                error: false
              });
              if (enableType === 'vxlan') {
                refs.btn.setState({
                  disabled: false
                });
              } else if (enableType === 'vlan') {
                vlanItem.forEach((m) => {
                  if (m[0] === phyiscalNet) {
                    if (m[0] === phyiscalNet) {
                      testMin = m[1];
                      testMax = m[2];
                      if(!(typeof parseInt(vlanState.value, 10) === 'number' && vlanState.value >= testMin && vlanState.value <= testMax)){
                        refs.btn.setState({
                          disabled: true
                        });
                        refs.vlan_id.setState({
                          error: vlanState.value !== ''
                        });
                      } else if (vlanState.value !== '' && netVlanstate.value === ''){
                        refs.btn.setState({
                          disabled: true
                        });
                      } else {
                        if(netVlanstate && vlanState) {
                          refs.btn.setState({
                            disabled: false
                          });
                        }
                      }
                    }
                  }
                });
              } else {
                if (!testFlat.test(flatState.value)) {
                  refs.btn.setState({
                    disabled: true
                  });
                  refs.physical_network.setState({
                    error: flatState.value !== ''
                  });
                } else if (vlanState.value !== '' && netVlanstate.value === ''){
                  refs.btn.setState({
                    disabled: true
                  });
                  refs.vlan_id.setState({
                    error: false
                  });
                } else {
                  refs.physical_network.setState({
                    error: false
                  });

                  if(netVlanstate && flatState) {
                    refs.btn.setState({
                      disabled: false
                    });
                  }
                }
                refs.vlan_id.setState({
                  hide: true
                });
                refs.physical_network.setState({
                  hide: false
                });
              }
            }
          }
          break;
        default:
          break;
      }
    }
  };

  commonModal(props);
}

module.exports = pop;
<commit_msg>network: vlan bugfix<commit_after>const commonModal = require('client/components/modal_common/index');
const config = require('./config.json');
const request = require('../../request');
const networkType = require('./network_type');
const __ = require('locale/client/dashboard.lang.json');
const getErrorMessage = require('../../../../utils/error_message');

function chooseVlan(refs, vlanState, testMin, testMax, testAddr, netVlanstate, subnetChecked, vlanLength){
  let vlanNumber = parseInt(vlanState.value, 10);
  if (/^[0-9]*$/.test(vlanState.value)) {
    if (!(vlanNumber >= testMin && vlanNumber <= testMax)) {
      refs.btn.setState({
        disabled: true
      });
      refs.vlan_id.setState({
        error: vlanState.value !== ''
      });
    } else if (subnetChecked) {
      refs.vlan_id.setState({
        error: false
      });
      if (vlanState.value !== '' && netVlanstate.value === ''){
        refs.btn.setState({
          disabled: true
        });
      } else {
        if(testAddr.test(netVlanstate.value, 10) && (vlanNumber > testMin && vlanNumber < testMax)) {
          refs.btn.setState({
            disabled: false
          });
        }
      }
    } else if (!subnetChecked) {
      refs.vlan_id.setState({
        error: false
      });
      refs.btn.setState({
        disabled: vlanState.value === ''
      });
    }
  } else {
    refs.vlan_id.setState({
      error: true
    });
  }
  if (vlanLength === 1) {
    refs.select_physical_network.setState({
      hide: true
    });
  }
}

function chooseFlat(refs, subnetChecked, netVlanstate, testFlat, flatState, testAddr) {
  if (!testFlat.test(flatState.value)) {
    refs.btn.setState({
      disabled: true
    });
    refs.physical_network.setState({
      error: flatState.value !== ''
    });
  } else if (subnetChecked) {
    refs.physical_network.setState({
      error: false
    });
    if (flatState.value !== '' && netVlanstate.value === ''){
      refs.btn.setState({
        disabled: true
      });
    } else {
      if(testAddr.test(netVlanstate.value) && flatState) {
        refs.btn.setState({
          disabled: false
        });
      }
    }
  } else if (!subnetChecked) {
    refs.physical_network.setState({
      error: false
    });
    refs.btn.setState({
      disabled: flatState.value === ''
    });
  }
}

function pop(parent, callback) {
  if (!HALO.settings.is_show_vlan) {
    config.fields[2].hide = true;
  }
  let phyNet = HALO.configs.neutron_network_vlanranges.split(',');
  let props = {
    __: __,
    parent: parent,
    config: config,
    onInitialize: function(refs, field) {
      refs.enable_vlan.setState({
        renderer: networkType
      });

      let phyItem;
      let item = phyNet.map((items, index) => {
        phyItem = items.split(':');
        return {
          id: phyItem[0],
          name: phyItem[0]
        };
      });
      refs.select_physical_network.setState({
        data: item,
        value: item[0].id
      });
    },
    onConfirm: function(refs, cb) {
      let data = {
        name: refs.network_name.state.value
      };
      let netType = refs.enable_vlan.refs.enable_type.state.selectedValue;
      switch(netType) {
        case 'vlan':
          data['provider:network_type'] = 'vlan';
          refs.vlan_id.setState({
            hide: false
          });
          let vId = refs.vlan_id.state.value;
          let physicalNetwork = refs.select_physical_network.state.value;
          if(phyNet.length === 1) {
            data['provider:physical_network'] = phyNet[0].split(':')[0];
          }
          data['provider:segmentation_id'] = vId;
          data['provider:physical_network'] = physicalNetwork;
          refs.btn.setState({
            disabled: true
          });
          break;
        case 'vxlan':
          data['provider:network_type'] = 'vxlan';
          break;
        case 'flat':
          data['provider:network_type'] = 'flat';
          let physical = refs.physical_network.state.value;
          if(physical !== '') {
            data['provider:physical_network'] = physical;
          }
          break;
        default:
          break;
      }
      if (!refs.enable_security.state.checked) {
        data.port_security_enabled = false;
      }

      if(refs.create_subnet.state.checked) {
        request.createNetwork(data).then((res) => {
          data = {
            ip_version: 4,
            name: refs.subnet_name.state.value,
            network_id: res.network.id,
            cidr: refs.net_address.state.value,
            enable_dhcp: true
          };
          request.createSubnet(data).then(() => {
            callback && callback(res.network);
            cb(true);
          });
        });
      } else {
        request.createNetwork(data).then((res) => {
          callback && callback(res.network);
          cb(true);
        }).catch(err => {
          cb(false, getErrorMessage(err));
        });
      }
    },
    onAction: function(field, status, refs) {
      let subnetChecked = refs.create_subnet.state.checked,
        netVlanstate = refs.net_address.state,
        testAddr = /^(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\/(\d|1\d|2\d|3[0-2])$/,
        vlanState = refs.vlan_id.state,
        flatState = refs.physical_network.state,
        enableType = refs.enable_vlan.refs.enable_type.state.selectedValue,
        testFlat = /^\w+$/;
      let phyiscalNet = refs.select_physical_network.state.value;
      let vlanLength = phyNet.length;

      let vlanItem = [];
      let testMin, testMax;
      phyNet.forEach(item => {
        vlanItem.push(item.split(':'));
      });
      switch (field) {
        case 'create_subnet':
          refs.subnet_name.setState({
            hide: !subnetChecked
          });
          refs.net_address.setState({
            hide: !subnetChecked
          });
          refs.btn.setState({
            disabled: vlanState.value === ''
          });
          break;
        case 'vlan_id':
          if (enableType === 'vlan') {
            vlanItem.forEach((m) => {
              if (m[0] === phyiscalNet) {
                testMin = m[1];
                testMax = m[2];
                chooseVlan(refs, vlanState, testMin, testMax, testAddr, netVlanstate, subnetChecked, vlanLength);
              }
            });
            refs.select_physical_network.setState({
              hide: false
            });
            if (vlanLength === 1) {
              refs.select_physical_network.setState({
                hide: true
              });
            }
          }
          break;
        case 'physical_network':
          if (enableType === 'flat') {
            chooseFlat(refs, subnetChecked, netVlanstate, testFlat, flatState, testAddr);
            refs.select_physical_network.setState({
              hide: true
            });
          }
          break;
        case 'enable_vlan':
          switch (enableType) {
            case 'vlan':
              refs.vlan_id.setState({
                hide: false
              });
              refs.physical_network.setState({
                hide: true
              });
              vlanItem.forEach((m) => {
                if (m[0] === phyiscalNet) {
                  testMin = m[1];
                  testMax = m[2];
                  chooseVlan(refs, vlanState, testMin, testMax, testAddr, netVlanstate, subnetChecked);
                }
              });
              if (!subnetChecked) {
                refs.vlan_id.setState({
                  error: false
                });
                refs.btn.setState({
                  disabled: vlanState.value === ''
                });
              }
              break;
            case 'vxlan':
              if (subnetChecked && testAddr.test(netVlanstate.value)) {
                refs.btn.setState({
                  disabled: netVlanstate.value === ''
                });
              } else if (!subnetChecked) {
                refs.btn.setState({
                  disabled: false
                });
              }
              refs.vlan_id.setState({
                hide: true
              });
              refs.physical_network.setState({
                hide: true
              });
              refs.select_physical_network.setState({
                hide: true
              });
              break;
            case 'flat':
              if (enableType === 'flat') {
                chooseFlat(refs, subnetChecked, netVlanstate, testFlat, flatState, testAddr);
              }
              refs.vlan_id.setState({
                hide: true
              });
              refs.physical_network.setState({
                hide: false
              });
              refs.select_physical_network.setState({
                hide: true
              });
              refs.btn.setState({
                disabled: vlanState.value === ''
              });
              break;
            default:
              break;
          }
          break;
        case 'select_physical_network':
          vlanItem.forEach((m) => {
            if (m[0] === phyiscalNet) {
              testMin = m[1];
              testMax = m[2];
              refs.vlan_id.setState({
                tip_info: __.vlan_tip.replace('{0}', testMin).replace('{1}', testMax)
              });
              chooseVlan(refs, vlanState, testMin, testMax, testAddr, netVlanstate, subnetChecked);
            }
          });
          break;
        case 'net_address':
          if(refs.create_subnet.state.checked) {
            if (!testAddr.test(netVlanstate.value)) {
              if(netVlanstate.value !== '') {
                refs.net_address.setState({
                  error: true
                });
                refs.btn.setState({
                  disabled: true
                });
              } else {
                refs.net_address.setState({
                  error: false
                });
                refs.btn.setState({
                  disabled: true
                });
              }
            } else {
              refs.net_address.setState({
                error: false
              });
              if (enableType === 'vxlan') {
                refs.btn.setState({
                  disabled: false
                });
              } else if (enableType === 'vlan') {
                vlanItem.forEach((m) => {
                  if (m[0] === phyiscalNet) {
                    if (m[0] === phyiscalNet) {
                      testMin = m[1];
                      testMax = m[2];
                      if(!(typeof parseInt(vlanState.value, 10) === 'number' && vlanState.value >= testMin && vlanState.value <= testMax)){
                        refs.btn.setState({
                          disabled: true
                        });
                        refs.vlan_id.setState({
                          error: vlanState.value !== ''
                        });
                      } else if (vlanState.value !== '' && netVlanstate.value === ''){
                        refs.btn.setState({
                          disabled: true
                        });
                      } else {
                        if(netVlanstate && vlanState) {
                          refs.btn.setState({
                            disabled: false
                          });
                        }
                      }
                    }
                  }
                });
              } else {
                if (!testFlat.test(flatState.value)) {
                  refs.btn.setState({
                    disabled: true
                  });
                  refs.physical_network.setState({
                    error: flatState.value !== ''
                  });
                } else if (vlanState.value !== '' && netVlanstate.value === ''){
                  refs.btn.setState({
                    disabled: true
                  });
                  refs.vlan_id.setState({
                    error: false
                  });
                } else {
                  refs.physical_network.setState({
                    error: false
                  });

                  if(netVlanstate && flatState) {
                    refs.btn.setState({
                      disabled: false
                    });
                  }
                }
                refs.vlan_id.setState({
                  hide: true
                });
                refs.physical_network.setState({
                  hide: false
                });
              }
            }
          }
          break;
        default:
          break;
      }
    }
  };

  commonModal(props);
}

module.exports = pop;
<|endoftext|>


<commit_before>define('tempo30/app/tracking', [
    'jquery',
    'tempo30/model/version'
], function ($, version) {

    'use strict';

    var url="https://tools.adfc-hamburg.de/tempo30-backend/master/track.php?";
    var first=0;
    function track(data, step) {
        if (data.tracking === 0) {
            return;
        }
        if (first != data.tracking) {
            first= data.tracking;
            $.get(url, {
                id: data.tracking,
                url: window.location.toString(),
                rev: version.revision,
                step: step,
            });
        } else {
            $.get(url, {
                id: data.tracking,
                step: step,
            });

        }
    };
    return track;
});
<commit_msg>added tracking, fixing #50<commit_after>define('tempo30/app/tracking', [
    'jquery',
    'tempo30/model/version'
], function ($, version) {

    'use strict';

    var url="https://tools.adfc-hamburg.de/tempo30-backend/master/track.php?";
    var first=0;
    function track(data, step) {
        if (data.tracking === 0) {
            return;
        }
        if (first != data.tracking) {
            first= data.tracking;
            $.get(url, {
                id: data.tracking,
                url: window.location.toString(),
                rev: version.revision,
                step: step,
            });
        } else {
            $.get(url, {
                id: data.tracking,
                step: step,
            });

        }
    }
    return track;
});
<|endoftext|>


<commit_before>const path = require('path');
const electron = require('electron');

const remote = electron.remote;
const mainProcess = remote.require('./main');
window.$ = window.jQuery = require('jquery');
var Sortable = require('sortablejs');
require('../menu');
require('pkginfo')(module, 'version');

/* global $:true */
/* global window:true */
/* global document:true */

$(document).ready(function () {
	mainProcess.sortableList(function (data) {
		mainProcess.parseConfigRenderer('get', 'main', false, function (mainConfig) {
			var length;
			if (mainConfig.extraCabinets === true) {
				length = Object.keys(data).length;
			} else {
				length = 30;
			}
			for (let i = 0; i < length; i++) {
				$('#videoFiles').append(`<li class="list-group-item"><span class="badge">${i + 1}</span>${path.basename(data[i].path)}</li>`);
			}
		});
	});

	$('.bottom-bar').addClass('bottom-bar-info');
	$('.bottom-bar').html(`Version: ${module.exports.version}`);
});

var el = document.getElementById('videoFiles');
var sortable = new Sortable(el, {
	onEnd: function (evt) {
		switchGridPosition(evt.oldIndex, evt.newIndex);
	}
});

function switchGridPosition(from, to) {
	mainProcess.parseConfigRenderer('get', 'videoFiles', false, function (videoFiles) {
		var videoFilesTmp = {};
		var videoFilesArr = [];
		// Convert to array
		videoFilesArr = Object.keys(videoFiles).map(key => videoFiles[key]);
		// Move item in array
		videoFilesArr = arrayMove(videoFilesArr, from, to);
		// Convert back to Object
		videoFilesTmp = videoFilesArr.reduce(function (o, v, i) {
			o[i] = v;
			return o;
		}, {});
		// Save to config
		mainProcess.parseConfigRenderer('set', 'videoFiles', videoFilesTmp, function () {
			// Re number the list
			var i = 1;
			$('#videoFiles li').each(function () {
				$(this)[0].firstChild.innerText = i++;
			});
		});
	});
}

function arrayMove(array, oldIndex, newIndex) {
	while (oldIndex < 0) {
		oldIndex += array.length;
	}
	while (newIndex < 0) {
		newIndex += array.length;
	}
	if (newIndex >= array.length) {
		var k = newIndex - array.length;
		while ((k--) + 1) {
			array.push(undefined);
		}
	}
	array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
	return array;
}
<commit_msg>Fix no-unused-vars<commit_after>const path = require('path');
const electron = require('electron');

const remote = electron.remote;
const mainProcess = remote.require('./main');
window.$ = window.jQuery = require('jquery');
var Sortable = require('sortablejs');
require('../menu');
require('pkginfo')(module, 'version');

/* global $:true */
/* global window:true */
/* global document:true */

$(document).ready(function () {
	mainProcess.sortableList(function (data) {
		mainProcess.parseConfigRenderer('get', 'main', false, function (mainConfig) {
			var length;
			if (mainConfig.extraCabinets === true) {
				length = Object.keys(data).length;
			} else {
				length = 30;
			}
			for (let i = 0; i < length; i++) {
				$('#videoFiles').append(`<li class="list-group-item"><span class="badge">${i + 1}</span>${path.basename(data[i].path)}</li>`);
			}
		});
	});

	$('.bottom-bar').addClass('bottom-bar-info');
	$('.bottom-bar').html(`Version: ${module.exports.version}`);
});

var el = document.getElementById('videoFiles');
Sortable.create(el, {
	onEnd: function (evt) {
		switchGridPosition(evt.oldIndex, evt.newIndex);
	}
});

function switchGridPosition(from, to) {
	mainProcess.parseConfigRenderer('get', 'videoFiles', false, function (videoFiles) {
		var videoFilesTmp = {};
		var videoFilesArr = [];
		// Convert to array
		videoFilesArr = Object.keys(videoFiles).map(key => videoFiles[key]);
		// Move item in array
		videoFilesArr = arrayMove(videoFilesArr, from, to);
		// Convert back to Object
		videoFilesTmp = videoFilesArr.reduce(function (o, v, i) {
			o[i] = v;
			return o;
		}, {});
		// Save to config
		mainProcess.parseConfigRenderer('set', 'videoFiles', videoFilesTmp, function () {
			// Re number the list
			var i = 1;
			$('#videoFiles li').each(function () {
				$(this)[0].firstChild.innerText = i++;
			});
		});
	});
}

function arrayMove(array, oldIndex, newIndex) {
	while (oldIndex < 0) {
		oldIndex += array.length;
	}
	while (newIndex < 0) {
		newIndex += array.length;
	}
	if (newIndex >= array.length) {
		var k = newIndex - array.length;
		while ((k--) + 1) {
			array.push(undefined);
		}
	}
	array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
	return array;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var fs = require('fs');
var glob = require('glob');
var nconf = require('nconf');
var path = require('path');
var program = require('commander');
var prompt = require('prompt');
var qs = require('querystring');
var request = require('request');
var unzip = require('unzip');
var url = require('url');

var config = 'chatbot.json';

var sep = function (str) {
    return str ? '/' + str : '';
}

var composeUri = function (mode, botname, kind, filename) {
    var uri = {
	protocol: nconf.get('protocol'),
	hostname: nconf.get('hostname')
    }
    var path = mode;
    path += sep(conf_app_id());
    path += sep(botname);
    path += sep(kind);
    path += sep(filename);
    uri.pathname = path;
    return uri;
}

var composeParams = function (params) {
    params.user_key = conf_user_key();
    return params;
}

var listUri = function () {
    var uri = composeUri('bot', '', '', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var botUri = function () {
    var uri = composeUri('bot', conf_botname(), '', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var fileUri = function (filename) {
    var ext = path.extname(filename);
    var base = path.basename(filename, ext);
    var kind = ext.slice(1);
    var botname = conf_botname();
    var uri;
    if (kind === 'pdefaults' || kind === 'properties')
	uri = composeUri('bot', botname, kind, '');
    else if (kind === 'map' || kind === 'set' || kind === 'substitution')
	uri = composeUri('bot', botname, kind, base);
    else if (kind === 'aiml')
	uri = composeUri('bot', botname, 'file', base + ext);
    else {
	console.log('illegal file name: ' + filename);
	return;
    }
    uri.query = composeParams({});
    return url.format(uri);
}

var zipUri = function () {
    var uri = composeUri('bot', conf_botname(), '', '');
    uri.query = composeParams({return: 'zip'});
    return url.format(uri);
}

var verifyUri = function () {
    var uri = composeUri('bot', conf_botname(), 'verify', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var talkUri = function () {
    var uri = composeUri('talk', conf_botname(), '', '');
    return url.format(uri);
}

var okResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log(jObj.message)
	if (jObj.results !== undefined)
	    console.log(JSON.stringify(jObj.results[0], null, 2))
    }
}

var deleteResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log(jObj.message);
	var prop  = {
	    message: 'Re-enter the name of the bot to delete:',
	    name: 'botname',
	    required: true
	};
	prompt.get(prop, function (error, result) {
	    if (error) {
		console.log("aborted.");
		process.exit(2);
	    }
	    else {
		nconf.set('botname', result.botname);
		request.del(botUri(), deleteResp);
	    }
	});
    }
}

var listBotResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200) {
	jObj.forEach (function (entry) {
	    console.log(entry.botname);
	});
    }
    else
	console.log(jObj.message)
}

var fileList = function (jObj) {
    var files = [];
    if (jObj.properties.length) files.push(jObj.botname + ".properties");
    if (jObj.pdefaults.length) files.push(jObj.botname + ".pdefaults");
    jObj.files.forEach (function (entry) { files.push(entry.name); });
    jObj.sets.forEach (function (entry) { files.push(entry.name + ".set"); });
    jObj.maps.forEach (function (entry) { files.push(entry.name + ".map"); });
    jObj.substitutions.forEach (function (entry) { files.push(entry.name + ".substitution"); });
    return files;
}

var listFileResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200)
	fileList(jObj).forEach (function (file) { console.log(file); });
    else
	console.log(jObj.message)
}

var pullResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200) {
	fileList(jObj).forEach (function (file) {
	    request.get(fileUri(file)).pipe(fs.createWriteStream(file));
	});
    }
    else
	console.log(jObj.message)
}

var talkResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok') {
	nconf.set('sessionid', jObj.sessionid);
	if (nconf.get('extra') || nconf.get('trace'))
	    console.log(jObj);
	else {
	    jObj.responses.forEach (function (entry) {
		console.log(entry);
	    });
	}
    }
    else
	console.log(jObj.message)
}

var conf_app_id = function () {
    var app_id = nconf.get('app_id');
    if (app_id === undefined) {
	console.log('app_id required. use --app_id <app_id> or do init');
	process.exit(1);
    }
    return app_id;
}

var conf_user_key = function () {
    var user_key = nconf.get('user_key');
    if (user_key === undefined) {
	console.log('user_key required. use --user_key <user_key> or do init');
	process.exit(1);
    }
    return user_key;
}

var conf_botname = function () {
    var botname = nconf.get('botname');
    if (botname === undefined) {
	console.log('botname required. use --botname <botname> or do init');
	process.exit(1);
    }
    return botname;
}

prompt.message = "";
prompt.delimiter = "";

nconf.env();
nconf.file({file: config});
nconf.defaults({
    protocol: 'https',
    hostname: 'aiaas.pandorabots.com',
    app_id: undefined,
    user_key: undefined,
    botname: undefined,
    client_name: undefined,
    sessionid: undefined,
    all: undefined,
    extra: undefined,
    reset: undefined,
    trace: undefined,
    reload: undefined,
    recent: undefined
});

program
    .version('0.0.1')
    .usage('command [options] <file ...>')
    .option('-p, --protocol <protocol>', 'protocol')
    .option('-h, --hostname <hostname>', 'hostname')
    .option('-i, --app_id <app_id>', 'app_id')
    .option('-k, --user_key <user_key>', 'user_key')
    .option('-b, --botname <botname>', 'name of bot')
    .option('-c, --client_name <client_name>', 'name of client')
    .option('-s, --sessionid <sessionid>', 'session id of conversation')
    .option('-e, --extra', 'provides additional information with bot response')
    .option('-t, --trace', 'adds trace data into response')
    .option('-r, --reload', 'force system to reload bot')
    .option('-R, --recent', 'use most recently compiled version of bot')
    .option('-a, --all', 'downloads all files')
    .parse(process.argv);

if (program.protocol)
    nconf.set('protocol', program.protocol);
if (program.hostname)
    nconf.set('hostname', program.hostname);
if (program.app_id)
    nconf.set('app_id', program.app_id);
if (program.user_key)
    nconf.set('user_key', program.user_key);
if (program.botname)
    nconf.set('botname', program.botname);
if (program.client_name)
    nconf.set('client_name', program.client_name);
if (program.sessionid)
    nconf.set('sessionid', program.sessionid);
if (program.extra)
    nconf.set('extra', program.extra);
if (program.trace)
    nconf.set('trace', program.trace);
if (program.reload)
    nconf.set('reload', program.reload);
if (program.recent)
    nconf.set('recent', program.recent);
if (program.all)
    nconf.set('all', program.all);

// Initialize
if (program.args[0] === 'init') {
    var props = [
	{message: 'app_id? (required)', name: 'app_id',
	    required: true, validator: /^[0-9a-z]+$/,
	    warning: 'app_id must consist of alphanumeric, lowercase characters'},
	{message: 'user_key? (required)', name: 'user_key',
	    required: true, validator: /^[0-9a-z]+$/,
	    warning: 'user_key must consist of alphanumeric, lowercase characters'},
	{message: 'botname? (recommended)', name: 'botname'},
	{message: 'hostname? (optional)', name: 'hostname'}
    ];
    prompt.get(props, function (error, result) {
	if (error) {
	    console.log("aborted.");
	    process.exit(2);
	}
	else {
	    var prop = {};
	    for (var key in result) {
		if (result[key]) {
		    prop[key] = result[key];
		}
	    }
	    fs.writeFileSync(config, JSON.stringify(prop, null, 4));
	}
    });
}

// List names of bots
else if (program.args[0] === 'list') {
    request.get(listUri(), listBotResp);
}

// Create a bot
else if (program.args[0] === 'create') {
    request.put(botUri(), okResp);
}

// Delete a bot
else if (program.args[0] === 'delete') {
    request.del(botUri(), deleteResp);
}

// Upload a file
else if (program.args[0] === 'upload') {
    if (program.args[1]) {
	fs.createReadStream(program.args[1]).pipe(request.put(fileUri(program.args[1]), okResp))
    }
    else {
	console.log('usage: upload <filename>');
    }
}

// Upload all files at once
else if (program.args[0] === 'push') {
    var files = glob.sync('*.{pdefaults,properties,map,set,substitution,aiml}', {});
    if (files.length) {
	files.forEach (function (entry) {
	    console.log('uploading: ' + entry);
	    fs.createReadStream(entry).pipe(request.put(fileUri(entry), okResp))
	});
    }
    else {
	console.log('no bot files found');
    }
}

// Remove a file
else if (program.args[0] === 'remove') {
    if (program.args[1]) {
	request.del(fileUri(program.args[1]), okResp);
    }
    else {
	console.log('usage: remove <filename>');
    }
}

// Download a file
else if (program.args[0] === 'download') {
    if (program.args[1]) {
	request.get(fileUri(program.args[1])).pipe(fs.createWriteStream(program.args[1]));;
    }
    else {
	console.log('usage: download <filename>');
    }
}

// List files of bot
else if (program.args[0] === 'get' && !program.all) {
    request.get(botUri(), listFileResp);
}

// Retrieve all files as ZIP
else if (program.args[0] === 'get' && program.all) {
    request.get(zipUri()).pipe(fs.createWriteStream(conf_botname() + '.zip'));
}

// Retrieve all files at once
else if (program.args[0] === 'pull') {
    //request.get(zipUri()).pipe(unzip.Extract({path: conf_botname()}));
    //it should work however gets freeze after zip have been downloaded; ugly workaround below
    request.get(botUri(), pullResp);
}

// Compile a bot
else if (program.args[0] === 'compile') {
    request.get(verifyUri(), okResp);
}

// Talk to a bot
else if (program.args[0] === 'talk') {
    if (program.args[1]) {
	var param = {input: program.args.slice(1).join(' ')};
	if (nconf.get('client_name')) param.client_name = nconf.get('client_name');
	if (nconf.get('sessionid')) param.sessionid = nconf.get('sessionid');
	if (nconf.get('extra')) param.extra = true;
	if (nconf.get('reset')) param.reset = true;
	if (nconf.get('trace')) param.trace = true;
	if (nconf.get('reload')) param.reload = true;
	if (nconf.get('recent')) param.recent = true;
	request.post(talkUri(), talkResp).form(composeParams(param));
    }
    else {
	console.log('usage: talk <text...>');
    }
}

else if (program.args[0] === undefined)
    console.log('usage: <command> [--options...]');
else {
    console.log('invalid command: ' + program.args[0]);
    process.exit(1);
}

<commit_msg>adds missing reset option in pb-cli<commit_after>#!/usr/bin/env node

'use strict';

var fs = require('fs');
var glob = require('glob');
var nconf = require('nconf');
var path = require('path');
var program = require('commander');
var prompt = require('prompt');
var qs = require('querystring');
var request = require('request');
var unzip = require('unzip');
var url = require('url');

var config = 'chatbot.json';

var sep = function (str) {
    return str ? '/' + str : '';
}

var composeUri = function (mode, botname, kind, filename) {
    var uri = {
	protocol: nconf.get('protocol'),
	hostname: nconf.get('hostname')
    }
    var path = mode;
    path += sep(conf_app_id());
    path += sep(botname);
    path += sep(kind);
    path += sep(filename);
    uri.pathname = path;
    return uri;
}

var composeParams = function (params) {
    params.user_key = conf_user_key();
    return params;
}

var listUri = function () {
    var uri = composeUri('bot', '', '', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var botUri = function () {
    var uri = composeUri('bot', conf_botname(), '', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var fileUri = function (filename) {
    var ext = path.extname(filename);
    var base = path.basename(filename, ext);
    var kind = ext.slice(1);
    var botname = conf_botname();
    var uri;
    if (kind === 'pdefaults' || kind === 'properties')
	uri = composeUri('bot', botname, kind, '');
    else if (kind === 'map' || kind === 'set' || kind === 'substitution')
	uri = composeUri('bot', botname, kind, base);
    else if (kind === 'aiml')
	uri = composeUri('bot', botname, 'file', base + ext);
    else {
	console.log('illegal file name: ' + filename);
	return;
    }
    uri.query = composeParams({});
    return url.format(uri);
}

var zipUri = function () {
    var uri = composeUri('bot', conf_botname(), '', '');
    uri.query = composeParams({return: 'zip'});
    return url.format(uri);
}

var verifyUri = function () {
    var uri = composeUri('bot', conf_botname(), 'verify', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var talkUri = function () {
    var uri = composeUri('talk', conf_botname(), '', '');
    return url.format(uri);
}

var okResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log(jObj.message)
	if (jObj.results !== undefined)
	    console.log(JSON.stringify(jObj.results[0], null, 2))
    }
}

var deleteResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log(jObj.message);
	var prop  = {
	    message: 'Re-enter the name of the bot to delete:',
	    name: 'botname',
	    required: true
	};
	prompt.get(prop, function (error, result) {
	    if (error) {
		console.log("aborted.");
		process.exit(2);
	    }
	    else {
		nconf.set('botname', result.botname);
		request.del(botUri(), deleteResp);
	    }
	});
    }
}

var listBotResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200) {
	jObj.forEach (function (entry) {
	    console.log(entry.botname);
	});
    }
    else
	console.log(jObj.message)
}

var fileList = function (jObj) {
    var files = [];
    if (jObj.properties.length) files.push(jObj.botname + ".properties");
    if (jObj.pdefaults.length) files.push(jObj.botname + ".pdefaults");
    jObj.files.forEach (function (entry) { files.push(entry.name); });
    jObj.sets.forEach (function (entry) { files.push(entry.name + ".set"); });
    jObj.maps.forEach (function (entry) { files.push(entry.name + ".map"); });
    jObj.substitutions.forEach (function (entry) { files.push(entry.name + ".substitution"); });
    return files;
}

var listFileResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200)
	fileList(jObj).forEach (function (file) { console.log(file); });
    else
	console.log(jObj.message)
}

var pullResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200) {
	fileList(jObj).forEach (function (file) {
	    request.get(fileUri(file)).pipe(fs.createWriteStream(file));
	});
    }
    else
	console.log(jObj.message)
}

var talkResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok') {
	nconf.set('sessionid', jObj.sessionid);
	if (nconf.get('extra') || nconf.get('trace'))
	    console.log(jObj);
	else {
	    jObj.responses.forEach (function (entry) {
		console.log(entry);
	    });
	}
    }
    else
	console.log(jObj.message)
}

var conf_app_id = function () {
    var app_id = nconf.get('app_id');
    if (app_id === undefined) {
	console.log('app_id required. use --app_id <app_id> or do init');
	process.exit(1);
    }
    return app_id;
}

var conf_user_key = function () {
    var user_key = nconf.get('user_key');
    if (user_key === undefined) {
	console.log('user_key required. use --user_key <user_key> or do init');
	process.exit(1);
    }
    return user_key;
}

var conf_botname = function () {
    var botname = nconf.get('botname');
    if (botname === undefined) {
	console.log('botname required. use --botname <botname> or do init');
	process.exit(1);
    }
    return botname;
}

prompt.message = "";
prompt.delimiter = "";

nconf.env();
nconf.file({file: config});
nconf.defaults({
    protocol: 'https',
    hostname: 'aiaas.pandorabots.com',
    app_id: undefined,
    user_key: undefined,
    botname: undefined,
    client_name: undefined,
    sessionid: undefined,
    all: undefined,
    extra: undefined,
    reset: undefined,
    trace: undefined,
    reload: undefined,
    recent: undefined
});

program
    .version('0.0.1')
    .usage('command [options] <file ...>')
    .option('-p, --protocol <protocol>', 'protocol')
    .option('-h, --hostname <hostname>', 'hostname')
    .option('-i, --app_id <app_id>', 'app_id')
    .option('-k, --user_key <user_key>', 'user_key')
    .option('-b, --botname <botname>', 'name of bot')
    .option('-c, --client_name <client_name>', 'name of client')
    .option('-s, --sessionid <sessionid>', 'session id of conversation')
    .option('-e, --extra', 'provides additional information with bot response')
    .option('-M, --reset', 'reset the bot memory')
    .option('-t, --trace', 'adds trace data into response')
    .option('-r, --reload', 'force system to reload bot')
    .option('-R, --recent', 'use most recently compiled version of bot')
    .option('-a, --all', 'downloads all files')
    .parse(process.argv);

if (program.protocol)
    nconf.set('protocol', program.protocol);
if (program.hostname)
    nconf.set('hostname', program.hostname);
if (program.app_id)
    nconf.set('app_id', program.app_id);
if (program.user_key)
    nconf.set('user_key', program.user_key);
if (program.botname)
    nconf.set('botname', program.botname);
if (program.client_name)
    nconf.set('client_name', program.client_name);
if (program.sessionid)
    nconf.set('sessionid', program.sessionid);
if (program.extra)
    nconf.set('extra', program.extra);
if (program.reset)
    nconf.set('reset', program.reset);
if (program.trace)
    nconf.set('trace', program.trace);
if (program.reload)
    nconf.set('reload', program.reload);
if (program.recent)
    nconf.set('recent', program.recent);
if (program.all)
    nconf.set('all', program.all);

// Initialize
if (program.args[0] === 'init') {
    var props = [
	{message: 'app_id? (required)', name: 'app_id',
	    required: true, validator: /^[0-9a-z]+$/,
	    warning: 'app_id must consist of alphanumeric, lowercase characters'},
	{message: 'user_key? (required)', name: 'user_key',
	    required: true, validator: /^[0-9a-z]+$/,
	    warning: 'user_key must consist of alphanumeric, lowercase characters'},
	{message: 'botname? (recommended)', name: 'botname'},
	{message: 'hostname? (optional)', name: 'hostname'}
    ];
    prompt.get(props, function (error, result) {
	if (error) {
	    console.log("aborted.");
	    process.exit(2);
	}
	else {
	    var prop = {};
	    for (var key in result) {
		if (result[key]) {
		    prop[key] = result[key];
		}
	    }
	    fs.writeFileSync(config, JSON.stringify(prop, null, 4));
	}
    });
}

// List names of bots
else if (program.args[0] === 'list') {
    request.get(listUri(), listBotResp);
}

// Create a bot
else if (program.args[0] === 'create') {
    request.put(botUri(), okResp);
}

// Delete a bot
else if (program.args[0] === 'delete') {
    request.del(botUri(), deleteResp);
}

// Upload a file
else if (program.args[0] === 'upload') {
    if (program.args[1]) {
	fs.createReadStream(program.args[1]).pipe(request.put(fileUri(program.args[1]), okResp))
    }
    else {
	console.log('usage: upload <filename>');
    }
}

// Upload all files at once
else if (program.args[0] === 'push') {
    var files = glob.sync('*.{pdefaults,properties,map,set,substitution,aiml}', {});
    if (files.length) {
	files.forEach (function (entry) {
	    console.log('uploading: ' + entry);
	    fs.createReadStream(entry).pipe(request.put(fileUri(entry), okResp))
	});
    }
    else {
	console.log('no bot files found');
    }
}

// Remove a file
else if (program.args[0] === 'remove') {
    if (program.args[1]) {
	request.del(fileUri(program.args[1]), okResp);
    }
    else {
	console.log('usage: remove <filename>');
    }
}

// Download a file
else if (program.args[0] === 'download') {
    if (program.args[1]) {
	request.get(fileUri(program.args[1])).pipe(fs.createWriteStream(program.args[1]));;
    }
    else {
	console.log('usage: download <filename>');
    }
}

// List files of bot
else if (program.args[0] === 'get' && !program.all) {
    request.get(botUri(), listFileResp);
}

// Retrieve all files as ZIP
else if (program.args[0] === 'get' && program.all) {
    request.get(zipUri()).pipe(fs.createWriteStream(conf_botname() + '.zip'));
}

// Retrieve all files at once
else if (program.args[0] === 'pull') {
    //request.get(zipUri()).pipe(unzip.Extract({path: conf_botname()}));
    //it should work however gets freeze after zip have been downloaded; ugly workaround below
    request.get(botUri(), pullResp);
}

// Compile a bot
else if (program.args[0] === 'compile') {
    request.get(verifyUri(), okResp);
}

// Talk to a bot
else if (program.args[0] === 'talk') {
    if (program.args[1]) {
	var param = {input: program.args.slice(1).join(' ')};
	if (nconf.get('client_name')) param.client_name = nconf.get('client_name');
	if (nconf.get('sessionid')) param.sessionid = nconf.get('sessionid');
	if (nconf.get('extra')) param.extra = true;
	if (nconf.get('reset')) param.reset = true;
	if (nconf.get('trace')) param.trace = true;
	if (nconf.get('reload')) param.reload = true;
	if (nconf.get('recent')) param.recent = true;
	request.post(talkUri(), talkResp).form(composeParams(param));
    }
    else {
	console.log('usage: talk <text...>');
    }
}

else if (program.args[0] === undefined)
    console.log('usage: <command> [--options...]');
else {
    console.log('invalid command: ' + program.args[0]);
    process.exit(1);
}

<|endoftext|>


<commit_before>var hubChart = {
  version: ".1"
};

function HubChart(options) {
  this.options = options;
  this.data = "";
  this.loadData();
}

HubChart.prototype.getOption = function(key) {
  return this.options[key];
}

HubChart.prototype.setOption = function(key, value) {
  return this.options[key] = value;
}

HubChart.prototype.loadData = function() {
  $$ = this;
  if ($$.options.mimeType === "json") {
    $.ajax({
      url: $$.options.data,
      type: 'GET',
      success: function(response) {
        if ($$.options.transform !== "") {
          var transformer = new Transformer();
          var transform = new window[$$.options.transform];
          if (typeof transform === "object") {
            transformer.setTransform(transform);
            response = transformer.run(response, $$);
          }
          else {
            throw new Error('transformer does not exist for ' + this.options.chartTitle);
          }
        }
        $$.data = response;
        $$.render();
      }
    });
  }
  else {
    $$.data = $$.options.data;
    $$.render();
  }
};

HubChart.prototype.render = function() {
  /*
  initiate defaults
  */

  var options = this.options,
    data = this.data,
    max = null,
    pleft = null,
    show = true,
    rotated = false,
    names = {},
    legend = 'bottom',
    type = 'area',
    mimeType = 'csv';

  /* detect whether the data is being passed via external url */
  if (typeof data === "string") {
    var url = (/^https?:\/\//.test(data)) ? data : '/data-browser/data/' + data;
  }
  /* define derived variables based on input options */
  show = options.legend == 'none' ? false : true;
  rotated = options.type == 'bar-horizontal' ? true : false;
  /* redefine certain parameters */
  options.legend = options.legend == '' ? legend : options.legend;
  options.groups = options.groups == null ? [] : options.groups;
  options.type = options.type == '' ? type : (options.type == 'bar-horizontal' ? 'bar' : options.type);
  options.mimeType = options.mimeType == '' ? mimeType : options.mimeType;
  options.yFormat = (Object.prototype.toString.call(options.yFormat) === '[object Function]') ? options.yFormat : d3.format(options.yFormat);
  options.emphasis = options.emphasis == null ? [null, null, null] : options.emphasis;
  /*
  generate names from chart values to make them human friendly
  - remove underscores
  - title case
  */
  if (options.value) {
    options.value.forEach(function(v, idx) {
      names[v] = (options.names ? options.names[idx] : v.replace(/_/g, " ").toTitleCase());
    });
  }

  /* override tooltips to include Margins of Error where applicable*/
  var tooltip_contents = function(d, defaultTitleFormat, defaultValueFormat, color) {
    var $$ = this,
      config = $$.config,
      CLASS = $$.CLASS,
      titleFormat = config.tooltip_format_title || defaultTitleFormat,
      nameFormat = config.tooltip_format_name || function(name) {
        return name;
      },
      valueFormat = config.tooltip_format_value || defaultValueFormat,
      text, i, title, value, name, bgcolor;

    // You can access all of data like this:
    var allData = $$.data.targets;

    for (i = 0; i < d.length; i++) {
      if (!(d[i] && (d[i].value || d[i].value === 0))) {
        continue;
      }

      if (!text) {
        title = titleFormat ? titleFormat(d[i].x) : d[i].x;
        text = "
" + (title || title === 0 ? "
" + title + "
" : "");
      }

      name = nameFormat(d[i].name);
      value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
      if ((typeof allData[i + i + 1] != "undefined") && allData[i + i + 1].id.indexOf("MOE") > -1) {
        value += " +/-" + valueFormat(allData[i + i + 1].values[d[i].index].value);
      }
      bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);

      text += "
";
      text += "" + name + "	";
      text += "" + value + "	";
      text += "
";
    }
    return text + "
";
  };

  console.log(options.groups)

  var chart = c3.generate({
    bindto: '#' + options.container,
    padding: {
      bottom: 30,
      left: pleft
    },
    data: {
      x: options.x,
      xFormat: options.xFormat,
      url: url || undefined,
      json: (Object.prototype.toString.call(data[0]) === '[object Object]' ? data : undefined),
      columns: (Object.prototype.toString.call(data[0]) === '[object Array]' ? data : undefined),
      mimeType: options.mimeType,
      keys: {
        x: options.x,
        value: options.value
      },
      names: names,
      groups: [options.groups],
      type: options.type,
      color: function(color, d) {
        return d.id && d.index == options.emphasis[1] && d.id == options.emphasis[0] ? d3.rgb('#' + options.emphasis[2]) : color;
      },
      order: null,
      hide: ["MOE", "MOE_Renter", "MOE_Owner", "MOE_More", "MOE_Less"]
    },
    tooltip: {
      contents: tooltip_contents
    },
    color: {
      pattern: ['#5a9bd4', '#7ac36a', '#faa75b', '#9e67ab', '#ce7058', '#d77fb4', '#f15a60', '#737373']
    },
    legend: {
      position: options.legend,
      show: show,
      hide: ["MOE", "MOE_Renter", "MOE_Owner", "MOE_More", "MOE_Less"]
    },
    axis: {
      rotated: rotated,
      x: {
        label: {
          text: options.xLabel || null,
          position: 'outer-center'
        },
        type: options.axisType,
        tick: {
          format: options.xTickFormat,
          width: 150
        }
      },
      y: {
        label: {
          text: options.yLabel || null,
          position: 'outer-middle'
        },
        min: 0,
        max: max,
        padding: {
          bottom: 0,
          top: 3
        },
        tick: {
          format: options.yFormat
        }
      }
    }
  });
};

hubChart.generate = function(options, container) {
  if (container) {
    options.container = container;
  }
  return new HubChart(options);
};
<commit_msg>pass counts to donut and pie charts<commit_after>var hubChart = {
  version: ".1"
};

function HubChart(options) {
  this.options = options;
  this.data = "";
  this.loadData();
}

HubChart.prototype.getOption = function(key) {
  return this.options[key];
}

HubChart.prototype.setOption = function(key, value) {
  return this.options[key] = value;
}

HubChart.prototype.loadData = function() {
  $$ = this;
  if ($$.options.mimeType === "json") {
    $.ajax({
      url: $$.options.data,
      type: 'GET',
      success: function(response) {
        if ($$.options.transform !== "") {
          var transformer = new Transformer();
          var transform = new window[$$.options.transform];
          if (typeof transform === "object") {
            transformer.setTransform(transform);
            response = transformer.run(response, $$);
          }
          else {
            throw new Error('transformer does not exist for ' + this.options.chartTitle);
          }
        }
        $$.data = response;
        $$.render();
      }
    });
  }
  else {
    $$.data = $$.options.data;
    $$.render();
  }
};

HubChart.prototype.render = function() {
  /*
  initiate defaults
  */

  var options = this.options,
    data = this.data,
    max = null,
    pleft = null,
    show = true,
    rotated = false,
    names = {},
    legend = 'bottom',
    type = 'area',
    mimeType = 'csv';

  /* detect whether the data is being passed via external url */
  if (typeof data === "string") {
    var url = (/^https?:\/\//.test(data)) ? data : '/data-browser/data/' + data;
  }
  /* define derived variables based on input options */
  show = options.legend == 'none' ? false : true;
  rotated = options.type == 'bar-horizontal' ? true : false;
  /* redefine certain parameters */
  options.legend = options.legend == '' ? legend : options.legend;
  options.groups = options.groups == null ? [] : options.groups;
  options.type = options.type == '' ? type : (options.type == 'bar-horizontal' ? 'bar' : options.type);
  options.mimeType = options.mimeType == '' ? mimeType : options.mimeType;
  options.yFormat = (Object.prototype.toString.call(options.yFormat) === '[object Function]') ? options.yFormat : d3.format(options.yFormat);
  options.emphasis = options.emphasis == null ? [null, null, null] : options.emphasis;
  /*
  generate names from chart values to make them human friendly
  - remove underscores
  - title case
  */
  if (options.value) {
    options.value.forEach(function(v, idx) {
      names[v] = (options.names ? options.names[idx] : v.replace(/_/g, " ").toTitleCase());
    });
  }

  /* override tooltips to include Margins of Error where applicable*/
  var tooltip_contents = function(d, defaultTitleFormat, defaultValueFormat, color) {
    var $$ = this,
      config = $$.config,
      CLASS = $$.CLASS,
      titleFormat = config.tooltip_format_title || defaultTitleFormat,
      nameFormat = config.tooltip_format_name || function(name) {
        return name;
      },
      valueFormat = config.tooltip_format_value || defaultValueFormat,
      text, i, title, value, name, bgcolor;

    // You can access all of data like this:
    var allData = $$.data.targets;

    for (i = 0; i < d.length; i++) {
      if (!(d[i] && (d[i].value || d[i].value === 0))) {
        continue;
      }

      if (!text) {
        title = titleFormat ? titleFormat(d[i].x) : d[i].x;
        text = "
" + (title || title === 0 ? "
" + title + "
" : "");
      }

      name = nameFormat(d[i].name);
      value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
      if ((typeof allData[i + i + 1] != "undefined") && allData[i + i + 1].id.indexOf("MOE") > -1) {
        value += " +/-" + valueFormat(allData[i + i + 1].values[d[i].index].value);
      }

      if (config.data_type === 'donut' || config.data_type === 'pie') {
        var formatComma = d3.format(",")
        value = formatComma(d[i].value)
      }

      bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);

      text += "
";
      text += "" + name + "	";
      text += "" + value + "	";
      text += "
";
    }
    return text + "
";
  };

  console.log(options.groups)

  var chart = c3.generate({
    bindto: '#' + options.container,
    padding: {
      bottom: 30,
      left: pleft
    },
    data: {
      x: options.x,
      xFormat: options.xFormat,
      url: url || undefined,
      json: (Object.prototype.toString.call(data[0]) === '[object Object]' ? data : undefined),
      columns: (Object.prototype.toString.call(data[0]) === '[object Array]' ? data : undefined),
      mimeType: options.mimeType,
      keys: {
        x: options.x,
        value: options.value
      },
      names: names,
      groups: [options.groups],
      type: options.type,
      color: function(color, d) {
        return d.id && d.index == options.emphasis[1] && d.id == options.emphasis[0] ? d3.rgb('#' + options.emphasis[2]) : color;
      },
      order: null,
      hide: ["MOE", "MOE_Renter", "MOE_Owner", "MOE_More", "MOE_Less"]
    },
    tooltip: {
      contents: tooltip_contents
    },
    color: {
      pattern: ['#5a9bd4', '#7ac36a', '#faa75b', '#9e67ab', '#ce7058', '#d77fb4', '#f15a60', '#737373']
    },
    legend: {
      position: options.legend,
      show: show,
      hide: ["MOE", "MOE_Renter", "MOE_Owner", "MOE_More", "MOE_Less"]
    },
    axis: {
      rotated: rotated,
      x: {
        label: {
          text: options.xLabel || null,
          position: 'outer-center'
        },
        type: options.axisType,
        tick: {
          format: options.xTickFormat,
          width: 150
        }
      },
      y: {
        label: {
          text: options.yLabel || null,
          position: 'outer-middle'
        },
        min: 0,
        max: max,
        padding: {
          bottom: 0,
          top: 3
        },
        tick: {
          format: options.yFormat
        }
      }
    }
  });
};

hubChart.generate = function(options, container) {
  if (container) {
    options.container = container;
  }
  return new HubChart(options);
};
<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initHolds();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		this.toggleCheckboxGroup('.spl-field-cko-select-all'
														,'.spl-field-cko-select-item');

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { token: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		this.initHoldsPending();

	} // initHolds()

, initHoldsPending: function() {

		this.initHoldsPendingSuspend();

		var $form = $('#spl-form-holds-pending');

		this.toggleCheckboxGroup('.spl-field-holds-pending-select-all'
														,'.spl-field-holds-pending-select-item');

		$('.spl-field-holds-pending-control').click(function(e) {
			$form.data('action', $(this).data('action')).submit();
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var holdkeys = new Array;
				$('.spl-field-holds-pending-select-item:checked').each(function() {
					holdkeys.push( $(this).data('holdkey') );
				});

				if ( holdkeys.length > 0 ) {
					_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					$(this).data('action', '');
				} else {
					alert('Please select hold(s).');
				}

			}

		});

	} // initHoldsPending()

, initHoldsPendingSuspend: function() {
		var $suspend = $('.spl-field-holds-pending-suspend');
		var $date = $('.spl-field-holds-pending-date');
		$date.on('change', function(e) {
			if ( $(this).val().length > 0 ) {
				$suspend.attr('disabled', false);
			} else {
				$suspend.attr('disabled', true);
			}
		});
		// disallow dates in the past
		$date.datepicker({startDate: new Date() });

} // initHoldsPendingSuspend()

, holdsPendingUpdate: function(action, holdkeys) {
		var $form = $('#spl-form-holds-pending');
		var $submit = $('.spl-field-holds-pending-control');
		var $hidden = $('#spl-field-holds-pending-update');

		var $location = $('.spl-field-holds-pending-location');
		var $date = $('.spl-field-holds-pending-date');

		$submit.button('loading'); //$submit.button('reset');

		var data = { params: {sessionToken: this.user.sessionToken
	    									,	holdKeys: holdkeys
	    									}
	    					}

		var endpoint;

		switch ( action ) {
			case 'cancel':
				endpoint = 'cancel-holds';
				break;
			case 'pickup':
				endpoint = 'pickup';
				data.params.newLocation = $location.val();
				break;
			case 'suspend':
				endpoint = 'suspend-holds';
				data.params.suspendEndDate = $date.val();
				break;
			case 'resume':
				endpoint = 'resume-holds';
				break;
			default:
				endpoint = null;
				break;
		}

		if ( null != typeof(endpoint) ) {
			$.ajax({
		    url: this.config.endpoint.hzws+endpoint
	    , data: data
		  })
		  .done(function(obj) {
		  	// pass results through
				$hidden.val(JSON.stringify(obj));
				console.log(obj);
				$submit.button('reset');
				//$form.data('process', 'http').submit();
		  })
		  .fail(function() {
		  })
		  .always(function() {
		  });
		}

	} // holdsPendingUpdate()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

, toggleCheckboxGroup: function(all, item) {
		var $selectAll = $(all);
		var $selectItem = $(item);

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<commit_msg>suspend<commit_after>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initHolds();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		this.toggleCheckboxGroup('.spl-field-cko-select-all'
														,'.spl-field-cko-select-item');

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { token: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		this.initHoldsPending();

	} // initHolds()

, initHoldsPending: function() {

		this.initHoldsPendingSuspend();

		var $form = $('#spl-form-holds-pending');

		this.toggleCheckboxGroup('.spl-field-holds-pending-select-all'
														,'.spl-field-holds-pending-select-item');

		$('.spl-field-holds-pending-control').click(function(e) {
			$form.data('action', $(this).data('action')).submit();
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var holdkeys = new Array;
				$('.spl-field-holds-pending-select-item:checked').each(function() {
					holdkeys.push( $(this).data('holdkey') );
				});

				if ( holdkeys.length > 0 ) {
					_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					$(this).data('action', '');
				} else {
					alert('Please select hold(s).');
				}

			}

		});

	} // initHoldsPending()

, initHoldsPendingSuspend: function() {
		var $suspend = $('.spl-field-holds-pending-suspend');
		var $date = $('.spl-field-holds-pending-date');
		$date.on('change', function(e) {
			if ( $(this).val().length > 0 ) {
				$suspend.attr('disabled', false);
			} else {
				$suspend.attr('disabled', true);
			}
		});
		// disallow dates in the past
		$date.datepicker({startDate: new Date() });

} // initHoldsPendingSuspend()

, holdsPendingUpdate: function(action, holdkeys) {
		var $form = $('#spl-form-holds-pending');
		var $submit = $('.spl-field-holds-pending-control');
		var $hidden = $('#spl-field-holds-pending-update');

		var $location = $('.spl-field-holds-pending-location');
		var $date = $('.spl-field-holds-pending-date');

		$submit.button('loading'); //$submit.button('reset');

		var data = { params: {sessionToken: this.user.sessionToken
	    									,	holdKeys: holdkeys
	    									}
	    					}

		var endpoint;

		switch ( action ) {
			case 'cancel':
				endpoint = 'cancel-holds';
				break;
			case 'pickup':
				endpoint = 'pickup';
				data.params.newLocation = $location.val();
				break;
			case 'suspend':
				endpoint = 'suspend';
				data.params.suspendEndDate = $date.val();
				break;
			case 'resume':
				endpoint = 'resume';
				break;
			default:
				endpoint = null;
				break;
		}

		if ( null != typeof(endpoint) ) {
			$.ajax({
		    url: this.config.endpoint.hzws+endpoint
	    , data: data
		  })
		  .done(function(obj) {
		  	// pass results through
				$hidden.val(JSON.stringify(obj));
				console.log(obj);
				$submit.button('reset');
				//$form.data('process', 'http').submit();
		  })
		  .fail(function() {
		  })
		  .always(function() {
		  });
		}

	} // holdsPendingUpdate()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

, toggleCheckboxGroup: function(all, item) {
		var $selectAll = $(all);
		var $selectItem = $(item);

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/request/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		this.setUser();

		// init ui
		this.initRequestItem();

	} // init()

, setUser: function(user) {
		if ( !ORG.user ) {
			ORG.setUser(user);
		}
		this.user = ORG.user;
}

, initRequestItem: function() {

		/*
		$('body').on('change', 'input:radio[name = "spl-form[material]"]', function() {
			var materialTypeDescription = $(this).parent().text();
			console.log(materialTypeDescription);
		});
		*/

		// hide material type selectors on choose
		$('body').on('show.bs.collapse', '#spl-form-request-panels', function() {
			$('#spl-form-request-panel-choose').collapse('hide');
		});

		$('body').on('show.bs.collapse', '.spl-form-request-material', function() {
			$('#spl-form-panel-request').collapse('show');
		});

		/*

		$('body').on('shown.bs.collapse', '.spl-form-request-material', function() {
			$('#spl-form-panel-request').collapse('show');
		});
*/

		/*
		$('body').on('show.bs.collapse', '#spl-form-request-panel-choose', function() {
			console.log('hide panels');
			$('#spl-form-request-panels').hide();
		});
		*/

		/*

		*/

  } // initRequestItem()

};
<commit_msg>request<commit_after>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/request/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		this.setUser();

		// init ui
		this.initRequestItem();

	} // init()

, setUser: function(user) {
		if ( !ORG.user ) {
			ORG.setUser(user);
		}
		this.user = ORG.user;
}

, initRequestItem: function() {

		/*
		$('body').on('change', 'input:radio[name = "spl-form[material]"]', function() {
			var materialTypeDescription = $(this).parent().text();
			console.log(materialTypeDescription);
		});
		*/

		// hide material type selectors on choose
		$('body').on('show.bs.collapse', '#spl-form-request-panels', function() {
			$('#spl-form-request-panel-choose').collapse('hide');
		});

		$('body').on('hide.bs.collapse', '#spl-form-request-panels', function() {
			$('#spl-form-panel-request').collapse('hide');
		});

		$('body').on('show.bs.collapse', '.spl-form-request-material', function() {
			$('#spl-form-panel-request').collapse('show');
		});

		/*

		$('body').on('shown.bs.collapse', '.spl-form-request-material', function() {
			$('#spl-form-panel-request').collapse('show');
		});
*/

		/*
		$('body').on('show.bs.collapse', '#spl-form-request-panel-choose', function() {
			console.log('hide panels');
			$('#spl-form-request-panels').hide();
		});
		*/

		/*

		*/

  } // initRequestItem()

};
<|endoftext|>


<commit_before>var $ = window.$;
var util = require('./util');
var pageConfig = require('./pageConfig');
var pageRules = require('./pageRules');
var pageSession = require('./pageSessions');
var keyControl = require('./keyControl');

var showPage = function(target,id){
    var left = id == 'rules' ? 200: 800;
    target.css('webkitTransform','translateX('+left+'px)').addClass('on');
}

var hidePage = function(target, id){
    var left = id == 'rules' ? 1180: 1230;
    target.css('webkitTransform','translateX('+left+'px)').removeClass('on');
}

var bind = function(){
    $('.container .add').on('click',function(e){
        var target = $(e.target).parent(),
            id = target.attr('id');
        if(target.hasClass('on')){
            hidePage(target,id);
        }else{
            showPage(target,id);
        }
    });
    keyControl.on(function(e){
        if(e.ctrlKey){
        }
        return false;
    });
};

exports.init = function(){
    bind();
    pageSession.init();
    pageRules.init();
    pageConfig.init();

}<commit_msg>support page toggle from key 1/2<commit_after>var $ = window.$;
var util = require('./util');
var pageConfig = require('./pageConfig');
var pageRules = require('./pageRules');
var pageSession = require('./pageSessions');
var keyControl = require('./keyControl');

var showPage = function(target,id){
    var left = id == 'rules' ? 200: 800;
    target.css('webkitTransform','translateX('+left+'px)').addClass('on');
}

var hidePage = function(target, id){
    var left = id == 'rules' ? 1180: 1230;
    target.css('webkitTransform','translateX('+left+'px)').removeClass('on');
}

var togglePage = function(target, id){
    var target = target || $('#'+id);
    if(target.hasClass('on')){
        hidePage(target,id);
    }else{
        showPage(target,id);
    }
}

var bind = function(){
    $('.container .add').on('click',function(e){
        var target = $(e.target).parent(),
            id = target.attr('id');
        togglePage(target, id);
    });
    keyControl.on(function(e){
        if(e.ctrlKey){
            switch (e.which){
                case 49:  //1
                    togglePage(null,'rules');
                    break;
                case 50:  //2
                    togglePage(null,'config');
                    break;
            }
        }
        return false;
    });
};

exports.init = function(){
    bind();
    pageSession.init();
    pageRules.init();
    pageConfig.init();

}<|endoftext|>