<commit_before>var app_version = '1.0';
var app = {

    initialize: function() {
        this.bind();
    },

    bind: function() {
        document.addEventListener("deviceready", this.deviceready, false);
        document.addEventListener("backbutton", closeScan, false);
        //document.addEventListener("online", function(){alert('online');}, false);
        //document.addEventListener("offline", function(){alert('offline');}, false);
        $('#normal_bulk').on("filterablebeforefilter", bulk_keypress_cb);
        $('#normal_bulk').on("tap", "li", select_bulk_cb);
        $('#normal_layer').on("change", set_layer_cb);
        $('#normal_employee').on("tap", bc_pressed);
        $('#normal_operation').on("tap", bc_pressed);
        $('#normal_bt_submit').on("tap", normal_submit);

        $('#flagno_bulk').on("filterablebeforefilter", bulk_keypress_cb);
        $('#flagno_bulk').on("tap", "li", select_bulk_cb);
        $('#flagno_employee').on("tap", bc_pressed);
        $('#flagno_bt_submit').on("tap", flagno_submit);
        $('#flagno_hours_container').on("slidestop", '#flagno_hours', hours_flagno_select);
        $('#flagno_minutes_container').on("slidestop", '#flagno_minutes', minutes_flagno_select);
    },

    deviceready: function() {
        app.start();
    },

    start: function() {
        //alert('application started...');
    }
};

var normal_data = {};
var flagno_data = {};
var scan_in_progress = false;
var base_url = 'http://192.168.1.1'; // 192.168.0.11
var post_url = base_url+'/supervisor_input_b.php';
var get_operations = base_url+'/supervisor_getoperations.php';
var get_flagno_operations = base_url+'/supervisor_getoperations_flagno.php';
var get_bulks = base_url+'/supervisor_getbulks.php';

function is_wifi_enable(){
/*
    var networkState = navigator.connection.type;
    return (networkState == Connection.WIFI);
*/
return true;
}

function bc_pressed(){
    var elem_id = $(this).attr('id');
    if(elem_id == 'normal_employee' || elem_id == 'normal_operation'){
        startScan(elem_id.split('_')[1],'normal');
    } else if(elem_id == 'flagno_employee'){
        startScan(elem_id.split('_')[1],'flagno');
    }
}

function date_select(page){
    /* callback for date select event */
    if(page == 'normal'){
        normal_data['date']=$('#normal_scan_date').val();
    } else if(page == 'flagno'){
        flagno_data['date']=$('#flagno_scan_date').val();
    }
    check_params();
}

function bulk_keypress_cb(e, data){
    var $ul = $( this ),
        $input = $( data.input ),
        value = $input.val(),
        html = "";
    $ul.html( "" );
    //console.log(value);
    if ( value && value.length > 0 ) {
        //console.log('performing ajax call');
        $ul.html( "

" );
        $ul.listview( "refresh" );
        if($.mobile.activePage.attr('id') == 'normal'){
            normal_data['bulk'] = value;
        } else {
            flagno_data['bulk'] = value;
        }
        $.post(get_bulks,{'bulk':value},function(response){
            $.each( response, function ( i, val ) {
                html += "
" + val + "
";
            });
            $ul.html( html );
            $ul.listview( "refresh" );
            $ul.trigger( "updatelayout");
            //console.log(html);
        },'json');
    }
    check_params();
}

function select_bulk_cb(){
    var text = $(this).text();
    //console.log(text);
    $(this).closest("ul").prev("form").find("input").val(text);
    $(this).closest("ul").empty();
    if($.mobile.activePage.attr('id') == 'normal'){
        normal_data['bulk'] = text;
        fill_manual_operation(text);
    } else {
        flagno_data['bulk'] = text;
    }
    check_params();
}

function set_layer_cb(event){
    normal_data['layer'] = event.currentTarget.value;
    check_params();
}

function hours_flagno_select(){
    /* callback for onchange on flagno hours */
    flagno_data['tot_ore_flag_no'] = $('#flagno_hours').val();
    check_params();
}

function minutes_flagno_select(){
    /* callback for onchange on flagno minutes */
    flagno_data['tot_min_flag_no'] = $('#flagno_minutes').val();
    check_params();
}

function operation_flagno_select(elem){
    /* callback for onchange on flagno operation field */
    flagno_data['operation'] = elem.value;
    check_params();
}

function operation_manual_select(elem){
    /* callback for onchange on operation manual */
    normal_data['operation'] = elem.value;
    $('#normal_operation').val(elem.value);
    check_params();
}

function fill_manual_operation(bulk){
    /* get all operation for a bulk and enable select control */
    $.post(get_operations,{'bulk':bulk},function(operations){
        $('#normal_manual_operation').empty().append('<option>Select Operation (for bulk)</option>');
        $.each(operations, function(k,v){
            var opt = '<option value="' +k+ '">'+k+' - '+v+'</option>';
            $('#normal_manual_operation').append(opt);
        });
        $('#normal_manual_operation').selectmenu('refresh',true).selectmenu('enable');
        check_params();
    },'json');
}

function fill_flagno_operations(){
    /* get all flagno operation */
    $.post(get_flagno_operations,function(operations){
        $('#flagno_operation').empty().append('<option>Select Operation</option>');
        $.each(operations, function(k,v){
            var opt = '<option value="' +k+ '">'+k+' - '+v+'</option>';
            $('#flagno_operation').append(opt);
        });
        $('#flagno_operation').selectmenu('refresh',true).selectmenu('enable');
        check_params();
    },'json');
}

function closeScan(){
    /* this is an hack to prevent exiting from the application when
       someone clicks on back button during when the scanner is active */
    if(scan_in_progress){
        alert('Scan cancelled');
    }
}

function check_params(){
    /* Check if all params are correctly set and enable the submit button*/
    /* normal page */
    if(normal_data['date']!='' &&
        normal_data['bulk']!='' &&
        normal_data['operation']!='' &&
        normal_data['employee']!='' &&
        normal_data['layer']!=''){
        $('#normal_bt_submit').removeClass('ui-disabled');
    } else {
        $('#normal_bt_submit').addClass('ui-disabled');
    }

    /* flagno page */
    if(flagno_data['date']!='' &&
        flagno_data['employee']!='' &&
        flagno_data['bulk']!='' &&
        flagno_data['operation']!='' &&
        !(flagno_data['tot_ore_flag_no']=='0' && flagno_data['tot_min_flag_no']=='0'))
    {
        //console.log('ALLOW',flagno_data);
        $('#flagno_bt_submit').removeClass('ui-disabled');
    } else {
        //console.log('DISALLOW',flagno_data);
        $('#flagno_bt_submit').addClass('ui-disabled');
    }
}

function reset_fields(){
    /* reset all fields at app startup and after every submit */
    var d = new Date();
    normal_data = {};
    flagno_data = {};

    /* normal page */
    $('#normal_bt_submit').addClass('ui-disabled');
    $('#normal_employee').val('');
    $('#normal_bulk').val(''); // TODO: comment it!
    $('#normal_manual_operation').selectmenu('disable').empty();
    $('#normal_operation').val('');
    $('#normal_layer').val('1');
    $('#normal_scan_date').val(d.toISOString().split('T')[0]);
    normal_data['date']=$('#normal_scan_date').val();
    normal_data['employee']='';
    normal_data['bulk']='';
    normal_data['operation']='';
    normal_data['layer']='1';
    normal_data['id_device'] = window.localStorage.getItem('id_device');

    /* flag no page */
    $('#flagno_bt_submit').addClass('ui-disabled');
    $('#flagno_employee').val('');
    $('#flagno_bulk').val('');
    $('#flagno_operation').val('');
    $('#flagno_scan_date').val(d.toISOString().split('T')[0]);
    $('#flagno_hours').val('0');
    $('#flagno_minutes').val('0');
    flagno_data['date']=$('#flagno_scan_date').val();
    flagno_data['employee']='';
    flagno_data['bulk']='';
    flagno_data['operation']='';
    flagno_data['tot_ore_flag_no']='0';
    flagno_data['tot_min_flag_no']='0';
    flagno_data['id_device'] = window.localStorage.getItem('id_device');
}

function normal_submit(){
    /* here we have to subm it the data to the server */
    if(!is_wifi_enable()){
        alert('wifi connection is not enable');
        return false;
    }
    $.mobile.loading('show');
    $.post(post_url,normal_data,function(data){
        if(data.OK != undefined && data.OK != ''){
            alert(data.OK);
            $.mobile.loading('hide');
            reset_fields();
        }else{
            alert(data.ERR);
            $.mobile.loading('hide');
        }
    },'json')
    .fail(function(){
        alert('Communication error!');
        $.mobile.loading('hide');
    });
}

function flagno_submit(){
    /* here we have to subm it the data to the server */
    if(!is_wifi_enable()){
        alert('wifi connection is not enable');
        return false;
    }
    $.mobile.loading('show');
    $.post(post_url,flagno_data,function(data){
        if(data.OK != undefined && data.OK != ''){
            alert(data.OK);
            $.mobile.loading('hide');
            reset_fields();
        }else{
            alert(data.ERR);
            $.mobile.loading('hide');
        }
    },'json')
    .fail(function(){
        alert('Communication error!');
        $.mobile.loading('hide');
    });
}

function quit(){
    navigator.app.exitApp();
}

function startScan(elem, page) {
    if(typeof cordova==='undefined'){
        if(page == 'normal'){
            normal_data[elem] = 'testvalue';
            $('#normal_'+elem).val('testvalue');
        } else if(page == 'flagno'){
            flagno_data[elem] = 'testvalue';
            $('#flagno_'+elem).val('testvalue');
        }
        check_params();
        return true;
    }
    scan_in_progress = true;
    $.mobile.loading('show');
    cordova.plugins.barcodeScanner.scan(
    function (result) {
        var s = "Result: " + result.text + "
" +
            "Format: " + result.format + "
" +
            "Cancelled: " + result.cancelled;
        if(!result.cancelled){
            if(page == 'normal'){
                normal_data[elem] = result.text;
                $('#normal_'+elem).val(result.text);
            } else if(page == 'flagno'){
                flagno_data[elem] = result.text;
                $('#flagno_'+elem).val(result.text);
            }
            scan_in_progress = false;
        }
        check_params();
        $.mobile.loading('hide');
    },
    function (error) {
        alert("Scanning failed: " + error);
        scan_in_progress = false;
        $.mobile.loading('hide');
    });
}

function save_id_device(){
    var id_device = $('#id_device').val();
    if(id_device != ''){
        window.localStorage.setItem('id_device',id_device);
        $('.id_device').text(' - '+id_device);
        $("body").pagecontainer("change", "#normal", {
            transition: 'slidedown',
            reload    : true
        });
    }
}

$(document).on('pageinit','#normal',function(){
    $('#version').append(app_version);
    var id_device = window.localStorage.getItem('id_device');
    if(id_device==null){
        $("body").pagecontainer("change", "#line_input", {
            transition: 'slidedown',
            reload    : true
        });
    }
    $('.id_device').text(' - '+id_device);
    /* this is needed only to have a better graphic for input text fields */
    $('.ui-input-text').removeClass('ui-state-disabled');
    reset_fields();
    app.initialize();
});

$(document).on('pageinit','#flagno',function(){
    /* this is needed only to have a better graphic for input text fields */
    $('.ui-input-text').removeClass('ui-state-disabled');
    fill_flagno_operations();
});
<commit_msg>change remote address<commit_after>var app_version = '1.0';
var app = {

    initialize: function() {
        this.bind();
    },

    bind: function() {
        document.addEventListener("deviceready", this.deviceready, false);
        document.addEventListener("backbutton", closeScan, false);
        //document.addEventListener("online", function(){alert('online');}, false);
        //document.addEventListener("offline", function(){alert('offline');}, false);
        $('#normal_bulk').on("filterablebeforefilter", bulk_keypress_cb);
        $('#normal_bulk').on("tap", "li", select_bulk_cb);
        $('#normal_layer').on("change", set_layer_cb);
        $('#normal_employee').on("tap", bc_pressed);
        $('#normal_operation').on("tap", bc_pressed);
        $('#normal_bt_submit').on("tap", normal_submit);

        $('#flagno_bulk').on("filterablebeforefilter", bulk_keypress_cb);
        $('#flagno_bulk').on("tap", "li", select_bulk_cb);
        $('#flagno_employee').on("tap", bc_pressed);
        $('#flagno_bt_submit').on("tap", flagno_submit);
        $('#flagno_hours_container').on("slidestop", '#flagno_hours', hours_flagno_select);
        $('#flagno_minutes_container').on("slidestop", '#flagno_minutes', minutes_flagno_select);
    },

    deviceready: function() {
        app.start();
    },

    start: function() {
        //alert('application started...');
    }
};

var normal_data = {};
var flagno_data = {};
var scan_in_progress = false;
// var base_url = 'http://192.168.1.1';
var base_url = 'http://192.168.0.11';
var post_url = base_url+'/supervisor_input_b.php';
var get_operations = base_url+'/supervisor_getoperations.php';
var get_flagno_operations = base_url+'/supervisor_getoperations_flagno.php';
var get_bulks = base_url+'/supervisor_getbulks.php';

function is_wifi_enable(){
/*
    var networkState = navigator.connection.type;
    return (networkState == Connection.WIFI);
*/
return true;
}

function bc_pressed(){
    var elem_id = $(this).attr('id');
    if(elem_id == 'normal_employee' || elem_id == 'normal_operation'){
        startScan(elem_id.split('_')[1],'normal');
    } else if(elem_id == 'flagno_employee'){
        startScan(elem_id.split('_')[1],'flagno');
    }
}

function date_select(page){
    /* callback for date select event */
    if(page == 'normal'){
        normal_data['date']=$('#normal_scan_date').val();
    } else if(page == 'flagno'){
        flagno_data['date']=$('#flagno_scan_date').val();
    }
    check_params();
}

function bulk_keypress_cb(e, data){
    var $ul = $( this ),
        $input = $( data.input ),
        value = $input.val(),
        html = "";
    $ul.html( "" );
    //console.log(value);
    if ( value && value.length > 0 ) {
        //console.log('performing ajax call');
        $ul.html( "

" );
        $ul.listview( "refresh" );
        if($.mobile.activePage.attr('id') == 'normal'){
            normal_data['bulk'] = value;
        } else {
            flagno_data['bulk'] = value;
        }
        $.post(get_bulks,{'bulk':value},function(response){
            $.each( response, function ( i, val ) {
                html += "
" + val + "
";
            });
            $ul.html( html );
            $ul.listview( "refresh" );
            $ul.trigger( "updatelayout");
            //console.log(html);
        },'json');
    }
    check_params();
}

function select_bulk_cb(){
    var text = $(this).text();
    //console.log(text);
    $(this).closest("ul").prev("form").find("input").val(text);
    $(this).closest("ul").empty();
    if($.mobile.activePage.attr('id') == 'normal'){
        normal_data['bulk'] = text;
        fill_manual_operation(text);
    } else {
        flagno_data['bulk'] = text;
    }
    check_params();
}

function set_layer_cb(event){
    normal_data['layer'] = event.currentTarget.value;
    check_params();
}

function hours_flagno_select(){
    /* callback for onchange on flagno hours */
    flagno_data['tot_ore_flag_no'] = $('#flagno_hours').val();
    check_params();
}

function minutes_flagno_select(){
    /* callback for onchange on flagno minutes */
    flagno_data['tot_min_flag_no'] = $('#flagno_minutes').val();
    check_params();
}

function operation_flagno_select(elem){
    /* callback for onchange on flagno operation field */
    flagno_data['operation'] = elem.value;
    check_params();
}

function operation_manual_select(elem){
    /* callback for onchange on operation manual */
    normal_data['operation'] = elem.value;
    $('#normal_operation').val(elem.value);
    check_params();
}

function fill_manual_operation(bulk){
    /* get all operation for a bulk and enable select control */
    $.post(get_operations,{'bulk':bulk},function(operations){
        $('#normal_manual_operation').empty().append('<option>Select Operation (for bulk)</option>');
        $.each(operations, function(k,v){
            var opt = '<option value="' +k+ '">'+k+' - '+v+'</option>';
            $('#normal_manual_operation').append(opt);
        });
        $('#normal_manual_operation').selectmenu('refresh',true).selectmenu('enable');
        check_params();
    },'json');
}

function fill_flagno_operations(){
    /* get all flagno operation */
    $.post(get_flagno_operations,function(operations){
        $('#flagno_operation').empty().append('<option>Select Operation</option>');
        $.each(operations, function(k,v){
            var opt = '<option value="' +k+ '">'+k+' - '+v+'</option>';
            $('#flagno_operation').append(opt);
        });
        $('#flagno_operation').selectmenu('refresh',true).selectmenu('enable');
        check_params();
    },'json');
}

function closeScan(){
    /* this is an hack to prevent exiting from the application when
       someone clicks on back button during when the scanner is active */
    if(scan_in_progress){
        alert('Scan cancelled');
    }
}

function check_params(){
    /* Check if all params are correctly set and enable the submit button*/
    /* normal page */
    if(normal_data['date']!='' &&
        normal_data['bulk']!='' &&
        normal_data['operation']!='' &&
        normal_data['employee']!='' &&
        normal_data['layer']!=''){
        $('#normal_bt_submit').removeClass('ui-disabled');
    } else {
        $('#normal_bt_submit').addClass('ui-disabled');
    }

    /* flagno page */
    if(flagno_data['date']!='' &&
        flagno_data['employee']!='' &&
        flagno_data['bulk']!='' &&
        flagno_data['operation']!='' &&
        !(flagno_data['tot_ore_flag_no']=='0' && flagno_data['tot_min_flag_no']=='0'))
    {
        //console.log('ALLOW',flagno_data);
        $('#flagno_bt_submit').removeClass('ui-disabled');
    } else {
        //console.log('DISALLOW',flagno_data);
        $('#flagno_bt_submit').addClass('ui-disabled');
    }
}

function reset_fields(){
    /* reset all fields at app startup and after every submit */
    var d = new Date();
    normal_data = {};
    flagno_data = {};

    /* normal page */
    $('#normal_bt_submit').addClass('ui-disabled');
    $('#normal_employee').val('');
    $('#normal_bulk').val(''); // TODO: comment it!
    $('#normal_manual_operation').selectmenu('disable').empty();
    $('#normal_operation').val('');
    $('#normal_layer').val('1');
    $('#normal_scan_date').val(d.toISOString().split('T')[0]);
    normal_data['date']=$('#normal_scan_date').val();
    normal_data['employee']='';
    normal_data['bulk']='';
    normal_data['operation']='';
    normal_data['layer']='1';
    normal_data['id_device'] = window.localStorage.getItem('id_device');

    /* flag no page */
    $('#flagno_bt_submit').addClass('ui-disabled');
    $('#flagno_employee').val('');
    $('#flagno_bulk').val('');
    $('#flagno_operation').val('');
    $('#flagno_scan_date').val(d.toISOString().split('T')[0]);
    $('#flagno_hours').val('0');
    $('#flagno_minutes').val('0');
    flagno_data['date']=$('#flagno_scan_date').val();
    flagno_data['employee']='';
    flagno_data['bulk']='';
    flagno_data['operation']='';
    flagno_data['tot_ore_flag_no']='0';
    flagno_data['tot_min_flag_no']='0';
    flagno_data['id_device'] = window.localStorage.getItem('id_device');
}

function normal_submit(){
    /* here we have to subm it the data to the server */
    if(!is_wifi_enable()){
        alert('wifi connection is not enable');
        return false;
    }
    $.mobile.loading('show');
    $.post(post_url,normal_data,function(data){
        if(data.OK != undefined && data.OK != ''){
            alert(data.OK);
            $.mobile.loading('hide');
            reset_fields();
        }else{
            alert(data.ERR);
            $.mobile.loading('hide');
        }
    },'json')
    .fail(function(){
        alert('Communication error!');
        $.mobile.loading('hide');
    });
}

function flagno_submit(){
    /* here we have to subm it the data to the server */
    if(!is_wifi_enable()){
        alert('wifi connection is not enable');
        return false;
    }
    $.mobile.loading('show');
    $.post(post_url,flagno_data,function(data){
        if(data.OK != undefined && data.OK != ''){
            alert(data.OK);
            $.mobile.loading('hide');
            reset_fields();
        }else{
            alert(data.ERR);
            $.mobile.loading('hide');
        }
    },'json')
    .fail(function(){
        alert('Communication error!');
        $.mobile.loading('hide');
    });
}

function quit(){
    navigator.app.exitApp();
}

function startScan(elem, page) {
    if(typeof cordova==='undefined'){
        if(page == 'normal'){
            normal_data[elem] = 'testvalue';
            $('#normal_'+elem).val('testvalue');
        } else if(page == 'flagno'){
            flagno_data[elem] = 'testvalue';
            $('#flagno_'+elem).val('testvalue');
        }
        check_params();
        return true;
    }
    scan_in_progress = true;
    $.mobile.loading('show');
    cordova.plugins.barcodeScanner.scan(
    function (result) {
        var s = "Result: " + result.text + "
" +
            "Format: " + result.format + "
" +
            "Cancelled: " + result.cancelled;
        if(!result.cancelled){
            if(page == 'normal'){
                normal_data[elem] = result.text;
                $('#normal_'+elem).val(result.text);
            } else if(page == 'flagno'){
                flagno_data[elem] = result.text;
                $('#flagno_'+elem).val(result.text);
            }
            scan_in_progress = false;
        }
        check_params();
        $.mobile.loading('hide');
    },
    function (error) {
        alert("Scanning failed: " + error);
        scan_in_progress = false;
        $.mobile.loading('hide');
    });
}

function save_id_device(){
    var id_device = $('#id_device').val();
    if(id_device != ''){
        window.localStorage.setItem('id_device',id_device);
        $('.id_device').text(' - '+id_device);
        $("body").pagecontainer("change", "#normal", {
            transition: 'slidedown',
            reload    : true
        });
    }
}

$(document).on('pageinit','#normal',function(){
    $('#version').append(app_version);
    var id_device = window.localStorage.getItem('id_device');
    if(id_device==null){
        $("body").pagecontainer("change", "#line_input", {
            transition: 'slidedown',
            reload    : true
        });
    }
    $('.id_device').text(' - '+id_device);
    /* this is needed only to have a better graphic for input text fields */
    $('.ui-input-text').removeClass('ui-state-disabled');
    reset_fields();
    app.initialize();
});

$(document).on('pageinit','#flagno',function(){
    /* this is needed only to have a better graphic for input text fields */
    $('.ui-input-text').removeClass('ui-state-disabled');
    fill_flagno_operations();
});
<|endoftext|>


<commit_before>import EmberArray from 'ember-runtime/mixins/array';
import EmberObject from 'ember-runtime/system/object';

// ........................................
// TYPING & ARRAY MESSAGING
//
var TYPE_MAP = {
  '[object Boolean]':  'boolean',
  '[object Number]':   'number',
  '[object String]':   'string',
  '[object Function]': 'function',
  '[object Array]':    'array',
  '[object Date]':     'date',
  '[object RegExp]':   'regexp',
  '[object Object]':   'object'
};

var toString = Object.prototype.toString;

/**
  Returns true if the passed object is an array or Array-like.

  Ember Array Protocol:

    - the object has an objectAt property
    - the object is a native Array
    - the object is an Object, and has a length property

  Unlike `Ember.typeOf` this method returns true even if the passed object is
  not formally array but appears to be array-like (i.e. implements `Ember.Array`)

  ```javascript
  Ember.isArray();                                          // false
  Ember.isArray([]);                                        // true
  Ember.isArray(Ember.ArrayProxy.create({ content: [] }));  // true
  ```

  @method isArray
  @for Ember
  @param {Object} obj The object to test
  @return {Boolean} true if the passed object is an array or Array-like
  @public
*/
export function isArray(obj) {
  if (!obj || obj.setInterval) { return false; }
  if (Array.isArray(obj)) { return true; }
  if (EmberArray.detect(obj)) { return true; }

  let type = typeOf(obj);
  if ('array' === type) { return true; }
  if ((obj.length !== undefined) && 'object' === type) { return true; }
  return false;
}

/**
  Returns a consistent type for the passed item.

  Use this instead of the built-in `typeof` to get the type of an item.
  It will return the same result across all browsers and includes a bit
  more detail. Here is what will be returned:

      | Return Value  | Meaning                                              |
      |---------------|------------------------------------------------------|
      | 'string'      | String primitive or String object.                   |
      | 'number'      | Number primitive or Number object.                   |
      | 'boolean'     | Boolean primitive or Boolean object.                 |
      | 'null'        | Null value                                           |
      | 'undefined'   | Undefined value                                      |
      | 'function'    | A function                                           |
      | 'array'       | An instance of Array                                 |
      | 'regexp'      | An instance of RegExp                                |
      | 'date'        | An instance of Date                                  |
      | 'class'       | An Ember class (created using Ember.Object.extend()) |
      | 'instance'    | An Ember object instance                             |
      | 'error'       | An instance of the Error object                      |
      | 'object'      | A JavaScript object not inheriting from Ember.Object |

  Examples:

  ```javascript
  Ember.typeOf();                       // 'undefined'
  Ember.typeOf(null);                   // 'null'
  Ember.typeOf(undefined);              // 'undefined'
  Ember.typeOf('michael');              // 'string'
  Ember.typeOf(new String('michael'));  // 'string'
  Ember.typeOf(101);                    // 'number'
  Ember.typeOf(new Number(101));        // 'number'
  Ember.typeOf(true);                   // 'boolean'
  Ember.typeOf(new Boolean(true));      // 'boolean'
  Ember.typeOf(Ember.makeArray);        // 'function'
  Ember.typeOf([1, 2, 90]);             // 'array'
  Ember.typeOf(/abc/);                  // 'regexp'
  Ember.typeOf(new Date());             // 'date'
  Ember.typeOf(Ember.Object.extend());  // 'class'
  Ember.typeOf(Ember.Object.create());  // 'instance'
  Ember.typeOf(new Error('teamocil'));  // 'error'

  // 'normal' JavaScript object
  Ember.typeOf({ a: 'b' });             // 'object'
  ```

  @method typeOf
  @for Ember
  @param {Object} item the item to check
  @return {String} the type
  @public
*/
export function typeOf(item) {
  if (item === null) { return 'null'; }
  if (item === undefined) { return 'undefined'; }
  var ret = TYPE_MAP[toString.call(item)] || 'object';

  if (ret === 'function') {
    if (EmberObject.detect(item)) {
      ret = 'class';
    }
  } else if (ret === 'object') {
    if (item instanceof Error) {
      ret = 'error';
    } else if (item instanceof EmberObject) {
      ret = 'instance';
    } else if (item instanceof Date) {
      ret = 'date';
    }
  }

  return ret;
}
<commit_msg>[BUGFIX release] Fix bug in utils.isArray wherein an object with a length property would be considered an array. <commit_after>import EmberArray from 'ember-runtime/mixins/array';
import EmberObject from 'ember-runtime/system/object';

// ........................................
// TYPING & ARRAY MESSAGING
//
var TYPE_MAP = {
  '[object Boolean]':  'boolean',
  '[object Number]':   'number',
  '[object String]':   'string',
  '[object Function]': 'function',
  '[object Array]':    'array',
  '[object Date]':     'date',
  '[object RegExp]':   'regexp',
  '[object Object]':   'object'
};

var toString = Object.prototype.toString;

/**
  Returns true if the passed object is an array or Array-like.

  Ember Array Protocol:

    - the object has an objectAt property
    - the object is a native Array
    - the object is an Object, and has a length property

  Unlike `Ember.typeOf` this method returns true even if the passed object is
  not formally array but appears to be array-like (i.e. implements `Ember.Array`)

  ```javascript
  Ember.isArray();                                          // false
  Ember.isArray([]);                                        // true
  Ember.isArray(Ember.ArrayProxy.create({ content: [] }));  // true
  ```

  @method isArray
  @for Ember
  @param {Object} obj The object to test
  @return {Boolean} true if the passed object is an array or Array-like
  @public
*/
export function isArray(obj) {
  if (!obj || obj.setInterval) { return false; }
  if (Array.isArray(obj)) { return true; }
  if (EmberArray.detect(obj)) { return true; }

  let type = typeOf(obj);
  if ('array' === type) { return true; }
  if (!isNaN(obj.length) && 'object' === type) { return true; }
  return false;
}

/**
  Returns a consistent type for the passed item.

  Use this instead of the built-in `typeof` to get the type of an item.
  It will return the same result across all browsers and includes a bit
  more detail. Here is what will be returned:

      | Return Value  | Meaning                                              |
      |---------------|------------------------------------------------------|
      | 'string'      | String primitive or String object.                   |
      | 'number'      | Number primitive or Number object.                   |
      | 'boolean'     | Boolean primitive or Boolean object.                 |
      | 'null'        | Null value                                           |
      | 'undefined'   | Undefined value                                      |
      | 'function'    | A function                                           |
      | 'array'       | An instance of Array                                 |
      | 'regexp'      | An instance of RegExp                                |
      | 'date'        | An instance of Date                                  |
      | 'class'       | An Ember class (created using Ember.Object.extend()) |
      | 'instance'    | An Ember object instance                             |
      | 'error'       | An instance of the Error object                      |
      | 'object'      | A JavaScript object not inheriting from Ember.Object |

  Examples:

  ```javascript
  Ember.typeOf();                       // 'undefined'
  Ember.typeOf(null);                   // 'null'
  Ember.typeOf(undefined);              // 'undefined'
  Ember.typeOf('michael');              // 'string'
  Ember.typeOf(new String('michael'));  // 'string'
  Ember.typeOf(101);                    // 'number'
  Ember.typeOf(new Number(101));        // 'number'
  Ember.typeOf(true);                   // 'boolean'
  Ember.typeOf(new Boolean(true));      // 'boolean'
  Ember.typeOf(Ember.makeArray);        // 'function'
  Ember.typeOf([1, 2, 90]);             // 'array'
  Ember.typeOf(/abc/);                  // 'regexp'
  Ember.typeOf(new Date());             // 'date'
  Ember.typeOf(Ember.Object.extend());  // 'class'
  Ember.typeOf(Ember.Object.create());  // 'instance'
  Ember.typeOf(new Error('teamocil'));  // 'error'

  // 'normal' JavaScript object
  Ember.typeOf({ a: 'b' });             // 'object'
  ```

  @method typeOf
  @for Ember
  @param {Object} item the item to check
  @return {String} the type
  @public
*/
export function typeOf(item) {
  if (item === null) { return 'null'; }
  if (item === undefined) { return 'undefined'; }
  var ret = TYPE_MAP[toString.call(item)] || 'object';

  if (ret === 'function') {
    if (EmberObject.detect(item)) {
      ret = 'class';
    }
  } else if (ret === 'object') {
    if (item instanceof Error) {
      ret = 'error';
    } else if (item instanceof EmberObject) {
      ret = 'instance';
    } else if (item instanceof Date) {
      ret = 'date';
    }
  }

  return ret;
}
<|endoftext|>


<commit_before>define(["underscore", "js/core/List", "js/type/Color"], function (_, List, Color) {

    var COLOR_MAP = {
        white: 0xFFFFFF,
        black: 0x000000,
        blue: 0x2244AA,
        red: 0xB91816,
        grey: 0xCCCCCC,
        brown: 0x664B2F,
        green: 0x669933,
        yellow: 0xFFF500,
        turquoise: 0x0AC7DF,
        pink: 0xFB4E81
    };

    var productTypeToColorMap = {},
        colorMap = {},
        color,
        colors = [],
        productTypeDepartmentToSizeMap = {},
        categoryToSizeMap = {},
        departmentProductTypeMap = {},
        productTypeToDepartmentsMap = {};

    // init color map
    for (var key in COLOR_MAP) {
        if (COLOR_MAP.hasOwnProperty(key)) {
            color = Color.parse(COLOR_MAP[key]);
            color.key = key;
            colors.push(color);
            colorMap[color.toString()] = color;
        }
    }

    return {
        /***
         * initializes the productTypeColorCache
         * @param {js.core.List} productTypes
         */
        initProductTypeColorCache: function (productTypes) {
            var color,
                distance,
                bestColor,
                bestAppearance,
                tmpDistance,
                tmpProductType,
                colorKey;

            productTypes.each(function (productType) {
                bestColor = null;
                productTypeToColorMap[productType.$.id] = tmpProductType = {};
                var appearances = productType.getAvailableAppearances();
                if (appearances) {
                    for (var i = 0; i < colors.length; i++) {
                        distance = Number.MAX_VALUE;
                        bestColor = null;
                        bestAppearance = null;
                        color = colors[i];

                        appearances.each(function (appearance) {
                            tmpDistance = color.distanceTo(appearance.getMainColor());
                            if (tmpDistance < distance) {
                                distance = tmpDistance;
                                bestColor = color;
                                bestAppearance = appearance;
                            }
                            if (distance < 30) {
                                colorKey = bestColor.toString();
                                if (!tmpProductType[colorKey]) {
                                    tmpProductType[colorKey] = [];
                                }
                                if (bestAppearance === appearance) {
                                    tmpProductType[colorKey].unshift(appearance);
                                } else {
                                    tmpProductType[colorKey].push(appearance);
                                }
                            }
                        });

                    }
                }
            });
        },
        /***
         *
         * @param {js.core.List} productTypeDepartments
         */
        initProductTypeSizeCache: function (productTypeDepartment, productTypeCategory) {

            var departmentSizes,
                categorySizes;

            departmentSizes = productTypeDepartmentToSizeMap[productTypeDepartment.$.name] = productTypeDepartmentToSizeMap[productTypeDepartment.$.name] || {};
            productTypeDepartment.$.categories.each(function (category) {
                if ((!productTypeCategory || productTypeCategory === category) &&
                    (!categoryToSizeMap[category.identifier()])) {
                    categorySizes = categoryToSizeMap[category.identifier()] = {};
                    category.$.productTypes.each(function (productType) {
                        if (productType.$.sizes) {
                            productType.$.sizes.each(function (size) {
                                if (!departmentSizes[size.$.name]) {
                                    departmentSizes[size.$.name] = {
                                        productTypes: []
                                    };
                                }
                                departmentSizes[size.$.name].productTypes.push(productType);
                                if (!categorySizes[size.$.name]) {
                                    categorySizes[size.$.name] = {
                                        productTypes: []
                                    };
                                }
                                categorySizes[size.$.name].productTypes.push(productType);
                            });

                            departmentProductTypeMap[productTypeDepartment.$.name] = departmentProductTypeMap[productTypeDepartment.$.name] || {};
                            departmentProductTypeMap[productTypeDepartment.$.name][productType.$.id] = productTypeDepartment.$.name;
                            if (!productTypeToDepartmentsMap[productType.$.id]) {
                                productTypeToDepartmentsMap[productType.$.id] = [];
                            }
                            productTypeToDepartmentsMap[productType.$.id].push(productTypeDepartment);
                        }
                    });
                }
            });

        },
        /***
         *
         * @returns {Array}
         */
        getGroupedSizes: function (productTypes, department) {

            function sizeMapToArray(sizeMap, departmentName) {
                var ret = [];
                for (var sizeName in sizeMap) {
                    if (sizeMap.hasOwnProperty(sizeName)) {
                        ret.push({
                            name: sizeName,
                            departmentName: departmentName,
                            productTypes: sizeMap[sizeName].productTypes
                        });
                    }
                }

                return ret;
            }

            var departmentSizeMap = productTypeDepartmentToSizeMap;

            if (productTypes) {
                var departmentHash,
                    key, departments;

                departmentSizeMap = {};
                productTypes.each(function (productType) {
                    if (department) {
                        departments = [department];
                    } else {
                        departments = productTypeToDepartmentsMap[productType.$.id];
                    }
                    if (departments) {
                        for (var i = 0; i < departments.length; i++) {
                            key = departments[i].$.name;
                            departmentHash = departmentSizeMap[key] = departmentSizeMap[key] || {};
                            if (productType.$.sizes) {
                                productType.$.sizes.each(function (size) {
                                    if (!departmentHash[size.$.name]) {
                                        departmentHash[size.$.name] = {
                                            productTypes: []
                                        };
                                    }
                                    departmentHash[size.$.name].productTypes.push(productType);
                                });
                            }
                        }
                    }
                });
            }
            var groups = [],
                group;
            for (var departmentName in departmentSizeMap) {
                if (departmentSizeMap.hasOwnProperty(departmentName)) {
                    group = {
                        name: departmentName,
                        items: sizeMapToArray(departmentSizeMap[departmentName], departmentName)
                    };
                    groups.push(group);
                }
            }

            return groups;

        },

        /***
         * Returns true of the productType has the given color
         * @param {sprd.model.ProductType} productType
         * @param {js.type.Color} color
         * @returns {*|boolean}
         */
        hasProductTypeColor: function (productType, color) {
            return color && productTypeToColorMap[productType.$.id] && productTypeToColorMap[productType.$.id].hasOwnProperty(color.toString());
        },

        hasProductTypeSize: function (productType, sizeItem) {
            return sizeItem && departmentProductTypeMap[sizeItem.departmentName] && departmentProductTypeMap[sizeItem.departmentName][productType.$.id] === sizeItem.departmentName && productType.getSizeByName(sizeItem.name);
        },
        /***
         *
         * @param {sprd.model.ProductType} productType
         * @param {js.type.Color} color
         * @returns {*}
         */
        getAppearanceForProductTypeAndColor: function (productType, color) {
            if (color && productType) {
                var colorHash = productTypeToColorMap[productType.$.id],
                    appearances = colorHash[color.toString()];

                if (appearances && appearances.length) {
                    return appearances[0];
                }
            }
            return null;
        },
        /***
         * Returns a Array of color strings for a js.core.List of productTypes
         * @param {js.core.List} productTypes
         * @returns {Array}
         */
        getColorsForProductTypes: function (productTypes) {

            var colorHash,
                ret = [];
            productTypes.each(function (productType) {
                colorHash = productTypeToColorMap[productType.$.id];
                for (var color in colorHash) {
                    if (colorHash.hasOwnProperty(color) && (ret.indexOf(colorMap[color]) === -1)) {
                        ret.push(colorMap[color]);
                    }
                }
            });

            return ret;
        }

    };

});<commit_msg>DEV-65821 - TypeError: 'undefined' is not an object (evaluating 'n[ t.toString()]')<commit_after>define(["underscore", "js/core/List", "js/type/Color"], function (_, List, Color) {

    var COLOR_MAP = {
        white: 0xFFFFFF,
        black: 0x000000,
        blue: 0x2244AA,
        red: 0xB91816,
        grey: 0xCCCCCC,
        brown: 0x664B2F,
        green: 0x669933,
        yellow: 0xFFF500,
        turquoise: 0x0AC7DF,
        pink: 0xFB4E81
    };

    var productTypeToColorMap = {},
        colorMap = {},
        color,
        colors = [],
        productTypeDepartmentToSizeMap = {},
        categoryToSizeMap = {},
        departmentProductTypeMap = {},
        productTypeToDepartmentsMap = {};

    // init color map
    for (var key in COLOR_MAP) {
        if (COLOR_MAP.hasOwnProperty(key)) {
            color = Color.parse(COLOR_MAP[key]);
            color.key = key;
            colors.push(color);
            colorMap[color.toString()] = color;
        }
    }

    return {
        /***
         * initializes the productTypeColorCache
         * @param {js.core.List} productTypes
         */
        initProductTypeColorCache: function (productTypes) {
            var color,
                distance,
                bestColor,
                bestAppearance,
                tmpDistance,
                tmpProductType,
                colorKey;

            productTypes.each(function (productType) {
                bestColor = null;
                productTypeToColorMap[productType.$.id] = tmpProductType = {};
                var appearances = productType.getAvailableAppearances();
                if (appearances) {
                    for (var i = 0; i < colors.length; i++) {
                        distance = Number.MAX_VALUE;
                        bestColor = null;
                        bestAppearance = null;
                        color = colors[i];

                        appearances.each(function (appearance) {
                            tmpDistance = color.distanceTo(appearance.getMainColor());
                            if (tmpDistance < distance) {
                                distance = tmpDistance;
                                bestColor = color;
                                bestAppearance = appearance;
                            }
                            if (distance < 30) {
                                colorKey = bestColor.toString();
                                if (!tmpProductType[colorKey]) {
                                    tmpProductType[colorKey] = [];
                                }
                                if (bestAppearance === appearance) {
                                    tmpProductType[colorKey].unshift(appearance);
                                } else {
                                    tmpProductType[colorKey].push(appearance);
                                }
                            }
                        });

                    }
                }
            });
        },
        /***
         *
         * @param {js.core.List} productTypeDepartments
         */
        initProductTypeSizeCache: function (productTypeDepartment, productTypeCategory) {

            var departmentSizes,
                categorySizes;

            departmentSizes = productTypeDepartmentToSizeMap[productTypeDepartment.$.name] = productTypeDepartmentToSizeMap[productTypeDepartment.$.name] || {};
            productTypeDepartment.$.categories.each(function (category) {
                if ((!productTypeCategory || productTypeCategory === category) &&
                    (!categoryToSizeMap[category.identifier()])) {
                    categorySizes = categoryToSizeMap[category.identifier()] = {};
                    category.$.productTypes.each(function (productType) {
                        if (productType.$.sizes) {
                            productType.$.sizes.each(function (size) {
                                if (!departmentSizes[size.$.name]) {
                                    departmentSizes[size.$.name] = {
                                        productTypes: []
                                    };
                                }
                                departmentSizes[size.$.name].productTypes.push(productType);
                                if (!categorySizes[size.$.name]) {
                                    categorySizes[size.$.name] = {
                                        productTypes: []
                                    };
                                }
                                categorySizes[size.$.name].productTypes.push(productType);
                            });

                            departmentProductTypeMap[productTypeDepartment.$.name] = departmentProductTypeMap[productTypeDepartment.$.name] || {};
                            departmentProductTypeMap[productTypeDepartment.$.name][productType.$.id] = productTypeDepartment.$.name;
                            if (!productTypeToDepartmentsMap[productType.$.id]) {
                                productTypeToDepartmentsMap[productType.$.id] = [];
                            }
                            productTypeToDepartmentsMap[productType.$.id].push(productTypeDepartment);
                        }
                    });
                }
            });

        },
        /***
         *
         * @returns {Array}
         */
        getGroupedSizes: function (productTypes, department) {

            function sizeMapToArray(sizeMap, departmentName) {
                var ret = [];
                for (var sizeName in sizeMap) {
                    if (sizeMap.hasOwnProperty(sizeName)) {
                        ret.push({
                            name: sizeName,
                            departmentName: departmentName,
                            productTypes: sizeMap[sizeName].productTypes
                        });
                    }
                }

                return ret;
            }

            var departmentSizeMap = productTypeDepartmentToSizeMap;

            if (productTypes) {
                var departmentHash,
                    key, departments;

                departmentSizeMap = {};
                productTypes.each(function (productType) {
                    if (department) {
                        departments = [department];
                    } else {
                        departments = productTypeToDepartmentsMap[productType.$.id];
                    }
                    if (departments) {
                        for (var i = 0; i < departments.length; i++) {
                            key = departments[i].$.name;
                            departmentHash = departmentSizeMap[key] = departmentSizeMap[key] || {};
                            if (productType.$.sizes) {
                                productType.$.sizes.each(function (size) {
                                    if (!departmentHash[size.$.name]) {
                                        departmentHash[size.$.name] = {
                                            productTypes: []
                                        };
                                    }
                                    departmentHash[size.$.name].productTypes.push(productType);
                                });
                            }
                        }
                    }
                });
            }
            var groups = [],
                group;
            for (var departmentName in departmentSizeMap) {
                if (departmentSizeMap.hasOwnProperty(departmentName)) {
                    group = {
                        name: departmentName,
                        items: sizeMapToArray(departmentSizeMap[departmentName], departmentName)
                    };
                    groups.push(group);
                }
            }

            return groups;

        },

        /***
         * Returns true of the productType has the given color
         * @param {sprd.model.ProductType} productType
         * @param {js.type.Color} color
         * @returns {*|boolean}
         */
        hasProductTypeColor: function (productType, color) {
            return color && productTypeToColorMap[productType.$.id] && productTypeToColorMap[productType.$.id].hasOwnProperty(color.toString());
        },

        hasProductTypeSize: function (productType, sizeItem) {
            return sizeItem && departmentProductTypeMap[sizeItem.departmentName] && departmentProductTypeMap[sizeItem.departmentName][productType.$.id] === sizeItem.departmentName && productType.getSizeByName(sizeItem.name);
        },
        /***
         *
         * @param {sprd.model.ProductType} productType
         * @param {js.type.Color} color
         * @returns {*}
         */
        getAppearanceForProductTypeAndColor: function (productType, color) {
            if (color && productType) {
                var colorHash = productTypeToColorMap[productType.$.id],
                    appearances;

                if (colorHash) {
                    appearances = colorHash[color.toString()];
                }

                if (appearances && appearances.length) {
                    return appearances[0];
                }
            }
            return null;
        },
        /***
         * Returns a Array of color strings for a js.core.List of productTypes
         * @param {js.core.List} productTypes
         * @returns {Array}
         */
        getColorsForProductTypes: function (productTypes) {

            var colorHash,
                ret = [];
            productTypes.each(function (productType) {
                colorHash = productTypeToColorMap[productType.$.id];
                for (var color in colorHash) {
                    if (colorHash.hasOwnProperty(color) && (ret.indexOf(colorMap[color]) === -1)) {
                        ret.push(colorMap[color]);
                    }
                }
            });

            return ret;
        }

    };

});<|endoftext|>


<commit_before>//x times corpse smooch combo.
function CorpseSmooch(){
	this.canRepeat = true;
	this.playerList = [];  //what players are already in the medium when i trigger?
	this.dreamersToRevive = [];
	this.combo = 0;

	this.trigger = function(playerList){
		this.playerList = playerList;
		this.dreamersToRevive = [];
		//all dead players who aren't god tier and are destined to be god tier god tier now.
		var deadPlayers = findDeadPlayers(playerList);
		for(var i = 0; i<deadPlayers.length; i++){
			var p = deadPlayers[i];
			//only get one shot at this. if you're a jerk, no luck.
			if(p.dreamSelf && p.getFriends().length > 0){
				this.dreamersToRevive.push(p);
			}
		}
		//corspses can't smooch themselves.
		return this.dreamersToRevive.length > 0 && this.dreamersToRevive.length < playerList.length;

	}

	this.renderContent = function(div){
		this.combo = 0;
		div.append("
"+this.contentForRender(div));

		if(this.combo>1){
			var divID = (div.attr("id")) + "_" + "combo";
			var canvasHTML = "
<canvas id='canvasCombo" + divID+"' width='" +canvasWidth + "' height="+canvasHeight/3 + "'>  </canvas>";
			div.append(canvasHTML);
			var canvasDiv = document.getElementById("canvasCombo"+ divID);
			this.drawCombo(canvasDiv, this.combo);
		}
	}

	this.makeAlive = function(d){
		d.dead = false;
		d.dreamSelf = false;
		d.isDreamSelf = true;
		d.murderMode = false;
		d.grimDark = false;
		d.triggerLevel = 1;
		d.victimBlood = null; //clean face
	}

	this.makeDead = function(d){
		d.dreamSelf = false;
		d.dead = true;
	}

	//smoocher on left, corpse on right, them waking up on prospit/derse on far right
	this.drawCorpseSmooch = function(canvas, dead_player, royalty, repeatTime){
		var pSpriteBuffer = getBufferCanvas(document.getElementById("sprite_template"));
		drawSprite(pSpriteBuffer,royalty,repeatTime)

		dead_player.dead = true;
		dead_player.isDreamSelf = false;  //temporarily show non dream version
		var dSpriteBuffer = getBufferCanvas(document.getElementById("sprite_template"));
		drawSprite(dSpriteBuffer,dead_player,repeatTime)

		copyTmpCanvasToRealCanvasAtPos(canvas, pSpriteBuffer,-100,0)
		copyTmpCanvasToRealCanvasAtPos(canvas, dSpriteBuffer,100,0)

		var moonBuffer = getBufferCanvas(document.getElementById("canvas_template"));
		drawMoon(moonBuffer, dead_player);
		dead_player.dead = false;
		dead_player.isDreamSelf = true;
		drawSprite(moonBuffer,dead_player,repeatTime)
		copyTmpCanvasToRealCanvasAtPos(canvas, moonBuffer,600,0)
		this.makeAlive(dead_player); //make SURE the player is alive after smooches.

	}

	this.drawCombo = function(canvas,comboNum){
		drawComboText(canvas, comboNum);
	}

	this.ignoreEnemies = function(player, royalty){
		if(!royalty){
			return null;
		}
		var r = royalty.getRelationshipWith(player);
		if(!r || (r && r.value < 0)){
			return null;
		}
		return royalty;
	}

	this.getRoyalty = function(d){
		var royalty = d.getWhoLikesMeBestFromList(findLivingPlayers(availablePlayers));
		royalty = this.ignoreEnemies(d, royalty);
		if(!royalty){
			//okay, princes are traditional...
			royalty = findClassPlayer(findLivingPlayers(availablePlayers), "Prince");
			if(royalty && royalty.grimDark == true){
				royalty = null; //grim dark won't corpse smooch unless they actual want to.
			}
		}
		royalty = this.ignoreEnemies(d, royalty);
		if(!royalty){
			//okay, anybody free?
			royalty = getRandomElementFromArray(findLivingPlayers(availablePlayers));
			if(royalty && royalty.grimDark == true){
				royalty = null; //grim dark won't corpse smooch unless they actual want to.
			}
		}
		royalty = this.ignoreEnemies(d, royalty);
		//shit, maybe your best friend can drop what they are doing to save your ass?
		if(!royalty){
			royalty = d.getWhoLikesMeBestFromList(findLivingPlayers(this.playerList));
		}
		royalty = this.ignoreEnemies(d, royalty);
		//is ANYBODY even alive out there????
		if(!royalty){
			royalty = getRandomElementFromArray(findLivingPlayers(this.playerList));
			if(royalty && royalty.grimDark == true){
				royalty = null; //grim dark won't corpse smooch unless they actual want to.
			}
		}
		royalty = this.ignoreEnemies(d, royalty);
		return royalty;
	}

	this.renderForPlayer = function(div, deadPlayer){
		var royalty = this.getRoyalty(deadPlayer)
		if(royalty){
			var divID = (div.attr("id")) + "_" + deadPlayer.chatHandle;
			var canvasHTML = "
<canvas id='canvas" + divID+"' width='" +canvasWidth + "' height="+canvasHeight + "'>  </canvas>";
			div.append(canvasHTML);
			var canvasDiv = document.getElementById("canvas"+ divID);
			this.drawCorpseSmooch(canvasDiv, deadPlayer, royalty, 1000)
		}else{
			this.makeDead(deadPlayer); //dream self dies, too
		}

	}

	//don't actually bring themt o life yet, cause it gets rid of grimdark/murdermode etc.
	this.contentForRender = function(div){
		var ret = "";
		this.combo = 0;
		for(var i = 0; i<this.dreamersToRevive.length; i++){
			var d = this.dreamersToRevive[i];
			//have best friend mac on you.
			var royalty = this.getRoyalty(d);

			if(royalty){
				royalty.triggerLevel ++;
				ret += " The " + royalty.htmlTitle() + ", as a member of the royalty of " + royalty.moon + ", administers the universal remedy for the unawakened ";
				ret += " to the " + d.htmlTitle() + ". Their dream self takes over on " + d.moon + ". ";
				this.renderForPlayer(div, this.dreamersToRevive[i]);
				//this.makeAlive(d);
				this.combo ++;
			}else{
				ret += d.htmlTitle() + "'s corpse waits patiently for the kiss of life. But nobody came. ";
				ret += " Their dream self dies as well. ";
				//this.makeDead(d);
			}
		}
		if(this.combo > 1){
			ret += this.combo +"X CORPSEMOOCH COMBO!!!";
		}
		//x times corpse smooch combo
		return ret;
	}

	//prefer to be smooched by prince who doesn't hate you, or person who likes you best.
	this.content = function(){
		var ret = "";
		var combo = 0;
		for(var i = 0; i<this.dreamersToRevive.length; i++){
			var d = this.dreamersToRevive[i];
			//have best friend mac on you.
			var royalty = this.getRoyalty(d);

			if(royalty){
				royalty.triggerLevel ++;
				ret += " The " + royalty.htmlTitle() + ", as a member of the royalty of " + royalty.moon + ", administers the universal remedy for the unawakened ";
				ret += " to the " + d.htmlTitle() + ". Their dream self takes over on " + d.moon + ". ";
				this.makeAlive(d);
				combo ++;
			}else{
				ret += d.htmlTitle() + "'s corpse waits patiently for the kiss of life. But nobody came. ";
				ret += " Their dream self dies as well. ";
				this.makeDead(d);
			}
		}
		if(combo > 1){
			ret += combo +"X CORPSEMOOCH COMBO!!!";
		}
		//x times corpse smooch combo
		return ret;

	}

}
<commit_msg>made sure dead players who don't get revived don't get a second chance. but introduced when preventing royalty from being random<commit_after>//x times corpse smooch combo.
function CorpseSmooch(){
	this.canRepeat = true;
	this.playerList = [];  //what players are already in the medium when i trigger?
	this.dreamersToRevive = [];
	this.combo = 0;

	this.trigger = function(playerList){
		this.playerList = playerList;
		this.dreamersToRevive = [];
		//all dead players who aren't god tier and are destined to be god tier god tier now.
		var deadPlayers = findDeadPlayers(playerList);
		for(var i = 0; i<deadPlayers.length; i++){
			var p = deadPlayers[i];
			//only get one shot at this. if you're a jerk, no luck.
			if(p.dreamSelf && p.getFriends().length > 0){
				this.dreamersToRevive.push(p);
			}
		}
		//corspses can't smooch themselves.
		return this.dreamersToRevive.length > 0 && this.dreamersToRevive.length < playerList.length;

	}

	this.renderContent = function(div){
		this.combo = 0;
		div.append("
"+this.contentForRender(div));

		if(this.combo>1){
			var divID = (div.attr("id")) + "_" + "combo";
			var canvasHTML = "
<canvas id='canvasCombo" + divID+"' width='" +canvasWidth + "' height="+canvasHeight/3 + "'>  </canvas>";
			div.append(canvasHTML);
			var canvasDiv = document.getElementById("canvasCombo"+ divID);
			this.drawCombo(canvasDiv, this.combo);
		}
	}

	this.makeAlive = function(d){
		d.dead = false;
		d.dreamSelf = false;
		d.isDreamSelf = true;
		d.murderMode = false;
		d.grimDark = false;
		d.triggerLevel = 1;
		d.victimBlood = null; //clean face
	}

	this.makeDead = function(d){
		d.dreamSelf = false;
		d.dead = true;
	}

	//smoocher on left, corpse on right, them waking up on prospit/derse on far right
	this.drawCorpseSmooch = function(canvas, dead_player, royalty, repeatTime){
		var pSpriteBuffer = getBufferCanvas(document.getElementById("sprite_template"));
		drawSprite(pSpriteBuffer,royalty,repeatTime)

		dead_player.dead = true;
		dead_player.isDreamSelf = false;  //temporarily show non dream version
		var dSpriteBuffer = getBufferCanvas(document.getElementById("sprite_template"));
		drawSprite(dSpriteBuffer,dead_player,repeatTime)

		copyTmpCanvasToRealCanvasAtPos(canvas, pSpriteBuffer,-100,0)
		copyTmpCanvasToRealCanvasAtPos(canvas, dSpriteBuffer,100,0)

		var moonBuffer = getBufferCanvas(document.getElementById("canvas_template"));
		drawMoon(moonBuffer, dead_player);
		dead_player.dead = false;
		dead_player.isDreamSelf = true;
		drawSprite(moonBuffer,dead_player,repeatTime)
		copyTmpCanvasToRealCanvasAtPos(canvas, moonBuffer,600,0)
		this.makeAlive(dead_player); //make SURE the player is alive after smooches.

	}

	this.drawCombo = function(canvas,comboNum){
		drawComboText(canvas, comboNum);
	}

	this.ignoreEnemies = function(player, royalty){
		if(!royalty){
			return null;
		}
		var r = royalty.getRelationshipWith(player);
		if(!r || (r && r.value < 0)){
			return null;
		}
		return royalty;
	}

	this.getRoyalty = function(d){
		var royalty = d.getWhoLikesMeBestFromList(findLivingPlayers(availablePlayers));
		royalty = this.ignoreEnemies(d, royalty);
		if(!royalty){
			//okay, princes are traditional...
			royalty = findClassPlayer(findLivingPlayers(availablePlayers), "Prince");
			if(royalty && royalty.grimDark == true){
				royalty = null; //grim dark won't corpse smooch unless they actual want to.
			}
		}
		royalty = this.ignoreEnemies(d, royalty);
		if(!royalty){
			//okay, anybody free?
			royalty = getRandomElementFromArray(findLivingPlayers(availablePlayers));
			if(royalty && royalty.grimDark == true){
				royalty = null; //grim dark won't corpse smooch unless they actual want to.
			}
		}
		royalty = this.ignoreEnemies(d, royalty);
		//shit, maybe your best friend can drop what they are doing to save your ass?
		if(!royalty){
			royalty = d.getWhoLikesMeBestFromList(findLivingPlayers(this.playerList));
		}
		royalty = this.ignoreEnemies(d, royalty);
		//is ANYBODY even alive out there????
		if(!royalty){
			royalty = getRandomElementFromArray(findLivingPlayers(this.playerList));
			if(royalty && royalty.grimDark == true){
				royalty = null; //grim dark won't corpse smooch unless they actual want to.
			}
		}
		royalty = this.ignoreEnemies(d, royalty);
		return royalty;
	}

	this.renderForPlayer = function(div, deadPlayer){
		var royalty = this.getRoyalty(deadPlayer)
		if(royalty){
			var divID = (div.attr("id")) + "_" + deadPlayer.chatHandle;
			var canvasHTML = "
<canvas id='canvas" + divID+"' width='" +canvasWidth + "' height="+canvasHeight + "'>  </canvas>";
			div.append(canvasHTML);
			var canvasDiv = document.getElementById("canvas"+ divID);
			this.drawCorpseSmooch(canvasDiv, deadPlayer, royalty, 1000)
		}else{
			this.makeDead(deadPlayer); //dream self dies, too
		}

	}

	//don't actually bring themt o life yet, cause it gets rid of grimdark/murdermode etc.
	this.contentForRender = function(div){
		var ret = "";
		this.combo = 0;
		for(var i = 0; i<this.dreamersToRevive.length; i++){
			var d = this.dreamersToRevive[i];
			//have best friend mac on you.
			var royalty = this.getRoyalty(d);

			if(royalty){
				royalty.triggerLevel ++;
				ret += " The " + royalty.htmlTitle() + ", as a member of the royalty of " + royalty.moon + ", administers the universal remedy for the unawakened ";
				ret += " to the " + d.htmlTitle() + ". Their dream self takes over on " + d.moon + ". ";
				this.renderForPlayer(div, this.dreamersToRevive[i]);
				//this.makeAlive(d);
				this.combo ++;
			}else{
				ret += d.htmlTitle() + "'s corpse waits patiently for the kiss of life. But nobody came. ";
				ret += " Their dream self dies as well. ";
				this.makeDead(d);
			}
		}
		if(this.combo > 1){
			ret += this.combo +"X CORPSEMOOCH COMBO!!!";
		}
		//x times corpse smooch combo
		return ret;
	}

	//prefer to be smooched by prince who doesn't hate you, or person who likes you best.
	this.content = function(){
		var ret = "";
		var combo = 0;
		for(var i = 0; i<this.dreamersToRevive.length; i++){
			var d = this.dreamersToRevive[i];
			//have best friend mac on you.
			var royalty = this.getRoyalty(d);

			if(royalty){
				royalty.triggerLevel ++;
				ret += " The " + royalty.htmlTitle() + ", as a member of the royalty of " + royalty.moon + ", administers the universal remedy for the unawakened ";
				ret += " to the " + d.htmlTitle() + ". Their dream self takes over on " + d.moon + ". ";
				this.makeAlive(d);
				combo ++;
			}else{
				ret += d.htmlTitle() + "'s corpse waits patiently for the kiss of life. But nobody came. ";
				ret += " Their dream self dies as well. ";
				this.makeDead(d);
			}
		}
		if(combo > 1){
			ret += combo +"X CORPSEMOOCH COMBO!!!";
		}
		//x times corpse smooch combo
		return ret;

	}

}
<|endoftext|>


<commit_before>const _ = require('lodash')
const R = require('../../dist/rambda.js')
const Ramda = require('ramda')
const Utils = require('../../scripts/run-benchmarks/utils')

const listEmpty = [
  {
    label : 'Rambda',
    fn    : () => {
      const list = []
      const fn = Utils.Noop

      return () => R.forEach(fn, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const list = []
      const fn = Utils.Noop

      return () => Ramda.forEach(fn, list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      const list = []
      const fn = Utils.Noop

      return () => _.forEach(list, fn)
    },
  },
]

const listLarge = [
  {
    label : 'Rambda',
    fn    : () => {
      const LIMIT = 10000
      const list = Utils.range(0, LIMIT)
      const fn = Utils.Noop

      return () => R.forEach(fn, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const LIMIT = 10000
      const list = Utils.range(0, LIMIT)
      const fn = Utils.Noop

      return () => Ramda.forEach(fn, list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      const LIMIT = 10000
      const list = Utils.range(0, LIMIT)
      const fn = Utils.Noop

      return () => _.forEach(list, fn)
    },
  },
]

const objectEmpty = [
  {
    label : 'Rambda',
    fn    : () => {
      const obj = {}
      const fn = Utils.Noop

      return () => R.forEach(fn, obj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const obj = {}
      const fn = Utils.Noop

      return () => Ramda.forEach(fn, obj)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      const obj = {}
      const fn = Utils.Noop

      return () => _.forEach(obj, fn)
    },
  },
]

const objectLarge = [
  {
    label : 'Rambda',
    fn    : () => {
      const LIMIT = 10000
      const obj = Utils.range(0, LIMIT).map(i => ({i}))
      const fn = Utils.Noop

      return () => R.forEach(fn, obj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const LIMIT = 10000
      const obj = Utils.range(0, LIMIT).map(i => ({i}))
      const fn = Utils.Noop

      return () => Ramda.forEachObjIndexed(fn, obj)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      const LIMIT = 10000
      const obj = Utils.range(0, LIMIT).map(i => ({i}))
      const fn = Utils.Noop

      return () => _.forEach(obj, fn)
    },
  },
]

module.exports = [
  {label: 'forEach#listEmpty', suites: listEmpty},
  {label: 'forEach#listLarge', suites: listLarge},
  {label: 'forEach#objectEmpty', suites: objectEmpty},
  {label: 'forEach#objectLarge', suites: objectLarge},
]
<commit_msg>forEach bench: fix generating object (#484)<commit_after>const _ = require('lodash')
const R = require('../../dist/rambda.js')
const Ramda = require('ramda')
const Utils = require('../../scripts/run-benchmarks/utils')

const listEmpty = [
  {
    label : 'Rambda',
    fn    : () => {
      const list = []
      const fn = Utils.Noop

      return () => R.forEach(fn, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const list = []
      const fn = Utils.Noop

      return () => Ramda.forEach(fn, list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      const list = []
      const fn = Utils.Noop

      return () => _.forEach(list, fn)
    },
  },
]

const listLarge = [
  {
    label : 'Rambda',
    fn    : () => {
      const LIMIT = 10000
      const list = Utils.range(0, LIMIT)
      const fn = Utils.Noop

      return () => R.forEach(fn, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const LIMIT = 10000
      const list = Utils.range(0, LIMIT)
      const fn = Utils.Noop

      return () => Ramda.forEach(fn, list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      const LIMIT = 10000
      const list = Utils.range(0, LIMIT)
      const fn = Utils.Noop

      return () => _.forEach(list, fn)
    },
  },
]

const objectEmpty = [
  {
    label : 'Rambda',
    fn    : () => {
      const obj = {}
      const fn = Utils.Noop

      return () => R.forEach(fn, obj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const obj = {}
      const fn = Utils.Noop

      return () => Ramda.forEach(fn, obj)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      const obj = {}
      const fn = Utils.Noop

      return () => _.forEach(obj, fn)
    },
  },
]

const objectLarge = [
  {
    label : 'Rambda',
    fn    : () => {
      const LIMIT = 10000
      const obj = {}
      Utils.range(0, LIMIT).forEach(i => obj[i] = i)
      const fn = Utils.Noop

      return () => R.forEach(fn, obj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const LIMIT = 10000
      const obj = {}
      Utils.range(0, LIMIT).forEach(i => obj[i] = i)
      const fn = Utils.Noop

      return () => Ramda.forEachObjIndexed(fn, obj)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      const LIMIT = 10000
      const obj = {}
      Utils.range(0, LIMIT).forEach(i => obj[i] = i)
      const fn = Utils.Noop

      return () => _.forEach(obj, fn)
    },
  },
]

module.exports = [
  {label: 'forEach#listEmpty', suites: listEmpty},
  {label: 'forEach#listLarge', suites: listLarge},
  {label: 'forEach#objectEmpty', suites: objectEmpty},
  {label: 'forEach#objectLarge', suites: objectLarge},
]
<|endoftext|>


<commit_before>(function() {
  var log = require('../../core/lib/logger'),
      _ = require('lodash'),
      SMI = require('./smi'),
      Backend = require('./backend'),
      Frontend = require('./frontend');

  var Broker = function(configuration, smiService, frontend, backend){
    var defaults = {
      version: '0.0',
      frontend: 'tcp://127.0.0.1:5560',
      backend: 'tcp://127.0.0.1:5559',
      smi: {
        // heartbeat interval in ms
        heartbeat: 1000,
        // max ttl for a service in ms
        maxTTL: 1500,
        // refresh service ttl update interval in ms
        updateInterval: 100
      }
    };

    var config = _.defaults(configuration, defaults);

    // public methods

    this.run = function(){
      log.info("Async Broker v%s", config.version);

      smiService = smiService || new SMI(config.smi);
      smiService.run(config.smi);

      backend =  backend || new Backend({ backend: config.backend }, smiService);
      frontend = frontend || new Frontend({ frontend: config.frontend }, smiService);

      backend.frontendSendCallback = frontend.send;
      frontend.backendSendCallback = backend.send;

      backend.run();
      frontend.run();

      log.info("Waiting for messages...");
    };

    this.stop = function(){
      log.info("Async Broker disconnecting...");

      smiService.stop();
      frontend.stop();
      backend.stop();
    };

  };

  module.exports = Broker;
})();
<commit_msg>improved logging<commit_after>(function() {
  var log = require('../../core/lib/logger'),
      _ = require('lodash'),
      SMI = require('./smi'),
      Backend = require('./backend'),
      Frontend = require('./frontend');

  var Broker = function(configuration, smiService, frontend, backend){
    var defaults = {
      version: '0.0',
      frontend: 'tcp://127.0.0.1:5560',
      backend: 'tcp://127.0.0.1:5559',
      smi: {
        // heartbeat interval in ms
        heartbeat: 1000,
        // max ttl for a service in ms
        maxTTL: 1500,
        // refresh service ttl update interval in ms
        updateInterval: 100
      }
    };

    var config = _.defaults(configuration, defaults);

    // public methods

    this.run = function(){
      log.info("Async Broker v%s", config.version);

      smiService = smiService || new SMI(config.smi);
      smiService.run(config.smi);

      backend =  backend || new Backend({ backend: config.backend }, smiService);
      frontend = frontend || new Frontend({ frontend: config.frontend }, smiService);

      backend.frontendSendCallback = frontend.send;
      frontend.backendSendCallback = backend.send;

      backend.run();
      frontend.run();

      log.info("Async Broker is waiting for messages...\n");
    };

    this.stop = function(){
      log.info("\nAsync Broker disconnecting...");

      smiService.stop();
      frontend.stop();
      backend.stop();
    };

  };

  module.exports = Broker;
})();
<|endoftext|>


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

var clicloud = require('clicloud')
var tinycloud = require('./index.js')

var cli = new clicloud()

var args = cli.parse(process.argv)

var groups = [
  {tag: 'master', count: 1},
  {tag: 'worker', count: args.count}
]

var cloud = new tinycloud(args, groups)

cli.init(args, cloud)
<commit_msg>Use updated naming convention<commit_after>#! /usr/bin/env node

var clicloud = require('clicloud')
var tinycloud = require('./index.js')

var opts = {
  name: 'tinycloud'
}

var cli = new clicloud(opts)

var args = cli.parse(process.argv)

var groups = [
  {tag: 'master', count: 1},
  {tag: 'worker', count: args.count}
]

var cloud = new tinycloud(args, groups)

cli.init(args, cloud)
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at http://www.mozillapopcorn.org/butter-license.txt */

/**
 * Module: TrackEvent
 *
 * Supports a single event in the Media > Track > TrackEvent model.
 */
define( [
          "./logger",
          "./eventmanager",
          "util/lang",
          "util/time",
          "./views/trackevent-view"
        ],
        function(
          Logger,
          EventManagerWrapper,
          LangUtil,
          TimeUtil,
          TrackEventView
        ){

  var __guid = 0;

  /**
   * Class: TrackEvent
   *
   * Represents and governs a single popcorn event.
   *
   * @param {Object} options: Options for initialization. Can contain the properties type, name, and popcornOptions. If the popcornOptions property is specified, its contents will be used to initialize the plugin instance associated with this TrackEvent.
   */
  var TrackEvent = function ( options ) {

    options = options || {};

    var _this = this,
        _id = "TrackEvent" + __guid++,
        _name = options.name || _id,
        _logger = new Logger( _id ),
        _track,
        _type = options.type + "",
        _popcornOptions = options.popcornOptions || {
          start: 0,
          end: 1
        },
        _view = new TrackEventView( this, _type, _popcornOptions ),
        _selected = false;

    EventManagerWrapper( _this );

    _this.popcornOptions = _popcornOptions;

    function defaultValue( item ) {
      if ( item.default ) {
        return item.default;
      } else {
        return item.type === "number" ? 0 : "";
      }
    }

    if( !_type ){
      _logger.log( "Warning: " + _id + " has no type." );
    } //if

    _popcornOptions.start = _popcornOptions.start || 0;
    _popcornOptions.start = TimeUtil.roundTime( _popcornOptions.start );
    _popcornOptions.end = _popcornOptions.end || _popcornOptions.start + 1;
    _popcornOptions.end = TimeUtil.roundTime( _popcornOptions.end );

    /**
     * Member: update
     *
     * Updates the event properties and runs sanity checks on input.
     *
     * @param {Object} updateOptions: Object containing plugin-specific properties to be updated for this TrackEvent.
     * @event trackeventupdatefailed: Occurs when an update operation failed because of conflicting times or other serious property problems. As the data property on this event is a string which represents the reason for failure.
     * @event trackeventupdated: Occurs whenan update operation succeeded.
     */
    this.update = function( updateOptions ) {
      var failed = false,
          newStart = _popcornOptions.start,
          newEnd = _popcornOptions.end;

      if ( !isNaN( updateOptions.start ) ) {
        newStart = TimeUtil.roundTime( updateOptions.start );
      }
      if ( !isNaN( updateOptions.end ) ) {
        newEnd = TimeUtil.roundTime( updateOptions.end );
      }

      if ( newStart >= newEnd ){
        failed = "invalidtime";
      }
      else {
        if( _track && _track._media ){
          var media = _track._media;
          if( ( newStart > media.duration ) ||
              ( newEnd > media.duration ) ||
              ( newStart < 0 ) ) {
            failed = "invalidtime";
          }
        }
      }

      if( failed ){
        _this.dispatch( "trackeventupdatefailed", failed );
      } else {
        var _manifest = Popcorn.manifest[ _type ] && Popcorn.manifest[ _type ].options;
        for ( var prop in _manifest ) {
          if ( _manifest.hasOwnProperty( prop ) ) {
            if ( updateOptions[ prop ] === undefined ) {
              _popcornOptions[ prop ] = defaultValue( _manifest[ prop ] );
            } else {
              _popcornOptions[ prop ] = updateOptions[ prop ];
            }
          }
        }
        if( newStart ){
          _popcornOptions.start = newStart;
        }
        if( newEnd ){
          _popcornOptions.end = newEnd;
        }
        _view.update( _popcornOptions );
        _this.popcornOptions = _popcornOptions;
        _this.dispatch( "trackeventupdated", _this );
      }

    }; //update

    /**
     * Member: moveFrameLeft
     *
     * Moves the event to the left, or shrinks it by a specified amount.
     *
     * @param {Number} inc: Amount by which the event is to move or grow.
     * @param {Boolean} metaKey: State of the metaKey (windows, command, etc.). When true, the event duration is shortened.
     * @event trackeventupdated: Occurs whenan update operation succeeded.
     */
    this.moveFrameLeft = function( inc, metaKey ){
      if( !metaKey ) {
        if( _popcornOptions.start > inc ) {
          _popcornOptions.start -= inc;
          _popcornOptions.end -= inc;
        } else {
          _popcornOptions.end = _popcornOptions.end - _popcornOptions.start;
          _popcornOptions.start = 0;
        } // if
      } else if ( _popcornOptions.end - _popcornOptions.start > inc ) {
        _popcornOptions.end -= inc;
      } else {
        _popcornOptions.end = _popcornOptions.start;
      } // if
      _this.dispatch( "trackeventupdated", _this );
      _view.update( _popcornOptions );
    }; //moveFrameLeft

    /**
     * Member: moveFrameRight
     *
     * Moves the event to the right, or elongates it by a specified amount.
     *
     * @param {Number} inc: Amount by which the event is to move or grow.
     * @param {Boolean} metaKey: State of the metaKey (windows, command, etc.). When true, the event duration is lengthened.
     * @event trackeventupdated: Occurs whenan update operation succeeded.
     */
    this.moveFrameRight = function( inc, metaKey ){
      if( _popcornOptions.end < _track._media.duration - inc ) {
        _popcornOptions.end += inc;
        if( !metaKey ) {
          _popcornOptions.start += inc;
        }
      } else {
        if( !metaKey ) {
          _popcornOptions.start += _track._media.duration - _popcornOptions.end;
        }
        _popcornOptions.end = _track._media.duration;
      }
      _this.dispatch( "trackeventupdated", _this );
      _view.update( _popcornOptions );
    }; //moveFrameRight

    _view.listen( "trackeventviewupdated", function( e ){
      _popcornOptions.start = _view.start;
      _popcornOptions.end = _view.end;
      _this.dispatch( "trackeventupdated" );
    });

    Object.defineProperties( this, {

      /**
       * Property: _track
       *
       * Specifies the track on which this TrackEvent currently sites. When set, an update occurs.
       * @malleable: Yes, but not recommended. Butter will manipulate this value automatically. Other uses may yield unexpected results.
       */
      _track: {
        enumerable: true,
        get: function(){
          return _track;
        },
        set: function( val ){
          _track = val;
          _this.update( _popcornOptions );
        }
      },

      /**
       * Property: view
       *
       * A reference to the view object generated for this TrackEvent.
       * @malleable: No.
       */
      view: {
        enumerable: true,
        configurable: false,
        get: function(){
          return _view;
        }
      },

      /**
       * Property: type
       *
       * The type representing the popcorn plugin created and manipulated by this TrackEvent.
       * @malleable: No.
       */
      type: {
        enumerable: true,
        get: function(){
          return _type;
        }
      },

      /**
       * Property: name
       *
       * Name of this TrackEvent.
       * @malleable: No.
       */
      name: {
        enumerable: true,
        get: function(){
          return _name;
        }
      },

      /**
       * Property: id
       *
       * Name of this TrackEvent.
       * @malleable: No.
       */
      id: {
        enumerable: true,
        get: function(){
          return _id;
        }
      },

      /**
       * Property: selected
       *
       * Specifies the state of selection. When true, this TrackEvent is selected.
       *
       * @malleable: Yes.
       * @event trackeventselected: Dispatched when selected state changes to true.
       * @event trackeventdeselected: Dispatched when selected state changes to false.
       */
      selected: {
        enumerable: true,
        get: function(){
          return _selected;
        },
        set: function( val ){
          if( val !== _selected ){
            _selected = val;
            _view.selected = _selected;
            if( _selected ){
              _this.dispatch( "trackeventselected" );
            }
            else {
              _this.dispatch( "trackeventdeselected" );
            } //if
          } //if
        }
      },

      /**
       * Property: json
       *
       * Represents this TrackEvent in a portable JSON format.
       *
       * @malleable: Yes. Will import JSON in the same format that it was exported.
       * @event trackeventupdated: When this property is set, the TrackEvent's data will change, so a trackeventupdated event will be dispatched.
       */
      json: {
        enumerable: true,
        get: function(){
          return {
            id: _id,
            type: _type,
            popcornOptions: LangUtil.clone( _popcornOptions ),
            track: _track ? _track.name : undefined,
            name: _name
          };
        },
        set: function( importData ){
          _type = _popcornOptions.type = importData.type;
          if( importData.name ){
            _name = importData.name;
          }
          _popcornOptions = importData.popcornOptions;
          _this.popcornOptions = _popcornOptions;
          _view.type = _type;
          _view.update( _popcornOptions );
          _this.dispatch( "trackeventupdated", _this );
        }
      }
    }); //properties

  }; //TrackEvent

  return TrackEvent;

}); //define
<commit_msg>[#1343] Fixed bad if block<commit_after>/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at http://www.mozillapopcorn.org/butter-license.txt */

/**
 * Module: TrackEvent
 *
 * Supports a single event in the Media > Track > TrackEvent model.
 */
define( [
          "./logger",
          "./eventmanager",
          "util/lang",
          "util/time",
          "./views/trackevent-view"
        ],
        function(
          Logger,
          EventManagerWrapper,
          LangUtil,
          TimeUtil,
          TrackEventView
        ){

  var __guid = 0;

  /**
   * Class: TrackEvent
   *
   * Represents and governs a single popcorn event.
   *
   * @param {Object} options: Options for initialization. Can contain the properties type, name, and popcornOptions. If the popcornOptions property is specified, its contents will be used to initialize the plugin instance associated with this TrackEvent.
   */
  var TrackEvent = function ( options ) {

    options = options || {};

    var _this = this,
        _id = "TrackEvent" + __guid++,
        _name = options.name || _id,
        _logger = new Logger( _id ),
        _track,
        _type = options.type + "",
        _popcornOptions = options.popcornOptions || {
          start: 0,
          end: 1
        },
        _view = new TrackEventView( this, _type, _popcornOptions ),
        _selected = false;

    EventManagerWrapper( _this );

    _this.popcornOptions = _popcornOptions;

    function defaultValue( item ) {
      if ( item.default ) {
        return item.default;
      }
      return item.type === "number" ? 0 : "";
    }

    if( !_type ){
      _logger.log( "Warning: " + _id + " has no type." );
    } //if

    _popcornOptions.start = _popcornOptions.start || 0;
    _popcornOptions.start = TimeUtil.roundTime( _popcornOptions.start );
    _popcornOptions.end = _popcornOptions.end || _popcornOptions.start + 1;
    _popcornOptions.end = TimeUtil.roundTime( _popcornOptions.end );

    /**
     * Member: update
     *
     * Updates the event properties and runs sanity checks on input.
     *
     * @param {Object} updateOptions: Object containing plugin-specific properties to be updated for this TrackEvent.
     * @event trackeventupdatefailed: Occurs when an update operation failed because of conflicting times or other serious property problems. As the data property on this event is a string which represents the reason for failure.
     * @event trackeventupdated: Occurs whenan update operation succeeded.
     */
    this.update = function( updateOptions ) {
      var failed = false,
          newStart = _popcornOptions.start,
          newEnd = _popcornOptions.end;

      if ( !isNaN( updateOptions.start ) ) {
        newStart = TimeUtil.roundTime( updateOptions.start );
      }
      if ( !isNaN( updateOptions.end ) ) {
        newEnd = TimeUtil.roundTime( updateOptions.end );
      }

      if ( newStart >= newEnd ){
        failed = "invalidtime";
      }
      else {
        if( _track && _track._media ){
          var media = _track._media;
          if( ( newStart > media.duration ) ||
              ( newEnd > media.duration ) ||
              ( newStart < 0 ) ) {
            failed = "invalidtime";
          }
        }
      }

      if( failed ){
        _this.dispatch( "trackeventupdatefailed", failed );
      } else {
        var _manifest = Popcorn.manifest[ _type ] && Popcorn.manifest[ _type ].options;
        for ( var prop in _manifest ) {
          if ( _manifest.hasOwnProperty( prop ) ) {
            if ( updateOptions[ prop ] === undefined ) {
              _popcornOptions[ prop ] = defaultValue( _manifest[ prop ] );
            } else {
              _popcornOptions[ prop ] = updateOptions[ prop ];
            }
          }
        }
        if( newStart ){
          _popcornOptions.start = newStart;
        }
        if( newEnd ){
          _popcornOptions.end = newEnd;
        }
        _view.update( _popcornOptions );
        _this.popcornOptions = _popcornOptions;
        _this.dispatch( "trackeventupdated", _this );
      }

    }; //update

    /**
     * Member: moveFrameLeft
     *
     * Moves the event to the left, or shrinks it by a specified amount.
     *
     * @param {Number} inc: Amount by which the event is to move or grow.
     * @param {Boolean} metaKey: State of the metaKey (windows, command, etc.). When true, the event duration is shortened.
     * @event trackeventupdated: Occurs whenan update operation succeeded.
     */
    this.moveFrameLeft = function( inc, metaKey ){
      if( !metaKey ) {
        if( _popcornOptions.start > inc ) {
          _popcornOptions.start -= inc;
          _popcornOptions.end -= inc;
        } else {
          _popcornOptions.end = _popcornOptions.end - _popcornOptions.start;
          _popcornOptions.start = 0;
        } // if
      } else if ( _popcornOptions.end - _popcornOptions.start > inc ) {
        _popcornOptions.end -= inc;
      } else {
        _popcornOptions.end = _popcornOptions.start;
      } // if
      _this.dispatch( "trackeventupdated", _this );
      _view.update( _popcornOptions );
    }; //moveFrameLeft

    /**
     * Member: moveFrameRight
     *
     * Moves the event to the right, or elongates it by a specified amount.
     *
     * @param {Number} inc: Amount by which the event is to move or grow.
     * @param {Boolean} metaKey: State of the metaKey (windows, command, etc.). When true, the event duration is lengthened.
     * @event trackeventupdated: Occurs whenan update operation succeeded.
     */
    this.moveFrameRight = function( inc, metaKey ){
      if( _popcornOptions.end < _track._media.duration - inc ) {
        _popcornOptions.end += inc;
        if( !metaKey ) {
          _popcornOptions.start += inc;
        }
      } else {
        if( !metaKey ) {
          _popcornOptions.start += _track._media.duration - _popcornOptions.end;
        }
        _popcornOptions.end = _track._media.duration;
      }
      _this.dispatch( "trackeventupdated", _this );
      _view.update( _popcornOptions );
    }; //moveFrameRight

    _view.listen( "trackeventviewupdated", function( e ){
      _popcornOptions.start = _view.start;
      _popcornOptions.end = _view.end;
      _this.dispatch( "trackeventupdated" );
    });

    Object.defineProperties( this, {

      /**
       * Property: _track
       *
       * Specifies the track on which this TrackEvent currently sites. When set, an update occurs.
       * @malleable: Yes, but not recommended. Butter will manipulate this value automatically. Other uses may yield unexpected results.
       */
      _track: {
        enumerable: true,
        get: function(){
          return _track;
        },
        set: function( val ){
          _track = val;
          _this.update( _popcornOptions );
        }
      },

      /**
       * Property: view
       *
       * A reference to the view object generated for this TrackEvent.
       * @malleable: No.
       */
      view: {
        enumerable: true,
        configurable: false,
        get: function(){
          return _view;
        }
      },

      /**
       * Property: type
       *
       * The type representing the popcorn plugin created and manipulated by this TrackEvent.
       * @malleable: No.
       */
      type: {
        enumerable: true,
        get: function(){
          return _type;
        }
      },

      /**
       * Property: name
       *
       * Name of this TrackEvent.
       * @malleable: No.
       */
      name: {
        enumerable: true,
        get: function(){
          return _name;
        }
      },

      /**
       * Property: id
       *
       * Name of this TrackEvent.
       * @malleable: No.
       */
      id: {
        enumerable: true,
        get: function(){
          return _id;
        }
      },

      /**
       * Property: selected
       *
       * Specifies the state of selection. When true, this TrackEvent is selected.
       *
       * @malleable: Yes.
       * @event trackeventselected: Dispatched when selected state changes to true.
       * @event trackeventdeselected: Dispatched when selected state changes to false.
       */
      selected: {
        enumerable: true,
        get: function(){
          return _selected;
        },
        set: function( val ){
          if( val !== _selected ){
            _selected = val;
            _view.selected = _selected;
            if( _selected ){
              _this.dispatch( "trackeventselected" );
            }
            else {
              _this.dispatch( "trackeventdeselected" );
            } //if
          } //if
        }
      },

      /**
       * Property: json
       *
       * Represents this TrackEvent in a portable JSON format.
       *
       * @malleable: Yes. Will import JSON in the same format that it was exported.
       * @event trackeventupdated: When this property is set, the TrackEvent's data will change, so a trackeventupdated event will be dispatched.
       */
      json: {
        enumerable: true,
        get: function(){
          return {
            id: _id,
            type: _type,
            popcornOptions: LangUtil.clone( _popcornOptions ),
            track: _track ? _track.name : undefined,
            name: _name
          };
        },
        set: function( importData ){
          _type = _popcornOptions.type = importData.type;
          if( importData.name ){
            _name = importData.name;
          }
          _popcornOptions = importData.popcornOptions;
          _this.popcornOptions = _popcornOptions;
          _view.type = _type;
          _view.update( _popcornOptions );
          _this.dispatch( "trackeventupdated", _this );
        }
      }
    }); //properties

  }; //TrackEvent

  return TrackEvent;

}); //define
<|endoftext|>


<commit_before>//Google Analytics track
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-60593831-1']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = 'https://ssl.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
<commit_msg>Delete ga.js<commit_after><|endoftext|>