<commit_before>
function navClicked(sourceLink) {
    let el = document.getElementById("#item"+sourceLink)
    if (el) {
        el.classList.toggle("in")
    }
}

let outputLetNav = [], totalTopics = 0;

function pageIsInSection(tree) {
    function processBranch(branch) {
        for (let k = 0; k < branch.length; k++) {
            if (branch[k].section) {
                processBranch(branch[k].section);
            } else {
                if (branch[k].path === pageURL && !branch[k].nosync) {
                    found = true;
                    break;
                }
            }
        }
    }

    let found = false;
    processBranch(tree);
    return found;
}

function walkTree(tree) {
    for (let j = 0; j < tree.length; j++) {
        totalTopics++;
        if (tree[j].section) {
            let sectionHasPath = pageIsInSection(tree[j].section);
            outputLetNav.push('
" + tree[j].sectiontitle + '');
            outputLetNav.push('
');
            walkTree(tree[j].section);
            outputLetNav.push("

");
        } else {
            // just a regular old topic; this is a leaf, not a branch; render a link!
            outputLetNav.push('
" + tree[j].title + "
")
        }
    }
}

function renderNav() {
    getJSON( "/js/toc.json", function( data ) {
        for (const item of data.horizontalnav) {
            if (item.path === pageURL || pageIsInSection(data[item.node])) {
                // This is the current section. Set the corresponding header-nav link
                // to active, and build the left-hand (vertical) navigation
                _('#'+item.node).closest("li").classList.add("active")
                walkTree(data[item.node]);
                _("#jsTOCLeftNav").innerHTML = outputLetNav.join("");
            }
        }
        // Scroll the current menu item into view. We actually pick the item *above*
        // the current item to give some headroom above
        scrollMenuItem("#jsTOCLeftNav a.currentPage")
    });
}

// Scroll the given menu item into view. We actually pick the item *above*
// the current item to give some headroom above
function scrollMenuItem(selector) {
    let item = document.querySelector(selector)
    if (item) {
        item = item.closest("li")
    }
    if (item) {
        item = item.previousElementSibling
    }
    if (item) {
        item.scrollIntoView(true)
        if (window.location.hash.length < 2) {
            // Scrolling the side-navigation may scroll the whole page as well
            // this is a dirty hack to scroll the main content back to the top
            // if we're not on a specific anchor
            document.querySelector("main.col-content").scrollIntoView(true)
        }
    }
}

function highlightRightNav(heading) {
    $("#my_toc a.active").removeClass("active");

    if (heading !== "title") {
        $("#my_toc a[href='#" + heading + "']").addClass("active");
    }
}

var currentHeading = "";
$(window).scroll(function () {
    var headingPositions = [];
    $("h1, h2, h3, h4, h5, h6").each(function () {
        if (this.id === "") this.id = "title";
        headingPositions[this.id] = this.getBoundingClientRect().top;
    });
    headingPositions.sort();
    // the headings have all been grabbed and sorted in order of their scroll
    // position (from the top of the page). First one is toppermost.
    for (var key in headingPositions) {
        if (!headingPositions.hasOwnProperty(key)) {
            continue;
        }
        if (headingPositions[key] > 0 && headingPositions[key] < 200) {
            if (currentHeading !== key) {
                // a new heading has scrolled to within 200px of the top of the page.
                // highlight the right-nav entry and de-highlight the others.
                highlightRightNav(key);
                currentHeading = key;
            }
            break;
        }
    }
});

var navHeight = $(".navbar").outerHeight(true) + 80;

$(document.body).scrollspy({
    target: "#leftCol",
    offset: navHeight
});

function loadHash(hashObj) {
    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $("html, body").animate({scrollTop: $(hashObj).offset().top - 80}, 800);
}

$(document).ready(function () {
    // Add smooth scrolling to all links
    $(".toc-nav a").on("click", function (event) {
        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();

            // Store hash
            var hash = this.hash;
            loadHash(hash);

            // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
        }
    });
    if (window.location.hash) loadHash(window.location.hash);
});

$(document).ready(function () {
    // Add smooth scrolling to all links
    $(".nav-sidebar ul li a").on("click", function (event) {

        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();

            // Store hash
            var hash = this.hash;

            // Using jQuery's animate() method to add smooth page scroll
            // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
            $("html, body").animate({
                scrollTop: $(hash).offset().top - 80
            }, 800, function () {
                // Add hash (#) to URL when done scrolling (default click behavior)
                window.location.hash = hash;
            });
        }
    });
});

function initNavToggle() {
    $("#menu-toggle").click(function (e) {
        e.preventDefault();
        $(".wrapper").toggleClass("right-open");
        $(".col-toc").toggleClass("col-toc-hidden");
    });

    $(".navbar-toggle").click(function () {
        $("#sidebar-nav").each(function () {
            $(this).toggleClass("hidden-sm");
            $(this).toggleClass("hidden-xs");
        });
    });
}

ready(() => {
    renderNav()
    initNavToggle()
    $('[data-toggle="tooltip"]').tooltip()

    // sync tabs with the same data-group
    $(".nav-tabs > li > a").click(function () {
        const group = $(this).attr("data-group");
        $(`.nav-tabs > li > a[data-group='${ group }']`).tab("show");
    });
});
<commit_msg>js/docs.js: small cleanup in walkTree() function<commit_after>
function navClicked(sourceLink) {
    let el = document.getElementById("#item"+sourceLink)
    if (el) {
        el.classList.toggle("in")
    }
}

let outputLetNav = [], totalTopics = 0;

function pageIsInSection(tree) {
    function processBranch(branch) {
        for (let k = 0; k < branch.length; k++) {
            if (branch[k].section) {
                processBranch(branch[k].section);
            } else {
                if (branch[k].path === pageURL && !branch[k].nosync) {
                    found = true;
                    break;
                }
            }
        }
    }

    let found = false;
    processBranch(tree);
    return found;
}

function walkTree(tree) {
    for (const page of tree) {
        totalTopics++;
        if (page.section) {
            let sectionHasPath = pageIsInSection(page.section);
            outputLetNav.push('
" + page.sectiontitle + '');
            outputLetNav.push('
');
            walkTree(page.section);
            outputLetNav.push("

");
        } else {
            // just a regular old topic; this is a leaf, not a branch; render a link!
            outputLetNav.push('
" + page.title + "
")
        }
    }
}

function renderNav() {
    getJSON( "/js/toc.json", function( data ) {
        for (const item of data.horizontalnav) {
            if (item.path === pageURL || pageIsInSection(data[item.node])) {
                // This is the current section. Set the corresponding header-nav link
                // to active, and build the left-hand (vertical) navigation
                _('#'+item.node).closest("li").classList.add("active")
                walkTree(data[item.node]);
                _("#jsTOCLeftNav").innerHTML = outputLetNav.join("");
            }
        }
        // Scroll the current menu item into view. We actually pick the item *above*
        // the current item to give some headroom above
        scrollMenuItem("#jsTOCLeftNav a.currentPage")
    });
}

// Scroll the given menu item into view. We actually pick the item *above*
// the current item to give some headroom above
function scrollMenuItem(selector) {
    let item = document.querySelector(selector)
    if (item) {
        item = item.closest("li")
    }
    if (item) {
        item = item.previousElementSibling
    }
    if (item) {
        item.scrollIntoView(true)
        if (window.location.hash.length < 2) {
            // Scrolling the side-navigation may scroll the whole page as well
            // this is a dirty hack to scroll the main content back to the top
            // if we're not on a specific anchor
            document.querySelector("main.col-content").scrollIntoView(true)
        }
    }
}

function highlightRightNav(heading) {
    $("#my_toc a.active").removeClass("active");

    if (heading !== "title") {
        $("#my_toc a[href='#" + heading + "']").addClass("active");
    }
}

var currentHeading = "";
$(window).scroll(function () {
    var headingPositions = [];
    $("h1, h2, h3, h4, h5, h6").each(function () {
        if (this.id === "") this.id = "title";
        headingPositions[this.id] = this.getBoundingClientRect().top;
    });
    headingPositions.sort();
    // the headings have all been grabbed and sorted in order of their scroll
    // position (from the top of the page). First one is toppermost.
    for (var key in headingPositions) {
        if (!headingPositions.hasOwnProperty(key)) {
            continue;
        }
        if (headingPositions[key] > 0 && headingPositions[key] < 200) {
            if (currentHeading !== key) {
                // a new heading has scrolled to within 200px of the top of the page.
                // highlight the right-nav entry and de-highlight the others.
                highlightRightNav(key);
                currentHeading = key;
            }
            break;
        }
    }
});

var navHeight = $(".navbar").outerHeight(true) + 80;

$(document.body).scrollspy({
    target: "#leftCol",
    offset: navHeight
});

function loadHash(hashObj) {
    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $("html, body").animate({scrollTop: $(hashObj).offset().top - 80}, 800);
}

$(document).ready(function () {
    // Add smooth scrolling to all links
    $(".toc-nav a").on("click", function (event) {
        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();

            // Store hash
            var hash = this.hash;
            loadHash(hash);

            // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
        }
    });
    if (window.location.hash) loadHash(window.location.hash);
});

$(document).ready(function () {
    // Add smooth scrolling to all links
    $(".nav-sidebar ul li a").on("click", function (event) {

        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();

            // Store hash
            var hash = this.hash;

            // Using jQuery's animate() method to add smooth page scroll
            // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
            $("html, body").animate({
                scrollTop: $(hash).offset().top - 80
            }, 800, function () {
                // Add hash (#) to URL when done scrolling (default click behavior)
                window.location.hash = hash;
            });
        }
    });
});

function initNavToggle() {
    $("#menu-toggle").click(function (e) {
        e.preventDefault();
        $(".wrapper").toggleClass("right-open");
        $(".col-toc").toggleClass("col-toc-hidden");
    });

    $(".navbar-toggle").click(function () {
        $("#sidebar-nav").each(function () {
            $(this).toggleClass("hidden-sm");
            $(this).toggleClass("hidden-xs");
        });
    });
}

ready(() => {
    renderNav()
    initNavToggle()
    $('[data-toggle="tooltip"]').tooltip()

    // sync tabs with the same data-group
    $(".nav-tabs > li > a").click(function () {
        const group = $(this).attr("data-group");
        $(`.nav-tabs > li > a[data-group='${ group }']`).tab("show");
    });
});
<|endoftext|>


<commit_before>/*
 *
 * swapStyleSheet*********************************************************************
 *
 */

$("#menu-toggle").click(function(e) {
        e.preventDefault();
        $("#wrapper").toggleClass("toggled");
    });

var navHeight = $('.navbar').outerHeight(true) + 80;

$(document.body).scrollspy({
	target: '#leftCol',
	offset: navHeight
});

$(document).ready(function(){
  // Add smooth scrolling to all links
  $(".toc-nav a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

$(document).ready(function(){
  // Add smooth scrolling to all links
  $(".nav-sidebar ul li a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

/*
 *
 * make dropdown show on hover *********************************************************************
 *
 */

$('ul.nav li.dropdown').hover(function() {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function() {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});

/*
 *
 * swapStyleSheet*********************************************************************
 *
 */

function swapStyleSheet(sheet) {
    document.getElementById('pagestyle').setAttribute('href', sheet);
}

$('#switch-style').change(function() {

    if ($(this).is(':checked')) {
        swapStyleSheet('/css/style-alt.css');

    } else {
        swapStyleSheet('/css/style.css');

    }
});

/*
 *
 * TEMP HACK For side menu*********************************************************************
 *
 */

$('.nav-sidebar ul li a').click(function() {
    $(this).addClass('collapse').siblings().toggleClass('in');
});

if($('.nav-sidebar ul a.active').length != 0)
{
  $('.nav-sidebar ul').click(function() {
      $(this).addClass('collapse in').siblings;
  });
}
<commit_msg>Add cookie saving for day/night mode<commit_after>// Cookie functions
function createCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}
if (readCookie("night") == "true") {
  document.getElementById('pagestyle').setAttribute('href', '/css/style-alt.css');
  $('#switch-style').prop('checked', true);
} else {
  document.getElementById('pagestyle').setAttribute('href', '/css/style.css');
  $('#switch-style').prop('checked', false);
}

/*
 *
 * swapStyleSheet*********************************************************************
 *
 */

$("#menu-toggle").click(function(e) {
        e.preventDefault();
        $("#wrapper").toggleClass("toggled");
    });

var navHeight = $('.navbar').outerHeight(true) + 80;

$(document.body).scrollspy({
	target: '#leftCol',
	offset: navHeight
});

$(document).ready(function(){
  // Add smooth scrolling to all links
  $(".toc-nav a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

$(document).ready(function(){
  // Add smooth scrolling to all links
  $(".nav-sidebar ul li a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

/*
 *
 * make dropdown show on hover *********************************************************************
 *
 */

$('ul.nav li.dropdown').hover(function() {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function() {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});

/*
 *
 * swapStyleSheet*********************************************************************
 *
 */

function swapStyleSheet(sheet) {
    document.getElementById('pagestyle').setAttribute('href', sheet);
}

$('#switch-style').change(function() {

    if ($(this).is(':checked')) {
        swapStyleSheet('/css/style-alt.css');
        createCookie("night",true,999)
    } else {
        swapStyleSheet('/css/style.css');
        eraseCookie("night")
    }
});

/*
 *
 * TEMP HACK For side menu*********************************************************************
 *
 */

$('.nav-sidebar ul li a').click(function() {
    $(this).addClass('collapse').siblings().toggleClass('in');
});

if($('.nav-sidebar ul a.active').length != 0)
{
  $('.nav-sidebar ul').click(function() {
      $(this).addClass('collapse in').siblings;
  });
}
<|endoftext|>


<commit_before>/**
 * Created by huiji-001 on 2015/12/15.
 */
function addCategory(category){
    var api = new mw.Api()
    api.postWithToken( "edit", {
        action: "edit",
        title: mw.config.get( "wgPageName" ),
        summary: "快速添加分类",
        appendtext: category
    } ).done( function( result, jqXHR ) {
        var a ='';
        var b = category.split(']][[Category:');
        b[0] = b[0].substring(11);
        b[b.length-1] = b[b.length-1].substring(0,b[b.length-1].length-2);
        b.forEach(function(i){
            a += '
'+i+'
'
        })
        $('#catlinks .last').before(a);
        $('#add-category-btn').popover('hide');
    } ).fail( function( code, result ) {
        if ( code === "http" ) {
            console.log( "HTTP error: " + result.textStatus ); // result.xhr contains the jqXHR object
        } else if ( code === "ok-but-empty" ) {
            mw.log( "Got an empty response from the server" );
        } else {
            mw.log( "API error: " + code );
        }
    } );
}
function addSpan(){
    var val = $('.edit-field input').val();
    var html = '
'+val+'
';
    if(val == ''||val == ' '){
        mw.notification.notify('分类不能为空，请重新输入');
        $('.edit-field input').val('');
        return;
    }
    $('#mw-normal-catlinks>ul>li:not(.last)>a,.edit-span').each(function(){
        if($(this).text()==val){
            mw.notification.notify('分类不能重复，请重新输入');
            $('.edit-field input').val('');
            return;
        }
    });
    $('.edit-field').before(html);
    $('.edit-field input').val('');
}
function getData(){
    var data='';
    $('.edit-choices .edit-span').each(function(){
        data += '[[Category:'+$(this).text()+']]';
    });
    return data;
}
$(function(){
    if (mw.config.get('wgUserName')==''){
        return;
    }
    var addbtn = '
添加分类
';
    var content = '
' +
        '
'+
        '
'+
        '
<input type="text">
'+
        '
'+
        '
'+
        '
' +
        '<button class="btn btn-primary edit-submit"></button> ' +
        '<button type="button" class="btn edit-cancel"></button>' +
        '
' +
        '
';
    $('#mw-normal-catlinks>ul').append(addbtn);
    $('#add-category-btn').popover({title:'添加分类',content:content,html:true});
    $('#mw-normal-catlinks').on('keyup','.edit-field input',function(event){
       if(event.keyCode == 13){
           addSpan();
       }
    }).on('click','.edit-input i',function(){
        $(this).parents('.edit-choices li').remove();
    }).on('click','.edit-input',function(){
        $('.edit-field input').focus();
    }).on('click','.edit-submit',function(e){
        e.stopPropagation();
        var data = getData();
        addCategory(data);
    }).on('click','.edit-cancel',function(){
        $('#add-category-btn').popover('hide');
    });
});
<commit_msg>Update edit.js<commit_after>/**
 * Created by huiji-001 on 2015/12/15.
 */
function addCategory(category){
    var api = new mw.Api()
    api.postWithToken( "edit", {
        action: "edit",
        title: mw.config.get( "wgPageName" ),
        summary: "快速添加分类",
        appendtext: category
    } ).done( function( result, jqXHR ) {
        var a ='';
        var b = category.split(']][[Category:');
        b[0] = b[0].substring(11);
        b[b.length-1] = b[b.length-1].substring(0,b[b.length-1].length-2);
        b.forEach(function(i){
            a += '
'+i+'
'
        })
        $('#catlinks .last').before(a);
        $('#add-category-btn').popover('hide');
    } ).fail( function( code, result ) {
        if ( code === "http" ) {
            console.log( "HTTP error: " + result.textStatus ); // result.xhr contains the jqXHR object
        } else if ( code === "ok-but-empty" ) {
            mw.log( "Got an empty response from the server" );
        } else {
            mw.log( "API error: " + code );
        }
    } );
}
function addSpan(){
    var val = $('.edit-field input').val();
    var html = '
'+val+'
';
    if(val == ''||val == ' '){
        mw.notification.notify('分类不能为空，请重新输入');
        $('.edit-field input').val('');
        return;
    }
    $('#mw-normal-catlinks>ul>li:not(.last)>a,.edit-span').each(function(){
        if($(this).text()==val){
            mw.notification.notify('分类不能重复，请重新输入');
            $('.edit-field input').val('');
            return;
        }
    });
    $('.edit-field').before(html);
    $('.edit-field input').val('');
}
function getData(){
    var data='';
    $('.edit-choices .edit-span').each(function(){
        data += '[[Category:'+$(this).text()+']]';
    });
    return data;
}
$(function(){
    if (mw.config.get('wgUserName')==''){
        return;
    }
    var addbtn = '
添加分类
';
    var content = '
' +
        '
'+
        '
'+
        '
<input type="text">
'+
        '
'+
        '
'+
        '
' +
        '
可输入多个，在每个分类后轻敲回车。
'+
        '<button class="btn btn-primary edit-submit"></button> ' +
        '<button type="button" class="btn edit-cancel"></button>' +
        '
' +
        '
';
    $('#mw-normal-catlinks>ul').append(addbtn);
    $('#add-category-btn').popover({title:'添加分类',content:content,html:true});
    $('#mw-normal-catlinks').on('keyup','.edit-field input',function(event){
       if(event.keyCode == 13){
           addSpan();
       }
    }).on('click','.edit-input i',function(){
        $(this).parents('.edit-choices li').remove();
    }).on('click','.edit-input',function(){
        $('.edit-field input').focus();
    }).on('click','.edit-submit',function(e){
        e.stopPropagation();
        var data = getData();
        addCategory(data);
    }).on('click','.edit-cancel',function(){
        $('#add-category-btn').popover('hide');
    });
});
<|endoftext|>


<commit_before>import React from 'react'

export const getDefaultProps = prop =>
  `default${prop[0].toUpperCase()}${prop.substring(1)}`

export default (propsMapping = {}, instanceMethods = []) => Component =>
  class ControllableComponent extends React.PureComponent {
    controllableHandlers = {}

    constructor(props) {
      super(props)

      const state = {}

      Object.keys(propsMapping).forEach(prop => {
        const defaultPropName = getDefaultProps(prop)
        let defaultValue = props[defaultPropName]

        if (defaultValue === undefined && Component.defaultProps) {
          defaultValue = Component.defaultProps[defaultPropName]
        }

        state[prop] = props[prop] === undefined
          ? defaultValue
          : props[prop]

        this.controllableHandlers[prop] = value => {
          if (this.state[prop] === value) {
            return
          }

          if (props[prop] === undefined) {
            this.setState({ [prop]: value })
          }

          if (props[propsMapping[prop]]) {
            props[propsMapping[prop]](value)
          }
        }
      })

      this.state = state

      instanceMethods.forEach(method => {
        this[method] = Component.prototype[method]
      })
    }

    componentWillReceiveProps(nextProps) {
      const newState = {}

      Object.keys(propsMapping).forEach(prop => {
        if (this.props[prop] !== nextProps[prop]) {
          newState[prop] = nextProps[prop]
        }
      })

      if (Object.keys(newState).length > 0) {
        this.setState(newState)
      }
    }

    render() {
      const props = {}

      Object.keys(propsMapping).forEach(prop => {
        props[prop] = this.state[prop]
        props[propsMapping[prop]] = this.controllableHandlers[prop]
      })

      return (
        <Component
          {...this.props}
          {...props}
        />
      )
    }
  }
<commit_msg>Fixes methods pass through<commit_after>import React from 'react'

export const getDefaultProps = prop =>
  `default${prop[0].toUpperCase()}${prop.substring(1)}`

export default (propsMapping = {}, instanceMethods = []) => Component =>
  class ControllableComponent extends React.PureComponent {
    controllableHandlers = {}

    constructor(props) {
      super(props)

      const state = {}

      Object.keys(propsMapping).forEach(prop => {
        const defaultPropName = getDefaultProps(prop)
        let defaultValue = props[defaultPropName]

        if (defaultValue === undefined && Component.defaultProps) {
          defaultValue = Component.defaultProps[defaultPropName]
        }

        state[prop] = props[prop] === undefined
          ? defaultValue
          : props[prop]

        this.controllableHandlers[prop] = value => {
          if (this.state[prop] === value) {
            return
          }

          if (props[prop] === undefined) {
            this.setState({ [prop]: value })
          }

          if (props[propsMapping[prop]]) {
            props[propsMapping[prop]](value)
          }
        }
      })

      this.state = state

      instanceMethods.forEach(method => {
        this[method] = (...args) => (
          this.controlled[method](...args)
        )
      })
    }

    componentWillReceiveProps(nextProps) {
      const newState = {}

      Object.keys(propsMapping).forEach(prop => {
        if (this.props[prop] !== nextProps[prop]) {
          newState[prop] = nextProps[prop]
        }
      })

      if (Object.keys(newState).length > 0) {
        this.setState(newState)
      }
    }

    controlledRef = controlled => {
      this.controlled = controlled
    }

    render() {
      const props = {}

      Object.keys(propsMapping).forEach(prop => {
        props[prop] = this.state[prop]
        props[propsMapping[prop]] = this.controllableHandlers[prop]
      })

      return (
        <Component
          {...this.props}
          {...props}
          ref={this.controlledRef}
        />
      )
    }
  }
<|endoftext|>


<commit_before>const utils = require('../lib/modelUtils');

const BaseModel = require('./_base');

/**
 *
 */
function Code (data, parent) {
  BaseModel.call(this, data, parent);
}

Object.defineProperty(Code, 'pathIdentifier', {value: 'code'});

utils.initModel(Code, '/codes', {}, BaseModel);

exports = module.exports = Code;
<commit_msg>Claim Code fixes that should have already gone<commit_after>const utils = require('../lib/modelUtils');

const BaseModel = require('./_base');

/**
 *
 */
function ClaimCode (data, parent) {
  BaseModel.call(this, data, parent);
}

ClaimCode.parseResponse = function parseResponse (data) {
  if (data.badge) {
    if (data.claimCodes) {
      data.claimCodes = data.claimCodes.map(function (code) {
        code.badge = data.badge;
        return code;
      });
    } else if (data.claimCode) {
      data.claimCode.badge = data.badge;
    }
  }

  return data;
}

Object.defineProperty(ClaimCode, 'pathIdentifier', {value: 'code'});

utils.initModel(ClaimCode, '/codes', {
  claim: function claimClaimCode (email, callback) {
    const options = {
      path: this._path + '/claim',
      filter: 'claimCode',
      generator: new utils.Generator(ClaimCode, this._heritage.badge),
      data: {email: email}
    };

    this._remote.post(options, callback);
  }
}, BaseModel);

exports = module.exports = ClaimCode;
<|endoftext|>


<commit_before>function nedface() {
    var image = document.getElementById('myImage');
    if (image.src.match("http://isaiahpatton.github.io/ned/imgs/ned.gif")) {
        image.src = "http://isaiahpatton.github.io/ned/imgs/ned.jpg";
    } else {
        image.src = "http://isaiahpatton.github.io/ned/imgs/ned.gif";
    }
}
<commit_msg>Update face.js<commit_after>function nedface() {
    var image = document.getElementById('myImage');
    if (image.src.match("http://i.imgur.com/AP5imrD.png")) {
        image.src = "http://isaiahpatton.github.io/ned/imgs/ned.gif";
    } else {
        image.src = "http://i.imgur.com/AP5imrD.png";
    }
}
<|endoftext|>


<commit_before>$(document).ready(main);

 function main()

{
  $("#submit").click(function(event){
var slt_weather_val=$("#slt_weather").val();
var humor_val=$("#humor").val();

//added a couple options to show I understand the concept of each form of logic. This could be expanded using this same logic/form though at that point it's just typing. I could refactor this with new stuff, but that isn't in the scope of this assignment.
if (slt_weather_val === 'rain') && (humor_val === 'fantasy' || 'dead') {
 alert("Portland has everything you need!");
} else if (slt_weather_val === 'sea') && (humor_val === 'fantasy') {
  alert("Storm Cove Will sooth your melancholy soul.");
} else if (slt_weather_val === 'sea') && (humor_val === 'dead') {
  alert("Set your sails for The Burmuda Triangle.");
} else if (slt_weather_val === 'indoors') {
  alert("You should go to the Catacombs Of Paris.");
}
  });
}

// then i need to show with an if else the tags
// #portland, #storm, #catacombs {
// display: none;

//     }

<commit_msg>update brackets.<commit_after>$(document).ready(main);

 function main()

{
  $("#submit").click(function(event){
var slt_weather_val=$("#slt_weather").val();
var humor_val=$("#humor").val();

//added a couple options to show I understand the concept of each form of logic. This could be expanded using this same logic/form though at that point it's just typing. I could refactor this with new stuff, but that isn't in the scope of this assignment.
if ((slt_weather_val === 'rain') && (humor_val === 'fantasy' || humor_val === 'dead')) {
 alert("Portland has everything you need!");
} else if ((slt_weather_val === 'sea') && (humor_val === 'fantasy')) {
  alert("Storm Cove Will sooth your melancholy soul.");
} else if ((slt_weather_val === 'sea') && (humor_val === 'dead')) {
  alert("Set your sails for The Burmuda Triangle.");
} else if (slt_weather_val === 'indoors') {
  alert("You should go to the Catacombs Of Paris.");
}
  });
}

// then i need to show with an if else the tags
// #portland, #storm, #catacombs {
// display: none;

//     }

<|endoftext|>


<commit_before>(function($) {
  $(document).ready(function() {
    $(".signupForm").submit(function(event) {
      var formData = {
        'phoneNumber': $('input[name=phoneNumber]').val()
      }

      $.ajax({
        type: 'POST',
        url: 'https://autolotto-backend-production.herokuapp.com/api/v1/pre/signup',
        data: formData,
        dataType: 'json',
        crossDomain: true,
        encode: true
      }).done(function() {
        window.location.href = "/confirmation";
      });

      event.preventDefault();
      window.location.href = "http://a6n2jd5.autolotto.com/confirmation/";
    });
  });
})(jQuery);
<commit_msg>redirect the PARENT location<commit_after>(function($) {
  $(document).ready(function() {
    $(".signupForm").submit(function(event) {
      var formData = {
        'phoneNumber': $('input[name=phoneNumber]').val()
      }

      $.ajax({
        type: 'POST',
        url: 'https://autolotto-backend-production.herokuapp.com/api/v1/pre/signup',
        data: formData,
        dataType: 'json',
        crossDomain: true,
        encode: true
      }).done(function() {
        window.location.href = "/confirmation";
      });

      event.preventDefault();
      window.parent.location.href = "http://a6n2jd5.autolotto.com/confirmation/";
    });
  });
})(jQuery);
<|endoftext|>


<commit_before>d3.selection.prototype.moveToFront = function() {
  return this.each(function(){
    this.parentNode.appendChild(this);
  });
};

function setKodairaDimension(value) {
  if (value == -1)
    $("output#kodaira-output").text("$-\\infty$");
  else
    $("output#kodaira-output").text(value);

  var className = "kodaira-" + value;
  if (value == -1)
    className = "kodaira-infty";

  console.log(d3.selectAll("circle"));
  d3.selectAll("circle")
    .classed("inactive", true);

  var activeNodes = d3.selectAll("circle")
    .filter(function(d, i) { return d[2] == value; })
  activeNodes.classed("inactive", false);
  activeNodes.moveToFront();

  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}

$(document).ready(function() {
  setKodairaDimension("-1");
});

<commit_msg>Small improvement to comments<commit_after>d3.selection.prototype.moveToFront = function() {
  return this.each(function(){
    this.parentNode.appendChild(this);
  });
};

function setKodairaDimension(value) {
  if (value == -1)
    $("output#kodaira-output").text("$-\\infty$");
  else
    $("output#kodaira-output").text(value);

  var className = "kodaira-" + value;
  if (value == -1)
    className = "kodaira-infty";

  // make all nodes inactive
  d3.selectAll("circle")
    .classed("inactive", true);

  // make the nodes of the correct Kodaira dimension active
  var activeNodes = d3.selectAll("circle")
    .filter(function(d, i) { return d[2] == value; })
  activeNodes.classed("inactive", false);
  // SVG doesn't have a z-index so we change the order of elements
  activeNodes.moveToFront();

  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}

$(document).ready(function() {
  setKodairaDimension("-1");
});

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import AnimateHeight from 'react-animate-height';
import classnames from 'classnames';
import Icon from '../../base/icons/Icon';

import genId from '../../util/generateAlphaName';

// Note: DrawerPanel relies on a parent (Drawer) with ThemeProvider wrapping it
const PanelWrapper = styled.div`
  border-bottom: 1px solid ${props => props.theme.colors.gray3};
`;

const PanelButton = styled.button`
  background: none;
  border: 0;
  color: ${props => props.theme.colors.primary};
  cursor: pointer;
  display: flex;
  font-size: 18px;
  justify-content: space-between;
  padding: 10px 15px;
  width: 100%;

  &:hover {
    background-color: ${props => props.theme.colors.gray2};
    color: ${props => props.theme.brandColors.vbBlue};
  }
`;

const PanelIcon = styled(Icon)`
  margin-right: 0.4em;
  position: relative;
  top: -2px;
`;

const PanelBody = styled(({ noPadding, ...rest }) => (
  <AnimateHeight {...rest} />
))`
  background-color: ${props => props.theme.colors.white};
  color: ${props => props.theme.colors.gray9};

  > div {
    border-bottom: 4px solid ${props => props.theme.colors.gray3};
    padding: ${props => (props.noPadding ? '0' : '10px 10px 10px 40px')};
  }
`;

const DrawerPanel = props => {
  const {
    children,
    className,
    closedIconName,
    isOpen,
    noPadding,
    onItemClick,
    openedIconName,
    title,
    titleAside
  } = props;

  const headingAriaId = genId();
  const regionAriaId = genId();
  const aside = titleAside && {titleAside};

  return (
    <PanelWrapper className={classnames('es-drawer__panel', className)}>

        <PanelButton
          aria-expanded={isOpen}
          aria-controls={regionAriaId}
          onClick={() => onItemClick()}
        >

            <PanelIcon name={isOpen ? openedIconName : closedIconName} />
            {title}

          {aside}
        </PanelButton>

      <PanelBody
        aria-labelledby={headingAriaId}
        className="es-drawer__body"
        duration={300}
        height={isOpen ? 'auto' : 0}
        id={regionAriaId}
        noPadding={noPadding}
        role="region"
      >
        {children}
      </PanelBody>
    </PanelWrapper>
  );
};

DrawerPanel.propTypes = {
  children: PropTypes.any.isRequired,
  /** Add additional CSS classes to the drawer item element */
  className: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
  /** @ignore */
  closedIconName: PropTypes.string,
  /** Title text displayed next to the open/close icon */
  title: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.node
  ]).isRequired,
  /** Aside text/content displayed on the right side of the panel title */
  titleAside: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  /** @ignore */
  isOpen: PropTypes.bool,
  /** Removes the default padding from the panel body */
  noPadding: PropTypes.bool,
  /** @ignore */
  onItemClick: PropTypes.func,
  /** @ignore */
  openedIconName: PropTypes.string
};

DrawerPanel.defaultProps = {
  isOpen: false,
  noPadding: false,
  className: null,
  closedIconName: null,
  titleAside: null,
  onItemClick: () => {},
  openedIconName: null
};

export default DrawerPanel;
<commit_msg>Using noop in DrawerPanel.<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import AnimateHeight from 'react-animate-height';
import classnames from 'classnames';
import { noop } from 'lodash';
import Icon from '../../base/icons/Icon';

import genId from '../../util/generateAlphaName';

// Note: DrawerPanel relies on a parent (Drawer) with ThemeProvider wrapping it
const PanelWrapper = styled.div`
  border-bottom: 1px solid ${props => props.theme.colors.gray3};
`;

const PanelButton = styled.button`
  background: none;
  border: 0;
  color: ${props => props.theme.colors.primary};
  cursor: pointer;
  display: flex;
  font-size: 18px;
  justify-content: space-between;
  padding: 10px 15px;
  width: 100%;

  &:hover {
    background-color: ${props => props.theme.colors.gray2};
    color: ${props => props.theme.brandColors.vbBlue};
  }
`;

const PanelIcon = styled(Icon)`
  margin-right: 0.4em;
  position: relative;
  top: -2px;
`;

const PanelBody = styled(({ noPadding, ...rest }) => (
  <AnimateHeight {...rest} />
))`
  background-color: ${props => props.theme.colors.white};
  color: ${props => props.theme.colors.gray9};

  > div {
    border-bottom: 4px solid ${props => props.theme.colors.gray3};
    padding: ${props => (props.noPadding ? '0' : '10px 10px 10px 40px')};
  }
`;

const DrawerPanel = props => {
  const {
    children,
    className,
    closedIconName,
    isOpen,
    noPadding,
    onItemClick,
    openedIconName,
    title,
    titleAside
  } = props;

  const headingAriaId = genId();
  const regionAriaId = genId();
  const aside = titleAside && {titleAside};

  return (
    <PanelWrapper className={classnames('es-drawer__panel', className)}>

        <PanelButton
          aria-expanded={isOpen}
          aria-controls={regionAriaId}
          onClick={() => onItemClick()}
        >

            <PanelIcon name={isOpen ? openedIconName : closedIconName} />
            {title}

          {aside}
        </PanelButton>

      <PanelBody
        aria-labelledby={headingAriaId}
        className="es-drawer__body"
        duration={300}
        height={isOpen ? 'auto' : 0}
        id={regionAriaId}
        noPadding={noPadding}
        role="region"
      >
        {children}
      </PanelBody>
    </PanelWrapper>
  );
};

DrawerPanel.propTypes = {
  children: PropTypes.any.isRequired,
  /** Add additional CSS classes to the drawer item element */
  className: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
  /** @ignore */
  closedIconName: PropTypes.string,
  /** Title text displayed next to the open/close icon */
  title: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.node
  ]).isRequired,
  /** Aside text/content displayed on the right side of the panel title */
  titleAside: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  /** @ignore */
  isOpen: PropTypes.bool,
  /** Removes the default padding from the panel body */
  noPadding: PropTypes.bool,
  /** @ignore */
  onItemClick: PropTypes.func,
  /** @ignore */
  openedIconName: PropTypes.string
};

DrawerPanel.defaultProps = {
  isOpen: false,
  noPadding: false,
  className: null,
  closedIconName: null,
  titleAside: null,
  onItemClick: noop,
  openedIconName: null
};

export default DrawerPanel;
<|endoftext|>


<commit_before><commit_msg>Fix #41, updated VB.NET rule, pt2<commit_after><|endoftext|>


<commit_before>var config = require('../config');

/**
 * A block or signoff in a comment.
 */
function Signature(data) {
   this.data = {
      number:           data.number,
      user:             data.user,
      user_id:          data.user_id,
      type:             data.type,
      created_at:       data.created_at,
      active:           data.active,
      comment_id:       data.comment_id
   };
}

/**
 * Parses a GitHub comment and returns an array of Signature objects.
 * Returns an empty array if the comment did not contain any of our tags.
 */
Signature.parseComment = function parseComment(comment, pullNumber) {
   var signatures = [];
   config.tags.forEach(function(tag) {
      if (hasTag(comment.body, tag)) {
         signatures.push(new Signature({
            number: pullNumber,
            user: comment.user.login,
            // avatarUrl = "https://avatars.githubusercontent.com/u/" + user_id
            user_id: comment.user.id,
            type: tag,
            created_at: comment.created_at,
            // `active` is unknown until all the signatures have been created
            // and parsed. See Pull.prototype.updateActiveSignatures()
            active: true,
            comment_id: comment.id
         }));
      }
   });

   return signatures;
}

/**
 * Takes an object representing a DB row, and returns an object which mimics
 * a GitHub API response which may be used to initialize an instance of this
 * Signature object.
 */
Signature.getFromDB = function(data) {
   return {
      number:     data.number,
      user:       data.user,
      type:       data.type,
      created_at: data.created_at,
      active:     data.active,
      comment_id: data.comment_id
   };
}

/**
 * A compare function for Signatures that can be passed to a custom sorter.
 * Sorts signatures in chronologically
 */
Signature.compare = function(a, b) {
   return Date.parse(a.data.created_at) - Date.parse(b.data.created_at);
};

module.exports = Signature;

var tagRegExps = {};

function hasTag(body, tagName) {
   if (typeof tagRegExps[tagName] === 'undefined') {
      // e.g. "dev_block :+1:" or " CR :asdf:."
      tagRegExps[tagName]
         = new RegExp("\\b" + tagName + " :[^\n:]+:");
   }
   return tagRegExps[tagName].test(body);
}
<commit_msg>Make tags in comments case-insensitive<commit_after>var config = require('../config');

/**
 * A block or signoff in a comment.
 */
function Signature(data) {
   this.data = {
      number:           data.number,
      user:             data.user,
      user_id:          data.user_id,
      type:             data.type,
      created_at:       data.created_at,
      active:           data.active,
      comment_id:       data.comment_id
   };
}

/**
 * Parses a GitHub comment and returns an array of Signature objects.
 * Returns an empty array if the comment did not contain any of our tags.
 */
Signature.parseComment = function parseComment(comment, pullNumber) {
   var signatures = [];
   config.tags.forEach(function(tag) {
      if (hasTag(comment.body, tag)) {
         signatures.push(new Signature({
            number: pullNumber,
            user: comment.user.login,
            // avatarUrl = "https://avatars.githubusercontent.com/u/" + user_id
            user_id: comment.user.id,
            type: tag,
            created_at: comment.created_at,
            // `active` is unknown until all the signatures have been created
            // and parsed. See Pull.prototype.updateActiveSignatures()
            active: true,
            comment_id: comment.id
         }));
      }
   });

   return signatures;
}

/**
 * Takes an object representing a DB row, and returns an object which mimics
 * a GitHub API response which may be used to initialize an instance of this
 * Signature object.
 */
Signature.getFromDB = function(data) {
   return {
      number:     data.number,
      user:       data.user,
      type:       data.type,
      created_at: data.created_at,
      active:     data.active,
      comment_id: data.comment_id
   };
}

/**
 * A compare function for Signatures that can be passed to a custom sorter.
 * Sorts signatures in chronologically
 */
Signature.compare = function(a, b) {
   return Date.parse(a.data.created_at) - Date.parse(b.data.created_at);
};

module.exports = Signature;

var tagRegExps = {};

function hasTag(body, tagName) {
   if (typeof tagRegExps[tagName] === 'undefined') {
      // e.g. "dev_block :+1:" or " CR :asdf:."
      tagRegExps[tagName]
         = new RegExp("\\b" + tagName + " :[^\n:]+:", 'i');
   }
   return tagRegExps[tagName].test(body);
}
<|endoftext|>


<commit_before>if (typeof VIE === 'undefined') {
    VIE = {};
}

VIE.ContainerManager = {
    models: {},
    views: {},

    /**
     * @private
     */
    _getContainerProperties: function(element, emptyValues) {
        var containerProperties = {};

        jQuery.each(jQuery('[property]', element), function(index, objectProperty) {
            var objectProperty = jQuery(objectProperty);
            var propertyName = objectProperty.attr('property');

            if (emptyValues) {
                containerProperties[propertyName] = '';
                return true;
            }

            containerProperties[propertyName] = objectProperty.html();
        });

        return containerProperties;
    },

    /**
     * @private
     */
    _getContainerValue: function(element, propertyName) {
        var element = jQuery(element);

        if (typeof element.attr(propertyName) !== 'undefined')
        {
            // Direct match with container
            return element.attr(propertyName);
        }
        return element.find('[' + propertyName + ']').attr(propertyName);
    },

    cloneContainer: function(element) {
        var element = jQuery(element).clone(false);

        if (typeof element.attr('about') !== 'undefined')
        {
            // Direct match with container
            element.attr('about', '');
        }
        element.find('[about]').attr('about', '');
        element.find('[property]').html('');

        return element;
    },

    /**
     * @access private
     */
    _getViewForContainer: function(element) {
        var element = jQuery(element);
        var type = VIE.ContainerManager._getContainerValue(element, 'typeof');

        if (typeof VIE.ContainerManager.views[type] !== 'undefined') {
            // We already have a view for this type
            return VIE.ContainerManager.views[type];
        }

        var viewProperties = {};
        viewProperties.initialize = function() {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
            this.model.view = this;
        };
        viewProperties.tagName = element.get(0).nodeName;
        viewProperties.make = function(tagName, attributes, content) {
            return VIE.ContainerManager.cloneContainer(element);
        };
        viewProperties.render = function() {
            var model = this.model;
            jQuery('[property]', this.el).each(function(index, propertyElement) {
                var propertyElement = jQuery(propertyElement);
                var property = propertyElement.attr('property');
                propertyElement.html(model.get(property));
            });
            return this;
        };

        VIE.ContainerManager.views[type] = Backbone.View.extend(viewProperties);

        return VIE.ContainerManager.views[type];
    },

    getModelForContainer: function(element) {
        var type = VIE.ContainerManager._getContainerValue(element, 'typeof');

        if (typeof VIE.ContainerManager.models[type] !== 'undefined') {
            // We already have a model for this type
            return VIE.ContainerManager.models[type];
        }

        // Parse the relevant properties from DOM
        var modelPropertiesFromRdf = VIE.ContainerManager._getContainerProperties(element, true);
        var modelProperties = jQuery.extend({}, modelPropertiesFromRdf);

        modelProperties.initialize = function() {
            var modelInstance = this;
            var populateProperties = {};
            jQuery.each(modelPropertiesFromRdf, function(propName, propValue) {

                if (!modelInstance.get(propName)) {
                    populateProperties[propName] = modelInstance.getPlaceholder(propName);
                }

            });

            if (!jQuery.isEmptyObject(populateProperties)) {
                modelInstance.set(populateProperties);
            }
        };

        VIE.ContainerManager.models[type] = Backbone.Model.extend(modelProperties);

        return VIE.ContainerManager.models[type];
    },

    /**
     * Override this to seek additional properties from the element to include to the model
     */
    findAdditionalProperties: function(element, properties) {
    },

    getInstanceForContainer: function(element) {
        var model = VIE.ContainerManager.getModelForContainer(element);
        var properties = VIE.ContainerManager._getContainerProperties(element, false);
        var view = VIE.ContainerManager._getViewForContainer(element);

        properties.id = VIE.ContainerManager._getContainerValue(element, 'about');
        VIE.ContainerManager.findAdditionalProperties(element, properties);

        var modelInstance = new model(properties);
        modelInstance.view = new view({model: modelInstance, el: element});

        return modelInstance;
    }
};
<commit_msg>We need additional properties callbacks for both model and instance<commit_after>if (typeof VIE === 'undefined') {
    VIE = {};
}

VIE.ContainerManager = {
    models: {},
    views: {},

    /**
     * @private
     */
    _getContainerProperties: function(element, emptyValues) {
        var containerProperties = {};

        jQuery.each(jQuery('[property]', element), function(index, objectProperty) {
            var objectProperty = jQuery(objectProperty);
            var propertyName = objectProperty.attr('property');

            if (emptyValues) {
                containerProperties[propertyName] = '';
                return true;
            }

            containerProperties[propertyName] = objectProperty.html();
        });

        return containerProperties;
    },

    /**
     * @private
     */
    _getContainerValue: function(element, propertyName) {
        var element = jQuery(element);

        if (typeof element.attr(propertyName) !== 'undefined')
        {
            // Direct match with container
            return element.attr(propertyName);
        }
        return element.find('[' + propertyName + ']').attr(propertyName);
    },

    cloneContainer: function(element) {
        var element = jQuery(element).clone(false);

        if (typeof element.attr('about') !== 'undefined')
        {
            // Direct match with container
            element.attr('about', '');
        }
        element.find('[about]').attr('about', '');
        element.find('[property]').html('');

        return element;
    },

    /**
     * @access private
     */
    _getViewForContainer: function(element) {
        var element = jQuery(element);
        var type = VIE.ContainerManager._getContainerValue(element, 'typeof');

        if (typeof VIE.ContainerManager.views[type] !== 'undefined') {
            // We already have a view for this type
            return VIE.ContainerManager.views[type];
        }

        var viewProperties = {};
        viewProperties.initialize = function() {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
            this.model.view = this;
        };
        viewProperties.tagName = element.get(0).nodeName;
        viewProperties.make = function(tagName, attributes, content) {
            return VIE.ContainerManager.cloneContainer(element);
        };
        viewProperties.render = function() {
            var model = this.model;
            jQuery('[property]', this.el).each(function(index, propertyElement) {
                var propertyElement = jQuery(propertyElement);
                var property = propertyElement.attr('property');
                propertyElement.html(model.get(property));
            });
            return this;
        };

        VIE.ContainerManager.views[type] = Backbone.View.extend(viewProperties);

        return VIE.ContainerManager.views[type];
    },

    getModelForContainer: function(element) {
        var type = VIE.ContainerManager._getContainerValue(element, 'typeof');

        if (typeof VIE.ContainerManager.models[type] !== 'undefined') {
            // We already have a model for this type
            return VIE.ContainerManager.models[type];
        }

        // Parse the relevant properties from DOM
        var modelPropertiesFromRdf = VIE.ContainerManager._getContainerProperties(element, true);
        var modelProperties = jQuery.extend({}, modelPropertiesFromRdf);

        modelProperties.type = type;

        modelProperties.initialize = function() {
            var modelInstance = this;
            var populateProperties = {};
            jQuery.each(modelPropertiesFromRdf, function(propName, propValue) {

                if (!modelInstance.get(propName)) {
                    populateProperties[propName] = modelInstance.getPlaceholder(propName);
                }

            });

            if (!jQuery.isEmptyObject(populateProperties)) {
                modelInstance.set(populateProperties);
            }
        };

        VIE.ContainerManager.findAdditionalModelProperties(element, modelProperties);

        VIE.ContainerManager.models[type] = Backbone.Model.extend(modelProperties);

        return VIE.ContainerManager.models[type];
    },

    /**
     * Override this to seek additional properties from the element to include to the model
     */
    findAdditionalModelProperties: function(element, properties) {
    },

    /**
     * Override this to seek additional properties from the element to include to the instance
     */
    findAdditionalInstanceProperties: function(element, properties) {
    },

    getInstanceForContainer: function(element) {
        var model = VIE.ContainerManager.getModelForContainer(element);
        var properties = VIE.ContainerManager._getContainerProperties(element, false);
        var view = VIE.ContainerManager._getViewForContainer(element);

        properties.id = VIE.ContainerManager._getContainerValue(element, 'about');

        VIE.ContainerManager.findAdditionalInstanceProperties(element, properties);

        var modelInstance = new model(properties);
        modelInstance.view = new view({model: modelInstance, el: element});

        return modelInstance;
    }
};
<|endoftext|>


<commit_before>
var Person = require('./person.js');
var Platform = require('./block_platform');

var gamma = 0;
var grav = 0.5;
var holdLeft = false;
var holdRight = false;
var holdUp = false;
var plat = [];
var platLava = [];
var platFragile = [];
var totalPlats = 150;
var platRatio = 1.05;
var score;
var highscore;
window.intervalId = 0;
var canv;
var ctx;

var player = new Person(200, 200);

window.onload = function() {
    var tmp = getCookie('highscore');
    if (tmp != '') {
        highscore = parseInt(tmp);
    } else {
        highscore = 0;
    }

    canv = document.getElementById('gc');
    ctx = canv.getContext('2d');
    ctx.font = '30px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    document.addEventListener('keydown', startGame);
    document.addEventListener('touchstart', startGame);
    score = highscore - 1;
    refresh(false);
    update();
    ctx.fillStyle = 'rgba(120, 120, 120, 0.7)';
    ctx.fillRect(0, 0, canv.width, canv.height);
    ctx.fillStyle = 'white';
    ctx.font = '36px Arial';
    ctx.fillText('Press any key or tap the screen to begin',
        canv.width/2,  canv.height/2);
};

function startGame() {
    document.removeEventListener('keydown', startGame);
    document.removeEventListener('touchstart', startGame);

    platRatio = 1.05;
    score = -1;
    refresh(false);
    game();
}

function game(){

    window.onblur = pauseGame;
    ctx.font = '30px Arial';
    window.intervalId = setInterval(update,1000/30);
    document.addEventListener('keydown', keyDown);
    document.addEventListener('keyup', keyUp);
    document.addEventListener('touchstart', touchStart);
    document.addEventListener('touchend', touchEnd);
    window.addEventListener('deviceorientation', gyroscopeChange);
}

function pauseGame(){
    clearInterval(window.intervalId);
    document.removeEventListener('keydown', keyDown);
    document.removeEventListener('keyup', keyUp);
    document.removeEventListener('touchstart', touchStart);
    document.removeEventListener('touchend', touchEnd);
    window.removeEventListener('deviceorientation', gyroscopeChange);

    document.addEventListener('keydown', resumeGameKey);
    document.addEventListener('touchstart', resumeGameTouch);

    ctx.fillStyle = 'rgba(120, 120, 120, 0.7)';
    ctx.fillRect(0, 0, canv.width, canv.height);
    ctx.fillStyle = 'white';
    ctx.font = '36px Arial';
    ctx.fillText('Press ESC or tap to continue', canv.width/2, canv.height/2);

    holdLeft = false;
    holdRight = false;
}

function resumeGameKey(evt) {
    switch (evt.keyCode) {
    case 27:
        document.removeEventListener('keydown', resumeGameKey);
        document.removeEventListener('touchstart', resumeGameTouch);
        game();
        break;
    default:
        break;
    }
}

function resumeGameTouch() {
    document.removeEventListener('keydown', resumeGameKey);
    document.removeEventListener('touchstart', resumeGameTouch);
    game();
}

function gameOver() {
    window.onblur = function () {};
    clearInterval(window.intervalId);
    document.removeEventListener('keydown', keyDown);
    document.removeEventListener('keyup', keyUp);
    document.removeEventListener('touchstart', touchStart);
    document.removeEventListener('touchend', touchEnd);
    window.removeEventListener('deviceorientation', gyroscopeChange);

    document.addEventListener('keydown', startGame);
    document.addEventListener('touchstart', startGame);

    holdLeft = false;
    holdRight = false;
    holdUp = false;

    ctx.fillStyle = 'rgba(120, 120, 120, 0.7)';
    ctx.fillRect(0, 0, canv.width, canv.height);
    ctx.fillStyle = 'white';
    ctx.font = '36px Arial';
    ctx.fillText('Your score was: ' + score, canv.width/2, canv.height/2);
}

function refresh(died) {
    player.xv = 0;
    player.yv = 0;
    if(!died){
        score += 1;
        platRatio *= 0.95;
    } else {
        if (highscore < score){
            createCookie('highscore', score);
            highscore = score;
        }
        gameOver();
    }
    plat = [];
    platLava = [];
    platFragile = [];
    var ground = new Platform(-100, canv.height - 20, '#aaaaaa');
    ground.w = canv.width + 200;
    ground.h = 200;
    plat.push(ground);
    (function () {
        for (var i = 0; i < totalPlats * platRatio; i += 1) {
            var x = Math.floor(Math.random()*canv.width/30)*canv.width/30;
            var y = Math.floor(Math.random()*canv.width/30)*canv.width/30;
            var c = '#aaaaaa';
            plat.push(new Platform(x, y, c));
        }
    })();

    var fragileblocks;
    if (score < totalPlats / 6) {
        fragileblocks =
            Math.floor(Math.random() * score * 2.5 +
            score + totalPlats - Math.floor(totalPlats * platRatio));
    } else {
        fragileblocks =
            Math.floor(Math.random() * plat.length / 2.3 +
            score + totalPlats - Math.floor(totalPlats*platRatio));
    }
    (function () {
        for (var i = 1; i < fragileblocks + 1; i += 1) {
            var x = Math.floor(Math.random() * canv.width/30) * canv.width/30;
            var y = Math.floor(Math.random() * canv.width/30) * canv.width/30;
            var c = '#009999';
            var fragilePlat = new Platform(x, y, c);
            fragilePlat.t = -1;
            platFragile.push(fragilePlat);
        }
    })();

    var lavablocks;
    if (score < totalPlats / 6) {
        lavablocks = Math.floor(Math.random() * score * 2.5 + score);
    } else {
        lavablocks = Math.floor(Math.random() * totalPlats / 2.3 + score);
    }

    (function () {
        for(var i = 1; i < lavablocks + 1; i += 1){
            platLava.push(
                {
                    x:Math.floor(Math.random() * canv.width / 30) *
                        canv.width / 30 + 3,
                    y:Math.floor(Math.random() * canv.width / 30) *
                        canv.width / 30 + 3,
                    w:canv.width / 30 - 6,
                    h:canv.width / 30 - 6,
                    c:'#990000'
                });
        }
    })();

    plat.push(
        {
            x:player.px - (player.px % 30),
            y:player.py - (player.py % 30),
            w:canv.width / 30,
            h:canv.width / 30,
            c:'#aaaaaa'
        });

    plat.push(
        {
            x:Math.floor(Math.random()*canv.width/30)*canv.width/30,
            y:Math.floor(Math.random()*canv.width/30)*canv.width/30,
            w:canv.width/30,
            h:canv.width/30,
            c:'#009900'
        });

    (function () {
        for (var i = 0; i < plat.length - 1; i += 1) {
            if (plat[i].x == plat[plat.length - 1].x &&
                plat[i].y == plat[plat.length - 1].y) {
                plat.splice(i, 1);
            }
        }
    })();

}
function update() {
    if(holdLeft) {
        if (gamma > -15 && gamma != 0) {
            player.xv = (gamma + 5) * 0.1 * 4;
        } else {
            player.xv =- 4;
        }
    }
    if(holdRight) {
        if (gamma < 15 && gamma != 0) {
            player.xv = (gamma - 5) * 0.1 * 4;
        } else {
            player.xv = 4;
        }
    }
    player.move();
    if (player.onG) {
        player.xv *= 0.2;
    } else {
        player.yv += grav;
    }

    if (player.px < 0) {
        player.px = canv.width;
    }
    if (player.px > canv.width) {
        player.px = 0;
    }
    player.onG = false;

    (function () {
        for(var i=0; i < plat.length; i += 1) {
            if(player.px > plat[i].x && player.px < plat[i].x + plat[i].w &&
                player.py > plat[i].y && player.py < plat[i].y + plat[i].h) {
                if (plat[i].c == '#009900') {
                    refresh(false);
                    return;
                }
                player.py = plat[i].y;
                player.onG = true;
                player.yv = 0.000001;
            }
        }
    })();

    (function () {
        for (var i = 0; i < platFragile.length; i += 1) {
            if (platFragile[i].t > 0){
                platFragile[i].t -= 1;
            }

            if (player.px > platFragile[i].x &&
                player.px < platFragile[i].x + platFragile[i].w &&
                player.py > platFragile[i].y &&
                player.py < platFragile[i].y + platFragile[i].h) {
                // start timer
                if (platFragile[i].t < 0) {
                    platFragile[i].t = 30;
                }
                player.py = platFragile[i].y;
                player.onG = true;
                player.yv = 0.000001;
            }
            if (platFragile[i].t == 0) {
                //remove block
                platFragile.splice(i, 1);
            }
        }
    })();
    var isDead = false;
    (function () {
        for (var i = 0; i < platLava.length; i += 1) {
            if (player.px > platLava[i].x &&
                player.px < platLava[i].x + platLava[i].w &&
                player.py > platLava[i].y &&
                player.py < platLava[i].y + platLava[i].h) {
                refresh(true);
                isDead = true;
            }
        }
    })();

    player.update(holdUp);
    if(!isDead){
        drawScreen();
    }
}

function drawScreen() {
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, canv.width, canv.height);
    (function () {
        for(var i = 0; i < platFragile.length; i += 1) {
            if (platFragile[i].t >= 0) {
                platFragile[i].c =
                    '#00' + (3 * platFragile[i].t + 9) +
                    (3 * platFragile[i].t + 9);
            }
            ctx.fillStyle = platFragile[i].c;

            ctx.fillRect(platFragile[i].x, platFragile[i].y,
                platFragile[i].w, 2);
            ctx.fillRect(platFragile[i].x + platFragile[i].w - 2,
                platFragile[i].y, 2, platFragile[i].h);
            ctx.fillRect(platFragile[i].x,
                platFragile[i].y + platFragile[i].h - 2,
                platFragile[i].w, 2);
            ctx.fillRect(platFragile[i].x, platFragile[i].y,
                2, platFragile[i].h);

            ctx.fillRect(platFragile[i].x + 4, platFragile[i].y + 4,
                platFragile[i].w - 8, platFragile[i].h - 8);
        }
    })();

    (function () {
        for (var i = 0; i < plat.length; i += 1) {
            ctx.fillStyle = plat[i].c;

            ctx.fillRect(plat[i].x, plat[i].y, plat[i].w, 2);
            ctx.fillRect(plat[i].x + plat[i].w - 2, plat[i].y, 2, plat[i].h);
            ctx.fillRect(plat[i].x, plat[i].y + plat[i].h - 2, plat[i].w, 2);
            ctx.fillRect(plat[i].x, plat[i].y, 2, plat[i].h);

            ctx.fillRect(plat[i].x + 4, plat[i].y + 4,
                plat[i].w - 8, plat[i].h - 8);
        }
    })();

    (function () {
        for (var i = 0; i < platLava.length; i += 1) {
            ctx.fillStyle = platLava[i].c;
            ctx.fillRect(platLava[i].x, platLava[i].y,
                platLava[i].w, platLava[i].h);
        }
    })();

    player.draw(ctx);

    ctx.fillStyle = 'white';
    ctx.fillText(score, 40, 40);
}

function keyDown(evt) {
    switch (evt.keyCode) {
    case 37:
        holdLeft=true;
        break;
    case 38:
        holdUp = true;
        break;
    case 39:
        holdRight=true;
        break;
    case 27:
        pauseGame();
        break;
    }
}
function touchStart(){
    if(player.onG) {
        player.yv =- 10;
    }
    holdUp = true;
}
function touchEnd(){
    if(player.yv < -4) {
        player.yv = -4;
    }
    holdUp = false;
}

function gyroscopeChange(evt) {
    gamma = evt.gamma;
    if(gamma > 5){
        holdRight = true;
        holdLeft = false;
        return;
    } else if(gamma < -5){
        holdLeft = true;
        holdRight = false;
        return;
    } else {
        holdRight = false;
        holdLeft = false;
    }
}

function keyUp(evt) {
    switch(evt.keyCode) {
    case 37:
        holdLeft = false;
        break;
    case 38:
        if(player.yv < -4) {
            player.yv = -4;
        }
        holdUp = false;
        break;
    case 39:
        holdRight = false;
        break;
    }
}

var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = '; expires=' + date.toGMTString();
    }
    else {
        expires = '';
    }
    document.cookie = name + '=' + value + expires + '; path=/';
};

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + '=');
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(';', c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return '';
}
<commit_msg>changed player catching platform to Platform()<commit_after>
var Person = require('./person.js');
var Platform = require('./block_platform');

var gamma = 0;
var grav = 0.5;
var holdLeft = false;
var holdRight = false;
var holdUp = false;
var plat = [];
var platLava = [];
var platFragile = [];
var totalPlats = 150;
var platRatio = 1.05;
var score;
var highscore;
window.intervalId = 0;
var canv;
var ctx;

var player = new Person(200, 200);

window.onload = function() {
    var tmp = getCookie('highscore');
    if (tmp != '') {
        highscore = parseInt(tmp);
    } else {
        highscore = 0;
    }

    canv = document.getElementById('gc');
    ctx = canv.getContext('2d');
    ctx.font = '30px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    document.addEventListener('keydown', startGame);
    document.addEventListener('touchstart', startGame);
    score = highscore - 1;
    refresh(false);
    update();
    ctx.fillStyle = 'rgba(120, 120, 120, 0.7)';
    ctx.fillRect(0, 0, canv.width, canv.height);
    ctx.fillStyle = 'white';
    ctx.font = '36px Arial';
    ctx.fillText('Press any key or tap the screen to begin',
        canv.width/2,  canv.height/2);
};

function startGame() {
    document.removeEventListener('keydown', startGame);
    document.removeEventListener('touchstart', startGame);

    platRatio = 1.05;
    score = -1;
    refresh(false);
    game();
}

function game(){

    window.onblur = pauseGame;
    ctx.font = '30px Arial';
    window.intervalId = setInterval(update,1000/30);
    document.addEventListener('keydown', keyDown);
    document.addEventListener('keyup', keyUp);
    document.addEventListener('touchstart', touchStart);
    document.addEventListener('touchend', touchEnd);
    window.addEventListener('deviceorientation', gyroscopeChange);
}

function pauseGame(){
    clearInterval(window.intervalId);
    document.removeEventListener('keydown', keyDown);
    document.removeEventListener('keyup', keyUp);
    document.removeEventListener('touchstart', touchStart);
    document.removeEventListener('touchend', touchEnd);
    window.removeEventListener('deviceorientation', gyroscopeChange);

    document.addEventListener('keydown', resumeGameKey);
    document.addEventListener('touchstart', resumeGameTouch);

    ctx.fillStyle = 'rgba(120, 120, 120, 0.7)';
    ctx.fillRect(0, 0, canv.width, canv.height);
    ctx.fillStyle = 'white';
    ctx.font = '36px Arial';
    ctx.fillText('Press ESC or tap to continue', canv.width/2, canv.height/2);

    holdLeft = false;
    holdRight = false;
}

function resumeGameKey(evt) {
    switch (evt.keyCode) {
    case 27:
        document.removeEventListener('keydown', resumeGameKey);
        document.removeEventListener('touchstart', resumeGameTouch);
        game();
        break;
    default:
        break;
    }
}

function resumeGameTouch() {
    document.removeEventListener('keydown', resumeGameKey);
    document.removeEventListener('touchstart', resumeGameTouch);
    game();
}

function gameOver() {
    window.onblur = function () {};
    clearInterval(window.intervalId);
    document.removeEventListener('keydown', keyDown);
    document.removeEventListener('keyup', keyUp);
    document.removeEventListener('touchstart', touchStart);
    document.removeEventListener('touchend', touchEnd);
    window.removeEventListener('deviceorientation', gyroscopeChange);

    document.addEventListener('keydown', startGame);
    document.addEventListener('touchstart', startGame);

    holdLeft = false;
    holdRight = false;
    holdUp = false;

    ctx.fillStyle = 'rgba(120, 120, 120, 0.7)';
    ctx.fillRect(0, 0, canv.width, canv.height);
    ctx.fillStyle = 'white';
    ctx.font = '36px Arial';
    ctx.fillText('Your score was: ' + score, canv.width/2, canv.height/2);
}

function refresh(died) {
    player.xv = 0;
    player.yv = 0;
    if(!died){
        score += 1;
        platRatio *= 0.95;
    } else {
        if (highscore < score){
            createCookie('highscore', score);
            highscore = score;
        }
        gameOver();
    }
    plat = [];
    platLava = [];
    platFragile = [];
    var ground = new Platform(-100, canv.height - 20, '#aaaaaa');
    ground.w = canv.width + 200;
    ground.h = 200;
    plat.push(ground);
    (function () {
        for (var i = 0; i < totalPlats * platRatio; i += 1) {
            var x = Math.floor(Math.random()*canv.width/30)*canv.width/30;
            var y = Math.floor(Math.random()*canv.width/30)*canv.width/30;
            var c = '#aaaaaa';
            plat.push(new Platform(x, y, c));
        }
    })();

    var fragileblocks;
    if (score < totalPlats / 6) {
        fragileblocks =
            Math.floor(Math.random() * score * 2.5 +
            score + totalPlats - Math.floor(totalPlats * platRatio));
    } else {
        fragileblocks =
            Math.floor(Math.random() * plat.length / 2.3 +
            score + totalPlats - Math.floor(totalPlats*platRatio));
    }
    (function () {
        for (var i = 1; i < fragileblocks + 1; i += 1) {
            var x = Math.floor(Math.random() * canv.width/30) * canv.width/30;
            var y = Math.floor(Math.random() * canv.width/30) * canv.width/30;
            var c = '#009999';
            var fragilePlat = new Platform(x, y, c);
            fragilePlat.t = -1;
            platFragile.push(fragilePlat);
        }
    })();

    var lavablocks;
    if (score < totalPlats / 6) {
        lavablocks = Math.floor(Math.random() * score * 2.5 + score);
    } else {
        lavablocks = Math.floor(Math.random() * totalPlats / 2.3 + score);
    }

    (function () {
        for(var i = 1; i < lavablocks + 1; i += 1){
            platLava.push(
                {
                    x:Math.floor(Math.random() * canv.width / 30) *
                        canv.width / 30 + 3,
                    y:Math.floor(Math.random() * canv.width / 30) *
                        canv.width / 30 + 3,
                    w:canv.width / 30 - 6,
                    h:canv.width / 30 - 6,
                    c:'#990000'
                });
        }
    })();

    plat.push(new Platform(
        player.px - (player.px % 30),
        player.py - (player.py % 30),
        '#aaaaaa'
    ));

    plat.push(
        {
            x:Math.floor(Math.random()*canv.width/30)*canv.width/30,
            y:Math.floor(Math.random()*canv.width/30)*canv.width/30,
            w:canv.width/30,
            h:canv.width/30,
            c:'#009900'
        });

    (function () {
        for (var i = 0; i < plat.length - 1; i += 1) {
            if (plat[i].x == plat[plat.length - 1].x &&
                plat[i].y == plat[plat.length - 1].y) {
                plat.splice(i, 1);
            }
        }
    })();

}
function update() {
    if(holdLeft) {
        if (gamma > -15 && gamma != 0) {
            player.xv = (gamma + 5) * 0.1 * 4;
        } else {
            player.xv =- 4;
        }
    }
    if(holdRight) {
        if (gamma < 15 && gamma != 0) {
            player.xv = (gamma - 5) * 0.1 * 4;
        } else {
            player.xv = 4;
        }
    }
    player.move();
    if (player.onG) {
        player.xv *= 0.2;
    } else {
        player.yv += grav;
    }

    if (player.px < 0) {
        player.px = canv.width;
    }
    if (player.px > canv.width) {
        player.px = 0;
    }
    player.onG = false;

    (function () {
        for(var i=0; i < plat.length; i += 1) {
            if(player.px > plat[i].x && player.px < plat[i].x + plat[i].w &&
                player.py > plat[i].y && player.py < plat[i].y + plat[i].h) {
                if (plat[i].c == '#009900') {
                    refresh(false);
                    return;
                }
                player.py = plat[i].y;
                player.onG = true;
                player.yv = 0.000001;
            }
        }
    })();

    (function () {
        for (var i = 0; i < platFragile.length; i += 1) {
            if (platFragile[i].t > 0){
                platFragile[i].t -= 1;
            }

            if (player.px > platFragile[i].x &&
                player.px < platFragile[i].x + platFragile[i].w &&
                player.py > platFragile[i].y &&
                player.py < platFragile[i].y + platFragile[i].h) {
                // start timer
                if (platFragile[i].t < 0) {
                    platFragile[i].t = 30;
                }
                player.py = platFragile[i].y;
                player.onG = true;
                player.yv = 0.000001;
            }
            if (platFragile[i].t == 0) {
                //remove block
                platFragile.splice(i, 1);
            }
        }
    })();
    var isDead = false;
    (function () {
        for (var i = 0; i < platLava.length; i += 1) {
            if (player.px > platLava[i].x &&
                player.px < platLava[i].x + platLava[i].w &&
                player.py > platLava[i].y &&
                player.py < platLava[i].y + platLava[i].h) {
                refresh(true);
                isDead = true;
            }
        }
    })();

    player.update(holdUp);
    if(!isDead){
        drawScreen();
    }
}

function drawScreen() {
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, canv.width, canv.height);
    (function () {
        for(var i = 0; i < platFragile.length; i += 1) {
            if (platFragile[i].t >= 0) {
                platFragile[i].c =
                    '#00' + (3 * platFragile[i].t + 9) +
                    (3 * platFragile[i].t + 9);
            }
            ctx.fillStyle = platFragile[i].c;

            ctx.fillRect(platFragile[i].x, platFragile[i].y,
                platFragile[i].w, 2);
            ctx.fillRect(platFragile[i].x + platFragile[i].w - 2,
                platFragile[i].y, 2, platFragile[i].h);
            ctx.fillRect(platFragile[i].x,
                platFragile[i].y + platFragile[i].h - 2,
                platFragile[i].w, 2);
            ctx.fillRect(platFragile[i].x, platFragile[i].y,
                2, platFragile[i].h);

            ctx.fillRect(platFragile[i].x + 4, platFragile[i].y + 4,
                platFragile[i].w - 8, platFragile[i].h - 8);
        }
    })();

    (function () {
        for (var i = 0; i < plat.length; i += 1) {
            ctx.fillStyle = plat[i].c;

            ctx.fillRect(plat[i].x, plat[i].y, plat[i].w, 2);
            ctx.fillRect(plat[i].x + plat[i].w - 2, plat[i].y, 2, plat[i].h);
            ctx.fillRect(plat[i].x, plat[i].y + plat[i].h - 2, plat[i].w, 2);
            ctx.fillRect(plat[i].x, plat[i].y, 2, plat[i].h);

            ctx.fillRect(plat[i].x + 4, plat[i].y + 4,
                plat[i].w - 8, plat[i].h - 8);
        }
    })();

    (function () {
        for (var i = 0; i < platLava.length; i += 1) {
            ctx.fillStyle = platLava[i].c;
            ctx.fillRect(platLava[i].x, platLava[i].y,
                platLava[i].w, platLava[i].h);
        }
    })();

    player.draw(ctx);

    ctx.fillStyle = 'white';
    ctx.fillText(score, 40, 40);
}

function keyDown(evt) {
    switch (evt.keyCode) {
    case 37:
        holdLeft=true;
        break;
    case 38:
        holdUp = true;
        break;
    case 39:
        holdRight=true;
        break;
    case 27:
        pauseGame();
        break;
    }
}
function touchStart(){
    if(player.onG) {
        player.yv =- 10;
    }
    holdUp = true;
}
function touchEnd(){
    if(player.yv < -4) {
        player.yv = -4;
    }
    holdUp = false;
}

function gyroscopeChange(evt) {
    gamma = evt.gamma;
    if(gamma > 5){
        holdRight = true;
        holdLeft = false;
        return;
    } else if(gamma < -5){
        holdLeft = true;
        holdRight = false;
        return;
    } else {
        holdRight = false;
        holdLeft = false;
    }
}

function keyUp(evt) {
    switch(evt.keyCode) {
    case 37:
        holdLeft = false;
        break;
    case 38:
        if(player.yv < -4) {
            player.yv = -4;
        }
        holdUp = false;
        break;
    case 39:
        holdRight = false;
        break;
    }
}

var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = '; expires=' + date.toGMTString();
    }
    else {
        expires = '';
    }
    document.cookie = name + '=' + value + expires + '; path=/';
};

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + '=');
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(';', c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return '';
}
<|endoftext|>


<commit_before><commit_msg>code fixing based on jshint<commit_after><|endoftext|>