<commit_before>/**
 * Vow
 *
 * Copyright (c) 2012 Filatov Dmitry (dfilatov@yandex-team.ru)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @version 0.1.5
 */

(function(global) {

    var nextTick = typeof process === 'object'? // nodejs
            process.nextTick :
            global.setImmediate? // ie10
                global.setImmediate :
                global.postMessage? // modern browsers
                    (function() {
                        var fns = [],
                            msg = '__promise' + +new Date,
                            onMessage = function(e) {
                                if(e.data === msg) {
                                    e.stopPropagation?
                                        e.stopPropagation() :
                                        e.cancelBubble = true;

                                    var callFns = fns, i = 0, len = fns.length;
                                    fns = [];
                                    while(i < len) {
                                        callFns[i++]();
                                    }
                                }
                            };

                        global.addEventListener?
                            global.addEventListener('message', onMessage, true) :
                            global.attachEvent('onmessage', onMessage);

                        return function(fn) {
                            fns.push(fn) === 1 && global.postMessage(msg, '*');
                        };
                    })() :
                    function(fn) { // old browsers
                        setTimeout(fn, 0);
                    },
        isFunction = function(obj) {
            return typeof obj === 'function';
        };

    var Promise = function(val) {
        this._res = val;

        this._isFulfilled = typeof val !== 'undefined';
        this._isRejected = false;

        this._fulfilledCallbacks = [];
        this._rejectedCallbacks = [];
    };

    Promise.prototype = {
        valueOf : function() {
            return this._res;
        },

        isFulfilled : function() {
            return this._isFulfilled;
        },

        isRejected : function() {
            return this._isRejected;
        },

        isResolved : function() {
            return this._isFulfilled || this._isRejected;
        },

        fulfill : function(val) {
            if(this.isResolved()) {
                return;
            }

            this._isFulfilled = true;
            this._res = val;

            this._callCallbacks(this._fulfilledCallbacks);
            this._fulfilledCallbacks = this._rejectedCallbacks = null;
        },

        reject : function(error) {
            if(this.isResolved()) {
                return;
            }

            this._isRejected = true;
            this._res = error;

            this._callCallbacks(this._rejectedCallbacks);
            this._fulfilledCallbacks = this._rejectedCallbacks = null;
        },

        then : function(onFulfilled, onRejected) {
            var promise = new Promise(),
                cb;

            if(!this._isRejected) {
                cb = { promise : promise, fn : onFulfilled };
                this._isFulfilled?
                    this._callCallbacks([cb]) :
                    this._fulfilledCallbacks.push(cb);
            }

            if(!this._isFulfilled) {
                cb = { promise : promise, fn : onRejected };
                this._isRejected?
                    this._callCallbacks([cb]) :
                    this._rejectedCallbacks.push(cb);
            }

            return promise;
        },

        fail : function(onRejected) {
            return this.then(null, onRejected);
        },

        spread : function(onFulfilled, onRejected) {
            return this.then(
                function(val) {
                    return onFulfilled.apply(this, val);
                },
                onRejected);
        },

        _callCallbacks : function(callbacks) {
            if(!callbacks.length) {
                return;
            }

            var arg = this._res,
                isFulfilled = this.isFulfilled();

            nextTick(function() {
                var i = 0, len = callbacks.length, cb;
                while(i < len) {
                    var promise = (cb = callbacks[i++]).promise,
                        fn = cb.fn;

                    if(isFunction(fn)) {
                        var res;
                        try {
                            res = fn(arg);
                        }
                        catch(e) {
                            promise.reject(e);
                            continue;
                        }

                        Vow.isPromise(res)?
                            (function(promise) {
                                res.then(
                                    function(val) {
                                        promise.fulfill(val);
                                    },
                                    function(error) {
                                        promise.reject(error);
                                    })
                            })(promise) :
                            promise.fulfill(res);
                    }
                    else {
                        isFulfilled?
                            promise.fulfill(arg) :
                            promise.reject(arg);
                    }
                }
            });
        }
    };

    var Vow = {
        promise : function(val) {
            return new Promise(val);
        },

        when : function(obj, onFulfilled, onRejected) {
            return (this.isPromise(obj)? obj : new Promise(obj)).then(onFulfilled, onRejected);
        },

        isPromise : function(obj) {
            return obj && isFunction(obj.then);
        },

        isFulfilled : function(obj) {
            return this.isPromise(obj)? obj.isFulfilled() : true;
        },

        isRejected : function(obj) {
            return this.isPromise(obj)? obj.isRejected() : false;
        },

        isResolved : function(obj) {
            return this.isPromise(obj)? obj.isResolved() : true;
        },

        fulfill : function(val) {
            return this.when(val, null, function(error) {
                return error;
            });
        },

        reject : function(error) {
            return this.when(error, function(val) {
                var promise = new Promise();
                promise.reject(val);
                return promise;
            });
        },

        resolve : function(val) {
            return this.isPromise(val)?
                val :
                this.when(val);
        },

        forEach : function(promises, onFulfilled, onRejected) {
            var i = 0, len = promises.length;
            while(i < len) {
                this.when(promises[i++], onFulfilled, onRejected);
            }
        },

        all : function(promises) {
            var resPromise = new Promise(),
                i = promises.length;

            if(i) {
                var onFulfilled = function() {
                        if(!--i) {
                            var res = [],
                                promise;
                            while(promise = promises[i++]) {
                                res.push(promise.valueOf());
                            }
                            resPromise.fulfill(res);
                        }
                    },
                    onRejected = function(error) {
                        resPromise.reject(error);
                    };

                this.forEach(promises, onFulfilled, onRejected);
            }
            else {
                resPromise.fulfill([]);
            }

            return resPromise;
        },

        allResolved : function(promises) {
            var resPromise = new Promise(),
                i = promises.length;

            if(i) {
                var onProgress = function() {
                    if(!--i) {
                        resPromise.fulfill(promises);
                    }
                };

                this.forEach(promises, onProgress, onProgress);
            }
            else {
                resPromise.fulfill(promises);
            }

            return resPromise;
        },

        any : function(promises) {
            var resPromise = new Promise(),
                len = promises.length;

            if(len) {
                var i = 0, error,
                    onFulfilled = function(val) {
                        resPromise.fulfill(val);
                    },
                    onRejected = function(_error) {
                        i || (error = _error);
                        if(++i === len) {
                            resPromise.reject(error);
                        }
                    };

                this.forEach(promises, onFulfilled, onRejected);
            }
            else {
                resPromise.reject(Error());
            }

            return resPromise;
        },

        timeout : function(origPromise, timeout) {
            var resPromise = new Promise(),
                timer = setTimeout(function() {
                    resPromise.reject(Error('timed out'));
                }, timeout);

            origPromise.then(
                function(res) {
                    clearTimeout(timer);
                    resPromise.fulfill(res);
                },
                function(error) {
                    clearTimeout(timer);
                    resPromise.reject(error);
                });

            return resPromise;
        }
    };

    if(typeof exports === 'object') {
        module.exports = Vow;
    }
    else if(typeof define === 'function') {
        define(function(require, exports, module) {
            module.exports = Vow;
        });
    }
    else {
        global.Vow = Vow;
    }

})(this);<commit_msg>unindent<commit_after>/**
 * Vow
 *
 * Copyright (c) 2012 Filatov Dmitry (dfilatov@yandex-team.ru)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @version 0.1.5
 */

(function(global) {

var nextTick = typeof process === 'object'? // nodejs
        process.nextTick :
        global.setImmediate? // ie10
            global.setImmediate :
            global.postMessage? // modern browsers
                (function() {
                    var fns = [],
                        msg = '__promise' + +new Date,
                        onMessage = function(e) {
                            if(e.data === msg) {
                                e.stopPropagation?
                                    e.stopPropagation() :
                                    e.cancelBubble = true;

                                var callFns = fns, i = 0, len = fns.length;
                                fns = [];
                                while(i < len) {
                                    callFns[i++]();
                                }
                            }
                        };

                    global.addEventListener?
                        global.addEventListener('message', onMessage, true) :
                        global.attachEvent('onmessage', onMessage);

                    return function(fn) {
                        fns.push(fn) === 1 && global.postMessage(msg, '*');
                    };
                })() :
                function(fn) { // old browsers
                    setTimeout(fn, 0);
                },
    isFunction = function(obj) {
        return typeof obj === 'function';
    };

var Promise = function(val) {
    this._res = val;

    this._isFulfilled = typeof val !== 'undefined';
    this._isRejected = false;

    this._fulfilledCallbacks = [];
    this._rejectedCallbacks = [];
};

Promise.prototype = {
    valueOf : function() {
        return this._res;
    },

    isFulfilled : function() {
        return this._isFulfilled;
    },

    isRejected : function() {
        return this._isRejected;
    },

    isResolved : function() {
        return this._isFulfilled || this._isRejected;
    },

    fulfill : function(val) {
        if(this.isResolved()) {
            return;
        }

        this._isFulfilled = true;
        this._res = val;

        this._callCallbacks(this._fulfilledCallbacks);
        this._fulfilledCallbacks = this._rejectedCallbacks = null;
    },

    reject : function(error) {
        if(this.isResolved()) {
            return;
        }

        this._isRejected = true;
        this._res = error;

        this._callCallbacks(this._rejectedCallbacks);
        this._fulfilledCallbacks = this._rejectedCallbacks = null;
    },

    then : function(onFulfilled, onRejected) {
        var promise = new Promise(),
            cb;

        if(!this._isRejected) {
            cb = { promise : promise, fn : onFulfilled };
            this._isFulfilled?
                this._callCallbacks([cb]) :
                this._fulfilledCallbacks.push(cb);
        }

        if(!this._isFulfilled) {
            cb = { promise : promise, fn : onRejected };
            this._isRejected?
                this._callCallbacks([cb]) :
                this._rejectedCallbacks.push(cb);
        }

        return promise;
    },

    fail : function(onRejected) {
        return this.then(null, onRejected);
    },

    spread : function(onFulfilled, onRejected) {
        return this.then(
            function(val) {
                return onFulfilled.apply(this, val);
            },
            onRejected);
    },

    _callCallbacks : function(callbacks) {
        if(!callbacks.length) {
            return;
        }

        var arg = this._res,
            isFulfilled = this.isFulfilled();

        nextTick(function() {
            var i = 0, len = callbacks.length, cb;
            while(i < len) {
                var promise = (cb = callbacks[i++]).promise,
                    fn = cb.fn;

                if(isFunction(fn)) {
                    var res;
                    try {
                        res = fn(arg);
                    }
                    catch(e) {
                        promise.reject(e);
                        continue;
                    }

                    Vow.isPromise(res)?
                        (function(promise) {
                            res.then(
                                function(val) {
                                    promise.fulfill(val);
                                },
                                function(error) {
                                    promise.reject(error);
                                })
                        })(promise) :
                        promise.fulfill(res);
                }
                else {
                    isFulfilled?
                        promise.fulfill(arg) :
                        promise.reject(arg);
                }
            }
        });
    }
};

var Vow = {
    promise : function(val) {
        return new Promise(val);
    },

    when : function(obj, onFulfilled, onRejected) {
        return (this.isPromise(obj)? obj : new Promise(obj)).then(onFulfilled, onRejected);
    },

    isPromise : function(obj) {
        return obj && isFunction(obj.then);
    },

    isFulfilled : function(obj) {
        return this.isPromise(obj)? obj.isFulfilled() : true;
    },

    isRejected : function(obj) {
        return this.isPromise(obj)? obj.isRejected() : false;
    },

    isResolved : function(obj) {
        return this.isPromise(obj)? obj.isResolved() : true;
    },

    fulfill : function(val) {
        return this.when(val, null, function(error) {
            return error;
        });
    },

    reject : function(error) {
        return this.when(error, function(val) {
            var promise = new Promise();
            promise.reject(val);
            return promise;
        });
    },

    resolve : function(val) {
        return this.isPromise(val)?
            val :
            this.when(val);
    },

    forEach : function(promises, onFulfilled, onRejected) {
        var i = 0, len = promises.length;
        while(i < len) {
            this.when(promises[i++], onFulfilled, onRejected);
        }
    },

    all : function(promises) {
        var resPromise = new Promise(),
            i = promises.length;

        if(i) {
            var onFulfilled = function() {
                    if(!--i) {
                        var res = [],
                            promise;
                        while(promise = promises[i++]) {
                            res.push(promise.valueOf());
                        }
                        resPromise.fulfill(res);
                    }
                },
                onRejected = function(error) {
                    resPromise.reject(error);
                };

            this.forEach(promises, onFulfilled, onRejected);
        }
        else {
            resPromise.fulfill([]);
        }

        return resPromise;
    },

    allResolved : function(promises) {
        var resPromise = new Promise(),
            i = promises.length;

        if(i) {
            var onProgress = function() {
                if(!--i) {
                    resPromise.fulfill(promises);
                }
            };

            this.forEach(promises, onProgress, onProgress);
        }
        else {
            resPromise.fulfill(promises);
        }

        return resPromise;
    },

    any : function(promises) {
        var resPromise = new Promise(),
            len = promises.length;

        if(len) {
            var i = 0, error,
                onFulfilled = function(val) {
                    resPromise.fulfill(val);
                },
                onRejected = function(_error) {
                    i || (error = _error);
                    if(++i === len) {
                        resPromise.reject(error);
                    }
                };

            this.forEach(promises, onFulfilled, onRejected);
        }
        else {
            resPromise.reject(Error());
        }

        return resPromise;
    },

    timeout : function(origPromise, timeout) {
        var resPromise = new Promise(),
            timer = setTimeout(function() {
                resPromise.reject(Error('timed out'));
            }, timeout);

        origPromise.then(
            function(res) {
                clearTimeout(timer);
                resPromise.fulfill(res);
            },
            function(error) {
                clearTimeout(timer);
                resPromise.reject(error);
            });

        return resPromise;
    }
};

if(typeof exports === 'object') {
    module.exports = Vow;
}
else if(typeof define === 'function') {
    define(function(require, exports, module) {
        module.exports = Vow;
    });
}
else {
    global.Vow = Vow;
}

})(this);<|endoftext|>


<commit_before>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Site */

Site = {
  init: function() {
    var _this = this;

    _this.Utilities.init();
    _this.Header.init();
    _this.Search.init();
    _this.Support.init();
    _this.RadioPlayer.init();

  }
};

Site.Utilities = {
  init: function() {
    var _this = this;

    _this.bind();
    _this.fixWidows();

  },

  bind: function() {
    var _this = this;

    if ($('#single-resources-section').length) {
      _this.bindResourcesToggle();
    }

    $('.js-select').click(function() {
      $(this).selectText();
    });

  },

  bindResourcesToggle: function() {
    var $resources = $('#single-resources-section');

    $('#js-resources-toggle').click(function() {
      $resources.toggle();
    });

  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  },

};

Site.Header = {
  init: function() {
    var _this = this;

    _this.$menuToggle = $('#menu-toggle');
    _this.$headerSub = $('#header-sub');
    _this.$searchToggle = $('#search-toggle');
    _this.$headerSearch = $('#header-search');
    _this.$searchInput = $('#search-input');

    _this.bind();

    if ($('body').hasClass('single')) {
      _this.showSinglePostTitle();
    }

  },

  bind: function() {
    var _this = this;

    _this.$menuToggle.click(function() {
      _this.$headerSub.toggle();
    });

    _this.$searchToggle.click(function() {
      _this.$headerSearch.toggle();
       _this.$searchInput.focus();
    });

  },

  showSinglePostTitle: function(e) {
    var _this = this;

    _this.headerHeight = $('#header-main-wrapper').height();
    _this.$headerSinglePostTitle = $('#header-page-title');

    $(window).scroll(function() {

      if ($(window).scrollTop() > _this.headerHeight) {

        _this.$headerSinglePostTitle.css('opacity', 1);

      } else {

        _this.$headerSinglePostTitle.css('opacity', 0);

      }

    });

  }
};

Site.Search = {
  init: function() {
    var _this = this;

    _this.form = $('#search-input');
    _this.tags = $('.suggested-tag');
    _this.tagsList = $('#tag-suggestions');

    _this.bind();

     if ($('body').hasClass('error404')) {
      _this.fourzerofour();
    }

  },

  bind: function() {
    var _this = this;

    _this.form.on('change keyup input paste focus', function(event) {

      // Get Input Value
      var term = $(this).val();

      // Get matching tags
      var $suggested = _this.tags.siblings('.suggested-tag[data-tag^="' + term + '"]');

      // Hide all tags
      _this.tags.hide();

      // If matching tags, show them
      if( $suggested.length !== 0 ) {
        $suggested.show();
        _this.tagsList.show();
      } else {
        _this.tagsList.hide();
      }

    });
  },

  fourzerofour: function() {
    var href = window.location.href;
    // remove url before WP
    var request = href.split('/');
    // get last part of url

    // If trailing /
    if( request[request.length - 1] === "" ) {
      // Remove last element from the array
      request.pop();
    }

    request = request[request.length-1];
    // remove any dashes [in the case of a real permalink slug]
    request = request.replace(/-/g, ' ');

    if (request) {
      $('#search-input').val(request).focus();
    }
  },
};

Site.Support = {
  init: function() {
    if ($('.support-section').length) {
      this.bind();
    }
  },

  bind: function() {
    $('.support-form-slider').on('input', function() {
      var target = $(this).closest('.support-form').find('.support-form-value');
      target.html(this.value);
    });
  },
};

Site.RadioPlayer = {
  $radioPlayer: $('#radio-player'),
  playerIsInitialized: false,

  init: function() {
    var _this = this;

    // saves boolean for British Summer Time or not
    _this.isBST = _this.checkBST();

    if ($('body').hasClass('home')) {

      // checks if radio show is live in the schedule
      if (_this.isSchedule()) {
        _this.goLive();
      }

      setInterval((function() {
        if (_this.isSchedule()) {
          _this.goLive();
        } else {
          _this.goOffline();
        }
      }), 15000);

    }

  },

  goLive: function() {
    var _this = this;

    if (!_this.playerIsInitialized) {
      _this.initPlayer();
    }

    _this.$radioPlayer.show();
  },

  goOffline: function() {
    var _this = this;

    if (_this.playerIsInitialized) {
      _this.$jPlayer.jPlayer('stop');
    }

    _this.$radioPlayer.hide();
  },

  initPlayer: function() {
    var _this = this;

    _this.$jPlayer = $('#jplayer').jPlayer({
      ready: function () {
        $(this).jPlayer('setMedia', {
          title: 'resonancefm',
          mp3: 'http://54.77.136.103:8000/resonance',
        });
      },
      cssSelectorAncestor: '#jp_container_1',
      swfPath: '/js',
      supplied: 'mp3',
      useStateClassSkin: true,
      autoBlur: false,
      smoothPlayBar: true,
      keyEnabled: true,
    }).bind($.jPlayer.event.play, function() {
      $('.jp-play').hide();
      $('.jp-stop').show();
    }).bind($.jPlayer.event.pause, function() {
      $('.jp-stop').hide();
      $('.jp-play').show();
    });

    _this.playerIsInitialized = true;
  },

  isSchedule: function() {
    var _this = this;

    var utc = new Date();
    var now;

    if (_this.isBST) {
      now = new Date(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate(), (utc.getUTCHours() + 1), utc.getUTCMinutes(), utc.getUTCSeconds());
    } else {
      now = new Date(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate(), utc.getUTCHours(), utc.getUTCMinutes(), utc.getUTCSeconds());
    }

    var day = now.getDay();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var dayminutes = (hours * 60) + minutes;

    // checking if time is Monday between 7am and 8am with a little in and out flexibility
    // if not  checking if time is Friday between 1pm and 2pm with a little in and out flexibility
    if (day === 1 && dayminutes > 418 && dayminutes < 482) {
      return true;
    } else if (day === 5 && dayminutes > 778 && dayminutes < 842) {
      return true;
    }

    return false;

  },

  checkBST: function() {
    var d = new Date();
    var lSoM;
    var lSoO;

    // code from forgotton source. it checking against a pattern if date is in summer time or not
    for (var i = 31; i > 0; i--) {
      var tmp = new Date(d.getFullYear(), 2, i);
      if (tmp.getDay() === 0) {
        lSoM = tmp;
        break;
      }
    }

    for (var k = 31; k > 0; k--) {
      var tmpk = new Date(d.getFullYear(), 9, k);
      if (tmpk.getDay() === 0) {
        lSoO = tmpk;
        break;
      }
    }

    if (d < lSoM || d > lSoO) {
      return false;
    }

    return true;
  },

};

Site.init();<commit_msg>fix lints<commit_after>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, Site */

Site = {
  init: function() {
    var _this = this;

    _this.Utilities.init();
    _this.Header.init();
    _this.Search.init();
    _this.Support.init();
    _this.RadioPlayer.init();

  }
};

Site.Utilities = {
  init: function() {
    var _this = this;

    _this.bind();
    _this.fixWidows();

  },

  bind: function() {
    var _this = this;

    if ($('#single-resources-section').length) {
      _this.bindResourcesToggle();
    }

    $('.js-select').click(function() {
      $(this).selectText();
    });

  },

  bindResourcesToggle: function() {
    var $resources = $('#single-resources-section');

    $('#js-resources-toggle').click(function() {
      $resources.toggle();
    });

  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  },

};

Site.Header = {
  init: function() {
    var _this = this;

    _this.$menuToggle = $('#menu-toggle');
    _this.$headerSub = $('#header-sub');
    _this.$searchToggle = $('#search-toggle');
    _this.$headerSearch = $('#header-search');
    _this.$searchInput = $('#search-input');

    _this.bind();

    if ($('body').hasClass('single')) {
      _this.showSinglePostTitle();
    }

  },

  bind: function() {
    var _this = this;

    _this.$menuToggle.click(function() {
      _this.$headerSub.toggle();
    });

    _this.$searchToggle.click(function() {
      _this.$headerSearch.toggle();
       _this.$searchInput.focus();
    });

  },

  showSinglePostTitle: function() {
    var _this = this;

    _this.headerHeight = $('#header-main-wrapper').height();
    _this.$headerSinglePostTitle = $('#header-page-title');

    $(window).scroll(function() {

      if ($(window).scrollTop() > _this.headerHeight) {

        _this.$headerSinglePostTitle.css('opacity', 1);

      } else {

        _this.$headerSinglePostTitle.css('opacity', 0);

      }

    });

  }
};

Site.Search = {
  init: function() {
    var _this = this;

    _this.form = $('#search-input');
    _this.tags = $('.suggested-tag');
    _this.tagsList = $('#tag-suggestions');

    _this.bind();

     if ($('body').hasClass('error404')) {
      _this.fourzerofour();
    }

  },

  bind: function() {
    var _this = this;

    _this.form.on('change keyup input paste focus', function() {

      // Get Input Value
      var term = $(this).val();

      // Get matching tags
      var $suggested = _this.tags.siblings('.suggested-tag[data-tag^="' + term + '"]');

      // Hide all tags
      _this.tags.hide();

      // If matching tags, show them
      if( $suggested.length !== 0 ) {
        $suggested.show();
        _this.tagsList.show();
      } else {
        _this.tagsList.hide();
      }

    });
  },

  fourzerofour: function() {
    var href = window.location.href;
    // remove url before WP
    var request = href.split('/');
    // get last part of url

    // If trailing /
    if( request[request.length - 1] === "" ) {
      // Remove last element from the array
      request.pop();
    }

    request = request[request.length-1];
    // remove any dashes [in the case of a real permalink slug]
    request = request.replace(/-/g, ' ');

    if (request) {
      $('#search-input').val(request).focus();
    }
  },
};

Site.Support = {
  init: function() {
    if ($('.support-section').length) {
      this.bind();
    }
  },

  bind: function() {
    $('.support-form-slider').on('input', function() {
      var target = $(this).closest('.support-form').find('.support-form-value');
      target.html(this.value);
    });
  },
};

Site.RadioPlayer = {
  $radioPlayer: $('#radio-player'),
  playerIsInitialized: false,

  init: function() {
    var _this = this;

    // saves boolean for British Summer Time or not
    _this.isBST = _this.checkBST();

    if ($('body').hasClass('home')) {

      // checks if radio show is live in the schedule
      if (_this.isSchedule()) {
        _this.goLive();
      }

      setInterval((function() {
        if (_this.isSchedule()) {
          _this.goLive();
        } else {
          _this.goOffline();
        }
      }), 15000);

    }

  },

  goLive: function() {
    var _this = this;

    if (!_this.playerIsInitialized) {
      _this.initPlayer();
    }

    _this.$radioPlayer.show();
  },

  goOffline: function() {
    var _this = this;

    if (_this.playerIsInitialized) {
      _this.$jPlayer.jPlayer('stop');
    }

    _this.$radioPlayer.hide();
  },

  initPlayer: function() {
    var _this = this;

    _this.$jPlayer = $('#jplayer').jPlayer({
      ready: function () {
        $(this).jPlayer('setMedia', {
          title: 'resonancefm',
          mp3: 'http://54.77.136.103:8000/resonance',
        });
      },
      cssSelectorAncestor: '#jp_container_1',
      swfPath: '/js',
      supplied: 'mp3',
      useStateClassSkin: true,
      autoBlur: false,
      smoothPlayBar: true,
      keyEnabled: true,
    }).bind($.jPlayer.event.play, function() {
      $('.jp-play').hide();
      $('.jp-stop').show();
    }).bind($.jPlayer.event.pause, function() {
      $('.jp-stop').hide();
      $('.jp-play').show();
    });

    _this.playerIsInitialized = true;
  },

  isSchedule: function() {
    var _this = this;

    var utc = new Date();
    var now;

    if (_this.isBST) {
      now = new Date(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate(), (utc.getUTCHours() + 1), utc.getUTCMinutes(), utc.getUTCSeconds());
    } else {
      now = new Date(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate(), utc.getUTCHours(), utc.getUTCMinutes(), utc.getUTCSeconds());
    }

    var day = now.getDay();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var dayminutes = (hours * 60) + minutes;

    // checking if time is Monday between 7am and 8am with a little in and out flexibility
    // if not  checking if time is Friday between 1pm and 2pm with a little in and out flexibility
    if (day === 1 && dayminutes > 418 && dayminutes < 482) {
      return true;
    } else if (day === 5 && dayminutes > 778 && dayminutes < 842) {
      return true;
    }

    return false;

  },

  checkBST: function() {
    var d = new Date();
    var lSoM;
    var lSoO;

    // code from forgotton source. it checking against a pattern if date is in summer time or not
    for (var i = 31; i > 0; i--) {
      var tmp = new Date(d.getFullYear(), 2, i);
      if (tmp.getDay() === 0) {
        lSoM = tmp;
        break;
      }
    }

    for (var k = 31; k > 0; k--) {
      var tmpk = new Date(d.getFullYear(), 9, k);
      if (tmpk.getDay() === 0) {
        lSoO = tmpk;
        break;
      }
    }

    if (d < lSoM || d > lSoO) {
      return false;
    }

    return true;
  },

};

Site.init();<|endoftext|>


<commit_before>
$(document).ready(function() {
    var body = $('body');
    var devMode = true;

    var billGenerated = false;

    // COOKIES
    var COMPANY_NAME = "companyName";
    var COMPANY_PHONE = "companyPhone";
    var COMPANY_TIN = "companyTin";
    var COMPANY_SERVICE_TAX = "companyServiceTax";
    var COMPANY_ADDRESS = "companyAddress";
    // In days
    var DEFAULT_COOKIE_LIFE = 30;

    var getNumber = function(str) {
        str = str.replace('₹', '').trim();
        return str.length? parseFloat(str.replace('₹', '').trim()) : 0;
    };

    body.find('span.current-year').html(new Date().getFullYear());

    var checkServiceTaxApplicability = function() {
        var serviceTaxGroup = $('.service-tax-group');
        if($('#company-service-tax-no').val().length) {
            serviceTaxGroup.removeClass('hide');
        } else {
            serviceTaxGroup.addClass('hide');
        }
    };

    var updateItemTotal = function() {
        var total = 0;
        $('.items .item').each(function() {
            total = total + getNumber($(this).find('.item-row-price').html());
        });
        total = total.toFixed(2);
        $('.item-total').html('₹ '+total);
    };

    var updateDiscountTotal = function() {
        var percentageDiscount = getNumber($('input#discount').val());
        if(percentageDiscount>0) {
            var itemTotal = getNumber($('.item-total').html());
            var discountAmount = itemTotal*percentageDiscount/100;
            discountAmount = discountAmount.toFixed(2);
            $('.discount-amount').html('-₹ '+ discountAmount);
            $('.discount-total').html('₹ '+(itemTotal-discountAmount).toFixed(2));
        } else {
            $('.discount-amount').html('-₹ 0');
            $('.discount-total').html($('.item-total').html());
        }
    };

    var updateTotalPayable = function() {
        var totalAmount = getNumber($('.discount-total').html());
        var vatAmount = totalAmount*$('input#vat').val()/100;
        var serviceTaxAmount = totalAmount*$('input#service-tax').val()/100;
        var educationCess = serviceTaxAmount/50;
        var higherEducationCess = educationCess/2;
        var totalAmountWithTax = totalAmount+vatAmount+serviceTaxAmount+educationCess+higherEducationCess;

        vatAmount = vatAmount.toFixed(2);
        serviceTaxAmount = serviceTaxAmount.toFixed(2);
        educationCess = educationCess.toFixed(2);
        higherEducationCess = higherEducationCess.toFixed(2);
        totalAmountWithTax = totalAmountWithTax.toFixed(2);

        $('.vat-amount').html('₹ '+ vatAmount);
        $('.service-tax-amount').html('₹ '+ serviceTaxAmount);
        $('.education-cess').html('₹ '+ educationCess);
        $('.higher-education-cess').html('₹ '+ higherEducationCess);
        $('.total-with-tax').html('₹ '+totalAmountWithTax);
    };

    var updateTotals = function() {
        updateItemTotal();
        updateDiscountTotal();
        updateTotalPayable();
    };

    var clearForms = function() {
        // TODO Implement to fix #17
        $('form').each(function() {
            this.reset();
        });

        $('form .row.item').remove();
        $('.add-item').click();
        updateTotals();
    };

    body.on('change', '#company-name', function(e){
        var companyName = $(this).val();
        utils.setCookie(COMPANY_NAME, companyName, DEFAULT_COOKIE_LIFE);
        billWriter.config.companyName = companyName;
    });

    body.on('change', '#company-address', function(e){
        var companyAddress = $(this).val();
        utils.setCookie(COMPANY_ADDRESS, companyAddress, DEFAULT_COOKIE_LIFE);
        billWriter.config.address = companyAddress;
    });

    body.on('change', '#company-tin', function(e){
        var companyTin = $(this).val();
        utils.setCookie(COMPANY_TIN, companyTin, DEFAULT_COOKIE_LIFE);
        billWriter.config.tin = companyTin;
    });

    body.on('change', '#company-service-tax-no', function(e){
        var companyServiceTax = $(this).val();
        utils.setCookie(COMPANY_SERVICE_TAX, companyServiceTax, DEFAULT_COOKIE_LIFE);
        billWriter.config.serviceTax = companyServiceTax;
        checkServiceTaxApplicability();
    });

    body.on('change', '#company-contact', function(e){
        var companyPhone = $(this).val();
        utils.setCookie(COMPANY_PHONE, companyPhone, DEFAULT_COOKIE_LIFE);
        billWriter.config.contactNumber = companyPhone;
    });

    body.on('click', '.change-seller-info', function(e){
        $('.company-info').removeClass('hide');
        $(this).addClass('hide');
    });

    body.on('click', '.new-bill', function(e) {
        if (billGenerated) {
            // FIXME #17
            if(devMode) {
                clearForms();
            } else {
                location.reload();
            }
        } else {
            // TODO Replace this confirm with bootbox
            var result = confirm("This bill has not been generated. Do you still want to continue?");
            if(result) {
                if(devMode) {
                    clearForms();
                } else {
                    location.reload();
                }
            }
        }
    });

    body.on('click', '.add-item', function(e) {
        var i = $('.items .item').length+1;
        var itemElement = $('.item-template').clone();

        $(itemElement).removeClass('item-template hide').addClass('item');
        $(itemElement).attr('data-serial', i);
        $(itemElement).find('.sr-no').html(i);
        $(itemElement).appendTo('.items');
    });

    body.on('change', '.item-price, .item-quantity', function() {
        var parent = $(this).closest('.item');
        var price = getNumber($(parent).find('.item-price').val()) * getNumber($(parent).find('.item-quantity').val());
        price = price.toFixed(2);
        $(parent).find('.item-row-price').html('₹ '+ price);
        updateTotals();
    });

    body.on('change', 'input#discount', function() {
        var percentageDiscount = getNumber($(this).val());
        if(percentageDiscount>100 || percentageDiscount<0) {
            $(this).val(0);
        }

        updateDiscountTotal();
        updateTotalPayable();
    });

    body.on('change', 'input#vat', function() {
        var vatPercent = getNumber($(this).val());
        if(vatPercent>100 || vatPercent<0) {
            $(this).val(0);
        }
        updateTotalPayable();
    });

    body.on('change', 'input#service-tax', function() {
        var serviceTaxPercent = getNumber($(this).val());
        if(serviceTaxPercent>100 || serviceTaxPercent<0) {
            $(this).val(0);
        }
        if($(this).val() == 0) {
            $('.service-tax-extras').addClass('hide');
        } else {
            $('.service-tax-extras').removeClass('hide');
        }
        updateTotalPayable();
    });

    body.on('click', '.generate-bill', function() {
        billGenerated = true;
        var info = createFormDataObject();
        billWriter.config.blank = false;
        var doc = billWriter.generateBill(info);
        billWriter.download(doc);
    });

    // TODO #6 Re-enable this button
    //body.on('click', '.generate-blank-bill', function() {
    //    var info = createFormDataObject();
    //    billWriter.config.blank = true;
    //    var doc = billWriter.generateBill(info);
    //    billWriter.download(doc);
    //});

    var createFormDataObject = function() {
        var info = {};
        info.billNo = $('input#billNo').val();
        if(info.billNo == '') {
            var now = new Date();
            info.billNo = ''+now.getFullYear()+(now.getMonth()+1)+now.getDate();
        }

        info.customer = {
            name: $('input#purchaser').val(),
            address: $('textarea#purchaser-address').val(),
            pan: $('input#purchaser-tin').val()
        };

        info.items = {
            total: $('p.item-total').html(),
            list: []
        };
        $('.items .item').each(function() {
            info.items.list.push({
                name: $(this).find('input.item-name').val(),
                price: $(this).find('input.item-price').val(),
                unit: $(this).find('input.item-quantity').val(),
                amount: $(this).find('p.item-row-price').html()
            });
        });

        var discountPercent = parseFloat($('input#discount').val()).toFixed(2);
        info.discount = {
            available: discountPercent>0,
            percent: discountPercent+'%',
            amount: $('p.discount-amount').html(),
            totalAfterDiscount: $('p.discount-total').html()
        };

        info.taxes = {
            totalWithTaxes: $('p.total-with-tax').html(),
            list: []
        };

        var vatPercent = parseFloat($('input#vat').val()).toFixed(2);
        var serviceTaxPercent = parseFloat($('input#service-tax').val()).toFixed(2);
        if(vatPercent>0) {
            info.taxes.list.push({
                name: 'VAT',
                percent: vatPercent+'%',
                amount: $('p.vat-amount').html()
            });
        }

        if(serviceTaxPercent>0 && billWriter.config.serviceTax.length) {
            info.taxes.list.push({
                name: 'Service Tax',
                percent: serviceTaxPercent+'%',
                amount: $('p.service-tax-amount').html()
            });
            info.taxes.list.push({
                name: 'Education Cess',
                percent: '2%',
                amount: $('p.education-cess').html()
            });
            info.taxes.list.push({
                name: 'Higher Education Cess',
                percent: '1%',
                amount: $('p.higher-education-cess').html()
            });
        }

        info.taxApplied = info.taxes.list.length;

        info.invoiceType = $('input[type="radio"][name="invoiceType"]:checked').val();

        return info;
    };

    if(devMode) {
        // Fill in the test data
        $('input#billNo').val('TESTING');
        $('input#purchaser').val("John Ahmed Doe");
        $('textarea#purchaser-address').val("B-221, Baker Street\nDown Town\nLondon, UK");
        $('input#purchaser-tin').val("THSPD1251Y");

        $('.items .item input.item-name').val("Canon Printer");
        $('.items .item input.item-price').val(3500);
        $('.items .item input.item-quantity').val(1);
        updateTotals();
    }

    if(!utils.getCookie(COMPANY_NAME).length) {
        $('.company-info').removeClass('hide');
        $('.change-seller-info').addClass('hide');
    } else {
        billWriter.config.companyName = utils.getCookie(COMPANY_NAME);
        billWriter.config.contactNumber = utils.getCookie(COMPANY_PHONE);
        billWriter.config.address = utils.getCookie(COMPANY_ADDRESS);
        billWriter.config.tin = utils.getCookie(COMPANY_TIN);
        billWriter.config.serviceTax = utils.getCookie(COMPANY_SERVICE_TAX);

        $('#company-name').val(billWriter.config.companyName);
        $('#company-address').val(billWriter.config.address);
        $('#company-tin').val(billWriter.config.tin);
        $('#company-service-tax-no').val(billWriter.config.serviceTax);
        $('#company-contact').val(billWriter.config.contactNumber);
        checkServiceTaxApplicability();
    }

}); // END DOCUMENT READY
<commit_msg>Fixing the devMode variable and fixed #17<commit_after>
$(document).ready(function() {
    var body = $('body');
    var devMode = window.location.href.indexOf("localhost")>0;

    var billGenerated = false;

    // COOKIES
    var COMPANY_NAME = "companyName";
    var COMPANY_PHONE = "companyPhone";
    var COMPANY_TIN = "companyTin";
    var COMPANY_SERVICE_TAX = "companyServiceTax";
    var COMPANY_ADDRESS = "companyAddress";
    // In days
    var DEFAULT_COOKIE_LIFE = 30;

    var getNumber = function(str) {
        str = str.replace('₹', '').trim();
        return str.length? parseFloat(str.replace('₹', '').trim()) : 0;
    };

    body.find('span.current-year').html(new Date().getFullYear());

    var checkServiceTaxApplicability = function() {
        var serviceTaxGroup = $('.service-tax-group');
        if($('#company-service-tax-no').val().length) {
            serviceTaxGroup.removeClass('hide');
        } else {
            serviceTaxGroup.addClass('hide');
        }
    };

    var updateItemTotal = function() {
        var total = 0;
        $('.items .item').each(function() {
            total = total + getNumber($(this).find('.item-row-price').html());
        });
        total = total.toFixed(2);
        $('.item-total').html('₹ '+total);
    };

    var updateDiscountTotal = function() {
        var percentageDiscount = getNumber($('input#discount').val());
        if(percentageDiscount>0) {
            var itemTotal = getNumber($('.item-total').html());
            var discountAmount = itemTotal*percentageDiscount/100;
            discountAmount = discountAmount.toFixed(2);
            $('.discount-amount').html('-₹ '+ discountAmount);
            $('.discount-total').html('₹ '+(itemTotal-discountAmount).toFixed(2));
        } else {
            $('.discount-amount').html('-₹ 0');
            $('.discount-total').html($('.item-total').html());
        }
    };

    var updateTotalPayable = function() {
        var totalAmount = getNumber($('.discount-total').html());
        var vatAmount = totalAmount*$('input#vat').val()/100;
        var serviceTaxAmount = totalAmount*$('input#service-tax').val()/100;
        var educationCess = serviceTaxAmount/50;
        var higherEducationCess = educationCess/2;
        var totalAmountWithTax = totalAmount+vatAmount+serviceTaxAmount+educationCess+higherEducationCess;

        vatAmount = vatAmount.toFixed(2);
        serviceTaxAmount = serviceTaxAmount.toFixed(2);
        educationCess = educationCess.toFixed(2);
        higherEducationCess = higherEducationCess.toFixed(2);
        totalAmountWithTax = totalAmountWithTax.toFixed(2);

        $('.vat-amount').html('₹ '+ vatAmount);
        $('.service-tax-amount').html('₹ '+ serviceTaxAmount);
        $('.education-cess').html('₹ '+ educationCess);
        $('.higher-education-cess').html('₹ '+ higherEducationCess);
        $('.total-with-tax').html('₹ '+totalAmountWithTax);
    };

    var updateTotals = function() {
        updateItemTotal();
        updateDiscountTotal();
        updateTotalPayable();
    };

    var clearForms = function() {
        $('form').each(function() {
            this.reset();
        });

        $('form .row.item').remove();
        $('.add-item').click();
        updateTotals();
    };

    body.on('change', '#company-name', function(e){
        var companyName = $(this).val();
        utils.setCookie(COMPANY_NAME, companyName, DEFAULT_COOKIE_LIFE);
        billWriter.config.companyName = companyName;
    });

    body.on('change', '#company-address', function(e){
        var companyAddress = $(this).val();
        utils.setCookie(COMPANY_ADDRESS, companyAddress, DEFAULT_COOKIE_LIFE);
        billWriter.config.address = companyAddress;
    });

    body.on('change', '#company-tin', function(e){
        var companyTin = $(this).val();
        utils.setCookie(COMPANY_TIN, companyTin, DEFAULT_COOKIE_LIFE);
        billWriter.config.tin = companyTin;
    });

    body.on('change', '#company-service-tax-no', function(e){
        var companyServiceTax = $(this).val();
        utils.setCookie(COMPANY_SERVICE_TAX, companyServiceTax, DEFAULT_COOKIE_LIFE);
        billWriter.config.serviceTax = companyServiceTax;
        checkServiceTaxApplicability();
    });

    body.on('change', '#company-contact', function(e){
        var companyPhone = $(this).val();
        utils.setCookie(COMPANY_PHONE, companyPhone, DEFAULT_COOKIE_LIFE);
        billWriter.config.contactNumber = companyPhone;
    });

    body.on('click', '.change-seller-info', function(e){
        $('.company-info').removeClass('hide');
        $(this).addClass('hide');
    });

    body.on('click', '.new-bill', function(e) {
        if (billGenerated) {
            clearForms();
        } else {
            // TODO Replace this confirm with bootbox
            var result = confirm("This bill has not been generated. Do you still want to continue?");
            if(result) {
                clearForms();
            }
        }
    });

    body.on('click', '.add-item', function(e) {
        var i = $('.items .item').length+1;
        var itemElement = $('.item-template').clone();

        $(itemElement).removeClass('item-template hide').addClass('item');
        $(itemElement).attr('data-serial', i);
        $(itemElement).find('.sr-no').html(i);
        $(itemElement).appendTo('.items');
    });

    body.on('change', '.item-price, .item-quantity', function() {
        var parent = $(this).closest('.item');
        var price = getNumber($(parent).find('.item-price').val()) * getNumber($(parent).find('.item-quantity').val());
        price = price.toFixed(2);
        $(parent).find('.item-row-price').html('₹ '+ price);
        updateTotals();
    });

    body.on('change', 'input#discount', function() {
        var percentageDiscount = getNumber($(this).val());
        if(percentageDiscount>100 || percentageDiscount<0) {
            $(this).val(0);
        }

        updateDiscountTotal();
        updateTotalPayable();
    });

    body.on('change', 'input#vat', function() {
        var vatPercent = getNumber($(this).val());
        if(vatPercent>100 || vatPercent<0) {
            $(this).val(0);
        }
        updateTotalPayable();
    });

    body.on('change', 'input#service-tax', function() {
        var serviceTaxPercent = getNumber($(this).val());
        if(serviceTaxPercent>100 || serviceTaxPercent<0) {
            $(this).val(0);
        }
        if($(this).val() == 0) {
            $('.service-tax-extras').addClass('hide');
        } else {
            $('.service-tax-extras').removeClass('hide');
        }
        updateTotalPayable();
    });

    body.on('click', '.generate-bill', function() {
        billGenerated = true;
        var info = createFormDataObject();
        billWriter.config.blank = false;
        var doc = billWriter.generateBill(info);
        billWriter.download(doc);
    });

    // TODO #6 Re-enable this button
    //body.on('click', '.generate-blank-bill', function() {
    //    var info = createFormDataObject();
    //    billWriter.config.blank = true;
    //    var doc = billWriter.generateBill(info);
    //    billWriter.download(doc);
    //});

    var createFormDataObject = function() {
        var info = {};
        info.billNo = $('input#billNo').val();
        if(info.billNo == '') {
            var now = new Date();
            info.billNo = ''+now.getFullYear()+(now.getMonth()+1)+now.getDate();
        }

        info.customer = {
            name: $('input#purchaser').val(),
            address: $('textarea#purchaser-address').val(),
            pan: $('input#purchaser-tin').val()
        };

        info.items = {
            total: $('p.item-total').html(),
            list: []
        };
        $('.items .item').each(function() {
            info.items.list.push({
                name: $(this).find('input.item-name').val(),
                price: $(this).find('input.item-price').val(),
                unit: $(this).find('input.item-quantity').val(),
                amount: $(this).find('p.item-row-price').html()
            });
        });

        var discountPercent = parseFloat($('input#discount').val()).toFixed(2);
        info.discount = {
            available: discountPercent>0,
            percent: discountPercent+'%',
            amount: $('p.discount-amount').html(),
            totalAfterDiscount: $('p.discount-total').html()
        };

        info.taxes = {
            totalWithTaxes: $('p.total-with-tax').html(),
            list: []
        };

        var vatPercent = parseFloat($('input#vat').val()).toFixed(2);
        var serviceTaxPercent = parseFloat($('input#service-tax').val()).toFixed(2);
        if(vatPercent>0) {
            info.taxes.list.push({
                name: 'VAT',
                percent: vatPercent+'%',
                amount: $('p.vat-amount').html()
            });
        }

        if(serviceTaxPercent>0 && billWriter.config.serviceTax.length) {
            info.taxes.list.push({
                name: 'Service Tax',
                percent: serviceTaxPercent+'%',
                amount: $('p.service-tax-amount').html()
            });
            info.taxes.list.push({
                name: 'Education Cess',
                percent: '2%',
                amount: $('p.education-cess').html()
            });
            info.taxes.list.push({
                name: 'Higher Education Cess',
                percent: '1%',
                amount: $('p.higher-education-cess').html()
            });
        }

        info.taxApplied = info.taxes.list.length;

        info.invoiceType = $('input[type="radio"][name="invoiceType"]:checked').val();

        return info;
    };

    if(devMode) {
        // Fill in the test data
        $('input#billNo').val('TESTING');
        $('input#purchaser').val("John Ahmed Doe");
        $('textarea#purchaser-address').val("B-221, Baker Street\nDown Town\nLondon, UK");
        $('input#purchaser-tin').val("THSPD1251Y");

        $('.items .item input.item-name').val("Canon Printer");
        $('.items .item input.item-price').val(3500);
        $('.items .item input.item-quantity').val(1);
        updateTotals();
    }

    if(!utils.getCookie(COMPANY_NAME).length) {
        $('.company-info').removeClass('hide');
        $('.change-seller-info').addClass('hide');
    } else {
        billWriter.config.companyName = utils.getCookie(COMPANY_NAME);
        billWriter.config.contactNumber = utils.getCookie(COMPANY_PHONE);
        billWriter.config.address = utils.getCookie(COMPANY_ADDRESS);
        billWriter.config.tin = utils.getCookie(COMPANY_TIN);
        billWriter.config.serviceTax = utils.getCookie(COMPANY_SERVICE_TAX);

        $('#company-name').val(billWriter.config.companyName);
        $('#company-address').val(billWriter.config.address);
        $('#company-tin').val(billWriter.config.tin);
        $('#company-service-tax-no').val(billWriter.config.serviceTax);
        $('#company-contact').val(billWriter.config.contactNumber);
        checkServiceTaxApplicability();
    }

}); // END DOCUMENT READY
<|endoftext|>


<commit_before>(function ($) {

    // Protect IE8 from any erroneous console.log uses which would break everything
    if (!window.console) {
        console = { log: function() {} }
    };

    var $html = $('html'),
        lt10 = $html.hasClass('lt-ie10');

    $html.removeClass('no-js');

    pulsar.button = new pulsar.ButtonComponent($html);
    pulsar.disableUi = new pulsar.DisableUiComponent($html);
    pulsar.flash = new pulsar.FlashMessageComponent($html);
    pulsar.helpText = new pulsar.HelpTextComponent($html, window, document);
    pulsar.pulsarForm = new pulsar.PulsarFormComponent($html);
    pulsar.pulsarUI = new pulsar.PulsarUIComponent($html, pulsar.history);
    pulsar.pulsarSortable = new pulsar.PulsarSortableComponent($html, window);
    pulsar.signIn = new pulsar.SignInComponent($html);
    pulsar.masterSwitch = new pulsar.MasterSwitchComponent($html, pulsar.disableUi);
	pulsar.modulePermissions = new pulsar.ModulePermissionsComponent($html);
    pulsar.navMain = new pulsar.NavMainComponent($html, window);
    pulsar.filterBar = new pulsar.FilterBarComponent($html);
    pulsar.repeater = new pulsar.Repeater(window);

    $(function () {
        pulsar.button.init();
        pulsar.flash.init();
        pulsar.helpText.init();
        pulsar.helpText.updateHelpSidebar();
        pulsar.pulsarForm.init();
        pulsar.pulsarSortable.init();
        pulsar.pulsarUI.init();
        pulsar.signIn.init();
        pulsar.masterSwitch.init();
        pulsar.modulePermissions.init();
        pulsar.navMain.init();
        pulsar.filterBar.init();
        pulsar.disableUi.init();
        pulsar.dropZoneComponent = pulsar.DropZoneComponentFactory.create($('body')[0], '.dropzone');
        pulsar.repeater.init(document.querySelector('.repeater'));

        // Switch out .svg for .png for <img> elements in older browsers
        pulsar.svgeezy.init('nocheck', 'png');

        // Use clickover enhancements for popovers
        $('[rel="clickover"]').clickover({ 'global_close': true });

        // Open navigation (should be added to NavMainComponent)
        $('.mobile-menu-button').on('click', function(e) {
            e.preventDefault();

            $('body').toggleClass('open-nav');
            $(this).toggleClass('open');

            if ($(this).text() == 'Menu') {
                $(this).text('Close');
            } else {
                $(this).text('Menu');
            }
        });

        // jsTree
        $('#container').jstree({
            'plugins' : ['state']
        });

        // DropZone
        pulsar.dropZoneComponent.init({
            supported: !lt10,
            showInputNode: lt10
        });

        // Repeater debug
        document.getElementById('repeater-submit-debug').addEventListener('submit', event => {
            event.preventDefault();
            console.log('data: ', $(event.target).serialize());
        });
    });

}(jQuery));
<commit_msg>add messy init code, will revisit this<commit_after>(function ($) {

    // Protect IE8 from any erroneous console.log uses which would break everything
    if (!window.console) {
        console = { log: function() {} }
    };

    var $html = $('html'),
        lt10 = $html.hasClass('lt-ie10');

    $html.removeClass('no-js');

    pulsar.button = new pulsar.ButtonComponent($html);
    pulsar.disableUi = new pulsar.DisableUiComponent($html);
    pulsar.flash = new pulsar.FlashMessageComponent($html);
    pulsar.helpText = new pulsar.HelpTextComponent($html, window, document);
    pulsar.pulsarForm = new pulsar.PulsarFormComponent($html);
    pulsar.pulsarUI = new pulsar.PulsarUIComponent($html, pulsar.history);
    pulsar.pulsarSortable = new pulsar.PulsarSortableComponent($html, window);
    pulsar.signIn = new pulsar.SignInComponent($html);
    pulsar.masterSwitch = new pulsar.MasterSwitchComponent($html, pulsar.disableUi);
	pulsar.modulePermissions = new pulsar.ModulePermissionsComponent($html);
    pulsar.navMain = new pulsar.NavMainComponent($html, window);
    pulsar.filterBar = new pulsar.FilterBarComponent($html);
    pulsar.repeater = new pulsar.Repeater(window);

    $(function () {
        pulsar.button.init();
        pulsar.flash.init();
        pulsar.helpText.init();
        pulsar.helpText.updateHelpSidebar();
        pulsar.pulsarForm.init();
        pulsar.pulsarSortable.init();
        pulsar.pulsarUI.init();
        pulsar.signIn.init();
        pulsar.masterSwitch.init();
        pulsar.modulePermissions.init();
        pulsar.navMain.init();
        pulsar.filterBar.init();
        pulsar.disableUi.init();
        pulsar.dropZoneComponent = pulsar.DropZoneComponentFactory.create($('body')[0], '.dropzone');

        // Switch out .svg for .png for <img> elements in older browsers
        pulsar.svgeezy.init('nocheck', 'png');

        // Use clickover enhancements for popovers
        $('[rel="clickover"]').clickover({ 'global_close': true });

        // Open navigation (should be added to NavMainComponent)
        $('.mobile-menu-button').on('click', function(e) {
            e.preventDefault();

            $('body').toggleClass('open-nav');
            $(this).toggleClass('open');

            if ($(this).text() == 'Menu') {
                $(this).text('Close');
            } else {
                $(this).text('Menu');
            }
        });

        // jsTree
        $('#container').jstree({
            'plugins' : ['state']
        });

        // DropZone
        pulsar.dropZoneComponent.init({
            supported: !lt10,
            showInputNode: lt10
        });

        // TODO, tidy this up
        const repeatable = document.querySelector('.repeater');

        // TODO, handle multiple instances of a repeater
        if (repeatable) {
            pulsar.repeater.init(repeatable);
        }

        // Repeater debug
        document.getElementById('repeater-submit-debug').addEventListener('submit', event => {
            event.preventDefault();
            console.log('data: ', $(event.target).serialize());
        });
    });

}(jQuery));
<|endoftext|>


<commit_before>var defaults = {
    todoTask: 'tood-task',
    todoHeader: 'task-header',
    todoDate: 'task-date',
    taskId: 'task-',
    deleteDiv: 'delete-div'
}, codes = {
    '1': '#list-inbox',
    '2': '#list-urgent',
    '3': '#list-today'
};

var TODO = {
    init: function() {
        console.log("in init");
        $('.todo-input').keydown(this.add.bind(this));
    },
    add: function(e) {
        console.log("in add");
        if($('.todo-input').val() && e.keyCode === 13) {
            console.log("haha");
            var title = $('.todo-input').val();
            console.log(title);
            var key = 13;
            TODO.appendTODOHTML(title, key, 0, 1);
            $('.todo-input').val(""); //인풋이 많으니 골라 지워
        }

    },
    appendTODOHTML: function(title, id, completed, code) {
        var parent = $(codes[code])
        var source   = $("#todo-template").html();
        var template = Handlebars.compile(source);
        var data = {
            id: id,
            title : title,
            completed: completed
        };
        $(parent).append(template(data));
        console.log(template(data));

    }
    // generateElement({
    //   id: "123",
    //   code: "1", //리스트 이름
    //   title: "My Uber Important Task",
    //   start-date: "5/9/2015",
    //   completed-date: "5/10/2015",
    //   completed: '0'
    // });
}

TODO.init();
<commit_msg>[week2] add todo<commit_after>var consts = {

}, lists = {
    '1': '#list-inbox',
    '2': '#list-urgent',
    '3': '#list-today'
};

var TODO = {
    init: function() {
        $('.todo-input').keydown(this.add.bind(this));
    },
    add: function(e) {
        if($('.todo-input').val() && e.keyCode === 13) {
            var title = $('.todo-input').val();
            var key = 15;
            TODO.appendTODOHTML(title, key, 0, 1);
            $('.todo-input').val(""); //인풋이 많으니 골라 지워
        }

    },
    appendTODOHTML: function(title, id, completed, list) {
        var parent = $(lists[list])
        var source   = $("#todo-template").html();
        var template = Handlebars.compile(source);
        var data = {
            id: id,
            title : title,
            completed: completed
        };
        $(parent).append(template(data));

    }
    /*
    generateElement({
      id: "123",
      code: "1", //리스트 이름
      title: "My Uber Important Task",
      start_date: "5/9/2015",
      completed_date: "5/10/2015",
      completed: '0'
    });
    */
    remove: function(id) {

    }
}

TODO.init();
<|endoftext|>


<commit_before>/**
 * Global vars
 */
var
	assets,
	GAME,
	GS_INTRO,
	GS_MENU,
	GS_LEVEL_INDEX = 0;

/**
 * Register assets
 */
assets = [

	//MAPS
	"res/maps/level-1-1.tmx",
	"res/maps/level-1-2.tmx",
	"res/maps/level-1-3.tmx",

	//TILESETS
	"res/img/tilesets/main-tileset.png",

	//BACKGROUNDS
	"res/img/parallax/layer-1.png",
	"res/img/parallax/layer-2.png",
	"res/img/parallax/layer-3.png",

	//FONTS
	"res/font/mario.fnt",
	"res/font/skranji.fnt",

	//LOGOS
	"res/img/logos/dackmin.png",
	"res/img/logos/freshflesh.png",
	"res/img/logos/cheezy.png",

	//MAIN MENU
	"res/img/menu/bg_grasslands.png",
	"res/img/menu/foreground.png",
	"res/img/menu/new_game.png",
	"res/img/menu/new_game_hover.png",
	"res/img/menu/settings.png",
	"res/img/menu/settings_hover.png",
	"res/img/menu/cheezy-logo.png",
	"res/img/menu/grassMid.png",
	"res/img/menu/star.png",
	"res/img/menu/cloud1.png",
	"res/img/menu/cloud2.png",
	"res/img/menu/cloud3.png",
	"res/img/menu/howto.png",
	"res/img/menu/howto-keyboard.png",
	"res/img/menu/howto-controller.png",

	//PAUSE MENU
	"res/img/pause/bg.png",
	"res/img/pause/resume.png",
	"res/img/pause/settings.png",
	"res/img/pause/menu.png",
	"res/img/pause/quit_bg.png",
	"res/img/pause/cancel_quit.png",
	"res/img/pause/ok_quit.png",

	//SETTINGS
	"res/img/settings/bg.png",
	"res/img/settings/key_bg.png",
	"res/img/settings/music.png",
	"res/img/settings/no_music.png",
	"res/img/settings/sounds.png",
	"res/img/settings/no_sounds.png",

	//HUD
	"res/img/hud/heart_full.png",
	"res/img/hud/heart_half.png",
	"res/img/hud/heart_empty.png",
	"res/img/hud/coins.png",
	"res/img/hud/timer.png",
	"res/img/hud/lives.png",

	//ITEMS
	"res/img/items/coin.png",
	"res/img/items/life.png",

	//ENEMIES
	"res/img/enemies/snail.png",
	"res/img/enemies/fish.png",

	//PLAYER
	"res/img/charsets/player.png"

];

/**
 * Entry point
 */
window.onload = function(){

	//Creating assets loader
	var assetLoader = new FF.AssetLoader(assets);

	//Listen on progress event to show a wonderful loader
	assetLoader.addEventListener("progress", function(e){
		document.getElementById("loader").style.width = ((e.loaded/e.total)*100)+"%";
	});

	//Listen on loaded event to launch the game when everything is loaded
	assetLoader.addEventListener("loaded", function(){

		//Create our gamestates
		GS_INTRO = new IntroGameState();
		//GS_SETTINGS = new SettingsGameState();
		GS_MENU = new MenuGameState();
		//GS_MAIN = new MainGameState();

		//Then create our fantastic game manager
		GAME = new FF.Game(GS_INTRO, { backgroundColor : "#000" });

		//Then hide our loader and lauch the game
		document.getElementById("loader").style.display = "none";
		GAME.launch();
	});

	//And finally load everything for the game to be able to start properly
	assetLoader.load();

};
<commit_msg>Add MainGameState in main.js<commit_after>/**
 * Global vars
 */
var
	assets,
	GAME,
	GS_INTRO,
	GS_MENU,
	GS_MAIN,
	GS_LEVEL_INDEX = 0;

/**
 * Register assets
 */
assets = [

	//MAPS
	"res/maps/level-1-1.tmx",
	"res/maps/level-1-2.tmx",
	"res/maps/level-1-3.tmx",

	//TILESETS
	"res/img/tilesets/main-tileset.png",

	//BACKGROUNDS
	"res/img/parallax/layer-1.png",
	"res/img/parallax/layer-2.png",
	"res/img/parallax/layer-3.png",

	//FONTS
	"res/font/mario.fnt",
	"res/font/skranji.fnt",

	//LOGOS
	"res/img/logos/dackmin.png",
	"res/img/logos/freshflesh.png",
	"res/img/logos/cheezy.png",

	//MAIN MENU
	"res/img/menu/bg_grasslands.png",
	"res/img/menu/foreground.png",
	"res/img/menu/new_game.png",
	"res/img/menu/new_game_hover.png",
	"res/img/menu/settings.png",
	"res/img/menu/settings_hover.png",
	"res/img/menu/cheezy-logo.png",
	"res/img/menu/grassMid.png",
	"res/img/menu/star.png",
	"res/img/menu/cloud1.png",
	"res/img/menu/cloud2.png",
	"res/img/menu/cloud3.png",
	"res/img/menu/howto.png",
	"res/img/menu/howto-keyboard.png",
	"res/img/menu/howto-controller.png",

	//PAUSE MENU
	"res/img/pause/bg.png",
	"res/img/pause/resume.png",
	"res/img/pause/settings.png",
	"res/img/pause/menu.png",
	"res/img/pause/quit_bg.png",
	"res/img/pause/cancel_quit.png",
	"res/img/pause/ok_quit.png",

	//SETTINGS
	"res/img/settings/bg.png",
	"res/img/settings/key_bg.png",
	"res/img/settings/music.png",
	"res/img/settings/no_music.png",
	"res/img/settings/sounds.png",
	"res/img/settings/no_sounds.png",

	//HUD
	"res/img/hud/heart_full.png",
	"res/img/hud/heart_half.png",
	"res/img/hud/heart_empty.png",
	"res/img/hud/coins.png",
	"res/img/hud/timer.png",
	"res/img/hud/lives.png",

	//ITEMS
	"res/img/items/coin.png",
	"res/img/items/life.png",

	//ENEMIES
	"res/img/enemies/snail.png",
	"res/img/enemies/fish.png",

	//PLAYER
	"res/img/charsets/player.png"

];

/**
 * Entry point
 */
window.onload = function(){

	//Creating assets loader
	var assetLoader = new FF.AssetLoader(assets);

	//Listen on progress event to show a wonderful loader
	assetLoader.addEventListener("progress", function(e){
		document.getElementById("loader").style.width = ((e.loaded/e.total)*100)+"%";
	});

	//Listen on loaded event to launch the game when everything is loaded
	assetLoader.addEventListener("loaded", function(){

		//Create our gamestates
		GS_INTRO = new IntroGameState();
		//GS_SETTINGS = new SettingsGameState();
		GS_MENU = new MenuGameState();
		GS_MAIN = new MainGameState();

		//Then create our fantastic game manager
		GAME = new FF.Game(GS_INTRO, { backgroundColor : "#000" });

		//Then hide our loader and lauch the game
		document.getElementById("loader").style.display = "none";
		GAME.launch();
	});

	//And finally load everything for the game to be able to start properly
	assetLoader.load();

};
<|endoftext|>


<commit_before>var map;
function initialize() {
  var mapOptions = {
    zoom: 9,
    enter: new google.maps.LatLng(34.708, -77.959),
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL
    }
  };

  google.maps.visualRefresh=true;
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Load a GeoJSON from the same server as our demo.
  var jsonData = "data/ncVacationData.json";
  map.data.loadGeoJson(jsonData);

  // Set mouseover event for each feature.
  map.data.addListener('mouseover', function(event) {
    content = event.feature.getProperty('Name');
  });

  var infoWindow = new google.maps.InfoWindow({
    // content: content
  });

}

google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>Update main.js<commit_after>var map;
function initialize() {
  var mapOptions = {
    zoom: 9,
    enter: new google.maps.LatLng(34.708, -77.959),
    zoomControl: true,
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL
    }
  };

  google.maps.visualRefresh=true;
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Load a GeoJSON from the same server as our demo.
  var jsonData = "data/ncVacationData.json";
  map.data.loadGeoJson(jsonData);

  // Set mouseover event for each feature.
  map.data.addListener('mouseover', function(event) {
    content = event.feature.getProperty('Name');
  });

  var infoWindow = new google.maps.InfoWindow({
    // content: content
  });

}

google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>