<commit_before>$(function () {
  'use strict';

  var $window = $(window),
      $items = $('div.menu-item > a'),
      $results = $('#search-results'), // search results
      targets = [], // items and corresponding article offset
      $active = null; // active menu item

  function eachParent($item, callback) {
    var $parent = $item.data('ndoc.parent');
    if ($parent && $parent.length) {
      eachParent($parent, callback);
      callback($parent);
    }
  }

  // activates item (used upon scrolling)
  function activate($item) {
    if ($active) {
      $active.removeClass('current');
      eachParent($active, function ($parent) {
        $parent.removeClass('current-parent');
      });
    }

    $active = $item.addClass('current');

    $item.data('ndoc.childs').data('ndoc.collapsed', false).animate({
      height: 'show',
      opacity: 'show'
    });

    eachParent($item, function ($parent) {
      $parent.addClass('current-parent');
      $parent.data('ndoc.childs')
        .data('ndoc.collapsed', false)
        .animate({
          height: 'show',
          opacity: 'show'
        });
    });
  }

  function processScroll() {
    var scrollTop = $window.scrollTop() + 10,
        i = targets.length;

    while (i--) {
      $active !== targets[i].item
        && scrollTop >= targets[i].offset
        && (!targets[i + 1].offset || scrollTop <= targets[i + 1].offset)
        && activate(targets[i].item);
    }
  }

  // init menu items
  $items.each(function () {
    var $item = $(this),
        $childs = $item.parent().next(),
        $parent = $item.parents('ul').eq(0).prev().children();

    // cross-ref tree
    $item.data('ndoc.parent', $parent);
    $item.data('ndoc.childs', $childs);

    // bind activator
    $item.on('click', function () {
      if ($item.hasClass('current') && !$childs.data('ndoc.collapsed')) {
        $childs.data('ndoc.collapsed', true).animate({
          height: 'hide',
          opacity: 'hide'
        });
        return false;
      }

      activate($item);
    });

    // fill-in article offset
    targets.push({
      item: $item,
      offset: $('[id="' + $item.attr('href').slice(1) + '"]').offset().top
    });

    // collapse all 2nd levels
    if (0 != $parent.length) {
      $childs.data('ndoc.collapsed', true).hide();
    }
  });

  function updateSearchResults() {
    $results.empty();

    if ('' == this.value) {
      $results.hide();
      return;
    }

    $results.show();

    $items.filter('[data-id*="' + this.value + '"]').each(function () {
      var $item = $(this);
      $('
').append(
        $item.clone(false)
          .text($item.data('id'))
          .on('click', function () {
            $item.trigger('click');
          })
      ).appendTo($results);
    });
  }

  // init search
  $('#search')
    // prevent from form submit
    .on('submit', function () { return false; })
    .find('input')
      .on('keyup', $.throttle(250, updateSearchResults))
      // click - cuz i don't know what event fied on input clear in Chrome
      .on('change click', updateSearchResults);

  // initial jump (for permalinks)
  processScroll();

  // init prettyprint
  $('pre > code').addClass('prettyprint');
  prettyPrint();
});
<commit_msg>Fixes highlight of active menu item<commit_after>$(function () {
  'use strict';

  var $window = $(window),
      $items = $('div.menu-item > a'),
      $results = $('#search-results'), // search results
      targets = [], // items and corresponding article offset
      $active = null; // active menu item

  function eachParent($item, callback) {
    var $parent = $item.data('ndoc.parent');
    if ($parent && $parent.length) {
      eachParent($parent, callback);
      callback($parent);
    }
  }

  // activates item (used upon scrolling)
  function activate($item, expandParents) {
    if ($active) {
      $active.removeClass('current');
      eachParent($active, function ($parent) {
        $parent.removeClass('current-parent');
      });
    }

    $active = $item.addClass('current');

    eachParent($item, function ($parent) {
      $parent.addClass('current-parent');
      if (expandParents) {
        $parent.data('ndoc.childs')
          .data('ndoc.collapsed', false)
          .animate({
            height: 'show',
            opacity: 'show'
          });
      }
    });
  }

  function processScroll(evt, expandParents) {
    var scrollTop = $window.scrollTop() + 10,
        i = targets.length;

    while (i--) {
      $active !== targets[i].item
        && scrollTop >= targets[i].offset
        && (!targets[i + 1].offset || scrollTop <= targets[i + 1].offset)
        && activate(targets[i].item, expandParents);
    }
  }

  // init menu items
  $items.each(function () {
    var $item = $(this),
        $childs = $item.parent().next(),
        $parent = $item.parents('ul').eq(0).prev().children();

    // cross-ref tree
    $item.data('ndoc.parent', $parent);
    $item.data('ndoc.childs', $childs);

    // bind activator
    $item.on('click', function () {
      if ($item.hasClass('current') && !$childs.data('ndoc.collapsed')) {
        $childs.data('ndoc.collapsed', true).animate({
          height: 'hide',
          opacity: 'hide'
        });
        return false;
      }

      activate($item);

      $item.data('ndoc.childs').data('ndoc.collapsed', false).animate({
        height: 'show',
        opacity: 'show'
      });
    });

    // fill-in article offset
    targets.push({
      item: $item,
      offset: $('[id="' + $item.attr('href').slice(1) + '"]').offset().top
    });

    // collapse all 2nd levels
    if (0 != $parent.length) {
      $childs.data('ndoc.collapsed', true).hide();
    }
  });

  function updateSearchResults() {
    $results.empty();

    if ('' == this.value) {
      $results.hide();
      return;
    }

    $results.show();

    $items.filter('[data-id*="' + this.value + '"]').each(function () {
      var $item = $(this);
      $('
').append(
        $item.clone(false)
          .text($item.data('id'))
          .on('click', function () {
            $item.trigger('click');
          })
      ).appendTo($results);
    });
  }

  // init search
  $('#search')
    // prevent from form submit
    .on('submit', function () { return false; })
    .find('input')
      .on('keyup', $.throttle(250, updateSearchResults))
      // click - cuz i don't know what event fied on input clear in Chrome
      .on('change click', updateSearchResults);

  // dirtyhack until we'll fix scrollspy
  $window.on('scroll', $.throttle(250, processScroll));

  // initial jump (for permalinks)
  processScroll(null, true);

  // init prettyprint
  $('pre > code').addClass('prettyprint');
  prettyPrint();
});
<|endoftext|>


<commit_before>CloudPebble = CloudPebble || {};

// This is a drop-in replacement for $.ajax
// TODO: is this overkill? It seems to work, and means that very few changes to other code are required.
// TODO: If we do keep this, (a) stick it in another file, (b) make sure it's robust
var EventedWebSocket = function(host) {
    var self = this;
    var mSocket = null;
    var ids = {};

    _.extend(this, Backbone.Events);

    this.getSocket = function() {
        return mSocket;
    };

    this.connect = function() {
        return new Promise(function(resolve, reject) {
            mSocket = new WebSocket(host);
            mSocket.onerror = function(e) {
                self.trigger('error', e);
                reject(e);
            };
            mSocket.onclose = handle_socket_close;
            mSocket.onopen = function() {
                self.trigger('open');
                resolve();
            };
        })

    };

    this.close = function() {
        mSocket.close();
        mSocket = null;
    };

    this.send = function(data) {
        return new Promise(function(resolve, reject) {
            // Take the first free ID
            var id = 0;
            while(id in ids) id++;
            ids[id] = true;
            data._id = id;
            // Send the data
            var text = JSON.stringify(data);
            mSocket.send(text);
            var callback;
            callback = function(e) {
                var data = JSON.parse(e.data);
                var m_id = data._id;
                if (m_id == id) {
                    mSocket.removeEventListener("message", callback);
                    delete ids[id];
                    if (!data.success) {
                        reject(new Error(data.error));
                    }
                    else {
                        resolve(data);
                    }
                }
            };
            mSocket.addEventListener("message", callback, false);
        });
    };

    this.isOpen = function() {
        return (mSocket.readyState == WebSocket.OPEN);
    };

    var handle_socket_close = function(e) {
        self.trigger('close', e);
        mSocket = null;
        _.each(ids, function(promise, key) {
            Promise.reject({'error': 'closed'})
        });
        ids = {};
    };
};

CloudPebble.YCM = new (function() {
    var self = this;
    var PING_INTERVAL = 90000;

    var mInitialised = false;
    var mIsInitialising = false;
    var mFailed = false;
    var mRestarting = false;
    var mURL = null;
    var mSocket = null;
    var mUUID = null;
    var mPingTimer = null;
    var mInitPromise = null;

    function pingServer() {
        ws_send('ping',{}).finally(function() {
            mPingTimer = _.delay(pingServer, PING_INTERVAL);
        });
    }

    function ws_send(command, data, timeout) {
        var packet = {
            'command': command,
            'data': data
        };
        return mSocket.send(packet, timeout);
    }
    function sendBuffers() {
        var editors = CloudPebble.Editor.GetAllEditors();
        var pending = 0;
        _.each(editors, function(editor) {
            editor.patch_list = [];
            editor.patch_sequence = 0;
            ++pending;

            ws_send('create', {
                    filename: editor.file_path,
                    content: editor.getValue()
            }).then(function() {
                if(--pending == 0) {
                    console.log('restart done.');
                    $('.prepare-autocomplete').hide();
                    $('.footer-credits').show();
                    mInitialised = true;
                    mRestarting = false;
                }
            }).catch(function() {
                mFailed = true;
                $('.prepare-autocomplete').text(gettext("Code completion resync failed."));
            });
        });
    }

    this.initialise = function() {
        if(mInitialised || mIsInitialising || mFailed) {
            return mInitPromise;
        }
        mIsInitialising = true;
        var platforms = (CloudPebble.ProjectInfo.app_platforms || 'aplite,basalt');
        if(CloudPebble.ProjectInfo.sdk_version == '2') {
            platforms = 'aplite';
        }
        var sdk_version = CloudPebble.ProjectInfo.sdk_version;
        mInitPromise = Ajax.Post('/ide/project/' + PROJECT_ID + '/autocomplete/init', {platforms: platforms, sdk: sdk_version})
            .then(function(data) {
                mUUID = data.uuid;
                mURL = data.server + 'ycm/' + data.uuid + '/ws';
                mSocket = new EventedWebSocket(mURL);
                mSocket.on('open', function() {
                    if(mRestarting) {
                        sendBuffers();
                    } else {
                        mInitialised = true;
                        mPingTimer = _.delay(pingServer, PING_INTERVAL);
                        $('.prepare-autocomplete').hide();
                        $('.footer-credits').show();
                    }
                });

                mSocket.on('close error', function() {
                    setTimeout(function() {self.restart();}, 1000);
                });

                return mSocket.connect();
            })
            .catch(function(e) {
                mFailed = true;
                $('.prepare-autocomplete').text(gettext("Code completion unavailable."));
                throw e;
            });
        return mInitPromise;

    };

    this.restart = function() {
        if(mRestarting) {
            return;
        }
        clearTimeout(mPingTimer);
        mPingTimer = null;
        mInitialised = false;
        mIsInitialising = false;
        mFailed = false;
        mRestarting = true;
        mURL = false;
        mSocket = null;
        mUUID = null;
        $('.prepare-autocomplete').text(gettext("Code completion lost; retrying...")).show();
        $('.footer-credits').hide();
        this.initialise();
    };

    this.getUUID = function() {
        return mUUID;
    };

    this.deleteFile = function(file) {
        if(!mInitialised) {
            return Promise.reject();
        }
        return ws_send('delete', {
            filename: ((file.target == 'worker') ? 'worker_src/' : 'src/') + file.name
        });
    };

    this.createFile = function(file, content) {
        if(!mInitialised) {
            return Promise.reject();
        }
        return ws_send('create', {
            filename: ((file.target == 'worker') ? 'worker_src/' : 'src/') + file.name,
            content: content || ''
        });
    };

    this.updateResources = function(resources) {
        if(!mInitialised) {
            return;
        }
        var defines = [];
        var counter = 1;
        _.each(resources, function(resource) {
            if(resource.kind != 'png-trans') {
                defines = defines.concat(_.map(resource.identifiers, function(id) {
                    return '#define RESOURCE_ID_' + id + ' ' + (counter++);
                }));
            } else {
                _.each(resource.identifiers, function(id) {
                    defines.push('#define RESOURCE_ID_' + id + '_BLACK ' + (counter++));
                    defines.push('#define RESOURCE_ID_' + id + '_WHITE ' + (counter++));
                })
            }
        });
        defines.push("");
        ws_send('create', {
            filename: 'build/src/resource_ids.auto.h',
            content: defines.join("\n")
        });
    };

    this.request = function(endpoint, editor, cursor) {
        var init_step = Promise.resolve();
        if (mFailed) {
            var err = new Error("YCM not functioning");
            err.noYCM = true;
            return Promise.reject(err);
        }
        else if (!mInitialised) {
            init_step = this.initialise();
        }
        cursor = cursor || editor.getCursor();
        var these_patches = editor.patch_list;
        editor.patch_list = [];
        return init_step.then(function() {
            return ws_send(endpoint, {
                file: editor.file_path,
                line: cursor.line,
                ch: cursor.ch,
                patches: these_patches
            })
        }).then(function(data) {
            return data['data'];
        });
    };
})();
<commit_msg>Resolve from YCM create/deleteFile when not initialised instead of reject.<commit_after>CloudPebble = CloudPebble || {};

// This is a drop-in replacement for $.ajax
// TODO: is this overkill? It seems to work, and means that very few changes to other code are required.
// TODO: If we do keep this, (a) stick it in another file, (b) make sure it's robust
var EventedWebSocket = function(host) {
    var self = this;
    var mSocket = null;
    var ids = {};

    _.extend(this, Backbone.Events);

    this.getSocket = function() {
        return mSocket;
    };

    this.connect = function() {
        return new Promise(function(resolve, reject) {
            mSocket = new WebSocket(host);
            mSocket.onerror = function(e) {
                self.trigger('error', e);
                reject(e);
            };
            mSocket.onclose = handle_socket_close;
            mSocket.onopen = function() {
                self.trigger('open');
                resolve();
            };
        })

    };

    this.close = function() {
        mSocket.close();
        mSocket = null;
    };

    this.send = function(data) {
        return new Promise(function(resolve, reject) {
            // Take the first free ID
            var id = 0;
            while(id in ids) id++;
            ids[id] = true;
            data._id = id;
            // Send the data
            var text = JSON.stringify(data);
            mSocket.send(text);
            var callback;
            callback = function(e) {
                var data = JSON.parse(e.data);
                var m_id = data._id;
                if (m_id == id) {
                    mSocket.removeEventListener("message", callback);
                    delete ids[id];
                    if (!data.success) {
                        reject(new Error(data.error));
                    }
                    else {
                        resolve(data);
                    }
                }
            };
            mSocket.addEventListener("message", callback, false);
        });
    };

    this.isOpen = function() {
        return (mSocket.readyState == WebSocket.OPEN);
    };

    var handle_socket_close = function(e) {
        self.trigger('close', e);
        mSocket = null;
        _.each(ids, function(promise, key) {
            Promise.reject({'error': 'closed'})
        });
        ids = {};
    };
};

CloudPebble.YCM = new (function() {
    var self = this;
    var PING_INTERVAL = 90000;

    var mInitialised = false;
    var mIsInitialising = false;
    var mFailed = false;
    var mRestarting = false;
    var mURL = null;
    var mSocket = null;
    var mUUID = null;
    var mPingTimer = null;
    var mInitPromise = null;

    function pingServer() {
        ws_send('ping',{}).finally(function() {
            mPingTimer = _.delay(pingServer, PING_INTERVAL);
        });
    }

    function ws_send(command, data, timeout) {
        var packet = {
            'command': command,
            'data': data
        };
        return mSocket.send(packet, timeout);
    }
    function sendBuffers() {
        var editors = CloudPebble.Editor.GetAllEditors();
        var pending = 0;
        _.each(editors, function(editor) {
            editor.patch_list = [];
            editor.patch_sequence = 0;
            ++pending;

            ws_send('create', {
                    filename: editor.file_path,
                    content: editor.getValue()
            }).then(function() {
                if(--pending == 0) {
                    console.log('restart done.');
                    $('.prepare-autocomplete').hide();
                    $('.footer-credits').show();
                    mInitialised = true;
                    mRestarting = false;
                }
            }).catch(function() {
                mFailed = true;
                $('.prepare-autocomplete').text(gettext("Code completion resync failed."));
            });
        });
    }

    this.initialise = function() {
        if(mInitialised || mIsInitialising || mFailed) {
            return mInitPromise;
        }
        mIsInitialising = true;
        var platforms = (CloudPebble.ProjectInfo.app_platforms || 'aplite,basalt');
        if(CloudPebble.ProjectInfo.sdk_version == '2') {
            platforms = 'aplite';
        }
        var sdk_version = CloudPebble.ProjectInfo.sdk_version;
        mInitPromise = Ajax.Post('/ide/project/' + PROJECT_ID + '/autocomplete/init', {platforms: platforms, sdk: sdk_version})
            .then(function(data) {
                mUUID = data.uuid;
                mURL = data.server + 'ycm/' + data.uuid + '/ws';
                mSocket = new EventedWebSocket(mURL);
                mSocket.on('open', function() {
                    if(mRestarting) {
                        sendBuffers();
                    } else {
                        mInitialised = true;
                        mPingTimer = _.delay(pingServer, PING_INTERVAL);
                        $('.prepare-autocomplete').hide();
                        $('.footer-credits').show();
                    }
                });

                mSocket.on('close error', function() {
                    setTimeout(function() {self.restart();}, 1000);
                });

                return mSocket.connect();
            })
            .catch(function(e) {
                mFailed = true;
                $('.prepare-autocomplete').text(gettext("Code completion unavailable."));
                throw e;
            });
        return mInitPromise;

    };

    this.restart = function() {
        if(mRestarting) {
            return;
        }
        clearTimeout(mPingTimer);
        mPingTimer = null;
        mInitialised = false;
        mIsInitialising = false;
        mFailed = false;
        mRestarting = true;
        mURL = false;
        mSocket = null;
        mUUID = null;
        $('.prepare-autocomplete').text(gettext("Code completion lost; retrying...")).show();
        $('.footer-credits').hide();
        this.initialise();
    };

    this.getUUID = function() {
        return mUUID;
    };

    this.deleteFile = function(file) {
        if(!mInitialised) {
            // We resolve here (and in createFile) because YCM not working isn't actually a problem.
            return Promise.resolve();
        }
        return ws_send('delete', {
            filename: ((file.target == 'worker') ? 'worker_src/' : 'src/') + file.name
        });
    };

    this.createFile = function(file, content) {
        if(!mInitialised) {
            return Promise.resolve();
        }
        return ws_send('create', {
            filename: ((file.target == 'worker') ? 'worker_src/' : 'src/') + file.name,
            content: content || ''
        });
    };

    this.updateResources = function(resources) {
        if(!mInitialised) {
            return;
        }
        var defines = [];
        var counter = 1;
        _.each(resources, function(resource) {
            if(resource.kind != 'png-trans') {
                defines = defines.concat(_.map(resource.identifiers, function(id) {
                    return '#define RESOURCE_ID_' + id + ' ' + (counter++);
                }));
            } else {
                _.each(resource.identifiers, function(id) {
                    defines.push('#define RESOURCE_ID_' + id + '_BLACK ' + (counter++));
                    defines.push('#define RESOURCE_ID_' + id + '_WHITE ' + (counter++));
                })
            }
        });
        defines.push("");
        ws_send('create', {
            filename: 'build/src/resource_ids.auto.h',
            content: defines.join("\n")
        });
    };

    this.request = function(endpoint, editor, cursor) {
        var init_step = Promise.resolve();
        if (mFailed) {
            var err = new Error("YCM not functioning");
            err.noYCM = true;
            return Promise.reject(err);
        }
        else if (!mInitialised) {
            init_step = this.initialise();
        }
        cursor = cursor || editor.getCursor();
        var these_patches = editor.patch_list;
        editor.patch_list = [];
        return init_step.then(function() {
            return ws_send(endpoint, {
                file: editor.file_path,
                line: cursor.line,
                ch: cursor.ch,
                patches: these_patches
            })
        }).then(function(data) {
            return data['data'];
        });
    };
})();
<|endoftext|>


<commit_before>// http://stackoverflow.com/a/5034657
// Adds a hook to eval
eval = (f => function() { _evalHook.apply(this, arguments); return f.apply(this, arguments); })(eval);<commit_msg>Patched the window object<commit_after>// Various transparent patches, that don't pollute the global namespace.

// Patches window
window = new Proxy(
	{},
	{
		get: function(target, name) {
			return (function(){return this})()[name]
		}
	}
)

// http://stackoverflow.com/a/5034657
// Adds a hook to eval
eval = (f => function() {
	_evalHook.apply(this, arguments);
	return f.apply(this, arguments);
})(eval);<|endoftext|>


<commit_before>'use strict';

$(document).ready(function () {
    var responsiveHelper = undefined;
    var breakpointDefinition = {
        tablet: 1024,
        phone : 480
    };

    var tableElement;
    var destroyingDataTable = false;

    // Initialize buttons
    $('button').click(function (event) {
        var ajaxUrl = $(this).attr('data-ajax-url');
        createDataTable(ajaxUrl);
    });

    /**
     * Create the data table.
     * @param {String} ajaxUrl
     */
    function createDataTable(ajaxUrl) {
        tableElement = $('#example');

        // This next part helps to clean things up so we can recreate a data
        // table on the same table element.
        if ($.fn.DataTable.fnIsDataTable(tableElement[0])) {
            // Set the destroying flag to prevent the responsive table from
            // being initialized during this phase.
            destroyingDataTable = true;

            // Get data table instance
            tableElement.dataTable();

            // Since we are destroying the table, let's clear it to speed things
            // up.
            tableElement.fnClearTable(false);

            // Disabling the helper will reset the the responsive changes to the
            // DOM.
            responsiveHelper.disable(true);

            // Remove the responsive helper.
            responsiveHelper = undefined;

            // Now that all things have been restored, let's destroy the table
            tableElement.fnDestroy();

            // Clear flag
            destroyingDataTable = false;
        }

        // Create data table
        tableElement.dataTable({
            sDom             : '<"row"<"span6"l><"span6"f>r>t<"row"<"span6"i><"span6"p>>',
            sPaginationType  : 'bootstrap',
            oLanguage        : {
                sLengthMenu: '_MENU_ records per page'
            },
            // disable sorting on the checkbox column
            aoColumnDefs     : [
                {
                    aTargets : [ 0 ],             // Column number which needs to be modified
                    bSortable: false,             // Column is not sortable
                    // Custom render function - add checkbox
                    mRender  : function (data, type) {
                        return '<input type="checkbox" name="id" value="' + data + '" class="checkbox"/>';
                    },
                    sClass   : 'centered-cell'    // Optional - class to be applied to this table cell
                },
                {
                    aTargets: [ 4 ],              // Column number which needs to be modified
                    sClass  : 'centered-cell'     // Optional - class to be applied to this table cell
                },
                {
                    aTargets: [ 5 ],              // Column number which needs to be modified
                    sClass  : 'centered-cell'     // Optional - class to be applied to this table cell
                }
            ],
            bProcessing      : true,
            bAutoWidth       : false,
            sAjaxSource      : ajaxUrl,
            bDestroy         : true,
            // Custom call back for AJAX
            fnServerData     : function (sSource, aoData, fnCallback, oSettings) {
                oSettings.jqXHR = $.ajax({
                    dataType: 'json',
                    type    : 'GET',
                    url     : sSource,
                    data    : aoData,
                    success : function (data) {
                        fnCallback(data);
                    }
                });
            },
            fnPreDrawCallback: function () {
                // Initialize the responsive data table helper once.
                if (!responsiveHelper && !destroyingDataTable) {
                    responsiveHelper = new ResponsiveDatatablesHelper(tableElement, breakpointDefinition);
                }
            },
            fnRowCallback    : function (nRow) {
                if (responsiveHelper) {
                    responsiveHelper.createExpandIcon(nRow);
                }
            },
            fnDrawCallback   : function () {
                // This function will be called every the table redraws.
                // Specifically, we're interested when next/previous page
                // occurs.
                toggleMasterCheckBasedOnAllOtherCheckboxes();

                // Respond to windows resize.
                if (responsiveHelper) {
                    responsiveHelper.respond();
                }
            },
            fnInitComplete   : function (oSettings) {
                // Register event handlers
                initializeMasterCheckboxEventHandler();
                initializeCheckboxEventHandlers();
                initializeTableRowEventHandlers();

                // Unregister event handlers when table is destroyed.
                oSettings.aoDestroyCallback.push({
                    'sName': 'UnregisterEventHandlers',
                    'fn'   : function () {
                        initializeMasterCheckboxEventHandler(false);
                        initializeCheckboxEventHandlers(false);
                        initializeTableRowEventHandlers(false);
                    }
                });
            }
        });
    }

    // NOTE: We did not add class="centered-cell" to the Engine version and CSS grade columns
    //       as in other examples.

    /**
     * Toggles the master checkbox if all checkboxes in the table that
     * are visible are checked.
     */
    function toggleMasterCheckBasedOnAllOtherCheckboxes() {
        // What we need to do here is check to see if every checkbox is checked.
        // If it is, the master checkbox in the header should be checked as well.
        var allCheckboxes = $('tbody input:checkbox', tableElement);
        var totalCheckboxCount = allCheckboxes.length;
        if (totalCheckboxCount) {
            var checkedChecboxCount = allCheckboxes.filter(':checked').length;
            $('#masterCheck', tableElement).prop('checked', totalCheckboxCount === checkedChecboxCount);
        }
    }

    /**
     * Initialize master checkbox event handlers.
     *
     * The on parameter is used to register/unregister the event handler.  The
     * default is true.
     *
     * @param {Boolean} on
     */
    function initializeMasterCheckboxEventHandler(on) {
        on = on === undefined ? true : on;

        if (on) {
            // Enable master checkbox
            $('#masterCheck', tableElement).prop('disabled', false);

            // Register master checkbox to check/uncheck all checkboxes
            $('#masterCheck', tableElement).on('click', function () {
                // Toggle all checkboxes by triggering a click event on them.  The click
                // event will fire the changed event that we can handle.  Directly changing
                // the checked property like this
                //
                //    $('tbody input:checkbox', tableContainer).not(this).prop('checked', this.checked);
                //
                // toggles all checkboxes but does not trigger click events.  Because there's
                // no click event, there's no changed events on the checkboxes.  We need the
                // changed events so that we can keep track of the checked checkboxes.
                if (this.checked) {
                    $('tbody input:checkbox:not(:checked)', tableElement).not(this).trigger('click');
                } else {
                    $('tbody input:checkbox:checked', tableElement).not(this).trigger('click');
                }
            });
        } else {
            // Disable master checkbox
            $('#masterCheck', tableElement).prop('disabled', true);

            // Unregister master checkbox to check/uncheck all checkboxes
            $('#masterCheck', tableElement).off('click');
        }
    }

    /**
     * Initialize checkbox event handlers.
     *
     * The on parameter is used to register/unregister the event handler.  The
     * default is true.
     *
     * The elementCollection parameter can be one of the following:
     *     - jQuery collection of checkbox elements
     *     - jQuery selector
     *     - undefined
     *
     * If elementCollection is undefined, all checkboxes in DataTable
     * will be selected.
     *
     * @param {Boolean} on
     * @param {Object|String|undefined} elementCollection
     */
    function initializeCheckboxEventHandlers(on, elementCollection) {
        on = on === undefined ? true : on;

        if (elementCollection === undefined) {
            elementCollection = $('input:checkbox', tableElement.fnGetNodes())
        } else if (elementCollection === 'string') {
            elementCollection = $(elementCollection, tableElement.fnGetNodes())
        }

        if (on) {
            // Register elementCollection handlers
            elementCollection.on('change', function (event) {
                // Keep track of the checked checkboxes.
                if (event.target.checked) {
                    // Do something with the checked item
                    // callSomeFunction(event.target.name, event.target.value);
                    console.log('Checkbox ' + event.target.name + ' checked', event.target.value);
                } else {
                    // Do something with the unchecked item
                    // callSomeFunction(event.target.name, event.target.value);
                    console.log('Checkbox ' + event.target.name + ' unchecked', event.target.value);
                }

                // Affect the other parts of the table/page...
                toggleMasterCheckBasedOnAllOtherCheckboxes();
            });
        } else {
            // Unregister elementCollection handlers
            elementCollection.off('change');
        }
    }

    /**
     * Initialize table row event handler.
     *
     * The on parameter is used to register/unregister the event handler.  The
     * default is true.
     *
     * The elementCollection can be one of the following:
     *     - jQuery collection of checkbox elements
     *     - jQuery selector
     *     - undefined
     *
     * If elementCollection is undefined, all table rows in DataTable
     * will be selected.
     *
     * @param {Boolean} on
     * @param {Object|String|undefined} elementCollection
     */
    function initializeTableRowEventHandlers(on, elementCollection) {
        on = on === undefined ? true : on;

        if (elementCollection === undefined) {
            elementCollection = $(tableElement.fnGetNodes())
        } else if (elementCollection === 'string') {
            elementCollection = $(elementCollection, tableElement.fnGetNodes())
        }

        if (on) {
            // Register elementCollection handlers as needed.
        } else {
            // Unregister elementCollection handlers as needed.
        }
    }
});
<commit_msg>Moved code to enable master checkbox to it's own function.<commit_after>'use strict';

$(document).ready(function () {
    var responsiveHelper = undefined;
    var breakpointDefinition = {
        tablet: 1024,
        phone : 480
    };

    var tableElement;
    var destroyingDataTable = false;

    // Initialize buttons
    $('button').click(function (event) {
        var ajaxUrl = $(this).attr('data-ajax-url');
        createDataTable(ajaxUrl);
    });

    /**
     * Create the data table.
     * @param {String} ajaxUrl
     */
    function createDataTable(ajaxUrl) {
        tableElement = $('#example');

        // This next part helps to clean things up so we can recreate a data
        // table on the same table element.
        if ($.fn.DataTable.fnIsDataTable(tableElement[0])) {
            // Set the destroying flag to prevent the responsive table from
            // being initialized during this phase.
            destroyingDataTable = true;

            // Get data table instance
            tableElement.dataTable();

            // Since we are destroying the table, let's clear it to speed things
            // up.
            tableElement.fnClearTable(false);

            // Disabling the helper will reset the the responsive changes to the
            // DOM.
            responsiveHelper.disable(true);

            // Remove the responsive helper.
            responsiveHelper = undefined;

            // Now that all things have been restored, let's destroy the table
            tableElement.fnDestroy();

            // Clear flag
            destroyingDataTable = false;
        }

        // Create data table
        tableElement.dataTable({
            sDom             : '<"row"<"span6"l><"span6"f>r>t<"row"<"span6"i><"span6"p>>',
            sPaginationType  : 'bootstrap',
            oLanguage        : {
                sLengthMenu: '_MENU_ records per page'
            },
            // disable sorting on the checkbox column
            aoColumnDefs     : [
                {
                    aTargets : [ 0 ],             // Column number which needs to be modified
                    bSortable: false,             // Column is not sortable
                    // Custom render function - add checkbox
                    mRender  : function (data, type) {
                        return '<input type="checkbox" name="id" value="' + data + '" class="checkbox"/>';
                    },
                    sClass   : 'centered-cell'    // Optional - class to be applied to this table cell
                },
                {
                    aTargets: [ 4 ],              // Column number which needs to be modified
                    sClass  : 'centered-cell'     // Optional - class to be applied to this table cell
                },
                {
                    aTargets: [ 5 ],              // Column number which needs to be modified
                    sClass  : 'centered-cell'     // Optional - class to be applied to this table cell
                }
            ],
            bProcessing      : true,
            bAutoWidth       : false,
            sAjaxSource      : ajaxUrl,
            bDestroy         : true,
            // Custom call back for AJAX
            fnServerData     : function (sSource, aoData, fnCallback, oSettings) {
                oSettings.jqXHR = $.ajax({
                    dataType: 'json',
                    type    : 'GET',
                    url     : sSource,
                    data    : aoData,
                    success : function (data) {
                        fnCallback(data);
                    }
                });
            },
            fnPreDrawCallback: function () {
                // Initialize the responsive data table helper once.
                if (!responsiveHelper && !destroyingDataTable) {
                    responsiveHelper = new ResponsiveDatatablesHelper(tableElement, breakpointDefinition);
                }
            },
            fnRowCallback    : function (nRow) {
                if (responsiveHelper) {
                    responsiveHelper.createExpandIcon(nRow);
                }
            },
            fnDrawCallback   : function () {
                // This function will be called every the table redraws.
                // Specifically, we're interested when next/previous page
                // occurs.
                toggleMasterCheckBasedOnAllOtherCheckboxes();

                // Respond to windows resize.
                if (responsiveHelper) {
                    responsiveHelper.respond();
                }
            },
            fnInitComplete   : function (oSettings) {
                // Register event handlers
                initializeMasterCheckboxEventHandler();
                initializeCheckboxEventHandlers();
                initializeTableRowEventHandlers();

                // Unregister event handlers when table is destroyed.
                oSettings.aoDestroyCallback.push({
                    'sName': 'UnregisterEventHandlers',
                    'fn'   : function () {
                        initializeMasterCheckboxEventHandler(false);
                        initializeCheckboxEventHandlers(false);
                        initializeTableRowEventHandlers(false);
                    }
                });
            }
        });
    }

    // NOTE: We did not add class="centered-cell" to the Engine version and CSS grade columns
    //       as in other examples.

    /**
     * Enable master checkbox if there are more than one row in the data table.
     *
     * The enable parameter is used to enable/disable the element.
     *
     * Returns true if enable was successful.
     *
     * @param {Boolean} enable
     * @returns {Boolean}
     */
    function enableMasterCheckbox (enable) {
        enable = enable === undefined ? true : enable;

        if (enable && $('tbody tr', tableElement).length) {
            $('#masterCheck', tableElement).prop('disabled', false);
            return true;
        } else {
            $('#masterCheck', tableElement).prop('disabled', true);
            return false;
        }
    }

    /**
     * Toggles the master checkbox if all checkboxes in the table that
     * are visible are checked.
     */
    function toggleMasterCheckBasedOnAllOtherCheckboxes() {
        // What we need to do here is check to see if every checkbox is checked.
        // If it is, the master checkbox in the header should be checked as well.
        var allCheckboxes = $('tbody input:checkbox', tableElement);
        var totalCheckboxCount = allCheckboxes.length;
        if (totalCheckboxCount) {
            var checkedChecboxCount = allCheckboxes.filter(':checked').length;
            $('#masterCheck', tableElement).prop('checked', totalCheckboxCount === checkedChecboxCount);
        }
    }

    /**
     * Initialize master checkbox event handlers.
     *
     * The on parameter is used to register/unregister the event handler.  The
     * default is true.
     *
     * @param {Boolean} on
     */
    function initializeMasterCheckboxEventHandler(on) {
        on = on === undefined ? true : on;

        if (on) {
            // Enable master checkbox
            enableMasterCheckbox();

            // Register master checkbox to check/uncheck all checkboxes
            $('#masterCheck', tableElement).on('click', function () {
                // Toggle all checkboxes by triggering a click event on them.  The click
                // event will fire the changed event that we can handle.  Directly changing
                // the checked property like this
                //
                //    $('tbody input:checkbox', tableContainer).not(this).prop('checked', this.checked);
                //
                // toggles all checkboxes but does not trigger click events.  Because there's
                // no click event, there's no changed events on the checkboxes.  We need the
                // changed events so that we can keep track of the checked checkboxes.
                if (this.checked) {
                    $('tbody input:checkbox:not(:checked)', tableElement).not(this).trigger('click');
                } else {
                    $('tbody input:checkbox:checked', tableElement).not(this).trigger('click');
                }
            });
        } else {
            // Disable master checkbox
            enableMasterCheckbox(false);

            // Unregister master checkbox to check/uncheck all checkboxes
            $('#masterCheck', tableElement).off('click');
        }
    }

    /**
     * Initialize checkbox event handlers.
     *
     * The on parameter is used to register/unregister the event handler.  The
     * default is true.
     *
     * The elementCollection parameter can be one of the following:
     *     - jQuery collection of checkbox elements
     *     - jQuery selector
     *     - undefined
     *
     * If elementCollection is undefined, all checkboxes in DataTable
     * will be selected.
     *
     * @param {Boolean} on
     * @param {Object|String|undefined} elementCollection
     */
    function initializeCheckboxEventHandlers(on, elementCollection) {
        on = on === undefined ? true : on;

        if (elementCollection === undefined) {
            elementCollection = $('input:checkbox', tableElement.fnGetNodes())
        } else if (elementCollection === 'string') {
            elementCollection = $(elementCollection, tableElement.fnGetNodes())
        }

        if (on) {
            // Register elementCollection handlers
            elementCollection.on('change', function (event) {
                // Keep track of the checked checkboxes.
                if (event.target.checked) {
                    // Do something with the checked item
                    // callSomeFunction(event.target.name, event.target.value);
                    console.log('Checkbox ' + event.target.name + ' checked', event.target.value);
                } else {
                    // Do something with the unchecked item
                    // callSomeFunction(event.target.name, event.target.value);
                    console.log('Checkbox ' + event.target.name + ' unchecked', event.target.value);
                }

                // Affect the other parts of the table/page...
                toggleMasterCheckBasedOnAllOtherCheckboxes();
            });
        } else {
            // Unregister elementCollection handlers
            elementCollection.off('change');
        }
    }

    /**
     * Initialize table row event handler.
     *
     * The on parameter is used to register/unregister the event handler.  The
     * default is true.
     *
     * The elementCollection can be one of the following:
     *     - jQuery collection of checkbox elements
     *     - jQuery selector
     *     - undefined
     *
     * If elementCollection is undefined, all table rows in DataTable
     * will be selected.
     *
     * @param {Boolean} on
     * @param {Object|String|undefined} elementCollection
     */
    function initializeTableRowEventHandlers(on, elementCollection) {
        on = on === undefined ? true : on;

        if (elementCollection === undefined) {
            elementCollection = $(tableElement.fnGetNodes())
        } else if (elementCollection === 'string') {
            elementCollection = $(elementCollection, tableElement.fnGetNodes())
        }

        if (on) {
            // Register elementCollection handlers as needed.
        } else {
            // Unregister elementCollection handlers as needed.
        }
    }
});
<|endoftext|>


<commit_before>const nextHandlerWrapper = app => {
  const handler = app.getRequestHandler()
  return async ({ raw, url }, h) => {
    await handler(raw.req, raw.res, url)
    return h.close
  }
}
const defaultHandlerWrapper = app => async ({ raw: { req, res }, url }) => {
  const { pathname, query } = url
  return app.renderToHTML(req, res, pathname, query)
}

const pathWrapper = (app, pathName, opts) => async ({ raw, query, params }) => {
  return app.renderToHTML(
    raw.req,
    raw.res,
    pathName,
    { ...query, ...params },
    opts
  )
}

module.exports = { pathWrapper, defaultHandlerWrapper, nextHandlerWrapper }
<commit_msg>feat(web): Passing actual status code instead 200 (#7735)<commit_after>const nextHandlerWrapper = app => {
  const handler = app.getRequestHandler()
  return async ({ raw, url }, h) => {
    await handler(raw.req, raw.res, url)
    return h.close
  }
}
const defaultHandlerWrapper = app => async ({ raw: { req, res }, url }, h) => {
  const { pathname, query } = url
  const html = await app.renderToHTML(req, res, pathname, query)
  return h.response(html).code(res.statusCode)
}

const pathWrapper = (app, pathName, opts) => async ({ raw, query, params }, h) => {
  const html = await app.renderToHTML(
    raw.req,
    raw.res,
    pathName,
    { ...query, ...params },
    opts
  )
  return h.response(html).code(raw.res.statusCode)
}

module.exports = { pathWrapper, defaultHandlerWrapper, nextHandlerWrapper }
<|endoftext|>


<commit_before>$(document).ready(function () {

    if (typeof BAT === "undefined") {
        alert("Load this page into BAT.");
        return;
    }

    // TODO
    $(".title-value").text("github-org-members.js");
    $("#browser").attr("src", "file:///home/ionicabizau/Documents/github-org-members.js/example/index.html");

    $(".close").on("click", BAT.closeWindow);

    var maximized = false;

    var mousePosition = BAT.getMousePosition();
    function mouseMove(callback) {
        setInterval(function () {
            var cMousePos = BAT.getMousePosition();
            if (mousePosition.left !== cMousePos.left || mousePosition.top !== cMouse.top) {
                callback(mousePosition = cMousePos);
            }
        }, 1);
    }

    $(".maximize").on("click", function () {
        if (!maximized) {
            BAT.setWindowState("MAXIMIZED");
            $(".window.finder").css({
                left:   "0px",
                top:    "0px",
                bottom: "0px",
                right:  "0px",
            });
            maximized = true;
        } else {
            BAT.setWindowState("RESTORED");
            maximized = false;
            $(".window.finder").css({
                left:   "90px",
                top:    "90px",
                bottom: "90px",
                right:  "90px",
            });
        }
    });

    $(".minimize").on("click", function () {
        BAT.setWindowState("MINIMIZED");
    });

    /* drag */
    var initialPos = {};
    var drag = false;
    $(".title").on("mousedown", function (e) {
        drag = true;
        initialPos.x = e.pageX;
        initialPos.y = e.pageY;
    });

    mouseMove(function (e) {
        if (!drag) { return; }

        var winLeft, winTop;
        winLeft = e.left - initialPos.x;
        winTop  = e.top - initialPos.y - 3;

        $(".pos").text(JSON.stringify({top: winTop, left: winLeft}));
        BAT.setWindowPosition(winLeft, winTop);
    });

    $(document).on("mouseup", function () {
        drag = false;
        initial = {};
    });
});
<commit_msg>Get the src and the title from argv.<commit_after>$(document).ready(function () {

    if (typeof BAT === "undefined") {
        alert("Load this page into BAT.");
        return;
    }

    var argv = BAT.argv()
      , src = BAT.argv().slice(-2)[0]
      , title = BAT.argv().slice(-2)[1]
      ;

    BAT.debug(src);
    BAT.debug(title);

    $(".title-value").text(title);
    $("#browser").attr("src", src);

    $(".close").on("click", BAT.closeWindow);

    var maximized = false;

    var mousePosition = BAT.getMousePosition();
    function mouseMove(callback) {
        setInterval(function () {
            var cMousePos = BAT.getMousePosition();
            if (mousePosition.left !== cMousePos.left || mousePosition.top !== cMouse.top) {
                callback(mousePosition = cMousePos);
            }
        }, 1);
    }

    $(".maximize").on("click", function () {
        if (!maximized) {
            BAT.setWindowState("MAXIMIZED");
            $(".window.finder").css({
                left:   "0px",
                top:    "0px",
                bottom: "0px",
                right:  "0px",
            });
            maximized = true;
        } else {
            BAT.setWindowState("RESTORED");
            maximized = false;
            $(".window.finder").css({
                left:   "90px",
                top:    "90px",
                bottom: "90px",
                right:  "90px",
            });
        }
    });

    $(".minimize").on("click", function () {
        BAT.setWindowState("MINIMIZED");
    });

    /* drag */
    var initialPos = {};
    var drag = false;
    $(".title").on("mousedown", function (e) {
        drag = true;
        initialPos.x = e.pageX;
        initialPos.y = e.pageY;
    });

    mouseMove(function (e) {
        if (!drag) { return; }

        var winLeft, winTop;
        winLeft = e.left - initialPos.x;
        winTop  = e.top - initialPos.y - 3;

        $(".pos").text(JSON.stringify({top: winTop, left: winLeft}));
        BAT.setWindowPosition(winLeft, winTop);
    });

    $(document).on("mouseup", function () {
        drag = false;
        initial = {};
    });
});
<|endoftext|>


<commit_before>var config = {
	connection: process.env.MONGO_CONNECTION,
	options: { auto_reconnect: true },

	applicationUrl: 'https://app.likeastore.com',
	siteUrl: 'https://likeastore.com',

	// api keys
	services: {
		github: {
			appId: process.env.GITHUB_APP_ID,
			appSecret: process.env.GITHUB_APP_SECRET
		},

		twitter: {
			consumerKey: process.env.TWITTER_CONSUMER_KEY,
			consumerSecret: process.env.TWITTER_CONSUMER_SECRET
		},

		facebook: {
			appId: process.env.FACEBOOK_APP_ID,
			appSecret: process.env.FACEBOOK_APP_SECRET
		},

		stackoverflow: {
			clientId: process.env.STACKOVERFLOW_CLIENT_ID,
			clientKey: process.env.STACKOVERFLOW_CLIENT_KEY,
			clientSecret: process.env.STACKOVERFLOW_CLIENT_SECRET
		}
	},

	mandrill: {
		token: process.env.MANDRILL_TOKEN
	},

	logentries: {
		token: process.env.LOGENTRIES_TOKEN
	},

	collector: {
		// scheduler cycle
		schedulerRestart: 1000,

		// after collector got to normal mode, next scheduled run in 15 mins
		nextNormalRunAfter: 1000 * 60 * 15,

		// after collector got to rateLimit mode, next scheduled run in hour
		nextRateLimitRunAfter: 1000 * 60 * 60,

		// initial mode quotes
		quotes: {
			facebook: {
				runAfter: 5000
			},

			github: {
				runAfter: 5000
			},

			gist: {
				runAfter: 5000
			},

			twitter: {
				runAfter: 60000
			},

			stackoverflow: {
				runAfter: 5000
			}
		},

		request: {
			timeout: 1000
		}
	}
};

module.exports = config;<commit_msg>production config<commit_after>var config = {
	connection: process.env.MONGO_CONNECTION,
	options: { auto_reconnect: true },

	applicationUrl: 'https://app.likeastore.com',
	siteUrl: 'https://likeastore.com',

	// api keys
	services: {
		github: {
			appId: process.env.GITHUB_APP_ID,
			appSecret: process.env.GITHUB_APP_SECRET
		},

		twitter: {
			consumerKey: process.env.TWITTER_CONSUMER_KEY,
			consumerSecret: process.env.TWITTER_CONSUMER_SECRET
		},

		facebook: {
			appId: process.env.FACEBOOK_APP_ID,
			appSecret: process.env.FACEBOOK_APP_SECRET
		},

		stackoverflow: {
			clientId: process.env.STACKOVERFLOW_CLIENT_ID,
			clientKey: process.env.STACKOVERFLOW_CLIENT_KEY,
			clientSecret: process.env.STACKOVERFLOW_CLIENT_SECRET
		}
	},

	mandrill: {
		token: process.env.MANDRILL_TOKEN
	},

	logentries: {
		token: process.env.LOGENTRIES_TOKEN
	},

	collector: {
		// scheduler cycle
		schedulerRestart: 1000,

		// after collector got to normal mode, next scheduled run in 15 mins
		nextNormalRunAfter: 1000 * 60 * 15,

		// after collector got to rateLimit mode, next scheduled run in hour
		nextRateLimitRunAfter: 1000 * 60 * 60,

		// initial mode quotes
		quotes: {
			facebook: {
				runAfter: 5000
			},

			github: {
				runAfter: 5000
			},

			gist: {
				runAfter: 5000
			},

			twitter: {
				runAfter: 60000
			},

			stackoverflow: {
				runAfter: 5000
			}
		},

		request: {
			timeout: 10000
		}
	}
};

module.exports = config;<|endoftext|>


<commit_before>
var apiRoot = "";

ko.extenders.required = function (target, opts) {

    target.OverrideDisplay = opts.OverrideDisplay;

    target.HasError = ko.computed(function () {
        var value = target();
        return null === value || typeof value === "undefined" || value.length === 0;
    });

    target.ShowError = ko.computed(function() {
        return !target.OverrideDisplay() && target.HasError();
    });

    target.ValidationMessage = (opts.Name || "Field") + " cannot be blank!";

    return target;
};

function AlertViewModel() {

    var self = this;

    self.Show = ko.observable(false);
    self.Type = ko.observable("alert-danger");
    self.BoldText = ko.observable("");
    self.Message = ko.observable("");

    self.HasBoldText = ko.computed(function () {
        var text = self.BoldText();
        return null !== text && typeof text !== "undefined" && text.length > 0;
    });

    self.Hide = function () {
        self.Show(false);
        self.Type("");
        self.BoldText("");
        self.Message("alert-danger");
    };
}

function ContactViewModel() {

    var self = this;

    self.OverrideErrorDisplay = ko.observable(true);

    self.Name = ko.observable().extend({ required: { Name: "Name", OverrideDisplay: self.OverrideErrorDisplay}});
    self.Email = ko.observable().extend({ required: { Name: "Email", OverrideDisplay: self.OverrideErrorDisplay } });
    self.Message = ko.observable().extend({ required: { Name: "Message", OverrideDisplay: self.OverrideErrorDisplay } });

    self.Alert = new AlertViewModel();

    self.IsValid = function() {
        return !self.Name.HasError() &&
               !self.Email.HasError() &&
               !self.Message.HasError();

    };

    self.Send = function () {
        self.OverrideErrorDisplay(false);
        if (!self.IsValid()) {
            return;
        }

        var message = ko.toJS({
            name: self.Name,
            email: self.Email,
            message: self.Message
        });

        console.log(message);

        $.ajax({
            method: "POST",
            url: apiRoot + "contactmessage/",
            data: JSON.stringify(message),
            contentType: "application/json",
            dataType: "JSON",
            jsonp: false
        }).done(function(res) {
            if (res.valid) {
                self.Alert.Type("alert-success");
                self.Alert.BoldText("");
                self.Alert.Message("Message sent successfully. Thank you I will be contact with you soon!");
                self.Clear();
            } else {
                self.Alert.Type("alert-danger");
                self.Alert.BoldText("Error");
                self.Alert.Message(res.message);
            }
            self.Alert.Show(true);
        }).fail(function() {
            self.Alert.Type("alert-danger");
            self.Alert.BoldText("Error");
            self.Alert.Message("An error has occured while sending your message. Please try again later.");
            self.Alert.Show(true);
        });

    };

    self.Clear = function() {
        self.Name("");
        self.Email("");
        self.Message("");

        self.OverrideErrorDisplay(true);
    };

}

$(document).ready(function() {

    //load in the API Root from the page
    apiRoot = $("#apiRoot").val();

    var vm = new ContactViewModel();
    var element = $("#formContact")[0];

    ko.applyBindings(vm, element);

});<commit_msg>Removed debug statement:<commit_after>
var apiRoot = "";

ko.extenders.required = function (target, opts) {

    target.OverrideDisplay = opts.OverrideDisplay;

    target.HasError = ko.computed(function () {
        var value = target();
        return null === value || typeof value === "undefined" || value.length === 0;
    });

    target.ShowError = ko.computed(function() {
        return !target.OverrideDisplay() && target.HasError();
    });

    target.ValidationMessage = (opts.Name || "Field") + " cannot be blank!";

    return target;
};

function AlertViewModel() {

    var self = this;

    self.Show = ko.observable(false);
    self.Type = ko.observable("alert-danger");
    self.BoldText = ko.observable("");
    self.Message = ko.observable("");

    self.HasBoldText = ko.computed(function () {
        var text = self.BoldText();
        return null !== text && typeof text !== "undefined" && text.length > 0;
    });

    self.Hide = function () {
        self.Show(false);
        self.Type("");
        self.BoldText("");
        self.Message("alert-danger");
    };
}

function ContactViewModel() {

    var self = this;

    self.OverrideErrorDisplay = ko.observable(true);

    self.Name = ko.observable().extend({ required: { Name: "Name", OverrideDisplay: self.OverrideErrorDisplay}});
    self.Email = ko.observable().extend({ required: { Name: "Email", OverrideDisplay: self.OverrideErrorDisplay } });
    self.Message = ko.observable().extend({ required: { Name: "Message", OverrideDisplay: self.OverrideErrorDisplay } });

    self.Alert = new AlertViewModel();

    self.IsValid = function() {
        return !self.Name.HasError() &&
               !self.Email.HasError() &&
               !self.Message.HasError();

    };

    self.Send = function () {
        self.OverrideErrorDisplay(false);
        if (!self.IsValid()) {
            return;
        }

        var message = ko.toJS({
            name: self.Name,
            email: self.Email,
            message: self.Message
        });

        $.ajax({
            method: "POST",
            url: apiRoot + "contactmessage/",
            data: JSON.stringify(message),
            contentType: "application/json",
            dataType: "JSON",
            jsonp: false
        }).done(function(res) {
            if (res.valid) {
                self.Alert.Type("alert-success");
                self.Alert.BoldText("");
                self.Alert.Message("Message sent successfully. Thank you I will be contact with you soon!");
                self.Clear();
            } else {
                self.Alert.Type("alert-danger");
                self.Alert.BoldText("Error");
                self.Alert.Message(res.message);
            }
            self.Alert.Show(true);
        }).fail(function() {
            self.Alert.Type("alert-danger");
            self.Alert.BoldText("Error");
            self.Alert.Message("An error has occured while sending your message. Please try again later.");
            self.Alert.Show(true);
        });

    };

    self.Clear = function() {
        self.Name("");
        self.Email("");
        self.Message("");

        self.OverrideErrorDisplay(true);
    };

}

$(document).ready(function() {

    //load in the API Root from the page
    apiRoot = $("#apiRoot").val();

    var vm = new ContactViewModel();
    var element = $("#formContact")[0];

    ko.applyBindings(vm, element);

});<|endoftext|>


<commit_before>var HijriDate = (function () {
  "use strict";

  // Hijri year remainders for determining Kabisa years
  var KABISA_YEAR_REMAINDERS = [2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29];

  // number of days in a Hijri year per month
  var DAYS_IN_YEAR = [30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325];

  // number of days in 30-years per Hijri year
  var DAYS_IN_30_YEARS = [
     354,  708, 1063, 1417, 1771, 2126, 2480, 2834,  3189,  3543,
    3898, 4252, 4606, 4961, 5315, 5669, 6024, 6378,  6732,  7087,
    7441, 7796, 8150, 8504, 8859, 9213, 9567, 9922, 10276, 10631
  ];

  var hijriDate = function (year, month, day) {
    this.year = year;
    this.month = month;
    this.day = day;
  };

  // is the specified Gregorian Date object a Julian date?
  hijriDate.isJulian = function (date) {
    if (date.getFullYear() < 1582) {
      return true;
    } else if (date.getFullYear() === 1582) {
      if (date.getMonth() < 10) {
        return true;
      } else if (date.getMonth() === 10) {
        if (date.getDate() < 5) {
          return true;
        }
      }
    }
    return false;
  };

  // return Astronomical Julian Date corresponding to the specified Gregorian Date object
  hijriDate.gregorianToAJD = function (date) {
    var a, b,
        year = date.getFullYear(),
        month = date.getMonth(),
        day = date.getDate()
            + date.getHours()/24
            + date.getMinutes()/1440
            + date.getSeconds()/86400
            + date.getMilliseconds()/86400000;
    if (month < 3) {
      year--;
      month += 12;
    }
    if (hijriDate.isJulian(date)) {
      b = 0;
    } else {
      a = Math.floor(year / 100);
      b = 2 - a + Math.floor(a / 4);
    }
    return Math.floor(365.25*(year + 4716)) + Math.floor(30.6001*(month + 1)) + day + b - 1524.5;
  };

  // return Gregorian Date object corresponding to the specified Astronomical Julian Date
  hijriDate.ajdToGregorian = function (ajd) {
    var a, b, c, d, e, f, z, alpha,
        year, month, day, hrs, min, sec, msc;
    z = Math.floor(ajd + 0.5);
    f = (ajd + 0.5 - z);
    if (z < 2299161) {
      a = z;
    } else {
      alpha = Math.floor((z - 1867216.25) / 36524.25);
      a = z + 1 + alpha - Math.floor(0.25*alpha);
    }
    b = a + 1524;
    c = Math.floor((b - 122.1) / 365.25);
    d = Math.floor(365.25*c);
    e = Math.floor((b - d) / 30.6001);

    day = b - d - Math.floor(30.6001*e) + f;
    hrs = (day - Math.floor(day))*24;
    min = (hrs - Math.floor(hrs))*60;
    sec = (min - Math.floor(min))*60;
    msc = (sec - Math.floor(sec))*1000;
    month = (e < 14) ? (e - 2) : (e - 14);
    year = (month < 2) ? (c - 4715) : (c - 4716);
    return new Date(year, month + 1, day, hrs, min, sec, msc);
  };

  // is the specified Hijri year a Kabisa year?
  hijriDate.isKabisa = function (year) {
    for (var i in KABISA_YEAR_REMAINDERS) {
      if (year % 30 === KABISA_YEAR_REMAINDERS[i]) {
        return true;
      }
    }
    return false;
  };

  // return number of days in the specified Hijri year and month
  hijriDate.daysInMonth = function (year, month) {
    return ((month === 12) && (hijriDate.isKabisa(year)) || (month % 2 === 1)) ? 30 : 29;
  };

  // return day of Hijri year corresponding to this Hijri Date object
  hijriDate.prototype.dayOfYear = function () {
    return (this.month === 1) ? this.day : (DAYS_IN_YEAR[this.month - 2] + this.day);
  };

  // return Hijri Date object corresponding to specified Astronomical Julian Date
  hijriDate.fromAJD = function (ajd) {
    var year,
        month,
        date,
        i = 0,
        left = Math.floor(ajd - 1948083.5),
        y30 = Math.floor(left / 10631.0);

    left -= y30*10631;
    while (left > DAYS_IN_30_YEARS[i]) {
      i += 1;
    }

    year = Math.round(y30*30.0 + i);
    if (i > 0) {
      left -= DAYS_IN_30_YEARS[i - 1];
    }
    i = 0;
    while (left > DAYS_IN_YEAR[i]) {
      i += 1;
    }
    month = Math.round(i + 1);
    date = (i > 0) ? Math.round(left - DAYS_IN_YEAR[i - 1]) : Math.round(left);

    return new hijriDate(year, month, date);
  };

  // return Astronomical Julian Date corresponding to this Hijri Date object
  hijriDate.prototype.toAJD = function () {
    var y30 = Math.floor(this.year / 30.0),
        ajd = 1948083.5 + y30*10631 + this.dayOfYear();
    if (this.year % 30 !== 0) {
      ajd += DAYS_IN_30_YEARS[this.year - y30*30 - 1];
    }
    return ajd;
  };

  // return Hijri Date object corresponding to the specified Gregorian date object
  hijriDate.fromGregorian = function (date) {
    return hijriDate.fromAJD(hijriDate.gregorianToAJD(date));
  };

  // return Gregorian date object corresponding to this Hijri Date object
  hijriDate.prototype.toGregorian = function () {
    return hijriDate.ajdToGregorian(this.toAJD());
  };

  return hijriDate;
})();
<commit_msg>Add attribute getters.<commit_after>var HijriDate = (function () {
  "use strict";

  // Hijri year remainders for determining Kabisa years
  var KABISA_YEAR_REMAINDERS = [2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29];

  // number of days in a Hijri year per month
  var DAYS_IN_YEAR = [30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325];

  // number of days in 30-years per Hijri year
  var DAYS_IN_30_YEARS = [
     354,  708, 1063, 1417, 1771, 2126, 2480, 2834,  3189,  3543,
    3898, 4252, 4606, 4961, 5315, 5669, 6024, 6378,  6732,  7087,
    7441, 7796, 8150, 8504, 8859, 9213, 9567, 9922, 10276, 10631
  ];

  var hijriDate = function (year, month, day) {
    this.year = year;
    this.month = month;
    this.day = day;
  };

  hijriDate.prototype.getYear = function () {
    return this.year;
  };

  hijriDate.prototype.getMonth = function () {
    return this.month;
  };

  hijriDate.prototype.getDate = function () {
    return this.day;
  };

  // is the specified Gregorian Date object a Julian date?
  hijriDate.isJulian = function (date) {
    if (date.getFullYear() < 1582) {
      return true;
    } else if (date.getFullYear() === 1582) {
      if (date.getMonth() < 10) {
        return true;
      } else if (date.getMonth() === 10) {
        if (date.getDate() < 5) {
          return true;
        }
      }
    }
    return false;
  };

  // return Astronomical Julian Date corresponding to the specified Gregorian Date object
  hijriDate.gregorianToAJD = function (date) {
    var a, b,
        year = date.getFullYear(),
        month = date.getMonth(),
        day = date.getDate()
            + date.getHours()/24
            + date.getMinutes()/1440
            + date.getSeconds()/86400
            + date.getMilliseconds()/86400000;
    if (month < 3) {
      year--;
      month += 12;
    }
    if (hijriDate.isJulian(date)) {
      b = 0;
    } else {
      a = Math.floor(year / 100);
      b = 2 - a + Math.floor(a / 4);
    }
    return Math.floor(365.25*(year + 4716)) + Math.floor(30.6001*(month + 1)) + day + b - 1524.5;
  };

  // return Gregorian Date object corresponding to the specified Astronomical Julian Date
  hijriDate.ajdToGregorian = function (ajd) {
    var a, b, c, d, e, f, z, alpha,
        year, month, day, hrs, min, sec, msc;
    z = Math.floor(ajd + 0.5);
    f = (ajd + 0.5 - z);
    if (z < 2299161) {
      a = z;
    } else {
      alpha = Math.floor((z - 1867216.25) / 36524.25);
      a = z + 1 + alpha - Math.floor(0.25*alpha);
    }
    b = a + 1524;
    c = Math.floor((b - 122.1) / 365.25);
    d = Math.floor(365.25*c);
    e = Math.floor((b - d) / 30.6001);

    day = b - d - Math.floor(30.6001*e) + f;
    hrs = (day - Math.floor(day))*24;
    min = (hrs - Math.floor(hrs))*60;
    sec = (min - Math.floor(min))*60;
    msc = (sec - Math.floor(sec))*1000;
    month = (e < 14) ? (e - 2) : (e - 14);
    year = (month < 2) ? (c - 4715) : (c - 4716);
    return new Date(year, month + 1, day, hrs, min, sec, msc);
  };

  // is the specified Hijri year a Kabisa year?
  hijriDate.isKabisa = function (year) {
    for (var i in KABISA_YEAR_REMAINDERS) {
      if (year % 30 === KABISA_YEAR_REMAINDERS[i]) {
        return true;
      }
    }
    return false;
  };

  // return number of days in the specified Hijri year and month
  hijriDate.daysInMonth = function (year, month) {
    return ((month === 12) && (hijriDate.isKabisa(year)) || (month % 2 === 1)) ? 30 : 29;
  };

  // return day of Hijri year corresponding to this Hijri Date object
  hijriDate.prototype.dayOfYear = function () {
    return (this.month === 1) ? this.day : (DAYS_IN_YEAR[this.month - 2] + this.day);
  };

  // return Hijri Date object corresponding to specified Astronomical Julian Date
  hijriDate.fromAJD = function (ajd) {
    var year,
        month,
        date,
        i = 0,
        left = Math.floor(ajd - 1948083.5),
        y30 = Math.floor(left / 10631.0);

    left -= y30*10631;
    while (left > DAYS_IN_30_YEARS[i]) {
      i += 1;
    }

    year = Math.round(y30*30.0 + i);
    if (i > 0) {
      left -= DAYS_IN_30_YEARS[i - 1];
    }
    i = 0;
    while (left > DAYS_IN_YEAR[i]) {
      i += 1;
    }
    month = Math.round(i + 1);
    date = (i > 0) ? Math.round(left - DAYS_IN_YEAR[i - 1]) : Math.round(left);

    return new hijriDate(year, month, date);
  };

  // return Astronomical Julian Date corresponding to this Hijri Date object
  hijriDate.prototype.toAJD = function () {
    var y30 = Math.floor(this.year / 30.0),
        ajd = 1948083.5 + y30*10631 + this.dayOfYear();
    if (this.year % 30 !== 0) {
      ajd += DAYS_IN_30_YEARS[this.year - y30*30 - 1];
    }
    return ajd;
  };

  // return Hijri Date object corresponding to the specified Gregorian date object
  hijriDate.fromGregorian = function (date) {
    return hijriDate.fromAJD(hijriDate.gregorianToAJD(date));
  };

  // return Gregorian date object corresponding to this Hijri Date object
  hijriDate.prototype.toGregorian = function () {
    return hijriDate.ajdToGregorian(this.toAJD());
  };

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


<commit_before>/* eslint-disable semi, space-before-function-paren, space-before-blocks*/

import React from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableHighlight
} from 'react-native';

import { Actions } from 'react-native-router-flux';

import TeamMap from '../Utilities/TeamMap';

class GameStatsTeam extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      homeStats: [],
      awayStats: [],
      homeScores: this.props.game.home,
      awayScores: this.props.game.visitor,
      homeRecord: '',
      awayRecord: '',
      loaded: false
    }
  }

  componentWillMount(){
    this.getGameStats();
  }

  // retrieves game stats for a specific game
  getGameStats(){
    var game = this.props.game;
    var date = game.date;
    var gameID = game.id;
    var url = 'http://data.nba.com/data/10s/json/cms/noseason/game/' + date + '/' + gameID + '/boxscore.json';
    fetch(url)
    .then((response) => response.json())
    .then((jsonResponse) => {
      var homeStats = jsonResponse.sports_content.game.home;
      var awayStats = jsonResponse.sports_content.game.visitor;
      this.setState({
        homeStats: homeStats,
        awayStats: awayStats,
        loaded: true
      });
    })
    .catch((error) => {
      console.log(error);
    });
  }

  render(){
    if (!this.state.loaded){
      return (
        <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
          <Image
            source={require('../Assets/Images/ring.gif')}
            style={{width: 70, height: 70}}
          />
        </View>
      )
    }
    var h1 = 0;
    var h2 = 0;
    var h3 = 0;
    var h4 = 0;
    var hFinal = 0;
    var a1 = 0;
    var a2 = 0;
    var a3 = 0;
    var a4 = 0;
    var aFinal = 0;
    if (this.state.awayScores.linescores && this.state.homeScores.linescores){
      switch (this.state.awayScores.linescores.period.length){
        case 1:
          a1 = this.state.awayScores.linescores.period[0].score;
          break;
        case 2:
          a1 = this.state.awayScores.linescores.period[0].score;
          a2 = this.state.awayScores.linescores.period[1].score;
          break;
        case 3:
          a1 = this.state.awayScores.linescores.period[0].score;
          a2 = this.state.awayScores.linescores.period[1].score;
          a3 = this.state.awayScores.linescores.period[2].score;
          break;
        case 4:
          a1 = this.state.awayScores.linescores.period[0].score;
          a2 = this.state.awayScores.linescores.period[1].score;
          a3 = this.state.awayScores.linescores.period[2].score;
          a4 = this.state.awayScores.linescores.period[3].score;
          break;
        default:
          a1 = 0;
          a2 = 0;
          a3 = 0;
          a4 = 0;
          break;
      }
      switch (this.state.homeScores.linescores.period.length){
        case 1:
          h1 = this.state.homeScores.linescores.period[0].score;
          break;
        case 2:
          h1 = this.state.homeScores.linescores.period[0].score;
          h2 = this.state.homeScores.linescores.period[1].score;
          break;
        case 3:
          h1 = this.state.homeScores.linescores.period[0].score;
          h2 = this.state.homeScores.linescores.period[1].score;
          h3 = this.state.homeScores.linescores.period[2].score;
          break;
        case 4:
          h1 = this.state.homeScores.linescores.period[0].score;
          h2 = this.state.homeScores.linescores.period[1].score;
          h3 = this.state.homeScores.linescores.period[2].score;
          h4 = this.state.homeScores.linescores.period[3].score;
          break;
        default:
          h1 = 0;
          h2 = 0;
          h3 = 0;
          h4 = 0;
          break;
      }
    }
    aFinal = parseInt(a1) + parseInt(a2) + parseInt(a3) + parseInt(a4);
    hFinal = parseInt(h1) + parseInt(h2) + parseInt(h3) + parseInt(h4);
    return (
      <View style={styles.main}>
        <View style={styles.scoreHead}>
          <View style={styles.scoreboardHeader}>
            <Text style={{flex: 1}}> Q1 </Text>
            <Text style={{flex: 1}}> Q2 </Text>
            <Text style={{flex: 1}}> Q3 </Text>
            <Text style={{flex: 1}}> Q4 </Text>
            <Text style={{flex: 1}}> Final </Text>
          </View>
          <View style={styles.line} />
          <View style={styles.quarterScores}>
            <View style={styles.teamScores}>
              <Text style={{flex: 1, alignSelf: 'center'}}> {this.state.awayStats.abbreviation} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {a1} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {a2} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {a3} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {a4} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {aFinal} </Text>
            </View>
            <View style={styles.line} />
            <View style={styles.teamScores}>
              <Text style={{flex: 1, alignSelf: 'center'}}> {this.state.homeStats.abbreviation} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {h1} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {h2} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {h3} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {h4} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {hFinal} </Text>
            </View>
          </View>
        </View>
        <View style={styles.line} />
        <View style={styles.head}>
          <TouchableHighlight onPress={() => Actions.TeamStats({team: this.state.awayStats.abbreviation.toLowerCase()})} underlayColor='#FFFFFF'>
            <Image
              style={styles.logo}
              source={TeamMap[this.state.awayStats.team_key.toLowerCase()].logo}
            />
          </TouchableHighlight>
          <View style={styles.vertical} />
          <Text> Stats </Text>
          <View style={styles.vertical} />
          <TouchableHighlight onPress={() => Actions.TeamStats({team: this.state.homeStats.abbreviation.toLowerCase()})} underlayColor='#FFFFFF'>
            <Image
              style={styles.logo}
              source={TeamMap[this.state.homeStats.team_key.toLowerCase()].logo}
            />
          </TouchableHighlight>
        </View>
        <View style={styles.line} />
        <View style={styles.body}>
          <View style={styles.statsColumn}>
            <Text> {this.state.awayStats.stats.points === '' ? '0' : this.state.awayStats.stats.points} </Text>
            <Text> {this.state.awayStats.stats.field_goals_made === '' ? '-' : this.state.awayStats.stats.field_goals_made + '/' + this.state.awayStats.stats.field_goals_attempted + '(' + this.state.awayStats.stats.field_goals_percentage + '%)'} </Text>
            <Text> {this.state.awayStats.stats.three_pointers_made === '' ? '-' : this.state.awayStats.stats.three_pointers_made + '/' + this.state.awayStats.stats.three_pointers_attempted + '(' + this.state.awayStats.stats.three_pointers_percentage + '%)'} </Text>
            <Text> {this.state.awayStats.stats.free_throws_made === '' ? '-' : this.state.awayStats.stats.free_throws_made + '/' + this.state.awayStats.stats.free_throws_attempted + '(' + this.state.awayStats.stats.free_throws_percentage + '%)'} </Text>
            <Text> {this.state.awayStats.stats.assists === '' ? '0' : this.state.awayStats.stats.assists} </Text>
            <Text> {this.state.awayStats.stats.rebounds_offensive === '' ? '0' : this.state.awayStats.stats.rebounds_offensive} </Text>
            <Text> {this.state.awayStats.stats.rebounds_defensive === '' ? '0' : this.state.awayStats.stats.rebounds_defensive} </Text>
            <Text> {this.state.awayStats.stats.steals === '' ? '0' : this.state.awayStats.stats.steals} </Text>
            <Text> {this.state.awayStats.stats.blocks === '' ? '0' : this.state.awayStats.stats.blocks} </Text>
            <Text> {this.state.awayStats.stats.turnovers === '' ? '0' : this.state.awayStats.stats.turnovers} </Text>
            <Text> {this.state.awayStats.stats.fouls === '' ? '0' : this.state.awayStats.stats.fouls} </Text>
          </View>
          <View style={styles.statsColumn}>
            <Text> Points </Text>
            <Text> Field Goals </Text>
            <Text> 3 Pointers </Text>
            <Text> Free Throws </Text>
            <Text> Assists </Text>
            <Text> O. Rebounds </Text>
            <Text> D. Rebounds </Text>
            <Text> Steals </Text>
            <Text> Blocks </Text>
            <Text> Turnovers </Text>
            <Text> Fouls </Text>
          </View>
          <View style={styles.statsColumn}>
            <Text> {this.state.homeStats.stats.points === '' ? '0' : this.state.homeStats.stats.points} </Text>
            <Text> {this.state.homeStats.stats.field_goals_made === '' ? '-' : this.state.homeStats.stats.field_goals_made + '/' + this.state.homeStats.stats.field_goals_attempted + '(' + this.state.homeStats.stats.field_goals_percentage + '%)'} </Text>
            <Text> {this.state.homeStats.stats.three_pointers_made === '' ? '-' : this.state.homeStats.stats.three_pointers_made + '/' + this.state.homeStats.stats.three_pointers_attempted + '(' + this.state.homeStats.stats.three_pointers_percentage + '%)'} </Text>
            <Text> {this.state.homeStats.stats.free_throws_made === '' ? '-' : this.state.homeStats.stats.free_throws_made + '/' + this.state.homeStats.stats.free_throws_attempted + '(' + this.state.homeStats.stats.free_throws_percentage + '%)'} </Text>
            <Text> {this.state.homeStats.stats.assists === '' ? '0' : this.state.homeStats.stats.assists} </Text>
            <Text> {this.state.homeStats.stats.rebounds_offensive === '' ? '0' : this.state.homeStats.stats.rebounds_offensive} </Text>
            <Text> {this.state.homeStats.stats.rebounds_defensive === '' ? '0' : this.state.homeStats.stats.rebounds_defensive} </Text>
            <Text> {this.state.homeStats.stats.steals === '' ? '0' : this.state.homeStats.stats.steals} </Text>
            <Text> {this.state.homeStats.stats.blocks === '' ? '0' : this.state.homeStats.stats.blocks} </Text>
            <Text> {this.state.homeStats.stats.turnovers === '' ? '0' : this.state.homeStats.stats.turnovers} </Text>
            <Text> {this.state.homeStats.stats.fouls === '' ? '0' : this.state.homeStats.stats.fouls} </Text>
          </View>
        </View>
      </View>
    )
  }
}

var styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: '#FCFCFC'
  },
  quarterScores: {
    flex: 1,
    // marginLeft: 15
  },
  scoreHead: {
      flex: 0.5
  },
  scoreboardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginLeft: 75,
    marginRight: 30,
    marginTop: 10,
    marginBottom: -5,
    flex: 0.5
  },
  head: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginLeft: 30,
    marginRight: 30,
    marginTop: 10,
    marginBottom: 10
  },
  logo: {
    width: 70,
    height: 70,
    shadowColor: '#000000',
    shadowOpacity: 0.8,
    shadowRadius: 1,
    shadowOffset: {
      height: 1,
      width: 0
    }
  },
  body: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: 12,
    marginRight: 12,
    marginTop: 10
  },
  line: {
    marginLeft: 5,
    marginRight: 5,
    height: 1,
    backgroundColor: '#000'
  },
  vertical: {
    marginLeft: 15,
    marginRight: 15,
    width: 1,
    marginTop: -10,
    marginBottom: -10,
    backgroundColor: '#000'
  },
  verticalScores: {
    marginLeft: 15,
    marginRight: 15,
    marginTop: -10,
    width: 1,
    backgroundColor: '#000'
  },
  teamScores: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: 40,
    marginRight: 30,
    flex: 1,
    // marginTop: 10,
    marginLeft: 20,
    // backgroundColor: 'red'
  },
  statsColumn: {
    flexDirection: 'column',
    alignItems: 'center',
    flex: 1
  }
});

module.exports = GameStatsTeam;
/* eslint-enable semi, space-before-function-paren, space-before-blocks*/
<commit_msg>have lines seperating each column. need to work on centering now<commit_after>/* eslint-disable semi, space-before-function-paren, space-before-blocks*/

import React from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableHighlight
} from 'react-native';

import { Actions } from 'react-native-router-flux';

import TeamMap from '../Utilities/TeamMap';

class GameStatsTeam extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      homeStats: [],
      awayStats: [],
      homeScores: this.props.game.home,
      awayScores: this.props.game.visitor,
      homeRecord: '',
      awayRecord: '',
      loaded: false
    }
  }

  componentWillMount(){
    this.getGameStats();
  }

  // retrieves game stats for a specific game
  getGameStats(){
    var game = this.props.game;
    var date = game.date;
    var gameID = game.id;
    var url = 'http://data.nba.com/data/10s/json/cms/noseason/game/' + date + '/' + gameID + '/boxscore.json';
    fetch(url)
    .then((response) => response.json())
    .then((jsonResponse) => {
      var homeStats = jsonResponse.sports_content.game.home;
      var awayStats = jsonResponse.sports_content.game.visitor;
      this.setState({
        homeStats: homeStats,
        awayStats: awayStats,
        loaded: true
      });
    })
    .catch((error) => {
      console.log(error);
    });
  }

  render(){
    if (!this.state.loaded){
      return (
        <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
          <Image
            source={require('../Assets/Images/ring.gif')}
            style={{width: 70, height: 70}}
          />
        </View>
      )
    }
    var h1 = 0;
    var h2 = 0;
    var h3 = 0;
    var h4 = 0;
    var hFinal = 0;
    var a1 = 0;
    var a2 = 0;
    var a3 = 0;
    var a4 = 0;
    var aFinal = 0;
    if (this.state.awayScores.linescores && this.state.homeScores.linescores){
      switch (this.state.awayScores.linescores.period.length){
        case 1:
          a1 = this.state.awayScores.linescores.period[0].score;
          break;
        case 2:
          a1 = this.state.awayScores.linescores.period[0].score;
          a2 = this.state.awayScores.linescores.period[1].score;
          break;
        case 3:
          a1 = this.state.awayScores.linescores.period[0].score;
          a2 = this.state.awayScores.linescores.period[1].score;
          a3 = this.state.awayScores.linescores.period[2].score;
          break;
        case 4:
          a1 = this.state.awayScores.linescores.period[0].score;
          a2 = this.state.awayScores.linescores.period[1].score;
          a3 = this.state.awayScores.linescores.period[2].score;
          a4 = this.state.awayScores.linescores.period[3].score;
          break;
        default:
          a1 = 0;
          a2 = 0;
          a3 = 0;
          a4 = 0;
          break;
      }
      switch (this.state.homeScores.linescores.period.length){
        case 1:
          h1 = this.state.homeScores.linescores.period[0].score;
          break;
        case 2:
          h1 = this.state.homeScores.linescores.period[0].score;
          h2 = this.state.homeScores.linescores.period[1].score;
          break;
        case 3:
          h1 = this.state.homeScores.linescores.period[0].score;
          h2 = this.state.homeScores.linescores.period[1].score;
          h3 = this.state.homeScores.linescores.period[2].score;
          break;
        case 4:
          h1 = this.state.homeScores.linescores.period[0].score;
          h2 = this.state.homeScores.linescores.period[1].score;
          h3 = this.state.homeScores.linescores.period[2].score;
          h4 = this.state.homeScores.linescores.period[3].score;
          break;
        default:
          h1 = 0;
          h2 = 0;
          h3 = 0;
          h4 = 0;
          break;
      }
    }
    aFinal = parseInt(a1) + parseInt(a2) + parseInt(a3) + parseInt(a4);
    hFinal = parseInt(h1) + parseInt(h2) + parseInt(h3) + parseInt(h4);
    return (
      <View style={styles.main}>
        <View style={styles.scoreHead}>
          <View style={styles.scoreboardHeader}>
            <Text style={{flex: 1}}> Q1 </Text>
            <Text style={{flex: 1}}> Q2 </Text>
            <Text style={{flex: 1}}> Q3 </Text>
            <Text style={{flex: 1}}> Q4 </Text>
            <Text style={{flex: 1}}> Final </Text>
          </View>
          <View style={styles.line} />
          <View style={styles.quarterScores}>
            <View style={styles.teamScores}>
              <View style={{borderRightWidth: 1, borderRightColor: '#000', flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <Text> {this.state.awayStats.abbreviation} </Text>
              </View>
              <View style={{borderRightWidth: 1, borderRightColor: '#000', flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <Text> {a1} </Text>
              </View>
              <View style={{borderRightWidth: 1, borderRightColor: '#000', flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <Text> {a2} </Text>
              </View>
              <View style={{borderRightWidth: 1, borderRightColor: '#000', flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <Text> {a3} </Text>
              </View>
              <View style={{borderRightWidth: 1, borderRightColor: '#000', flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <Text> {a4} </Text>
              </View>
              <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <Text> {aFinal} </Text>
              </View>
            </View>
            <View style={styles.line} />
            <View style={styles.teamScores}>
              <Text style={{flex: 1, alignSelf: 'center'}}> {this.state.homeStats.abbreviation} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {h1} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {h2} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {h3} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {h4} </Text>
              <Text style={{flex: 1, alignSelf: 'center'}}> {hFinal} </Text>
            </View>
          </View>
        </View>
        <View style={styles.line} />
        <View style={styles.head}>
          <TouchableHighlight onPress={() => Actions.TeamStats({team: this.state.awayStats.abbreviation.toLowerCase()})} underlayColor='#FFFFFF'>
            <Image
              style={styles.logo}
              source={TeamMap[this.state.awayStats.team_key.toLowerCase()].logo}
            />
          </TouchableHighlight>
          <View style={styles.vertical} />
          <Text> Stats </Text>
          <View style={styles.vertical} />
          <TouchableHighlight onPress={() => Actions.TeamStats({team: this.state.homeStats.abbreviation.toLowerCase()})} underlayColor='#FFFFFF'>
            <Image
              style={styles.logo}
              source={TeamMap[this.state.homeStats.team_key.toLowerCase()].logo}
            />
          </TouchableHighlight>
        </View>
        <View style={styles.line} />
        <View style={styles.body}>
          <View style={styles.statsColumn}>
            <Text> {this.state.awayStats.stats.points === '' ? '0' : this.state.awayStats.stats.points} </Text>
            <Text> {this.state.awayStats.stats.field_goals_made === '' ? '-' : this.state.awayStats.stats.field_goals_made + '/' + this.state.awayStats.stats.field_goals_attempted + '(' + this.state.awayStats.stats.field_goals_percentage + '%)'} </Text>
            <Text> {this.state.awayStats.stats.three_pointers_made === '' ? '-' : this.state.awayStats.stats.three_pointers_made + '/' + this.state.awayStats.stats.three_pointers_attempted + '(' + this.state.awayStats.stats.three_pointers_percentage + '%)'} </Text>
            <Text> {this.state.awayStats.stats.free_throws_made === '' ? '-' : this.state.awayStats.stats.free_throws_made + '/' + this.state.awayStats.stats.free_throws_attempted + '(' + this.state.awayStats.stats.free_throws_percentage + '%)'} </Text>
            <Text> {this.state.awayStats.stats.assists === '' ? '0' : this.state.awayStats.stats.assists} </Text>
            <Text> {this.state.awayStats.stats.rebounds_offensive === '' ? '0' : this.state.awayStats.stats.rebounds_offensive} </Text>
            <Text> {this.state.awayStats.stats.rebounds_defensive === '' ? '0' : this.state.awayStats.stats.rebounds_defensive} </Text>
            <Text> {this.state.awayStats.stats.steals === '' ? '0' : this.state.awayStats.stats.steals} </Text>
            <Text> {this.state.awayStats.stats.blocks === '' ? '0' : this.state.awayStats.stats.blocks} </Text>
            <Text> {this.state.awayStats.stats.turnovers === '' ? '0' : this.state.awayStats.stats.turnovers} </Text>
            <Text> {this.state.awayStats.stats.fouls === '' ? '0' : this.state.awayStats.stats.fouls} </Text>
          </View>
          <View style={styles.statsColumn}>
            <Text> Points </Text>
            <Text> Field Goals </Text>
            <Text> 3 Pointers </Text>
            <Text> Free Throws </Text>
            <Text> Assists </Text>
            <Text> O. Rebounds </Text>
            <Text> D. Rebounds </Text>
            <Text> Steals </Text>
            <Text> Blocks </Text>
            <Text> Turnovers </Text>
            <Text> Fouls </Text>
          </View>
          <View style={styles.statsColumn}>
            <Text> {this.state.homeStats.stats.points === '' ? '0' : this.state.homeStats.stats.points} </Text>
            <Text> {this.state.homeStats.stats.field_goals_made === '' ? '-' : this.state.homeStats.stats.field_goals_made + '/' + this.state.homeStats.stats.field_goals_attempted + '(' + this.state.homeStats.stats.field_goals_percentage + '%)'} </Text>
            <Text> {this.state.homeStats.stats.three_pointers_made === '' ? '-' : this.state.homeStats.stats.three_pointers_made + '/' + this.state.homeStats.stats.three_pointers_attempted + '(' + this.state.homeStats.stats.three_pointers_percentage + '%)'} </Text>
            <Text> {this.state.homeStats.stats.free_throws_made === '' ? '-' : this.state.homeStats.stats.free_throws_made + '/' + this.state.homeStats.stats.free_throws_attempted + '(' + this.state.homeStats.stats.free_throws_percentage + '%)'} </Text>
            <Text> {this.state.homeStats.stats.assists === '' ? '0' : this.state.homeStats.stats.assists} </Text>
            <Text> {this.state.homeStats.stats.rebounds_offensive === '' ? '0' : this.state.homeStats.stats.rebounds_offensive} </Text>
            <Text> {this.state.homeStats.stats.rebounds_defensive === '' ? '0' : this.state.homeStats.stats.rebounds_defensive} </Text>
            <Text> {this.state.homeStats.stats.steals === '' ? '0' : this.state.homeStats.stats.steals} </Text>
            <Text> {this.state.homeStats.stats.blocks === '' ? '0' : this.state.homeStats.stats.blocks} </Text>
            <Text> {this.state.homeStats.stats.turnovers === '' ? '0' : this.state.homeStats.stats.turnovers} </Text>
            <Text> {this.state.homeStats.stats.fouls === '' ? '0' : this.state.homeStats.stats.fouls} </Text>
          </View>
        </View>
      </View>
    )
  }
}

var styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: '#FCFCFC'
  },
  quarterScores: {
    flex: 1,
    // marginLeft: 15
  },
  scoreHead: {
      flex: 0.5
  },
  scoreboardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginLeft: 75,
    marginRight: 30,
    marginTop: 10,
    marginBottom: -5,
    flex: 0.5
  },
  head: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginLeft: 30,
    marginRight: 30,
    marginTop: 10,
    marginBottom: 10
  },
  logo: {
    width: 70,
    height: 70,
    shadowColor: '#000000',
    shadowOpacity: 0.8,
    shadowRadius: 1,
    shadowOffset: {
      height: 1,
      width: 0
    }
  },
  body: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: 12,
    marginRight: 12,
    marginTop: 10
  },
  line: {
    marginLeft: 5,
    marginRight: 5,
    height: 1,
    backgroundColor: '#000'
  },
  vertical: {
    marginLeft: 15,
    marginRight: 15,
    width: 1,
    marginTop: -10,
    marginBottom: -10,
    backgroundColor: '#000'
  },
  verticalScores: {
    marginLeft: 15,
    marginRight: 15,
    marginTop: -10,
    width: 1,
    backgroundColor: '#000'
  },
  teamScores: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: 40,
    marginRight: 30,
    flex: 1,
    // marginTop: 10,
    marginLeft: 20,
    // backgroundColor: 'red'
  },
  statsColumn: {
    flexDirection: 'column',
    alignItems: 'center',
    flex: 1
  }
});

module.exports = GameStatsTeam;
/* eslint-enable semi, space-before-function-paren, space-before-blocks*/
<|endoftext|>