<commit_before>var cssjson = {
    "media" : {
        ""    : "@media only screen{",
        "l_"  : "@media only screen and (max-width: 95em){",        // 1520px
        "t_"  : "@media only screen and (max-width: 82.5em){",      // 1320px
        "tp_" : "@media only screen and (max-width: 62.5em){",      // 1000px
        "m_"  : "@media only screen and (max-width: 45em){",        // 720px
        "mp_" : "@media only screen and (max-width: 25em){"         // 400px
    },
/*
    "media" : {
        ""    : "@media only screen{",
        "l_"  : "@media only screen and (max-width: 1500px){",
        "t_"  : "@media only screen and (max-width: 1200px){",
        "tl_" : "@media only screen and (max-width: 1200px) and (orientation:landscape){",
        "m_"  : "@media only screen and (max-width: 45em){",
        "ml_" : "@media only screen and (max-width: 45em) and (orientation:landscape){"
    },
*/
    "rules" : [
        {
            "property" : {
                "w"  : "width",
                "h"  : "height",
                "fb" : "flex-basis"
            },
            "loop" : {
                "i"       : 12,   // from 0 to 11
                //"name"    : "(i+1) + '-12' ",
                "name"    : "if(i==0||i==4||i==6||i==10){'-'+ (i+1) + '-12'}else if(i==1||i==9){'-'+ ((i+1)/2) + '-6'}else if(i==2||i==8){'-'+ ((i+1)/3) + '-4'}else if(i==3||i==7){'-'+ ((i+1)/4) + '-3'}else if(i==5||i==11){'-1-'+ (12/(i+1))}",
                "func"    : "((i+1) * (100/12)).toFixed(4) + '%' "
            },
            "value" : {
                "-a" : "auto"
            }
        },
        {
            "property" : {
                "w"  : "width",
                "h"  : "height",
                "fb" : "flex-basis"
            },
            "loop" : {
                "i"       : 4,   // from 0 to 3
                "name"    : "'-' + (i+1) + '-5' ",
                "func"    : "((i+1) * (100/5)) + '%' "
            }
        },
        {
            "property" : {
                "w"  : "width",
                "h"  : "height",
                "fb" : "flex-basis"
            },
            "loop" : {
                "i"       : 20,
                "name"    : "'-'+(i+1)",
                "func"    : "(i+1) + 'rem'"
            }
        },
        {
            "property" : {
                "mw" : "max-width"
            },
            "loop" : {
                "i"       : 8,
                "name"    : "'-' + ((i*5) + 45)",
                "func"    : "((i*5) + 45) + 'em'"
            },
            "value" : {
                "-100" : "100%"
            }
        },
        {
            "property" : {
                "m" : "margin",
                "p" : "padding"
            },
            "suffix" : {
                ""  : "",
                "-l" : "-left",
                "-r" : "-right",
                "-b" : "-bottom",
                "-t" : "-top"
            },
            "loop" : {
                "i"       : 9,      // from 0 to 8
                "name"    : "('-'+(i/2)).replace('.','')",
                "func"    : "i/2 + 'em'"
            },
            "value" : {
                "-a"  : "auto"
            }
        },
        {
            "property" : {
                "tt" : "text-transform"
            },
            "value" : {
                "-u"  : "uppercase",
                "-l"  : "lowercase",
                "-n"  : "none"
            }
        },
        {
            "property" : {
                "td" : "text-decoration"
            },
            "value" : {
                "-u"  : "underline",
                "-n"  : "none"
            }
        },
        {
            "property": {
                "fs": "font-style"
            },
            "value": {
                "-i": "italic",
                "-n": "normal"
            }
        },
        {
            "property" : {
                "ta" : "text-align"
            },
            "value" : {
                "-c" : "center",
                "-l" : "left",
                "-r" : "right"
            }
        },
        {
            "property" : {
                "fw" : "font-weight"
            },
            "loop" : {
                "i" : 9,
                "name" : "'-' + ((i+1)*100)",
                "func" : "(i+1)*100"
            }
        },
        {
            "property" : {
                "lh" : "line-height"
            },
            "loop" : {
                "i" : 15,
                "name" : "('-1' + (i/2)).replace('.','')",
                "func" : "(1 + (i/20))"
            }
        },
        {
            "property" : {
                "fs" : "font-size"
            },
            "loop" : {
                "i" : 27,  // 12px - 64px
                "name" : "('-'+(12+(i*2)))",
                "func" : "((12 + (i*2))/16) + 'rem'"
            }
        },
        {
            "property" : {
                "d" : "display"
            },
            "value" : {
                "-f"  : "flex",
                "-b"  : "block",
                "-i"  : "inline",
                "-if" : "inline-flex",
                "-ib" : "inline-block",
                "-n"  : "none"
            }
        },
        {
            "property" : {
                "fw" : "flex-wrap"
            },
            "value" : {
                "-w"  : "wrap",
                "-n"  : "nowrap",
                "-wr" : "wrap-reverse"
            }
        },
        {
            "property" : {
                "fd" : "flex-direction"
            },
            "value" : {
                "-r"  : "row",
                "-c"  : "column",
                "-rr" : "row-reverse",
                "-cr" : "column-reverse"
            }
        },
        {
            "property" : {
                "jc" : "justify-content",
                "ai" : "align-items",
                "ac" : "align-content",
                "as" : "align-self"
            },
            "value" : {
                "-c"  : "center",
                "-fs" : "flex-start",
                "-fe" : "flex-end",
                "-sa" : "space-around",
                "-sb" : "space-between",
                "-s"  : "stretch",
                "-b"  : "baseline"
            }
        },
        {
            "property" : {
                "bp" : "background-position",
            },
            "value" : {
                "-c"  : "center",
                "-l"  : "left",
                "-r"  : "right",
                "-t"  : "top",
                "-b"  : "bottom",
                "-lt" : "left top",
                "-rt" : "right top",
                "-lb" : "left bottom",
                "-rb" : "right bottom"
            }
        },
        {
            "property" : {
                "va" : "vertical-align"
            },
            "value" : {
                "-m"  : "middle",
                "-t"  : "top",
                "-b"  : "bottom"
            }
        },
        {
            "property" : {
                "br" : "border"
            },
            "suffix" : {
                ""    : "-radius",
                "-tl" : "-top-left-radius",
                "-tr" : "-top-right-radius",
                "-bl" : "-bottom-left-radius",
                "-br" : "-bottom-right-radius"
            },
            "loop" : {
                "i" : 8,
                "name" : "'-' + (i*2)",
                "func" : "(i*2) + 'px'"
            },
            "value" : {
                "-99" : "9999px"
            }
        },
        {
            "property" : {
                "c-gray"  : "color",
                "bg-gray" : "background-color"
            },
            "loop" : {
                "i" : 21,  // 0 to 20
                "name" : "'-' + (i*5)",
                "func" : "'hsl(0, 0%, ' + (i*5) + '%)'"
            }
        },
        {
            "property" : {
                "c-hue"  : "color",
                "bg-hue" : "background-color"
            },
            "loop" : {
                "i" : 72,  // 0 to 71
                "name" : "'-' + (i*5)",
                "func" : "'hsl(' + (i*5) + ', 100%, 50%)'"
            },
            "pseudo" : {
                "" : "",
                "-hover" : ":hover"
            }
        }
    ]
}

var style = document.createElement("style");
document.head.appendChild(style);

var m = Object.keys(cssjson.media);
var ml = m.length;

function loopy(ar1, ar2, ar3){
    if(r.loop){
        var i = r.loop.i;
        while(i--){
            style.sheet.insertRule(mv + '.' + mk + pk + ar2 + eval(r.loop.name) + ar1 + "{" + pv + ar3 + ":" + eval(r.loop.func) + "}}", 0);
        }
    }
    if(r.value){
        var v = Object.keys(r.value);
        var vl = v.length;
        while(vl--){
            style.sheet.insertRule(mv + '.' + mk + pk + ar2 + v[vl] + ar1 + "{" + pv + ar3 + ":" + r.value[v[vl]] + "}}", 0);
        }
    }
}

function qwe(a1) {
    if(r.suffix) {
        var s = Object.keys(r.suffix);
        var sl = s.length;
        while(sl--) {
            loopy(a1, s[sl], r.suffix[s[sl]]);
        }
    }else{
        loopy(a1, '', '');
    }
}

while(ml--) {
    var mk = m[ml];
    var mv = cssjson.media[mk];
    var rl = cssjson.rules.length;
    while(rl--){
        var r = cssjson.rules[rl];
        var p = Object.keys(r.property);
        var pl = p.length;
        while(pl--) {
            var pk = p[pl];
            var pv = r.property[pk];
            if(!r.pseudo){
                qwe('');
            }else {
                var ps = Object.keys(r.pseudo);
                var psl = ps.length;
                while(psl--){
                    qwe(ps[psl]+r.pseudo[ps[psl]]);
                }
            }
        }
    }
}
<commit_msg>fixes ucj<commit_after>var cssjson = {
    "media" : {
        ""    : "@media only screen{",
        "l_"  : "@media only screen and (max-width: 95em){",        // 1520px
        "t_"  : "@media only screen and (max-width: 82.5em){",      // 1320px
        "tp_" : "@media only screen and (max-width: 62.5em){",      // 1000px
        "m_"  : "@media only screen and (max-width: 45em){",        // 720px
        "mp_" : "@media only screen and (max-width: 27.5em){"       // 440px
    },
/*
    "media" : {
        ""    : "@media only screen{",
        "l_"  : "@media only screen and (max-width: 1500px){",
        "t_"  : "@media only screen and (max-width: 1200px){",
        "tl_" : "@media only screen and (max-width: 1200px) and (orientation:landscape){",
        "m_"  : "@media only screen and (max-width: 45em){",
        "ml_" : "@media only screen and (max-width: 45em) and (orientation:landscape){"
    },
*/
    "rules" : [
        {
            "property" : {
                "w"  : "width",
                "h"  : "height",
                "fb" : "flex-basis"
            },
            "loop" : {
                "i"       : 12,   // from 0 to 11
                //"name"    : "(i+1) + '-12' ",
                "name"    : "if(i==0||i==4||i==6||i==10){'-'+ (i+1) + '-12'}else if(i==1||i==9){'-'+ ((i+1)/2) + '-6'}else if(i==2||i==8){'-'+ ((i+1)/3) + '-4'}else if(i==3||i==7){'-'+ ((i+1)/4) + '-3'}else if(i==5||i==11){'-1-'+ (12/(i+1))}",
                "func"    : "((i+1) * (100/12)).toFixed(4) + '%' "
            },
            "value" : {
                "-a" : "auto"
            }
        },
        {
            "property" : {
                "w"  : "width",
                "h"  : "height",
                "fb" : "flex-basis"
            },
            "loop" : {
                "i"       : 4,   // from 0 to 3
                "name"    : "'-' + (i+1) + '-5' ",
                "func"    : "((i+1) * (100/5)) + '%' "
            }
        },
        {
            "property" : {
                "w"  : "width",
                "h"  : "height",
                "fb" : "flex-basis"
            },
            "loop" : {
                "i"       : 20,
                "name"    : "'-'+(i+1)",
                "func"    : "(i+1) + 'rem'"
            }
        },
        {
            "property" : {
                "mw" : "max-width"
            },
            "loop" : {
                "i"       : 8,
                "name"    : "'-' + ((i*5) + 45)",
                "func"    : "((i*5) + 45) + 'em'"
            },
            "value" : {
                "-100" : "100%"
            }
        },
        {
            "property" : {
                "m" : "margin",
                "p" : "padding"
            },
            "suffix" : {
                ""  : "",
                "-l" : "-left",
                "-r" : "-right",
                "-b" : "-bottom",
                "-t" : "-top"
            },
            "loop" : {
                "i"       : 9,      // from 0 to 8
                "name"    : "('-'+(i/2)).replace('.','')",
                "func"    : "i/2 + 'em'"
            },
            "value" : {
                "-a"  : "auto"
            }
        },
        {
            "property" : {
                "tt" : "text-transform"
            },
            "value" : {
                "-u"  : "uppercase",
                "-l"  : "lowercase",
                "-n"  : "none"
            }
        },
        {
            "property" : {
                "td" : "text-decoration"
            },
            "value" : {
                "-u"  : "underline",
                "-n"  : "none"
            }
        },
        {
            "property": {
                "fs": "font-style"
            },
            "value": {
                "-i": "italic",
                "-n": "normal"
            }
        },
        {
            "property" : {
                "ta" : "text-align"
            },
            "value" : {
                "-c" : "center",
                "-l" : "left",
                "-r" : "right"
            }
        },
        {
            "property" : {
                "fw" : "font-weight"
            },
            "loop" : {
                "i" : 9,
                "name" : "'-' + ((i+1)*100)",
                "func" : "(i+1)*100"
            }
        },
        {
            "property" : {
                "lh" : "line-height"
            },
            "loop" : {
                "i" : 15,
                "name" : "('-1' + (i/2)).replace('.','')",
                "func" : "(1 + (i/20))"
            }
        },
        {
            "property" : {
                "fs" : "font-size"
            },
            "loop" : {
                "i" : 27,  // 12px - 64px
                "name" : "('-'+(12+(i*2)))",
                "func" : "((12 + (i*2))/16) + 'rem'"
            }
        },
        {
            "property" : {
                "d" : "display"
            },
            "value" : {
                "-f"  : "flex",
                "-b"  : "block",
                "-i"  : "inline",
                "-if" : "inline-flex",
                "-ib" : "inline-block",
                "-n"  : "none"
            }
        },
        {
            "property" : {
                "fw" : "flex-wrap"
            },
            "value" : {
                "-w"  : "wrap",
                "-n"  : "nowrap",
                "-wr" : "wrap-reverse"
            }
        },
        {
            "property" : {
                "fd" : "flex-direction"
            },
            "value" : {
                "-r"  : "row",
                "-c"  : "column",
                "-rr" : "row-reverse",
                "-cr" : "column-reverse"
            }
        },
        {
            "property" : {
                "jc" : "justify-content",
                "ai" : "align-items",
                "ac" : "align-content",
                "as" : "align-self"
            },
            "value" : {
                "-c"  : "center",
                "-fs" : "flex-start",
                "-fe" : "flex-end",
                "-sa" : "space-around",
                "-sb" : "space-between",
                "-s"  : "stretch",
                "-b"  : "baseline"
            }
        },
        {
            "property" : {
                "bp" : "background-position",
            },
            "value" : {
                "-c"  : "center",
                "-l"  : "left",
                "-r"  : "right",
                "-t"  : "top",
                "-b"  : "bottom",
                "-lt" : "left top",
                "-rt" : "right top",
                "-lb" : "left bottom",
                "-rb" : "right bottom"
            }
        },
        {
            "property" : {
                "va" : "vertical-align"
            },
            "value" : {
                "-m"  : "middle",
                "-t"  : "top",
                "-b"  : "bottom"
            }
        },
        {
            "property" : {
                "br" : "border"
            },
            "suffix" : {
                ""    : "-radius",
                "-tl" : "-top-left-radius",
                "-tr" : "-top-right-radius",
                "-bl" : "-bottom-left-radius",
                "-br" : "-bottom-right-radius"
            },
            "loop" : {
                "i" : 8,
                "name" : "'-' + (i*2)",
                "func" : "(i*2) + 'px'"
            },
            "value" : {
                "-99" : "9999px"
            }
        },
        {
            "property" : {
                "c-gray"  : "color",
                "bg-gray" : "background-color"
            },
            "loop" : {
                "i" : 21,  // 0 to 20
                "name" : "'-' + (i*5)",
                "func" : "'hsl(0, 0%, ' + (i*5) + '%)'"
            }
        },
        {
            "property" : {
                "c-hue"  : "color",
                "bg-hue" : "background-color"
            },
            "loop" : {
                "i" : 72,  // 0 to 71
                "name" : "'-' + (i*5)",
                "func" : "'hsl(' + (i*5) + ', 100%, 50%)'"
            },
            "pseudo" : {
                "" : "",
                "-hover" : ":hover"
            }
        }
    ]
}

var style = document.createElement("style");
document.head.appendChild(style);

var m = Object.keys(cssjson.media);
var ml = m.length;

function loopy(ar1, ar2, ar3){
    if(r.loop){
        var i = r.loop.i;
        while(i--){
            style.sheet.insertRule(mv + '.' + mk + pk + ar2 + eval(r.loop.name) + ar1 + "{" + pv + ar3 + ":" + eval(r.loop.func) + "}}", 0);
        }
    }
    if(r.value){
        var v = Object.keys(r.value);
        var vl = v.length;
        while(vl--){
            style.sheet.insertRule(mv + '.' + mk + pk + ar2 + v[vl] + ar1 + "{" + pv + ar3 + ":" + r.value[v[vl]] + "}}", 0);
        }
    }
}

function qwe(a1) {
    if(r.suffix) {
        var s = Object.keys(r.suffix);
        var sl = s.length;
        while(sl--) {
            loopy(a1, s[sl], r.suffix[s[sl]]);
        }
    }else{
        loopy(a1, '', '');
    }
}

while(ml--) {
    var mk = m[ml];
    var mv = cssjson.media[mk];
    var rl = cssjson.rules.length;
    while(rl--){
        var r = cssjson.rules[rl];
        var p = Object.keys(r.property);
        var pl = p.length;
        while(pl--) {
            var pk = p[pl];
            var pv = r.property[pk];
            if(!r.pseudo){
                qwe('');
            }else {
                var ps = Object.keys(r.pseudo);
                var psl = ps.length;
                while(psl--){
                    qwe(ps[psl]+r.pseudo[ps[psl]]);
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>!(function (factory) {
  if (typeof module !== 'undefined' && module.exports)
    module.exports = factory(require('q'))
  else if (typeof define === 'function' && define.amd) define(['q'], factory)
  else this['pj'] = factory(this['Q'])
} (function (Q) {
  var win = window
    , doc = document
    , rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/
    , readyState = 'readyState'
    , xmlHttpRequest = 'XMLHttpRequest'
    , xhr = win[xmlHttpRequest] ?
        function () { return new win[xmlHttpRequest]() } :
        function () { return new win.ActiveXObject('Microsoft.XMLHTTP') }
    , responseText = 'responseText'
    , contentType = 'Content-Type'
    , requestedWith = 'X-Requested-With'
    , defaultHeaders = {
          contentType : 'application/x-www-form-urlencoded; charset=UTF-8'
        , Accept      : {
              '*'    : 'text/javascript, text/html, application/xml,' +
                       ' text/xml, */*'
            , xml    : 'application/xml, text/xml'
            , html   : 'text/html'
            , text   : 'text/plain'
            , json   : 'application/json, text/javascript'
            , script : 'text/javascript, application/javascript,' +
                       ' application/ecmascript, application/x-ecmascript'
          }
        , requestedWith: xmlHttpRequest
      }

    , isArray = Array.isArray || function (obj) {
        return obj instanceof Array
      }

    , isFunction = typeof (/-/) !== 'function' ? function (obj) {
        return typeof obj === 'function'
      } : function (obj) {
        return Object.prototype.toString.call(obj) === '[object Function]'
      }

    , clone = function (o) {
        var copy = {}
          , prop

        for (prop in o) {
          if (o.hasOwnProperty(prop)) copy[prop] = o[prop];
        }

        return copy
      }

    , inferDataType = function (url) {
        var extension = url.substr(url.lastIndexOf('.') + 1)

        if (extension === url) return 'json'
        else if (extension === 'js') return 'script'
        else if (extension === 'txt') return 'text'
        else return extension
      }

    , toQueryString = function (data) {
        var prefix
          , queryStringBuilder = []

          , push = function(key, value) {
              var enc = encodeURIComponent

              value = isFunction(value) ?
                value() :
                (value == null ? '' : value)
              queryStringBuilder.push(enc(key) + '=' + enc(value))
            }

          , buildParams = function (prefix, obj) {
              var name
                , i
                , v

              if (isArray(obj)) {
                for (i = 0; i < obj.length; i++) {
                  v = obj[i]
                  if (/\[\]$/.test(prefix)) {
                    push(prefix, v)
                  }
                  else {
                    buildParams(
                        prefix + '[' + (typeof v === 'object' ? i : '') + ']'
                      , v)
                  }
                }
              }
              else if (obj && typeof obj === 'object') {
                for (name in obj) {
                  if (obj.hasOwnProperty(name))
                    buildParams(prefix + '[' + name + ']', obj[name])
                }
              }
              else push(prefix, obj)
            }

        if (isArray(data)) { // assume output from serializeArray
          for (prefix = 0; prefix < data.length; prefix++) {
            push(data[prefix].name, data[prefix].value)
          }
        }
        else {
          for (prefix in data) {
            if (data.hasOwnProperty(prefix))
              buildParams(prefix, data[prefix])
          }
        }

        return queryStringBuilder.join('&').replace(/%20/g, '+')
      }
    , val = function (el) {
        var v

        if (el.nodeName.toLowerCase() === 'select') {
          v = (function () {
            var v
              , vals = []
              , selectedIndex = el.selectedIndex
              , opt
              , options = el.options
              , isSingleSelect = el.type === 'select-one'
              , i
              , max

            if (selectedIndex < 0) return null

            i = isSingleSelect ? selectedIndex : 0;
            max = isSingleSelect ? selectedIndex + 1 : options.length;
            for (; i < max; i++) {
              opt = options[i]

              if (opt.selected && !opt.disabled &&
                  (!opt.parentNode.disabled ||
                    opt.parentNode.nodeName.toLowerCase() !== 'optgroup')) {
                v = val(opt)

                if (isSingleSelect) return v
                vals.push(v)
              }
            }

            return vals
          } ())
        }
        else if (el.nodeName.toLowerCase() === 'option') {
          v = el.attributes.value;
          return !v || v.specified ? el.value : el.text;
        }
        else if (el.type === 'button' ||
            el.nodeName.toLowerCase() === 'button') {
          v = el.getAttributeNode('value')
          return v ? v.value : undefined
        }
        else if (el.type === 'radio' || el.type === 'checkbox') {
          return el.getAttribute('value') === null ? 'on' : el.value
        }
        else {
          v = el.value;
        }

        return typeof v === 'string' ?
          v.replace(/\r/g, '') :
          v == null ? '' : v;
      }

    , urlAppend = function (url, dataString) {
        if (typeof dataString !== 'string') return url
        return url + (url.indexOf('?') !== -1 ? '&' : '?') + dataString
      }

    , setHeaders = function (http, options) {
        var headers = options.headers || {}
          , accept = 'Accept'
          , h

        headers[accept] = headers[accept] ||
          defaultHeaders[accept][options.dataType] ||
          defaultHeaders[accept]['*']

        if (!options.crossDomain && !headers[requestedWith])
          headers[requestedWith] = defaultHeaders.requestedWith
        if (!headers[contentType])
          headers[contentType] = options.contentType ||
            defaultHeaders.contentType
        for (h in headers)
          if (headers.hasOwnProperty(h)) http.setRequestHeader(h, headers[h])
      }

    , defaultParser = function (deferred) {
        deferred.resolve(this)
      }

    , responseParsers = {
        json   : function (deferred) {
          var r = this[responseText]

          try {
            r = win.JSON ? win.JSON.parse(r) : eval('(' + r + ')')
            deferred.resolve(r)
          } catch (err) {
            deferred.reject(new Error('Could not parse JSON in response.'))
          }
        }
      , script : function (deferred) {
          try {
            deferred.resolve(eval(this[responseText]))
          } catch (err) {
            deferred.reject(err)
          }
        }
      , text   : function (deferred) {
          deferred.resolve(String(this[responseText]))
        }
      , html   : function (deferred) {
          deferred.resolve(this[responseText])
        }
      , xml    : function (deferred) {
          var r = this.responseXML
          // Chrome makes `responseXML` null;
          // IE makes `documentElement` null;
          // FF makes up an element;
          // this is my attempt at standardization
          if (r === null || r.documentElement === null ||
              r.documentElement.nodeName === 'parsererror')
            deferred.resolve(null)
          else deferred.resolve(r)
        }
      }

    , sendLocal = function (o, deferred) {
        var http = isFunction(o.xhr) ? o.xhr() : xhr()

        http.open(o.type, o.url, true)
        setHeaders(http, o)

        http.onreadystatechange = function () {
          var status

          if (http && http[readyState] === 4) {
            status = http.status
            if (status >= 200 && status < 300 ||
                status === 304 ||
                status === 0 && http[responseText] !== '') {
              if (http[responseText])
                (responseParsers[o.dataType] || defaultParser)
                  .call(http, deferred)
              else
                deferred.resolve(null)
            }
            else deferred.reject(
                    new Error(o.type + ' ' + o.url + ': ' +
                      http.status + ' ' + http.statusText))
          }
        }

        try {
          http.send(o.data)
        } catch (err) {
          deferred.reject(err)
        }
      }

    , isCrossDomain = function (url, defaultUrl) {
        var parts = rurl.exec(url)
          , defaultParts = rurl.exec(defaultUrl)
        return !!(parts &&
          (parts[1] !== defaultParts[1] || parts[2] !== defaultParts[2] ||
            (parts[3] || (parts[1] === 'http:' ? 80 : 443)) !==
              (defaultParts[3] || (defaultParts[1] === 'http:' ? 80 : 443 ))))
      }
    , sendRemote = function (o, deferred) {
        var head = document.head || document.getElementsByTagName('head')[0] ||
            document.documentElement
          , script = document.createElement('script')
          , callbackName
          , callback
        script.async = 'async'
        if (o.dataType === 'jsonp') {
          callbackName =  o.jsonp || 'pajamas' +
            (Date.now || function () { return (new Date()).getTime() }).call()
          callback = function (data) {
            window[callbackName] = undefined
            try {
              delete window[callbackName]
            } catch (e) {}
            deferred.resolve(data)
          }
          window[callbackName] = callback
          //TODO: need timeout or this can never be rejected
          o.url += (o.url.indexOf('?') > -1 ? '&' : '?') +
            (o.jsonp || 'callback') + '=' + callbackName
          script.src = o.url
        }
        else {
          script.src = o.url
        }
        script.onload = script.onreadystatechange = function(_, isAbort) {
          if (isAbort || !script.readyState ||
            /loaded|complete/.test(script.readyState)) {
            script.onload = script.onreadystatechange = null;
            if (head && script.parentNode) {
              head.removeChild(script);
            }
            script = undefined;
            if (!isAbort) {
              if (o.dataType !== 'jsonp') deferred.resolve()
            }
          else deferred.reject(new Error(o.url + ' aborted'))
          }
        }
        head.appendChild(script)
      }
    , pajamas = function (options) {
        var deferred = Q.defer()
          , promise = deferred.promise
          , o = options == null ? {} : clone(options)
          , defaultUrl = (function () {
              var anchor
              try {
                return location.href
              } catch (e) {
                anchor = doc.createElement('a')
                anchor.href = ''
                return anchor.href
              }
            } ())
        o.type = o.type ? o.type.toUpperCase() : 'GET'
        o.url || (o.url = defaultUrl)
        o.data = (o.data && o.processData !== false &&
            typeof o.data !== 'string') ?
          toQueryString(o.data) :
          (o.data || null)
        o.dataType || (o.dataType = inferDataType(o.url))
        o.crossDomain || (o.crossDomain = isCrossDomain(o.url, defaultUrl))
        if (o.data && typeof o.data === 'string' && o.type === 'GET') {
          o.url = urlAppend(o.url, o.data)
          o.data = null
        }
        if (!o.crossDomain && o.dataType !== 'jsonp') sendLocal(o, deferred)
        else sendRemote(o, deferred)
        return promise;
      }

  pajamas.param = toQueryString
  pajamas.val = val
  pajamas.serializeArray = function () {
    var arr = []
      , i
      , el
      , crlf = /\r?\n/g
      , checkableType = /radio|checkbox/i
      , pushAll = function (elems) {
          var el
            , v
            , i
            , j
          for (i = 0; i < elems.length; i++) {
            el = elems[i]
            if (el.name && !el.disabled &&
                (checkableType.test(el.type) ? el.checked : true)) {
              v = val(el)
              if (v != null) {
                if (isArray(v)) { // from multiple select, for instance
                  for (j = 0; j < v.length; j++) {
                    arr.push({
                        name  : el.name
                      , value : v[j].replace(crlf, '\r\n')
                    })
                  }
                }
                else {
                  arr.push({
                      name  : el.name
                    , value : v.replace(crlf, '\r\n')
                  })
                }
              }
            }
          }
        }
    for (i = 0; i < arguments.length; i++) {
      el = arguments[i]
      el.elements ? pushAll(el.elements) : pushAll([el])
    }
    return arr
  }
  pajamas.serialize = function (){
    return pajamas.param(pajamas.serializeArray.apply(null, arguments))
  }

  return pajamas
}))
<commit_msg>moving code around. all exposed functions are defined where they are exposed.<commit_after>!(function (factory) {
  if (typeof module !== 'undefined' && module.exports)
    module.exports = factory(require('q'))
  else if (typeof define === 'function' && define.amd) define(['q'], factory)
  else this['pj'] = factory(this['Q'])
} (function (Q) {
  var win = window
    , doc = document
    , rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/
    , readyState = 'readyState'
    , xmlHttpRequest = 'XMLHttpRequest'
    , xhr = win[xmlHttpRequest] ?
        function () { return new win[xmlHttpRequest]() } :
        function () { return new win.ActiveXObject('Microsoft.XMLHTTP') }
    , responseText = 'responseText'
    , contentType = 'Content-Type'
    , requestedWith = 'X-Requested-With'
    , defaultHeaders = {
          contentType : 'application/x-www-form-urlencoded; charset=UTF-8'
        , Accept      : {
              '*'    : 'text/javascript, text/html, application/xml,' +
                       ' text/xml, */*'
            , xml    : 'application/xml, text/xml'
            , html   : 'text/html'
            , text   : 'text/plain'
            , json   : 'application/json, text/javascript'
            , script : 'text/javascript, application/javascript,' +
                       ' application/ecmascript, application/x-ecmascript'
          }
        , requestedWith: xmlHttpRequest
      }

    , isArray = Array.isArray || function (obj) {
        return obj instanceof Array
      }

    , isFunction = typeof (/-/) !== 'function' ? function (obj) {
        return typeof obj === 'function'
      } : function (obj) {
        return Object.prototype.toString.call(obj) === '[object Function]'
      }

    , clone = function (o) {
        var copy = {}
          , prop

        for (prop in o) {
          if (o.hasOwnProperty(prop)) copy[prop] = o[prop];
        }

        return copy
      }

    , inferDataType = function (url) {
        var extension = url.substr(url.lastIndexOf('.') + 1)

        if (extension === url) return 'json'
        else if (extension === 'js') return 'script'
        else if (extension === 'txt') return 'text'
        else return extension
      }

    , urlAppend = function (url, dataString) {
        if (typeof dataString !== 'string') return url
        return url + (url.indexOf('?') !== -1 ? '&' : '?') + dataString
      }

    , setHeaders = function (http, options) {
        var headers = options.headers || {}
          , accept = 'Accept'
          , h

        headers[accept] = headers[accept] ||
          defaultHeaders[accept][options.dataType] ||
          defaultHeaders[accept]['*']

        if (!options.crossDomain && !headers[requestedWith])
          headers[requestedWith] = defaultHeaders.requestedWith
        if (!headers[contentType])
          headers[contentType] = options.contentType ||
            defaultHeaders.contentType
        for (h in headers)
          if (headers.hasOwnProperty(h)) http.setRequestHeader(h, headers[h])
      }

    , defaultParser = function (deferred) {
        deferred.resolve(this)
      }

    , responseParsers = {
        json   : function (deferred) {
          var r = this[responseText]

          try {
            r = win.JSON ? win.JSON.parse(r) : eval('(' + r + ')')
            deferred.resolve(r)
          } catch (err) {
            deferred.reject(new Error('Could not parse JSON in response.'))
          }
        }
      , script : function (deferred) {
          try {
            deferred.resolve(eval(this[responseText]))
          } catch (err) {
            deferred.reject(err)
          }
        }
      , text   : function (deferred) {
          deferred.resolve(String(this[responseText]))
        }
      , html   : function (deferred) {
          deferred.resolve(this[responseText])
        }
      , xml    : function (deferred) {
          var r = this.responseXML
          // Chrome makes `responseXML` null;
          // IE makes `documentElement` null;
          // FF makes up an element;
          // this is my attempt at standardization
          if (r === null || r.documentElement === null ||
              r.documentElement.nodeName === 'parsererror')
            deferred.resolve(null)
          else deferred.resolve(r)
        }
      }

    , sendLocal = function (o, deferred) {
        var http = isFunction(o.xhr) ? o.xhr() : xhr()

        http.open(o.type, o.url, true)
        setHeaders(http, o)

        http.onreadystatechange = function () {
          var status

          if (http && http[readyState] === 4) {
            status = http.status
            if (status >= 200 && status < 300 ||
                status === 304 ||
                status === 0 && http[responseText] !== '') {
              if (http[responseText])
                (responseParsers[o.dataType] || defaultParser)
                  .call(http, deferred)
              else
                deferred.resolve(null)
            }
            else deferred.reject(
                    new Error(o.type + ' ' + o.url + ': ' +
                      http.status + ' ' + http.statusText))
          }
        }

        try {
          http.send(o.data)
        } catch (err) {
          deferred.reject(err)
        }
      }

    , isCrossDomain = function (url, defaultUrl) {
        var parts = rurl.exec(url)
          , defaultParts = rurl.exec(defaultUrl)
        return !!(parts &&
          (parts[1] !== defaultParts[1] || parts[2] !== defaultParts[2] ||
            (parts[3] || (parts[1] === 'http:' ? 80 : 443)) !==
              (defaultParts[3] || (defaultParts[1] === 'http:' ? 80 : 443 ))))
      }
    , sendRemote = function (o, deferred) {
        var head = document.head || document.getElementsByTagName('head')[0] ||
            document.documentElement
          , script = document.createElement('script')
          , callbackName
          , callback
        script.async = 'async'
        if (o.dataType === 'jsonp') {
          callbackName =  o.jsonp || 'pajamas' +
            (Date.now || function () { return (new Date()).getTime() }).call()
          callback = function (data) {
            window[callbackName] = undefined
            try {
              delete window[callbackName]
            } catch (e) {}
            deferred.resolve(data)
          }
          window[callbackName] = callback
          //TODO: need timeout or this can never be rejected
          o.url += (o.url.indexOf('?') > -1 ? '&' : '?') +
            (o.jsonp || 'callback') + '=' + callbackName
          script.src = o.url
        }
        else {
          script.src = o.url
        }
        script.onload = script.onreadystatechange = function(_, isAbort) {
          if (isAbort || !script.readyState ||
            /loaded|complete/.test(script.readyState)) {
            script.onload = script.onreadystatechange = null;
            if (head && script.parentNode) {
              head.removeChild(script);
            }
            script = undefined;
            if (!isAbort) {
              if (o.dataType !== 'jsonp') deferred.resolve()
            }
          else deferred.reject(new Error(o.url + ' aborted'))
          }
        }
        head.appendChild(script)
      }
    , pajamas = function (options) {
        var deferred = Q.defer()
          , promise = deferred.promise
          , o = options == null ? {} : clone(options)
          , defaultUrl = (function () {
              var anchor
              try {
                return location.href
              } catch (e) {
                anchor = doc.createElement('a')
                anchor.href = ''
                return anchor.href
              }
            } ())
        o.type = o.type ? o.type.toUpperCase() : 'GET'
        o.url || (o.url = defaultUrl)
        o.data = (o.data && o.processData !== false &&
            typeof o.data !== 'string') ?
          pajamas.param(o.data) :
          (o.data || null)
        o.dataType || (o.dataType = inferDataType(o.url))
        o.crossDomain || (o.crossDomain = isCrossDomain(o.url, defaultUrl))
        if (o.data && typeof o.data === 'string' && o.type === 'GET') {
          o.url = urlAppend(o.url, o.data)
          o.data = null
        }
        if (!o.crossDomain && o.dataType !== 'jsonp') sendLocal(o, deferred)
        else sendRemote(o, deferred)
        return promise;
      }

  pajamas.param = function (data) {
    var prefix
      , queryStringBuilder = []

      , push = function(key, value) {
          var enc = encodeURIComponent

          value = isFunction(value) ?
            value() :
            (value == null ? '' : value)
          queryStringBuilder.push(enc(key) + '=' + enc(value))
        }

      , buildParams = function (prefix, obj) {
          var name
            , i
            , v

          if (isArray(obj)) {
            for (i = 0; i < obj.length; i++) {
              v = obj[i]
              if (/\[\]$/.test(prefix)) {
                push(prefix, v)
              }
              else {
                buildParams(
                    prefix + '[' + (typeof v === 'object' ? i : '') + ']'
                  , v)
              }
            }
          }
          else if (obj && typeof obj === 'object') {
            for (name in obj) {
              if (obj.hasOwnProperty(name))
                buildParams(prefix + '[' + name + ']', obj[name])
            }
          }
          else push(prefix, obj)
        }

    if (isArray(data)) { // assume output from serializeArray
      for (prefix = 0; prefix < data.length; prefix++) {
        push(data[prefix].name, data[prefix].value)
      }
    }
    else {
      for (prefix in data) {
        if (data.hasOwnProperty(prefix))
          buildParams(prefix, data[prefix])
      }
    }

    return queryStringBuilder.join('&').replace(/%20/g, '+')
  }

  pajamas.val = function (el) {
    var v

    if (el.nodeName.toLowerCase() === 'select') {
      v = (function () {
        var v
          , vals = []
          , selectedIndex = el.selectedIndex
          , opt
          , options = el.options
          , isSingleSelect = el.type === 'select-one'
          , i
          , max

        if (selectedIndex < 0) return null

        i = isSingleSelect ? selectedIndex : 0;
        max = isSingleSelect ? selectedIndex + 1 : options.length;
        for (; i < max; i++) {
          opt = options[i]

          if (opt.selected && !opt.disabled &&
              (!opt.parentNode.disabled ||
                opt.parentNode.nodeName.toLowerCase() !== 'optgroup')) {
            v = pajamas.val(opt)

            if (isSingleSelect) return v
            vals.push(v)
          }
        }

        return vals
      } ())
    }
    else if (el.nodeName.toLowerCase() === 'option') {
      v = el.attributes.value;
      return !v || v.specified ? el.value : el.text;
    }
    else if (el.type === 'button' ||
        el.nodeName.toLowerCase() === 'button') {
      v = el.getAttributeNode('value')
      return v ? v.value : undefined
    }
    else if (el.type === 'radio' || el.type === 'checkbox') {
      return el.getAttribute('value') === null ? 'on' : el.value
    }
    else {
      v = el.value;
    }

    return typeof v === 'string' ?
      v.replace(/\r/g, '') :
      v == null ? '' : v;
  }

  pajamas.serializeArray = function () {
    var arr = []
      , i
      , el
      , crlf = /\r?\n/g
      , checkableType = /radio|checkbox/i
      , pushAll = function (elems) {
          var el
            , v
            , i
            , j
          for (i = 0; i < elems.length; i++) {
            el = elems[i]
            if (el.name && !el.disabled &&
                (checkableType.test(el.type) ? el.checked : true)) {
              v = pajamas.val(el)
              if (v != null) {
                if (isArray(v)) { // from multiple select, for instance
                  for (j = 0; j < v.length; j++) {
                    arr.push({
                        name  : el.name
                      , value : v[j].replace(crlf, '\r\n')
                    })
                  }
                }
                else {
                  arr.push({
                      name  : el.name
                    , value : v.replace(crlf, '\r\n')
                  })
                }
              }
            }
          }
        }
    for (i = 0; i < arguments.length; i++) {
      el = arguments[i]
      el.elements ? pushAll(el.elements) : pushAll([el])
    }
    return arr
  }
  pajamas.serialize = function (){
    return pajamas.param(pajamas.serializeArray.apply(null, arguments))
  }

  return pajamas
}))
<|endoftext|>


<commit_before>!(function (factory) {
  if (typeof module !== 'undefined' && module.exports) module.exports = factory(require('q'))
  else if (typeof define === 'function' && define.amd) define(['q'], factory)
  else this['pj'] = factory(this['Q'])
} (function (Q) {
  var win = window
    , doc = document
    , rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/
    , readyState = 'readyState'
    , xmlHttpRequest = 'XMLHttpRequest'
    , xhr = win[xmlHttpRequest] ?
        function () { return new win[xmlHttpRequest]() } :
        function () { return new win.ActiveXObject('Microsoft.XMLHTTP') }
    , responseText = 'responseText'
    , contentType = 'Content-Type'
    , requestedWith = 'X-Requested-With'
    , defaultHeaders = {
          contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
        , Accept: {
              '*'    : 'text/javascript, text/html, application/xml,' +
                       ' text/xml, */*'
            , xml    : 'application/xml, text/xml'
            , html   : 'text/html'
            , text   : 'text/plain'
            , json   : 'application/json, text/javascript'
            , script : 'text/javascript, application/javascript,' +
                       ' application/ecmascript, application/x-ecmascript'
          }
        , requestedWith: xmlHttpRequest
      }
    , isArray = Array.isArray || function (obj) {
        return obj instanceof Array
      }
    , isFunction = typeof (/-/) !== 'function' ? function (obj) {
        return typeof obj === 'function'
      } : function (obj) {
        return Object.prototype.toString.call(obj) === '[object Function]'
      }
    , inferDataType = function (url) {
        var extension = url.substr(url.lastIndexOf('.') + 1)
        if (extension === url) return 'json'
        else if (extension === 'js') return 'script'
        else if (extension === 'txt') return 'text'
        else return extension
      }
    , urlAppend = function (url, dataString) {
        if (typeof dataString !== 'string') return url
        return url + (url.indexOf('?') !== -1 ? '&' : '?') + dataString
      }
    , setHeaders = function (http, options) {
        var headers = options.headers || {}
          , accept = 'Accept'
          , h

        headers[accept] = headers[accept] ||
          defaultHeaders[accept][options.dataType] ||
          defaultHeaders[accept]['*']

        if (!options.crossDomain && !headers[requestedWith])
          headers[requestedWith] = defaultHeaders.requestedWith
        if (!headers[contentType])
          headers[contentType] = options.contentType ||
            defaultHeaders.contentType
        for (h in headers)
          if (headers.hasOwnProperty(h)) http.setRequestHeader(h, headers[h])
      }
    , toQueryString = function (data) {
        var queryString = ''
          , enc = encodeURIComponent
          , push = function (k, v) {
              queryString += enc(k) + '=' + enc(v) + '&'
            }
          , i
          , val
          , prop

        if (isArray(data)) {
          for (i = 0; data && i < data.length; i++)
            push(data[i].name, data[i].value)
        } else {
          for (prop in data) {
            if (data.hasOwnProperty(prop)) {
              val = data[prop]
              if (isArray(val))
                for (i = 0; i < val.length; i++) push(prop, val[i])
              else push(prop, data[prop])
            }
          }
        }

        return queryString.replace(/&$/, '').replace(/%20/g,'+')
      }
    , defaultParser = function (deferred) {
        deferred.resolve(this)
      }
    , responseParsers = {
        json   : function (deferred) {
          var r = this[responseText]
          try {
            r = win.JSON ? win.JSON.parse(r) : eval('(' + r + ')')
            deferred.resolve(r)
          } catch (err) {
            deferred.reject(new Error('Could not parse JSON in response.'))
          }
        }
      , script : function (deferred) {
          try {
            deferred.resolve(eval(this[responseText]))
          } catch (err) {
            deferred.reject(err)
          }
        }
      , text   : function (deferred) {
          deferred.resolve(String(this[responseText]))
        }
      , html   : function (deferred) {
          deferred.resolve(this[responseText])
        }
      , xml    : function (deferred) {
          var r = this.responseXML
          // Chrome makes `responseXML` null;
          // IE makes `documentElement` null;
          // FF makes up an element;
          // this is my attempt at standardization
          if (r === null || r.documentElement === null ||
              r.documentElement.nodeName === 'parsererror')
            deferred.resolve(null)
          else deferred.resolve(this.responseXML)
        }
      }
    , clone = function (o) {
        var copy = {}
          , prop
        for (prop in o) {
          if (o.hasOwnProperty(prop)) copy[prop] = o[prop];
        }
        return copy
      }
    , sendLocal = function (o, deferred) {
        var http = isFunction(o.xhr) ? o.xhr() : xhr()
        http.open(o.method, o.url, true)
        setHeaders(http, o)
        http.onreadystatechange = function () {
          var status
          if (http && http[readyState] === 4) {
            status = http.status
            if (status >= 200 && status < 300 ||
                status === 304 ||
                status === 0 && http[responseText] !== '') {
              if (http[responseText])
                (responseParsers[o.dataType] || defaultParser).call(http, deferred)
              else
                deferred.resolve(null)
            } else deferred.reject(
                    new Error(o.method + ' ' + o.url + ': ' +
                      http.status + ' ' + http.statusText))
          }
        }
        try {
          http.send(o.data)
        } catch (err) {
          deferred.reject(err)
        }
      }
    , isCrossDomain = function (url, defaultUrl) {
        var parts = rurl.exec(url)
          , defaultParts = rurl.exec(defaultUrl)
        return !!(parts &&
          (parts[1] !== defaultParts[1] || parts[2] !== defaultParts[2] ||
            (parts[3] || (parts[1] === "http:" ? 80 : 443)) !==
              (defaultParts[3] || (defaultParts[1] === "http:" ? 80 : 443 ))))
      }
    , sendRemote = function (o, deferred) {
        var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement
          , script = document.createElement('script')
          , callbackName
          , callback
        script.async = 'async'
        if (o.dataType === 'jsonp') {
          callbackName =  o.jsonp || 'pajamas' + (Date.now || function () { return (new Date()).getTime() }).call()
          callback = function (data) {
            delete window[callbackName]
            deferred.resolve(data)
          }
          window[callbackName] = callback
          //TODO: need timeout or this can never be rejected
          o.url += (o.url.indexOf('?') > -1 ? '&' : '?') + (o.jsonp || 'callback') + '=' + callbackName
          script.src = o.url
        }
        else {
          script.src = o.url
        }
        script.onload = script.onreadystatechange = function(_, isAbort) {
          if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
            script.onload = script.onreadystatechange = null;
            if (head && script.parentNode) {
              head.removeChild(script);
            }
            script = undefined;
            if (!isAbort) {
              if (o.dataType !== 'jsonp') deferred.resolve()
            }
          else deferred.reject(new Error(o.url + ' aborted'))
          }
        }
        head.appendChild(script)
      }

  return function (options) {
    var deferred = Q.defer()
      , promise = deferred.promise
      , o = options == null ? {} : clone(options)
      , defaultUrl = (function () {
          var anchor
          try {
            return location.href
          } catch (e) {
            anchor = doc.createElement('a')
            anchor.href = ''
            return anchor.href
          }
        } ())
    o.method = o.method ? o.method.toUpperCase() : 'GET'
    o.url || (o.url = defaultUrl)
    o.data = (o.data && o.processData !== false && typeof o.data !== 'string') ?
      toQueryString(o.data) :
      (o.data || null)
    o.dataType || (o.dataType = inferDataType(o.url))
    o.crossDomain || (o.crossDomain = isCrossDomain(o.url, defaultUrl))
    if (o.data && o.method === 'GET') {
      o.url = urlAppend(o.url, o.data)
      o.data = null
    }
    if (!o.crossDomain && o.dataType !== 'jsonp') sendLocal(o, deferred)
    else sendRemote(o, deferred)
    return promise;
  }
}))
<commit_msg>static methods for serializing objects and forms<commit_after>!(function (factory) {
  if (typeof module !== 'undefined' && module.exports)
    module.exports = factory(require('q'))
  else if (typeof define === 'function' && define.amd) define(['q'], factory)
  else this['pj'] = factory(this['Q'])
} (function (Q) {
  var win = window
    , doc = document
    , rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/
    , readyState = 'readyState'
    , xmlHttpRequest = 'XMLHttpRequest'
    , xhr = win[xmlHttpRequest] ?
        function () { return new win[xmlHttpRequest]() } :
        function () { return new win.ActiveXObject('Microsoft.XMLHTTP') }
    , responseText = 'responseText'
    , contentType = 'Content-Type'
    , requestedWith = 'X-Requested-With'
    , defaultHeaders = {
          contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
        , Accept: {
              '*'    : 'text/javascript, text/html, application/xml,' +
                       ' text/xml, */*'
            , xml    : 'application/xml, text/xml'
            , html   : 'text/html'
            , text   : 'text/plain'
            , json   : 'application/json, text/javascript'
            , script : 'text/javascript, application/javascript,' +
                       ' application/ecmascript, application/x-ecmascript'
          }
        , requestedWith: xmlHttpRequest
      }
    , isArray = Array.isArray || function (obj) {
        return obj instanceof Array
      }
    , isFunction = typeof (/-/) !== 'function' ? function (obj) {
        return typeof obj === 'function'
      } : function (obj) {
        return Object.prototype.toString.call(obj) === '[object Function]'
      }
    , inferDataType = function (url) {
        var extension = url.substr(url.lastIndexOf('.') + 1)
        if (extension === url) return 'json'
        else if (extension === 'js') return 'script'
        else if (extension === 'txt') return 'text'
        else return extension
      }
    , urlAppend = function (url, dataString) {
        if (typeof dataString !== 'string') return url
        return url + (url.indexOf('?') !== -1 ? '&' : '?') + dataString
      }
    , setHeaders = function (http, options) {
        var headers = options.headers || {}
          , accept = 'Accept'
          , h

        headers[accept] = headers[accept] ||
          defaultHeaders[accept][options.dataType] ||
          defaultHeaders[accept]['*']

        if (!options.crossDomain && !headers[requestedWith])
          headers[requestedWith] = defaultHeaders.requestedWith
        if (!headers[contentType])
          headers[contentType] = options.contentType ||
            defaultHeaders.contentType
        for (h in headers)
          if (headers.hasOwnProperty(h)) http.setRequestHeader(h, headers[h])
      }
    , toQueryString = function (data) {
        var queryStringBuilder = []
          , enc = encodeURIComponent
          , push = function (k, v) {
              queryStringBuilder.push(enc(k) + '=' + enc(v))
            }
          , i
          , val
          , prop

        if (isArray(data)) {
          for (i = 0; data && i < data.length; i++)
            push(data[i].name, data[i].value)
        } else {
          for (prop in data) {
            if (data.hasOwnProperty(prop)) {
              val = data[prop]
              if (isArray(val))
                for (i = 0; i < val.length; i++) push(prop + '[]', val[i])
              else push(prop, data[prop])
            }
          }
        }

        return queryStringBuilder.join('&').replace(/%20/g,'+')
      }
    , val = function (el) {
        var v

        if (el.nodeName === 'select') {
          v = (function () {
            var v
              , vals = []
              , selectedIndex = el.selectedIndex
              , values = []
              , opt
              , options = el.options
              , one = el.type === 'select-one'
              , i
              , max

            if (selectedIndex < 0) return null

            i = one ? selectedIndex : 0;
            max = one ? selectedIndex + 1 : options.length;
            for (; i < max; i++) {
              opt = options[i]

              if (opt.selected && !opt.disabled &&
                  (!opt.parentNode.disabled ||
                    opt.parentNode.nodeName.toLowerCase() !== 'optgroup')) {
                v = val(opt)

                if (one) return v
                vals.push(v);
              }
            }

            return vals;
          } ())
        }
        else if (el.nodeName === 'option') {
          v = el.attributes.value;
          return !v || v.specified ? el.value : el.text;
        }
        else {
          v = el.value;
        }

        return typeof v === 'string' ?
          v.replace(/\r/g, '') :
          v == null ? '' : v;
      }
    , defaultParser = function (deferred) {
        deferred.resolve(this)
      }
    , responseParsers = {
        json   : function (deferred) {
          var r = this[responseText]
          try {
            r = win.JSON ? win.JSON.parse(r) : eval('(' + r + ')')
            deferred.resolve(r)
          } catch (err) {
            deferred.reject(new Error('Could not parse JSON in response.'))
          }
        }
      , script : function (deferred) {
          try {
            deferred.resolve(eval(this[responseText]))
          } catch (err) {
            deferred.reject(err)
          }
        }
      , text   : function (deferred) {
          deferred.resolve(String(this[responseText]))
        }
      , html   : function (deferred) {
          deferred.resolve(this[responseText])
        }
      , xml    : function (deferred) {
          var r = this.responseXML
          // Chrome makes `responseXML` null;
          // IE makes `documentElement` null;
          // FF makes up an element;
          // this is my attempt at standardization
          if (r === null || r.documentElement === null ||
              r.documentElement.nodeName === 'parsererror')
            deferred.resolve(null)
          else deferred.resolve(this.responseXML)
        }
      }
    , clone = function (o) {
        var copy = {}
          , prop
        for (prop in o) {
          if (o.hasOwnProperty(prop)) copy[prop] = o[prop];
        }
        return copy
      }
    , sendLocal = function (o, deferred) {
        var http = isFunction(o.xhr) ? o.xhr() : xhr()
        http.open(o.method, o.url, true)
        setHeaders(http, o)
        http.onreadystatechange = function () {
          var status
          if (http && http[readyState] === 4) {
            status = http.status
            if (status >= 200 && status < 300 ||
                status === 304 ||
                status === 0 && http[responseText] !== '') {
              if (http[responseText])
                (responseParsers[o.dataType] || defaultParser)
                  .call(http, deferred)
              else
                deferred.resolve(null)
            } else deferred.reject(
                    new Error(o.method + ' ' + o.url + ': ' +
                      http.status + ' ' + http.statusText))
          }
        }
        try {
          http.send(o.data)
        } catch (err) {
          deferred.reject(err)
        }
      }
    , isCrossDomain = function (url, defaultUrl) {
        var parts = rurl.exec(url)
          , defaultParts = rurl.exec(defaultUrl)
        return !!(parts &&
          (parts[1] !== defaultParts[1] || parts[2] !== defaultParts[2] ||
            (parts[3] || (parts[1] === "http:" ? 80 : 443)) !==
              (defaultParts[3] || (defaultParts[1] === "http:" ? 80 : 443 ))))
      }
    , sendRemote = function (o, deferred) {
        var head = document.head || document.getElementsByTagName('head')[0] ||
            document.documentElement
          , script = document.createElement('script')
          , callbackName
          , callback
        script.async = 'async'
        if (o.dataType === 'jsonp') {
          callbackName =  o.jsonp || 'pajamas' +
            (Date.now || function () { return (new Date()).getTime() }).call()
          callback = function (data) {
            delete window[callbackName]
            deferred.resolve(data)
          }
          window[callbackName] = callback
          //TODO: need timeout or this can never be rejected
          o.url += (o.url.indexOf('?') > -1 ? '&' : '?') +
            (o.jsonp || 'callback') + '=' + callbackName
          script.src = o.url
        }
        else {
          script.src = o.url
        }
        script.onload = script.onreadystatechange = function(_, isAbort) {
          if (isAbort || !script.readyState ||
            /loaded|complete/.test(script.readyState)) {
            script.onload = script.onreadystatechange = null;
            if (head && script.parentNode) {
              head.removeChild(script);
            }
            script = undefined;
            if (!isAbort) {
              if (o.dataType !== 'jsonp') deferred.resolve()
            }
          else deferred.reject(new Error(o.url + ' aborted'))
          }
        }
        head.appendChild(script)
      }
    , pajamas = function (options) {
        var deferred = Q.defer()
          , promise = deferred.promise
          , o = options == null ? {} : clone(options)
          , defaultUrl = (function () {
              var anchor
              try {
                return location.href
              } catch (e) {
                anchor = doc.createElement('a')
                anchor.href = ''
                return anchor.href
              }
            } ())
        o.method = o.method ? o.method.toUpperCase() : 'GET'
        o.url || (o.url = defaultUrl)
        o.data = (o.data && o.processData !== false &&
            typeof o.data !== 'string') ?
          toQueryString(o.data) :
          (o.data || null)
        o.dataType || (o.dataType = inferDataType(o.url))
        o.crossDomain || (o.crossDomain = isCrossDomain(o.url, defaultUrl))
        if (o.data && o.method === 'GET') {
          o.url = urlAppend(o.url, o.data)
          o.data = null
        }
        if (!o.crossDomain && o.dataType !== 'jsonp') sendLocal(o, deferred)
        else sendRemote(o, deferred)
        return promise;
      }

  pajamas.param = toQueryString
  pajamas.val = val
  pajamas.serializeArray = function () {
    var arr = []
      , i
      , j
      , e
      , crlf = /\r?\n/g
      , pushAll = function (elems) {
          for (var j = 0; j < elems.length; j++)
            arr.push({
                name : elems[j].name
              , value: val(elems[j]).replace(crlf, '\r\n')
            })
        }
    for (i = 0; i < arguments.length; i++) {
      e = arguments[i]
      e.elements ?
        pushAll(e.elements) :
        arr.push({ name : e.name, value : val(e).replace(crlf, '\r\n') })
    }
    return arr
  }
  pajamas.serialize = function (){
    return pajamas.param(pajamas.serializeArray.apply(null, arguments))
  }

  return pajamas
}))
<|endoftext|>


<commit_before>/// pandora.js --- Module packing and unpacking on steroids
//
// Copyright (c) 2012 Quildreen Motta
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/// Module pandora
//
// Pandora is a module abstraction library, that brings combinators for
// handling first-class modules in JavaScript. Modules are treated as
// simple native objects, which can already be handled through the
// object services provided by the JavaScript language itself.
//
// Pandora extends these core services with a series of pure monadic
// combinators, which brings a declarative-ish syntax for module
// definition and formal contracts a module expects to be met.
//
// There is no need for providing a CommonJS module service under
// Pandora, since the library works directly on objects. On environments
// that support CommonJS modules, however, users can leverage better
// modularisation and a rather more declarative syntax.

//// -- Aliases --------------------------------------------------------
var inherit = Object.create
var proto   = Object.getPrototypeOf
var keys    = Object.keys

var slice   = [].slice.call.bind([].slice)
var clone   = with_mappings

//// -- Core interface -------------------------------------------------
function pandora(service) {
  return Pandora.make(service) }

function merge() {
  var boxed     = slice(arguments)
  var required  = []
  var overrides = {}
  var result    = boxed.reduce( function(result, module) {
                                  copy_keys(module, result, overrides)
                                  required.push.apply(required, module._required)
                                  return result }
                              , { } )

  return !satisfied_p(result, required)?  raise(PandoraNotSatisfiedE(required))
  :      /* otherwise */                  result }

//// -- Helpers --------------------------------------------------------
function satisfied_p(object, names) {
  return names.every(function(key) {
                       return key in object }) }

function copy_keys(origin, target, overrides) {
  var module = origin._value
  keys(module).forEach(function(key) {
                         !(key in target)?   target[key] = module[key]
                         : override_p(key)?  target[key]    = module[key]
                         : !overrides[key]?  raise(PandoraCollisionE(key))
                         : /* otherwise */   null // already overriden

                         overrides[key] = overrides[key] || origin._overrides[key] })

  return target

  function override_p(key) {
    if (origin._overrides[key] && overrides[key])  throw PandoraOverrideCollisionE(key)
    return origin._overrides[key] }}

function identity(x) {
  return x }

function callable_p(subject) {
  return typeof subject == 'function' }

function with_properties(origin, names, mapping) {
  mapping = mapping || identity
  return names.reduce( function(result, key) {
                         result[mapping(key)] = origin[key]
                         return result }
                     , {} )}

function with_mappings(origin, mapping) {
  return with_properties(origin, keys(origin), mapping) }

//// -- Core combinators -----------------------------------------------
var Pandora = {
  make:
  function _make(object) {
    var instance = inherit(this)

    instance._value     = clone(object || {})
    instance._required  = []
    instance._overrides = {}

    return instance }

, value:
  function _value() {
    return merge(this) }

, only:
  function _only() {
    this._value = with_properties(this._value, slice(arguments))
    return this }

, hiding:
  function _hiding() {
    var names = slice(arguments)
    names = keys(this._value).filter(function(key) {
                                       return !~names.indexOf(key) })
    this._value = with_properties(this._value, names)
    return this }

, prefix:
  function _prefix(name) {
    this._value = with_mappings( this._value
                               , function(k){ return name + k })
    return this }

, aliasing:
  function _aliasing(map) {
    var mapping = callable_p(map)?  map
                : /* otherwise */   function(k) {
                                      return k in map?        map[k]
                                      :      /* otherwise */  k }

    this._value = with_mappings(this._value, mapping)
    return this }

, map:
  function _map(mapping) {
    var value = this._value
    this._value = keys(value).reduce( function(result, key) {
                                        result[key] = mapping(value[key], key, value)
                                        return result }
                                    , {} )
    return this }

, require:
  function _require() {
    this._required.push.apply(this._required, arguments)
    return this }

, override:
  function _override() {
    slice(arguments).forEach( function(key) {
                                this._overrides[key] = true }
                            , this )
    return this }
}

//// -- Error handling -------------------------------------------------
function PandoraNotSatisfiedE(required) {
  var message = 'The following module\'s requirements haven\'t been met:\n  - '
              + required.join('\n  - ')
  var error   = Error.call(inherit(Error.prototype), message)
  error.name = 'PandoraNotSatisfiedE'
  return error }

function PandoraCollisionE(key) {
  var error = Error.call( inherit(Error.prototype)
                        , 'The key "' + key + '" already exists in the target module.')
  error.name = 'PandoraCollisionE'
  return error }

function PandoraOverrideCollisionE(key) {
  var error = Error.call( inherit(Error.prototype)
                        , 'The key "' + key + '" is already overriden by another module.')
  error.name = 'PandoraOverrideCollisionE'
  return error }

function raise(error) { throw error }

//// -- Exports --------------------------------------------------------
module.exports = { pandora : pandora
                 , merge   : merge
                 , Pandora : Pandora

                 , internal: { identity                  : identity
                             , callable_p                : callable_p
                             , satisfied_p               : satisfied_p
                             , with_properties           : with_properties
                             , with_mappings             : with_mappings
                             , copy_keys                 : copy_keys

                             , raise                     : raise
                             , PandoraNotSatisfiedE      : PandoraNotSatisfiedE
                             , PandoraCollisionE         : PandoraCollisionE
                             , PandoraOverrideCollisionE : PandoraOverrideCollisionE }}<commit_msg>Expands single-letter variables / minor formatting.<commit_after>/// pandora.js --- Module packing and unpacking on steroids
//
// Copyright (c) 2012 Quildreen Motta
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/// Module pandora
//
// Pandora is a module abstraction library, that brings combinators for
// handling first-class modules in JavaScript. Modules are treated as
// simple native objects, which can already be handled through the
// object services provided by the JavaScript language itself.
//
// Pandora extends these core services with a series of pure monadic
// combinators, which brings a declarative-ish syntax for module
// definition and formal contracts a module expects to be met.
//
// There is no need for providing a CommonJS module service under
// Pandora, since the library works directly on objects. On environments
// that support CommonJS modules, however, users can leverage better
// modularisation and a rather more declarative syntax.

//// -- Aliases --------------------------------------------------------
var inherit = Object.create
var proto   = Object.getPrototypeOf
var keys    = Object.keys

var slice   = [].slice.call.bind([].slice)
var clone   = with_mappings

//// -- Core interface -------------------------------------------------
function pandora(service) {
  return Pandora.make(service) }

function merge() {
  var boxed     = slice(arguments)
  var required  = []
  var overrides = {}
  var result    = boxed.reduce( function(result, module) {
                                  copy_keys(module, result, overrides)
                                  required.push.apply(required, module._required)
                                  return result }
                              , { } )

  return !satisfied_p(result, required)?  raise(PandoraNotSatisfiedE(required))
  :      /* otherwise */                  result }

//// -- Helpers --------------------------------------------------------
function satisfied_p(object, names) {
  return names.every(function(key) {
                       return key in object }) }

function copy_keys(origin, target, overrides) {
  var module = origin._value
  keys(module).forEach(function(key) {
                         !(key in target)?   target[key] = module[key]
                         : override_p(key)?  target[key] = module[key]
                         : !overrides[key]?  raise(PandoraCollisionE(key))
                         : /* otherwise */   null // already overriden

                         overrides[key] = overrides[key] || origin._overrides[key] })

  return target

  function override_p(key) {
    if (origin._overrides[key] && overrides[key])  throw PandoraOverrideCollisionE(key)
    return origin._overrides[key] }}

function identity(x) {
  return x }

function callable_p(subject) {
  return typeof subject == 'function' }

function with_properties(origin, names, mapping) {
  mapping = mapping || identity
  return names.reduce( function(result, key) {
                         result[mapping(key)] = origin[key]
                         return result }
                     , {} )}

function with_mappings(origin, mapping) {
  return with_properties(origin, keys(origin), mapping) }

//// -- Core combinators -----------------------------------------------
var Pandora = {
  make:
  function _make(object) {
    var instance = inherit(this)

    instance._value     = clone(object || {})
    instance._required  = []
    instance._overrides = {}

    return instance }

, value:
  function _value() {
    return merge(this) }

, only:
  function _only() {
    this._value = with_properties(this._value, slice(arguments))
    return this }

, hiding:
  function _hiding() {
    var names = slice(arguments)
    names = keys(this._value).filter(function(key) {
                                       return !~names.indexOf(key) })
    this._value = with_properties(this._value, names)
    return this }

, prefix:
  function _prefix(name) {
    this._value = with_mappings( this._value
                               , function(key){ return name + key })
    return this }

, aliasing:
  function _aliasing(map) {
    var mapping = callable_p(map)?  map
                : /* otherwise */   function(key) {
                                      return key in map?      map[key]
                                      :      /* otherwise */  key }

    this._value = with_mappings(this._value, mapping)
    return this }

, map:
  function _map(mapping) {
    var value = this._value
    this._value = keys(value).reduce( function(result, key) {
                                        result[key] = mapping(value[key], key, value)
                                        return result }
                                    , {} )
    return this }

, require:
  function _require() {
    this._required.push.apply(this._required, arguments)
    return this }

, override:
  function _override() {
    slice(arguments).forEach( function(key) {
                                this._overrides[key] = true }
                            , this )
    return this }
}

//// -- Error handling -------------------------------------------------
function PandoraNotSatisfiedE(required) {
  var message = 'The following module\'s requirements haven\'t been met:\n  - '
              + required.join('\n  - ')
  var error   = Error.call(inherit(Error.prototype), message)
  error.name = 'PandoraNotSatisfiedE'
  return error }

function PandoraCollisionE(key) {
  var error = Error.call( inherit(Error.prototype)
                        , 'The key "' + key + '" already exists in the target module.')
  error.name = 'PandoraCollisionE'
  return error }

function PandoraOverrideCollisionE(key) {
  var error = Error.call( inherit(Error.prototype)
                        , 'The key "' + key + '" is already overriden by another module.')
  error.name = 'PandoraOverrideCollisionE'
  return error }

function raise(error) { throw error }

//// -- Exports --------------------------------------------------------
module.exports = { pandora : pandora
                 , merge   : merge
                 , Pandora : Pandora

                 , internal: { identity                  : identity
                             , callable_p                : callable_p
                             , satisfied_p               : satisfied_p
                             , with_properties           : with_properties
                             , with_mappings             : with_mappings
                             , copy_keys                 : copy_keys

                             , raise                     : raise
                             , PandoraNotSatisfiedE      : PandoraNotSatisfiedE
                             , PandoraCollisionE         : PandoraCollisionE
                             , PandoraOverrideCollisionE : PandoraOverrideCollisionE }}<|endoftext|>


<commit_before>Molecule.module('Molecule.Physics', function (require, p) {

    p.addFriction = function (sprite, game) {
        if (sprite.speed.x > 0) {
            sprite.speed.x = sprite.speed.x * (1 - game.physics.friction.x);
            if (sprite.speed.x < 0.05) {
                sprite.speed.x = 0;
            }
        } else if (sprite.speed.x < 0) {
            sprite.speed.x = sprite.speed.x * (1 - game.physics.friction.x);
            if (sprite.speed.x > 0.05) {
                sprite.speed.x = 0;
            }
        }
        if (sprite.speed.y > 0) {
            sprite.speed.y = sprite.speed.y * (1 - game.physics.friction.y);
            if (sprite.speed.y < 0.05) {
                sprite.speed.y = 0;
            }
        } else if (sprite.speed.y < 0) {
            sprite.speed.y = sprite.speed.y * (1 - game.physics.friction.y);
            if (sprite.speed.y > 0.05) {
                sprite.speed.y = 0;
            }
        }
    };

    p.spriteHitsPlatformBelow = function (sprite, game) {
    	return sprite.affects.physics.gravity && game.physics.gravity.y > 0 && sprite.collision.sprite.down && game.scene.sprites[sprite.collision.sprite.id].platform;
    };

    p.spriteHitsPlatformAbove = function (sprite, game) {
      	return sprite.affects.physics.gravity && game.physics.gravity.y < 0 && sprite.collision.sprite.up && game.scene.sprites[sprite.collision.sprite.id].platform;
    };

    p.spriteHitsPlatformRight = function (sprite, game) {
      	return sprite.affects.physics.gravity && game.physics.gravity.x > 0 && sprite.collision.sprite.right && game.scene.sprites[sprite.collision.sprite.id].platform;
    };

    p.spriteHitsPlatformLeft = function (sprite, game) {
		return sprite.affects.physics.gravity && game.physics.gravity.x < 0 && sprite.collision.sprite.left && game.scene.sprites[sprite.collision.sprite.id].platform;
    };

    p.spriteSlowerThanCollisionSprite = function (axis, sprite, game) {
        return sprite.speed[axis] >= 0 && sprite.speed[axis] < game.scene.sprites[sprite.collision.sprite.id].speed[axis];
    };

    p.spriteFasterThanCollisionSprite = function (axis, sprite, game) {
        return sprite.speed[axis] <= 0 && sprite.speed[axis] > game.scene.sprites[sprite.collision.sprite.id].speed[axis];
    };

    p.increaseAcceleration = function (sprite) {
        sprite.speed.x += sprite.acceleration.x;
        sprite.speed.y += sprite.acceleration.y;
    };

    p.setSpeed = function (sprite) {
        var sx = sprite.speed.x >= 0 ? 1 : -1;
        var sy = sprite.speed.y >= 0 ? 1 : -1;
        if (Math.abs(sprite.speed.x) > sprite.speed.max.x) {
            sprite.speed.x = sprite.speed.max.x * sx;
        }
        if (Math.abs(sprite.speed.y) > sprite.speed.max.y) {
            sprite.speed.y = sprite.speed.max.y * sy;
        }
    };

    p.addGravity = function (sprite, game) {
        sprite.speed.x -= sprite.speed.gravity.x;
        sprite.speed.y -= sprite.speed.gravity.y;
        if (sprite.affects.physics.gravity) {
            sprite.speed.gravity.x += game.physics.gravity.x;
            sprite.speed.gravity.y += game.physics.gravity.y;
        }
        sprite.speed.x += sprite.speed.gravity.x;
        sprite.speed.y += sprite.speed.gravity.y;
    };

    p.cleanUpSpeed = function (sprite) {
        sprite.speed.x = parseFloat(sprite.speed.x.toFixed(3));
        sprite.speed.y = parseFloat(sprite.speed.y.toFixed(3));
        sprite.speed.t.x += sprite.speed.x;
        sprite.speed.t.y += sprite.speed.y;
        sprite.speed.t.x = parseFloat(sprite.speed.t.x.toFixed(3));
        sprite.speed.t.y = parseFloat(sprite.speed.t.y.toFixed(3));
        sprite.resetAcceleration();
        if (sprite.speed.x === 0) {
            sprite.speed.t.x = 0;
        }
        if (sprite.speed.y === 0) {
            sprite.speed.t.y = 0;
        }
    };

    return function (game) {
        var sprite;
        for (var i = 0; i < game.scene.sprites.length; i++) {
            sprite = game.scene.sprites[i];

            if (sprite.affects.physics.friction) {
                p.addFriction(sprite, game);
            }

            if (p.spriteHitsPlatformBelow(sprite, game) || p.spriteHitsPlatformAbove(sprite, game)) {

                if (p.spriteSlowerThanCollisionSprite('x', sprite, game)) {
                    sprite.speed.x = game.scene.sprites[sprite.collision.sprite.id].speed.x;
                } else if (p.spriteFasterThanCollisionSprite('x', sprite, game)) {
                    sprite.speed.x = game.scene.sprites[sprite.collision.sprite.id].speed.x;
                }

            } else if (p.spriteHitsPlatformRight(sprite, game) || p.spriteHitsPlatformLeft(sprite, game)) {

                if (p.spriteSlowerThanCollisionSprite('y', sprite, game)) {
                    sprite.speed.y = game.scene.sprites[sprite.collision.sprite.id].speed.y;
                } else if (p.spriteFasterThanCollisionSprite('y', sprite, game)) {
                    sprite.speed.y = game.scene.sprites[sprite.collision.sprite.id].speed.y;
                }

            }

            p.increaseAcceleration(sprite);
            p.setSpeed(sprite);
            p.addGravity(sprite, game);
            p.cleanUpSpeed(sprite);

        }

    }

});<commit_msg>Friction fix<commit_after>Molecule.module('Molecule.Physics', function (require, p) {

    p.addFriction = function (sprite, game) {
        if (sprite.speed.x > 0) {
            sprite.speed.x = sprite.speed.x * (1 - game.physics.friction.x);
            if (sprite.speed.x < 0.05) {
                sprite.speed.x = 0;
            }
        } else if (sprite.speed.x < 0) {
            sprite.speed.x = sprite.speed.x * (1 - game.physics.friction.x);
            if (sprite.speed.x > -0.05) {
                sprite.speed.x = 0;
            }
        }
        if (sprite.speed.y > 0) {
            sprite.speed.y = sprite.speed.y * (1 - game.physics.friction.y);
            if (sprite.speed.y < 0.05) {
                sprite.speed.y = 0;
            }
        } else if (sprite.speed.y < 0) {
            sprite.speed.y = sprite.speed.y * (1 - game.physics.friction.y);
            if (sprite.speed.y > -0.05) {
                sprite.speed.y = 0;
            }
        }
    };

    p.spriteHitsPlatformBelow = function (sprite, game) {
    	return sprite.affects.physics.gravity && game.physics.gravity.y > 0 && sprite.collision.sprite.down && game.scene.sprites[sprite.collision.sprite.id].platform;
    };

    p.spriteHitsPlatformAbove = function (sprite, game) {
      	return sprite.affects.physics.gravity && game.physics.gravity.y < 0 && sprite.collision.sprite.up && game.scene.sprites[sprite.collision.sprite.id].platform;
    };

    p.spriteHitsPlatformRight = function (sprite, game) {
      	return sprite.affects.physics.gravity && game.physics.gravity.x > 0 && sprite.collision.sprite.right && game.scene.sprites[sprite.collision.sprite.id].platform;
    };

    p.spriteHitsPlatformLeft = function (sprite, game) {
		return sprite.affects.physics.gravity && game.physics.gravity.x < 0 && sprite.collision.sprite.left && game.scene.sprites[sprite.collision.sprite.id].platform;
    };

    p.spriteSlowerThanCollisionSprite = function (axis, sprite, game) {
        return sprite.speed[axis] >= 0 && sprite.speed[axis] < game.scene.sprites[sprite.collision.sprite.id].speed[axis];
    };

    p.spriteFasterThanCollisionSprite = function (axis, sprite, game) {
        return sprite.speed[axis] <= 0 && sprite.speed[axis] > game.scene.sprites[sprite.collision.sprite.id].speed[axis];
    };

    p.increaseAcceleration = function (sprite) {
        sprite.speed.x += sprite.acceleration.x;
        sprite.speed.y += sprite.acceleration.y;
    };

    p.setSpeed = function (sprite) {
        var sx = sprite.speed.x >= 0 ? 1 : -1;
        var sy = sprite.speed.y >= 0 ? 1 : -1;
        if (Math.abs(sprite.speed.x) > sprite.speed.max.x) {
            sprite.speed.x = sprite.speed.max.x * sx;
        }
        if (Math.abs(sprite.speed.y) > sprite.speed.max.y) {
            sprite.speed.y = sprite.speed.max.y * sy;
        }
    };

    p.addGravity = function (sprite, game) {
        sprite.speed.x -= sprite.speed.gravity.x;
        sprite.speed.y -= sprite.speed.gravity.y;
        if (sprite.affects.physics.gravity) {
            sprite.speed.gravity.x += game.physics.gravity.x;
            sprite.speed.gravity.y += game.physics.gravity.y;
        }
        sprite.speed.x += sprite.speed.gravity.x;
        sprite.speed.y += sprite.speed.gravity.y;
    };

    p.cleanUpSpeed = function (sprite) {
        sprite.speed.x = parseFloat(sprite.speed.x.toFixed(3));
        sprite.speed.y = parseFloat(sprite.speed.y.toFixed(3));
        sprite.speed.t.x += sprite.speed.x;
        sprite.speed.t.y += sprite.speed.y;
        sprite.speed.t.x = parseFloat(sprite.speed.t.x.toFixed(3));
        sprite.speed.t.y = parseFloat(sprite.speed.t.y.toFixed(3));
        sprite.resetAcceleration();
        if (sprite.speed.x === 0) {
            sprite.speed.t.x = 0;
        }
        if (sprite.speed.y === 0) {
            sprite.speed.t.y = 0;
        }
    };

    return function (game) {
        var sprite;
        for (var i = 0; i < game.scene.sprites.length; i++) {
            sprite = game.scene.sprites[i];

            if (sprite.affects.physics.friction) {
                p.addFriction(sprite, game);
            }

            if (p.spriteHitsPlatformBelow(sprite, game) || p.spriteHitsPlatformAbove(sprite, game)) {

                if (p.spriteSlowerThanCollisionSprite('x', sprite, game)) {
                    sprite.speed.x = game.scene.sprites[sprite.collision.sprite.id].speed.x;
                } else if (p.spriteFasterThanCollisionSprite('x', sprite, game)) {
                    sprite.speed.x = game.scene.sprites[sprite.collision.sprite.id].speed.x;
                }

            } else if (p.spriteHitsPlatformRight(sprite, game) || p.spriteHitsPlatformLeft(sprite, game)) {

                if (p.spriteSlowerThanCollisionSprite('y', sprite, game)) {
                    sprite.speed.y = game.scene.sprites[sprite.collision.sprite.id].speed.y;
                } else if (p.spriteFasterThanCollisionSprite('y', sprite, game)) {
                    sprite.speed.y = game.scene.sprites[sprite.collision.sprite.id].speed.y;
                }

            }

            p.increaseAcceleration(sprite);
            p.setSpeed(sprite);
            p.addGravity(sprite, game);
            p.cleanUpSpeed(sprite);

        }

    }

});<|endoftext|>


<commit_before>'use strict';

const vorpal = require('vorpal')();
const util = require('util');
const chalk = vorpal.chalk;
const cliff = require('cliff');
const mapper = require('./mapper');

const log = {

  found: function(light, state) {
    let event = chalk.bgBlue.white.bold(' NEW ');
    logEvent(event, light);
  },

  discoveryCompleted: function() {
    let event = chalk.bgMagenta.white.bold(' DISCOVERY COMPLETED ');
    let msg = `${event} All lights found`;
    timestamp(msg);
  },

  online: function(light, state) {
    let event = chalk.bgGreen.white.bold(' ONLINE ');
    logEvent(event, light);
  },

  offline: function(light) {
    let event = chalk.bgRed.white.bold(' OFFLINE ');
    logEvent(event, light);
  },

  table: function (lights) {
    let properties = [
      'Label',
      'Power',
      'Hue',
      'Saturation',
      'Brightness',
      'Temperature',
      'ID',
      'IP'];
    let colors = ['bold', 'bold', 'bold', 'bold', 'bold'];
    let msg = cliff.stringifyObjectRows(lights, properties, colors);
    vorpal.log(msg);
  },

  info: function(msg) {
    timestamp(chalk.green('INFO: ') + msg);
  },

  warn: function(msg) {
    timestamp(chalk.yellow('WARNING: ') + msg);
  },

  error: function(msg) {
    timestamp(chalk.red('ERROR: ') + msg);
  },

  debug: function(object) {
    timestamp(chalk.cyan(util.inspect(object)));
  }
};

function logEvent(event, light) {
  let msg = util.format('%s %s', event, getLightInfo(light));
  timestamp(msg);
}

function timestamp(msg) {
  vorpal.log(util.format('%s %s', getTime(), msg));
}

function getLightInfo(light) {
  return light.label + ' (IP: ' + light.address + ')';
}

function getTime() {
  let now = new Date();
  let hour = now.getHours().toString();
  let minute = now.getMinutes().toString();

  if (hour.length === 1) { hour = '0' + hour; }
  if (minute.length === 1) { minute = '0' + minute; }

  return hour + ':' + minute;
}

// expose log
module.exports = exports = log;
<commit_msg>Include light alias in light listing<commit_after>'use strict';

const vorpal = new (require('vorpal'))();
const util = require('util');
const chalk = require('chalk');
const cliff = require('cliff');
const { sortBy } =require('lodash');

const log = {

  found: function(light, state) {
    let event = chalk.bgBlue.white.bold(' NEW ');
    logEvent(event, light);
  },

  discoveryCompleted: function() {
    let event = chalk.bgMagenta.white.bold(' DISCOVERY COMPLETED ');
    let msg = `${event} All lights found`;
    timestamp(msg);
  },

  online: function(light, state) {
    let event = chalk.bgGreen.white.bold(' ONLINE ');
    logEvent(event, light);
  },

  offline: function(light) {
    let event = chalk.bgRed.white.bold(' OFFLINE ');
    logEvent(event, light);
  },

  table: function(/** @type any[]*/ lights) {
    let rows = sortBy(lights, 'Label');
    let keys = [
      'Label',
      'Alias',
      'Power',
      'Hue',
      'Sat.',
      'Bri.',
      'Temp.',
      'ID',
      'IP'
    ];
    let colors = ['bold', 'bold', 'bold', 'bold', 'bold', 'bold'];
    let msg = cliff.stringifyObjectRows(rows, keys, colors);
    vorpal.log(msg);
  },

  info: function(msg) {
    timestamp(chalk.green('INFO: ') + msg);
  },

  warn: function(msg) {
    timestamp(chalk.yellow('WARNING: ') + msg);
  },

  error: function(msg, ...args) {
    timestamp(chalk.red('ERROR: ') + msg, ...args);
  },

  debug: function(object) {
    timestamp(chalk.cyan(util.inspect(object)));
  }
};

function logEvent(event, light) {
  let msg = util.format('%s %s', event, getLightInfo(light));
  timestamp(msg);
}

function timestamp(msg, ...args) {
  vorpal.log(util.format('%s %s', getTime(), msg), ...args);
}

function getLightInfo(light) {
  return light.label + ' (IP: ' + light.address + ')';
}

function getTime() {
  let now = new Date();
  let hour = now.getHours().toString();
  let minute = now.getMinutes().toString();

  if (hour.length === 1) { hour = '0' + hour; }
  if (minute.length === 1) { minute = '0' + minute; }

  return hour + ':' + minute;
}

// expose log
module.exports = exports = log;
<|endoftext|>