<commit_before>/*
 *    Copyright 2013 APPNEXUS INC
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

(function() {
 var isIOS = (/iphone|ipad|ipod/i).test(window.navigator.userAgent.toLowerCase());
 if (isIOS) {
 console = {};
 console.log = function(log) {
 var iframe = document.createElement('iframe');
 iframe.setAttribute('src', 'anwebconsole: ' + log);
 document.documentElement.appendChild(iframe);
 iframe.parentNode.removeChild(iframe);
 iframe = null;
 };
 console.debug = console.info = console.warn = console.error = console.log;
 }
 }());

(function() {

 // Set up some variables
 var mraid = window.mraid = {};
 mraid.util = {};
 var listeners = [];
 listeners['ready']=[];
 listeners['error']=[];
 listeners['stateChange']=[];
 listeners['viewableChange']=[];
 listeners['sizeChange']=[];
 var state='loading'; //Can be loading, default, expanded, hidden, or resized
 var placement_type='inline';
 var is_viewable=false;
 var expand_properties={width:-1, height:-1, useCustomClose:false, isModal:true};
 var orientation_properties={allowOrientationChange:true, forceOrientation:"none"};
 var resize_properties={width:-1, height:-1, offsetX: 0, offsetY: 0, customClosePosition: 'top-right', allowOffscreen: true};
 var screen_size={};
 var max_size={};
 var default_position={};
 var current_position={};

 // ----- MRAID AD API FUNCTIONS -----

 // getVersion() returns string '2.0'
 mraid.getVersion=function(){ return '2.0'};

 // getVendor() returns string 'appnexus'
 mraid.getVendor=function(){ return 'appnexus'};

 /** Adds a listener to a specific event. For example, a function onReady might be defined, and then mraid.addEventListener('ready', onReady)
  * is called. When the ready event is fired, onReady will be called.
  * Events 'error', 'viewableChange', 'stateChange', have parameters.
  */
 mraid.addEventListener=function(event_name, method){
 if(listeners[event_name].indexOf(method) > -1) return; // Listener is already registered
 listeners[event_name].push(method);
 };

 // Removes a listener from the registry
 mraid.removeEventListener=function(event_name, method){
 //If no method name is given, remove all listeners from event
 if(method == null){
 listeners[event_name].length=0;
 return;
 }

 var method_index = listeners[event_name].indexOf(method);
 if(method_index > -1){ //Don't try to remove unregistered listeners
 listeners[event_name].splice(method_index,1);
 }else{
 mraid.util.errorEvent("An unregistered listener was requested to be removed.", "mraid.removeEventListener()")
 }
 };

 //returns 'loading', 'default', 'expanded', or 'hidden'
 mraid.getState=function(){
 return state;
 };

 //returns 'inline' or 'interstitial'
 mraid.getPlacementType=function(){
 return placement_type;
 };

 //returns true or false
 mraid.isViewable=function(){
 return is_viewable;
 };

 // ----- MRAID JS TO NATIVE FUNCTIONS -----

 //Closes an expanded ad or hides an ad in default state
 mraid.close=function(){
 switch(mraid.getState()){
 case 'loading':
 mraid.util.errorEvent("mraid.close() called while state is 'loading'.", "mraid.close()");
 break;
 case 'default':
 window.open("mraid://close/");
 mraid.util.stateChangeEvent('hidden');
 break;
 case 'expanded':
 window.open("mraid://close/");
 mraid.util.stateChangeEvent('default');
 break;
 case 'hidden':
 mraid.util.errorEvent("mraid.close() called while ad was already hidden", "mraid.close()");
 break;
 case 'resized':
 window.open("mraid://close/");
 mraid.util.stateChangeEvent('default');
 }
 };

 // Expands a default state ad, or unhides a hidden ad. Optionally takes a URL to load in the expanded view
 mraid.expand=function(url){
 switch(mraid.getState()){
 case 'loading':
 mraid.util.errorEvent("mraid.expand() called while state is 'loading'.", "mraid.expand()");
 break;
 case 'default':
 if((expand_properties.height>0 && expand_properties.width>0) && (expand_properties.height < current_position.height || expand_properties.width < current_position.width)){
 mraid.util.errorEvent("Can't expand to a size smaller than the default size.", "mraid.expand()");
 return;
 }
 window.open("mraid://expand/"+"?w="+mraid.getExpandProperties().width+"&h="+mraid.getExpandProperties().height+"&useCustomClose="+mraid.getExpandProperties().useCustomClose+(url!=null ? "&url="+url:""));
 mraid.util.stateChangeEvent('expanded');
 if(url!=null){
 window.open(url);
 }
 break;
 case 'expanded':
 mraid.util.errorEvent("mraid.expand() called while state is 'expanded'.", "mraid.expand()");
 break;
 case 'hidden':
 mraid.util.errorEvent("mraid.expand() called while state is 'hidden'.", "mraid.expand()");
 break;
 case 'resized':
 mraid.util.stateChangeEvent('expanded');
 }
 };

 // Takes an object... {width:300, height:250, useCustomClose:false, isModal:false};
 mraid.setExpandProperties=function(properties){
 properties.isModal=true; // Read only property.
 expand_properties=properties;
 };

 //returns a json object... {width:300, height:250, useCustomClose:false, isModal:false};
 mraid.getExpandProperties=function(){
 return expand_properties;
 };

 // Takes a boolean
 mraid.useCustomClose=function(well_is_it){
 ep = mraid.getExpandProperties();
 ep.useCustomClose = well_is_it;
 mraid.setExpandProperties(ep);
 };

 // Loads a given URL
 mraid.open=function(url){
 window.location.href = url;
 };

 // MRAID 2.0 Stuff.
 mraid.resize=function(){
 if(resize_properties.height<0 || resize_properties.width<0){
 mraid.util.errorEvent("mraid.resize() called before mraid.setResizeProperties()", "mraid.resize()");
 return;
 }
 switch(mraid.getState()){
 case 'loading':
 mraid.util.errorEvent("mraid.resize() called while state is 'loading'.", "mraid.resize()");
 break;
 case 'expanded':
 mraid.util.errorEvent("mraid.resize() called while state is 'expanded'.", "mraid.resize()");
 break;
 case 'resized':
 case 'default':
 window.open("mraid://resize/?w="+resize_properties.width
             +"&h="+resize_properties.height
             +"&offset_x="+resize_properties.offsetX
             +"&offset_y="+resize_properties.offsetY
             +"&custom_close_position="+resize_properties.customClosePosition
             +"&allow_offscreen="+resize_properties.allowOffscreen);
 mraid.util.stateChangeEvent('resized');
 break;
 case 'hidden':
 break;

 }

 }

 mraid.setResizeProperties=function(props){
 if(props.customClosePosition!=null && props.customClosePosition != "top-right"
    && props.customClosePosition != "top-left"
    && props.customClosePosition != "center"
    && props.customClosePosition != "bottom-left"
    && props.customClosePosition != "bottom-right"
    && props.customClosePosition != "top-center"
    && props.customClosePosition != "bottom-center"){
 mraid.util.errorEvent("Invalid customClosePosition.", "mraid.setResizeProperties()");
 }else{
 resize_properties=props;
 }
 }

 mraid.getResizeProperties=function(){
 return resize_properties;
 }

 //returns a json object... {allowOrientationChange:true, forceOrientation:"none"};
 mraid.getOrientationProperties=function(){
 return orientation_properties;
 }

 // Takes an object... {allowOrientationChange:true, forceOrientation:"none"};
 mraid.setOrientationProperties=function(properties){
 orientation_properties=properties;

 if (typeof properties === "undefined") {
 return;
 }

 if(properties.forceOrientation!=='portrait' && properties.forceOrientation!=='landscape' && properties.forceOrientation!=='none' ){
 mraid.util.errorEvent("Invalid orientationProperties forceOrientation property", "mraid.setOrientationProperties()");
 properties.forceOrientation='none';
 }

 if(typeof properties.allowOrientationChange !== "boolean"){
 mraid.util.errorEvent("Invalid orientationProperties allowOrientationChange property", "mraid.setOrientationProperties()");
 properties.allowOrientationChange=true;
 }

 window.open("mraid://setOrientationProperties/?allow_orientation_change="+properties.allowOrientationChange
             +"&force_orientation="+properties.forceOrientation);
 }

 // Creates a calendar event when passed a W3C-formatted json object
 mraid.createCalendarEvent=function(event){
 window.open("mraid://createCalendarEvent/?p="+encodeURIComponent(JSON.stringify(event)));
 }

 // Plays a video in the native player
 mraid.playVideo=function(uri){
 window.open("mraid://playVideo/?uri="+encodeURIComponent(uri));
 }

 // Stores a picture on the device
 mraid.storePicture=function(uri){
 window.open("mraid://storePicture/?uri="+encodeURIComponent(uri));
 }

 // Convenience function to modify useCustomClose attribute of expandProperties
 mraid.useCustomClose=function(value){
 expand_properties.useCustomClose = value;
 }

 // Checks if a feature is supported by this device
 mraid.supports=function(feature){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.supports()' called during loading state.", "mraid.supports()");
 return;
 }
 switch(feature){
 case 'sms':
 return supports_sms;
 case 'tel':
 return supports_tel;
 case 'calendar':
 return supports_calendar;
 case 'storePicture':
 return supports_storePicture;
 case 'inlineVideo':
 return supports_inlineVideo;
 }
 mraid.util.errorEvent("Unknown feature to check for support: "+feature, "mraid.supports()");
 return false;
 }

 // Gets the screen size of the device
 mraid.getScreenSize=function(){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.getScreenSize()' called during loading state.", "mraid.getScreenSize()");
 return;
 }else{
 return screen_size;
 }
 }

 // Gets the max size of the ad if expanded (so it won't obscure the app's title bar)
 mraid.getMaxSize=function(){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.getMaxSize()' called during loading state.", "mraid.getMaxSize()");
 return;
 }else{
 return max_size;
 }
 }

 // Gets the default position of the ad view, in dips offset from top left.
 mraid.getDefaultPosition=function(){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.getDefaultPosition()' called during loading state.", "mraid.getDefaultPosition()");
 return;
 }else{
 return default_position;
 }
 }

 // Gets the current position of the ad view, in dips offset from top left.
 mraid.getCurrentPosition=function(){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.getCurrentPosition()' called during loading state.", "mraid.getCurrentPosition()");
 return;
 }else{
 return current_position;
 }
 }

 // ----- MRAID UTILITY FUNCTIONS -----
 // These functions are called by the native SDK to drive events and update information

 mraid.util.setPlacementType=function(type){
 placement_type=type;
 };

 mraid.util.readyEvent=function(){
 for(var i=0;i<listeners['ready'].length;i++){
 listeners['ready'][i]();
 }
 };

 mraid.util.errorEvent=function(message, what_doing){
 for(var i=0;i<listeners['error'].length;i++){
 listeners['error'][i](message, what_doing);
 }
 };

 mraid.util.viewableChangeEvent=function(is_viewable_now){
 is_viewable = is_viewable_now;
 for(var i=0;i<listeners['viewableChange'].length;i++){
 listeners['viewableChange'][i](is_viewable_now);
 }
 };

 mraid.util.setIsViewable=function(is_it_viewable){
 if(is_viewable===is_it_viewable) return;
 is_viewable=is_it_viewable;
 mraid.util.viewableChangeEvent(is_viewable);
 };

 mraid.util.stateChangeEvent=function(new_state){
 if(state===new_state && state!='resized') return;
 state=new_state;
 if(new_state==='hidden'){
 mraid.util.setIsViewable(false);
 }
 for(var i=0;i<listeners['stateChange'].length;i++){
 listeners['stateChange'][i](new_state);
 }
 };

 mraid.util.sizeChangeEvent=function(width, height){
 if(width != mraid.getCurrentPosition().width || height != mraid.getCurrentPosition().height){
 for(var i=0;i<listeners['sizeChange'].length;i++){
 listeners['sizeChange'][i](width, height);
 }
 }
 }

 var supports_sms = false;
 var supports_tel = false;
 var supports_calendar = false;
 var supports_storePicture = false;
 var supports_inlineVideo = false;
 mraid.util.setSupportsSMS=function(val){
 supports_sms = val;
 }

 mraid.util.setSupportsTel=function(val){
 supports_tel=val;
 }

 mraid.util.setSupportsCalendar=function(val){
 supports_calendar=val;
 }

 mraid.util.setSupportsStorePicture=function(val){
 supports_storePicture=val;
 }

 mraid.util.setSupportsInlineVideo=function(val){
 supports_inlineVideo=val;
 }

 mraid.util.setScreenSize=function(width, height){
 screen_size={"width":width,
 "height": height};
 }

 mraid.util.setMaxSize=function(width, height){
 max_size={"width":width,
 "height": height};
 }

 mraid.util.setDefaultPosition=function(x, y, width, height){
 default_position={"x": x,
 "y": y,
 "width":width,
 "height": height};
 current_position = default_position;
 }

 mraid.util.setCurrentPosition=function(x, y, width, height){
 current_position={"x": x,
 "y": y,
 "width":width,
 "height": height};
 }

 }());
<commit_msg>MS-423<commit_after>/*
 *    Copyright 2013 APPNEXUS INC
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

(function() {
 var isIOS = (/iphone|ipad|ipod/i).test(window.navigator.userAgent.toLowerCase());
 if (isIOS) {
 console = {};
 console.log = function(log) {
 var iframe = document.createElement('iframe');
 iframe.setAttribute('src', 'anwebconsole: ' + log);
 document.documentElement.appendChild(iframe);
 iframe.parentNode.removeChild(iframe);
 iframe = null;
 };
 console.debug = console.info = console.warn = console.error = console.log;
 }
 }());

(function() {

 // Set up some variables
 var mraid = window.mraid = {};
 mraid.util = {};
 var listeners = [];
 listeners['ready']=[];
 listeners['error']=[];
 listeners['stateChange']=[];
 listeners['viewableChange']=[];
 listeners['sizeChange']=[];
 var state='loading'; //Can be loading, default, expanded, hidden, or resized
 var placement_type='inline';
 var is_viewable=false;
 var expand_properties={width:-1, height:-1, useCustomClose:false, isModal:true};
 var orientation_properties={allowOrientationChange:true, forceOrientation:"none"};
 var resize_properties={width:-1, height:-1, offsetX: 0, offsetY: 0, customClosePosition: 'top-right', allowOffscreen: true};
 var screen_size={};
 var max_size={};
 var default_position={};
 var current_position={};

 // ----- MRAID AD API FUNCTIONS -----

 // getVersion() returns string '2.0'
 mraid.getVersion=function(){ return '2.0'};

 // getVendor() returns string 'appnexus'
 mraid.getVendor=function(){ return 'appnexus'};

 /** Adds a listener to a specific event. For example, a function onReady might be defined, and then mraid.addEventListener('ready', onReady)
  * is called. When the ready event is fired, onReady will be called.
  * Events 'error', 'viewableChange', 'stateChange', have parameters.
  */
 mraid.addEventListener=function(event_name, method){
 if(listeners[event_name].indexOf(method) > -1) return; // Listener is already registered
 listeners[event_name].push(method);
 };

 // Removes a listener from the registry
 mraid.removeEventListener=function(event_name, method){
 //If no method name is given, remove all listeners from event
 if(method == null){
 listeners[event_name].length=0;
 return;
 }

 var method_index = listeners[event_name].indexOf(method);
 if(method_index > -1){ //Don't try to remove unregistered listeners
 listeners[event_name].splice(method_index,1);
 }else{
 mraid.util.errorEvent("An unregistered listener was requested to be removed.", "mraid.removeEventListener()")
 }
 };

 //returns 'loading', 'default', 'expanded', or 'hidden'
 mraid.getState=function(){
 return state;
 };

 //returns 'inline' or 'interstitial'
 mraid.getPlacementType=function(){
 return placement_type;
 };

 //returns true or false
 mraid.isViewable=function(){
 return is_viewable;
 };

 // ----- MRAID JS TO NATIVE FUNCTIONS -----

 //Closes an expanded ad or hides an ad in default state
 mraid.close=function(){
 switch(mraid.getState()){
 case 'loading':
 mraid.util.errorEvent("mraid.close() called while state is 'loading'.", "mraid.close()");
 break;
 case 'default':
 window.open("mraid://close/");
 mraid.util.stateChangeEvent('hidden');
 break;
 case 'expanded':
 window.open("mraid://close/");
 mraid.util.stateChangeEvent('default');
 break;
 case 'hidden':
 mraid.util.errorEvent("mraid.close() called while ad was already hidden", "mraid.close()");
 break;
 case 'resized':
 window.open("mraid://close/");
 mraid.util.stateChangeEvent('default');
 }
 };

 // Expands a default state ad, or unhides a hidden ad. Optionally takes a URL to load in the expanded view
 mraid.expand=function(url){
 switch(mraid.getState()){
 case 'loading':
 mraid.util.errorEvent("mraid.expand() called while state is 'loading'.", "mraid.expand()");
 break;
 case 'default':
 if((expand_properties.height>0 && expand_properties.width>0) && (expand_properties.height < current_position.height || expand_properties.width < current_position.width)){
 mraid.util.errorEvent("Can't expand to a size smaller than the default size.", "mraid.expand()");
 return;
 }
 window.open("mraid://expand/"+"?w="+mraid.getExpandProperties().width+"&h="+mraid.getExpandProperties().height+"&useCustomClose="+mraid.getExpandProperties().useCustomClose+(url!=null ? "&url="+url:""));
 mraid.util.stateChangeEvent('expanded');
 if(url!=null){
 window.open(url);
 }
 break;
 case 'expanded':
 mraid.util.errorEvent("mraid.expand() called while state is 'expanded'.", "mraid.expand()");
 break;
 case 'hidden':
 mraid.util.errorEvent("mraid.expand() called while state is 'hidden'.", "mraid.expand()");
 break;
 case 'resized':
 mraid.util.stateChangeEvent('expanded');
 }
 };

 // Takes an object... {width:300, height:250, useCustomClose:false, isModal:false};
 mraid.setExpandProperties=function(properties){
 properties.isModal=true; // Read only property.
 expand_properties=properties;
 };

 //returns a json object... {width:300, height:250, useCustomClose:false, isModal:false};
 mraid.getExpandProperties=function(){
 return expand_properties;
 };

 // Takes a boolean
 mraid.useCustomClose=function(well_is_it){
 ep = mraid.getExpandProperties();
 ep.useCustomClose = well_is_it;
 mraid.setExpandProperties(ep);
 };

 // Loads a given URL
 mraid.open=function(url){
 window.location.href = url;
 };

 // MRAID 2.0 Stuff.
 mraid.resize=function(){
 if(resize_properties.height<0 || resize_properties.width<0){
 mraid.util.errorEvent("mraid.resize() called before mraid.setResizeProperties()", "mraid.resize()");
 return;
 }
 switch(mraid.getState()){
 case 'loading':
 mraid.util.errorEvent("mraid.resize() called while state is 'loading'.", "mraid.resize()");
 break;
 case 'expanded':
 mraid.util.errorEvent("mraid.resize() called while state is 'expanded'.", "mraid.resize()");
 break;
 case 'resized':
 case 'default':
 window.open("mraid://resize/?w="+resize_properties.width
             +"&h="+resize_properties.height
             +"&offset_x="+resize_properties.offsetX
             +"&offset_y="+resize_properties.offsetY
             +"&custom_close_position="+resize_properties.customClosePosition
             +"&allow_offscreen="+resize_properties.allowOffscreen);
 mraid.util.stateChangeEvent('resized');
 break;
 case 'hidden':
 break;

 }

 }

 mraid.setResizeProperties=function(props){
 if(props.customClosePosition!=null && props.customClosePosition != "top-right"
    && props.customClosePosition != "top-left"
    && props.customClosePosition != "center"
    && props.customClosePosition != "bottom-left"
    && props.customClosePosition != "bottom-right"
    && props.customClosePosition != "top-center"
    && props.customClosePosition != "bottom-center"){
 mraid.util.errorEvent("Invalid customClosePosition.", "mraid.setResizeProperties()");
 }else{
 resize_properties=props;
 }
 }

 mraid.getResizeProperties=function(){
 return resize_properties;
 }

 //returns a json object... {allowOrientationChange:true, forceOrientation:"none"};
 mraid.getOrientationProperties=function(){
 return orientation_properties;
 }

 // Takes an object... {allowOrientationChange:true, forceOrientation:"none"};
 mraid.setOrientationProperties=function(properties){
 orientation_properties=properties;

 if (typeof properties === "undefined") {
 return;
 }

 if(properties.forceOrientation!=='portrait' && properties.forceOrientation!=='landscape' && properties.forceOrientation!=='none' ){
 mraid.util.errorEvent("Invalid orientationProperties forceOrientation property", "mraid.setOrientationProperties()");
 properties.forceOrientation='none';
 }

 if(typeof properties.allowOrientationChange !== "boolean"){
 mraid.util.errorEvent("Invalid orientationProperties allowOrientationChange property", "mraid.setOrientationProperties()");
 properties.allowOrientationChange=true;
 }

 window.open("mraid://setOrientationProperties/?allow_orientation_change="+properties.allowOrientationChange
             +"&force_orientation="+properties.forceOrientation);
 }

 // Creates a calendar event when passed a W3C-formatted json object
 mraid.createCalendarEvent=function(event){
 window.open("mraid://createCalendarEvent/?p="+encodeURIComponent(JSON.stringify(event)));
 }

 // Plays a video in the native player
 mraid.playVideo=function(uri){
 window.open("mraid://playVideo/?uri="+encodeURIComponent(uri));
 }

 // Stores a picture on the device
 mraid.storePicture=function(uri){
 window.open("mraid://storePicture/?uri="+encodeURIComponent(uri));
 }

 // Convenience function to modify useCustomClose attribute of expandProperties
 mraid.useCustomClose=function(value){
 expand_properties.useCustomClose = value;
 }

 // Checks if a feature is supported by this device
 mraid.supports=function(feature){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.supports()' called during loading state.", "mraid.supports()");
 return;
 }
 switch(feature){
 case 'sms':
 return supports_sms;
 case 'tel':
 return supports_tel;
 case 'calendar':
 return supports_calendar;
 case 'storePicture':
 return supports_storePicture;
 case 'inlineVideo':
 return supports_inlineVideo;
 }
 mraid.util.errorEvent("Unknown feature to check for support: "+feature, "mraid.supports()");
 return false;
 }

 // Gets the screen size of the device
 mraid.getScreenSize=function(){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.getScreenSize()' called during loading state.", "mraid.getScreenSize()");
 return;
 }else{
 return screen_size;
 }
 }

 // Gets the max size of the ad if expanded (so it won't obscure the app's title bar)
 mraid.getMaxSize=function(){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.getMaxSize()' called during loading state.", "mraid.getMaxSize()");
 return;
 }else{
 return max_size;
 }
 }

 // Gets the default position of the ad view, in dips offset from top left.
 mraid.getDefaultPosition=function(){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.getDefaultPosition()' called during loading state.", "mraid.getDefaultPosition()");
 return;
 }else{
 return default_position;
 }
 }

 // Gets the current position of the ad view, in dips offset from top left.
 mraid.getCurrentPosition=function(){
 if(mraid.getState()=="loading"){
 mraid.util.errorEvent("Method 'mraid.getCurrentPosition()' called during loading state.", "mraid.getCurrentPosition()");
 return;
 }else{
 return current_position;
 }
 }

 // ----- MRAID UTILITY FUNCTIONS -----
 // These functions are called by the native SDK to drive events and update information

 mraid.util.setPlacementType=function(type){
 placement_type=type;
 };

 mraid.util.readyEvent=function(){
 for(var i=0;i<listeners['ready'].length;i++){
 listeners['ready'][i]();
 }
 };

 mraid.util.errorEvent=function(message, what_doing){
 for(var i=0;i<listeners['error'].length;i++){
 listeners['error'][i](message, what_doing);
 }
 };

 mraid.util.viewableChangeEvent=function(is_viewable_now){
 is_viewable = is_viewable_now;
 for(var i=0;i<listeners['viewableChange'].length;i++){
 listeners['viewableChange'][i](is_viewable_now);
 }
 };

 mraid.util.setIsViewable=function(is_it_viewable){
 if(is_viewable===is_it_viewable) return;
 is_viewable=is_it_viewable;
 mraid.util.viewableChangeEvent(is_viewable);
 };

 mraid.util.stateChangeEvent=function(new_state){
 if(state===new_state && state!='resized') return;
 state=new_state;
 if(new_state==='hidden'){
 mraid.util.setIsViewable(false);
 }
 for(var i=0;i<listeners['stateChange'].length;i++){
 listeners['stateChange'][i](new_state);
 }
 };

 mraid.util.sizeChangeEvent=function(width, height){
 if(state==='loading') return;
 if(width != mraid.getCurrentPosition().width || height != mraid.getCurrentPosition().height){
 for(var i=0;i<listeners['sizeChange'].length;i++){
 listeners['sizeChange'][i](width, height);
 }
 }
 }

 var supports_sms = false;
 var supports_tel = false;
 var supports_calendar = false;
 var supports_storePicture = false;
 var supports_inlineVideo = false;
 mraid.util.setSupportsSMS=function(val){
 supports_sms = val;
 }

 mraid.util.setSupportsTel=function(val){
 supports_tel=val;
 }

 mraid.util.setSupportsCalendar=function(val){
 supports_calendar=val;
 }

 mraid.util.setSupportsStorePicture=function(val){
 supports_storePicture=val;
 }

 mraid.util.setSupportsInlineVideo=function(val){
 supports_inlineVideo=val;
 }

 mraid.util.setScreenSize=function(width, height){
 screen_size={"width":width,
 "height": height};
 }

 mraid.util.setMaxSize=function(width, height){
 max_size={"width":width,
 "height": height};
 }

 mraid.util.setDefaultPosition=function(x, y, width, height){
 default_position={"x": x,
 "y": y,
 "width":width,
 "height": height};
 current_position = default_position;
 }

 mraid.util.setCurrentPosition=function(x, y, width, height){
 current_position={"x": x,
 "y": y,
 "width":width,
 "height": height};
 }

 }());
<|endoftext|>


<commit_before>function SpriteManager() {

	var sprites = new Array();

	/**
	 * add sprite to collection
	 *
	 * @return void
	 */
	this.addSprite = function(sprite) {
		sprite.setManager(this);
		sprites.push(sprite);
	};

	/**
	 * set player sprite that reacts on the mouse
	 *
	 * @param {Sprite} next_player
	 * @return void
	 */
	this.setPlayer = function(next_player) {
		$.each(sprites, function(k, v) {
			v.setPlayer(false);

			if (v == next_player) {
				next_player = k;
			}
		});

		sprites[next_player].setPlayer(true);
	}

	/**
	 * print out manager status
	 *
	 * @return void
	 */
	this.status = function() {
		var status = {sprites: {}};
		$.each(sprites, function(k, sprite) {
			status.sprites[k] = {isPlayer: sprite.isPlayer(), object: sprite};
		});
		return status;
	}

	this.animation_loop_update = 0;

	/**
	 * update loop
	 *
	 * @return void
	 */
	this.updateSprites = function() {
		if (this.animation_loop_update === 0) {
			this.animation_loop_update = new Date().getTime();
		}

		var self = this;

		window.requestAnimFrame(function() {
			var current = new Date().getTime(),
				delta = current - self.animation_loop_update;

			if (delta >= 40) {
				$.each(sprites, function(k, sprite) {
					sprite.update();
				});
				self.animation_loop_update = new Date().getTime();
			}

			self.updateSprites();
		});
	}

}
<commit_msg>oop redesign<commit_after>var SpriteManager = function() {

	this.sprites = new Array();

	this.animation_loop_update = 0;

}

/**
 * add sprite to collection
 *
 * @return void
 */
SpriteManager.prototype.addSprite = function(sprite) {
	sprite.setManager(this);
	this.sprites.push(sprite);
};

/**
 * set player sprite that reacts on the mouse
 *
 * @param {Sprite} next_player
 * @return void
 */
SpriteManager.prototype.setPlayer = function(next_player) {
	$.each(this.sprites, function(k, v) {
		v.setPlayer(false);

		if (v == next_player) {
			next_player = k;
		}
	});

	this.sprites[next_player].setPlayer(true);
}

/**
 * print out manager status
 *
 * @return void
 */
SpriteManager.prototype.status = function() {
	var status = {sprites: {}};
	$.each(this.sprites, function(k, sprite) {
		status.sprites[k] = {isPlayer: sprite.isPlayer(), object: sprite};
	});
	return status;
}

/**
 * update loop
 *
 * @return void
 */
SpriteManager.prototype.updateSprites = function() {
	if (this.animation_loop_update === 0) {
		this.animation_loop_update = new Date().getTime();
	}

	var self = this;

	window.requestAnimFrame(function() {
		var current = new Date().getTime(),
			delta = current - self.animation_loop_update;

		if (delta >= 40) {
			$.each(self.sprites, function(k, sprite) {
				sprite.update();
			});
			self.animation_loop_update = new Date().getTime();
		}

		self.updateSprites();
	});
}
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var CompanySchema = new Schema({
    name: String,
    info: String,
    active: Boolean
});

module.exports = mongoose.model('Company', CompanySchema);<commit_msg>Changed company model<commit_after>'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var CompanySchema = new Schema({
    name: {type: String, required: true},
    division: {type: String, required: true},
    admins: {type: [String], lowercase: true, required: true}
});

module.exports = mongoose.model('Company', CompanySchema);<|endoftext|>


<commit_before>const WEB_CONFIG = require('../../config/web');
const FEED_CONFIG = require('../../config/feed');
const rp = require('request-promise-native');
const logger = require('../../logger');

/**
 * Send a request to subscribe to facebook webhooks.
 *
 * @returns {Promise.<void>} Nothing
 */
async function subscribeWebhook() {
  const options = {
    method: 'POST',
    url: `${FEED_CONFIG.baseApi}/${FEED_CONFIG.appId}/subscriptions`,
    qs: {
      object: 'page',
      callback_url: `${WEB_CONFIG.publicURL}/api/feed/webhooks`,
      include_values: true,
      verify_token: FEED_CONFIG.verifyToken,
      fields: [
        'feed',
      ].join(', '),
    },
    headers: {
      Authorization: `Bearer ${FEED_CONFIG.accessToken}`,
    },
    json: true,
  };

  try {
    const res = await rp(options);
    if (!res.success) {
      logger.warn('Feed service: received a negative response from facebook: %o', res);
    }
    // TODO Send mail in case of failure
  } catch (error) {
    logger.warn('Feed service: error while subscribing to app feed: %o', error.error);
  }
}

/**
 * Import one change from one entry from the FB webhooks.
 *
 * @param field
 * @param value
 * @param value.item
 * @param value.post_id
 * @param value.verb
 * @param value.createdTime
 * @param value.isHidden
 * @param value.message
 * @return {Promise<void>}
 */
async function importOneChange({ field, value }) {
  const { item, post_id, verb, created_time: createdTime, is_hidden: isHidden, message } = value;

}

/**
 * Import only one entry from facebook.
 *
 * @param changes {any[]} Changes of a post of the page
 * @return {Promise<void>}
 */
async function importOneFacebookItem({ changes }) {
  return Promise.all(changes.map(importOneChange));
}

/**
 * Import raw data from facebook webhooks.
 *
 * @param object {string} Type of the object
 * @param entry {any[]} FB entries
 * @return {Promise<*>}
 */
async function importWebhookEvent({ object, entry }) {
  logger.verbose(`Facebook feed received for '${object}'. Got ${entry.length} items`);

  return Promise.all(entry.map(importOneFacebookItem));
}

module.exports = {
  subscribeWebhook,
  importWebhookEvent,
};
<commit_msg>Ready to handle each events from FB<commit_after>const WEB_CONFIG = require('../../config/web');
const FEED_CONFIG = require('../../config/feed');
const rp = require('request-promise-native');
const logger = require('../../logger');
const { FeedObject } = require('../models');
const { createUserError } = require('../../utils');

/**
 * Send a request to subscribe to facebook webhooks.
 *
 * @returns {Promise.<void>} Nothing
 */
async function subscribeWebhook() {
  const options = {
    method: 'POST',
    url: `${FEED_CONFIG.baseApi}/${FEED_CONFIG.appId}/subscriptions`,
    qs: {
      object: 'page',
      callback_url: `${WEB_CONFIG.publicURL}/api/feed/webhooks`,
      include_values: true,
      verify_token: FEED_CONFIG.verifyToken,
      fields: [
        'feed',
      ].join(', '),
    },
    headers: {
      Authorization: `Bearer ${FEED_CONFIG.accessToken}`,
    },
    json: true,
  };

  try {
    const res = await rp(options);
    if (!res.success) {
      logger.warn('Feed service: received a negative response from facebook: %o', res);
    }
    // TODO Send mail in case of failure
  } catch (error) {
    logger.warn('Feed service: error while subscribing to app feed: %o', error.error);
  }
}

/**
 * Import one change from one entry from the FB webhooks.
 *
 * @param field
 * @param value
 * @return {Promise<void>}
 */
async function _importChange({ field, value }) {
  logger.verbose(`Facebook feed received a ${field} update`);

  if (field !== 'feed') {
    logger.error(`Server received update for ${field} that it should not have received!`);
    throw createUserError('BadRequest', 'Could not handle this entry');
  }

  const {
    action,
    album_id: albumId,
    comment_id: commentId,
    created_time: createdTime,
    edited_time: editedTime,
    event_id: eventId,
    from,
    is_hidden: isHidden,
    item,
    link,
    message,
    parent_id: parentId,
    photo,
    photo_id: photoId,
    photo_ids: photoIds,
    photos,
    post,
    post_id: postId,
    published,
    reaction_type: reactionType,
    recipient_id: recipientId,
    share_id: shareId,
    verb,
    video,
    video_id,
  } = value;

  switch (verb) {
    case 'add': {
      break;
    }
    case 'block':
    case 'edit':
    case 'edited':
    case 'delete':
    case 'follow':
    case 'hide':
    case 'mute':
    case 'remove':
    case 'unblock':
    case 'unhide':
    case 'update':
      logger.warn(`Server does not implement ${verb} action for now`);
      break;
    default:
      logger.error(`Unrecognised verb from facebook webhooks: ${verb}`);
  }
}

/**
 * Import raw data from facebook webhooks.
 *
 * @param object {string} Type of the object
 * @param entry {array} FB entries
 * @return {Promise<*>}
 */
async function importWebhookEvent({ object, entry }) {
  logger.verbose(`Facebook feed received for '${object}'. Got ${entry.length} items`);

  // Each entry should is processed at the same time
  // But each changes of an entry is done one after another to have the right order
  return Promise.all(entry.map(({ changes }) =>
    changes.reduce(
      (p, change) => p.then(_importChange(change)),
      Promise.resolve(),
    )));
}

module.exports = {
  subscribeWebhook,
  importWebhookEvent,
};
<|endoftext|>


<commit_before>
import Comments from '/imports/collections/comments';
import Keywords from '/imports/collections/keywords';

Meteor.method('keyword_cron', () => {
	// console.log(' -- Starting cron: Keywords');

	const comments = Comments.find().fetch();
	const keywords = [];

	let isInKeywords = false;

	comments.forEach((comment, commentIndex) => {
		comment.keywords.forEach((commentKeyword, commentKeywordIndex) => {
			isInKeywords = false;
			keywords.forEach((keyword, keywordIndex) => {
				if (keyword.slug === commentKeyword.slug) {
					isInKeywords = true;
					keywords[keywordIndex].count++;
				}
			});

			if (!isInKeywords) {
				comments[commentIndex].keywords[commentKeywordIndex].count = 0;
				keywords.push(commentKeyword);
			}
		});
	});

	keywords.forEach((keyword) => {
		// console.log(' -- -- ', keyword.title, keyword.count);

		Keywords.update({ _id: keyword._id }, { $set: { count: keyword.count } });
	});

	/*
	 comments.forEach(function(comment){
	 var nLines = 1;

	 if('lineTo' in comment && comment.lineTo){
	 nLines = comment.lineTo - comment.lineFrom + 1;
	 // console.log(comment.lineFrom, comment.lineTo, comment.nLines);

	 }

	 Comments.update({_id: comment._id}, {$set:{nLines:nLines}});
	 });
	 */

	console.log(' -- Cron run complete: Keywords');

	return 1;
}, {
	url: 'keywords/cron',
	getArgsFromRequest(request) {
		// Sometime soon do validation here
		const content = request.body;

		return [content];
	},
});
<commit_msg>add exception for keywords that may be null<commit_after>
import Comments from '/imports/collections/comments';
import Keywords from '/imports/collections/keywords';

Meteor.method('keyword_cron', () => {
	// console.log(' -- Starting cron: Keywords');

	const comments = Comments.find().fetch();
	const keywords = [];

	let isInKeywords = false;

	comments.forEach((comment, commentIndex) => {
		comment.keywords.forEach((commentKeyword, commentKeywordIndex) => {
			isInKeywords = false;
			if (commentKeyword !== null) {
				keywords.forEach((keyword, keywordIndex) => {
					if (keyword.slug === commentKeyword.slug) {
						isInKeywords = true;
						keywords[keywordIndex].count++;
					}
				});

				if (!isInKeywords) {
					comments[commentIndex].keywords[commentKeywordIndex].count = 0;
					keywords.push(commentKeyword);
				}
			}
		});
	});

	keywords.forEach((keyword) => {
		// console.log(' -- -- ', keyword.title, keyword.count);

		Keywords.update({ _id: keyword._id }, { $set: { count: keyword.count } });
	});

	/*
	 comments.forEach(function(comment){
	 var nLines = 1;

	 if('lineTo' in comment && comment.lineTo){
	 nLines = comment.lineTo - comment.lineFrom + 1;
	 // console.log(comment.lineFrom, comment.lineTo, comment.nLines);

	 }

	 Comments.update({_id: comment._id}, {$set:{nLines:nLines}});
	 });
	 */

	console.log(' -- Cron run complete: Keywords');

	return 1;
}, {
	url: 'keywords/cron',
	getArgsFromRequest(request) {
		// Sometime soon do validation here
		const content = request.body;

		return [content];
	},
});
<|endoftext|>


<commit_before>const result = require('../result')

describe('prepare result to save to firebase', () => {
    test('prepare result', () => {

        expect.assertions(1)

        let payload = {
            answer: 'a1',
            question: 'question',
            point: 10
        }

        let prepareResult = result.prepareResultForFirebase(payload, ['a1', 'a2', 'a3'], 2,
            true, '2017-07-04T18:08:49+07:00', 1499167085389, 15, '00001', '12facts')

        let expected = [{
            answer: 'a1',
            point: 10,
            question: 'question',
            round: 2,
            score: 15,
            result: true,
            startedAt: '2017-07-04T18:08:49+07:00',
            doneAt: '2017-07-04T18:18:05+07:00',
            duration: 556389,
            category: '12facts'
        }]

        return expect(prepareResult).resolves.toEqual(expected)
    })
})<commit_msg>fix test<commit_after>const result = require('../result')

describe('prepare result to save to firebase', () => {
    test('prepare result', () => {

        expect.assertions(1)

        let payload = {
            answer: 'a1',
            question: 'question',
            point: 10
        }

        let prepareResult = result.prepareResultForFirebase(payload, 5, true, , '2017-07-04T18:08:49+07:00',
        ['a1', 'a2', 'a3'], 1499167085389, 15, '00001', '12facts')

        let expected = [{
            answer: 'a1',
            point: 10,
            question: 'question',
            round: 5,
            score: 15,
            result: true,
            startedAt: '2017-07-04T18:08:49+07:00',
            doneAt: '2017-07-04T18:18:05+07:00',
            duration: 556389,
            category: '12facts'
        }]

        return expect(prepareResult).resolves.toEqual(expected)
    })
})<|endoftext|>


<commit_before>(function() {
    function config($locationProvider, $stateProvider, $urlRouterProvider, $authProvider, userProvider) {
        // $locationProvider
        //     .html5Mode({
        //         enabled: true,
        //         requireBase: false
        //     });

        $stateProvider
            .state('home', {
                url: '/',
                controller: 'HomeCtrl',
                controllerAs: '$ctrl',
                templateUrl: 'client/scripts/views/home/home.html'
            })
            .state('dashboard', {
                url: '/dashboard',
                component: 'dashboard',
                resolve: {
                  auth: function($auth) {
                    return $auth.validateUser();
                  }
                }
            })
            .state('register', {
                url: '/register',
                component: 'userRegistration'
            })
            .state('login', {
                url: '/login',
                component: 'userLogin'
            })
            .state('request-password', {
                url: '/requestpassword',
                component: 'requestPasswordReset'
            })
            .state('update-password', {
                url: '/updatepassword',
                component: 'updatePassword'
            });

        $urlRouterProvider.otherwise('/');

        $authProvider
            .configure({
                apiUrl: '/api',
                authProviderPaths: {
                  facebook: '/auth/facebook',
                  google: '/auth/google_oauth2',
                  twitter: '/auth/twitter'
                },
                handleLoginResponse: function(response) {
                  userProvider.$set(response.data);
                },
                handleAccountUpdateResponse: function(response) {
                  userProvider.$set(response.data);
                },
                handleTokenValidationResponse: function(response) {
                  userProvider.$set(response.data);
                }
            });
    }

    angular
        .module('kaboodleme', ['ui.router', 'ng-token-auth'])
        .config(config);
})();
<commit_msg>Fix persistence issue<commit_after>(function() {
    function config($locationProvider, $stateProvider, $urlRouterProvider, $authProvider, userProvider) {
        // $locationProvider
        //     .html5Mode({
        //         enabled: true,
        //         requireBase: false
        //     });

        $stateProvider
            .state('home', {
                url: '/',
                controller: 'HomeCtrl',
                controllerAs: '$ctrl',
                templateUrl: 'client/scripts/views/home/home.html'
            })
            .state('dashboard', {
                url: '/dashboard',
                component: 'dashboard',
                resolve: {
                  auth: function($auth) {
                    return $auth.validateUser();
                  }
                }
            })
            .state('register', {
                url: '/register',
                component: 'userRegistration'
            })
            .state('login', {
                url: '/login',
                component: 'userLogin'
            })
            .state('request-password', {
                url: '/requestpassword',
                component: 'requestPasswordReset'
            })
            .state('update-password', {
                url: '/updatepassword',
                component: 'updatePassword'
            });

        $urlRouterProvider.otherwise('/');

        $authProvider
            .configure({
                apiUrl: '/api',
                authProviderPaths: {
                  facebook: '/auth/facebook',
                  google: '/auth/google_oauth2',
                  twitter: '/auth/twitter'
                },
                storage: 'localStorage',
                handleLoginResponse: function(response) {
                  userProvider.$set(response.data);
                },
                handleAccountUpdateResponse: function(response) {
                  userProvider.$set(response.data);
                },
                handleTokenValidationResponse: function(response) {
                  userProvider.$set(response.data);
                }
            });
    }

    angular
        .module('kaboodleme', ['ui.router', 'ng-token-auth'])
        .config(config);
})();
<|endoftext|>


<commit_before>'use strict';
const Express = require('express'),
      router = Express.Router(),
      BodyParser = require('body-parser'),
      parseUrlEncoded = BodyParser.urlencoded({ extended: false }),
      EventController = require('../controllers/EventsController');

router
  .route('/')
  .get(EventController.getStarredEvents);

module.exports = router;
<commit_msg>fix (Routing): Correct module import statement<commit_after>'use strict';
const Express = require('express'),
      router = Express.Router(),
      BodyParser = require('body-parser'),
      parseUrlEncoded = BodyParser.urlencoded({ extended: false }),
      SearchController = require('../controllers/SearchController');

router
  .route('/')
  .get(SearchController.getStarredEvents);

module.exports = router;
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//

// Edit user profile info ----------------------------------------------------//
router.put('/update/:id', function(req, res) {

  var userData = req.body.userData;
  // var userId = req.userStatus.userId;

  var userId = assignUserId(req);

  var queryObject = profileEditQueryBuilder(userData, userId);

  if (queryObject.queryString !== 'UPDATE mentors SE WHERE id = $1') {
    pg.connect(connectionString, function(error, client, done) {
      connectionErrorCheck(error);

      // Update the database
      client.query(queryObject.queryString, queryObject.propertyArray,
        function(error, result) {
          done(); // Close connection to the database

          if(error) {
            console.log('Unable to update user information: ', error);
            res.sendStatus(500);
          } else {
            res.sendStatus(200);
          }

        }
      );
    });
  }
});
//----------------------------------------------------------------------------//

// Create a new FAQ entry ----------------------------------------------------//
router.post('/new-faq', function(req, res) {
  var userId = req.userStatus.userId;
  var question = req.body.faqData.question;
  var answer = req.body.faqData.answer;
  console.log("FAQ OBJECT:", req.body.faqData);

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    client.query(
      'INSERT INTO faq (mentor_id, question, answer) VALUES ($1, $2, $3)',
      [userId, question, answer],
      function(error, result) {
        done(); // Close connection to the database

        if(error) {
          console.log('Error when creating new FAQ: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(201);
        }
      }
    );
  });
});
//----------------------------------------------------------------------------//

// Edit an existing FAQ entry ------------------------------------------------//
router.put('/edit-faq/:id', function(req, res) {
  var userId;
  var faqArray = req.body.faqArray;

  var queryObject = faqEditQueryBuilder(faqArray, userId);

  userId = assignUserId(req);

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    client.query(queryObject.queryString, queryObject.propertyArray,
      function(error, result) {
        done(); // Close connection to the database

        if(error) {
          console.log('Error when updating FAQ: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(201);
        }
      }
    );
  });
});
//----------------------------------------------------------------------------//

// Delete an existing FAQ entry ------------------------------------------------//
router.delete('/edit-faq/:id', function(req, res) {

});
//----------------------------------------------------------------------------//

// Delete a user and all related messages and FAQs from the database ---------//
router.delete('/delete-user/:id', function(req, res) {
  var isAdmin = req.userStatus.isAdmin;
  var userId = req.userStatus.userId;
  var userToDelete = req.params.id;

  if (isAdmin === true || userToDelete === userId){
    pg.connect(connectionString, function(error, client, done) {
      connectionErrorCheck(error);

      client.query(
        'DELETE FROM mentors WHERE id = $1', [userId],
        function(error, result) {
          done(); // Close connection to the database

          if(error) {
            console.log('Error when deleting user: ', error);
            res.sendStatus(500);
          } else {
            res.sendStatus(201);
          }
        }
      );
    });
  }
});

//----------------------------------------------------------------------------//

// Assigns userId based on isAdmin -------------------------------------------//
function assignUserId(req){
  if(req.userStatus.isAdmin){
    return req.params.id;
  } else {
    return req.userStatus.userId;
  }
}
//----------------------------------------------------------------------------//

// Checks for errors connecting to the database ------------------------------//
function connectionErrorCheck(error) {
  if (error) {
    console.log('Database connection error: ', error);
    res.sendStatus(500);
  }
}
//----------------------------------------------------------------------------//

// Cunstructs SQL query based off of the profile fields ----------------------//
function profileEditQueryBuilder(object, userId) {
  var query = 'UPDATE mentors SET ';
  var array = [];
  var index = 0;

  for (var property in object) {
    if (object[property]) {
      index++;
      query += property + ' = $' + index + ', ';
      array.push(object[property]);
    }
  }

  index++;
  query = query.slice(0, -2);
  query += ' WHERE id = $' + index;
  array.push(userId);

  return {
    queryString: query,
    propertyArray: array
  };
}
//----------------------------------------------------------------------------//

// Constructs SQL query based off of updated FAQ info ------------------------//
function faqEditQueryBuilder(faqArray, userId) {
  // console.log('ARRAY IN QUERY BUILDER', array);

  var queryString = '';
  var propertyArray = [];
  var questionString = '';
  var answerString = '';
  var loopTracker = 0;

  for (var index = 0; index < faqArray.length; index++) {
    loopTracker++;
    questionString += ' WHEN $' + loopTracker;
    loopTracker++;
    questionString += ' THEN $' + loopTracker;
  }

  for (index = 0; index < faqArray.length; index++) {
    loopTracker++;
    answerString += ' WHEN $' + loopTracker;
    loopTracker++;
    answerString += ' THEN $' + loopTracker;
  }

  queryString +=
    'UPDATE faq ' +
    'SET question = CASE id' + questionString + ' END, ' +
    'answer = CASE id' + answerString + ' END';

  for (index = 0; index < faqArray.length; index++) {
    propertyArray.push(faqArray[index].faq_id, faqArray[index].question);
  }

  for (index = 0; index < faqArray.length; index++) {
    propertyArray.push(faqArray[index].faq_id, faqArray[index].answer);
  }

  return {
    queryString: queryString,
    propertyArray: propertyArray
  };
}
//----------------------------------------------------------------------------//

module.exports = router;
<commit_msg>Deleting a user now works<commit_after>//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//

// Edit user profile info ----------------------------------------------------//
router.put('/update/:id', function(req, res) {

  var userData = req.body.userData;
  // var userId = req.userStatus.userId;

  var userId = assignUserId(req);

  var queryObject = profileEditQueryBuilder(userData, userId);

  if (queryObject.queryString !== 'UPDATE mentors SE WHERE id = $1') {
    pg.connect(connectionString, function(error, client, done) {
      connectionErrorCheck(error);

      // Update the database
      client.query(queryObject.queryString, queryObject.propertyArray,
        function(error, result) {
          done(); // Close connection to the database

          if(error) {
            console.log('Unable to update user information: ', error);
            res.sendStatus(500);
          } else {
            res.sendStatus(200);
          }

        }
      );
    });
  }
});
//----------------------------------------------------------------------------//

// Create a new FAQ entry ----------------------------------------------------//
router.post('/new-faq', function(req, res) {
  var userId = req.userStatus.userId;
  var question = req.body.faqData.question;
  var answer = req.body.faqData.answer;
  console.log("FAQ OBJECT:", req.body.faqData);

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    client.query(
      'INSERT INTO faq (mentor_id, question, answer) VALUES ($1, $2, $3)',
      [userId, question, answer],
      function(error, result) {
        done(); // Close connection to the database

        if(error) {
          console.log('Error when creating new FAQ: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(201);
        }
      }
    );
  });
});
//----------------------------------------------------------------------------//

// Edit an existing FAQ entry ------------------------------------------------//
router.put('/edit-faq/:id', function(req, res) {
  var userId;
  var faqArray = req.body.faqArray;

  var queryObject = faqEditQueryBuilder(faqArray, userId);

  userId = assignUserId(req);

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    client.query(queryObject.queryString, queryObject.propertyArray,
      function(error, result) {
        done(); // Close connection to the database

        if(error) {
          console.log('Error when updating FAQ: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(201);
        }
      }
    );
  });
});
//----------------------------------------------------------------------------//

// Delete a user and all related messages and FAQs from the database ---------//
router.delete('/delete-user/:id', function(req, res) {
  var isAdmin = req.userStatus.isAdmin;
  var userId = req.userStatus.userId;
  var userToDelete = req.params.id;

  if (isAdmin === true || userToDelete === userId){
    pg.connect(connectionString, function(error, client, done) {
      connectionErrorCheck(error);

      client.query(
        'DELETE FROM mentors WHERE id = $1', [userToDelete],
        function(error, result) {
          done(); // Close connection to the database

          if(error) {
            console.log('Error when deleting user: ', error);
            res.sendStatus(500);
          } else {
            res.sendStatus(201);
          }
        }
      );
    });
  }
});

//----------------------------------------------------------------------------//

// Assigns userId based on isAdmin -------------------------------------------//
function assignUserId(req){
  if(req.userStatus.isAdmin){
    return req.params.id;
  } else {
    return req.userStatus.userId;
  }
}
//----------------------------------------------------------------------------//

// Checks for errors connecting to the database ------------------------------//
function connectionErrorCheck(error) {
  if (error) {
    console.log('Database connection error: ', error);
    res.sendStatus(500);
  }
}
//----------------------------------------------------------------------------//

// Cunstructs SQL query based off of the profile fields ----------------------//
function profileEditQueryBuilder(object, userId) {
  var query = 'UPDATE mentors SET ';
  var array = [];
  var index = 0;

  for (var property in object) {
    if (object[property]) {
      index++;
      query += property + ' = $' + index + ', ';
      array.push(object[property]);
    }
  }

  index++;
  query = query.slice(0, -2);
  query += ' WHERE id = $' + index;
  array.push(userId);

  return {
    queryString: query,
    propertyArray: array
  };
}
//----------------------------------------------------------------------------//

// Constructs SQL query based off of updated FAQ info ------------------------//
function faqEditQueryBuilder(faqArray, userId) {
  // console.log('ARRAY IN QUERY BUILDER', array);

  var queryString = '';
  var propertyArray = [];
  var questionString = '';
  var answerString = '';
  var loopTracker = 0;

  for (var index = 0; index < faqArray.length; index++) {
    loopTracker++;
    questionString += ' WHEN $' + loopTracker;
    loopTracker++;
    questionString += ' THEN $' + loopTracker;
  }

  for (index = 0; index < faqArray.length; index++) {
    loopTracker++;
    answerString += ' WHEN $' + loopTracker;
    loopTracker++;
    answerString += ' THEN $' + loopTracker;
  }

  queryString +=
    'UPDATE faq ' +
    'SET question = CASE id' + questionString + ' END, ' +
    'answer = CASE id' + answerString + ' END';

  for (index = 0; index < faqArray.length; index++) {
    propertyArray.push(faqArray[index].faq_id, faqArray[index].question);
  }

  for (index = 0; index < faqArray.length; index++) {
    propertyArray.push(faqArray[index].faq_id, faqArray[index].answer);
  }

  return {
    queryString: queryString,
    propertyArray: propertyArray
  };
}
//----------------------------------------------------------------------------//

module.exports = router;
<|endoftext|>


<commit_before>/**
 * @author James Baicoianu / http://www.baicoianu.com/
 */

THREE.FlyControls = function ( object, domElement ) {

	this.object = object;

	this.domElement = ( domElement !== undefined ) ? domElement : document;
	if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );

	// API

	this.movementSpeed = 1.0;
	this.rollSpeed = 0.005;

	this.dragToLook = false;
	this.autoForward = false;

	// disable default target object behavior

	this.object.useQuaternion = true;

	// internals

	this.tmpQuaternion = new THREE.Quaternion();

	this.mouseStatus = 0;

	this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
	this.moveVector = new THREE.Vector3( 0, 0, 0 );
	this.rotationVector = new THREE.Vector3( 0, 0, 0 );

	this.handleEvent = function ( event ) {

		if ( typeof this[ event.type ] == 'function' ) {

			this[ event.type ]( event );

		}

	};

	this.keydown = function( event ) {

		if ( event.altKey ) {

			return;

		}

		//event.preventDefault();

		switch ( event.keyCode ) {

			case 16: /* shift */ this.movementSpeedMultiplier = .1; break;

			case 87: /*W*/ this.moveState.forward = 1; break;
			case 83: /*S*/ this.moveState.back = 1; break;

			case 65: /*A*/ this.moveState.left = 1; break;
			case 68: /*D*/ this.moveState.right = 1; break;

			case 82: /*R*/ this.moveState.up = 1; break;
			case 70: /*F*/ this.moveState.down = 1; break;

			case 38: /*up*/ this.moveState.pitchUp = 1; break;
			case 40: /*down*/ this.moveState.pitchDown = 1; break;

			case 37: /*left*/ this.moveState.yawLeft = 1; break;
			case 39: /*right*/ this.moveState.yawRight = 1; break;

			case 81: /*Q*/ this.moveState.rollLeft = 1; break;
			case 69: /*E*/ this.moveState.rollRight = 1; break;

		}

		this.updateMovementVector();
		this.updateRotationVector();

	};

	this.keyup = function( event ) {

		switch( event.keyCode ) {

			case 16: /* shift */ this.movementSpeedMultiplier = 1; break;

			case 87: /*W*/ this.moveState.forward = 0; break;
			case 83: /*S*/ this.moveState.back = 0; break;

			case 65: /*A*/ this.moveState.left = 0; break;
			case 68: /*D*/ this.moveState.right = 0; break;

			case 82: /*R*/ this.moveState.up = 0; break;
			case 70: /*F*/ this.moveState.down = 0; break;

			case 38: /*up*/ this.moveState.pitchUp = 0; break;
			case 40: /*down*/ this.moveState.pitchDown = 0; break;

			case 37: /*left*/ this.moveState.yawLeft = 0; break;
			case 39: /*right*/ this.moveState.yawRight = 0; break;

			case 81: /*Q*/ this.moveState.rollLeft = 0; break;
			case 69: /*E*/ this.moveState.rollRight = 0; break;

		}

		this.updateMovementVector();
		this.updateRotationVector();

	};

	this.mousedown = function( event ) {

		if ( this.domElement !== document ) {

			this.domElement.focus();

		}

		event.preventDefault();
		event.stopPropagation();

		if ( this.dragToLook ) {

			this.mouseStatus ++;

		} else {

			switch ( event.button ) {

				case 0: this.object.moveForward = true; break;
				case 2: this.object.moveBackward = true; break;

			}

		}

	};

	this.mousemove = function( event ) {

		if ( !this.dragToLook || this.mouseStatus > 0 ) {

			var container = this.getContainerDimensions();
			var halfWidth  = container.size[ 0 ] / 2;
			var halfHeight = container.size[ 1 ] / 2;

			this.moveState.yawLeft   = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth  ) / halfWidth;
			this.moveState.pitchDown =   ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;

			this.updateRotationVector();

		}

	};

	this.mouseup = function( event ) {

		event.preventDefault();
		event.stopPropagation();

		if ( this.dragToLook ) {

			this.mouseStatus --;

			this.moveState.yawLeft = this.moveState.pitchDown = 0;

		} else {

			switch ( event.button ) {

				case 0: this.moveForward = false; break;
				case 2: this.moveBackward = false; break;

			}

		}

		this.updateRotationVector();

	};

	this.update = function( delta ) {

		var moveMult = delta * this.movementSpeed;
		var rotMult = delta * this.rollSpeed;

		this.object.translateX( this.moveVector.x * moveMult );
		this.object.translateY( this.moveVector.y * moveMult );
		this.object.translateZ( this.moveVector.z * moveMult );

		this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
		this.object.quaternion.multiply( this.tmpQuaternion );

		// expose the rotation vector for convenience
		this.object.rotation.setEulerFromQuaternion( this.object.quaternion, this.object.eulerOrder );

	};

	this.updateMovementVector = function() {

		var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;

		this.moveVector.x = ( -this.moveState.left    + this.moveState.right );
		this.moveVector.y = ( -this.moveState.down    + this.moveState.up );
		this.moveVector.z = ( -forward + this.moveState.back );

		//console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );

	};

	this.updateRotationVector = function() {

		this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
		this.rotationVector.y = ( -this.moveState.yawRight  + this.moveState.yawLeft );
		this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );

		//console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );

	};

	this.getContainerDimensions = function() {

		if ( this.domElement != document ) {

			return {
				size	: [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
				offset	: [ this.domElement.offsetLeft,  this.domElement.offsetTop ]
			};

		} else {

			return {
				size	: [ window.innerWidth, window.innerHeight ],
				offset	: [ 0, 0 ]
			};

		}

	};

	function bind( scope, fn ) {

		return function () {

			fn.apply( scope, arguments );

		};

	};

	this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
	this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
	this.domElement.addEventListener( 'mouseup',   bind( this, this.mouseup ), false );

	this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
	this.domElement.addEventListener( 'keyup',   bind( this, this.keyup ), false );

	this.updateMovementVector();
	this.updateRotationVector();

};
<commit_msg>Fixed breakage in FlyControls.<commit_after>/**
 * @author James Baicoianu / http://www.baicoianu.com/
 */

THREE.FlyControls = function ( object, domElement ) {

	this.object = object;

	this.domElement = ( domElement !== undefined ) ? domElement : document;
	if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );

	// API

	this.movementSpeed = 1.0;
	this.rollSpeed = 0.005;

	this.dragToLook = false;
	this.autoForward = false;

	// disable default target object behavior

	this.object.useQuaternion = true;

	// internals

	this.tmpQuaternion = new THREE.Quaternion();

	this.mouseStatus = 0;

	this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
	this.moveVector = new THREE.Vector3( 0, 0, 0 );
	this.rotationVector = new THREE.Vector3( 0, 0, 0 );

	this.handleEvent = function ( event ) {

		if ( typeof this[ event.type ] == 'function' ) {

			this[ event.type ]( event );

		}

	};

	this.keydown = function( event ) {

		if ( event.altKey ) {

			return;

		}

		//event.preventDefault();

		switch ( event.keyCode ) {

			case 16: /* shift */ this.movementSpeedMultiplier = .1; break;

			case 87: /*W*/ this.moveState.forward = 1; break;
			case 83: /*S*/ this.moveState.back = 1; break;

			case 65: /*A*/ this.moveState.left = 1; break;
			case 68: /*D*/ this.moveState.right = 1; break;

			case 82: /*R*/ this.moveState.up = 1; break;
			case 70: /*F*/ this.moveState.down = 1; break;

			case 38: /*up*/ this.moveState.pitchUp = 1; break;
			case 40: /*down*/ this.moveState.pitchDown = 1; break;

			case 37: /*left*/ this.moveState.yawLeft = 1; break;
			case 39: /*right*/ this.moveState.yawRight = 1; break;

			case 81: /*Q*/ this.moveState.rollLeft = 1; break;
			case 69: /*E*/ this.moveState.rollRight = 1; break;

		}

		this.updateMovementVector();
		this.updateRotationVector();

	};

	this.keyup = function( event ) {

		switch( event.keyCode ) {

			case 16: /* shift */ this.movementSpeedMultiplier = 1; break;

			case 87: /*W*/ this.moveState.forward = 0; break;
			case 83: /*S*/ this.moveState.back = 0; break;

			case 65: /*A*/ this.moveState.left = 0; break;
			case 68: /*D*/ this.moveState.right = 0; break;

			case 82: /*R*/ this.moveState.up = 0; break;
			case 70: /*F*/ this.moveState.down = 0; break;

			case 38: /*up*/ this.moveState.pitchUp = 0; break;
			case 40: /*down*/ this.moveState.pitchDown = 0; break;

			case 37: /*left*/ this.moveState.yawLeft = 0; break;
			case 39: /*right*/ this.moveState.yawRight = 0; break;

			case 81: /*Q*/ this.moveState.rollLeft = 0; break;
			case 69: /*E*/ this.moveState.rollRight = 0; break;

		}

		this.updateMovementVector();
		this.updateRotationVector();

	};

	this.mousedown = function( event ) {

		if ( this.domElement !== document ) {

			this.domElement.focus();

		}

		event.preventDefault();
		event.stopPropagation();

		if ( this.dragToLook ) {

			this.mouseStatus ++;

		} else {

			switch ( event.button ) {

				case 0: this.moveState.forward = 1; break;
				case 2: this.moveState.back = 1; break;

			}

			this.updateMovementVector();

		}

	};

	this.mousemove = function( event ) {

		if ( !this.dragToLook || this.mouseStatus > 0 ) {

			var container = this.getContainerDimensions();
			var halfWidth  = container.size[ 0 ] / 2;
			var halfHeight = container.size[ 1 ] / 2;

			this.moveState.yawLeft   = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth  ) / halfWidth;
			this.moveState.pitchDown =   ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;

			this.updateRotationVector();

		}

	};

	this.mouseup = function( event ) {

		event.preventDefault();
		event.stopPropagation();

		if ( this.dragToLook ) {

			this.mouseStatus --;

			this.moveState.yawLeft = this.moveState.pitchDown = 0;

		} else {

			switch ( event.button ) {

				case 0: this.moveState.forward = 0; break;
				case 2: this.moveState.back = 0; break;

			}

			this.updateMovementVector();

		}

		this.updateRotationVector();

	};

	this.update = function( delta ) {

		var moveMult = delta * this.movementSpeed;
		var rotMult = delta * this.rollSpeed;

		this.object.translateX( this.moveVector.x * moveMult );
		this.object.translateY( this.moveVector.y * moveMult );
		this.object.translateZ( this.moveVector.z * moveMult );

		this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
		this.object.quaternion.multiply( this.tmpQuaternion );

		// expose the rotation vector for convenience
		this.object.rotation.setEulerFromQuaternion( this.object.quaternion, this.object.eulerOrder );

	};

	this.updateMovementVector = function() {

		var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;

		this.moveVector.x = ( -this.moveState.left    + this.moveState.right );
		this.moveVector.y = ( -this.moveState.down    + this.moveState.up );
		this.moveVector.z = ( -forward + this.moveState.back );

		//console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );

	};

	this.updateRotationVector = function() {

		this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
		this.rotationVector.y = ( -this.moveState.yawRight  + this.moveState.yawLeft );
		this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );

		//console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );

	};

	this.getContainerDimensions = function() {

		if ( this.domElement != document ) {

			return {
				size	: [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
				offset	: [ this.domElement.offsetLeft,  this.domElement.offsetTop ]
			};

		} else {

			return {
				size	: [ window.innerWidth, window.innerHeight ],
				offset	: [ 0, 0 ]
			};

		}

	};

	function bind( scope, fn ) {

		return function () {

			fn.apply( scope, arguments );

		};

	};

	this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

	this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
	this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
	this.domElement.addEventListener( 'mouseup',   bind( this, this.mouseup ), false );

	this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
	this.domElement.addEventListener( 'keyup',   bind( this, this.keyup ), false );

	this.updateMovementVector();
	this.updateRotationVector();

};
<|endoftext|>


<commit_before>class SiteInterface extends Interface {
    showDropdown(msg) {
        dropDowns.push($("

"));
		var currentBox = dropDowns[dropDowns.length - 1];
		currentBox.toggle();
		$("#dropdowns").prepend(currentBox);
		$("#dropdowns").prepend("
");
		currentBox.text(msg);
		currentBox.slideDown({duration: 500});
		setTimeout(() => {
			currentBox.slideUp({duration: 500});
		}, 4000);
    }
    showAlert(msg) {
        $("#alert-box").fadeIn(200);
        $("#overlay").fadeIn(300);
        $("#alert-msg").text(msg);
        $("#alert-msg")[0].innerHTML =  $("#alert-msg")[0].innerHTML.replace('\n', '
');
    }
    showLoading() {
        $("#overlay").fadeIn(200);
        $("#loading").fadeIn(300);
    }
    hideLoading() {
        $("#overlay").fadeOut(200);
        $("#loading").fadeOut(300);
    }
    onQuestionStart() {
        console.debug('Question started');
        $("#loading-area").fadeOut(250);
        $("#playing-area").fadeIn(250);
        this.parent.playingArea.style.opacity = 1;
        this.parent.showDropdown("Question started.");
    }
    onQuestionSubmit() {
        this.parent.showDropdown("Question submitted!");
        this.parent.playingArea.style.opacity = 0.4;
    }
    onQuestionEnd() {
        this.parent.showDropdown("The question has ended.");
    }
    handleAnswer(me, e) {
        var ans = null;
        switch (e.target.id) {
            case "ans0":
                ans = 0;
                break;
            case "ans1":
                ans = 1;
                break;
            case "ans2":
                ans = 2;
                break;
            case "ans3":
                ans = 3;
                break;
        }
        me.events.onAnswer.call(me, ans);
    }
    onJoin() {
        var me = this;
        // Call the original onJoin
        InterfaceEvents.onJoin
        .call(me.events).then(() => {
            $(me.joinArea).fadeOut(250);
            $(me.waitingArea).fadeIn(250);
            ukahoot.isWaiting = true;
            var pulse = false;
            var waitInterval = setInterval(() => { // Make the waiting text 'glow'
                if (ukahoot.isWaiting) {
                    if (pulse) {
                        me.waitText.style.opacity = 1;
                    } else {
                        me.waitText.style.opacity = 0.5;
                    }
                    pulse = !pulse;
                } else {
                    clearInterval(waitInterval);
                    return;
                }
            }, 750);
        }).catch(e => {
            if (e == "The maximum amount of clients allowed is 67.") {
                return me.showAlert(e);
            } else {
                me.showAlert("There was an issue joining.");
                console.error(e);
                return;
            }
        });
    }
    onJoinGame(pid) {
        var me = this;
        InterfaceEvents.onJoinGame
        .call(me.events, pid).then(token => {
            $(start).fadeOut(300);
            setTimeout(() => {
                $(me.joinArea).fadeIn(300);
            }, 300);
        }).catch(() => {
            me.hideLoading();
            setTimeout(() => {
                me.showAlert("There was an error requesting for the session token.\nMake sure you are using the correct PIN.");
                console.error(err);
            }, 500);
        });
    }
    onQuizEnd() {
        this.parent.showAlert("The Kahoot has ended.");
    }
    init() {
        var me = this;
        me.joinGameButton = document.getElementById('join');
        me.joinButton = document.getElementById('join-game');
        me.pidBox = document.getElementById("pid");
        me.playingArea = document.getElementById("playing-area");
        me.events.onJoinGame = me.onJoinGame;
        me.events.onJoin = me.onJoin;
        me.events.onQuizEnd = me.onQuizEnd;
        me.events.onQuestionStart = me.onQuestionStart;
        me.events.onQuestionSubmit = me.onQuestionSubmit;
        me.events.onQuestionEnd = me.onQuestionEnd;

        $(".ans").click(e => {
            me.handleAnswer.call(this, me, e);
        });
        me.joinGameButton.addEventListener('click', () => {
            me.events.onJoinGame.call(me, me.pidBox.value);
        });
        me.joinButton.addEventListener('click', () => {
            me.events.onJoin.call(me);
        });

        var join     = document.getElementById('join');
        var alertBox = document.getElementById('alert-box');
        var alertOk  = document.getElementById('alert-ok');
        var alertMsg = document.getElementById('alert-msg');
        var overlay  = document.getElementById('overlay');
        var loading  = document.getElementById('loading');
        me.joinArea = document.getElementById('join-area');
        var start    = document.getElementById('start');
        var tooltip  = document.getElementById('help-tooltip');
        var tooltipArea = document.getElementById('tooltip-area');
        me.nameArea = document.getElementById('name-area');
        me.clientCountArea = document.getElementById('client-count-area');
        me.waitingArea = document.getElementById('waiting-area');
        me.waitText = document.getElementById('wait');
        var loadingArea = document.getElementById('loading-area');

        $("#title").toggle();
        $(".start-body").toggle();
        $("#dropdown-msg").toggle();
        $(".description").toggle();
        $(me.joinArea).toggle();
        $(tooltipArea).toggle();
        $(me.waitingArea).toggle();
        $(loadingArea).toggle();
        // Load animations
        $("#title").slideDown({duration: 500});
        setTimeout(() => {
            $(".description").fadeIn(500);
            setTimeout(() => {
                $(".start-body").fadeIn(300);
            }, 300);
        }, 300);
        alertOk.addEventListener('click', () => {
            $(alertBox).fadeOut(300);
            $(overlay).fadeOut(200);
        });
        tooltip.addEventListener('mouseenter', () => {
            $(tooltipArea).fadeIn(200);
        });
        tooltip.addEventListener('mouseleave', () => {
            $(tooltipArea).fadeOut(200);
        });
    }
    constructor() {
        super();
        var me = this;
        window.addEventListener('load', () => {
            me.init.call(me);
        });
    }
}<commit_msg>Change question submit text<commit_after>class SiteInterface extends Interface {
    showDropdown(msg) {
        dropDowns.push($("

"));
		var currentBox = dropDowns[dropDowns.length - 1];
		currentBox.toggle();
		$("#dropdowns").prepend(currentBox);
		$("#dropdowns").prepend("
");
		currentBox.text(msg);
		currentBox.slideDown({duration: 500});
		setTimeout(() => {
			currentBox.slideUp({duration: 500});
		}, 4000);
    }
    showAlert(msg) {
        $("#alert-box").fadeIn(200);
        $("#overlay").fadeIn(300);
        $("#alert-msg").text(msg);
        $("#alert-msg")[0].innerHTML =  $("#alert-msg")[0].innerHTML.replace('\n', '
');
    }
    showLoading() {
        $("#overlay").fadeIn(200);
        $("#loading").fadeIn(300);
    }
    hideLoading() {
        $("#overlay").fadeOut(200);
        $("#loading").fadeOut(300);
    }
    onQuestionStart() {
        console.debug('Question started');
        $("#loading-area").fadeOut(250);
        $("#playing-area").fadeIn(250);
        this.parent.playingArea.style.opacity = 1;
        this.parent.showDropdown("Question started.");
    }
    onQuestionSubmit() {
        this.parent.showDropdown("Your answer has been submitted!");
        this.parent.playingArea.style.opacity = 0.4;
    }
    onQuestionEnd() {
        this.parent.showDropdown("The question has ended.");
    }
    handleAnswer(me, e) {
        var ans = null;
        switch (e.target.id) {
            case "ans0":
                ans = 0;
                break;
            case "ans1":
                ans = 1;
                break;
            case "ans2":
                ans = 2;
                break;
            case "ans3":
                ans = 3;
                break;
        }
        me.events.onAnswer.call(me, ans);
    }
    onJoin() {
        var me = this;
        // Call the original onJoin
        InterfaceEvents.onJoin
        .call(me.events).then(() => {
            $(me.joinArea).fadeOut(250);
            $(me.waitingArea).fadeIn(250);
            ukahoot.isWaiting = true;
            var pulse = false;
            var waitInterval = setInterval(() => { // Make the waiting text 'glow'
                if (ukahoot.isWaiting) {
                    if (pulse) {
                        me.waitText.style.opacity = 1;
                    } else {
                        me.waitText.style.opacity = 0.5;
                    }
                    pulse = !pulse;
                } else {
                    clearInterval(waitInterval);
                    return;
                }
            }, 750);
        }).catch(e => {
            if (e == "The maximum amount of clients allowed is 67.") {
                return me.showAlert(e);
            } else {
                me.showAlert("There was an issue joining.");
                console.error(e);
                return;
            }
        });
    }
    onJoinGame(pid) {
        var me = this;
        InterfaceEvents.onJoinGame
        .call(me.events, pid).then(token => {
            $(start).fadeOut(300);
            setTimeout(() => {
                $(me.joinArea).fadeIn(300);
            }, 300);
        }).catch(() => {
            me.hideLoading();
            setTimeout(() => {
                me.showAlert("There was an error requesting for the session token.\nMake sure you are using the correct PIN.");
                console.error(err);
            }, 500);
        });
    }
    onQuizEnd() {
        this.parent.showAlert("The Kahoot has ended.");
    }
    init() {
        var me = this;
        me.joinGameButton = document.getElementById('join');
        me.joinButton = document.getElementById('join-game');
        me.pidBox = document.getElementById("pid");
        me.playingArea = document.getElementById("playing-area");
        me.events.onJoinGame = me.onJoinGame;
        me.events.onJoin = me.onJoin;
        me.events.onQuizEnd = me.onQuizEnd;
        me.events.onQuestionStart = me.onQuestionStart;
        me.events.onQuestionSubmit = me.onQuestionSubmit;
        me.events.onQuestionEnd = me.onQuestionEnd;

        $(".ans").click(e => {
            me.handleAnswer.call(this, me, e);
        });
        me.joinGameButton.addEventListener('click', () => {
            me.events.onJoinGame.call(me, me.pidBox.value);
        });
        me.joinButton.addEventListener('click', () => {
            me.events.onJoin.call(me);
        });

        var join     = document.getElementById('join');
        var alertBox = document.getElementById('alert-box');
        var alertOk  = document.getElementById('alert-ok');
        var alertMsg = document.getElementById('alert-msg');
        var overlay  = document.getElementById('overlay');
        var loading  = document.getElementById('loading');
        me.joinArea = document.getElementById('join-area');
        var start    = document.getElementById('start');
        var tooltip  = document.getElementById('help-tooltip');
        var tooltipArea = document.getElementById('tooltip-area');
        me.nameArea = document.getElementById('name-area');
        me.clientCountArea = document.getElementById('client-count-area');
        me.waitingArea = document.getElementById('waiting-area');
        me.waitText = document.getElementById('wait');
        var loadingArea = document.getElementById('loading-area');

        $("#title").toggle();
        $(".start-body").toggle();
        $("#dropdown-msg").toggle();
        $(".description").toggle();
        $(me.joinArea).toggle();
        $(tooltipArea).toggle();
        $(me.waitingArea).toggle();
        $(loadingArea).toggle();
        // Load animations
        $("#title").slideDown({duration: 500});
        setTimeout(() => {
            $(".description").fadeIn(500);
            setTimeout(() => {
                $(".start-body").fadeIn(300);
            }, 300);
        }, 300);
        alertOk.addEventListener('click', () => {
            $(alertBox).fadeOut(300);
            $(overlay).fadeOut(200);
        });
        tooltip.addEventListener('mouseenter', () => {
            $(tooltipArea).fadeIn(200);
        });
        tooltip.addEventListener('mouseleave', () => {
            $(tooltipArea).fadeOut(200);
        });
    }
    constructor() {
        super();
        var me = this;
        window.addEventListener('load', () => {
            me.init.call(me);
        });
    }
}<|endoftext|>


<commit_before>'use strict';

// JSON result comparison tests to be run by NodeJS/JSDOM test runner
var jsonTests = {
  reviews: retrieveReviews
};

if (typeof init === 'undefined')
  var init = false;

// For execution in browser
if (typeof chrome !== 'undefined' && !init)
  setupExtensionEvents();

  function setupExtensionEvents() {
  chrome.runtime.onMessage.addListener(request => {
    if (request.action == 'retrieve') {
      if (!loggedIn()) {
        chrome.runtime.sendMessage({
          action: 'notice-login'
        });
        return false;
      }
      let datasets = {};
      datasets.schemaKey = request.schema.schema.key;
      datasets.schemaVersion = request.schema.schema.version;
      retrieveReviews(reviews => {
        datasets.reviews = new DataSet(reviews, request.schema.reviews).set;
        chrome.runtime.sendMessage({
          action: 'dispatch',
          data: datasets,
          schema: request.schema
        });
      });
    }
  });
  // Prevent repeated initialization
  init = true;
}

function loggedIn() {
  return Boolean($('.user-account .user-display-name').html());
}

function retrieveReviews(callback) {
  let page = 1;
  let reviews = {
    head: {},
    data: []
  };
  let firstURL = 'https://www.yelp.com/user_details_reviews_self';
  $.get(firstURL).done(processPage);

  function processPage(html) {
    let dom = $.parseHTML(html);
    if (page === 1) {
      let idLink = $(dom).find('.user-display-name');
      reviews.head.reviewerName = idLink.text();

      let idMatch;
      if ((idMatch = idLink.attr('href').match(/userid=(.*)/)))
        reviews.head.reviewerID = idMatch[1];
    }
    // Parse contents
    $(dom).find('div.review').each((i, e) => {
      let text = $(e).find('.review-content p').first().html();
      let subject = $(e).find('.biz-name').text();
      let subjectYelpURL = 'http://yelp.com' + $(e).find('.biz-name').attr('href');
      let date = $(e).find('.rating-qualifier').text().trim(); // TODO: other qualifiers

      let starRatingClass = $(e).find("[class^='star-img stars_']").attr('class');

      let starRatingMatch, starRating;
      if ((starRatingMatch = starRatingClass.match(/[0-9]/)))
        starRating = starRatingMatch[0];

      let checkins = $(e).find("[class$='checkin_c-common_sprite-wrap review-tag']")
        .text().match(/\d+/);

      let reviewObj = {
        subject,
        subjectYelpURL,
        date,
        text,
        starRating
      };
      if (checkins)
        reviewObj.checkins = checkins;

      reviews.data.push(reviewObj);
    });

    let nextURL = $(dom).find('.pagination-links .next').attr('href');
    if (nextURL) {
      page++;
      // Obtain and relay progress info
      let totalPageMatch, totalPages;
      if ((totalPageMatch = $(dom).find('.page-of-pages').text().match(/\d+.*?(\d+)/)))
        totalPages = totalPageMatch[1];
      plugin.report(`Fetching page ${page} of ${totalPages} …`);
      // Fetch next page
      $.get(nextURL).done(processPage);
    } else {
      callback(reviews);
    }
  }
}
<commit_msg>whitespace<commit_after>'use strict';

// JSON result comparison tests to be run by NodeJS/JSDOM test runner
var jsonTests = {
  reviews: retrieveReviews
};

if (typeof init === 'undefined')
  var init = false;

// For execution in browser
if (typeof chrome !== 'undefined' && !init)
  setupExtensionEvents();

function setupExtensionEvents() {
  chrome.runtime.onMessage.addListener(request => {
    if (request.action == 'retrieve') {
      if (!loggedIn()) {
        chrome.runtime.sendMessage({
          action: 'notice-login'
        });
        return false;
      }
      let datasets = {};
      datasets.schemaKey = request.schema.schema.key;
      datasets.schemaVersion = request.schema.schema.version;
      retrieveReviews(reviews => {
        datasets.reviews = new DataSet(reviews, request.schema.reviews).set;
        chrome.runtime.sendMessage({
          action: 'dispatch',
          data: datasets,
          schema: request.schema
        });
      });
    }
  });
  // Prevent repeated initialization
  init = true;
}

function loggedIn() {
  return Boolean($('.user-account .user-display-name').html());
}

function retrieveReviews(callback) {
  let page = 1;
  let reviews = {
    head: {},
    data: []
  };
  let firstURL = 'https://www.yelp.com/user_details_reviews_self';
  $.get(firstURL).done(processPage);

  function processPage(html) {
    let dom = $.parseHTML(html);
    if (page === 1) {
      let idLink = $(dom).find('.user-display-name');
      reviews.head.reviewerName = idLink.text();

      let idMatch;
      if ((idMatch = idLink.attr('href').match(/userid=(.*)/)))
        reviews.head.reviewerID = idMatch[1];
    }
    // Parse contents
    $(dom).find('div.review').each((i, e) => {
      let text = $(e).find('.review-content p').first().html();
      let subject = $(e).find('.biz-name').text();
      let subjectYelpURL = 'http://yelp.com' + $(e).find('.biz-name').attr('href');
      let date = $(e).find('.rating-qualifier').text().trim(); // TODO: other qualifiers

      let starRatingClass = $(e).find("[class^='star-img stars_']").attr('class');

      let starRatingMatch, starRating;
      if ((starRatingMatch = starRatingClass.match(/[0-9]/)))
        starRating = starRatingMatch[0];

      let checkins = $(e).find("[class$='checkin_c-common_sprite-wrap review-tag']")
        .text().match(/\d+/);

      let reviewObj = {
        subject,
        subjectYelpURL,
        date,
        text,
        starRating
      };
      if (checkins)
        reviewObj.checkins = checkins;

      reviews.data.push(reviewObj);
    });

    let nextURL = $(dom).find('.pagination-links .next').attr('href');
    if (nextURL) {
      page++;
      // Obtain and relay progress info
      let totalPageMatch, totalPages;
      if ((totalPageMatch = $(dom).find('.page-of-pages').text().match(/\d+.*?(\d+)/)))
        totalPages = totalPageMatch[1];
      plugin.report(`Fetching page ${page} of ${totalPages} …`);
      // Fetch next page
      $.get(nextURL).done(processPage);
    } else {
      callback(reviews);
    }
  }
}
<|endoftext|>


<commit_before>var canvas = document.getElementById('canvas')
  , cx = canvas.getContext('2d')
  , utils = require('utils')(cx, canvas)
  , Vector = require('vector2d')
;

var WIDTH = canvas.width
  , HEIGHT = canvas.height
;

var centerVec
  , mouseVec
  , mousePos
;

function setup() {
  console.log('setup');
  mousePos = {x: 0, y: 0};
  centerVec = new Vector.ObjectVector(WIDTH / 2, HEIGHT / 2);
	mouseVec = new Vector.ObjectVector(0, 0);
}

function draw() {
	utils.clear();

	var xPanning = WIDTH / 2;
	var yPanning = HEIGHT / 2;

	cx.translate(xPanning, yPanning);

	// set the mouseVector to the position of the mouse
	// modify the mousePos cords by the amount of the matrix
	// translation
	mouseVec.setX(mousePos.x - xPanning);
	mouseVec.setY(mousePos.y - yPanning);

	cx.beginPath();
	cx.moveTo(0, 0);
	cx.lineTo(mouseVec.getX(), mouseVec.getY());
	cx.stroke();

	cx.resetTransform();
  window.requestAnimationFrame(draw);
}

canvas.addEventListener('mousemove', function(event) {
  mousePos = utils.getMousePos(event);
});

(function() {
  setup();
  window.requestAnimationFrame(draw);
}());
<commit_msg>fixed and fisnied 1-3<commit_after>var canvas = document.getElementById('canvas')
  , cx = canvas.getContext('2d')
  , utils = require('utils')(cx, canvas)
  , Vector = require('vector2d')
;

var WIDTH = canvas.width
  , HEIGHT = canvas.height
;

var centerVec
  , mouseVec
  , mousePos
	, xPanning = WIDTH / 2
	, yPanning = HEIGHT / 2
;

function setup() {
  console.log('setup');
  mousePos = {x: 0, y: 0};
  centerVec = new Vector.ObjectVector(xPanning, yPanning);
	mouseVec = new Vector.ObjectVector(0, 0);
}

function draw() {
	utils.clear();

  mouseVec.setAxes(mousePos.x, mousePos.y);

  mouseVec.subtract(centerVec);

	cx.translate(xPanning, yPanning);

	cx.beginPath();
	cx.moveTo(0, 0);
	cx.lineTo(mouseVec.getX(), mouseVec.getY());
	cx.stroke();

	cx.resetTransform();
  window.requestAnimationFrame(draw);
}

canvas.addEventListener('mousemove', function(event) {
  mousePos = utils.getMousePos(event);
});

(function() {
  setup();
  window.requestAnimationFrame(draw);
}());
<|endoftext|>