Upgrade to 3.1 step 2 - js

This commit is contained in:
magnolia-fan
2011-09-08 03:47:11 +04:00
parent 6982e0cb32
commit e59f959bac
27 changed files with 49 additions and 1170 deletions
BIN
View File
Binary file not shown.
+85
View File
@@ -0,0 +1,85 @@
class window.Ajax
referer: false
loadArtistData: (name) ->
_search.showSpinner()
name = name.split(' ').join('+')
$.get '/artist/' +name+ '/', (data) ->
if data.status?
if data.status is 'loading'
_search.showArtistPics data.pics
setTimeout () ->
_ajax.loadArtistData name
, 3000
else if data.status is 'corrected'
_ajax.loadArtistData data.page
else if data.status is 'suggestions'
_search.hideSpinner()
_search.showSuggestions data.values
else if data.status == 'loading_failed'
_search.hideSpinner()
_search.showError()
_beathaven.redrawScrollbar()
else
_ajax.setArchor '/artist/' +name+ '/'
_pages.renderArtist data
_search.hideSpinner()
false
loadSearchPage: ->
false
loadSettingsPage: ->
$.get '/templates/settings.html', (data) ->
_ajax.setArchor '/settings/'
_pages.renderSettings _beathaven.localizeHTML $(data)
false
load404Page: ->
$.get '/404.html', (data) ->
$('.data-container .inner').html data
_beathaven.redrawScrollbar()
false
loadAboutPage: ->
$.get '/templates/about.html', (data) ->
_pages.renderTextpage data
_ajax.setTitle 'About'
false
setArchor: (anchor) ->
@referer = this.getAnchor()
window.location.hash = '#' +anchor
getAnchor: () ->
window.location.hash.substring 1;
setTitle: (title) ->
document.title = title+ ' @ BeatHaven'
go: (url) ->
this.setArchor url
false
detectPage: () ->
if m = _ajax.getAnchor().match /\/artist\/(.+)\//
_ajax.loadArtistData m[1]
else if _ajax.getAnchor() == '' or _ajax.getAnchor().match /\/search\//
_ajax.loadSearchPage();
else if _ajax.getAnchor().match /\/settings\//
_ajax.loadSettingsPage()
else if _ajax.getAnchor().match /\/about\//
_ajax.loadAboutPage()
else
_ajax.loadSearchPage()
false
$('a.data.artist').live 'click', ->
_ajax.loadArtistData $(this).html()
false
$(window).bind 'hashchange', ->
_ajax.detectPage()
false
+14
View File
@@ -0,0 +1,14 @@
//= require jquery/jquery.autocomplete
//= require jquery/jquery.jplayer
//= require jquery/jquery.scroll
//= require locale
//= require vkontakte
//= require session
//= require ajax
//= require player
//= require search
//= require pages
//= require settings
//= require beathaven
+136
View File
@@ -0,0 +1,136 @@
# Registering global objects
window._beathaven = null
window._session = 1
window._vkontakte = null
window._ajax = null
window._player = null
window._search = null
window._pages = null
window._settings = null
$ ->
l = document.location
if l.hostname not in ['beathaven.org', 'dev.beathaven.org']
l.href = 'http://beathaven.org/'+ l.hash
window._beathaven = new BeatHaven()
window._beathaven.init()
$(window).resize ->
_beathaven.adjustSizes()
_beathaven.redrawScrollbar()
false
window.setTimeout ->
window._beathaven.checkRedrawScrollbar()
false
, 500
class BeatHaven
last_height: false
lang: 'ru'
init: ->
this.adjustSizes()
this.checkRedrawScrollbar()
# if document.location.host == 'beathaven.org' then 2335068 else 2383163
window._vkontakte = new Vkontakte(2335068)
window._vkontakte.init()
window._ajax = new Ajax()
window._player = new Player()
window._player.initJplayer()
window._search = new Search()
window._pages = new Pages()
window._settings = new Settings()
false
adjustSizes: ->
$('.data-container').height $(window).height() - $('.header-container').height() - $('.pulldown').height()
$('.data-container').width $(window).width() - $('.player').width()
$('.player-container').height $(window).height()
$('.playlist').height $(window).height() - $('.player').height() - $('.player-container .additional-controls').height()
$('.data-container').scrollbar()
$('.playlist').scrollbar()
false
checkRedrawScrollbar: ->
focused_id = false
if document.activeElement.id?
focused_id = document.activeElement.id;
outer_height = $('.data-container > div').outerHeight()
if outer_height > 300 and outer_height != _beathaven.last_height
_beathaven.last_height = outer_height
_beathaven.redrawScrollbar()
if focused_id
document.getElementById(focused_id).focus()
focused_id = false
window.setTimeout ->
_beathaven.checkRedrawScrollbar()
false
, 500
false
redrawScrollbar: ->
$('.data-container').html $('.data-container').find('.inner').first()
$('.data-container').scrollbar()
false
localizeHTML: (obj, lang) ->
unless obj?
obj = $('body')
unless lang?
lang = _beathaven.lang
$(obj).find('[data-ls]').each ->
if _locale[$(this).attr 'data-ls']? and _locale[$(this).attr 'data-ls'][lang]?
if this.nodeName is 'INPUT'
$(this).val _locale[$(this).attr 'data-ls'][lang]
else
$(this).text _locale[$(this).attr 'data-ls'][lang]
return obj
ls: (id, lang) ->
unless lang?
lang = _beathaven.lang
if _locale[id]? and _locale[id][lang]?
_locale[id][lang]
else
id
pdShowSpinner: ->
$('.pulldown').html '<div class="pd-spinner"><img src="/images/loader.gif" alt=""/></div>'
false
pdHideSpinner: ->
$('.pulldown').html ''
false
String::htmlsafe = ->
replaces = [
["\\", "\\\\"]
["\"", "&quot;"]
["<", "&lt;"]
[">", "&gt;"]
]
str = this
for item in replaces
str = str.replace item[0], item[1]
str
String::trim = ->
str = this
while str.indexOf(' ') != -1
str = str.replace(' ', ' ')
if str.charAt(0) == ' '
str = str.substring 1
if str.charAt(str.length - 1) == ' '
str = str.substring(0, str.length - 1)
str
@@ -0,0 +1,400 @@
/**
* Ajax Autocomplete for jQuery, version 1.1.3
* (c) 2010 Tomas Kirda
*
* Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
* For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
*
* Last Review: 04/19/2010
*/
/*jslint onevar: true, evil: true, nomen: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true */
/*global window: true, document: true, clearInterval: true, setInterval: true, jQuery: true */
(function($) {
var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');
function fnFormatResult(value, data, currentValue) {
if (currentValue === 'and' || currentValue === '&' || currentValue === 'n\'') {
var pattern = '(and|\&|n\')';
} else {
var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
}
return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
}
function Autocomplete(el, options) {
this.el = $(el);
this.el.attr('autocomplete', 'off');
this.suggestions = [];
this.data = [];
this.badQueries = [];
this.selectedIndex = -1;
this.currentValue = this.el.val();
this.intervalId = 0;
this.cachedResponse = [];
this.onChangeInterval = null;
this.ignoreValueChange = false;
this.serviceUrl = options.serviceUrl;
this.isLocal = false;
this.options = {
autoSubmit: false,
minChars: 1,
maxHeight: 300,
deferRequestBy: 0,
width: 0,
highlight: true,
params: {},
fnFormatResult: fnFormatResult,
delimiter: null,
zIndex: 9999
};
this.initialize();
this.setOptions(options);
}
$.fn.bh_autocomplete = function(options) {
return new Autocomplete(this.get(0)||$('<input />'), options);
};
Autocomplete.prototype = {
killerFn: null,
initialize: function() {
var me, uid, autocompleteElId;
me = this;
uid = Math.floor(Math.random()*0x100000).toString(16);
autocompleteElId = 'Autocomplete_' + uid;
this.killerFn = function(e) {
if ($(e.target).parents('.autocomplete').size() === 0) {
me.killSuggestions();
me.disableKillerFn();
}
};
if (!this.options.width) { this.options.width = this.el.width(); }
this.mainContainerId = 'AutocompleteContainter_' + uid;
$('<div class="autocomplete-container" id="' + this.mainContainerId + '" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:300px;"></div></div></div>').appendTo('body');
this.container = $('#' + autocompleteElId);
this.fixPosition();
if (window.opera) {
this.el.keypress(function(e) { me.onKeyPress(e); });
} else {
this.el.keydown(function(e) { me.onKeyPress(e); });
}
this.el.keyup(function(e) { me.onKeyUp(e); });
this.el.blur(function() { me.enableKillerFn(); });
this.el.focus(function() { me.fixPosition(); });
},
setOptions: function(options){
var o = this.options;
$.extend(o, options);
if(o.lookup){
this.isLocal = true;
if($.isArray(o.lookup)){ o.lookup = { suggestions:o.lookup, data:[] }; }
}
$('#'+this.mainContainerId).css({ zIndex:o.zIndex });
this.container.css({ maxHeight: o.maxHeight + 'px', width:o.width });
},
clearCache: function(){
this.cachedResponse = [];
this.badQueries = [];
},
disable: function(){
this.disabled = true;
},
enable: function(){
this.disabled = false;
},
fixPosition: function() {
var offset = this.el.offset();
$('#' + this.mainContainerId).css({ top: (offset.top + this.el.innerHeight()) + 'px', left: offset.left + 'px' });
},
enableKillerFn: function() {
var me = this;
$(document).bind('click', me.killerFn);
},
disableKillerFn: function() {
var me = this;
$(document).unbind('click', me.killerFn);
},
killSuggestions: function() {
var me = this;
this.stopKillSuggestions();
this.intervalId = window.setInterval(function() { me.hide(); me.stopKillSuggestions(); }, 300);
},
stopKillSuggestions: function() {
window.clearInterval(this.intervalId);
},
onKeyPress: function(e) {
if (this.disabled || !this.enabled) { return; }
// return will exit the function
// and event will not be prevented
switch (e.keyCode) {
case 27: //KEY_ESC:
this.el.val(this.currentValue);
this.hide();
break;
case 9: //KEY_TAB:
case 13: //KEY_RETURN:
if (this.selectedIndex === -1) {
this.hide();
return;
}
this.select(this.selectedIndex);
if(e.keyCode === 9){ return; }
break;
case 38: //KEY_UP:
this.moveUp();
break;
case 40: //KEY_DOWN:
this.moveDown();
break;
default:
return;
}
e.stopImmediatePropagation();
e.preventDefault();
},
onKeyUp: function(e) {
if(this.disabled){ return; }
switch (e.keyCode) {
case 38: //KEY_UP:
case 40: //KEY_DOWN:
return;
}
clearInterval(this.onChangeInterval);
if (this.currentValue !== this.el.val()) {
if (this.options.deferRequestBy > 0) {
// Defer lookup in case when value changes very quickly:
var me = this;
this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy);
} else {
this.onValueChange();
}
}
},
onValueChange: function() {
clearInterval(this.onChangeInterval);
this.currentValue = this.el.val();
var q = this.getQuery(this.currentValue);
this.selectedIndex = -1;
if (this.ignoreValueChange) {
this.ignoreValueChange = false;
return;
}
if (q === '' || q.length < this.options.minChars) {
this.hide();
} else {
this.getSuggestions(q);
}
},
getQuery: function(val) {
var d, arr;
d = this.options.delimiter;
if (!d) { return $.trim(val); }
arr = val.split(d);
return $.trim(arr[arr.length - 1]);
},
getSuggestionsLocal: function(q) {
var ret, arr, len, val, i;
arr = this.options.lookup;
len = arr.suggestions.length;
ret = { suggestions:[], data:[] };
q = q.toLowerCase();
for(i=0; i< len; i++){
val = arr.suggestions[i];
if(val.toLowerCase().indexOf(q) === 0){
ret.suggestions.push(val);
ret.data.push(arr.data[i]);
}
}
return ret;
},
getSuggestions: function(q) {
var cr, me;
cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q];
if (cr && $.isArray(cr.suggestions)) {
this.suggestions = cr.suggestions;
this.data = cr.data;
this.suggest();
} else if (!this.isBadQuery(q)) {
me = this;
me.options.params.query = q;
$.get(this.serviceUrl, me.options.params, function(txt) { me.processResponse(txt); }, 'text');
}
},
isBadQuery: function(q) {
var i = this.badQueries.length;
while (i--) {
if (q.indexOf(this.badQueries[i]) === 0) { return true; }
}
return false;
},
hide: function() {
this.enabled = false;
this.selectedIndex = -1;
this.container.hide();
},
suggest: function() {
if (this.suggestions.length === 0) {
this.hide();
return;
}
var me, len, div, f, v, i, s, mOver, mClick;
me = this;
len = this.suggestions.length;
f = this.options.fnFormatResult;
v = this.getQuery(this.currentValue);
mOver = function(xi) { return function() { me.activate(xi); }; };
mClick = function(xi) { return function() { me.select(xi); }; };
this.container.hide().empty();
for (i = 0; i < len; i++) {
s = this.suggestions[i];
div = $((me.selectedIndex === i ? '<div class="selected"' : '<div') + ' title="' + s + '">' + f(s, this.data[i], v) + '</div>');
div.mouseover(mOver(i));
div.click(mClick(i));
this.container.append(div);
}
this.enabled = true;
that = this;
$('.pulldown').animate({height: 250}, 'fast', function(){
that.container.show();
_beathaven.adjustSizes()
_beathaven.redrawScrollbar()
});
},
processResponse: function(text) {
var response;
try {
response = eval('(' + text + ')');
} catch (err) { return; }
if (!$.isArray(response.data)) { response.data = []; }
if(!this.options.noCache){
this.cachedResponse[response.query] = response;
if (response.suggestions.length === 0) { this.badQueries.push(response.query); }
}
if (response.query === this.getQuery(this.currentValue)) {
this.suggestions = response.suggestions;
this.data = response.data;
this.suggest();
}
},
activate: function(index) {
var divs, activeItem;
divs = this.container.children();
// Clear previous selection:
if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
$(divs.get(this.selectedIndex)).removeClass();
}
this.selectedIndex = index;
if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
activeItem = divs.get(this.selectedIndex);
$(activeItem).addClass('selected');
}
return activeItem;
},
deactivate: function(div, index) {
div.className = '';
if (this.selectedIndex === index) { this.selectedIndex = -1; }
},
select: function(i) {
var selectedValue, f;
selectedValue = this.suggestions[i];
if (selectedValue) {
this.el.val(selectedValue);
if (this.options.autoSubmit) {
f = this.el.parents('form');
if (f.length > 0) { f.get(0).submit(); }
}
this.ignoreValueChange = true;
this.hide();
this.onSelect(i);
}
},
moveUp: function() {
if (this.selectedIndex === -1) { return; }
if (this.selectedIndex === 0) {
this.container.children().get(0).className = '';
this.selectedIndex = -1;
this.el.val(this.currentValue);
return;
}
this.adjustScroll(this.selectedIndex - 1);
},
moveDown: function() {
if (this.selectedIndex === (this.suggestions.length - 1)) { return; }
this.adjustScroll(this.selectedIndex + 1);
},
adjustScroll: function(i) {
var activeItem, offsetTop, upperBound, lowerBound;
activeItem = this.activate(i);
offsetTop = activeItem.offsetTop;
upperBound = this.container.scrollTop();
lowerBound = upperBound + this.options.maxHeight - 25;
if (offsetTop < upperBound) {
this.container.scrollTop(offsetTop);
} else if (offsetTop > lowerBound) {
this.container.scrollTop(offsetTop - this.options.maxHeight + 25);
}
this.el.val(this.getValue(this.suggestions[i]));
},
onSelect: function(i) {
var me, fn, s, d;
me = this;
fn = me.options.onSelect;
s = me.suggestions[i];
d = me.data[i];
me.el.val(me.getValue(s));
if ($.isFunction(fn)) { fn(s, d, me.el); }
},
getValue: function(value){
var del, currVal, arr, me;
me = this;
del = me.options.delimiter;
if (!del) { return value; }
currVal = me.currentValue;
arr = currVal.split(del);
if (arr.length === 1) { return value; }
return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value;
}
};
}(jQuery));
File diff suppressed because it is too large Load Diff
+660
View File
@@ -0,0 +1,660 @@
/*jslint eqeqeq: true, regexp: true */
/*global document, window, setInterval, clearInterval, handler, jQuery */
/*
* Scrollbar - a jQuery plugin for custom scrollbars
*
* @author Thomas Duerr, me@thomd.net
* @date 03.2010
* @requires jquery v1.4.2
* @version 0.3
*
*
* Usage:
*
* Append scrollbar to an arbitrary container with overflowed content:
*
* $('selector').scrollbar();
*
*
* Append scrollbar without arrows on top/bottom:
*
* $('selector').scrollbar({
* arrows: false
* });
*
*
*
* A vertical scrollbar is based on the following box model:
*
* +----------------------------------+
* | <----------------------------- content container
* | +-----------------+ +------+ |
* | | | | <-------------- handle arrow up
* | | | | | |
* | | | +------+ |
* | | | | +--+ | |
* | | | | | | | |
* | | | | | <-------------- handle
* | | | | | | | |
* | | | | | | | |
* | | | | | | | |
* | | | | +--+ | |
* | | | | | |
* | | | | <-------------- handle container
* | | | | | |
* | | <----------------------------- pane
* | | | | | |
* | | | | | |
* | | | +------+ |
* | | | | | |
* | | | | <-------------- handle arrow down
* | +-----------------+ +------+ |
* | |
* +----------------------------------+
*
*
*/
(function($, document){
$.fn.scrollbar = function(opts){
// Extend default options
var options = $.extend({}, $.fn.scrollbar.defaults, opts);
//
// append scrollbar to selected overflowed containers and return jquery object for chainability
//
return this.each(function(){
var container = $(this)
// properties
, props = {
arrows: options.arrows
};
// set container height explicitly if given by an option
if(options.containerHeight != 'auto'){
container.height(options.containerHeight);
}
// save container height in properties
props.containerHeight = container.height();
// save content height in properties
props.contentHeight = $.fn.scrollbar.contentHeight(container);
// if the content height is lower than the container height, do nothing and return.
if(props.contentHeight <= props.containerHeight){
return true;
}
// create a new scrollbar object
var scrollbar = new $.fn.scrollbar.Scrollbar(container, props, options);
// build HTML, initialize Handle and append Events
scrollbar.buildHtml().initHandle().appendEvents();
});
};
// # default options
//
//
$.fn.scrollbar.defaults = {
// ### containerHeight `Number` or `'auto'`
//
// height of content container. If set to `'auto'`, the naturally rendered height is used
containerHeight: 'auto',
arrows: true, // render up- and down-arrows
handleHeight: 'auto', // height of handle [px || 'auto']. If set to 'auto', the height will be calculated proportionally to the container-content height.
handleMinHeight: 30, // min-height of handle [px]. This property will only be used if handleHeight is set to 'auto'
scrollSpeed: 50, // speed of handle while mousedown on arrows [milli sec]
scrollStep: 20, // handle increment between two mousedowns on arrows [px]
scrollSpeedArrows: 40, // speed of handle while mousedown within the handle container [milli sec]
scrollStepArrows: 3 // handle increment between two mousedowns within the handle container [px]
};
//
// Scrollbar constructor
//
$.fn.scrollbar.Scrollbar = function(container, props, options){
// set object properties
this.container = container;
this.props = props;
this.opts = options;
this.mouse = {};
// disable arrows via class attribute 'no-arrows' on a container
this.props.arrows = this.container.hasClass('no-arrows') ? false : this.props.arrows;
};
//
// Scrollbar methods
//
$.fn.scrollbar.Scrollbar.prototype = {
//
// build DOM nodes for pane and scroll-handle
//
// from:
//
// <div class="foo"> --> arbitrary element with a fixed height or a max-height lower that its containing elements
// [...]
// </div>
//
// to:
//
// <div class="foo"> --> this.container
// <div class="scrollbar-pane"> --> this.pane
// [...]
// </div>
// <div class="scrollbar-handle-container"> --> this.handleContainer
// <div class="scrollbar-handle"></div> --> this.handle
// </div>
// <div class="scrollbar-handle-up"></div> --> this.handleArrows
// <div class="scrollbar-handle-down"></div> --> this.handleArrows
// </div>
//
//
// TODO: use detach-transform-attach or DOMfragment
//
buildHtml: function(){
// build new DOM nodes
this.container.children().wrapAll('<div class="scrollbar-pane"/>');
this.container.append('<div class="scrollbar-handle-container"><div class="scrollbar-handle"/></div>');
if(this.props.arrows){
this.container.append('<div class="scrollbar-handle-up"/>').append('<div class="scrollbar-handle-down"/>');
}
// save height of container to re-set it after some DOM manipulations
var height = this.container.height();
// set scrollbar-object properties
this.pane = this.container.find('.scrollbar-pane');
this.handle = this.container.find('.scrollbar-handle');
this.handleContainer = this.container.find('.scrollbar-handle-container');
this.handleArrows = this.container.find('.scrollbar-handle-up, .scrollbar-handle-down');
this.handleArrowUp = this.container.find('.scrollbar-handle-up');
this.handleArrowDown = this.container.find('.scrollbar-handle-down');
this.pane_last_top = 0;
// set some default CSS attributes (may be overwritten by CSS definitions in an external CSS file)
this.pane.defaultCss({
'top': 0,
'left': 0
});
this.handleContainer.defaultCss({
'right': 0
});
this.handle.defaultCss({
'top': 0,
'right': 0
});
this.handleArrows.defaultCss({
'right': 0
});
this.handleArrowUp.defaultCss({
'top': 0
});
this.handleArrowDown.defaultCss({
'bottom': 0
});
// set some necessary CSS attributes (can NOT be overwritten by CSS definitions)
this.container.css({
'position': this.container.css('position') === 'absolute' ? 'absolute' : 'relative',
'overflow': 'hidden',
'height': height
});
this.pane.css({
'position': 'absolute',
'overflow': 'visible',
'height': 'auto'
});
this.handleContainer.css({
'position': 'absolute',
'top': this.handleArrowUp.outerHeight(true),
'height': (this.props.containerHeight - (this.container.outerHeight(true) - this.container.height()) - this.handleArrowUp.outerHeight(true) - this.handleArrowDown.outerHeight(true)) + 'px'
});
this.handle.css({
'position': 'absolute',
'cursor': 'pointer'
});
this.handleArrows.css({
'position': 'absolute',
'cursor': 'pointer'
});
return this;
},
//
// calculate positions and dimensions of handle and arrow-handles
//
initHandle: function(){
this.props.handleContainerHeight = this.handleContainer.height();
this.props.contentHeight = this.pane.height();
// height of handle
this.props.handleHeight = this.opts.handleHeight == 'auto' ? Math.max(Math.ceil(this.props.containerHeight * this.props.handleContainerHeight / this.props.contentHeight), this.opts.handleMinHeight) : this.opts.handleHeight;
this.handle.height(this.props.handleHeight);
// if handle has a border (always be aware of the css box-model), we need to correct the handle height.
this.handle.height(2 * this.handle.height() - this.handle.outerHeight(true));
// min- and max-range for handle
this.props.handleTop = {
min: 0,
max: (this.props.handleContainerHeight - this.props.handleHeight)
};
// ratio of handle-container-height to content-container-height (to calculate position of content related to position of handle)
this.props.handleContentRatio = (this.props.contentHeight - this.props.containerHeight) / (this.props.handleContainerHeight - this.props.handleHeight);
// initial position of handle at top
this.handle.top = 0;
return this;
},
//
// append events on handle and handle-container
//
appendEvents: function(){
// append drag-drop event on scrollbar-handle
this.handle.bind('mousedown.handle', $.proxy(this, 'startOfHandleMove'));
// append mousedown event on handle-container
this.handleContainer.bind('mousedown.handle', $.proxy(this, 'onHandleContainerMousedown'));
// append hover event on handle-container
this.handleContainer.bind('mouseenter.container mouseleave.container', $.proxy(this, 'onHandleContainerHover'));
// append click event on scrollbar-up- and scrollbar-down-handles
this.handleArrows.bind('mousedown.arrows', $.proxy(this, 'onArrowsMousedown'));
// append mousewheel event on content container
this.container.bind('mousewheel.container', $.proxy(this, 'onMouseWheel'));
// append hover event on content container
this.container.bind('mouseenter.container mouseleave.container', $.proxy(this, 'onContentHover'));
// do not bubble down click events into content container
this.handle.bind('click.scrollbar', this.preventClickBubbling);
this.handleContainer.bind('click.scrollbar', this.preventClickBubbling);
this.handleArrows.bind('click.scrollbar', this.preventClickBubbling);
return this;
},
//
// get mouse position helper
//
mousePosition: function(ev) {
return ev.pageY || (ev.clientY + (document.documentElement.scrollTop || document.body.scrollTop)) || 0;
},
// ---------- event handler ---------------------------------------------------------------
//
// start moving of handle
//
startOfHandleMove: function(ev){
ev.preventDefault();
ev.stopPropagation();
// set start position of mouse
this.mouse.start = this.mousePosition(ev);
// set start position of handle
this.handle.start = this.handle.top;
// bind mousemove- and mouseout-event on document (binding it to document allows having a mousepointer outside handle while moving)
$(document).bind('mousemove.handle', $.proxy(this, 'onHandleMove')).bind('mouseup.handle', $.proxy(this, 'endOfHandleMove'));
// add class for visual change while moving handle
this.handle.addClass('move');
this.handleContainer.addClass('move');
},
//
// on moving of handle
//
onHandleMove: function(ev){
ev.preventDefault();
// calculate distance since last fireing of this handler
var distance = this.mousePosition(ev) - this.mouse.start;
// calculate new handle position
this.handle.top = this.handle.start + distance;
// update positions
this.setHandlePosition();
this.setContentPosition();
},
//
// end moving of handle
//
endOfHandleMove: function(ev){
// remove handle events (which were attached in the startOfHandleMove-method)
$(document).unbind('.handle');
// remove class for visual change
this.handle.removeClass('move');
this.handleContainer.removeClass('move');
},
//
// set position of handle
//
setHandlePosition: function(){
// stay within range [handleTop.min, handleTop.max]
this.handle.top = (this.handle.top > this.props.handleTop.max) ? this.props.handleTop.max : this.handle.top;
this.handle.top = (this.handle.top < this.props.handleTop.min) ? this.props.handleTop.min : this.handle.top;
this.handle[0].style.top = this.handle.top + 'px';
},
//
// set position of content
//
setContentPosition: function(){
// derive position of content from position of handle
this.pane.top = -1 * this.props.handleContentRatio * this.handle.top;
// var distance = Math.round(Math.abs(this.pane_last_top - this.pane.top));
// $(this.pane[0]).stop().animate({top: this.pane.top}, 10 * distance / Math.sqrt(distance));
this.pane[0].style.top = this.pane.top + 'px';
this.pane_last_top = this.pane.top;
},
//
// mouse wheel movement
//
onMouseWheel: function(ev, delta){
// calculate new handle position
this.handle.top -= delta*15; // awfull fix
this.setHandlePosition();
this.setContentPosition();
// prevent default scrolling of the entire document if handle is within [min, max]-range
if(this.handle.top > this.props.handleTop.min && this.handle.top < this.props.handleTop.max){
ev.preventDefault();
}
},
//
// append click handler on handle-container (outside of handle itself) to click up and down the handle
//
onHandleContainerMousedown: function(ev){
ev.preventDefault();
// do nothing if clicked on handle
if(!$(ev.target).hasClass('scrollbar-handle-container')){
return false;
}
// determine direction for handle movement (clicked above or below the handler?)
this.handle.direction = (this.handle.offset().top < this.mousePosition(ev)) ? 1 : -1;
// set incremental step of handle
this.handle.step = this.opts.scrollStep;
// stop handle movement on mouseup
var that = this;
$(document).bind('mouseup.handlecontainer', function(){
clearInterval(timer);
that.handle.unbind('mouseenter.handlecontainer');
$(document).unbind('mouseup.handlecontainer');
});
// stop handle movement when mouse is over handle
//
// TODO: this event is fired by Firefox only. Damn!
// Right now, I do not know any workaround for this. Mayby I should solve this by collision-calculation of mousepointer and handle
this.handle.bind('mouseenter.handlecontainer', function(){
clearInterval(timer);
});
// repeat handle movement while mousedown
var timer = setInterval($.proxy(this.moveHandle, this), this.opts.scrollSpeed);
},
//
// append mousedown handler on handle-arrows
//
onArrowsMousedown: function(ev){
ev.preventDefault();
// determine direction for handle movement
this.handle.direction = $(ev.target).hasClass('scrollbar-handle-up') ? -1 : 1;
// set incremental step of handle
this.handle.step = this.opts.scrollStepArrows;
// add class for visual change while moving handle
$(ev.target).addClass('move');
// repeat handle movement while mousedown
var timer = setInterval($.proxy(this.moveHandle, this), this.opts.scrollSpeedArrows);
// stop handle movement on mouseup
$(document).one('mouseup.arrows', function(){
clearInterval(timer);
$(ev.target).removeClass('move');
});
},
//
// move handle by a distinct step while click on arrows or handle-container
//
moveHandle: function(){
this.handle.top = (this.handle.direction === 1) ? Math.min(this.handle.top + this.handle.step, this.props.handleTop.max) : Math.max(this.handle.top - this.handle.step, this.props.handleTop.min);
this.handle[0].style.top = this.handle.top + 'px';
this.setContentPosition();
},
//
// add class attribute on content while interacting with content
//
onContentHover: function(ev){
if(ev.type === 'mouseenter'){
this.container.addClass('hover');
this.handleContainer.addClass('hover');
} else {
this.container.removeClass('hover');
this.handleContainer.removeClass('hover');
}
},
//
// add class attribute on handle-container while hovering it
//
onHandleContainerHover: function(ev){
if(ev.type === 'mouseenter'){
this.handleArrows.addClass('hover');
} else {
this.handleArrows.removeClass('hover');
}
},
//
// do not bubble down to avoid triggering click events attached within the container
//
preventClickBubbling: function(ev){
ev.stopPropagation();
}
};
// ----- helpers ------------------------------------------------------------------------------
//
// determine content height
//
$.fn.scrollbar.contentHeight = function(elem){
// clone and wrap content temporarily and meassure content height within the original context.
// wrapper container need to have an overflow set to 'hidden' to respect margin collapsing
// TODO: analyse anlternative which does not require an additional container. a clone may also allow to meassure a non visible element.
/*
var clone = elem.clone().wrapInner('<div/>').find(':first-child');
elem.append(clone);
var height = clone.css({overflow:'hidden'}).height();
clone.remove();
return height;
*/
var content = elem.wrapInner('<div/>');
var height = elem.find(':first').css({overflow:'hidden'}).height();
return height;
// FIXME: manipulating the DOM is not the resposibility of $.fn.scrollbar.contentHeight()
};
//
// ----- default css ---------------------------------------------------------------------
//
$.fn.defaultCss = function(styles){
// 'not-defined'-values
var notdef = {
'right': 'auto',
'left': 'auto',
'top': 'auto',
'bottom': 'auto',
'position': 'static'
};
// loop through all style definitions and check for a definition already set by css.
// if no definition is found, apply the default css definition
return this.each(function(){
var elem = $(this);
for(var style in styles){
if(elem.css(style) === notdef[style]){
elem.css(style, styles[style]);
}
}
});
};
//
// ----- mousewheel event ---------------------------------------------------------------------
// based on jquery.mousewheel.js from Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
//
$.event.special.mousewheel = {
setup: function(){
if (this.addEventListener){
this.addEventListener('mousewheel', $.fn.scrollbar.mouseWheelHandler, false);
this.addEventListener('DOMMouseScroll', $.fn.scrollbar.mouseWheelHandler, false);
} else {
this.onmousewheel = $.fn.scrollbar.mouseWheelHandler;
}
},
teardown: function(){
if (this.removeEventListener){
this.removeEventListener('mousewheel', $.fn.scrollbar.mouseWheelHandler, false);
this.removeEventListener('DOMMouseScroll', $.fn.scrollbar.mouseWheelHandler, false);
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn){
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn){
return this.unbind("mousewheel", fn);
}
});
$.fn.scrollbar.mouseWheelHandler = function(event) {
var orgEvent = event || window.event,
args = [].slice.call(arguments, 1),
delta = 0,
returnValue = true,
deltaX = 0,
deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if(event.wheelDelta){
delta = event.wheelDelta / 120;
}
if(event.detail){
delta = -event.detail / 3;
}
// Gecko
if(orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS){
deltaY = 0;
deltaX = -1 * delta;
}
// Webkit
if(orgEvent.wheelDeltaY !== undefined){
deltaY = orgEvent.wheelDeltaY / 120;
}
if(orgEvent.wheelDeltaX !== undefined){
deltaX = -1 * orgEvent.wheelDeltaX / 120;
}
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return $.event.handle.apply(this, args);
};
})(jQuery, document); // inject global jQuery object
+80
View File
@@ -0,0 +1,80 @@
window._locale =
# Global
SEARCH:
en: "Search"
ru: "Поиск"
NEWS:
en: "News"
ru: "Новости"
ABOUT:
en: "About"
ru: "О проекте"
LOGIN:
en: "Log in"
ru: "Войти"
LOGOUT:
en: "Log out"
ru: "Выйти"
ADD_SOME_MUSIC:
en: "Add some music to playlist"
ru: "Добавьте музыку в плей-лист"
LOGIN_PLEASE:
en: "Don't forget to log in, please. It's simple."
ru: "Авторизуйтесь, пожалуйста. Это действительно просто."
REPEAT:
en: "Repeat"
ru: "Повторять"
SHUFFLE:
en: "Shuffle"
ru: "Перемешать"
EMPTY_PLAYLIST:
en: "Empty playlist"
ru: "Очистить"
HELLO:
en: "Hi there"
ru: "Привет"
# Search
ARTIST_LOADING_FAILED:
en: "Something very bad happened while we tried out to load some info about this artist. How about some other one?"
ru: "Что-то ужасное произошло пока мы собирали информацию об этом исполнителе. Может пока поищем другого?"
ARTIST_LOADING_IN_PROCESS:
en: "Artist info is loading for the first time now. Usually it takes less than a minute, please wait a bit."
ru: "Прямо сейчас мы собираем всю возможною информацию об этом исполнителе в первый раз. Обычно это занимает меньше минуты."
MISSPELLED:
en: "Misspelled?"
ru: "Опечатались?"
# Settings
SETTINGS_ACCOUNT:
en: "Account"
ru: "Аккаунт"
SETTINGS_LASTFM:
en: "Last.fm"
ru: "Last.fm"
USERNAME:
en: "Username"
ru: "Имя"
EMAIL:
en: "Email"
ru: "Почта"
LANG:
en: "Language"
ru: "Язык"
USELESS_BUTTON:
en: "Hello, my name is Useless Button"
ru: "Привет, меня зовут Бесполезная Кнопка"
NOT_CONNECTED:
en: "Not connected"
ru: "Не подключен"
CONNECT:
en: "Connect"
ru: "Подключить"
WINDOW_LANG_RELOAD:
en: "To change application language it is needed to reload page. Your current playlist will be emptied and music will stop. Do you really wish to continue?"
ru: "Чтобы изменить язык приложения, необходимо перезагрузить страницу. Ваш текущий плей-лист будет очищен и музыка остановится. Вы действительно хотите продолжить?"
# Player
ADD_TO_NOW_PLAYING:
en: "Add to Now Playing"
ru: "Добавить в плей-лист"
+91
View File
@@ -0,0 +1,91 @@
class window.Pages
renderArtist: (data) ->
artist_info = $ '
<div class="artist-info">
<div class="pic">
<img src="' +data.artist.pic+ '" alt="' +data.artist.name+ '" width="250" />
</div>
<h1 class="name" data-id="'+data.artist.id+'">' +data.artist.name+ '</h1>
<div class="info">
' +data.artist.desc+ '
</div>
</div>'
albums_info = $ '<div class="albums"></div>'
$.each data.albums, (i, album) ->
if album.year?
album_info = $ '
<div class="album">
<h2 class="name" data-id="'+album.id+'">' +album.name+ ' (' +album.year+ ')</h2>
<div class="pic">
<img src="' +(if album.pic then album.pic else '/images/kitteh.png')+ '" alt="' +album.name+ ' by ' +data.artist.name+ '" width="250" height="250"/>
<div class="add-album-button-container">
<div class="add-album button gray">'+_beathaven.ls('ADD_TO_NOW_PLAYING')+'</div>
</div>
</div>
<div class="tracklist"><ul></ul></div>
</div>
<div class="kaboom"></div>'
$.each album.tracks.album, (i, track) ->
track_info = $ '
<li data-id="'+track.id+'">
<div class="add-track button gray">+</div>
<div class="track-container">
<div class="fade"></div>
<span class="index">' +(i+1)+ '</span>
<div class="trackname" title="' +track.name.htmlsafe()+ '">' +track.name+ '</div>
<div class="length">' +track.duration+ '</div>
</div>
</li>'
$(album_info).find('.tracklist ul').append(track_info)
$(albums_info).append(album_info)
$('.data-container').css backgroundImage: 'none'
$('.data-container .inner').html('').append(artist_info).append(albums_info)
yaCounter7596904.hit _ajax.getAnchor(), data.artist.name, _ajax.referer
_ajax.setTitle data.artist.name
_beathaven.redrawScrollbar()
false
renderSearch: (data) ->
$('.pulldown').html data
setTimeout ->
$('.search_field').first().bh_autocomplete
serviceUrl: '/artist/autocomplete' # Страница для обработки запросов автозаполнения
minChars: 2 # Минимальная длина запроса для срабатывания автозаполнения
delimiter: /(,|;)\s*/ # Разделитель для нескольких запросов, символ или регулярное выражение
maxHeight: 400 # Максимальная высота списка подсказок, в пикселях
width: 415 # Ширина списка
zIndex: 9999 # z-index списка
deferRequestBy: 500 # Задержка запроса (мсек)
onSelect: ->
_ajax.loadArtistData $('.search_field').first().val()
$('.search_field').first().focus()
, 1
false
renderSettings: (data) ->
unless _session.getUser().id?
_ajax.go('/search/')
return false
$('.data-container').css background: 'none'
$('.data-container .inner').html data
yaCounter7596904.hit _ajax.getAnchor(), 'Settings', _ajax.referer
_ajax.setTitle 'Settings'
$('.settings-container .tabs .tab').first().trigger 'click'
false
renderTextpage: (data) ->
$('.data-container').css background: 'url(/images/concrete_wall_2.png) 0 -30px repeat'
$('.data-container .inner').html data
_beathaven.redrawScrollbar()
false
$('.about').live 'click', ->
_ajax.go '/about/'
false
+259
View File
@@ -0,0 +1,259 @@
class window.Player
bar_width: 330
jp: null
scrobbled: false
initJplayer: ->
self = this
@jp = $("#jplayer")
@jp.jPlayer
swfPath: "/js"
supplied: "mp3"
cssSelectorAncestor: ""
cssSelector:
play: ".player .play"
pause: ".player .pause"
stop: ""
videoPlay: ""
seekBar: ""
playBar: ""
mute: ""
unmute: ""
volumeBar: ""
volumeBarValue: ""
currentTime: ""
duration: ""
@jp.bind $.jPlayer.event.timeupdate, (e) ->
data = e.jPlayer.status
if not _player.scrobbled and data.currentPercentAbsolute > 50
$obj = $('.playlist-tracks li.now')
self.scrobble $obj.attr('data-artist'), $obj.attr('data-album'), $obj.attr('data-track')
_player.scrobbled = true
$('.player .progress .loaded').width(data.seekPercent * self.bar_width / 100)
$('.player .progress .played').width(data.currentPercentAbsolute * self.bar_width / 100)
@jp.bind $.jPlayer.event.ended, (e) ->
next = self.nextTrack()
if not next
$('#jplayer').jPlayer 'clearMedia'
$('.player .now-playing').html 'Nothing left to <strike>lose</strike> play'
$('.player .loaded, .player .played').width 0
$('.playlist-tracks li').removeClass 'now'
else
self.setTrack next
false
addTracks: (tracks, autoplay) ->
if not autoplay?
autoplay = false
initial_count = $('.playlist-tracks li').length
for item in tracks
$('.playlist-tracks').append '
<li id="i' +Math.round(Math.random() * 999999)+ '" data-id="'+item.id+'" data-artist="'+item.artist.trim()+'" data-album="'+item.album.trim()+'" data-track="'+item.name.trim()+'" data-length="'+item.length+'">
<div class="item">
<div class="fade"></div>
<div class="dragbox"></div>
<span class="title">
<span class="data artist" title="Open ' +item.artist.htmlsafe()+ '\'s page">' +item.artist+ '</span>
&mdash;
<span class="playtrack" title="Play ' +item.name.htmlsafe()+ ' by ' +item.artist.htmlsafe()+ '">' +item.name+ '</span>
</span>
<span class="duration">' +item.length+ '</span>
<div class="remove">remove</div>
</div>
</li>'
$('.playlist').html($('.playlist-tracks')).scrollbar()
$('.playlist-tracks').sortable axis: 'y', handle: '.dragbox'
if autoplay
_player.setTrack($('.playlist-tracks li').last().attr('id').split('i')[1])
else if initial_count == 0 and not _player.hasTrack()
_player.setTrack($('.playlist-tracks li').first().attr('id').split('i')[1])
false
getDataFromLi: (obj) ->
id = $(obj).attr 'data-id'
track_name = $(obj).find('.trackname').html()
length = $(obj).find('.length').html()
id: id, name: track_name, length: length
setTrack: (id) ->
$obj = $('#i' +id)
query = $obj.attr('data-artist')+ ' &mdash; ' +$obj.attr('data-track')
$('.player .loaded, .player .played').width 0
$('.player .now-playing').html query+'<div class="fade"></div>'
$('.playlist-tracks li').removeClass 'now'
$obj.addClass 'now'
$('.tracklist li').removeClass 'now'
$('.tracklist li[data-id="'+$obj.attr('data-id')+'"]').addClass 'now'
_vkontakte.loadTracksData $obj.attr('data-artist'), $obj.attr('data-track'), $obj.attr('data-length'), (url) ->
_player.playSource url
this.updateNowListening $obj.attr('data-artist'), $obj.attr('data-album'), $obj.attr('data-track')
false
hasTrack: ->
if $('#jplayer audio').length > 0
return $('#jplayer audio').attr('src')? and $('#jplayer audio').attr('src') != ''
else if $('#jplayer object').length > 0
$('#jplayer').jPlayer 'play'
true
false
playSource: (url) ->
@scrobbled = false
$('#jplayer').jPlayer 'setMedia', mp3: url
$('#jplayer').jPlayer 'play'
false
nextTrack: (manual) ->
manual = manual?
cnt = $('.playlist-tracks li').length
if not this.onShuffle() # Shuffle off
if $('.playlist-tracks .now').next().length == 0 # Last track and repeat is on
if _player.onRepeat() or manual # Repeat or manual click
return $('.playlist-tracks li').first().attr('id').split('i')[1]
else
false
else
return $('.playlist-tracks .now').next().attr('id').split('i')[1]
else if cnt == 1 # Single track in the playlist
return $('.playlist-tracks li').first().attr('id').split('i')[1]
else # Shuffle on
while true
rnd = Math.floor(Math.random() * (cnt + .999))
$li = $('.playlist-tracks li').eq rnd
if $li.length > 0 and not $li.hasClass 'now'
return $li.attr('id').split('i')[1]
false
prevTrack: ->
cnt = $('.playlist-tracks li').length
if not _player.onShuffle() # Shuffle off
if $('.playlist-tracks .now').prev().length == 0 # First track in the playlist
return $('.playlist-tracks li').last().attr('id').split('i')[1]
else
return $('.playlist-tracks .now').prev().attr('id').split('i')[1]
else if cnt == 1 # Single track in the playlist
return $('.playlist-tracks li').first().attr('id').split('i')[1]
else # Shuffle on
while true
rnd = Math.floor(Math.random() * (cnt + .999))
$li = $('.playlist-tracks li').eq rnd
if $li.length > 0 and not $li.hasClass 'now'
return $li.attr('id').split('i')[1]
false
onShuffle: ->
return $('#shuffle').hasClass 'active'
onRepeat: ->
return $('#repeat').hasClass 'active'
updateNowListening: (artist, album, track) ->
if _session.getUser().lastfm_username
_session.query '/lastfm/listening?r=' +Math.random(), artist: artist, album: album, track: track
false
scrobble: (artist, album, track) ->
if _session.getUser().lastfm_username
_session.query '/lastfm/scrobble?r=' +Math.random(), artist: artist, album: album, track: track
false
# Player Controls
$('.player .controls .prev').live 'click', ->
_player.setTrack _player.prevTrack()
false
$('.player .controls .next').live 'click', ->
_player.setTrack _player.nextTrack(true)
false
$('.player .play').live 'click', ->
if $('.playlist-tracks li').length > 0 and not _player.hasTrack()
_player.setTrack $('.playlist-tracks li').first().attr('id').split('i')[1]
false
$('.player .progress').live 'click', (e) ->
$('#jplayer').jPlayer 'playHead', Math.round((e.offsetX / _player.bar_width) * 100)
false
# Player Additional Controls
$('#repeat, #shuffle').live 'click', ->
$(this).toggleClass 'active'
false
$('#empty-playlist').live 'click', ->
if confirm('Are you sure?')
$('.playlist-tracks li').remove()
$('#jplayer').jPlayer 'clearMedia'
$('.player .now-playing').text 'Add some music to playlist'
$('.player .loaded, .player .played').width 0
false
# Playlist Actions
$('.playlist-tracks li .fade, .playlist-tracks li .duration, .playlist-tracks li .remove').live 'mousemove mouseover mouseout', (e) ->
if e.type in ['mouseover', 'mousemove'] and ($(window).width() - e.clientX) < 60
$(this).parent().find('.duration').hide()
$(this).parent().find('.remove').show()
else
$(this).parent().find('.remove').hide()
$(this).parent().find('.duration').show()
false
$('.playlist-tracks li .remove').live 'click', ->
$li = $(this).parent().parent()
if $li.hasClass 'now'
$('#jplayer').jPlayer 'clearMedia'
$('.player .now-playing').text '...'
$('.player .loaded, .player .played').width 0
$li.remove()
false
$('.playlist-tracks li .title .playtrack').live 'click', ->
_player.setTrack $(this).parent().parent().parent().attr('id').split('i')[1]
false
# Adding To Playlist actions
$('.add-album').live 'click', ->
artist = $('.artist-info .name').html()
album = $(this).parent().parent().parent().find('h2.name').text().replace /\s\([\d]{4}\)$/, ''
tracks = []
for item in $(this).parent().parent().parent().find('.tracklist li')
track = _player.getDataFromLi item
track['artist'] = artist
track['album'] = album
tracks.push track
_player.addTracks tracks
false
$('.add-track').live 'click', ->
track = _player.getDataFromLi $(this).parent()
track['artist'] = $('.artist-info .name').html()
track['album'] = $(this).parent().parent().parent().parent().find('h2.name').text().replace /\s\([\d]{4}\)$/, ''
_player.addTracks [track]
false
$('.tracklist li').live 'mouseover mouseout', (e) ->
if e.type == 'mouseover'
$(this).find('.add-track').show()
else
$(this).find('.add-track').hide()
false
$('.tracklist li').live 'click', (e) ->
track = _player.getDataFromLi this
track['artist'] = $('.artist-info .name').html()
track['album'] = $(this).parent().parent().parent().find('h2.name').text().replace /\s\([\d]{4}\)$/, ''
_player.addTracks [track], true
false
+75
View File
@@ -0,0 +1,75 @@
class window.Search
pics: []
showSpinner: ->
$('.search-container input').first().attr(disabled: 'disabled').blur()
$('.search-container img').first().show()
$('.autocomplete-container').hide()
$('.artist_loading.failed').first().hide()
this.hideSuggestions()
false
hideSpinner: ->
$('.search-container input').first().removeAttr 'disabled'
$('.search_field').first().focus()
$('.search-container img').first().hide()
false
showSuggestions: (values) ->
for item in values
$('.suggestions ul').append '
<li>
<a class="data artist">' +item.name+ '</a>
' +(if item.desc? then '<br/><span>'+item.desc+'</span>' else '')+ '
</li>'
$('.suggestions').show()
false
hideSuggestions: ->
$('.suggestions ul li').remove()
$('.suggestions').hide()
false
showArtistPics: (pics) ->
$('.artist_loading.ok, .artist_pics').show()
for pic in pics
if @pics.indexOf(pic) == -1
@pics.push(pic);
$('.artist_pics').append '
<div class="pic">
<img src="' +pic+ '" alt=""/>
</div>'
false
showError: ->
$('.artist_loading.ok, .artist_pics').hide()
$('.artist_loading.failed').show()
@pics = []
$('.search').live 'click', ->
if $('.pulldown').css('display') is 'none'
$('.pulldown').width $('.data-container').width() - 50
$('.pulldown').height 300#38
$('.pulldown').slideDown 'fast', ->
data = '<div class="search-container">'+$('.subpages .search-container').html()+'</div>'
_pages.renderSearch _beathaven.localizeHTML $(data)
_beathaven.adjustSizes()
_beathaven.redrawScrollbar()
else
$('.pulldown').slideUp 'fast', ->
$('.pulldown').height 0
_beathaven.adjustSizes()
_beathaven.redrawScrollbar()
false
$('.search_form').live 'submit', ->
$('.autocomplete-container').remove()
_ajax.loadArtistData $('.search_field').first().val()
false
$('.suggestions a').live 'click', ->
$('.search_field').first().val $(this).text()
false
$('.data.artist').live 'click', ->
_ajax.go('/artist/'+$(this).text().replace(' ', '+')+'/');
false;
+32
View File
@@ -0,0 +1,32 @@
class window.Session
vk_params: null
user: null
constructor: (params) ->
attrs = ['expire', 'mid', 'secret', 'sid', 'sig']
_params = {}
for key in attrs
if params[key]?
_params[key] = params[key]
@vk_params = _params
setUser: (user) ->
@user = user
_beathaven.lang = @user.lang || 'ru'
_beathaven.localizeHTML()
false
getUser: ->
@user
query: (url, params, callback) ->
q_params = $.extend {}, @vk_params, params
$.post url, q_params, callback
false
reloadSession: ->
_session.query '/user/auth', {}, (ar) ->
_session.setUser ar.user
false
false
+64
View File
@@ -0,0 +1,64 @@
class window.Settings
getAccountInfo: (callback) ->
_session.query '/user/update/', {}, callback
false
saveAccountInfo: (params, callback) ->
_session.query '/user/update', params, callback
false
loadFormData: (form) ->
if form == 'account'
$('.settings-container .form input[name$="username"]').val _session.getUser().name
$('.settings-container .form input[name$="email"]').val _session.getUser().email
$('.settings-container .form select').val _session.getUser().lang
else if form == 'lastfm'
if _session.getUser().lastfm_username
$('.form-container input[name$="username"]').first().val _session.getUser().lastfm_username
false
updateLastfmLogin: ->
if window.lastfm_popup.closed
_session.query '/user/auth', {}, (ar) ->
_session.setUser ar.user
_settings.loadFormData 'lastfm'
else
setTimeout _settings.updateLastfmLogin, 100
false
$('.settings') .live 'click', ->
_ajax.go('/settings/');
false
$('.settings-container .tabs .tab').live 'click', ->
if not $(this).hasClass 'active'
$('.settings-container .tabs .tab').removeClass 'active'
$(this).addClass 'active'
$('.form-container').html $('.forms .'+ $(this).attr 'data-fieldset').html()
_settings.loadFormData $(this).attr 'data-fieldset'
false
$('.lastfm-connect') .live 'click', ->
window.lastfm_popup = window.open _session.getUser().lastfm_login_url
setTimeout _settings.updateLastfmLogin, 100
false
$('.settings-container .form input, .settings-container .form select').live 'blur', ->
active_tab = $('.settings-container .tabs .tab.active').attr 'data-fieldset'
if active_tab == 'account'
params =
username: $('.settings-container .form input[name$="username"]').first().val()
email: $('.settings-container .form input[name$="email"]').first().val()
lang: $('.settings-container .form select').first().val()
lang_changed = params.lang != _session.getUser().lang
if lang_changed
if not confirm _beathaven.ls 'WINDOW_LANG_RELOAD', params.lang
$('.settings-container .form select').val _session.getUser().lang
_settings.saveAccountInfo params, ->
if lang_changed
window.location.reload()
$('.header-container .hello .greating span').text (if params.username.length > 0 then params.username else '%username%')
false
false
+143
View File
@@ -0,0 +1,143 @@
class window.Vkontakte
qr: null
api_id: null
constructor: (@api_id) ->
getApiId: ->
@api_id
init: ->
@qr = []
window.vkAsyncInit = ->
VK.init apiId: _vkontakte.getApiId()
VK.Auth.getLoginStatus (response) ->
_vkontakte.authInfo(response)
setTimeout ->
$('#vk_api_transport').append('<script async="async" type="text/javascript" src="http://vkontakte.ru/js/api/openapi.js"></script>')
, 0
authInfo: (response) ->
if typeof response isnt 'undefined' and response.session
_session = new Session(response.session)
$('#vk_login, .auth-notice').hide()
$('#vk_logout').css display: 'block'
$('#search_field').focus() if $('#search_field').length > 0
_session.query '/user/auth', {}, (ar) ->
if ar.newbie
VK.Api.call 'getVariable', key: 1281, (r) ->
_session.query '/user/update', name: r.response, (ar2) ->
_session.setUser ar2.user
$('.header-container .hello .greating')
.html _beathaven.ls('HELLO')+', <span class="settings">' +(if _session.getUser().name then _session.getUser().name else '%username%')+ '</span>!'
window._session = _session
_ajax.detectPage()
$('.fullscreen').hide();
else
_session.setUser ar.user
$('.header-container .hello').show()
$('.header-container .hello .greating')
.html _beathaven.ls('HELLO')+', <span class="settings">' +(if _session.getUser().name then _session.getUser().name else '%username%')+ '</span>!'
window._session = _session
_ajax.detectPage()
$('.fullscreen').hide();
if response.session.expire?
setTimeout ->
_vkontakte.auth()
false
, response.session.expire * 1000 - new Date().getTime() + 1000
else
_session = new Session({})
_session.setUser {}
$('#vk_login').css display: 'block'
$('.auth-notice').css('left', $('#vk_login').offset().left).show()
$('.header-container .hello').hide()
window._session = _session
_ajax.detectPage()
$('.fullscreen').hide();
auth: ->
VK.Auth.getLoginStatus (response) ->
_vkontakte.authInfo(response)
false
, 8
false
loadTracksData: (artist, track, duration, callback) ->
track_prepared = track.replace(/\(.*\)/i, '').split('/')[0];
query = artist+' '+track_prepared;
if url = _vkontakte.getQR query
callback url
else
VK.Api.call 'audio.search', q: query, (r) ->
url = _vkontakte.matchPerfectResult r.response, artist, track, duration
_vkontakte.addQR query, url
callback url
matchPerfectResult: (data, artist, track, duration) ->
duration = duration.split ':'
duration = parseInt(duration[0], 10) * 60 + parseInt(duration[1], 10)
best_score = 0;
best_result = null;
for item in data
if typeof item is 'object'
score = 0;
item.artist = item.artist.trim();
item.title = item.title.trim();
if item.artist == artist
score += 10
else if item.artist.split(artist).length is 2
score += 5
else if item.title.split(artist).length is 2
score += 4
if item.title == track
score += 10
else if item.title.split(track).length is 2
score += 5
if parseInt(item.duration, 10) == duration
score += 15
else
delta = Math.abs parseInt(item.duration, 10) - duration
score += (10 - delta) if delta < 10
if score > best_score
best_score = score
best_result = item
if score is 35
return best_result.url
return best_result.url
addQR: (query, url) ->
@qr[query] = url;
getQR: (query) ->
if @qr[query]?
@qr[query]
false
$('#vk_login, .auth-notice').live 'click', ->
VK.Auth.login (response) ->
_vkontakte.authInfo(response)
false
, 8
false
$('#vk_logout').live 'click', ->
_ajax.go '/search/';
VK.Auth.logout (response) ->
_vkontakte.authInfo(response)
false
false