1
0
mirror of https://gitee.com/coder-xiaomo/flashsale synced 2025-09-12 15:01:39 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee

添加Metronic(作为LFS)

This commit is contained in:
2022-03-01 21:24:58 +08:00
parent 080ca33954
commit 465c454101
3280 changed files with 561969 additions and 0 deletions

View File

@@ -0,0 +1,222 @@
jQuery.extend({
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error )
s.error( xhr, status, e );
// If we have some XML response text (e.g. from an AJAX call) then log it in the console
else if(xhr.responseText)
console.log(xhr.responseText);
},
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone(true);
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" ){
data = r.responseText;
var start = data.indexOf(">");
if(start != -1) {
var end = data.indexOf("<", start + 1);
if(end != -1) {
data = data.substring(start + 1, end);
}
}
eval( "data = " + data );
//data = jQuery.parseJSON(jQuery(data).text());
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
}
})

View File

@@ -0,0 +1,12 @@
/**
* @preserve
* Project: Bootstrap Hover Dropdown
* Author: Cameron Spear
* Version: v2.2.1
* Contributors: Mattia Larentis
* Dependencies: Bootstrap's Dropdown plugin, jQuery
* Description: A simple plugin to enable Bootstrap dropdowns to active on hover and provide a nice user experience.
* License: MIT
* Homepage: http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/
*/
!function(e,n){var o=e();e.fn.dropdownHover=function(t){return"ontouchstart"in document?this:(o=o.add(this.parent()),this.each(function(){function r(){d.parents(".navbar").find(".navbar-toggle").is(":visible")||(n.clearTimeout(a),n.clearTimeout(i),i=n.setTimeout(function(){o.find(":focus").blur(),v.instantlyCloseOthers===!0&&o.removeClass("open"),n.clearTimeout(i),d.attr("aria-expanded","true"),s.addClass("open"),d.trigger(h)},v.hoverDelay))}var a,i,d=e(this),s=d.parent(),u={delay:500,hoverDelay:0,instantlyCloseOthers:!0},l={delay:e(this).data("delay"),hoverDelay:e(this).data("hover-delay"),instantlyCloseOthers:e(this).data("close-others")},h="show.bs.dropdown",c="hide.bs.dropdown",v=e.extend(!0,{},u,t,l);s.hover(function(e){return s.hasClass("open")||d.is(e.target)?void r(e):!0},function(){n.clearTimeout(i),a=n.setTimeout(function(){d.attr("aria-expanded","false"),s.removeClass("open"),d.trigger(c)},v.delay)}),d.hover(function(e){return s.hasClass("open")||s.is(e.target)?void r(e):!0}),s.find(".dropdown-submenu").each(function(){var o,t=e(this);t.hover(function(){n.clearTimeout(o),t.children(".dropdown-menu").show(),t.siblings().children(".dropdown-menu").hide()},function(){var e=t.children(".dropdown-menu");o=n.setTimeout(function(){e.hide()},v.delay)})})}))},e(document).ready(function(){e('[data-hover="dropdown"]').dropdownHover()})}(jQuery,window);

378
frontend/static/js/bootstrap-modal.js vendored Normal file
View File

@@ -0,0 +1,378 @@
/* ===========================================================
* bootstrap-modal.js v2.2.5
* ===========================================================
* Copyright 2012 Jordan Schroter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* MODAL CLASS DEFINITION
* ====================== */
var Modal = function (element, options) {
this.init(element, options);
};
Modal.prototype = {
constructor: Modal,
init: function (element, options) {
var that = this;
this.options = options;
this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this));
this.options.remote && this.$element.find('.modal-body').load(this.options.remote, function () {
var e = $.Event('loaded');
that.$element.trigger(e);
});
var manager = typeof this.options.manager === 'function' ?
this.options.manager.call(this) : this.options.manager;
manager = manager.appendModal ?
manager : $(manager).modalmanager().data('modalmanager');
manager.appendModal(this);
},
toggle: function () {
return this[!this.isShown ? 'show' : 'hide']();
},
show: function () {
var e = $.Event('show');
if (this.isShown) return;
this.$element.trigger(e);
if (e.isDefaultPrevented()) return;
this.escape();
this.tab();
this.options.loading && this.loading();
},
hide: function (e) {
e && e.preventDefault();
e = $.Event('hide');
this.$element.trigger(e);
if (!this.isShown || e.isDefaultPrevented()) return;
this.isShown = false;
this.escape();
this.tab();
this.isLoading && this.loading();
$(document).off('focusin.modal');
this.$element
.removeClass('in')
.removeClass('animated')
.removeClass(this.options.attentionAnimation)
.removeClass('modal-overflow')
.attr('aria-hidden', true);
$.support.transition && this.$element.hasClass('fade') ?
this.hideWithTransition() :
this.hideModal();
},
layout: function () {
var prop = this.options.height ? 'height' : 'max-height',
value = this.options.height || this.options.maxHeight;
if (this.options.width){
this.$element.css('width', this.options.width);
var that = this;
this.$element.css('margin-left', function () {
if (/%/ig.test(that.options.width)){
return -(parseInt(that.options.width) / 2) + '%';
} else {
return -($(this).width() / 2) + 'px';
}
});
} else {
this.$element.css('width', '');
this.$element.css('margin-left', '');
}
this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');
if (value){
this.$element.find('.modal-body')
.css('overflow', 'auto')
.css(prop, value);
}
var modalOverflow = $(window).height() - 10 < this.$element.height();
if (modalOverflow || this.options.modalOverflow) {
this.$element
.css('margin-top', 0)
.addClass('modal-overflow');
} else {
this.$element
.css('margin-top', 0 - this.$element.height() / 2)
.removeClass('modal-overflow');
}
},
tab: function () {
var that = this;
if (this.isShown && this.options.consumeTab) {
this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) {
if (e.keyCode && e.keyCode == 9){
var elements = [],
tabindex = Number($(this).data('tabindex'));
that.$element.find('[data-tabindex]:enabled:visible:not([readonly])').each(function (ev) {
elements.push(Number($(this).data('tabindex')));
});
elements.sort(function(a,b){return a-b});
var arrayPos = $.inArray(tabindex, elements);
if (!e.shiftKey){
arrayPos < elements.length-1 ?
that.$element.find('[data-tabindex='+elements[arrayPos+1]+']').focus() :
that.$element.find('[data-tabindex='+elements[0]+']').focus();
} else {
arrayPos == 0 ?
that.$element.find('[data-tabindex='+elements[elements.length-1]+']').focus() :
that.$element.find('[data-tabindex='+elements[arrayPos-1]+']').focus();
}
e.preventDefault();
}
});
} else if (!this.isShown) {
this.$element.off('keydown.tabindex.modal');
}
},
escape: function () {
var that = this;
if (this.isShown && this.options.keyboard) {
if (!this.$element.attr('tabindex')) this.$element.attr('tabindex', -1);
this.$element.on('keyup.dismiss.modal', function (e) {
e.which == 27 && that.hide();
});
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
},
hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end);
that.hideModal();
}, 500);
this.$element.one($.support.transition.end, function () {
clearTimeout(timeout);
that.hideModal();
});
},
hideModal: function () {
var prop = this.options.height ? 'height' : 'max-height';
var value = this.options.height || this.options.maxHeight;
if (value){
this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');
}
this.$element
.hide()
.trigger('hidden');
},
removeLoading: function () {
this.$loading.remove();
this.$loading = null;
this.isLoading = false;
},
loading: function (callback) {
callback = callback || function () {};
var animate = this.$element.hasClass('fade') ? 'fade' : '';
if (!this.isLoading) {
var doAnimate = $.support.transition && animate;
this.$loading = $('<div class="loading-mask ' + animate + '">')
.append(this.options.spinner)
.appendTo(this.$element);
if (doAnimate) this.$loading[0].offsetWidth; // force reflow
this.$loading.addClass('in');
this.isLoading = true;
doAnimate ?
this.$loading.one($.support.transition.end, callback) :
callback();
} else if (this.isLoading && this.$loading) {
this.$loading.removeClass('in');
var that = this;
$.support.transition && this.$element.hasClass('fade')?
this.$loading.one($.support.transition.end, function () { that.removeLoading() }) :
that.removeLoading();
} else if (callback) {
callback(this.isLoading);
}
},
focus: function () {
var $focusElem = this.$element.find(this.options.focusOn);
$focusElem = $focusElem.length ? $focusElem : this.$element;
$focusElem.focus();
},
attention: function (){
// NOTE: transitionEnd with keyframes causes odd behaviour
if (this.options.attentionAnimation){
this.$element
.removeClass('animated')
.removeClass(this.options.attentionAnimation);
var that = this;
setTimeout(function () {
that.$element
.addClass('animated')
.addClass(that.options.attentionAnimation);
}, 0);
}
this.focus();
},
destroy: function () {
var e = $.Event('destroy');
this.$element.trigger(e);
if (e.isDefaultPrevented()) return;
this.$element
.off('.modal')
.removeData('modal')
.removeClass('in')
.attr('aria-hidden', true);
if (this.$parent !== this.$element.parent()) {
this.$element.appendTo(this.$parent);
} else if (!this.$parent.length) {
// modal is not part of the DOM so remove it.
this.$element.remove();
this.$element = null;
}
this.$element.trigger('destroyed');
}
};
/* MODAL PLUGIN DEFINITION
* ======================= */
$.fn.modal = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modal'),
options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option);
if (!data) $this.data('modal', (data = new Modal(this, options)));
if (typeof option == 'string') data[option].apply(data, [].concat(args));
else if (options.show) data.show()
})
};
$.fn.modal.defaults = {
keyboard: true,
backdrop: true,
loading: false,
show: true,
width: null,
height: null,
maxHeight: null,
modalOverflow: false,
consumeTab: true,
focusOn: null,
replace: false,
resize: false,
attentionAnimation: 'shake',
manager: 'body',
spinner: '<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
backdropTemplate: '<div class="modal-backdrop" />'
};
$.fn.modal.Constructor = Modal;
/* MODAL DATA-API
* ============== */
$(function () {
$(document).off('click.modal').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) {
var $this = $(this),
href = $this.attr('href'),
$target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))), //strip for ie7
option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data());
e.preventDefault();
$target
.modal(option)
.one('hide', function () {
$this.focus();
})
});
});
}(window.jQuery);

View File

@@ -0,0 +1,423 @@
/* ===========================================================
* bootstrap-modalmanager.js v2.2.5
* ===========================================================
* Copyright 2012 Jordan Schroter.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* MODAL MANAGER CLASS DEFINITION
* ====================== */
var ModalManager = function (element, options) {
this.init(element, options);
};
ModalManager.prototype = {
constructor: ModalManager,
init: function (element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
this.stack = [];
this.backdropCount = 0;
if (this.options.resize) {
var resizeTimeout,
that = this;
$(window).on('resize.modal', function(){
resizeTimeout && clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(function(){
for (var i = 0; i < that.stack.length; i++){
that.stack[i].isShown && that.stack[i].layout();
}
}, 10);
});
}
},
createModal: function (element, options) {
$(element).modal($.extend({ manager: this }, options));
},
appendModal: function (modal) {
this.stack.push(modal);
var that = this;
modal.$element.on('show.modalmanager', targetIsSelf(function (e) {
var showModal = function(){
modal.isShown = true;
var transition = $.support.transition && modal.$element.hasClass('fade');
that.$element
.toggleClass('modal-open', that.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < that.$element.height());
modal.$parent = modal.$element.parent();
modal.$container = that.createContainer(modal);
modal.$element.appendTo(modal.$container);
that.backdrop(modal, function () {
modal.$element.show();
if (transition) {
//modal.$element[0].style.display = 'run-in';
modal.$element[0].offsetWidth;
//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
}
modal.layout();
modal.$element
.addClass('in')
.attr('aria-hidden', false);
var complete = function () {
that.setFocus();
modal.$element.trigger('shown');
};
transition ?
modal.$element.one($.support.transition.end, complete) :
complete();
});
};
modal.options.replace ?
that.replace(showModal) :
showModal();
}));
modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {
that.backdrop(modal);
// handle the case when a modal may have been removed from the dom before this callback executes
if (!modal.$element.parent().length) {
that.destroyModal(modal);
} else if (modal.$backdrop){
var transition = $.support.transition && modal.$element.hasClass('fade');
// trigger a relayout due to firebox's buggy transition end event
if (transition) { modal.$element[0].offsetWidth; }
$.support.transition && modal.$element.hasClass('fade') ?
modal.$backdrop.one($.support.transition.end, function () { modal.destroy(); }) :
modal.destroy();
} else {
modal.destroy();
}
}));
modal.$element.on('destroyed.modalmanager', targetIsSelf(function (e) {
that.destroyModal(modal);
}));
},
getOpenModals: function () {
var openModals = [];
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) openModals.push(this.stack[i]);
}
return openModals;
},
hasOpenModal: function () {
return this.getOpenModals().length > 0;
},
setFocus: function () {
var topModal;
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}
if (!topModal) return;
topModal.focus();
},
destroyModal: function (modal) {
modal.$element.off('.modalmanager');
if (modal.$backdrop) this.removeBackdrop(modal);
this.stack.splice(this.getIndexOfModal(modal), 1);
var hasOpenModal = this.hasOpenModal();
this.$element.toggleClass('modal-open', hasOpenModal);
if (!hasOpenModal){
this.$element.removeClass('page-overflow');
}
this.removeContainer(modal);
this.setFocus();
},
getModalAt: function (index) {
return this.stack[index];
},
getIndexOfModal: function (modal) {
for (var i = 0; i < this.stack.length; i++){
if (modal === this.stack[i]) return i;
}
},
replace: function (callback) {
var topModal;
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}
if (topModal) {
this.$backdropHandle = topModal.$backdrop;
topModal.$backdrop = null;
callback && topModal.$element.one('hidden',
targetIsSelf( $.proxy(callback, this) ));
topModal.hide();
} else if (callback) {
callback();
}
},
removeBackdrop: function (modal) {
modal.$backdrop.remove();
modal.$backdrop = null;
},
createBackdrop: function (animate, tmpl) {
var $backdrop;
if (!this.$backdropHandle) {
$backdrop = $(tmpl)
.addClass(animate)
.appendTo(this.$element);
} else {
$backdrop = this.$backdropHandle;
$backdrop.off('.modalmanager');
this.$backdropHandle = null;
this.isLoading && this.removeSpinner();
}
return $backdrop;
},
removeContainer: function (modal) {
modal.$container.remove();
modal.$container = null;
},
createContainer: function (modal) {
var $container;
$container = $('<div class="modal-scrollable">')
.css('z-index', getzIndex('modal', this.getOpenModals().length))
.appendTo(this.$element);
if (modal && modal.options.backdrop != 'static') {
$container.on('click.modal', targetIsSelf(function (e) {
modal.hide();
}));
} else if (modal) {
$container.on('click.modal', targetIsSelf(function (e) {
modal.attention();
}));
}
return $container;
},
backdrop: function (modal, callback) {
var animate = modal.$element.hasClass('fade') ? 'fade' : '',
showBackdrop = modal.options.backdrop &&
this.backdropCount < this.options.backdropLimit;
if (modal.isShown && showBackdrop) {
var doAnimate = $.support.transition && animate && !this.$backdropHandle;
modal.$backdrop = this.createBackdrop(animate, modal.options.backdropTemplate);
modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getOpenModals().length ));
if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow
modal.$backdrop.addClass('in');
this.backdropCount += 1;
doAnimate ?
modal.$backdrop.one($.support.transition.end, callback) :
callback();
} else if (!modal.isShown && modal.$backdrop) {
modal.$backdrop.removeClass('in');
this.backdropCount -= 1;
var that = this;
$.support.transition && modal.$element.hasClass('fade')?
modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal) }) :
that.removeBackdrop(modal);
} else if (callback) {
callback();
}
},
removeSpinner: function(){
this.$spinner && this.$spinner.remove();
this.$spinner = null;
this.isLoading = false;
},
removeLoading: function () {
this.$backdropHandle && this.$backdropHandle.remove();
this.$backdropHandle = null;
this.removeSpinner();
},
loading: function (callback) {
callback = callback || function () { };
this.$element
.toggleClass('modal-open', !this.isLoading || this.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < this.$element.height());
if (!this.isLoading) {
this.$backdropHandle = this.createBackdrop('fade', this.options.backdropTemplate);
this.$backdropHandle[0].offsetWidth; // force reflow
var openModals = this.getOpenModals();
this.$backdropHandle
.css('z-index', getzIndex('backdrop', openModals.length + 1))
.addClass('in');
var $spinner = $(this.options.spinner)
.css('z-index', getzIndex('modal', openModals.length + 1))
.appendTo(this.$element)
.addClass('in');
this.$spinner = $(this.createContainer())
.append($spinner)
.on('click.modalmanager', $.proxy(this.loading, this));
this.isLoading = true;
$.support.transition ?
this.$backdropHandle.one($.support.transition.end, callback) :
callback();
} else if (this.isLoading && this.$backdropHandle) {
this.$backdropHandle.removeClass('in');
var that = this;
$.support.transition ?
this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading() }) :
that.removeLoading();
} else if (callback) {
callback(this.isLoading);
}
}
};
/* PRIVATE METHODS
* ======================= */
// computes and caches the zindexes
var getzIndex = (function () {
var zIndexFactor,
baseIndex = {};
return function (type, pos) {
if (typeof zIndexFactor === 'undefined'){
var $baseModal = $('<div class="modal hide" />').appendTo('body'),
$baseBackdrop = $('<div class="modal-backdrop hide" />').appendTo('body');
baseIndex['modal'] = +$baseModal.css('z-index');
baseIndex['backdrop'] = +$baseBackdrop.css('z-index');
zIndexFactor = baseIndex['modal'] - baseIndex['backdrop'];
$baseModal.remove();
$baseBackdrop.remove();
$baseBackdrop = $baseModal = null;
}
return baseIndex[type] + (zIndexFactor * pos);
}
}());
// make sure the event target is the modal itself in order to prevent
// other components such as tabsfrom triggering the modal manager.
// if Boostsrap namespaced events, this would not be needed.
function targetIsSelf(callback){
return function (e) {
if (e && this === e.target){
return callback.apply(this, arguments);
}
}
}
/* MODAL MANAGER PLUGIN DEFINITION
* ======================= */
$.fn.modalmanager = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modalmanager');
if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)));
if (typeof option === 'string') data[option].apply(data, [].concat(args))
})
};
$.fn.modalmanager.defaults = {
backdropLimit: 999,
resize: true,
spinner: '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
backdropTemplate: '<div class="modal-backdrop" />'
};
$.fn.modalmanager.Constructor = ModalManager
// ModalManager handles the modal-open class so we need
// to remove conflicting bootstrap 3 event handlers
$(function () {
$(document).off('show.bs.modal').off('hidden.bs.modal');
});
}(jQuery);

2306
frontend/static/js/bootstrap.js vendored Normal file

File diff suppressed because it is too large Load Diff

7
frontend/static/js/bootstrap.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,838 @@
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
jQuery.extend({
getCommonProblemCellElement:function(problemEntity,cellId,options){
if(options == null){
options = {};
}
var elementStr = "";
var problemId = problemEntity.id;
var mainId = 0;
if(options.isShowFeedInfo){
var feedObjForId = options.feedObj;
mainId = feedObjForId.id;
}else if(options.isShowTrendInfo){
var trendObjForId = options.trendObj;
mainId = trendObjForId.id;
}else if(options.customId != null){
mainId = options.customId;
}else{
mainId = problemId;
}
elementStr += '<div id="' + cellId + mainId + '" class="commonProblemCell">';
if(options.isShowFeedInfo){
var feedObj = options.feedObj;
if(feedObj != null){
var feedFromUser = feedObj.fromUser;
var feedFromUserAvatar = "";
var feedFromUserName = "";
var feedInfo = "";
var feedFromUserGuid = "";
if(feedFromUser == null){
feedFromUserAvatar = "/public/img/default_avatar.jpg";
feedFromUserName = "该用户已被删除";
}else{
feedFromUserAvatar = feedFromUser.avatarThumbUrl + "&w=60&h=60";
feedFromUserName = feedFromUser.userName;
feedFromUserGuid = feedFromUser.guid;
}
var feedCreationTime = $.getMeaningfulTimeStr(feedObj.creationTime);
if(feedObj.type == 5){
feedInfo = " 关注了一个问题 • "+feedCreationTime;
}
elementStr += '<div class="commonProblemCellFeedInfo">\
<div class="commonProblemCellFeedUserInfo">\
<a target="_blank" href="/users/get?guid='+feedFromUserGuid+'"><img data-placement="bottom" class="img-circle commonProblemCellFeedAvatar" src="'+feedFromUserAvatar+'"/></a>\
<div class="commonProblemCellFeedUserNameInfo">\
<p><a data-placement="bottom" target="_blank" href="/users/get?guid='+feedFromUserGuid+'">'+$.htmlspecialchars(feedFromUserName)+'</a>'+$.htmlspecialchars(feedInfo)+'</p>\
</div>\
<div class="clear"></div>\
</div>';
elementStr += '<div class="clear"></div></div>';
}
}else if(options.isShowTrendInfo){
var trendObj = options.trendObj;
if(trendObj != null){
var trendFromUser = trendObj.user;
var trendFromUserAvatar = "";
var trendFromUserName = "";
var trendInfo = "";
var trendFromUserGuid = "";
if(trendFromUser == null){
trendFromUserAvatar = "/public/img/default_avatar.jpg";
trendFromUserName = "该用户已被删除";
}else{
trendFromUserAvatar = trendFromUser.avatarThumbUrl + "&w=60&h=60";
trendFromUserName = trendFromUser.userName;
trendFromUserGuid = trendFromUser.guid;
}
var trendCreationTime = $.getMeaningfulTimeStr(trendObj.creationTime);
if(trendObj.type == 3){
trendInfo = " 关注了一个问题 • "+trendCreationTime;
}
elementStr += '<div class="commonProblemCellFeedInfo">\
<div class="commonProblemCellFeedUserInfo">\
<a target="_blank" href="/users/get?guid='+trendFromUserGuid+'"><img data-placement="bottom" class="img-circle commonProblemCellFeedAvatar" src="'+trendFromUserAvatar+'"/></a>\
<div class="commonProblemCellFeedUserNameInfo">\
<p><a data-placement="bottom" target="_blank" href="/users/get?guid='+trendFromUserGuid+'">'+$.htmlspecialchars(trendFromUserName)+'</a>'+$.htmlspecialchars(trendInfo)+'</p>\
</div>\
<div class="clear"></div>\
</div>';
elementStr += '<div class="clear"></div></div>';
}
}
if(options.isNotShowMark){
}else{
var markElementStr = "";
var markArr = problemEntity.marks;
for(var j = 0; j < markArr.length; j++){
markElementStr += '<a target="_blank" href="/articles/listbymark?mark_id='+markArr[j].id+'"><span class="commonProblemCellMarkSpanContainer">'+$.htmlspecialchars(markArr[j].name)+'</span></a>';
}
elementStr += '<div class="commonProblemCellMarkContainer">'+markElementStr+'</div>';
}
var problemTitle = problemEntity.content;
problemTitle = $.htmlspecialchars(problemTitle);
if(options.isNotShowTitle){
}else{
elementStr += '<p class="commonProblemCellTitle"><a href="/problems/get?guid='+problemEntity.guid+'" target="_blank">'+problemTitle+'</a></p>';
}
var followCount = problemEntity.followCount;
var followClass = "";
if(problemEntity.hasFollow == 1){
followClass = "dragonfont-unfollow";
followCount = "已关注|" + followCount;
}else{
followClass = "dragonfont-follow";
followCount = "关注问题|" + followCount;
}
if(options.isNotShowCount){
}else{
elementStr += '<div class="commonProblemCellCountContainer">\
<a id="commonProblemCellFollow'+mainId+'" href="javascript:;" class="linkBlue commonProblemCellFollow">\
<span class="dragonfont '+followClass+'"></span>\
<span>'+followCount+'</span>\
</a>\
</div>';
}
elementStr += '</div>';
var element = $(elementStr);
return element;
},
getCommonArticleCellElement:function(articleEntity,cellId,options) {
if(options == null){
options = {};
}
var elementStr = "";
var articleId = articleEntity.id;
var mainId = 0;
if(options.isShowFeedInfo){
var feedObjForId = options.feedObj;
mainId = feedObjForId.id;
}else if(options.isShowTrendInfo){
var trendObjForId = options.trendObj;
mainId = trendObjForId.id;
}else if(options.customId != null){
mainId = options.customId;
}else{
mainId = articleId;
}
elementStr += '<div id="' + cellId + mainId + '" class="commonArticleCell">';
if(options.isShowFeedInfo){
var feedObj = options.feedObj;
if(feedObj != null){
if(feedObj.type == 3 || feedObj.type == 4){
var feedFromUser = feedObj.fromUser;
var feedFromUserAvatar = "";
var feedFromUserName = "";
var feedInfo = "";
var feedFromUserGuid = "";
if(feedFromUser == null){
feedFromUserAvatar = "/public/img/default_avatar.jpg";
feedFromUserName = "该用户已被删除";
}else{
feedFromUserAvatar = feedFromUser.avatarThumbUrl + "&w=60&h=60";
feedFromUserName = feedFromUser.userName;
feedFromUserGuid = feedFromUser.guid;
}
var feedCreationTime = $.getMeaningfulTimeStr(feedObj.creationTime);
if(feedObj.type == 3){
feedInfo = " 回答了一个问题 • "+feedCreationTime;
}else if(feedObj.type == 4){
feedInfo = " 推荐了一个回答 • "+feedCreationTime;
}
var feedHasTeamClass = "";
if(articleEntity.team_id > 0){
feedHasTeamClass = "hasTeamInfo";
}
elementStr += '<div class="commonArticleCellFeedInfo">\
<div class="commonArticleCellFeedUserInfo '+feedHasTeamClass+' ">\
<a target="_blank" href="/users/get?guid='+feedFromUserGuid+'"><img data-placement="bottom" class="img-circle commonArticleCellFeedAvatar" src="'+feedFromUserAvatar+'"/></a>\
<div class="commonArticleCellFeedUserNameInfo">\
<p><a data-placement="bottom" target="_blank" href="/users/get?guid='+feedFromUserGuid+'">'+$.htmlspecialchars(feedFromUserName)+'</a>'+$.htmlspecialchars(feedInfo)+'</p>\
</div>\
<div class="clear"></div>\
</div>';
//team相关信息在feed内显示在此处
if(articleEntity.team_id > 0){
var feedTeamIcon = "";
var feedTeamName = "";
var feedTeamId = 0;
if(articleEntity.team == null){
feedTeamName = "该团队已被删除";
}else{
feedTeamIcon = articleEntity.team.iconThumbUrl + "&w=60&h=60";
feedTeamName = articleEntity.team.name;
feedTeamId = articleEntity.team.id;
}
elementStr += '<div class="commonArticleCellFeedTeamPartInfo">\
<a target="_blank" href="/teams/get?id='+feedTeamId+'"><img data-placement="bottom" class="img-circle commonArticleCellFeedTeamPartAvatar" src='+feedTeamIcon+'/></a>\
<div class="commonArticleCellFeedTeamPartName">\
<p><a data-placement="bottom" target="_blank" href="/teams/get?id='+feedTeamId+'">'+$.htmlspecialchars(feedTeamName)+'</a></p>\
</div>\
<div class="clear"></div>\
</div>';
}
elementStr += '<div class="clear"></div></div>';
}else if(feedObj.type == 6){
var feedFromTeam = feedObj.fromTeam;
var feedFromTeamIcon = "";
var feedFromTeamName = "";
var feedInfo = "";
var feedFromTeamId = 0;
if(feedFromTeam == null){
feedFromTeamName = "该团队已被删除";
}else{
feedFromTeamIcon = feedFromTeam.iconThumbUrl + "&w=60&h=60";
feedFromTeamName = feedFromTeam.name;
feedFromTeamId = feedFromTeam.id;
}
if(feedObj.type == 6){
feedInfo = " 团队添加了一个回答";
}
elementStr += '<div class="commonArticleCellFeedInfo">\
<div class="commonArticleCellFeedTeamInfo">\
<a target="_blank" href="/teams/get?id='+feedFromTeamId+'"><img data-placement="bottom" class="img-circle commonArticleCellFeedAvatar" src="'+feedFromTeamIcon+'"/></a>\
<div class="commonArticleCellFeedTeamNameInfo">\
<p><a data-placement="bottom" target="_blank" href="/teams/get?id='+feedFromTeamId+'">'+$.htmlspecialchars(feedFromTeamName)+'</a>'+$.htmlspecialchars(feedInfo)+'</p>\
</div>\
<div class="clear"></div>\
</div>';
elementStr += '<div class="clear"></div></div>';
}
}
}else if(options.isShowTrendInfo){
var trendObj = options.trendObj;
if(trendObj != null){
var trendFromUser = trendObj.user;
var trendFromUserAvatar = "";
var trendFromUserName = "";
var trendInfo = "";
var trendFromUserGuid = "";
if(trendFromUser == null){
trendFromUserAvatar = "/public/img/default_avatar.jpg";
trendFromUserName = "该用户已被删除";
}else{
trendFromUserAvatar = trendFromUser.avatarThumbUrl + "&w=60&h=60";
trendFromUserName = trendFromUser.userName;
trendFromUserGuid = trendFromUser.guid;
}
var trendCreationTime = $.getMeaningfulTimeStr(trendObj.creationTime);
if(trendObj.type == 1){
trendInfo = " 回答了一个问题 • "+trendCreationTime;
}else if(trendObj.type == 2){
trendInfo = " 推荐了一个回答 • "+trendCreationTime;
}
elementStr += '<div class="commonArticleCellFeedInfo">\
<div class="commonArticleCellFeedUserInfo">\
<a target="_blank" href="/users/get?guid='+trendFromUserGuid+'"><img data-placement="bottom" class="img-circle commonArticleCellFeedAvatar" src="'+trendFromUserAvatar+'"/></a>\
<div class="commonArticleCellFeedUserNameInfo">\
<p><a data-placement="bottom" target="_blank" href="/users/get?guid='+trendFromUserGuid+'">'+$.htmlspecialchars(trendFromUserName)+'</a>'+$.htmlspecialchars(trendInfo)+'</p>\
</div>\
<div class="clear"></div>\
</div>';
elementStr += '<div class="clear"></div></div>';
}
}
if(articleEntity.team_id != 0){
var teamId = articleEntity.team_id;
var teamName = "";
var teamIconUrl = "";
if(articleEntity.team == null){
teamName = "该团队已被删除";
}else{
teamName = articleEntity.team.name;
teamIconUrl = articleEntity.team.iconThumbUrl + "&w=60&h=60";
}
if(options.isNotShowTeam){
}else{
elementStr += '<div class="commonArticleCellTeamContainer">';
elementStr += '<a target="_blank" href="/teams/get?id='+teamId+'"><img data-placement="bottom" class="img-circle commonArticleCellTeamIcon" src="'+teamIconUrl+'"/></a>';
elementStr += '<a target="_blank" href="/teams/get?id='+teamId+'" data-placement="bottom" class="commonArticleCellTeamName">'+teamName+'</a>'
elementStr += '</div>';
}
}
var articleTitle = "";
if(articleEntity.problem_id != 0){
if(articleEntity.problem == null){
articleTitle = "该问题已被删除";
}else{
articleTitle = articleEntity.problem.content;
}
}else{
articleTitle = articleEntity.title;
}
articleTitle = $.htmlspecialchars(articleTitle);
if(options.isNotShowTitle){
}else{
if(articleEntity.problem_id != 0){
//link为问题detail
elementStr += '<p class="commonArticleCellTitle"><a href="/problems/get?guid='+articleEntity.problem.guid+'" target="_blank">'+articleTitle+'</a></p>';
}else{
//link为文章detail
elementStr += '<p class="commonArticleCellTitle"><a href="/articles/get?guid='+articleEntity.guid+'" target="_blank">'+articleTitle+'</a></p>';
}
}
var articleCreatorId = articleEntity.creator_id;
var articleCreator = articleEntity.creator;
var articleCreatorAvatar = "";
var articleCreatorUserName = "";
var articleCreatorWord = "";
var articleCreatorGuid = "";
if(articleCreator == null){
articleCreatorAvatar = "/public/img/default_avatar.jpg";
articleCreatorUserName = "该用户已被删除";
articleCreatorWord = "";
articleCreatorGuid = "";
}else{
articleCreatorAvatar = articleCreator.avatarThumbUrl + "&w=100&h=100";
articleCreatorUserName = articleCreator.userName;
articleCreatorWord = articleCreator.word;
articleCreatorGuid = articleCreator.guid;
if(articleCreatorWord != ""){
articleCreatorWord = ""+articleCreatorWord;
}
}
if(options.isNotShowCreator){
}else{
elementStr += '<div class="commonArticleCellCreatorInfo">';
elementStr += '<a target="_blank" href="/users/get?guid='+articleCreatorGuid+'"><img data-placement="bottom" src="'+articleCreatorAvatar+'" class="img-circle commonArticleCellCreatorAvatar"></a>';
elementStr += '<p class="commonArticleCellCreatorNameInfo"><a data-placement="bottom" target="_blank" href="/users/get?guid='+articleCreatorGuid+'">'+$.htmlspecialchars(articleCreatorUserName)+'</a>'+$.htmlspecialchars(articleCreatorWord)+'</p>';
elementStr += '<div class="clear"></div>'
elementStr += '</div>';
}
if(articleEntity.coverlist_id != 0){
var coverUrl = articleEntity.coverListMediumUrl;
if(options.isNotShowCover){
}else{
elementStr += '<a href="/articles/get?guid='+articleEntity.guid+'" target="_blank"><img class="commonArticleCellCover" src="'+coverUrl+'"/></a>';
}
}
var articleContent = articleEntity.content;
var bMore = false;
if(articleContent.length > 110){
articleContent = articleContent.substr(0,111);
articleContent = articleContent + "……";
bMore = true;
}
articleContent = $.htmlspecialchars(articleContent);
if(options.isNotShowContent){
}else{
if(bMore){
elementStr += '<p id="commonArticleCellContent'+mainId+'" class="commonArticleCellContent">'+articleContent+'<a id="commonArticleCellShowMore'+mainId+'" class="commonArticleCellShowMore" href="/articles/get?guid='+articleEntity.guid+'" target="_blank">(更多)</a></p>';
}else{
elementStr += '<p id="commonArticleCellContent'+mainId+'" class="commonArticleCellContent">'+articleContent+'</p>';
}
}
var recommendCount = articleEntity.recommendCount;
var remarkCount = articleEntity.remarkCount;
var heatClass = "dragonfont-heartempty";
var appendElement = "";
if(articleEntity.problem_id > 0){
//是回答显示关注
if(articleEntity.problem != null){
var followCount = articleEntity.problem.followCount;
var followClass = "";
if(articleEntity.problem.hasFollow == 1){
followClass = "dragonfont-unfollow";
followCount = "已关注|" + followCount;
}else{
followClass = "dragonfont-follow";
followCount = "关注问题|" + followCount;
}
appendElement = '<a id="commonArticleCellFollow'+mainId+'" href="javascript:;" class="linkGray commonArticleCellFollow">\
<span class="dragonfont '+followClass+'"></span>\
<span>'+followCount+'</span>\
</a>';
}
}
if(articleEntity.hasRecommend == 1){
recommendCount = '已推荐|' + recommendCount;
heatClass = "dragonfont-heart";
}else{
recommendCount = '推荐|' + recommendCount;
heatClass = "dragonfont-heartempty";
}
if(options.isNotShowCount){
}else{
elementStr += '<div class="commonArticleCellCountContainer">\
<a id="commonArticleCellRecommend'+mainId+'" href="javascript:;" class="linkBlue commonArticleCellRecommend">\
<span class="dragonfont '+heatClass+'"></span>\
<span>'+recommendCount+'</span>\
</a>'+appendElement+'\
<a href="/articles/get?guid='+articleEntity.guid+'&source=remark" target="_blank" class="linkGray commonArticleCellRemark">\
<span class="dragonfont dragonfont-chatbubble"></span>\
<span>'+remarkCount+' 条评论</span>\
</a>\
</div>';
}
var timeStr = $.getMeaningfulTimeStr(articleEntity.createdAt);
if(options.isNotShowTimeAndOpr){
}else{
elementStr += '<div class="commonArticleCellOprContainer">\
<span>'+timeStr+'</span>\
<span id="commonArticleCellDot'+mainId+'" class="commonArticleCellDot">•</span>\
<a href="javascript:;" tabindex="0" id="commonArticleCellOpr'+mainId+'" class="linkGray commonArticleCellOpr"><span class="dragonfont dragonfont-ellipsis"></span></a>\
</div>';
}
elementStr += '</div>';
var element = $(elementStr);
return element;
},
installCommonProblemCellEffect:function(id,options){
//安装点关注相关
var hasLogin = options.hasLogin;
var problemEntity = options.problemEntity;
var redirectLoginUrl = options.redirectLoginUrl;
//问题关注操作
$("#commonProblemCellFollow"+id).click(function(){
if(!hasLogin){
window.location.href=redirectLoginUrl;
return;
}
if(problemEntity == null){
return;
}
if(problemEntity.hasFollow == 0){
problemEntity.hasFollow = 1;
problemEntity.followCount = problemEntity.followCount + 1;
$("#commonProblemCellFollow"+id + " > span:first-child").removeClass("dragonfont-follow").addClass('dragonfont-unfollow');
$("#commonProblemCellFollow"+id + " > span:eq(1)").text("已关注|" + problemEntity.followCount );
//$("#feedProblemCellFollow"+arg).removeClass("feedProblemCellUnFollow").addClass("feedProblemCellAlreadyFollow");
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/problems/followproblem",
data : "problem_id=" + problemEntity.id,
beforeSend:function(){
var currentReq = $("#commonProblemCellFollow"+id).data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$("#commonProblemCellFollow"+id).data("jRequest",null);
},
success : function(data){
problemEntity.followCount = data.followCount;
$("#commonProblemCellFollow"+id + " > span:eq(1)").text("已关注|" + problemEntity.followCount );
},
error : function(data){
if(data.statusText=="abort"){
return;
}
problemEntity.hasFollow = 0;
problemEntity.followCount = problemEntity.followCount - 1;
$("#commonProblemCellFollow"+id + " > span:first-child").removeClass("dragonfont-unfollow").addClass('dragonfont-follow');
$("#commonProblemCellFollow"+id + " > span:eq(1)").text("关注问题|" + problemEntity.followCount );
//$("#feedProblemCellFollow"+arg).removeClass("feedProblemCellAlreadyFollow").addClass("feedProblemCellUnFollow");
}});
$("#commonProblemCellFollow"+id).data("jRequest",jRequest);
}else{
problemEntity.hasFollow = 0;
problemEntity.followCount = problemEntity.followCount - 1;
$("#commonProblemCellFollow"+id + " > span:first-child").removeClass("dragonfont-unfollow").addClass('dragonfont-follow');
$("#commonProblemCellFollow"+id + " > span:eq(1)").text("关注问题|" + problemEntity.followCount );
//$("#feedProblemCellFollow"+arg).removeClass("feedProblemCellAlreadyFollow").addClass("feedProblemCellUnFollow");
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/problems/unfollowproblem",
data : "problem_id=" + problemEntity.id,
beforeSend:function(){
var currentReq = $("#commonProblemCellFollow"+id).data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$("#commonProblemCellFollow"+id).data("jRequest",null);
},
success : function(data){
problemEntity.followCount = data.followCount;
$("#commonProblemCellFollow"+id + " > span:eq(1)").text("关注问题|" + problemEntity.followCount );
},
error : function(data){
if(data.statusText=="abort"){
return;
}
problemEntity.hasFollow = 0;
problemEntity.followCount = problemEntity.followCount - 1;
$("#commonProblemCellFollow"+id + " > span:first-child").removeClass("dragonfont-follow").addClass('dragonfont-unfollow');
$("#commonProblemCellFollow"+id + " > span:eq(1)").text("已关注|" + problemEntity.followCount );
//$("#feedProblemCellFollow"+arg).removeClass("feedProblemCellUnFollow").addClass("feedProblemCellAlreadyFollow");
}});
$("#commonProblemCellFollow"+id).data("jRequest",jRequest);
}
});
},
installCommonArticleCellEffect:function(id,options){
if($("#commonArticleCellShowMore" + id).length > 0){
//安装hover内容同步hover更多
$("#commonArticleCellContent" + id).hover(function(){
$("#commonArticleCellShowMore" + id).addClass("commonArticleCellShowMoreDynamic");
},function(){
$("#commonArticleCellShowMore" + id).removeClass("commonArticleCellShowMoreDynamic");
});
}
var articleEntity = options.articleEntity;
//安装原文链接跳转相关
$("#commonArticleCellContent" + id).on("click",function(){
window.open("/articles/get?guid="+articleEntity.guid);
});
//安装点赞相关
var hasLogin = options.hasLogin;
var redirectLoginUrl = options.redirectLoginUrl;
$("#commonArticleCellRecommend"+id).click(function(){
if(!hasLogin){
window.location.href=redirectLoginUrl;
return;
}
if(articleEntity == null){
return;
}
if(articleEntity.hasRecommend == 0){
articleEntity.hasRecommend = 1;
articleEntity.recommendCount = articleEntity.recommendCount + 1;
$("#commonArticleCellRecommend"+id + " > span:first-child").removeClass("dragonfont-heartempty").addClass('dragonfont-heart');
$("#commonArticleCellRecommend"+id + " > span:eq(1)").text("已推荐|" + articleEntity.recommendCount );
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/articles/recommend",
data : "articleId=" + articleEntity.id,
beforeSend:function(){
var currentReq = $("#commonArticleCellRecommend"+id).data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$("#commonArticleCellRecommend"+id).data("jRequest",null);
},
success : function(data){
articleEntity.recommendCount = data.recommendCount;
$("#commonArticleCellRecommend"+id + " > span:eq(1)").text("已推荐|" + articleEntity.recommendCount );
},
error : function(data){
if(data.statusText=="abort"){
return;
}
articleEntity.hasRecommend = 0;
articleEntity.recommendCount = articleEntity.recommendCount - 1;
$("#commonArticleCellRecommend"+id + " > span:first-child").removeClass("dragonfont-heart").addClass('dragonfont-heartempty');
$("#commonArticleCellRecommend"+id + " > span:eq(1)").text("推荐|" + articleEntity.recommendCount );
}});
$("#commonArticleCellRecommend"+id).data("jRequest",jRequest);
}else{
articleEntity.hasRecommend = 0;
articleEntity.recommendCount = articleEntity.recommendCount - 1;
$("#commonArticleCellRecommend"+id + " > span:first-child").removeClass("dragonfont-heart").addClass('dragonfont-heartempty');
$("#commonArticleCellRecommend"+id + " > span:eq(1)").text("推荐|" + articleEntity.recommendCount );
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/articles/unrecommend",
data : "articleId=" + articleEntity.id,
beforeSend:function(){
var currentReq = $("#commonArticleCellRecommend"+id).data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$("#commonArticleCellRecommend"+id).data("jRequest",null);
},
success : function(data){
articleEntity.recommendCount = data.recommendCount;
$("#commonArticleCellRecommend"+id + " > span:eq(1)").text("推荐|" + articleEntity.recommendCount );
},
error : function(data){
if(data.statusText=="abort"){
return;
}
articleEntity.hasRecommend = 1;
articleEntity.recommendCount = articleEntity.recommendCount + 1;
$("#commonArticleCellRecommend"+id + " > span:first-child").removeClass("dragonfont-heartempty").addClass('dragonfont-heart');
$("#commonArticleCellRecommend"+id + " > span:eq(1)").text("已推荐|" + articleEntity.recommendCount );
}});
$("#commonArticleCellRecommend"+id).data("jRequest",jRequest);
}
});
//安装关注相关
var problemEntity = articleEntity.problem;
if(problemEntity != null){
//问题关注操作
$("#commonArticleCellFollow"+id).click(function(){
if(!hasLogin){
window.location.href=redirectLoginUrl;
return;
}
if(problemEntity == null){
return;
}
if(problemEntity.hasFollow == 0){
problemEntity.hasFollow = 1;
problemEntity.followCount = problemEntity.followCount + 1;
$("#commonArticleCellFollow"+id + " > span:first-child").removeClass("dragonfont-follow").addClass('dragonfont-unfollow');
$("#commonArticleCellFollow"+id + " > span:eq(1)").text("已关注|" + problemEntity.followCount );
//$("#feedProblemCellFollow"+arg).removeClass("feedProblemCellUnFollow").addClass("feedProblemCellAlreadyFollow");
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/problems/followproblem",
data : "problem_id=" + problemEntity.id,
beforeSend:function(){
var currentReq = $("#commonArticleCellFollow"+id).data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$("#commonArticleCellFollow"+id).data("jRequest",null);
},
success : function(data){
problemEntity.followCount = data.followCount;
$("#commonArticleCellFollow"+id + " > span:eq(1)").text("已关注|" + problemEntity.followCount );
},
error : function(data){
if(data.statusText=="abort"){
return;
}
problemEntity.hasFollow = 0;
problemEntity.followCount = problemEntity.followCount - 1;
$("#commonArticleCellFollow"+id + " > span:first-child").removeClass("dragonfont-unfollow").addClass('dragonfont-follow');
$("#commonArticleCellFollow"+id + " > span:eq(1)").text("关注问题|" + problemEntity.followCount );
//$("#feedProblemCellFollow"+arg).removeClass("feedProblemCellAlreadyFollow").addClass("feedProblemCellUnFollow");
}});
$("#commonArticleCellFollow"+id).data("jRequest",jRequest);
}else{
problemEntity.hasFollow = 0;
problemEntity.followCount = problemEntity.followCount - 1;
$("#commonArticleCellFollow"+id + " > span:first-child").removeClass("dragonfont-unfollow").addClass('dragonfont-follow');
$("#commonArticleCellFollow"+id + " > span:eq(1)").text("关注问题|" + problemEntity.followCount );
//$("#feedProblemCellFollow"+arg).removeClass("feedProblemCellAlreadyFollow").addClass("feedProblemCellUnFollow");
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/problems/unfollowproblem",
data : "problem_id=" + problemEntity.id,
beforeSend:function(){
var currentReq = $("#commonArticleCellFollow"+id).data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$("#commonArticleCellFollow"+id).data("jRequest",null);
},
success : function(data){
problemEntity.followCount = data.followCount;
$("#commonArticleCellFollow"+id + " > span:eq(1)").text("关注问题|" + problemEntity.followCount );
},
error : function(data){
if(data.statusText=="abort"){
return;
}
problemEntity.hasFollow = 0;
problemEntity.followCount = problemEntity.followCount - 1;
$("#commonArticleCellFollow"+id + " > span:first-child").removeClass("dragonfont-follow").addClass('dragonfont-unfollow');
$("#commonArticleCellFollow"+id + " > span:eq(1)").text("已关注|" + problemEntity.followCount );
//$("#feedProblemCellFollow"+arg).removeClass("feedProblemCellUnFollow").addClass("feedProblemCellAlreadyFollow");
}});
$("#commonArticleCellFollow"+id).data("jRequest",jRequest);
}
});
}
}
});

View File

@@ -0,0 +1,117 @@
/**
* 定义全局JS函数
*/
//保存后禁用按钮,防止重复提交
function Disabled($this,btn_text){
$this.attr('disabled','disabled').text(btn_text).val(btn_text);
}
//设置按钮为可用状态
function Enabled($this,btn_text){
$this.removeAttr('disabled').empty().text(btn_text).val(btn_text);
}
//loading
function Loading($this,bgColor){
var $loading=$('<div class="loading">'+
'<div class="loading1"></div>'+
'<div class="loading2"></div>'+
'<div class="loading3"></div>'+
'</div>');
$this.append($loading);
arguments[1]&&arguments[1]!=''?$this.find('.loading div').css('background',bgColor):'';
}
/* 查看是否拥有该权限 */
function hasAuth(DropDownArray,authList_array){
var returnValue=[];
for(var j=0;j<DropDownArray.length;j++){
for(var i=0;i<authList_array.length;i++){
/* 判断是否拥有该权限 */
var flag = authList_array[i].module===DropDownArray[j].module &&
authList_array[i].controller===DropDownArray[j].controller &&
authList_array[i].action===DropDownArray[j].action &&
authList_array[i].method===DropDownArray[j].method;
if(flag){
var returnValue_json={};
returnValue_json.index=j;
returnValue_json.menuItem=DropDownArray[j].menuItem;
returnValue_json.link='/'+authList_array[i].controller+'/'+authList_array[i].action;
returnValue.push(returnValue_json);
break;
}
}
}
return returnValue;
}
//MODAL
function ModalOperation(showModalElem){
/* 显示Modal框 */
showModalElem.click(function(){
$('.modal,.modal-background').show();
});
/* 隐藏Modal框 */
$(document).on('click','.modal-background,.modal-footer input[type="reset"],.modal .close-btn',function(){
$('.input-area').val('');
$('.modal,.modal-background').hide();
});
}
//图片在容器居中显示
function centerCropImg(url,$container){
/* 取图片正中间部分 */
var img=new Image();
img.src=url;
img.onload=function(){
/* 容器宽高 */
var containerHeight=$container.height(),containerWidth=$container.width();
/* 容器比例 */
var containerScale=containerWidth/containerHeight;
/* 等比例缩放后图片宽高 */
var imgHeight,imgWidth;
/* 横图 */
if(img.width/img.height>containerScale){
imgWidth=img.width/img.height*containerHeight;
var _left=(imgWidth-containerWidth)/2;
$container.find('img').height(containerHeight).css({
'left':'-'+_left+'px'
});
}
/* 竖图 */
else{
imgHeight=img.height/img.width*containerWidth;
var _top=(imgHeight-containerHeight)/2;
$container.find('img').width(containerWidth).css({
'top':'-'+_top+'px'
});
}
}
}
//时间戳转换日期
function timeStampToDateString(ts){
var datetime=new Date(parseInt(ts)*1000);
var year=datetime.getFullYear();
var month=datetime.getMonth()+1;
var date=datetime.getDate();
var dateString=year+'-'+month+'-'+date;
return dateString;
}
//JSON数组排序函数
function getSortFun(order, sortBy) {
var ordAlpah = (order == 'asc') ? '>' : '<';
var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?1:-1');
return sortFun;
}
function lazyload(){
var $unload=$('.shot-image .unload');
for(var i=0;i<$unload.length;i++){
var top=$(window).scrollTop(),height=$(window).height();
/* 未加载的图片元素进入可视区域 */
if(top+height>$unload.eq(i).offset().top){
var url=$unload.eq(i).data('url');
$unload.eq(i).removeClass('unload').addClass('loaded').attr('src',url).fadeIn(500);
}
}
}

View File

@@ -0,0 +1,680 @@
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
jQuery.extend({
drWindowLocation:function(href,isShownLoading){
if(isShownLoading){
$('#loadingBar').drloadingbar("startLoad");
}
window.location.href=href;
},
adjustNode:function(node,isRoot){
var childNodes = node.children();
var tagName = node[0].tagName.toLowerCase();
if(tagName == null){
//普通字符串节点,不转化
return;
}
if(childNodes.length > 0){
//不是叶子节点,先去调整所有子节点
for(var i = 0; i < childNodes.length; i++){
$.adjustNode($(childNodes[i]),false);
}
}else{
//叶子节点
var display = $.getElementDefaultDisplay(tagName);
if(display == "block" || display=="list-item"){
if(tagName == "p"){
//本身就是段落,不替换
}else if(tagName == "hr"){
//分割线,不替换
}else{
//替换成段落
if(node.hasClass("drimgCaption")){
//不替换
}else{
node.contents().unwrap().wrap("<p></p>");
}
}
}else{
//行内元素,不替换
if(tagName=="img"){
//图片元素包裹imgcaption
if(!node.parent().hasClass("drimgPackage")){
node.wrap('<div class="drimgPackage"></div>');
node.parent().append($('<div class="drimgCaption">&nbsp;<br></div>'));
}
}
}
return;
}
//非叶子节点调整完所有底部节点后
//处理换行问题
var hasBr = false;;
for(var i = 0; i < node.children().length; i++){
if(node.children()[i].tagName.toLowerCase() == "br"){
if(node.closest(".drimgPackage").length > 0){
}else{
hasBr = true;
}
break;
}
}
if(hasBr){
var brNodePosition = [];
var contentsChild = node.contents();
for(var i = 0; i < contentsChild.length; i++){
var content = contentsChild[i];
if(content.nodeType == 1){
var contentTagName = content.tagName.toLowerCase();
if(contentTagName == "br"){
brNodePosition.push(i);
}
}
}
var shouldWrapNodePosition = [];
var wrapGroup = [];
for(var i = 0; i < brNodePosition.length;i++){
var j = i + 1;
var k = i - 1;
var allPrevNode = [];
if(i == 0){
for(var index = 0; index < brNodePosition[i]; index++ ){
allPrevNode.push($(node.contents()[index]));
}
}else{
}
var allPostNode = [];
if(j < brNodePosition.length){
for(var index = brNodePosition[i] + 1; index < brNodePosition[j]; index++ ){
allPostNode.push($(node.contents()[index]));
}
}else{
for(var index = brNodePosition[i] + 1; index < node.contents().length; index++ ){
allPostNode.push($(node.contents()[index]));
}
}
wrapGroup.push(allPrevNode);
wrapGroup.push(allPostNode);
}
var originContent = node.contents();
for(var i = 0; i < wrapGroup.length; i++){
var wrapObj = originContent.filter(function(){
for(var j = 0; j < wrapGroup[i].length;j++){
if(wrapGroup[i][j][0] == this){
return true;
}
}
return false;
});
wrapObj.wrapAll("<p></p>");
}
//去掉br
node.find("br").remove();
}
if(isRoot){
return;
}
var display = $.getElementDefaultDisplay(tagName);
if(display == "block" || display=="list-item"){
if(tagName == "p"){
//本身就是段落,不替换
}else if(tagName=="aside" || tagName=="blockquote" || tagName == "ul" || tagName == "ol" || tagName =="dl"
|| tagName == "div" || tagName=="section" || tagName=="article" || tagName=="header" || tagName=="footer"
|| tagName == "div" || tagName =="form" || tagName == "head" || tagName == "nav"){
//容器类
if(tagName == "div" && (node.hasClass("drimgPackage") || node.hasClass("drimgCaption") )){
}else{
var prev = node.prev();
var next = node.next();
var parent = node.parent();
if(prev.length > 0){
node.children().insertAfter(prev);
}else if(next.length > 0){
node.children().insertBefore(next);
}else{
node.children().prependTo(parent);
}
node.remove();
}
}else{
$newElement = $("<p></p>");
var oldAttrs = node.attr();
for(var key in oldAttrs){
$newElement.attr(key,oldAttrs[key]);
}
$newElement.html(node.html());
$newElement.insertAfter(node);
node.remove();
}
}else{
//行内元素
}
},
getElementDefaultDisplay:function(tag) {
var cStyle,
t = document.createElement(tag),
gcs = "getComputedStyle" in window;
document.body.appendChild(t);
cStyle = (gcs ? window.getComputedStyle(t, "") : t.currentStyle).display;
document.body.removeChild(t);
return cStyle;
},
clearNode:function(node){
if(node != null){
if(node.hasClass("drimgCaption")){
node.removeAttr("class");
node.addClass("drimgCaption");
}else if(node.hasClass("drimgPackage")){
node.removeAttr("class");
node.addClass("drimgPackage");
}else{
node.removeAttr("class");
}
node.removeAttr("style");
if(node[0].tagName == null){
//普通文本没有tag
return false;
}
//去掉所有内置属性
var tagName = node[0].tagName.toLowerCase();
var attrObj = node.attr();
for(var key in attrObj){
if(tagName == "img" && key == "src"){
continue;
}else if(tagName=="a" && key=="href"){
node.attr("target","_blank");
continue;
}else if(tagName=="a" && key=="target"){
continue;
}else if(key=="class"){
continue;
}
node.removeAttr(key);
}
if($.shouldbeEmptyNode(node)){
//本节点自身为空,去除
return true;
}else{
var children = node.children();
var removeNode = [];
for(var i = 0; i < children.length; i++){
if($.clearNode($(children[i]))){
removeNode.push($(children[i]));
}
}
for(var i = 0; i < removeNode.length; i++){
removeNode[i].remove();
}
//子节点移除后判断父节点是否为空
if($.shouldbeEmptyNode(node)){
return true;
}
return false;
}
}
},
shouldbeEmptyNode:function(node){
var tagName = node[0].tagName.toLowerCase();
if(tagName == "img"){
return false;
}
if(tagName == "hr"){
return false;
}
if(tagName == "br"){
return false;
}
if(tagName == "div" && (node.hasClass("drimgCaption") || node.hasClass("drimgPackage"))){
return false;
}
var ret = ($.trim(node.text()) === '' && node.children().length == 0);
return ret;
},
removeEmptyNode:function(node){
node.filter(function() {
var returnValue = ($.trim($(this).text()) === '' && $(this).children().length == 0);
return returnValue;
}).remove();
},
getGuid:function(){
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return (S4()+S4()+""+S4()+""+S4()+""+S4()+""+S4()+S4()+S4());
},
// processContentEditableStr:function(blockElement){
// var content = "";
// var inputChildren = blockElement.children();
// for(var i = 0; i < inputChildren.length; i++){
// if($(inputChildren[i])[0].tagName.toLowerCase() == "br"){
// content = content + "\n";
// continue;
// }
// var tagName = inputChildren[i].tagName.toLowerCase();
//
// if($.getElementDefaultDisplay(tagName)=="block" || $.getElementDefaultDisplay(tagName)=="list-item"){
// if($(inputChildren[i]).text() != ""){
// content = content + "\n" + $.processContentEditableStr($(inputChildren[i]));
// }else{
// content = content + $.processContentEditableStr($(inputChildren[i]));
// }
//
// }else{
// content = content + $(inputChildren[i]).text();
// }
//
// }
// var parentContent = blockElement.contents().filter(function() {
// return this.nodeType === 3;
// }).text();
// content = parentContent + content;
// return content;
// },
processContentEditableStr:function(blockElement,isRoot){
var content = "";
var inputChildren = blockElement.contents();
for(var i = 0; i < inputChildren.length; i++){
if(inputChildren[i].nodeType === 3){
content = content + $(inputChildren[i]).text();
continue;
}
if(inputChildren[i].tagName.toLowerCase() == "br"){
content = content + "\n";
continue;
}
var tagName = inputChildren[i].tagName.toLowerCase();
if($.getElementDefaultDisplay(tagName)=="block" || $.getElementDefaultDisplay(tagName)=="list-item"){
var textNode= $(inputChildren[i]).contents().filter(function() {
return this.nodeType === 3;
});
if(textNode.length > 0){
content = content + "\n" + $.processContentEditableStr($(inputChildren[i]),false);
}else{
content = content + $.processContentEditableStr($(inputChildren[i]),false);
}
}else{
content = content + $.processContentEditableStr($(inputChildren[i]),false);
}
}
// var parentContent = blockElement.contents().filter(function() {
// return this.nodeType === 3;
// }).text();
// content = parentContent + content;
if(isRoot){
//去掉第一个回车
if(content != "" && content[0] == "\n"){
content = content.substring(1,content.length);
}
}
return content;
},
nl2br:function(str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br/>' : '<br>';
//return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
str=str.replace(/\r\n/g,breakTag);
str=str.replace(/\n/g,breakTag);
return str;
},
setSelectionRange:function(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
},
focuscurorInContentEditable:function(selector,position){
selector.each(function(){
var el = this;
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el.childNodes[0], position);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
});
},
getDeviceWidthType: function(){
var clientWidth = document.documentElement.clientWidth;
if(clientWidth <= 800){
return 1;
}else{
return 4; //>800统一按照pc处理暂时
}
},
getDeviceWidth:function(){
var clientWidth = document.documentElement.clientWidth;
return clientWidth;
},
getDeviceHeight:function(){
var clientHeight = document.documentElement.clientHeight;
return clientHeight;
},
htmlspecialchars:function(str){
str = str.replace(/&/g, '&amp;');
str = str.replace(/</g, '&lt;');
str = str.replace(/>/g, '&gt;');
str = str.replace(/"/g, '&quot;');
str = str.replace(/'/g, '&#039;');
return str;
},
getDateFormat:function(time){
time = new Date(time*1000);
var year=time.getYear() + 1900;
var month=time.getMonth()+1;
var date=time.getDate();
var hour=time.getHours();
var minute=time.getMinutes();
var second=time.getSeconds();
return year+"."+month+"."+date;
},
getMeaningfulTimeStr:function(time){
var nowTime = (Date.parse(new Date()))/1000;
var time = time;
var delta = nowTime-time;
if(delta < 60){
return "1 分钟前";
}else if(delta < 3600){
delta = Math.floor(delta/60);
return delta+" 分钟前";
}else if(delta < 86400){
delta = Math.floor(delta/3600);
return delta+" 小时前";
}else {
//判断是否是昨天
var today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
var oneday = 1000* 60 * 60 * 24;
var yesterday = new Date(today - oneday);
var yesterdayTime = (Date.parse(yesterday))/1000;
timeDate = new Date(time*1000);
var year=timeDate.getYear() + 1900;
var month=timeDate.getMonth()+1;
var date=timeDate.getDate();
var hour=timeDate.getHours();
var minute=timeDate.getMinutes();
var second=timeDate.getSeconds();
if (month.toString().length == 1) {
month = "0" + month;
}
if (date.toString().length == 1) {
date = "0" + date;
}
if (minute.toString().length == 1) {
minute = "0" + minute;
}
if (hour.toString().length == 1) {
hour = "0" + hour;
}
if (second.toString().length == 1) {
second = "0" + second;
}
if(yesterdayTime <= time){
//是昨天
return "昨天 " + hour +":"+minute;
}else{
return year+"-"+month+"-"+date + " " + hour +":"+minute;
}
}
},
getTransitionEnd:function() {
var el = document.createElement('dragon')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
});
//补充jquery被废弃的broswer变量判断浏览器类型
var matched, browser;
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie)[\s?]([\w.]+)/.exec( ua ) ||
/(trident)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
//IE 11+ fix (Trident)
matched.browser = matched.browser == 'trident' ? 'msie' : matched.browser;
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
(function( $ ){
var methods = {
init : function( options ){
var $this = this;
options = $.extend( $.fn.drcontenteditable.options, options );
return this.each(function(){
$this.on("paste",function(e){
var pasteText = e.originalEvent.clipboardData.getData("text/plain");
//替换/r/n为br
pasteText = pasteText.replace(/\r\n/g,"<br/>");
pasteText = pasteText.replace(/\r/g,"<br/>");
pasteText = pasteText.replace(/\n/g,"<br/>");
document.execCommand("insertHTML", false, pasteText);
e.preventDefault();
});
});
},
getContent:function(){
function extractTextWithWhitespaceWorker(elems, lineBreakNodeName)
{
var ret = "";
var elem;
for (var i = 0; elems[i]; i++)
{
elem = elems[i];
if (elem.nodeType === 3 // text node
|| elem.nodeType === 4) // CDATA node
{
ret += elem.nodeValue;
}
if (elem.nodeName === lineBreakNodeName )
{
if(elem.nodeType == 1 && $(elem).text() != ""){
ret += "\n";
}
}
if(elem.nodeName === "BR"){
ret += "\n";
}
if (elem.nodeType !== 8) // comment node
{
ret += extractTextWithWhitespace(elem.childNodes, lineBreakNodeName);
}
}
return ret;
}
function extractTextWithWhitespace(elems)
{
var lineBreakNodeName = "BR"; // Use <br> as a default
if ($.browser.webkit)
{
lineBreakNodeName = "DIV";
}
else if ($.browser.msie)
{
lineBreakNodeName = "P";
}
else if ($.browser.mozilla)
{
lineBreakNodeName = "BR";
}
else if ($.browser.opera)
{
lineBreakNodeName = "P";
}
var extractedText = extractTextWithWhitespaceWorker(elems, lineBreakNodeName);
return extractedText;
}
return extractTextWithWhitespace(this.contents());
}
};
$.fn.drcontenteditable = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.drcontenteditable' );
}
};
$.fn.drcontenteditable.options = {};
})( jQuery );

View File

@@ -0,0 +1,181 @@
(function( $ ){
var methods = {
init : function( options ){
var $this = this;
options = $.extend( $.fn.createproblem.options, options );
return this.each(function(){
$("#createProblemMarkContainer").markinput("init",{adjustLeftComponent:$("#problemModalBody")});
$("#createProblemSummary").on("keydown",function(e){
var keyCode = e.keyCode;
if(keyCode == 13){
e.preventDefault();
}
});
$("#createProblemSummary").on("paste",function(e){
var pasteText = e.originalEvent.clipboardData.getData("text/plain");
pasteText = pasteText.replace(/\r\n/g,"");
pasteText = pasteText.replace(/\r/g,"");
pasteText = pasteText.replace(/\n/g,"");
document.execCommand("insertHTML", false, pasteText);
e.preventDefault();
});
//统计字数
$("#createProblemSummary").on("keydown cut copy paste",function(){
setTimeout(function(){
$("#createProblemModel").modal("adjustBackdrop");
var inputText = $("#createProblemSummary").text();
if(inputText.length > 500){
$("#problemSummaryLimit").show();
$("#problemSummaryLimit").css("color","red");
$("#problemSummaryLimit").text(inputText.length + " / 500");
}else if(inputText.length > 350){
$("#problemSummaryLimit").show();
$("#problemSummaryLimit").css("color","#838383");
$("#problemSummaryLimit").text(inputText.length + " / 500");
}else{
$("#problemSummaryLimit").hide();
}
},0);
});
$("#createProblemContent").on("keydown cut copy paste",function(){
setTimeout(function(){
var inputText = $("#createProblemContent").val();
if(inputText.length > 100){
$("#problemContentLimit").show();
$("#problemContentLimit").css("color","red");
$("#problemContentLimit").text(inputText.length + " / 100");
}else if(inputText.length > 80){
$("#problemContentLimit").show();
$("#problemContentLimit").css("color","#838383");
$("#problemContentLimit").text(inputText.length + " / 100");
}else{
$("#problemContentLimit").hide();
}
},0);
});
$("#createProblemCancel").on("click",function(){
$("#createProblemModel").modal("hide");
});
$("#createProblemSubmit").on("click",function(){
var problemContent = $("#createProblemContent").val();
var problemSummary = $("#createProblemSummary").text();
if(problemContent.length <= 0){
$("#drTipbar").drtipbar("showMsg","请输入问题");
return;
}
if(problemContent.length > 100){
$("#drTipbar").drtipbar("showMsg","问题内容最多100个字");
return;
}
if(problemSummary.length > 500){
$("#drTipbar").drtipbar("showMsg","问题描述最多500个字");
return;
}
//验证是否以问号结尾
var lastStr = problemContent.substr(problemContent.length - 1,problemContent.length);
if(lastStr != '?' && lastStr != ''){
$("#drTipbar").drtipbar("showMsg","问题必须以问号结尾");
return;
}
problemContent = encodeURIComponent(problemContent);
problemSummary = encodeURIComponent(problemSummary);
var markArr = $("#createProblemMarkContainer").markinput("getMarkArray");
if(markArr.length == 0){
$("#drTipbar").drtipbar("showMsg","问题必须带标签");
return;
}
var markDataString = JSON.stringify(markArr);
markDataString = encodeURIComponent(markDataString);
$("#createProblemSubmit").attr("disabled",true);
jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/problems/create",
data : "content="+problemContent+"&summary="+problemSummary+"&markstr="+markDataString,
beforeSend: function(request) {
$('#loadingBar').drloadingbar("startLoad");
},
success : function(data){
//disable不能去除在页面跳转前会有再被点的风险
$.drWindowLocation("/problems/get?guid="+data.guid,true);
},
error : function(data){
$('#loadingBar').drloadingbar("stopLoad");
$("#createProblemSubmit").removeAttr("disabled");
if(data.responseJSON == null){
$("#drTipbar").drtipbar("showMsg","网络不给力");
}else{
if(data.responseJSON.errCode != null){
$("#drTipbar").drtipbar("showMsg",data.responseJSON.errMessage);
}else{
$("#drTipbar").drtipbar("showMsg","网络不给力");
}
}
}
});
});
});
},
modalShow:function(){
$("#createProblemModel").modal("show");
}
};
$.fn.createproblem = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.createproblem' );
}
};
$.fn.createproblem.options = {};
})( jQuery );

View File

@@ -0,0 +1,71 @@
/**
* file-input.js
* target container must be id "preview"
*/
function previewImage(file,className,id)
{
var MAXWIDTH,MAXHEIGHT;
var div = $('#'+id).get(0);
if(className==='preview-long'){
MAXWIDTH = 200;
MAXHEIGHT = 356;
}
else if(className==='preview-short'){
MAXWIDTH = 200;
MAXHEIGHT = 300;
}
else{
MAXWIDTH = 120;
MAXHEIGHT = 120;
}
if (file.files && file.files[0])
{
div.innerHTML = '<img class=imghead>';
var img = $('#'+id).find('.imghead').get(0);
img.onload = function(){
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
img.width = rect.width;
img.height = rect.height;
img.style.marginLeft = rect.left+'px';
img.style.marginTop = rect.top+'px';
}
var reader = new FileReader();
reader.onload = function(evt){img.src = evt.target.result;}
reader.readAsDataURL(file.files[0]);
}
else
{
var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
file.select();
var src = document.selection.createRange().text;
div.innerHTML = '<img class=imghead>';
var img = $('#'+id).find('.imghead').get(0);
img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height);
div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;margin-left:"+rect.left+"px;"+sFilter+src+"\"'></div>";
}
$('.file').attr('name','image');
}
function clacImgZoomParam( maxWidth, maxHeight, width, height ){
var param = {top:0, left:0, width:width, height:height};
if( width>maxWidth || height>maxHeight )
{
rateWidth = width / maxWidth;
rateHeight = height / maxHeight;
if( rateWidth > rateHeight )
{
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
}else
{
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
}
param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
}

View File

@@ -0,0 +1,39 @@
/**
* form validation
*/
function formValidation(_element){
if(_element.next('.help-block').length<1){
var $help_block=$('<span class="help-block"></span>');
$help_block.insertAfter(_element);
}
// 验证错误
if(!_element.valid()){
_element.next('.help-block').children('.iconfont.success').remove();
if(_element.next('.help-block').children('.iconfont').length<1){
var $error_icon=$('<i class="iconfont fl error" >&#xe601;</i>');
$error_icon.insertBefore(_element.next('.help-block').children('h5'));
}
}
// 验证成功
else{
_element.next('.help-block').children('.iconfont.error').remove();
if(_element.next('.help-block').children('.iconfont').length<1){
var $success_icon=$('<i class="iconfont fl success" >&#xe605;</i>');
$success_icon.insertBefore(_element.next('.help-block').children('h5'));
}
}
}
function errorMessageShow(error,element){
if(element.next('.help-block').length<1){
var $help_block=$('<span class="help-block"></span>');
$help_block.insertAfter(element);
}
error.appendTo(element.next('.help-block'));
element.next('.help-block').children('.iconfont.success').remove();
if(element.next('.help-block').children('.iconfont').length<1){
var $error_icon=$('<i class="iconfont fl error" >&#xe601;</i>');
$error_icon.insertBefore(element.next('.help-block').children('h5'));
}
}

View File

@@ -0,0 +1,16 @@
/*! glDatePicker v2.0 | Tue Jan 1 2013 | http://glad.github.com/glDatePicker/ */;
(function(){$.fn.glDatePicker=function(a){var G=this.data("glDatePicker");return!G?this.each(function(){return $(this).data("glDatePicker",new O(this,a))}):!0===a?G:this};$.fn.glDatePicker.defaults={cssName:"default",zIndex:1E3,borderSize:1,calendarOffset:{x:0,y:1},showAlways:!1,hideOnClick:!0,allowMonthSelect:!0,allowYearSelect:!0,todayDate:new Date,selectedDate:null,prevArrow:"\u25c4",nextArrow:"\u25ba",selectableDates:null,selectableDateRange:null,specialDates:null,selectableMonths:null,selectableYears:null,
selectableDOW:null,monthNames:null,dowNames:null,dowOffset:0,onClick:function(a,G,g){a.val(g.toLocaleDateString())},onHover:function(){},onShow:function(a){a.show()},onHide:function(a){a.hide()},firstDate:null};var O=function(){function a(a,g){var d=this;d.el=$(a);var b=d.el;d.options=$.extend(!0,{},$.fn.glDatePicker.defaults,g);var c=d.options;d.calendar=$($.find("[gldp-el="+b.attr("gldp-id")+" ]"));c.selectedDate=c.selectedDate||c.todayDate;c.firstDate=(new Date(c.firstDate||c.selectedDate))._first();
(b.attr("gldp-id")||"").length||b.attr("gldp-id","gldp-"+Math.round(1E10*Math.random()));b.addClass("gldp-el").bind("click",function(b){d.show(b)}).bind("focus",function(b){d.show(b)});d.calendar.length&&!c.showAlways&&d.calendar.hide();$(document).bind("mouseup",function(a){var a=a.target,c=d.calendar;!b.is(a)&&(!c.is(a)&&0===c.has(a).length&&c.is(":visible"))&&d.hide()});d.render()}a.prototype={show:function(){$.each($(".gldp-el").not(this.el),function(a,g){if(g.length)g.options.onHide(g.calendar)});
this.options.onShow(this.calendar)},hide:function(){if(this.options&&!this.options.showAlways)this.options.onHide(this.calendar)},render:function(a){var g=this,d=g.el,b=g.options,c=g.calendar,j="gldp-"+b.cssName,t=b.todayDate._val(),u=t.time,h=b.borderSize+"px",y=function(b,m,a){for(var c=[],e=b;e<=m;e++)c.push(e);if(a){var d=[];$.each(a,function(a,c){c>=b&&(c<=m&&0>d._indexOf(c))&&d.push(c)});c=d.length?d:c}c.sort();return c},H=y(0,11,b.selectableMonths),v=y(t.year-5,t.year+5,b.selectableYears),
y=y(0,6,b.selectableDOW),z=b.dowNames||"Sun Mon Tue Wed Thu Fri Sat".split(" "),t=b.monthNames||"January February March April May June July August September October November December".split(" "),f=d.outerWidth(),e,k=f/7+6*(b.borderSize/7),f=f/8+7*(b.borderSize/8);c.length?eval(c.data("is"))||(f=c.outerWidth(),e=c.outerHeight(),k=f/7+6*(b.borderSize/7),f=e/8+7*(b.borderSize/8)):(g.calendar=c=$("<div/>").attr("gldp-el",d.attr("gldp-id")).data("is",!0).css({display:b.showAlways?void 0:"none",zIndex:b.zIndex,
width:7*k+"px"}),$("body").append(c));d.is(":visible")||c.hide();c.removeClass().addClass(j).children().remove();j=function(){var i=d.offset();c.css({top:i.top+d.outerHeight()+b.calendarOffset.y+"px",left:i.left+b.calendarOffset.x+"px"})};$(window).resize(j);j();var j={width:k+"px",height:f+"px",lineHeight:f+"px"},f=function(i){for(var m=new Date(b.firstDate),i=i||0;;){m.setMonth(m.getMonth()+i);m.setDate(Math.min(1,m._max()));if(0==i)break;var c=m._val(),a=c.year;if(-1!=H._indexOf(c.month))if(-1!=
v._indexOf(a))break;else if(a<v[0]||a>v[v.length-1])return null}return m},A=f(-1),B=f(1),f=b.firstDate=f();e=f._val();var I=e.month,J=e.year,f=new Date(f);e=Math.abs(Math.min(6,Math.max(0,b.dowOffset)));var l=f.getDay()-e,l=1>l?-7-l:-l,z=z.concat(z).slice(e,e+7);f._add(l);e=$("<div/>").addClass(" core border monyear ").css($.extend({},j,{borderWidth:h+" 0 0 "+h})).append($("<a/>").addClass("prev-arrow"+(A?"":"-off")).html(b.prevArrow)).mousedown(function(){return!1}).click(function(i){""!=b.prevArrow&&
A&&(i.stopPropagation(),A&&(b.firstDate=A,g.render()))});k=5*k-5*b.borderSize+b.borderSize;k=$("<div/>").addClass(" core border monyear title").css($.extend({},j,{width:k+"px",borderTopWidth:h,marginLeft:"-"+h}));l=$("<div/>").addClass(" core border monyear ").css($.extend({},j,{marginLeft:"-"+h,borderWidth:h+" "+h+" 0 0"})).append($("<a/>").addClass("next-arrow"+(B?"":"-off")).html(b.nextArrow)).mousedown(function(){return!1}).click(function(i){""!=b.nextArrow&&B&&(i.stopPropagation(),B&&(b.firstDate=
B,g.render()))});c.append(e).append(k).append(l);for(l=e=0;7>e;e++)for(var q=0;7>q;q++,l++){var C=new Date(f),n="day",r=b.zIndex+l,w=$("<div/>");if(e){C._add(q+7*(e-1));var p=C._val(),x=p.time,K=null,s=!0,D=function(b,a){!0===b.repeatYear&&a.setYear(p.year);!0===b.repeatMonth&&a.setMonth(p.month);return a._val()};w.html(p.date);b.selectableDateRange&&(s=!1,$.each(b.selectableDateRange,function(b,a){var c=a.from,d=a.to||null,d=d||new Date(a.from.getFullYear(),a.from.getMonth(),a.from._max()),c=D(a,
c),d=D(a,d);if(x>=c.time&&x<=d.time)return s=!0}));if(b.selectableDates){if(b.selectableDateRange&&!s||s&&!b.selectableDateRange)s=!1;$.each(b.selectableDates,function(b,a){if(D(a,a.date).time==x)return s=!0})}!s||0>v._indexOf(p.year)||0>H._indexOf(p.month)||0>y._indexOf(p.day)?n="noday":(n="sun mon tue wed thu fri sat".split(" ")[p.day],I!=p.month&&(n+=" outday"),u==x&&(n="today",r+=50),b.selectedDate._time()==x&&(n="selected",r+=51),b.specialDates&&$.each(b.specialDates,function(b,a){D(a,a.date).time==
x&&(n=a.cssClass||"special",r+=52,K=a.data)}),w.mousedown(function(){return!1}).hover(function(a){a.stopPropagation();a=$(this).data("data");b.onHover(d,w,a.date,a.data)}).click(function(a){a.stopPropagation();a=$(this).data("data");b.selectedDate=b.firstDate=a.date;g.render(function(){!b.showAlways&&b.hideOnClick&&g.hide()});b.onClick(d,$(this),a.date,a.data)}))}else n="dow",w.html(z[q]),C=null;$.extend(j,{borderTopWidth:h,borderBottomWidth:h,borderLeftWidth:0<e||!e&&!q?h:0,borderRightWidth:0<e||
!e&&6==q?h:0,marginLeft:0<q?"-"+h:0,marginTop:0<e?"-"+h:0,zIndex:r});w.data("data",{date:C,data:K}).addClass(" core border "+n).css(j);c.append(w)}var N=function(a){b.allowMonthSelect&&(L.css({display:!a?"none":"inline-block"}),E.css({display:!a?"inline-block":"none"}));b.allowYearSelect&&(M.css({display:a?"none":"inline-block"}),F.css({display:a?"inline-block":"none"}))},u=function(){b.firstDate=new Date(F.val(),E.val(),1);g.render()},E=$("<select/>").hide().change(u),F=$("<select/>").hide().change(u),
L=$("<span/>").html(t[I]).mousedown(function(){return!1}).click(function(a){a.stopPropagation();N(!1)}),M=$("<span/>").html(J).mousedown(function(){return!1}).click(function(a){a.stopPropagation();N(!0)});$.each(t,function(a,c){if(b.allowMonthSelect&&-1!=H._indexOf(a)){var d=$("<option/>").html(c).attr("value",a);a==I&&d.attr("selected","selected");E.append(d)}});$.each(v,function(a,c){if(b.allowYearSelect){var d=$("<option/>").html(c).attr("value",c);c==J&&d.attr("selected","selected");F.append(d)}});
u=$("<div/>").append(L).append(E).append(M).append(F);k.children().remove();k.append(u);(a||function(){})()}};return a}();Date.prototype._clear=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this};Date.prototype._time=function(){return this._clear().getTime()};Date.prototype._max=function(){return[31,28+(1==(new Date(this.getYear(),1,29)).getMonth()?1:0),31,30,31,30,31,31,30,31,30,31][this.getMonth()]};Date.prototype._add=function(a){this.setDate(this.getDate()+
a)};Date.prototype._first=function(){var a=new Date(this);a.setDate(1);return a};Date.prototype._val=function(){this._clear();return{year:this.getFullYear(),month:this.getMonth(),date:this.getDate(),time:this.getTime(),day:this.getDay()}};Array.prototype._indexOf=function(a){return $.inArray(a,this)}})();

View File

@@ -0,0 +1,39 @@
jQuery.fn.extend({
imgPreview: function (opts) {
var _self = this,
_this = $(this);
opts = jQuery.extend({
id: "imgPreview",
width: '100px',
height: '100px',
imgType: ["gif", "jpeg", "jpg", "bmp", "png"],
callback: function () {}
}, opts || {});
$("#" + opts.id).css({
'width': opts.width,
'height': opts.height
});
_self.getObjectURL = function (file) {
var url = null;
if (window.createObjectURL != undefined) {
url = window.createObjectURL(file);
} else if (window.URL != undefined) {
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) {
url = window.webkitURL.createObjectURL(file);
}
return url;
};
_this.change(function () {
if (this.value) {
if (!RegExp("\.(" + opts.imgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
alert("选择文件错误,图片类型必须是" + opts.imgType.join("") + "中的一种");
this.value = "";
return false;
}
$("#" + opts.id).attr('src', _self.getObjectURL(this.files[0]));
opts.callback();
}
})
}
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,37 @@
/**
* LeftBar Generate
*/
var LeftBar=function(){
var MarkCategory=function(text,markcategories_Array){
/* LeftBar init*/
$('.leftbar .title').text(text);
$('.mark-category li:first').addClass('active');
/* 切换标签类别 */
$(document).on('click','.mark-category li',function(){
var $this=$(this);
$('.mark-category li').removeClass('active');
$this.addClass('active');
$('.mark-category').hide();
$('.leftbar .title').text($this.text());
var index=$this.attr('id');
$('.bar-content li:not(:first)').remove();
for(var i=0;i<markcategories_Array[index].marks.length;i++){
$('.bar-content').append('<li><a href="/marks/listscreenshotbymark?mark_id='+markcategories_Array[index].marks[i].id+'">'+markcategories_Array[index].marks[i].name+'</a></li>');
}
})
/* 显示隐藏标签类别 */
$(".dropdown-area").hover(function(){
$('.mark-category').stop().slideDown('fast');
},function(){
$('.mark-category').stop().slideUp('fast');
})
};
return {
init:function(text,markcategories_Array){
MarkCategory(text,markcategories_Array);
}
};
}();

View File

@@ -0,0 +1,334 @@
/**
* ajax load more data
*/
/**
* 加载更多(供index&标签详情使用)
*/
function loadData(params){
/* 打开页面首次加载数据 */
var returnJson={};
getReturnJson(returnJson,params);
/* 点击加载更多 */
$('.loadMore').click(function(){
/* 正常加载数据 */
if(returnJson.status===0){
params.page++;
getReturnJson(returnJson,params);
}
/* 没有更多数据 */
else if(returnJson.status===1){
$('.loadTips').text('没有更多数据').stop().fadeIn(500).fadeOut(1500);
}
/* 加载数据异常,重试 */
else{
getReturnJson(returnJson,params);
}
});
}
//获取ajax的success or error回调函数返回的JSON
function getReturnJson(returnJson,params){
Disabled($('.loadMore'),'');
Loading($('.loadMore'));
$.when(getScreenShotList(params.url,params.page))
.done(function(data){
returnJson.status=data.status;
returnJson.msg=data.msg;
})
.fail(function(data){
returnJson.status=data.status;
returnJson.msg=data.msg;
});
}
//获取ScreenShotList
/* 加载更多(供index&标签详情使用) */
function getScreenShotList(url,page){
var returnJson={};
var defer=$.Deferred();
/* ajax请求获取数据 */
$.ajax({
type:"GET",
url:url,
dataType:'json',
data:{
page:page
},
contentType : 'application/json',
success:function(data,status){
console.log(status);
console.log('screenshots:'+data);
//获取json数据不为空
if(data.content.length>0){
/* 遍历screenshorts */
$.each(data.content,function(key,value){
$('.shot-container').append(
'<div class="shot third column" id="screenshot'+value.id+'" data-application="">'+
'<div class="shot-image">'+
'<div class="actions">'+
'</div>'+
'<img src="http://www.placehold.it/286x508/EFEFEF/AAAAAA&text=egggo.cn" data-url="'+value.pic.mediumFileUrl+'" class="unload"/>'+
'<div class="cover"></div>'+
'</div>'+
'<div class="shot-info">'+
'<div class="text-overflow"><a class="two-thirds dark-gray text-align-left" href="/applications/get/'+value.application.id+'" target="_blank">'+value.application.name+'</a></div>'+
'<div class="third text-align-right fr"><i class="iconfont like-count inline-block">&#xe606;</i><h6>'+value.likeCount+'</h6></div>'+
'<div id="'+value.id+'" class="mark-container light-gray" name="screenshot-mark-container">'+
'<h6 class="text-overflow">'+
'</h6>'+
'</div>'+
'</div>'+
'</div>'
);
var marks=[],screenShotContents=[],application={};
/* LikeOrNot */
if(value.isLiked===0){
$('#screenshot'+value.id).find('.actions').append(
'<a class="btn-like text-align-center" id="'+value.id+'" onclick="like(this,'+value.id+')">'+
'<i class="iconfont unlike inline-block is-hidden">&#xe606;</i>'+
'<i class="iconfont liked inline-block">&#xe607;</i>'+
'</a>'
);
}
else{
$('#screenshot'+value.id).find('.actions').append(
'<a class="btn-like text-align-center" id="'+value.id+'" onclick="unlike(this,'+value.id+')">'+
'<i class="iconfont unlike inline-block">&#xe606;</i>'+
'<i class="iconfont liked inline-block is-hidden">&#xe607;</i>'+
'</a>'
);
}
/* 遍历marks */
$.each(value.marks,function(k,v){
$('#screenshot'+value.id).find('.mark-container').find('.text-overflow').append(
'<a href="/screenshots/searchscreenshot?search='+v.name+'" target="_blank">'+v.name+'</a>'+
'<span> , </span>'
);
marks.push({
id:v.id,
name:v.name
});
});
/* 遍历ScreenshotsContent */
$.each(value.screenShotContents,function(k,v){
screenShotContents.push({
type:v.type,
url:v.pic.mediumFileUrl+'&method=attachment'
});
});
//浏览图片Modal需要的数据
var application={
screenShotId:value.id,
pic:value.pic.originFileUrl,
appVersion:value.appVersion,
likeCount:value.likeCount,
applicationName:value.application.name,
applicationIcon:value.application.icon.thumbFileUrl,
updatedTime:value.createdAt,
marks:marks,
screenShotContents:screenShotContents
};
$('#screenshot'+value.id).data('application',application)
.find('.mark-container').find('span:last').remove();
});
lazyload();
returnJson.status=0;
returnJson.msg='正常加载数据';
Enabled($('.loadMore'),'加载更多');
}
else{
console.log('page out of range');
$('.loadTips').text('没有更多数据').stop().fadeIn(500).fadeOut(1500);
returnJson.status=1;
returnJson.msg='没有更多数据';
Enabled($('.loadMore'),'没有更多了');
}
$('#footer-total-count,#resultsCount').text(data.count);
defer.resolve(returnJson);
},
error:function(data,status){
console.log(status);
Enabled($('.loadMore'),'加载更多');
$('.loadTips').text('加载数据异常,请重试!').stop().fadeIn(500).fadeOut(2000);
returnJson.status=2;
returnJson.msg='加载数据异常';
defer.reject(returnJson);
}
});
return defer.promise();
}
/**
* 加载更多(供搜索标签结果使用)
*/
function loadSearchScreenshotsData(params,keyword){
/* 打开页面首次加载数据 */
var returnJson={};
getSearchReturnJson(returnJson,params,keyword);
/* 点击加载更多 */
$('.loadMore').click(function(){
/* 正常加载数据 */
if(returnJson.status===0){
params.page++;
getSearchReturnJson(returnJson,params,keyword);
}
/* 没有更多数据 */
else if(returnJson.status===1){
$('.loadTips').text('没有更多数据').stop().fadeIn(500).fadeOut(1500);
}
/* 加载数据异常,重试 */
else{
getSearchReturnJson(returnJson,params,keyword);
}
});
}
//获取ajax的success or error回调函数返回的JSON
function getSearchReturnJson(returnJson,params,keyword){
Disabled($('.loadMore'),'');
Loading($('.loadMore'));
$.when(getSearchScreenShotList(params.url,params.page,keyword))
.done(function(data){
returnJson.status=data.status;
returnJson.msg=data.msg;
lazyload();
})
.fail(function(data){
returnJson.status=data.status;
returnJson.msg=data.msg;
});
}
//获取SearchScreenShotList
function getSearchScreenShotList(url,page,keyword){
var returnJson={};
var defer=$.Deferred();
/* ajax请求获取数据 */
$.ajax({
type:"GET",
url:url,
dataType:'json',
data:{
page:page
},
contentType : 'application/json',
success:function(data,status){
console.log(status);
console.log('screenshots:'+data);
//获取json数据不为空
if(data.content.length>0){
/* 遍历screenshorts */
$.each(data.content,function(key,value){
$('.shot-container').append(
'<div class="shot third column" id="screenshot'+value.id+'" data-application="">'+
'<div class="shot-image">'+
'<div class="actions">'+
'</div>'+
'<img src="http://www.placehold.it/286x508/EFEFEF/AAAAAA&text=egggo.cn" data-url="'+value.pic.mediumFileUrl+'" class="unload"/>'+
'<div class="cover"></div>'+
'</div>'+
'<div class="shot-info">'+
'<div class="text-overflow"><a class="two-thirds dark-gray text-align-left" href="/applications/get/'+value.application.id+'" target="_blank">'+value.application.name+'</a></div>'+
'<div class="third text-align-right fr"><i class="iconfont like-count inline-block">&#xe606;</i><h6>'+value.likeCount+'</h6></div>'+
'<div id="'+value.id+'" class="mark-container light-gray" name="screenshot-mark-container">'+
'<h6 class="text-overflow">'+
'</h6>'+
'</div>'+
'</div>'+
'</div>'
);
var marks=[],screenShotContents=[],application={};
/* LikeOrNot */
if(value.isLiked===0){
$('#screenshot'+value.id).find('.actions').append(
'<a class="btn-like text-align-center" id="'+value.id+'" onclick="like(this,'+value.id+')">'+
'<i class="iconfont unlike inline-block is-hidden">&#xe606;</i>'+
'<i class="iconfont liked inline-block">&#xe607;</i>'+
'</a>'
);
}
else{
$('#screenshot'+value.id).find('.actions').append(
'<a class="btn-like text-align-center" id="'+value.id+'" onclick="unlike(this,'+value.id+')">'+
'<i class="iconfont unlike inline-block">&#xe606;</i>'+
'<i class="iconfont liked inline-block is-hidden">&#xe607;</i>'+
'</a>'
);
}
/* 遍历marks */
$.each(value.marks,function(k,v){
if(v.name.indexOf(keyword)>-1){
$('#screenshot'+value.id).find('.mark-container').find('.text-overflow').append(
'<a href="/screenshots/searchscreenshot?search='+v.name+'" class="highlight" target="_blank">'+v.name+'</a>'+
'<span> , </span>'
);
}else{
$('#screenshot'+value.id).find('.mark-container').find('.text-overflow').append(
'<a href="/screenshots/searchscreenshot?search='+v.name+'" target="_blank">'+v.name+'</a>'+
'<span> , </span>'
);
}
marks.push({
id:v.id,
name:v.name
});
});
/* 遍历ScreenshotsContent */
$.each(value.screenShotContents,function(k,v){
screenShotContents.push({
type:v.type,
url:v.pic.mediumFileUrl+'&method=attachment'
});
});
//浏览图片Modal需要的数据
var application={
screenShotId:value.id,
pic:value.pic.originFileUrl,
appVersion:value.appVersion,
likeCount:value.likeCount,
applicationName:value.application.name,
applicationIcon:value.application.icon.thumbFileUrl,
updatedTime:value.createdAt,
marks:marks,
screenShotContents:screenShotContents
};
$('#screenshot'+value.id).data('application',application)
.find('.mark-container').find('span:last').remove();
});
lazyload();
returnJson.status=0;
returnJson.msg='正常加载数据';
Enabled($('.loadMore'),'加载更多');
}
else{
console.log('page out of range');
$('.loadTips').text('没有更多数据').stop().fadeIn(500).fadeOut(1500);
returnJson.status=1;
returnJson.msg='没有更多数据';
Enabled($('.loadMore'),'没有更多了');
}
$('#footer-total-count,#resultsCount').text(data.count);
defer.resolve(returnJson);
},
error:function(data,status){
console.log(status);
Enabled($('.loadMore'),'加载更多');
$('.loadTips').text('加载数据异常,请重试!').stop().fadeIn(500).fadeOut(2000);
returnJson.status=2;
returnJson.msg='加载数据异常';
defer.reject(returnJson);
}
});
return defer.promise();
}

View File

@@ -0,0 +1,88 @@
(function( $ ){
var methods = {
init : function( options ){
var $this = this;
options = $.extend( $.fn.drloadingbar.options, options );
$this.data("isLoading",false);
$this.data("loadingLoop",false);
return this.each(function(){
});
},
startLoad:function(){
return this.each(function(){
var $this = $(this);
function loading(){
$this.removeClass("loadingBarLoadStaticPhase").addClass("loadingBarLoadPhase1");
$this.one(($.getTransitionEnd()).end, function() {
//$this.one('webkitTransitionEnd', function() {
$this.removeClass("loadingBarLoadPhase1").addClass("loadingBarLoadStaticPhase");
if($this.data("loadingLoop")){
$this.data("nextTimer",setTimeout(loading,500));
//setTimeout(loading,500);
//loading();
}else{
//console.log("已停止");
$this.data("isLoading",false);
}
});
}
if(!$this.data("isLoading")){
$this.data("isLoading",true);
$this.data("loadingLoop",true);
//console.log("开始");
loading();
}else{
//console.log("运行中");
}
});
},
stopLoad:function(){
return this.each(function(){
var $this = $(this);
//console.log("结束");
$this.data("loadingLoop", false);
var timer = $this.data("nextTimer");
if(timer != null){
clearTimeout(timer);
$this.data("nextTimer",null);
$this.data("isLoading",false);
}
});
}
};
$.fn.drloadingbar = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.drloadingbar' );
}
};
$.fn.drloadingbar.options = {};
})( jQuery );

View File

@@ -0,0 +1,482 @@
(function( $ ){
var methods = {
init : function( options ){
var $this = this;
options = $.extend( $.fn.markinput.options, options );
return this.each(function(){
var $thisMarkInput = $(this);
var markData = options.markData;
if(markData == null){
markData = [];
}
$thisMarkInput .data("markData",markData);
var adjustLeftComponent = options.adjustLeftComponent;
if(adjustLeftComponent != null){
$thisMarkInput .data("adjustLeftComponent",adjustLeftComponent);
}
var $appendVar = $('<div id="drMarkInputContentContainer"><div id="drMarkInputContent" contentEditable="true" data-placeHolder="添加至多 3 个标签(输入标签后按回车确定)"></div></div>\
<div id="drMarkInputErrorPopoverContainer" style="display:none;">\
<div id="drMarkInputErrorPopover">\
<p id="drMarkInputErrorPopoverContent">输入内容过长</p>\
</div>\
</div>\
<div id="drMarkInputPopoverSearchContainer" style="display:none;">\
<ul id="drMarkInputPopoverSearch">\
</ul>\
</div>');
$thisMarkInput.append($appendVar);
for(var i = 0; i < markData.length; i++){
$element = $("<span></span>");
$element.text(markData[i]);
$element.addClass("drMarkSpanContainer");
$element.insertBefore($("#drMarkInputContentContainer"));
}
if(markData.length > 0){
$("#drMarkInputContent")[0].setAttribute("data-placeholder","");
}else{
$("#drMarkInputContent")[0].setAttribute("data-placeholder","添加至多 3 个标签(输入标签后按回车确定)");
}
function isMarkInputErrorShown(){
return $("#drMarkInputContent").data('bs.popover').tip().hasClass('in');
}
function isMarkSearchResShown(){
return $("#drMarkInputContentContainer").data('bs.popover').tip().hasClass('in');
}
function deleteOneMark($element){
var markData = $thisMarkInput.data("markData");
if(markData.length <= 0){
return;
}
if($element == null){
//删除最后一个
$(".drMarkSpanContainer")[markData.length - 1].remove();
markData.splice(markData.length-1,1);
if(markData.length > 0){
$("#drMarkInputContent")[0].setAttribute("data-placeholder","");
}else{
$("#drMarkInputContent")[0].setAttribute("data-placeholder","添加至多 3 个标签(输入标签后按回车确定)");
}
}else{
var tagName = $element.text();
for(var i = 0; i < markData.length; i++){
if(markData[i] == tagName){
markData.splice(i,1);
break;
}
}
if(markData.length > 0){
$("#drMarkInputContent")[0].setAttribute("data-placeholder","");
}else{
$("#drMarkInputContent")[0].setAttribute("data-placeholder","添加至多 3 个标签(输入标签后按回车确定)");
}
$element.remove();
}
}
function addOneMark(markName){
var markData = $thisMarkInput.data("markData");
if(markName == ""){
return;
}else if(markName.length > 30){
//提示长度
$("#drMarkInputErrorPopoverContent").text("标签最大字数为 30 个");
if(isMarkInputErrorShown()){
}else{
$("#drMarkInputContent").popover("show");
}
return;
}
for(var i = 0; i < markData.length; i++){
if(markName == markData[i]){
//提示重复
$("#drMarkInputErrorPopoverContent").text("已经添加了该标签");
if(isMarkInputErrorShown()){
}else{
$("#drMarkInputContent").popover("show");
}
return;
}
}
markData.push(markName);
if(markData.length > 0){
$("#drMarkInputContent")[0].setAttribute("data-placeholder","");
}else{
$("#drMarkInputContent")[0].setAttribute("data-placeholder","添加至多 3 个标签(输入标签后按回车确定)");
}
$element = $("<span></span>");
$element.text(markName);
$element.addClass("drMarkSpanContainer");
$element.insertBefore($("#drMarkInputContentContainer"));
$("#drMarkInputContent").text("");
if(isMarkSearchResShown()){
$("#drMarkInputContentContainer").popover("hide");
}
}
function searchMarkKeyword(keyword){
if(keyword == null || keyword == ""){
if(isMarkSearchResShown()){
$("#drMarkInputContentContainer").popover("hide");
}
return;
}
keyword = encodeURIComponent(keyword);
var jRequest = $.ajax({
type : "GET",
contentType : "application/x-www-form-urlencoded",
url : "/marks/searchforchoose?q="+keyword,
beforeSend:function(){
$('#loadingBar').drloadingbar("startLoad");
var currentReq = $("#drMarkInputContentContainer").data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
success : function(data){
$('#loadingBar').drloadingbar("stopLoad");
var dataLength = data.length;
if(dataLength > 0){
if(isMarkSearchResShown()){
$("#drMarkInputContentContainer").popover("hide");
}
$("#drMarkInputPopoverSearch").empty();
for(var i = 0; i < dataLength; i++){
$element = $("<li class='drMarkInputPopoverSearchList'><span><strong>"+data[i].name+"</strong>"+data[i].useCount+"</span></li>");
$element.appendTo($("#drMarkInputPopoverSearch"));
}
$("#drMarkInputContentContainer").popover("show");
}else{
if(isMarkSearchResShown()){
$("#drMarkInputContentContainer").popover("hide");
}
}
},
error : function(data){
if(data.statusText=="abort"){
return;
}
$('#loadingBar').drloadingbar("stopLoad");
}});
$("#drMarkInputContentContainer").data("jRequest",jRequest);
}
$("#drMarkInputContent").on("paste",function(e){
var markData = $thisMarkInput.data("markData");
if(markData.length >= 3){
//提示只能输入3个标签
$("#drMarkInputErrorPopoverContent").text("只能添加 3 个标签");
if(isMarkInputErrorShown()){
}else{
$("#drMarkInputContent").popover("show");
}
e.preventDefault();
return
}
if(isMarkInputErrorShown()){
$("#drMarkInputContent").popover("hide");
}
var pasteText = e.originalEvent.clipboardData.getData("text/plain");
pasteText = pasteText.replace(/\r\n/g,"");
pasteText = pasteText.replace(/\r/g,"");
pasteText = pasteText.replace(/\n/g,"");
document.execCommand("insertHTML", false, pasteText);
e.preventDefault();
searchMarkKeyword($(this).text());
});
$("#drMarkInputContent").on("blur",function(e){
if(isMarkInputErrorShown()){
$("#drMarkInputContent").popover("hide");
}
if(isMarkSearchResShown()){
setTimeout(function(){
//延迟200毫秒触发否则若点击在content cell内部则立马被hide掉无法触发
$("#drMarkInputContentContainer").popover("hide");
},200);
}
});
$("#drMarkInputContent").on("keydown",function(e){
var markData = $thisMarkInput.data("markData");
var keyCode = e.keyCode;
if(keyCode == 8 || keyCode == 46){
if(isMarkInputErrorShown()){
$("#drMarkInputContent").popover("hide");
}
if($(this).text() == "" && markData.length > 0){
deleteOneMark();
e.preventDefault();
return;
}
}
if(markData.length >= 3){
$(this).text("");
//提示只能输入3个标签
$("#drMarkInputErrorPopoverContent").text("只能添加 3 个标签");
if(isMarkInputErrorShown()){
}else{
$("#drMarkInputContent").popover("show");
}
e.preventDefault();
return;
}
if(isMarkInputErrorShown()){
$("#drMarkInputContent").popover("hide");
}
if(keyCode == 13 || keyCode == 108){
e.preventDefault();
if(isMarkInputErrorShown()){
$("#drMarkInputContent").popover("hide");
}
//处理标签
var content = "";
if(isMarkSearchResShown() && $(".drMarkInputPopoverSearchList.isActive").length > 0){
content = $(".drMarkInputPopoverSearchList.isActive span strong").text();
$("#drMarkInputContentContainer").popover("hide");
}else{
content = $(this).text();
}
var checkContent = $.trim(content);
if(checkContent != ""){
addOneMark(content);
}
return;
}else if(keyCode==40){
//下
if(isMarkSearchResShown()){
if($(".drMarkInputPopoverSearchList.isActive").length > 0){
if($(".drMarkInputPopoverSearchList.isActive")[0].nextSibling == null){
//指向第一个
$(".drMarkInputPopoverSearchList.isActive").removeClass("isActive");
$(".drMarkInputPopoverSearchList").first().addClass("isActive");
}else{
//指向下一个
var nextNode = $($(".drMarkInputPopoverSearchList.isActive")[0].nextSibling);
$(".drMarkInputPopoverSearchList.isActive").removeClass("isActive");
nextNode.addClass("isActive");
}
}else{
//指向第一个
$(".drMarkInputPopoverSearchList").first().addClass("isActive");
}
e.preventDefault();
}
}else if(keyCode==38){
//上
if(isMarkSearchResShown()){
if($(".drMarkInputPopoverSearchList.isActive").length > 0){
if($(".drMarkInputPopoverSearchList.isActive")[0].previousSibling == null){
//指向最后一个
$(".drMarkInputPopoverSearchList.isActive").removeClass("isActive");
$(".drMarkInputPopoverSearchList").last().addClass("isActive");
}else{
//指向上一个
var previousNode = $($(".drMarkInputPopoverSearchList.isActive")[0].previousSibling);
$(".drMarkInputPopoverSearchList.isActive").removeClass("isActive");
previousNode.addClass("isActive");
}
}else{
//指向最后一个
$(".drMarkInputPopoverSearchList").last().addClass("isActive");
}
e.preventDefault();
}
}else{
var $this = $(this);
setTimeout(function(){
searchMarkKeyword($this.text());
}, 100);
}
});
$("#drMarkInputContent").popover({
trigger:"manual",
html : true,
animation:false,
placement:"top",
content: function(){
return $('#drMarkInputErrorPopoverContainer').html();
}
});
$("#drMarkInputContent").on('hide.bs.popover', function(e){
if(e.target != $("#drMarkInputContent")[0]){
return;
}
$('#drMarkInputErrorPopoverContainer').append($('#drMarkInputErrorPopover'));
});
$("#drMarkInputContent").on('shown.bs.popover', function(e){
if(e.target != $("#drMarkInputContent")[0]){
return;
}
$('#drMarkInputErrorPopoverContainer #drMarkInputErrorPopover').remove();
});
$("#drMarkInputContentContainer").popover({
trigger:"manual",
html : true,
animation:false,
placement:"bottom",
content: function(){
return $('#drMarkInputPopoverSearchContainer').html();
}
});
$("#drMarkInputContentContainer").on('hide.bs.popover',function(e){
if(e.target != $("#drMarkInputContentContainer")[0]){
return;
}
$('#drMarkInputPopoverSearchContainer').append($('#drMarkInputPopoverSearch'));
});
$("#drMarkInputContentContainer").on('shown.bs.popover',function(e){
if(e.target != $("#drMarkInputContentContainer")[0]){
return;
}
var topVal = parseInt($('#drMarkInputContentContainer+.popover').css('top').substr(0,$('#drMarkInputContentContainer+.popover').css('top').length - 2));
$('#drMarkInputContentContainer+.popover').css('top',(topVal - 15 ) + 'px');
//重新计算left
var left = 0;
var adjustLeftComponent = $thisMarkInput.data("adjustLeftComponent");
if(adjustLeftComponent == null){
left = $("#drMarkInputContentContainer").offset().left;
}else{
var left1 = $("#drMarkInputContentContainer").offset().left;
var left2 = adjustLeftComponent.offset().left;
left = left1 - left2;
}
//var left = $("#markInputContentContainer+.popover").css('left');
var inText = $("#drMarkInputContent").text();
$('#drMarkInputContentContainer+.popover').css('left', (left - 20) + 'px');
$('#drMarkInputContentContainer+.popover .arrow').css('left', (20 + 14 * inText.length / 2 ) + 'px');
$('#drMarkInputPopoverSearchContainer #drMarkInputPopoverSearch').remove();
$("#drMarkInputPopoverSearch").off("mouseenter");
$("#drMarkInputPopoverSearch").off("mouseleave");
$("#drMarkInputPopoverSearch").off("click");
$("#drMarkInputPopoverSearch").on("mouseenter",".drMarkInputPopoverSearchList",function(){
if(!$(this).hasClass("isActive")){
$(".drMarkInputPopoverSearchList.isActive").each(function(){
$(this).removeClass("isActive");
});
$(this).addClass("isActive");
}
});
$("#drMarkInputPopoverSearch").on("mouseleave",".drMarkInputPopoverSearchList",function(){
$(this).removeClass("isActive");
});
$("#drMarkInputPopoverSearch").on("click",".drMarkInputPopoverSearchList.isActive",function(){
//选中输入
var content = $(this).find("span strong").text();
addOneMark(content);
$("#drMarkInputContent").focus();
});
});
$thisMarkInput.on("click",".drMarkSpanContainer",function(e){
deleteOneMark($(this));
});
});
},
getMarkArray:function(){
return this.data("markData");
}
};
$.fn.markinput = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.markinput' );
}
};
$.fn.markinput.options = {};
})( jQuery );

View File

@@ -0,0 +1,107 @@
(function( $ ){
var methods = {
init : function( options ){
var $this = this;
options = $.extend( $.fn.drnavbar.options, options );
$this.data('previousScroll', 0);
$('#drNavbarUser').click(function(e){
var isVisible = $(".drNavbarPopover").is(":visible");
if(isVisible){
$this.drnavbar("hideDropDownMenu");
}else{
$('#drNavbarUser').trigger("drNavbarPopoverFocus");
}
});
//focusout在safari下无法获取related target不得已加入mousedown check focus out
function installMouseDown(){
$(document).one("mousedown",function(e){
var target = e.target;
if(target != null){
if(target==$('#drNavbarUser')[0]){
return;
}
var targetParents = $(target).parents();
for(var i = 0; i < targetParents.length;i++){
var parent = targetParents[i];
if(parent == $(".drNavbarDropDownMenu")[0]){
installMouseDown();
return;
}
}
}
$('#drNavbarUser').trigger("click");
});
}
$('#drNavbarUser').on("drNavbarPopoverFocus",function(){
$this.drnavbar("showDropDownMenu");
setTimeout(installMouseDown,200);
});
//设置
$("#drNavbarDropdownSetting").hover(function(){
$("#drNavbarDropdownSetting span").css("color","black");
},function(){
$("#drNavbarDropdownSetting span").css("color","");
});
//退出
$("#drNavbarDropdownLogout").hover(function(){
$("#drNavbarDropdownLogout span").css("color","black");
},function(){
$("#drNavbarDropdownLogout span").css("color","");
});
showDropDownMenu:function(){
$(".drNavbarPopover").show();
var deviceType = $.getDeviceWidthType();
var deviceWidth = $.getDeviceWidth();
var deviceHeight = $.getDeviceHeight();
if(deviceType == 1){
var top = 71;
var width = deviceWidth;
var height = deviceHeight - top;
var arrowTop = -14;
var arrowLeft = width - 38;
$(".drNavbarPopover").css("top",top+"px");
$(".drNavbarPopover").css("width",width+"px");
$(".drNavbarPopover").css("height",height+"px");
$(".drNavbarPopover").css("left","0px");
$(".drNavbarPopoverArrow").css("left",arrowLeft+"px");
}
},
hideDropDownMenu:function(){
$(".drNavbarPopover").hide();
$(".drNavbarPopover").css("top","");
$(".drNavbarPopover").css("width","");
$(".drNavbarPopover").css("height","");
$(".drNavbarPopover").css("left","");
$(".drNavbarPopoverArrow").css("left","");
}
};
$.fn.drnavbar = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.drnavbar' );
}
};
$.fn.drnavbar.options = {notificationUnReadTotalCount:0, personallettersUnReadTotalCount:0};
})( jQuery );

View File

@@ -0,0 +1,72 @@
/**
* pagination.js
* target container must be id "page-container"
*/
function setPage(currPage,totalCount,urlHeader) //currPage 当前页数; totalCount 总数量
{
var container = document.getElementById('page-container');
var iPageSize = 20; //每页的数量
var b = ((totalCount%iPageSize)!=0);
var iPageCount = parseInt(totalCount/iPageSize)+(b?1:0);//总共页数
//if (currPage > iPageCount) return false;
currPage = parseInt(currPage);
var sTemp = "";
var sTemp1 = "<div class=\"page-number-container inline-block\"><span class=\"page-number\">"+ currPage +"</span>/<span class=\"page-number\">"+ iPageCount +"</span></div>";
var sTemp2 = "<div class=\"page-btn-container inline-block\"><input type=\"text\" id=\"goPageNo\" value=\""+currPage+"\" class=\"search-area-for-page border text-align-center\" /><a class=\"btn inline-block border-btn page-btn\" type=\"button\" href=\"Javascript:toPage('"+urlHeader+"');\");\">跳转</a></div>"
if (totalCount==0)
{
sTemp = "无";
container.innerHTML = sTemp;
}
else if (iPageCount==1)
{
sTemp = "<a href='#' class='disabled'>上一页</a>"+ sTemp1 +"<a href='#' class='disabled'>下一页</a>";
container.innerHTML = sTemp +" "+ sTemp2 ;
}
else if (iPageCount==currPage)
{
sTemp = "<a href='#'>上一页</a>"+ sTemp1 +"<a href='#' class='disabled'>下一页</a>";
container.innerHTML = sTemp +" "+ sTemp2 ;
}
else if (currPage==1)
{
sTemp = "<a href='#' class='disabled'>上一页</a>"+ sTemp1 +"<a href='#'>下一页</a>";
container.innerHTML = sTemp +" "+ sTemp2 ;
}
else
{
sTemp = " <a href='#'>上一页</a>"+ sTemp1 +"<a href='#'>下一页</a>";
container.innerHTML = sTemp +" "+ sTemp2 ;
}
//事件点击
var pageClick = function() {
var oAlink = container.getElementsByTagName("a");
var inx = currPage; //初始的页码
if(oAlink.length > 1){
oAlink[0].onclick = function() { //点击上一页
if (inx == 1) {
return false;
}
inx--;
window.location.href=urlHeader+inx;
return false;
}
oAlink[1].onclick = function() { //点击下一页
if (inx == iPageCount) {
return false;
}
inx++;
//setPage(container, count, inx);
window.location.href=urlHeader+inx;
return false;
}
}
} ()
}
function toPage(s) {
var tempUrl = "";
tempUrl = s + document.getElementById('goPageNo').value;
window.location.href = tempUrl;
}

View File

@@ -0,0 +1,85 @@
(function($) {
$(document).ready(function(){
var currentPathName = window.location.pathname;
// 格式化粘贴文本控件初始化
$("#createPersonallettersContent").drcontenteditable("init");
// 取消
$("#createPersonallettersCancel").on("click", function(){
$("#createPersonallettersModel").modal("hide");
});
// 统计字数
$("#createPersonallettersContent").on("keydown cut copy paste", function(){
setTimeout(function(){
var inputText = $("#createPersonallettersContent").drcontenteditable("getContent");
$("#createPersonallettersModel").modal("adjustBackdrop");
if(inputText.length > 3000){
$("#personallettersContentLimit").show();
$("#personallettersContentLimit").css("color","red");
$("#personallettersContentLimit").text(inputText.length + " / 3000");
}else if(inputText.length > 2500){
$("#personallettersContentLimit").show();
$("#personallettersContentLimit").css("color","#838383");
$("#personallettersContentLimit").text(inputText.length + " / 3000");
}else{
$("#personallettersContentLimit").hide();
}
}, 0);
});
// 提交
$("#createPersonallettersSubmit").on("click", function(){
var toUserId = $(".drUserSpanContainer[data-userid]").attr("data-userid");
var content = $("#createPersonallettersContent").drcontenteditable("getContent");
if(!toUserId){
$("#drTipbar").drtipbar("showMsg","请选择收件人");
return;
}
if(content.length == 0){
$("#drTipbar").drtipbar("showMsg","私信内容不能为空");
return;
}
if(content.length > 3000){
$("#drTipbar").drtipbar("showMsg","私信内容最多3000个字");
return;
}
content = encodeURIComponent(content);
$("#createPersonallettersSubmit").attr("disabled",true);
jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/personalletters/create",
data : "content="+content+"&toUserId="+toUserId,
beforeSend : function(request) {
$('#loadingBar').drloadingbar("startLoad");
},
success : function(data){
$("#createPersonallettersContent").empty();
$('#loadingBar').drloadingbar("stopLoad");
$("#drTipbar").drtipbar("showMsg","发送成功");
$("#createPersonallettersModel").modal("hide");
$('#createPersonallettersModel').on('hidden.bs.modal', function (e) {
$("#createPersonallettersSubmit").removeAttr("disabled");
});
if(currentPathName == "/personalletters/enterlistconversations" || currentPathName == "/personalletters/enterlistletters"){
window.location.reload();
}
},
error : function(data){
$('#loadingBar').drloadingbar("stopLoad");
$("#createPersonallettersSubmit").removeAttr("disabled");
if(data.responseJSON == null){
$("#drTipbar").drtipbar("showMsg","网络不给力");
}else{
if(data.responseJSON.errCode != null){
$("#drTipbar").drtipbar("showMsg",data.responseJSON.errMessage);
}else{
$("#drTipbar").drtipbar("showMsg","网络不给力");
}
}
}
});
});
});
})(jQuery);

View File

@@ -0,0 +1,261 @@
/**
* preview image
*/
var PreviewImage=function(){
var Preview=function(params,keyword){
//关闭图片预览Modal
$(document).on('click','.image-preview-close',function(){
$('.image-preview-background').fadeOut(500).removeClass('image-preview-background-hover');
$('.shot-container .curPreview').removeClass('curPreview');
})
//显示Modal浏览图片
$(document).on('click','.shot-image .cover,.shot-image img',function(){
var $curShot=$(this).parents('.shot');
generatePreviewImgModal($curShot);
})
//鼠标点击下一张
$(document).on('click','.image-preview-next',function(){
goToPage(false,params,keyword);
})
//鼠标点击上一张
$(document).on('click','.image-preview-prev',function(){
goToPage(true,params,keyword);
})
//方向键控制左右翻页
$(document).keydown(function(event){
//Modal处于显示状态才能触发翻页操作
if($('.image-preview-background').css('display')=='block'){
// -->
if (event.keyCode == 39){
goToPage(false,params,keyword);
}
// <--
else if(event.keyCode == 37){
goToPage(true,params,keyword);
}
}
});
};
return {
init:function(params,keyword){
Preview(params,keyword);
}
};
}();
/**
* 图片预览左右翻页
* 上一张flag=true , 下一张flag=false
*/
function goToPage(flag,params,keyword){
// 上一张
if(flag){
//存在上一张
if($('.shot-container .curPreview').prev().length>=1){
slider(true);
}
//已经是第一张
else{
console.log('已经是第一张');
$('.loadTips').text('已经是第一张 !').stop().fadeIn(500).fadeOut(1500);
}
}
// 下一张
else{
//存在下一张
if($('.shot-container .curPreview').next().length>=1){
slider(false);
}
//已经是最后一张
else{
//触发操作,加载更多数据
params.page++;
Disabled($('.loadMore'),'');
Loading($('.loadMore'));
$.when(keyword==''?getScreenShotList(params.url,params.page):getSearchScreenShotList(params.url,params.page,keyword))
.done(function(data){
if($('.shot-container .curPreview').next().length>=1){
slider(false);
}
else{
console.log('已经是最后一张');
$('.loadTips').text('已经是最后一张 !').stop().fadeIn(500).fadeOut(1500);
}
});
}
}
}
/**
* slider效果
* 上一张flag=true , 下一张flag=false
*/
function slider(flag){
if(flag){
$('.image-preview-container').addClass('image-preview-container-prev');
var $curShot=$('.shot-container .curPreview').removeClass('curPreview').prev();
}
else{
$('.image-preview-container').addClass('image-preview-container-next');
var $curShot=$('.shot-container .curPreview').removeClass('curPreview').next();
}
generatePreviewImgModal($curShot);
setTimeout(function(){
if(flag){
$('.image-preview-container').removeClass('image-preview-container-prev');
}
else{
$('.image-preview-container').removeClass('image-preview-container-next');
}
},500);
}
/**
* 生成图片预览Modal
*/
function generatePreviewImgModal($curShot){
$curShot.addClass('curPreview');
//滚动条随预览图片滚动
var scrollTop=$('.curPreview').offset().top;
$("html,body").animate({scrollTop:scrollTop+"px"},500);
var application=$curShot.data('application');
if($('.image-preview-background').length<1){
$('body').append(
'<div class="image-preview-background is-hidden">'+
'<i class="iconfont image-preview-ctrl image-preview-close">&#xe60b;</i>'+
'<i class="iconfont image-preview-ctrl image-preview-prev">&#xe60a;</i>'+
'<i class="iconfont image-preview-ctrl image-preview-next">&#xe60a;</i>'+
'<div class="image-preview-wrapper">'+
'<div class="image-preview-container white">'+
'<div class="column three-fifths text-align-center">'+
'<img class="main-image" src="">'+
'<h6 class="fastKey">键盘快捷键: ← 前一张图片 → 后一张图片</h6>'+
'</div>'+
'<div class="column two-fifths text-align-left">'+
'<i class="iconfont like-icon inline-block">&#xe606;</i>&nbsp;&nbsp;喜欢&nbsp;&nbsp;<span class="likeCount"></span>'+
'<div class="edit-screenshots-items">'+
'</div>'+
'<hr class="horizontal-line text-align-left">'+
'<ul class="screenshot-info">'+
'<li>'+
'<img class="app-logo" src=""/>'+
'<a class="app-name" target="_blank"></a>'+
'</li>'+
'<li>'+
'<h6>版本号</h6>'+
'<h6 class="app-version"></h6>'+
'</li>'+
'<li>'+
'<h6>更新时间</h6>'+
'<h6 class="updateTime"></h6>'+
'</li>'+
'<li>'+
'<h6>所属标签</h6>'+
'<div class="Marks">'+
'</div>'+
'</li>'+
'</ul>'+
'<div class="downloadPic-area">'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'
);
}
$image_preview_background=$('.image-preview-background');
FillModalData(application,$image_preview_background);
$('.image-preview-background').fadeIn(500).addClass('image-preview-background-hover');
}
/**
* 填充Modal数据
*/
function FillModalData(application,$image_preview_background){
$image_preview_background.find('.column.three-fifths img').attr('src',application.pic);
$image_preview_background.find('.column.two-fifths .likeCount').text(application.likeCount);
$image_preview_background.find('.app-logo').attr('src',application.applicationIcon);
$image_preview_background.find('.app-name').text(application.applicationName).attr('href','/applications/get/'+application.id);
$image_preview_background.find('.app-version').text(application.appVersion);
$image_preview_background.find('.updateTime').text(timeStampToDateString(application.updatedTime));
//遍历Marks
$image_preview_background.find('.screenshot-info .Marks').empty();
$.each(application.marks,function(key,value){
$image_preview_background.find('.screenshot-info .Marks').append(
'<a class="edit-btn" href="/screenshots/searchscreenshot?search='+value.name+'" target="_blank">'+value.name+'</a>'
);
});
var sizeArray=['640X960','640X1136','750X1334','1080X1920'];
// 按Type从小到大排序
var newArray=application.screenShotContents;
if(newArray.length<1){
$image_preview_background.find('.downloadPic-area').empty().append('抱歉,暂时没有更新下载截图。')
}
else{
$image_preview_background.find('.downloadPic-area').empty().append('下载:');
newArray.sort(getSortFun('asc', 'type'));
//遍历screenShotContents
$.each(newArray,function(key,value){
$image_preview_background.find('.downloadPic-area').append(
'<a class="downloadPic-btn" href="'+value.url+'">'+sizeArray[value.type-1]+'</a>'
);
});
}
//EditScreenShot
var EditScreenShot_Array=[{
'module':'default',
'controller':'screenshots',
'action':'enterscreenshotcontent',
'method':'GET',
'menuItem':'编辑截图包'
},
{
'module':'default',
'controller':'screenshots',
'action':'enterupdate',
'method':'GET',
'menuItem':'编辑基本信息'
},
{
'module':'default',
'controller':'screenshots',
'action':'delete',
'method':'POST',
'menuItem':'删除界面'
}];
$('.edit-screenshots-items').empty();
for(var i=0;i<EditScreenShot_Array.length;i++){
$('.edit-screenshots-items').append('<a class="is-hidden edit-btn edit-btn-'+i+'" href="" target="_blank">'+EditScreenShot_Array[i].menuItem+'</a>');
}
var $editScreenShot=$('.edit-screenshots-items');
$editScreenShot.find(".edit-btn-0").attr('href','/screenshots/enterscreenshotcontent?screenShotId='+application.screenShotId);
$editScreenShot.find(".edit-btn-1").attr('href','/screenshots/enterupdate/'+application.screenShotId);
$editScreenShot.find(".edit-btn-2").attr('href','/screenshots/delete/'+application.screenShotId);
/* 根据权限显示ScreenShot操作按钮 */
var returnValue=hasAuth(EditScreenShot_Array,authList_array);
for(var i=0;i<returnValue.length;i++){
$editScreenShot.find('.edit-btn-'+returnValue[i].index).removeClass('is-hidden');
}
$editScreenShot.find('.is-hidden').remove();
}

View File

@@ -0,0 +1,17 @@
function getProjectRole(){
var role = ["产品经理","设计师","硬件工程师","软件工程师","运营","公关",
"市场销售","人力资源","财务","法务","其他"];
return role;
}
function getProjectPhase(){
var phase = ["想法阶段","Demo 阶段","产品已上线","有运营数据","已停止运营"];
return phase;
}
function getFinancePhase(){
var phase = ["种子","天使","Pre-A","A 轮","B 轮","C 轮","D 轮","E 轮","F 轮","Pre-IPO"];
return phase;
}

View File

@@ -0,0 +1,24 @@
function getProvince(){
var province = ["上海"];
return province;
}
function getCityByProvince(province){
var arr = getProvinceAndCity();
return arr[province];
}
function getProvinceAndCity(){
var arr = {"上海": ["上海"]};
return arr;
}
function getDistrictByCity(city){
var arr = getCityAndDistrict();
return arr[city];
}
function getCityAndDistrict(){
var arr = {"上海": ["黄浦区","徐汇区","长宁区","静安区","普陀区","虹口区","闸北区","杨浦区","闵行区","宝山区","青浦区","松江区","嘉定区","奉贤区","金山区","浦东新区","崇明县"]};
return arr;
}

View File

@@ -0,0 +1,36 @@
/*
RequireJS 2.1.17 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved.
Available via the MIT or new BSD license.
see: http://github.com/jrburke/requirejs for details
*/
var requirejs,require,define;
(function(ba){function G(b){return"[object Function]"===K.call(b)}function H(b){return"[object Array]"===K.call(b)}function v(b,c){if(b){var d;for(d=0;d<b.length&&(!b[d]||!c(b[d],d,b));d+=1);}}function T(b,c){if(b){var d;for(d=b.length-1;-1<d&&(!b[d]||!c(b[d],d,b));d-=1);}}function t(b,c){return fa.call(b,c)}function m(b,c){return t(b,c)&&b[c]}function B(b,c){for(var d in b)if(t(b,d)&&c(b[d],d))break}function U(b,c,d,e){c&&B(c,function(c,g){if(d||!t(b,g))e&&"object"===typeof c&&c&&!H(c)&&!G(c)&&!(c instanceof
RegExp)?(b[g]||(b[g]={}),U(b[g],c,d,e)):b[g]=c});return b}function u(b,c){return function(){return c.apply(b,arguments)}}function ca(b){throw b;}function da(b){if(!b)return b;var c=ba;v(b.split("."),function(b){c=c[b]});return c}function C(b,c,d,e){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=e;d&&(c.originalError=d);return c}function ga(b){function c(a,k,b){var f,l,c,d,e,g,i,p,k=k&&k.split("/"),h=j.map,n=h&&h["*"];if(a){a=a.split("/");l=a.length-1;j.nodeIdCompat&&
Q.test(a[l])&&(a[l]=a[l].replace(Q,""));"."===a[0].charAt(0)&&k&&(l=k.slice(0,k.length-1),a=l.concat(a));l=a;for(c=0;c<l.length;c++)if(d=l[c],"."===d)l.splice(c,1),c-=1;else if(".."===d&&!(0===c||1===c&&".."===l[2]||".."===l[c-1])&&0<c)l.splice(c-1,2),c-=2;a=a.join("/")}if(b&&h&&(k||n)){l=a.split("/");c=l.length;a:for(;0<c;c-=1){e=l.slice(0,c).join("/");if(k)for(d=k.length;0<d;d-=1)if(b=m(h,k.slice(0,d).join("/")))if(b=m(b,e)){f=b;g=c;break a}!i&&(n&&m(n,e))&&(i=m(n,e),p=c)}!f&&i&&(f=i,g=p);f&&(l.splice(0,
g,f),a=l.join("/"))}return(f=m(j.pkgs,a))?f:a}function d(a){z&&v(document.getElementsByTagName("script"),function(k){if(k.getAttribute("data-requiremodule")===a&&k.getAttribute("data-requirecontext")===i.contextName)return k.parentNode.removeChild(k),!0})}function e(a){var k=m(j.paths,a);if(k&&H(k)&&1<k.length)return k.shift(),i.require.undef(a),i.makeRequire(null,{skipMap:!0})([a]),!0}function n(a){var k,c=a?a.indexOf("!"):-1;-1<c&&(k=a.substring(0,c),a=a.substring(c+1,a.length));return[k,a]}function p(a,
k,b,f){var l,d,e=null,g=k?k.name:null,j=a,p=!0,h="";a||(p=!1,a="_@r"+(K+=1));a=n(a);e=a[0];a=a[1];e&&(e=c(e,g,f),d=m(r,e));a&&(e?h=d&&d.normalize?d.normalize(a,function(a){return c(a,g,f)}):-1===a.indexOf("!")?c(a,g,f):a:(h=c(a,g,f),a=n(h),e=a[0],h=a[1],b=!0,l=i.nameToUrl(h)));b=e&&!d&&!b?"_unnormalized"+(O+=1):"";return{prefix:e,name:h,parentMap:k,unnormalized:!!b,url:l,originalName:j,isDefine:p,id:(e?e+"!"+h:h)+b}}function s(a){var k=a.id,b=m(h,k);b||(b=h[k]=new i.Module(a));return b}function q(a,
k,b){var f=a.id,c=m(h,f);if(t(r,f)&&(!c||c.defineEmitComplete))"defined"===k&&b(r[f]);else if(c=s(a),c.error&&"error"===k)b(c.error);else c.on(k,b)}function w(a,b){var c=a.requireModules,f=!1;if(b)b(a);else if(v(c,function(b){if(b=m(h,b))b.error=a,b.events.error&&(f=!0,b.emit("error",a))}),!f)g.onError(a)}function x(){R.length&&(ha.apply(A,[A.length,0].concat(R)),R=[])}function y(a){delete h[a];delete V[a]}function F(a,b,c){var f=a.map.id;a.error?a.emit("error",a.error):(b[f]=!0,v(a.depMaps,function(f,
d){var e=f.id,g=m(h,e);g&&(!a.depMatched[d]&&!c[e])&&(m(b,e)?(a.defineDep(d,r[e]),a.check()):F(g,b,c))}),c[f]=!0)}function D(){var a,b,c=(a=1E3*j.waitSeconds)&&i.startTime+a<(new Date).getTime(),f=[],l=[],g=!1,h=!0;if(!W){W=!0;B(V,function(a){var i=a.map,j=i.id;if(a.enabled&&(i.isDefine||l.push(a),!a.error))if(!a.inited&&c)e(j)?g=b=!0:(f.push(j),d(j));else if(!a.inited&&(a.fetched&&i.isDefine)&&(g=!0,!i.prefix))return h=!1});if(c&&f.length)return a=C("timeout","Load timeout for modules: "+f,null,
f),a.contextName=i.contextName,w(a);h&&v(l,function(a){F(a,{},{})});if((!c||b)&&g)if((z||ea)&&!X)X=setTimeout(function(){X=0;D()},50);W=!1}}function E(a){t(r,a[0])||s(p(a[0],null,!0)).init(a[1],a[2])}function I(a){var a=a.currentTarget||a.srcElement,b=i.onScriptLoad;a.detachEvent&&!Y?a.detachEvent("onreadystatechange",b):a.removeEventListener("load",b,!1);b=i.onScriptError;(!a.detachEvent||Y)&&a.removeEventListener("error",b,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}function J(){var a;
for(x();A.length;){a=A.shift();if(null===a[0])return w(C("mismatch","Mismatched anonymous define() module: "+a[a.length-1]));E(a)}}var W,Z,i,L,X,j={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},h={},V={},$={},A=[],r={},S={},aa={},K=1,O=1;L={require:function(a){return a.require?a.require:a.require=i.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports?r[a.map.id]=a.exports:a.exports=r[a.map.id]={}},module:function(a){return a.module?
a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){return m(j.config,a.map.id)||{}},exports:a.exports||(a.exports={})}}};Z=function(a){this.events=m($,a.id)||{};this.map=a;this.shim=m(j.shim,a.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};Z.prototype={init:function(a,b,c,f){f=f||{};if(!this.inited){this.factory=b;if(c)this.on("error",c);else this.events.error&&(c=u(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=
c;this.inited=!0;this.ignore=f.ignore;f.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,b){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=b)},fetch:function(){if(!this.fetched){this.fetched=!0;i.startTime=(new Date).getTime();var a=this.map;if(this.shim)i.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],u(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=
this.map.url;S[a]||(S[a]=!0,i.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,b,c=this.map.id;b=this.depExports;var f=this.exports,l=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){this.defining=!0;if(1>this.depCount&&!this.defined){if(G(l)){if(this.events.error&&this.map.isDefine||g.onError!==ca)try{f=i.execCb(c,l,b,f)}catch(d){a=d}else f=i.execCb(c,l,b,f);this.map.isDefine&&void 0===f&&((b=this.module)?f=b.exports:this.usingExports&&
(f=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else f=l;this.exports=f;if(this.map.isDefine&&!this.ignore&&(r[c]=f,g.onResourceLoad))g.onResourceLoad(i,this.map,this.depMaps);y(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a=
this.map,b=a.id,d=p(a.prefix);this.depMaps.push(d);q(d,"defined",u(this,function(f){var l,d;d=m(aa,this.map.id);var e=this.map.name,P=this.map.parentMap?this.map.parentMap.name:null,n=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(e=f.normalize(e,function(a){return c(a,P,!0)})||""),f=p(a.prefix+"!"+e,this.map.parentMap),q(f,"defined",u(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),d=m(h,f.id)){this.depMaps.push(f);
if(this.events.error)d.on("error",u(this,function(a){this.emit("error",a)}));d.enable()}}else d?(this.map.url=i.nameToUrl(d),this.load()):(l=u(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),l.error=u(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];B(h,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),l.fromText=u(this,function(f,c){var d=a.name,e=p(d),P=M;c&&(f=c);P&&(M=!1);s(e);t(j.config,b)&&(j.config[d]=j.config[b]);try{g.exec(f)}catch(h){return w(C("fromtexteval",
"fromText eval for "+b+" failed: "+h,h,[b]))}P&&(M=!0);this.depMaps.push(e);i.completeLoad(d);n([d],l)}),f.load(a.name,n,l,j))}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){V[this.map.id]=this;this.enabling=this.enabled=!0;v(this.depMaps,u(this,function(a,b){var c,f;if("string"===typeof a){a=p(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=m(L,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;q(a,"defined",u(this,function(a){this.defineDep(b,
a);this.check()}));this.errback?q(a,"error",u(this,this.errback)):this.events.error&&q(a,"error",u(this,function(a){this.emit("error",a)}))}c=a.id;f=h[c];!t(L,c)&&(f&&!f.enabled)&&i.enable(a,this)}));B(this.pluginMaps,u(this,function(a){var b=m(h,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){v(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:j,contextName:b,
registry:h,defined:r,urlFetched:S,defQueue:A,Module:Z,makeModuleMap:p,nextTick:g.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=j.shim,c={paths:!0,bundles:!0,config:!0,map:!0};B(a,function(a,b){c[b]?(j[b]||(j[b]={}),U(j[b],a,!0,!0)):j[b]=a});a.bundles&&B(a.bundles,function(a,b){v(a,function(a){a!==b&&(aa[a]=b)})});a.shim&&(B(a.shim,function(a,c){H(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);
b[c]=a}),j.shim=b);a.packages&&v(a.packages,function(a){var b,a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(j.paths[b]=a.location);j.pkgs[b]=a.name+"/"+(a.main||"main").replace(ia,"").replace(Q,"")});B(h,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=p(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ba,arguments));return b||a.exports&&da(a.exports)}},makeRequire:function(a,e){function j(c,d,m){var n,
q;e.enableBuildCallback&&(d&&G(d))&&(d.__requireJsBuild=!0);if("string"===typeof c){if(G(d))return w(C("requireargs","Invalid require call"),m);if(a&&t(L,c))return L[c](h[a.id]);if(g.get)return g.get(i,c,a,j);n=p(c,a,!1,!0);n=n.id;return!t(r,n)?w(C("notloaded",'Module name "'+n+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[n]}J();i.nextTick(function(){J();q=s(p(null,a));q.skipMap=e.skipMap;q.init(c,d,m,{enabled:!0});D()});return j}e=e||{};U(j,{isBrowser:z,toUrl:function(b){var d,
e=b.lastIndexOf("."),k=b.split("/")[0];if(-1!==e&&(!("."===k||".."===k)||1<e))d=b.substring(e,b.length),b=b.substring(0,e);return i.nameToUrl(c(b,a&&a.id,!0),d,!0)},defined:function(b){return t(r,p(b,a,!1,!0).id)},specified:function(b){b=p(b,a,!1,!0).id;return t(r,b)||t(h,b)}});a||(j.undef=function(b){x();var c=p(b,a,!0),e=m(h,b);d(b);delete r[b];delete S[c.url];delete $[b];T(A,function(a,c){a[0]===b&&A.splice(c,1)});e&&(e.events.defined&&($[b]=e.events),y(b))});return j},enable:function(a){m(h,a.id)&&
s(a).enable()},completeLoad:function(a){var b,c,d=m(j.shim,a)||{},g=d.exports;for(x();A.length;){c=A.shift();if(null===c[0]){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);E(c)}c=m(h,a);if(!b&&!t(r,a)&&c&&!c.inited){if(j.enforceDefine&&(!g||!da(g)))return e(a)?void 0:w(C("nodefine","No define call for "+a,null,[a]));E([a,d.deps||[],d.exportsFn])}D()},nameToUrl:function(a,b,c){var d,e,h;(d=m(j.pkgs,a))&&(a=d);if(d=m(aa,a))return i.nameToUrl(d,b,c);if(g.jsExtRegExp.test(a))d=a+(b||"");else{d=j.paths;
a=a.split("/");for(e=a.length;0<e;e-=1)if(h=a.slice(0,e).join("/"),h=m(d,h)){H(h)&&(h=h[0]);a.splice(0,e,h);break}d=a.join("/");d+=b||(/^data\:|\?/.test(d)||c?"":".js");d=("/"===d.charAt(0)||d.match(/^[\w\+\.\-]+:/)?"":j.baseUrl)+d}return j.urlArgs?d+((-1===d.indexOf("?")?"?":"&")+j.urlArgs):d},load:function(a,b){g.load(i,a,b)},execCb:function(a,b,c,d){return b.apply(d,c)},onScriptLoad:function(a){if("load"===a.type||ja.test((a.currentTarget||a.srcElement).readyState))N=null,a=I(a),i.completeLoad(a.id)},
onScriptError:function(a){var b=I(a);if(!e(b.id))return w(C("scripterror","Script error for: "+b.id,a,[b.id]))}};i.require=i.makeRequire();return i}var g,x,y,D,I,E,N,J,s,O,ka=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,la=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,Q=/\.js$/,ia=/^\.\//;x=Object.prototype;var K=x.toString,fa=x.hasOwnProperty,ha=Array.prototype.splice,z=!!("undefined"!==typeof window&&"undefined"!==typeof navigator&&window.document),ea=!z&&"undefined"!==typeof importScripts,ja=
z&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,Y="undefined"!==typeof opera&&"[object Opera]"===opera.toString(),F={},q={},R=[],M=!1;if("undefined"===typeof define){if("undefined"!==typeof requirejs){if(G(requirejs))return;q=requirejs;requirejs=void 0}"undefined"!==typeof require&&!G(require)&&(q=require,require=void 0);g=requirejs=function(b,c,d,e){var n,p="_";!H(b)&&"string"!==typeof b&&(n=b,H(c)?(b=c,c=d,d=e):b=[]);n&&n.context&&(p=n.context);(e=m(F,p))||(e=F[p]=g.s.newContext(p));
n&&e.configure(n);return e.require(b,c,d)};g.config=function(b){return g(b)};g.nextTick="undefined"!==typeof setTimeout?function(b){setTimeout(b,4)}:function(b){b()};require||(require=g);g.version="2.1.17";g.jsExtRegExp=/^\/|:|\?|\.js$/;g.isBrowser=z;x=g.s={contexts:F,newContext:ga};g({});v(["toUrl","undef","defined","specified"],function(b){g[b]=function(){var c=F._;return c.require[b].apply(c,arguments)}});if(z&&(y=x.head=document.getElementsByTagName("head")[0],D=document.getElementsByTagName("base")[0]))y=
x.head=D.parentNode;g.onError=ca;g.createNode=function(b){var c=b.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");c.type=b.scriptType||"text/javascript";c.charset="utf-8";c.async=!0;return c};g.load=function(b,c,d){var e=b&&b.config||{};if(z)return e=g.createNode(e,c,d),e.setAttribute("data-requirecontext",b.contextName),e.setAttribute("data-requiremodule",c),e.attachEvent&&!(e.attachEvent.toString&&0>e.attachEvent.toString().indexOf("[native code"))&&
!Y?(M=!0,e.attachEvent("onreadystatechange",b.onScriptLoad)):(e.addEventListener("load",b.onScriptLoad,!1),e.addEventListener("error",b.onScriptError,!1)),e.src=d,J=e,D?y.insertBefore(e,D):y.appendChild(e),J=null,e;if(ea)try{importScripts(d),b.completeLoad(c)}catch(m){b.onError(C("importscripts","importScripts failed for "+c+" at "+d,m,[c]))}};z&&!q.skipDataMain&&T(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(I=b.getAttribute("data-main"))return s=I,q.baseUrl||(E=s.split("/"),
s=E.pop(),O=E.length?E.join("/")+"/":"./",q.baseUrl=O),s=s.replace(Q,""),g.jsExtRegExp.test(s)&&(s=I),q.deps=q.deps?q.deps.concat(s):[s],!0});define=function(b,c,d){var e,g;"string"!==typeof b&&(d=c,c=b,b=null);H(c)||(d=c,c=null);!c&&G(d)&&(c=[],d.length&&(d.toString().replace(ka,"").replace(la,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(M){if(!(e=J))N&&"interactive"===N.readyState||T(document.getElementsByTagName("script"),function(b){if("interactive"===
b.readyState)return N=b}),e=N;e&&(b||(b=e.getAttribute("data-requiremodule")),g=F[e.getAttribute("data-requirecontext")])}(g?g.defQueue:R).push([b,c,d])};define.amd={jQuery:!0};g.exec=function(b){return eval(b)};g(q)}})(this);

View File

@@ -0,0 +1,153 @@
/**
* screenshothover.js
* each file using screenshots must include this file
*/
/* hover */
$(document).on('mouseenter','.shot .shot-image',function(){
$(this).addClass('shot-image-hover');
$(this).find('.cover').addClass('cover-hover');
$(this).find('.actions').fadeIn(500).addClass('actions-hover');
});
$(document).on('mouseleave','.shot .shot-image',function(){
$(this).removeClass('shot-image-hover');
$(this).find('.cover').removeClass('cover-hover');
$(this).find('.actions').fadeOut(500).removeClass('actions-hover');
});
/* like */
$(document).on('click','.actions',function(){
if(!$.isEmptyObject(currentUserInfo)){
$(this).find('.iconfont').toggleClass('is-hidden');
}
});
function like(e,id){
if($.isEmptyObject(currentUserInfo)){
alert("请先登录");
}else{
var id = $(e).attr("id");
$.ajax( {
url:'/screenshots/likescreenshot',
data:{
screenshot_id : id
},
type:'post',
dataType:'json',
success:function(data) {
//alert("操作成功!");
e.setAttribute("onclick", "unlike(this,"+id+")");
if($(e).find('.unlike').hasClass('is-hidden')){
$(e).find('.iconfont').toggleClass('is-hidden');
}
},
error : function() {
//alert("操作失败!");
if($(e).find('.like').hasClass('is-hidden')){
$(e).find('.iconfont').toggleClass('is-hidden');
}
e.setAttribute("onclick", "like(this,"+id+")");
if($(e).find('.liked').hasClass('is-hidden')){
$(e).find('.iconfont').toggleClass('is-hidden');
}
}
});
}
}
function unlike(e,id){
if($.isEmptyObject(currentUserInfo)){
alert("请先登录");
}else{
var id = $(e).attr("id");
$.ajax( {
url:'/screenshots/dislikescreenshot',
data:{
screenshot_id : id
},
type:'post',
dataType:'json',
success:function(data) {
//alert("操作成功!");
e.setAttribute("onclick", "like(this,"+id+")");
if($(e).find('.liked').hasClass('is-hidden')){
$(e).find('.iconfont').toggleClass('is-hidden');
}
},
error : function() {
//alert("操作失败!");
if($(e).find('.unlike').hasClass('is-hidden')){
$(e).find('.iconfont').toggleClass('is-hidden');
}
e.setAttribute("onclick", "unlike(this,"+id+")");
}
});
}
}
function detaillike(e,id){
if($.isEmptyObject(currentUserInfo)){
alert("请先登录");
}else{
var s = e.getElementsByTagName('span')[0].innerHTML;
e.getElementsByTagName('span')[0].innerHTML = parseInt(s)+1;
e.getElementsByTagName('i')[0].innerHTML = "&#xe606;";
e.onclick=function(){};
var id = $(e).attr("id");
$.ajax( {
url:'/screenshots/likescreenshot',
data:{
screenshot_id : id
},
type:'post',
dataType:'json',
success:function(data) {
//alert("操作成功!");
e.setAttribute("onclick", "detailunlike(this,"+id+")");
e.getElementsByTagName('i')[0].innerHTML = "&#xe606;";
},
error : function() {
//alert("操作失败!");
e.setAttribute("onclick", "detaillike(this,"+id+")");
e.getElementsByTagName('i')[0].innerHTML = "&#xe607;";
e.getElementsByTagName('span')[0].innerHTML = parseInt(s)-2;
}
});
}
}
function detailunlike(e,id){
if($.isEmptyObject(currentUserInfo)){
alert("请先登录");
}else{
var s = e.getElementsByTagName('span')[0].innerHTML;
e.getElementsByTagName('span')[0].innerHTML = parseInt(s)-1;
e.getElementsByTagName('i')[0].innerHTML = "&#xe607;";
e.onclick=function(){};
var id = $(e).attr("id");
$.ajax( {
url:'/screenshots/dislikescreenshot',
data:{
screenshot_id : id
},
type:'post',
dataType:'json',
success:function(data) {
//alert("操作成功!");
e.setAttribute("onclick", "detaillike(this,"+id+")");
e.getElementsByTagName('i')[0].innerHTML = "&#xe607;";
},
error : function() {
//alert("操作失败!");
e.setAttribute("onclick", "detailunlike(this,"+id+")");
e.getElementsByTagName('i')[0].innerHTML = "&#xe606;";
e.getElementsByTagName('span')[0].innerHTML = parseInt(s)+2;
}
});
}
}
function cleanMarksStyle(){/* 清除截图下面每行标签的最后一个, */
var list = document.getElementsByName('screenshot-mark-container');
for(var k=0;k<list.length;k++){
var tempList = list[k].getElementsByTagName('span');
if(tempList.length>0){
var lastSpan = tempList[tempList.length-1];
lastSpan.parentNode.removeChild(lastSpan);
}
}
}

View File

@@ -0,0 +1,431 @@
(function($) {
var methods = {
init: function(options) {
var $this = this;
options = $.extend($.fn.searchUser.options, options);
return this.each(function() {
var $thisSearchUser = $(this);
var userData = [].concat(options.userData); // 用户数组[{userId, userName}](解除引用传递)
var adjustLeftComponent = options.adjustLeftComponent; // 对齐控件
var limitUser = options.limitUser; // 限制用户数量
var isChangeable = options.isChangeable; // 是否可以改变用户
var placeholder = options.placeholder; // 搜索控件提示文字
var deleteOneUserFunc = options.deleteOneUserFunc; //删除一个用户的回调函数
var addOneUserFunc = options.addOneUserFunc; //加入一个用户的回调函数
$thisSearchUser.data("userData", userData);
$thisSearchUser.data("adjustLeftComponent", adjustLeftComponent);
$thisSearchUser.data("limitUser", limitUser);
$thisSearchUser.data("isChangeable", isChangeable);
$thisSearchUser.data("placeholder", placeholder);
$thisSearchUser.data("deleteOneUserFunc", deleteOneUserFunc);
$thisSearchUser.data("addOneUserFunc", addOneUserFunc);
//初始化外部预设的user
$(".drUserSpanContainer").off("click");
$(".drUserSpanContainer").remove();
for(var i = 0; i < userData.length; i++){
$thisSearchUser.searchUser("addOneUserSpanView",userData[i]);
}
//初始化placeholder
$thisSearchUser.searchUser("setChangeable",isChangeable);
// 搜索用户
function searchUserKeyword(keyword) {
if ($.trim(keyword) == "") {
if ($thisSearchUser.searchUser("isUserSearchShown")) {
$("#drSearchUserContainer").popover("hide");
}
return;
}
keyword = encodeURIComponent(keyword);
var jRequest = $.ajax({
type: "GET",
contentType: "application/x-www-form-urlencoded",
url: "/indexhome/indexsearch?type=2&searchtype=3&top=8&keyword=" + keyword,
beforeSend: function() {
$('#loadingBar').drloadingbar("startLoad");
var currentReq = $("#drSearchUserContainer").data("jRequest");
if (currentReq != null) { // 前面的请求还未完成
currentReq.abort();
}
},
success: function(data) {
$('#loadingBar').drloadingbar("stopLoad");
var userArray = data.content,
userLength = userArray.length;
if (userLength > 0) {
if ($thisSearchUser.searchUser("isUserSearchShown")) {
$("#drSearchUserContainer").popover("hide");
}
$("#drSearchUserContainer").popover("show");
for (var i = 0; i < userLength; i++) {
$element = $("<li class='drUserInputPopoverSearchList'><span><img src='" + userArray[i].avatarThumbUrl + "&w=60&h=60' class='img-circle' /></span><span data-userid='" + userArray[i].id + "' ><strong>" + $.htmlspecialchars(userArray[i].userName) + "</strong></span></li>");
if(i == 0){ // 默认选中第一个用户
$element.addClass("isActive");
}
$element.appendTo($("#drUserInputPopoverSearch"));
}
$("#drUserInputPopoverSearch").off("mouseenter");
$("#drUserInputPopoverSearch").off("click");
// 鼠标移到上面高亮显示
$("#drUserInputPopoverSearch").on("mouseenter", ".drUserInputPopoverSearchList", function() {
if(!$(this).hasClass("isActive")){
$(".drUserInputPopoverSearchList.isActive").each(function(){
$(this).removeClass("isActive");
});
$(this).addClass("isActive");
}
});
// 鼠标单击选中
$("#drUserInputPopoverSearch").on("click", ".drUserInputPopoverSearchList.isActive", function(e) {
var content = $(this).find("span strong").text();
var userId = $(this).find("span[data-userid]").attr("data-userid");
$thisSearchUser.searchUser("addOneUser",userId, content);
$("#drSearchUser").focus();
});
} else {
if ($thisSearchUser.searchUser("isUserSearchShown")) {
$("#drSearchUserContainer").popover("hide");
}
}
},
error: function(data) {
if (data.statusText == "abort") {
return;
}
$('#loadingBar').drloadingbar("stopLoad");
}
});
$("#drSearchUserContainer").data("jRequest", jRequest);
}
// 粘贴事件
$("#drSearchUser").on("paste", function(e) {
var userData = $thisSearchUser.data("userData");
var limitUser = $thisSearchUser.data("limitUser");
if (userData.length >= limitUser) {
// 提示只能输入多少个用户
$("#drUserInputErrorPopoverContent").text("只能添加 " + limitUser + " 个用户");
if (!$thisSearchUser.searchUser("isUserInputErrorShown")) {
$("#drSearchUser").popover("show");
}
e.preventDefault();
return;
}
if ($thisSearchUser.searchUser("isUserInputErrorShown")) {
$("#drSearchUser").popover("hide");
}
var pasteText = e.originalEvent.clipboardData.getData("text/plain");
pasteText = pasteText.replace(/\r\n/g, "");
pasteText = pasteText.replace(/\r/g, "");
pasteText = pasteText.replace(/\n/g, "");
document.execCommand("insertHTML", false, pasteText);
searchUserKeyword($(this).text());
});
// 光标离开事件
$("#drSearchUser").on("blur", function(e) {
//return;
if ($thisSearchUser.searchUser("isUserInputErrorShown")) {
$("#drSearchUser").popover("hide");
}
if ($thisSearchUser.searchUser("isUserSearchShown")) {
setTimeout(function() {
// 延迟200毫秒触发否则若点击在content cell内部则立马被hide掉无法触发
$("#drSearchUserContainer").popover("hide");
}, 200);
}
});
// 键盘按键事件
$("#drSearchUser").on("keydown", function(e) {
var userData = $thisSearchUser.data("userData");
var limitUser = $thisSearchUser.data("limitUser");
var isChangeable = $thisSearchUser.data("isChangeable");
var keyCode = e.keyCode;
if(!isChangeable){
e.preventDefault();
return;
}
if (keyCode == 8 || keyCode == 46) { // BackSpace, Delete
if ($thisSearchUser.searchUser("isUserInputErrorShown")) {
$("#drSearchUser").popover("hide");
}
if ($(this).text() == "" && userData.length > 0) {
e.preventDefault();
$thisSearchUser.searchUser("deleteOneUser");
return;
}
}
if (userData.length >= limitUser) {
e.preventDefault();
$(this).text("");
if (!$thisSearchUser.searchUser("isUserInputErrorShown")) {
$("#drSearchUser").popover("show");
// 提示只能输入多少个用户
$("#drUserInputErrorPopoverContent").text("只能添加 " + limitUser + " 个用户");
}
return;
}
if ($thisSearchUser.searchUser("isUserInputErrorShown")) {
$("#drSearchUser").popover("hide");
}
if (keyCode == 13 || keyCode == 108) { // Enter键
e.preventDefault();
// 处理标签
if ($thisSearchUser.searchUser("isUserSearchShown")) {
var content = $(".drUserInputPopoverSearchList.isActive span strong").text();
var userId = $(".drUserInputPopoverSearchList.isActive span[data-userid]").attr("data-userid");
$thisSearchUser.searchUser("addOneUser",userId, content);
$("#drSearchUserContainer").popover("hide");
}
} else if (keyCode == 40) { // 下方向键
if ($thisSearchUser.searchUser("isUserSearchShown")) {
var $nextNode = $($(".drUserInputPopoverSearchList.isActive")[0].nextSibling);
$(".drUserInputPopoverSearchList.isActive").removeClass("isActive");
if ($nextNode.length == 0) {
// 指向第一个
$(".drUserInputPopoverSearchList").first().addClass("isActive");
} else {
// 指向下一个
$nextNode.addClass("isActive");
}
}
} else if (keyCode == 38) { // 上方向键
if ($thisSearchUser.searchUser("isUserSearchShown")) {
var $previousNode = $($(".drUserInputPopoverSearchList.isActive")[0].previousSibling);
$(".drUserInputPopoverSearchList.isActive").removeClass("isActive");
if ($previousNode.length == 0) {
// 指向最后一个
$(".drUserInputPopoverSearchList").last().addClass("isActive");
} else {
// 指向上一个
$previousNode.addClass("isActive");
}
}
} else {
var $this = $(this);
setTimeout(function() {
searchUserKeyword($this.text());
}, 100);
}
});
// 错误弹出框初始化
$("#drSearchUser").popover({
trigger: "manual",
html: true,
animation: false,
placement: "top",
content: '<div id="userInputErrorPopoverContainer"><div id="userInputErrorPopover"><p id="drUserInputErrorPopoverContent"></p></div></div>'
});
// 搜索弹出框初始化
$("#drSearchUserContainer").popover({
trigger: "manual",
html: true,
animation: false,
placement: "bottom",
content: "<div id='userInputPopoverSearchContainer'><ul id='drUserInputPopoverSearch'></ul></div>"
});
// 搜索弹出框显示后调整位置
$("#drSearchUserContainer").on('shown.bs.popover', function(e) {
if (e.target != $("#drSearchUserContainer")[0]) {
return;
}
var topVal = parseInt($('#drSearchUserContainer+.popover').css('top').substr(0, $('#drSearchUserContainer+.popover').css('top').length - 2)),
inText = $("#drSearchUser").text();
$('#drSearchUserContainer+.popover').css('top', (topVal - 15) + 'px');
// 重新计算left
var left = 0;
if (!adjustLeftComponent) {
left = $("#drSearchUserContainer").offset().left;
} else {
var left1 = $("#drSearchUserContainer").offset().left;
var left2 = adjustLeftComponent.offset().left;
left = left1 - left2;
}
$('#drSearchUserContainer+.popover').css('left', (left - 20) + 'px');
$('#drSearchUserContainer+.popover .arrow').css('left', (20 + 14 * inText.length / 2) + 'px');
});
// 单击删除一个用户
$thisSearchUser.on("click", ".drUserSpanContainer", function(e) {
var isChangeable = $thisSearchUser.data("isChangeable");
if(!isChangeable){
e.preventDefault();
return;
}
$thisSearchUser.searchUser("deleteOneUser",$(e.target).data("userid"));
});
});
}, // init End
getUserArray: function() {
return this.data("userData");
},
resetData:function(userData,isChangeable,limitUser){
this.data("userData", userData);
this.data("limitUser", limitUser);
this.searchUser("setChangeable", isChangeable);
$(".drUserSpanContainer").off("click");
$(".drUserSpanContainer").remove();
for(var i = 0; i < userData.length; i++){
this.searchUser("addOneUserSpanView", userData[i]);
}
},
setPlaceholder:function(text){
var userData = this.data("userData");
if(userData.length > 0){
$("#drSearchUser")[0].setAttribute("data-placeholder", "");
}else{
$("#drSearchUser")[0].setAttribute("data-placeholder", text);
}
},
setChangeable:function(isChangeable){
this.data("isChangeable",isChangeable);
var placeholder = this.data("placeholder");
if(isChangeable){
$("#drSearchUser").css("visibility", "visible");
this.searchUser("setPlaceholder",placeholder);
}else{
$("#drSearchUser").css("visibility", "hidden");
}
},
// 错误输入框popover是否存在
isUserInputErrorShown:function(){
if($("#drSearchUser").data('bs.popover') != null){
return $("#drSearchUser").data('bs.popover').tip().hasClass('in');
}else{
return false;
}
},
// 用户popover是否存在
isUserSearchShown:function(){
if($("#drSearchUserContainer").data('bs.popover') != null){
return $("#drSearchUserContainer").data('bs.popover').tip().hasClass('in');
}else{
return false;
}
},
//删除一个用户
deleteOneUser:function(userId) {
var userData = this.data("userData");
var placeholder = this.data("placeholder");
var deleteOneUserFunc = this.data("deleteOneUserFunc");
var limitUser = this.data("limitUser");
if (userData.length <= limitUser) {
if (this.searchUser("isUserInputErrorShown")) {
$("#drSearchUser").popover("hide");
}
}
if(userData.length == 0){
return;
}
var deleteUserData = {};
if(userId == null){
//删除最后一个
var $deleteElement = $($(".drUserSpanContainer")[userData.length - 1]);
$deleteElement.off("click");
$deleteElement.remove();
deleteUserData = userData[userData.length-1];
userData.splice(userData.length-1, 1);
this.searchUser("setPlaceholder",placeholder);
}else{
var $deleteElement = $(".drUserSpanContainer[data-userid="+userId+"]");
$deleteElement.off("click");
$deleteElement.remove();
for(var i = 0; i < userData.length; i++){
if(userData[i].userId == userId){
deleteUserData = userData[i];
userData.splice(i, 1);
break;
}
}
this.searchUser("setPlaceholder",placeholder);
}
if(deleteOneUserFunc != null){
if(arguments.length <= 1){
deleteOneUserFunc(deleteUserData);
}
}
},
//增加用户对应的view操作
addOneUserSpanView:function(userDataElement){
$element = $("<span></span>");
$element.text(userDataElement.userName);
$element.attr("data-userid", userDataElement.userId);
$element.addClass("drUserSpanContainer");
$element.insertBefore($("#drSearchUserContainer"));
},
// 增加用户
addOneUser:function(userId, userName) {
var userData = this.data("userData");
var placeholder = this.data("placeholder");
var limitUser = this.data("limitUser");
var addOneUserFunc = this.data("addOneUserFunc");
if (userName == "") {
return;
}
if (userData.length >= limitUser) {
// 提示只能输入多少个用户
if (!this.searchUser("isUserInputErrorShown")) {
$("#drSearchUser").popover("show");
$("#drUserInputErrorPopoverContent").text("只能添加 " + limitUser + " 个用户");
}
return;
}
for(var i = 0; i < userData.length; i++){
if(userId == userData[i].userId){
//提示重复
if(!this.searchUser("isUserInputErrorShown")){
$("#drSearchUser").popover("show");
$("#drUserInputErrorPopoverContent").text("已经添加了该用户");
}
return;
}
}
var addUserData = {userId:userId, userName:userName};
userData.push(addUserData);
this.searchUser("setPlaceholder",placeholder);
// 添加一个标签
this.searchUser("addOneUserSpanView",addUserData);
$("#drSearchUser").text("");
if(this.searchUser("isUserSearchShown")){
$("#drSearchUserContainer").popover("hide");
}
if(addOneUserFunc != null){
if(arguments.length <= 2){
addOneUserFunc(addUserData);
}
}
}
};
$.fn.searchUser = function(method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.searchUser');
}
};
$.fn.searchUser.options = {userData: [], limitUser: 1, isChangeable: false, placeholder: "搜索收件人"};
})(jQuery);

View File

@@ -0,0 +1,380 @@
;(function() {
$.fn.spacecalendar = function(options) {
var pluginName = 'spacecalendar';
// Find the plugin attached to the element
var instance = this.data(pluginName);
// If the instance wasn't found, create it...
if(!instance) {
// Return the element being bound to
return this.each(function() {
return $(this).data(pluginName, new spacecalendar(this, options));
});
}
// ...otherwise if the user passes true to the plugin (on the second call),
// then return the instance of the plugin itself
return (options === true) ? instance : this;
};
// Default options
$.fn.spacecalendar.defaults =
{
// The house id
houseId: 0,
// 开始时间
startDate: null,
// 房源配置数组
spaceData: [],
// 是否可以编辑
isEditable: true,
// The date that will be treated as 'today'.
todayDate: function(){
var today = new Date();
return today._clear();
},
// The date that will appear selected when the spacecalendar renders.
// By default it will be set to todayDate.
selectedDate: null,
// Names of the month that will be shown in the title.
// Will default to 1月, 2月,...,12月
monthNames: null,
// Names of the days of the Week that will be shown below the title.
// Will default to 周一, 周二,...,周日
dowNames: null,
// The day of the week to start the spacecalendar on. 0 is Sunday, 1 is Monday and so on.
dowOffset: 1,
// First date of the month.
firstDate: null
};
// Our plugin object
var spacecalendar = (function() {
// Main entry point. Initialize the plugin
function spacecalendar(element, userOptions) {
// Grab handle to this
var self = this;
// Save bound element to el
self.el = $(element);
var el = self.el;
// Merge user options into default options
self.options = $.extend(true, {}, $.fn.spacecalendar.defaults, userOptions);
var options = self.options;
// Find the spacecalendar element if the user provided one
self.spacecalendar = $($.find('[gldp-el=' + el.attr('gldp-id') + ' ]'));
if(!(el.attr('gldp-id') || '').length) {
el.attr('gldp-id', 'gldp-' + Math.round(Math.random() * 1e10))
}
el.addClass('gldp-el');
// Render spacecalendar
self.render();
// self.show();
};
// Public methods
spacecalendar.prototype =
{
// Render the spacecalendar
render: function(renderCalback) {
var self = this;
var el = self.el;
var options = self.options;
var spacecalendar = self.spacecalendar;
// Build a core class (with border) that every element would have
var coreClass = ' core border ';
var cssName = 'gldp-default';
// Get today
var todayVal = options.todayDate()._val();
var todayTime = todayVal.time/1000;
// Constants
var maxRow = 6;
var maxCol = 7;
var dowNames = options.dowNames || [ '周日', '周一', '周二', '周三', '周四', '周五', '周六' ];
var monthNames = options.monthNames || [ ' 1 月', ' 2 月', ' 3 月', ' 4 月', ' 5 月', ' 6 月', ' 7 月', ' 8 月', ' 9 月', ' 10 月', ' 11 月', ' 12 月' ];
// Create container width based on el size
var containerWidth = el.outerWidth();
// Create cell width based on container size
var cellWidth = containerWidth / maxCol;
// If spacecalendar doesn't exist, create it and re-assign it to self
if(!spacecalendar.length) {
self.spacecalendar = spacecalendar = $('<div/>')
.attr('gldp-el', el.attr('gldp-id'))
.css(
{
width: containerWidth + 'px'
});
$(el).append(spacecalendar);
}
// Add core classes and remove spacecalendar's children
spacecalendar.removeClass()
.addClass(cssName)
.children().remove();
// Helper function to setDate
(function() {
var _firstDate = new Date(options.startDate);
if(_firstDate.getDate() != 1){
_firstDate.setDate(1);
_firstDate.setMonth(_firstDate.getMonth() + 1);
}
options.firstDate = _firstDate;
})();
var getStartEndDate = function(_offset) {
// Create start date as the first date of the month
var _firstDate = new Date(options.firstDate);
// Default to no offset
_offset = _offset || 0;
// Adjust date for month offset
_firstDate.setMonth(_firstDate.getMonth() + _offset);
var startOffset = _firstDate.getDay() - options.dowOffset;
startOffset = startOffset < 1 ? -7 - startOffset : -startOffset;
var _startDate = _firstDate._add(startOffset)/1000,
_endDate = _firstDate._add(7*6-1)/1000;
return {startDate: _startDate, endDate: _endDate};
};
// Get the previous, next start/end dates
var prevDateObj = getStartEndDate(-1),
nextDateObj = getStartEndDate(1);
var prevStartDate = prevDateObj.startDate,
prevEndDate = prevDateObj.endDate;
var nextStartDate = nextDateObj.startDate,
nextEndDate = nextDateObj.endDate;
// Get the first date for the current month being rendered
var firstDateVal = options.firstDate._val();
var firstDateMonth = firstDateVal.month;
var firstDateYear = firstDateVal.year;
var prevCell = $('<div/>')
.addClass("title")
.append(
$('<img/>')
.addClass('prev-arrow')
.attr("src", "/public/img/prev.png")
)
.mousedown(function() { return false; })
.click(function(e) {
window.location.href = "/spaces/index?house_id=" + options.houseId + "&startDate=" + prevStartDate + "&endDate=" + prevEndDate;
});
var titleCell = $('<div/>').addClass('title');
var nextCell = $('<div/>')
.addClass("title")
.append(
$('<img/>')
.addClass('next-arrow')
.attr("src", "/public/img/next.png")
)
.mousedown(function() { return false; })
.click(function(e) {
window.location.href = "/spaces/index?house_id=" + options.houseId + "&startDate=" + nextStartDate + "&endDate=" + nextEndDate;
});
// Add cells for prev/title/next
spacecalendar
.append(prevCell)
.append(titleCell)
.append(nextCell)
.append($('<div style="clear: both;"></div>'));
// Add all the cells to the spacecalendar
for(var row = 0, cellIndex = 0; row < maxRow + 1; row++) {
for(var col = 0; col < maxCol; col++, cellIndex++) {
var cellDate = new Date(options.startDate);
var cellClass = 'day';
var cell = $('<div/>');
var cellCSS = {width: cellWidth + 'px'};
if(!row) {
cellClass = 'core dow';
cell.html(dowNames[col]);
cellDate = null;
// Assign other properties to the cell
cell.addClass(cellClass)
.css(cellCSS);
if(col == maxCol-2){
cell.addClass("sat");
}else if(col == maxCol-1){
cell.addClass("sun");
}
} else {
// Get the new date for this cell
cellDate._add(col + ((row - 1) * maxCol));
// Get value for this date
var cellDateVal = cellDate._val();
var cellDateTime = cellDateVal.time/1000;
// Assign date for the cell
var daySpan = $("<span/>");
daySpan.addClass("day").html(cellDateVal.date + "日");
cell.append(daySpan);
// 房源配置信息
var spaceDiv = $("<div/>");
if(options.spaceData.length == 0){
if(todayTime <= cellDateTime){
spaceDiv.addClass("opening countDiv").html("等待开放预约");
}else{
spaceDiv.addClass("unopened countDiv").html("未开放预约");
}
}else{
var isFind = false;
for(var i = 0, len = options.spaceData.length; i < len; i++){
var spaceData = options.spaceData[i];
if(spaceData.useDate == cellDateTime){
var slashSpan = $('<span/>').html(" / ");
var useSpan = $('<span/>');
useSpan.addClass("useCount").html(spaceData.useCount);
var totalSpan = $('<span/>');
totalSpan.addClass("totalCount").html(spaceData.totalCount);
spaceDiv
.addClass("opened countDiv")
.append(useSpan)
.append(slashSpan)
.append(totalSpan);
cell.data('spaceData', spaceData);
isFind = true;
break;
}
}
if(!isFind){
if(todayTime <= cellDateTime){
spaceDiv.addClass("opening countDiv").html("等待开放预约");
}else{
spaceDiv.addClass("unopened countDiv").html("未开放预约");
}
}
}
cell.append(spaceDiv);
// Handle active dates and weekends
cellClass = ([ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ])[cellDateVal.day];
// Handle today or selected dates
if(cellDateVal.month != firstDateMonth) { cellClass += ' outMonth'; }
if(cellDateTime < todayTime) { cellClass += ' prevDay'; }
if(cellDateTime == todayTime) { cellClass = 'today';}
// Update the css for the cell
if(col == 0){
$.extend(cellCSS,
{
borderLeftWidth: 0
});
}else if(col == 6){
$.extend(cellCSS,
{
borderRightWidth: 0
});
}
// Assign other properties to the cell
cell
.data('useDate', cellDateTime)
.addClass(coreClass + cellClass)
.css(cellCSS);
// 加入popover
if(options.isEditable){
if(cellDateTime >= todayTime) {
cell.spacepopover("init", {id: cellDateTime, idName: "spacePopover"});
}
}
}
// Add cell to spacecalendar
spacecalendar.append(cell);
}
}
// Render the month / year title
// Build month label
var monthText = $('<span/>')
.html(monthNames[firstDateMonth]);
// Build year label
var yearText = $('<span/>')
.html(firstDateYear + " 年 ");
var titleYearMonth = $('<div/>')
.append(yearText)
.append(monthText);
// Add to title
titleCell.children().remove();
titleCell.append(titleYearMonth);
// Run the callback signaling end of the render
renderCalback = renderCalback || (function() {});
renderCalback();
}
};
// Return the plugin
return spacecalendar;
})();
// One time initialization of useful prototypes
(function() {
Date.prototype._clear = function() {
this.setHours(8);
this.setMinutes(0);
this.setSeconds(0);
this.setMilliseconds(0);
return this;
};
Date.prototype._add = function(days) {
return this.setDate(this.getDate() + days);
};
Date.prototype._val = function() {
return {
year: this.getFullYear(),
month: this.getMonth(),
date: this.getDate(),
time: this.getTime(),
day: this.getDay()
};
};
})();
})();

View File

@@ -0,0 +1,269 @@
(function( $ ){
var methods = {
init : function( options ){
var $this = this;
options = $.extend( $.fn.spacepopover.options, options );
return this.each(function(){
var $this = $(this);
var spaceEntity = $this.data("spaceData")||{};
var idName = options.idName;
var id = options.id;
var shownFunc = options.shownFunc;
var changeFollowFunc = options.changeFollowFunc;
$this.data("data-id", id);
$this.data("data-idName", idName);
$this.popover({
placement: 'left',
trigger:"manual",
html : true,
animation:false,
container:"body",
content: (function(arg){
return function(){
return $this.spacepopover("getPopoverHtml", spaceEntity, idName, id);
}
})(id)
});
$this.on("click", function(){
var $activePop = $(".popover.in");
if($activePop.length > 0){
$activePop.spacepopover("hidePopover");
}else{
$this.spacepopover("showPopover");
}
});
$this.on('shown.bs.popover', function(){
if(shownFunc != null){
return shownFunc;
}else{
$("#saveButton").on("click", function(e){
$(this).attr('disabled', "true");
var spaceEntity = $this.data("spaceData") || {};
var $popContainer = $(this).parent();
var totalCount = $popContainer.find(".totalCount").val();
totalCount = $.trim(totalCount);
if($.isEmptyObject(spaceEntity)){
if(totalCount == ""){
$("#drTipbar").drtipbar("showMsg", "开放工位不能为空");
$(this).removeAttr('disabled');
return false;
}
if(totalCount == 0){
$("#drTipbar").drtipbar("showMsg", "开放工位必须大于0");
$(this).removeAttr('disabled');
return false;
}
$this.spacepopover("createAction", totalCount, $(this));
} else {
var spaceId = spaceEntity.id,
useCount = spaceEntity.useCount;
if(totalCount < useCount){
$("#drTipbar").drtipbar("showMsg", "开放工位不能小于已售出工位");
$(this).removeAttr('disabled');
return false;
}
if(useCount > 0 && totalCount == spaceEntity.totalCount){
return false;
}
if(totalCount == 0 || totalCount == ""){
$this.spacepopover("deleteAction", spaceId, $(this));
}else{
$this.spacepopover("updateAction", spaceId, totalCount, $(this));
}
}
});
}
});
});
},
createAction: function(totalCount, $ele){
var $this = $(this);
var useDate = $this.data("useDate");
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/spaces/create",
data : "house_id=" + g_houseId + "&useDate=" + useDate + "&totalCount=" + totalCount,
beforeSend:function(){
var currentReq = $this.data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$this.data("jRequest",null);
},
success : function(data){
var countDiv = $this.find(".countDiv");
var slashSpan = $('<span/>').html("/");
var useSpan = $('<span/>');
useSpan.addClass("useCount").html(data.useCount);
var totalSpan = $('<span/>');
totalSpan.addClass("totalCount").html(data.totalCount);
countDiv
.empty()
.attr("class", "opened countDiv")
.append(useSpan)
.append(slashSpan)
.append(totalSpan);
$this.data('spaceData', data);
$this.spacepopover("hidePopover");
},
error : function(data){
$ele.removeAttr('disabled');
$("#drTipbar").drtipbar("showMsg", data.responseJSON.errMessage);
if(data.statusText=="abort"){
return;
}
}
});
$this.data("jRequest", jRequest);
},
deleteAction: function(spaceId, $ele){
var $this = $(this);
var useDate = $this.data("useDate");
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/spaces/delete",
data : "space_id=" + spaceId,
beforeSend:function(){
var currentReq = $this.data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$this.data("jRequest",null);
},
success : function(data){
var countDiv = $this.find(".countDiv");
countDiv
.empty()
.attr("class", "opening countDiv")
.html("等待开放预约")
$this.data('spaceData', data);
$this.spacepopover("hidePopover");
},
error : function(data){
$ele.removeAttr('disabled');
$("#drTipbar").drtipbar("showMsg", data.responseJSON.errMessage);
if(data.statusText=="abort"){
return;
}
}
});
$this.data("jRequest", jRequest);
},
updateAction: function(spaceId, totalCount, $ele){
var $this = $(this);
var useDate = $this.data("useDate");
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/spaces/update",
data : "totalCount=" + totalCount + "&space_id=" + spaceId,
beforeSend:function(){
var currentReq = $this.data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$this.data("jRequest",null);
},
success : function(data){
$this.find(".useCount").html(data.useCount);
$this.find(".totalCount").html(data.totalCount);
$this.data('spaceData', data);
$this.spacepopover("hidePopover");
},
error : function(data){
$ele.removeAttr('disabled');
$("#drTipbar").drtipbar("showMsg", data.responseJSON.errMessage);
if(data.statusText=="abort"){
return;
}
}
});
$this.data("jRequest", jRequest);
},
showPopover:function(){
var $this = $(this),
spaceEntity = $this.data("spaceData") || {},
id = $this.data("data-id"),
idName = $this.data("data-idName");
$this.popover("show");
var popDiv = $("#"+idName+id);
popDiv.find(".totalCount").val(spaceEntity.totalCount || 0);
popDiv.find(".useCount").html(spaceEntity.useCount || 0);
popDiv.find(".availableCount").html(spaceEntity.availableCount || 0);
},
hidePopover:function(){
var $this = $(this);
$this.popover("hide");
},
getPopoverHtml:function(spaceEntity, idName, id){
var totalCount = spaceEntity.totalCount || 0,
useCount = spaceEntity.useCount || 0,
availableCount = spaceEntity.availableCount || 0;
return '<div id="' + idName + id + '" class="spacePopoverContentContainer">\
<p class="total">\
<span class="totalTitle">开放工位</span>\
<input class="totalCount rightPos" value="' + totalCount + '" onpaste="return false;" onkeypress="numberLimit()" />\
<div class="clear"></div>\
</p>\
<p class="use">\
<span class="useTitle">已售出工位</span>\
<span class="useCount rightPos">' + useCount + '</span>\
<div class="clear"></div>\
</p>\
<p class="available">\
<span class="availableTitle">剩余工位</span>\
<span class="availableCount rightPos">' + availableCount + '</span>\
<div class="clear"></div>\
</p>\
<button class="btnBlue" id="saveButton">保存</button>\
</div>';
}
};
$.fn.spacepopover = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.spacepopover' );
}
};
$.fn.spacepopover.options = {};
})( jQuery );

View File

@@ -0,0 +1,265 @@
(function($) {
var methods = {
init: function(options) {
var $this = this;
options = $.extend($.fn.teampopover.options, options);
return this.each(function() {
var $this = $(this);
var teamEntity = options.teamEntity;
var idName = options.idName;
var id = options.id;
var shownFunc = options.shownFunc;
var changeFollowFunc = options.changeFollowFunc;
var hasLogin = options.hasLogin;
var redirectLoginUrl = options.redirectLoginUrl;
if (teamEntity == null) {
return;
}
$this.data("teamEntity", teamEntity);
$this.data("idName", idName);
$this.data("id", id);
$this.data("hasLogin", hasLogin);
$this.data("redirectLoginUrl", redirectLoginUrl);
//加上对应data标记
$this.attr("data-teampopover", id);
$this.popover({
trigger: "manual",
html: true,
animation: false,
container: "body",
content: (function(arg) {
return function() {
return $this.teampopover("getPopoverHtml", teamEntity, idName, id);
}
})(id)
});
$this.on("mouseenter", (function(arg) {
return function(e) {
var appearTimeOut = setTimeout(function() {
appearTimeOut = null;
$this.off("mouseleave");
if ($this.data('bs.popover').tip().hasClass('in')) {
return;
}
$this.teampopover("showPopover");
var timeout = null;
$this.on("mouseleave", function(e) {
timeout = setTimeout(function() {
$this.teampopover("hidePopover");
}, 500);
});
$("#" + idName + arg).parent().parent().off("mouseenter");
$("#" + idName + arg).parent().parent().on("mouseenter", function() {
if (timeout != null) {
clearTimeout(timeout);
timeout = null;
}
$("#" + idName + arg).parent().parent().off("mouseleave");
$("#" + idName + arg).parent().parent().on("mouseleave", function() {
$this.teampopover("hidePopover");
});
});
}, 500);
$this.on("mouseleave", function() {
if (appearTimeOut != null) {
clearTimeout(appearTimeOut);
appearTimeOut = null;
}
});
}
})(id));
$this.on('shown.bs.popover', (function(arg) {
if (shownFunc != null) {
return shownFunc;
} else {
return function(e) {
var hasLogin = $this.data("hasLogin");
var redirectLoginUrl = $this.data("redirectLoginUrl");
var dataplacement = $this.data("placement");
//调整位置
var oldTop = $('.popover').css('top');
oldTop = parseInt(oldTop.substr(0, oldTop.length - 2));
var newTop = 0;
if (dataplacement == "top") {
newTop = oldTop - 5;
} else {
newTop = oldTop + 5;
}
$('.popover').css('top', newTop + "px");
var newLeft = $(e.target).offset().left - 50,
contentWidth = e.target.offsetWidth;
$('.popover').css('left', newLeft + "px");
$('.arrow').css('left', contentWidth / 2 + 50 + 'px');
$("[data-popoverfollowteamid]").on("click", function(e) {
e.preventDefault();
if (!hasLogin) {
window.location.href = redirectLoginUrl;
return;
}
var followTeamId = $("[data-popoverfollowteamid]").data("popoverfollowteamid");
var isYourFollow = $("[data-popoverfollowteamid]").data("popoverisfollowteam");
if (isYourFollow == 0) {
$("[data-popoverfollowteamid=" + followTeamId + "]").addClass("active");
$("[data-popoverfollowteamid=" + followTeamId + "]").text("已关注");
$("[data-popoverfollowteamid=" + followTeamId + "]").data("popoverisfollowteam", 1);
if (changeFollowFunc != null) {
changeFollowFunc(followTeamId, 1);
}
var jRequest = jQuery.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: "/teams/followteam",
data: "team_id=" + followTeamId,
beforeSend: function() {
var currentReq = $("[data-popoverfollowteamid]").data("jRequest");
if (currentReq != null) {
currentReq.abort();
}
},
complete: function() {
$("[data-popoverFollowTeamId]").data("jRequest", null);
},
success: function(data) {
},
error: function(data) {
if (data.statusText == "abort") {
return;
}
$("[data-popoverfollowteamid=" + followTeamId + "]").removeClass("active");
$("[data-popoverfollowteamid=" + followTeamId + "]").text("关注");
$("[data-popoverfollowteamid=" + followTeamId + "]").data("popoverisfollowteam", 0);
if (changeFollowFunc != null) {
changeFollowFunc(followTeamId, 0);
}
}
});
$("[data-popoverfollowteamid]").data("jRequest", jRequest);
} else {
//取消关注
$("[data-popoverfollowteamid=" + followTeamId + "]").removeClass("active");
$("[data-popoverfollowteamid=" + followTeamId + "]").text("关注");
$("[data-popoverfollowteamid=" + followTeamId + "]").data("popoverisfollowteam", 0);
if (changeFollowFunc != null) {
changeFollowFunc(followTeamId, 0);
}
var jRequest = jQuery.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: "/teams/unfollowteam",
data: "team_id=" + followTeamId,
beforeSend: function() {
var currentReq = $("[data-popoverfollowteamid]").data("jRequest");
if (currentReq != null) {
currentReq.abort();
}
},
complete: function() {
$("[data-popoverfollowteamid]").data("jRequest", null);
},
success: function(data) {
},
error: function(data) {
if (data.statusText == "abort") {
return;
}
$("[data-popoverfollowteamid=" + followTeamId + "]").addClass("active");
$("[data-popoverfollowteamid=" + followTeamId + "]").text("已关注");
$("[data-popoverfollowteamid=" + followTeamId + "]").data("popoverisfollowteam", 1);
if (changeFollowFunc != null) {
changeFollowFunc(followTeamId, 1);
}
}
});
$("[data-popoverfollowteamid]").data("jRequest", jRequest);
}
});
}
}
})(id));
});
},
showPopover: function() {
var $this = this;
return this.each(function() {
//hide掉其他所有的
$("[data-teampopover]").popover("hide");
$this.popover("show");
});
},
hidePopover: function() {
var $this = this;
return this.each(function() {
$this.popover("hide");
});
},
getPopoverHtml: function(teamEntity, idName, id) {
if (teamEntity == null) {
return null;
}
var fromTeamIconUrl = teamEntity.iconThumbUrl,
fromTeamName = teamEntity.name,
fromTeamWord = teamEntity.content,
fromTeamArticleCount = teamEntity.articleCount,
fromTeamFanCount = teamEntity.followCount,
teamPopoverFollowStr = "",
teamPopoverFollowStrClass = "",
fromTeamId = teamEntity.id;
if (teamEntity.hasFollow == 1) {
teamPopoverFollowStr = "已关注";
teamPopoverFollowStrClass = "btnBlue active ";
} else {
teamPopoverFollowStr = "关注";
teamPopoverFollowStrClass = "btnBlue ";
}
return '<div id="' + idName + id + '" class="teamPopoverContentContainer">\
<div>\
<a target="_blank" href="/teams/get?id=' + fromTeamId + '"><img class="teamPopoverTeamIcon img-circle" src="' + fromTeamIconUrl + '"/></a>\
<div class="teamPopoverTeamInfoContainer">\
<p class="teamPopoverTeamName"><a target="_blank" href="/teams/get?id=' + fromTeamId + '">' + $.htmlspecialchars(fromTeamName) + '</a></p>\
<p class="teamPopoverTeamWord">' + $.htmlspecialchars(fromTeamWord) + '</p>\
</div>\
<div class="clear"></div>\
<div class="divider"></div>\
</div>\
<div class="teamPopoverContentCountInfoContainer">\
<div class="teamPopoverContentCountInfo">\
<div class="teamPopoverContentArticleCountContainer"><span>' + fromTeamArticleCount + '</span><span>文章</span></div>\
<div class="teamPopoverContentFanCountContainer"><span>' + fromTeamFanCount + '</span><span>粉丝</span></div>\
</div>\
<button class="' + teamPopoverFollowStrClass + ' teamPopoverFollowButton" data-popoverisfollowteam=' + teamEntity.hasFollow + ' data-popoverfollowteamid="' + teamEntity.id + '" id="teamPopoverFollowButton' + id + '">' + teamPopoverFollowStr + '</button>\
<div class="clear"></div>\
</div>\
</div>';
}
};
$.fn.teampopover = function(method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.teampopover');
}
};
$.fn.teampopover.options = {};
})(jQuery);

View File

@@ -0,0 +1,81 @@
(function( $ ){
var methods = {
init : function( options ){
var $this = this;
options = $.extend( $.fn.drtipbar.options, options );
return this.each(function(){
// this.isShow = false;
var $this = $(this);
$this.data("isShow", false);
$this.data("disappearTimer" , null);
// this.disappearTimer = null;
});
},
showMsg:function(msg){
return this.each(function(){
var $this = $(this);
if($this.data("isShow")){
//直接显示msg
$("#drTipbarContent").text(msg);
$this.data("isShow", true);
if($this.data("disappearTimer") != null){
clearTimeout($this.data("disappearTimer") );
var disappearTimer=setTimeout(function(){
//消失动画
$this.removeClass("drTipShow").addClass("drTipHide");
$this.one(($.getTransitionEnd()).end, function() {
$this.data("disappearTimer",null)
$this.data("isShow",false)
});
},3000);
$this.data("disappearTimer",disappearTimer)
}
}else{
$this.data("isShow", true);
$("#drTipbarContent").text(msg);
$this.removeClass("drTipHide").addClass("drTipShow");
var disappearTimer=setTimeout(function(){
//消失动画
$this.removeClass("drTipShow").addClass("drTipHide");
$this.one(($.getTransitionEnd()).end, function() {
$this.data("disappearTimer",null)
$this.data("isShow",false)
});
},3000);
$this.data("disappearTimer",disappearTimer)
}
});
}
};
$.fn.drtipbar = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.drtipbar' );
}
};
$.fn.drtipbar.options = {};
})( jQuery );

View File

@@ -0,0 +1,332 @@
(function( $ ){
var methods = {
init : function( options ){
var $this = this;
options = $.extend( $.fn.userpopover.options, options );
return this.each(function(){
var $this = $(this);
var userEntity = options.userEntity;
var idName = options.idName;
var id = options.id;
var shownFunc = options.shownFunc;
var currentUserId = options.currentUserId;
var changeFollowFunc = options.changeFollowFunc;
var hasLogin = options.hasLogin;
var redirectLoginUrl = options.redirectLoginUrl;
if(userEntity == null){
return;
}
$this.data("userEntity",userEntity);
$this.data("idName",idName);
$this.data("id",id);
$this.data("currentUserId",currentUserId);
$this.data("hasLogin",hasLogin);
$this.data("redirectLoginUrl",redirectLoginUrl);
//加上对应data标记
$this.attr("data-userpopover",id);
$this.popover({
trigger:"manual",
html : true,
animation:false,
container:"body",
content: (function(arg){
return function(){
return $this.userpopover("getPopoverHtml",userEntity,idName,id);
}
})(id)
});
$this.on("mouseenter",(function(arg){
return function(e){
var appearTimeOut = setTimeout(function(){
appearTimeOut = null;
$this.off("mouseleave");
if($this.data('bs.popover').tip().hasClass('in')){
return;
}
$this.userpopover("showPopover");
var timeout = null;
$this.on("mouseleave",function(e){
timeout = setTimeout(function(){
$this.userpopover("hidePopover");
},500);
});
$("#"+idName + arg ).parent().parent().off("mouseenter");
$("#"+idName + arg ).parent().parent().on("mouseenter",function(){
if(timeout != null){
clearTimeout(timeout);
timeout = null;
}
$("#"+idName + arg ).parent().parent().off("mouseleave");
$("#"+idName + arg ).parent().parent().on("mouseleave",function(){
$this.userpopover("hidePopover");
});
});
},500);
$this.on("mouseleave",function(){
if(appearTimeOut != null){
clearTimeout(appearTimeOut);
appearTimeOut = null;
}
});
}
})(id));
$this.on('shown.bs.popover',(function(arg){
if(shownFunc != null){
return shownFunc;
}else{
return function(e){
var currentUserId = $this.data("currentUserId");
var hasLogin = $this.data("hasLogin");
var redirectLoginUrl = $this.data("redirectLoginUrl");
var dataplacement = $this.data("placement");
//调整位置
var oldTop = $('.popover').css('top');
oldTop = parseInt(oldTop.substr(0,oldTop.length - 2));
var newTop = 0;
if(dataplacement == "top"){
newTop = oldTop - 5;
}else{
newTop = oldTop + 5;
}
$('.popover').css('top', newTop + "px");
var oldLeft = $('.popover').css('left');
oldLeft = parseInt(oldLeft.substr(0,oldLeft.length - 2));
var newLeft = oldLeft;
var outerWidth = $('.popover').outerWidth();
newLeft = $(e.target).offset().left - 50;
var contentWidth = e.target.offsetWidth;
$('.popover').css('left', newLeft + "px");
$('.arrow').css('left',contentWidth/2 + 50 + 'px');
var role = $("[data-popoverfollowuserid]").data("popoveruserrole");
var popUserId = $("[data-popoverfollowuserid]").data("popoverfollowuserid");
if(role == "超级管理员" || currentUserId == popUserId ){
$("[data-popoverfollowuserid]").hide();
}
$("[data-popoverfollowuserid]").on("click",function(e){
e.preventDefault();
if(!hasLogin){
window.location.href=redirectLoginUrl;
return;
}
var followUserId = $("[data-popoverfollowuserid]").data("popoverfollowuserid");
var isYourFollow = $("[data-popoverfollowuserid]").data("popoverisfollowuser");
if(isYourFollow == 0){
$("[data-popoverfollowuserid="+followUserId+"]").addClass("active");
$("[data-popoverfollowuserid="+followUserId+"]").text("已关注");
$("[data-popoverfollowuserid="+followUserId+"]").data("popoverisfollowuser",1);
if(changeFollowFunc != null){
changeFollowFunc(followUserId,1);
}
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/users/follow",
data : "follow_id=" + followUserId,
beforeSend:function(){
var currentReq = $("[data-popoverfollowuserid]").data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$("[data-popoverFollowUserId]").data("jRequest",null);
},
success : function(data){
//刷新ui
$("[data-popoverfollowuserid="+followUserId+"]").addClass("active");
$("[data-popoverfollowuserid="+followUserId+"]").text("已关注");
$("[data-popoverfollowuserid="+followUserId+"]").data("popoverisfollowuser",1);
if(changeFollowFunc != null){
changeFollowFunc(followUserId,1);
}
},
error : function(data){
if(data.statusText=="abort"){
return;
}
$("[data-popoverfollowuserid="+followUserId+"]").removeClass("active");
$("[data-popoverfollowuserid="+followUserId+"]").text("关注");
$("[data-popoverfollowuserid="+followUserId+"]").data("popoverisfollowuser",0);
if(changeFollowFunc != null){
changeFollowFunc(followUserId,0);
}
}});
$("[data-popoverfollowuserid]").data("jRequest",jRequest);
}else{
//取消关注
$("[data-popoverfollowuserid="+followUserId+"]").removeClass("active");
$("[data-popoverfollowuserid="+followUserId+"]").text("关注");
$("[data-popoverfollowuserid="+followUserId+"]").data("popoverisfollowuser",0);
if(changeFollowFunc != null){
changeFollowFunc(followUserId,0);
}
var jRequest = jQuery.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded",
url : "/users/unfollow",
data : "follow_id=" + followUserId,
beforeSend:function(){
var currentReq = $("[data-popoverfollowuserid]").data("jRequest");
if(currentReq != null){
currentReq.abort();
}
},
complete:function(){
$("[data-popoverfollowuserid]").data("jRequest",null);
},
success : function(data){
$("[data-popoverfollowuserid="+followUserId+"]").removeClass("active");
$("[data-popoverfollowuserid="+followUserId+"]").text("关注");
$("[data-popoverfollowuserid="+followUserId+"]").data("popoverisfollowuser",0);
if(changeFollowFunc != null){
changeFollowFunc(followUserId,0);
}
},
error : function(data){
if(data.statusText=="abort"){
return;
}
$("[data-popoverfollowuserid="+followUserId+"]").addClass("active");
$("[data-popoverfollowuserid="+followUserId+"]").text("已关注");
$("[data-popoverfollowuserid="+followUserId+"]").data("popoverisfollowuser",1);
if(changeFollowFunc != null){
changeFollowFunc(followUserId,1);
}
}
});
$("[data-popoverfollowuserid]").data("jRequest",jRequest);
}
});
}
}
})(id));
});
},
showPopover:function(){
var $this = this;
return this.each(function(){
//hide掉其他所有的
$("[data-userpopover]").popover("hide");
$this.popover("show");
});
},
hidePopover:function(){
var $this = this;
return this.each(function(){
$this.popover("hide");
});
},
getPopoverHtml:function(userEntity,idName,id){
if(userEntity == null){
return null;
}
var fromUserAvatarUrl = userEntity.avatarThumbUrl;
var fromUserName = userEntity.userName;
var fromUserWord = userEntity.word;
var fromUserArticleCount = userEntity.articleCount;
var fromUserFanCount = userEntity.fanCount;
var userPopoverFollowStr = "";
var userPopoverFollowStrClass = "";
var fromUserGuid = userEntity.guid;
if(userEntity.isYourFollow == 1){
userPopoverFollowStr = "已关注";
userPopoverFollowStrClass = "btnBlue active ";
}else{
userPopoverFollowStr = "关注";
userPopoverFollowStrClass = "btnBlue ";
}
return '<div id="' + idName + id + '" class="userPopoverContentContainer">\
<div>\
<a target="_blank" href="/users/get?guid='+fromUserGuid+'"><img class="userPopoverUserAvatar img-circle" src="'+fromUserAvatarUrl+'"/></a>\
<div class="userPopoverUserInfoContainer">\
<p class="userPopoverUserName"><a target="_blank" href="/users/get?guid='+fromUserGuid+'">'+$.htmlspecialchars(fromUserName)+'</a></p>\
<p class="userPopoverUserWord">'+$.htmlspecialchars(fromUserWord)+'</p>\
</div>\
<div class="clear"></div>\
<div class="divider"></div>\
</div>\
<div class="userPopoverContentCountInfoContainer">\
<div class="userPopoverContentCountInfo">\
<div class="userPopoverContentArticleCountContainer"><span>'+fromUserArticleCount+'</span><span>文章</span></div>\
<div class="userPopoverContentFanCountContainer"><span>'+fromUserFanCount+'</span><span>粉丝</span></div>\
</div>\
<button class="'+userPopoverFollowStrClass+' userPopoverFollowButton" data-popoveruserrole="'+userEntity.role+'" data-popoverisfollowuser='+userEntity.isYourFollow+' data-popoverfollowuserid="'+userEntity.id+'" id="userPopoverFollowButton'+id+'">'+userPopoverFollowStr+'</button>\
<div class="clear"></div>\
</div>\
</div>';
}
};
$.fn.userpopover = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.userpopover' );
}
};
$.fn.userpopover.options = {};
})( jQuery );

View File

@@ -0,0 +1,71 @@
/**
* file-input.js
* target container must be id "preview"
*/
function previewImage(file,className,id)
{
var MAXWIDTH,MAXHEIGHT;
var div = $('#'+id).get(0);
if(className==='preview-long'){
MAXWIDTH = 200;
MAXHEIGHT = 356;
}
else if(className==='preview-short'){
MAXWIDTH = 200;
MAXHEIGHT = 300;
}
else{
MAXWIDTH = 120;
MAXHEIGHT = 120;
}
if (file.files && file.files[0])
{
div.innerHTML = '<img class=imghead>';
var img = $('#'+id).find('.imghead').get(0);
img.onload = function(){
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
img.width = rect.width;
img.height = rect.height;
img.style.marginLeft = rect.left+'px';
img.style.marginTop = rect.top+'px';
}
var reader = new FileReader();
reader.onload = function(evt){img.src = evt.target.result;}
reader.readAsDataURL(file.files[0]);
}
else
{
var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
file.select();
var src = document.selection.createRange().text;
div.innerHTML = '<img class=imghead>';
var img = $('#'+id).find('.imghead').get(0);
img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height);
div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;margin-left:"+rect.left+"px;"+sFilter+src+"\"'></div>";
}
$('.file').attr('name','image');
}
function clacImgZoomParam( maxWidth, maxHeight, width, height ){
var param = {top:0, left:0, width:width, height:height};
if( width>maxWidth || height>maxHeight )
{
rateWidth = width / maxWidth;
rateHeight = height / maxHeight;
if( rateWidth > rateHeight )
{
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
}else
{
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
}
param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
}

9789
frontend/static/js/jquery-1.10.2.js vendored Normal file

File diff suppressed because it is too large Load Diff

10346
frontend/static/js/jquery-1.11.2.js vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,469 @@
/*
* EASYDROPDOWN - A Drop-down Builder for Styleable Inputs and Menus
* Version: 2.1.3
* License: Creative Commons Attribution 3.0 Unported - CC BY 3.0
* http://creativecommons.org/licenses/by/3.0/
* This software may be used freely on commercial and non-commercial projects with attribution to the author/copyright holder.
* Author: Patrick Kunka
* Copyright 2013 Patrick Kunka, All Rights Reserved
*/
(function($){
function EasyDropDown(){
this.isField = true,
this.down = false,
this.inFocus = false,
this.disabled = false,
this.cutOff = false,
this.hasLabel = false,
this.keyboardMode = false,
this.nativeTouch = true,
this.wrapperClass = 'dropdown',
this.onChange = null;
};
EasyDropDown.prototype = {
constructor: EasyDropDown,
instances: [],
init: function(domNode, settings){
var self = this;
$.extend(self, settings);
self.$select = $(domNode);
self.id = domNode.id;
self.options = [];
self.$options = self.$select.find('option');
self.isTouch = 'ontouchend' in document;
self.$select.removeClass(self.wrapperClass+' dropdown');
if(self.$select.is(':disabled')){
self.disabled = true;
};
if(self.$options.length){
self.$options.each(function(i){
var $option = $(this);
if($option.is(':selected')){
self.selected = {
index: i,
title: $option.text()
}
self.focusIndex = i;
};
if($option.hasClass('label') && i == 0){
self.hasLabel = true;
self.label = $option.text();
$option.attr('value','');
} else {
self.options.push({
domNode: $option[0],
title: $option.text(),
value: $option.val(),
selected: $option.is(':selected')
});
};
});
if(!self.selected){
self.selected = {
index: 0,
title: self.$options.eq(0).text()
}
self.focusIndex = 0;
};
self.render();
};
},
render: function(){
var self = this,
touchClass = self.isTouch && self.nativeTouch ? ' touch' : '',
disabledClass = self.disabled ? ' disabled' : '';
self.$container = self.$select.wrap('<div class="'+self.wrapperClass+touchClass+disabledClass+'"><span class="old"/></div>').parent().parent();
self.$active = $('<span class="selected">'+self.selected.title+'</span>').appendTo(self.$container);
self.$carat = $('<span class="carat"/>').appendTo(self.$container);
self.$scrollWrapper = $('<div><ul/></div>').appendTo(self.$container);
self.$dropDown = self.$scrollWrapper.find('ul');
self.$form = self.$container.closest('form');
$.each(self.options, function(){
var option = this,
active = option.selected ? ' class="active"':'';
self.$dropDown.append('<li'+active+'>'+option.title+'</li>');
});
self.$items = self.$dropDown.find('li');
self.maxHeight = 0;
if(self.cutOff && self.$items.length > self.cutOff)self.$container.addClass('scrollable');
for(i = 0; i < self.$items.length; i++){
var $item = self.$items.eq(i);
self.maxHeight += $item.outerHeight();
if(self.cutOff == i+1){
break;
};
};
if(self.isTouch && self.nativeTouch){
self.bindTouchHandlers();
} else {
self.bindHandlers();
};
},
bindTouchHandlers: function(){
var self = this;
self.$container.on('click.easyDropDown',function(){
self.$select.focus();
});
self.$select.on({
change: function(){
var $selected = $(this).find('option:selected'),
title = $selected.text(),
value = $selected.val();
self.$active.text(title);
if(typeof self.onChange === 'function'){
self.onChange.call(self.$select[0],{
title: title,
value: value
});
};
},
focus: function(){
self.$container.addClass('focus');
},
blur: function(){
self.$container.removeClass('focus');
}
});
},
bindHandlers: function(){
var self = this;
self.query = '';
self.$container.on({
'click.easyDropDown': function(){
if(!self.down && !self.disabled){
self.open();
} else {
self.close();
};
},
'mousemove.easyDropDown': function(){
if(self.keyboardMode){
self.keyboardMode = false;
};
}
});
$('body').on('click.easyDropDown.'+self.id,function(e){
var $target = $(e.target),
classNames = self.wrapperClass.split(' ').join('.');
if(!$target.closest('.'+classNames).length && self.down){
self.close();
};
});
self.$items.on({
'click.easyDropDown': function(){
var index = $(this).index();
self.select(index);
self.$select.focus();
},
'mouseover.easyDropDown': function(){
if(!self.keyboardMode){
var $t = $(this);
$t.addClass('focus').siblings().removeClass('focus');
self.focusIndex = $t.index();
};
},
'mouseout.easyDropDown': function(){
if(!self.keyboardMode){
$(this).removeClass('focus');
};
}
});
self.$select.on({
'focus.easyDropDown': function(){
self.$container.addClass('focus');
self.inFocus = true;
},
'blur.easyDropDown': function(){
self.$container.removeClass('focus');
self.inFocus = false;
},
'keydown.easyDropDown': function(e){
if(self.inFocus){
self.keyboardMode = true;
var key = e.keyCode;
if(key == 38 || key == 40 || key == 32){
e.preventDefault();
if(key == 38){
self.focusIndex--
self.focusIndex = self.focusIndex < 0 ? self.$items.length - 1 : self.focusIndex;
} else if(key == 40){
self.focusIndex++
self.focusIndex = self.focusIndex > self.$items.length - 1 ? 0 : self.focusIndex;
};
if(!self.down){
self.open();
};
self.$items.removeClass('focus').eq(self.focusIndex).addClass('focus');
if(self.cutOff){
self.scrollToView();
};
self.query = '';
};
if(self.down){
if(key == 9 || key == 27){
self.close();
} else if(key == 13){
e.preventDefault();
self.select(self.focusIndex);
self.close();
return false;
} else if(key == 8){
e.preventDefault();
self.query = self.query.slice(0,-1);
self.search();
clearTimeout(self.resetQuery);
return false;
} else if(key != 38 && key != 40){
var letter = String.fromCharCode(key);
self.query += letter;
self.search();
clearTimeout(self.resetQuery);
};
};
};
},
'keyup.easyDropDown': function(){
self.resetQuery = setTimeout(function(){
self.query = '';
},1200);
}
});
self.$dropDown.on('scroll.easyDropDown',function(e){
if(self.$dropDown[0].scrollTop >= self.$dropDown[0].scrollHeight - self.maxHeight){
self.$container.addClass('bottom');
} else {
self.$container.removeClass('bottom');
};
});
if(self.$form.length){
self.$form.on('reset.easyDropDown', function(){
var active = self.hasLabel ? self.label : self.options[0].title;
self.$active.text(active);
});
};
},
unbindHandlers: function(){
var self = this;
self.$container
.add(self.$select)
.add(self.$items)
.add(self.$form)
.add(self.$dropDown)
.off('.easyDropDown');
$('body').off('.'+self.id);
},
open: function(){
var self = this,
scrollTop = window.scrollY || document.documentElement.scrollTop,
scrollLeft = window.scrollX || document.documentElement.scrollLeft,
scrollOffset = self.notInViewport(scrollTop);
self.closeAll();
self.$select.focus();
window.scrollTo(scrollLeft, scrollTop+scrollOffset);
self.$container.addClass('open');
self.$scrollWrapper.css('height',self.maxHeight+'px');
self.down = true;
},
close: function(){
var self = this;
self.$container.removeClass('open');
self.$scrollWrapper.css('height','0px');
self.focusIndex = self.selected.index;
self.query = '';
self.down = false;
},
closeAll: function(){
var self = this,
instances = Object.getPrototypeOf(self).instances;
for(var key in instances){
var instance = instances[key];
instance.close();
};
},
select: function(index){
var self = this;
if(typeof index === 'string'){
index = self.$select.find('option[value='+index+']').index() - 1;
};
var option = self.options[index],
selectIndex = self.hasLabel ? index + 1 : index;
self.$items.removeClass('active').eq(index).addClass('active');
self.$active.text(option.title);
self.$select
.find('option')
.removeAttr('selected')
.eq(selectIndex)
.prop('selected',true)
.parent()
.trigger('change');
self.selected = {
index: index,
title: option.title
};
self.focusIndex = i;
if(typeof self.onChange === 'function'){
self.onChange.call(self.$select[0],{
title: option.title,
value: option.value
});
};
},
search: function(){
var self = this,
lock = function(i){
self.focusIndex = i;
self.$items.removeClass('focus').eq(self.focusIndex).addClass('focus');
self.scrollToView();
},
getTitle = function(i){
return self.options[i].title.toUpperCase();
};
for(i = 0; i < self.options.length; i++){
var title = getTitle(i);
if(title.indexOf(self.query) == 0){
lock(i);
return;
};
};
for(i = 0; i < self.options.length; i++){
var title = getTitle(i);
if(title.indexOf(self.query) > -1){
lock(i);
break;
};
};
},
scrollToView: function(){
var self = this;
if(self.focusIndex >= self.cutOff){
var $focusItem = self.$items.eq(self.focusIndex),
scroll = ($focusItem.outerHeight() * (self.focusIndex + 1)) - self.maxHeight;
self.$dropDown.scrollTop(scroll);
};
},
notInViewport: function(scrollTop){
var self = this,
range = {
min: scrollTop,
max: scrollTop + (window.innerHeight || document.documentElement.clientHeight)
},
menuBottom = self.$dropDown.offset().top + self.maxHeight;
if(menuBottom >= range.min && menuBottom <= range.max){
return 0;
} else {
return (menuBottom - range.max) + 5;
};
},
destroy: function(){
var self = this;
self.unbindHandlers();
self.$select.unwrap().siblings().remove();
self.$select.unwrap();
delete Object.getPrototypeOf(self).instances[self.$select[0].id];
},
disable: function(){
var self = this;
self.disabled = true;
self.$container.addClass('disabled');
self.$select.attr('disabled',true);
if(!self.down)self.close();
},
enable: function(){
var self = this;
self.disabled = false;
self.$container.removeClass('disabled');
self.$select.attr('disabled',false);
}
};
var instantiate = function(domNode, settings){
domNode.id = !domNode.id ? 'EasyDropDown'+rand() : domNode.id;
var instance = new EasyDropDown();
if(!instance.instances[domNode.id]){
instance.instances[domNode.id] = instance;
instance.init(domNode, settings);
};
},
rand = function(){
return ('00000'+(Math.random()*16777216<<0).toString(16)).substr(-6).toUpperCase();
};
$.fn.easyDropDown = function(){
var args = arguments,
dataReturn = [],
eachReturn;
eachReturn = this.each(function(){
if(args && typeof args[0] === 'string'){
var data = EasyDropDown.prototype.instances[this.id][args[0]](args[1], args[2]);
if(data)dataReturn.push(data);
} else {
instantiate(this, args[0]);
};
});
if(dataReturn.length){
return dataReturn.length > 1 ? dataReturn : dataReturn[0];
} else {
return eachReturn;
};
};
$(function(){
if(typeof Object.getPrototypeOf !== 'function'){
if(typeof 'test'.__proto__ === 'object'){
Object.getPrototypeOf = function(object){
return object.__proto__;
};
} else {
Object.getPrototypeOf = function(object){
return object.constructor.prototype;
};
};
};
$('select.dropdown').each(function(){
var json = $(this).attr('data-settings');
settings = json ? $.parseJSON(json) : {};
instantiate(this, settings);
});
});
})(jQuery);

View File

@@ -0,0 +1,24 @@
/*
* EASYDROPDOWN - A Drop-down Builder for Styleable Inputs and Menus
* Version: 2.1.3
* License: Creative Commons Attribution 3.0 Unported - CC BY 3.0
* http://creativecommons.org/licenses/by/3.0/
* This software may be used freely on commercial and non-commercial projects with attribution to the author/copyright holder.
* Author: Patrick Kunka
* Copyright 2013 Patrick Kunka, All Rights Reserved
*/
(function(d){function e(){this.isField=!0;this.keyboardMode=this.hasLabel=this.cutOff=this.disabled=this.inFocus=this.down=!1;this.nativeTouch=!0;this.wrapperClass="dropdown";this.onChange=null}e.prototype={constructor:e,instances:[],init:function(a,c){var b=this;d.extend(b,c);b.$select=d(a);b.id=a.id;b.options=[];b.$options=b.$select.find("option");b.isTouch="ontouchend"in document;b.$select.removeClass(b.wrapperClass+" dropdown");b.$select.is(":disabled")&&(b.disabled=!0);b.$options.length&&(b.$options.each(function(a){var c=
d(this);c.is(":selected")&&(b.selected={index:a,title:c.text()},b.focusIndex=a);c.hasClass("label")&&0==a?(b.hasLabel=!0,b.label=c.text(),c.attr("value","")):b.options.push({domNode:c[0],title:c.text(),value:c.val(),selected:c.is(":selected")})}),b.selected||(b.selected={index:0,title:b.$options.eq(0).text()},b.focusIndex=0),b.render())},render:function(){var a=this;a.$container=a.$select.wrap('<div class="'+a.wrapperClass+(a.isTouch&&a.nativeTouch?" touch":"")+(a.disabled?" disabled":"")+'"><span class="old"/></div>').parent().parent();
a.$active=d('<span class="selected">'+a.selected.title+"</span>").appendTo(a.$container);a.$carat=d('<span class="carat"/>').appendTo(a.$container);a.$scrollWrapper=d("<div><ul/></div>").appendTo(a.$container);a.$dropDown=a.$scrollWrapper.find("ul");a.$form=a.$container.closest("form");d.each(a.options,function(){a.$dropDown.append("<li"+(this.selected?' class="active"':"")+">"+this.title+"</li>")});a.$items=a.$dropDown.find("li");a.maxHeight=0;a.cutOff&&a.$items.length>a.cutOff&&a.$container.addClass("scrollable");
for(i=0;i<a.$items.length;i++){var c=a.$items.eq(i);a.maxHeight+=c.outerHeight();if(a.cutOff==i+1)break}a.isTouch&&a.nativeTouch?a.bindTouchHandlers():a.bindHandlers()},bindTouchHandlers:function(){var a=this;a.$container.on("click.easyDropDown",function(){a.$select.focus()});a.$select.on({change:function(){var c=d(this).find("option:selected"),b=c.text(),c=c.val();a.$active.text(b);"function"===typeof a.onChange&&a.onChange.call(a.$select[0],{title:b,value:c})},focus:function(){a.$container.addClass("focus")},
blur:function(){a.$container.removeClass("focus")}})},bindHandlers:function(){var a=this;a.query="";a.$container.on({"click.easyDropDown":function(){a.down||a.disabled?a.close():a.open()},"mousemove.easyDropDown":function(){a.keyboardMode&&(a.keyboardMode=!1)}});d("body").on("click.easyDropDown."+a.id,function(c){c=d(c.target);var b=a.wrapperClass.split(" ").join(".");!c.closest("."+b).length&&a.down&&a.close()});a.$items.on({"click.easyDropDown":function(){var c=d(this).index();a.select(c);a.$select.focus()},
"mouseover.easyDropDown":function(){if(!a.keyboardMode){var c=d(this);c.addClass("focus").siblings().removeClass("focus");a.focusIndex=c.index()}},"mouseout.easyDropDown":function(){a.keyboardMode||d(this).removeClass("focus")}});a.$select.on({"focus.easyDropDown":function(){a.$container.addClass("focus");a.inFocus=!0},"blur.easyDropDown":function(){a.$container.removeClass("focus");a.inFocus=!1},"keydown.easyDropDown":function(c){if(a.inFocus){a.keyboardMode=!0;var b=c.keyCode;if(38==b||40==b||32==
b)c.preventDefault(),38==b?(a.focusIndex--,a.focusIndex=0>a.focusIndex?a.$items.length-1:a.focusIndex):40==b&&(a.focusIndex++,a.focusIndex=a.focusIndex>a.$items.length-1?0:a.focusIndex),a.down||a.open(),a.$items.removeClass("focus").eq(a.focusIndex).addClass("focus"),a.cutOff&&a.scrollToView(),a.query="";if(a.down)if(9==b||27==b)a.close();else{if(13==b)return c.preventDefault(),a.select(a.focusIndex),a.close(),!1;if(8==b)return c.preventDefault(),a.query=a.query.slice(0,-1),a.search(),clearTimeout(a.resetQuery),
!1;38!=b&&40!=b&&(c=String.fromCharCode(b),a.query+=c,a.search(),clearTimeout(a.resetQuery))}}},"keyup.easyDropDown":function(){a.resetQuery=setTimeout(function(){a.query=""},1200)}});a.$dropDown.on("scroll.easyDropDown",function(c){a.$dropDown[0].scrollTop>=a.$dropDown[0].scrollHeight-a.maxHeight?a.$container.addClass("bottom"):a.$container.removeClass("bottom")});if(a.$form.length)a.$form.on("reset.easyDropDown",function(){a.$active.text(a.hasLabel?a.label:a.options[0].title)})},unbindHandlers:function(){this.$container.add(this.$select).add(this.$items).add(this.$form).add(this.$dropDown).off(".easyDropDown");
d("body").off("."+this.id)},open:function(){var a=window.scrollY||document.documentElement.scrollTop,c=window.scrollX||document.documentElement.scrollLeft,b=this.notInViewport(a);this.closeAll();this.$select.focus();window.scrollTo(c,a+b);this.$container.addClass("open");this.$scrollWrapper.css("height",this.maxHeight+"px");this.down=!0},close:function(){this.$container.removeClass("open");this.$scrollWrapper.css("height","0px");this.focusIndex=this.selected.index;this.query="";this.down=!1},closeAll:function(){var a=
Object.getPrototypeOf(this).instances,c;for(c in a)a[c].close()},select:function(a){"string"===typeof a&&(a=this.$select.find("option[value="+a+"]").index()-1);var c=this.options[a],b=this.hasLabel?a+1:a;this.$items.removeClass("active").eq(a).addClass("active");this.$active.text(c.title);this.$select.find("option").removeAttr("selected").eq(b).prop("selected",!0).parent().trigger("change");this.selected={index:a,title:c.title};this.focusIndex=i;"function"===typeof this.onChange&&this.onChange.call(this.$select[0],
{title:c.title,value:c.value})},search:function(){var a=this,c=function(b){a.focusIndex=b;a.$items.removeClass("focus").eq(a.focusIndex).addClass("focus");a.scrollToView()};for(i=0;i<a.options.length;i++){var b=a.options[i].title.toUpperCase();if(0==b.indexOf(a.query)){c(i);return}}for(i=0;i<a.options.length;i++)if(b=a.options[i].title.toUpperCase(),-1<b.indexOf(a.query)){c(i);break}},scrollToView:function(){if(this.focusIndex>=this.cutOff){var a=this.$items.eq(this.focusIndex).outerHeight()*(this.focusIndex+
1)-this.maxHeight;this.$dropDown.scrollTop(a)}},notInViewport:function(a){var c=a+(window.innerHeight||document.documentElement.clientHeight),b=this.$dropDown.offset().top+this.maxHeight;return b>=a&&b<=c?0:b-c+5},destroy:function(){this.unbindHandlers();this.$select.unwrap().siblings().remove();this.$select.unwrap();delete Object.getPrototypeOf(this).instances[this.$select[0].id]},disable:function(){this.disabled=!0;this.$container.addClass("disabled");this.$select.attr("disabled",!0);this.down||
this.close()},enable:function(){this.disabled=!1;this.$container.removeClass("disabled");this.$select.attr("disabled",!1)}};var f=function(a,c){a.id=a.id?a.id:"EasyDropDown"+("00000"+(16777216*Math.random()<<0).toString(16)).substr(-6).toUpperCase();var b=new e;b.instances[a.id]||(b.instances[a.id]=b,b.init(a,c))};d.fn.easyDropDown=function(){var a=arguments,c=[],b;b=this.each(function(){if(a&&"string"===typeof a[0]){var b=e.prototype.instances[this.id][a[0]](a[1],a[2]);b&&c.push(b)}else f(this,a[0])});
return c.length?1<c.length?c:c[0]:b};d(function(){"function"!==typeof Object.getPrototypeOf&&(Object.getPrototypeOf="object"===typeof"test".__proto__?function(a){return a.__proto__}:function(a){return a.constructor.prototype});d("select.dropdown").each(function(){var a=d(this).attr("data-settings");settings=a?d.parseJSON(a):{};f(this,settings)})})})(jQuery);

View File

@@ -0,0 +1,106 @@
/*
* jQuery Input Limitor plugin 1.0
* http://rustyjeans.com/jquery-plugins/input-limitor/
*
* Copyright (c) 2009 Russel Fones
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
(function($) {
$.fn.inputlimitor = function(options) {
var opts = $.extend({}, $.fn.inputlimitor.defaults, options);
if ( opts.boxAttach && !$('#'+opts.boxId).length )
{
$('<div/>').appendTo("body").attr({id: opts.boxId, 'class': opts.boxClass}).css({'position': 'absolute'}).hide();
// apply bgiframe if available
if ( $.fn.bgiframe )
$('#'+opts.boxId).bgiframe();
}
$(this).each(function(i){
$(this).keyup(function(e){
if ( $(this).val().length > opts.limit )
$(this).val($(this).val().substring(0,opts.limit));
if ( opts.boxAttach )
{
$('#'+opts.boxId).css({
'width': $(this).outerWidth() - ($('#'+opts.boxId).outerWidth() - $('#'+opts.boxId).width()) + 'px',
'left': $(this).offset().left + 'px',
'top': ($(this).offset().top + $(this).outerHeight()) - 1 + 'px'
});
}
var remText = opts.remText;
remText = remText.replace(/\%n/g, opts.limit - $(this).val().length);
remText = remText.replace(/\%s/g, ( opts.limit - $(this).val().length == 1?'':'s' ));
var limitText = opts.limitText;
limitText = limitText.replace(/\%n/g, opts.limit);
limitText = limitText.replace(/\%s/g, ( opts.limit == 1?'':'s' ));
if ( opts.limitTextShow )
{
$('#'+opts.boxId).html(remText + ' ' + limitText);
// Check to see if the text is wrapping in the box
// If it is lets break it between the remaining test and the limit test
var textWidth = $("<span/>").appendTo("body").attr({id: '19cc9195583bfae1fad88e19d443be7a', 'class': opts.boxClass}).html(remText + ' ' + limitText).innerWidth();
$("#19cc9195583bfae1fad88e19d443be7a").remove();
if ( textWidth > $('#'+opts.boxId).innerWidth() ) {
$('#'+opts.boxId).html(remText + '<br />' + limitText);
}
// Show the limitor box
$('#'+opts.boxId).show();
}
else
$('#'+opts.boxId).html(remText).show();
});
$(this).keypress(function(e){
if ( (!e.keyCode || (e.keyCode > 46 && e.keyCode < 90)) && $(this).val().length >= opts.limit )
return false;
});
$(this).blur(function(){
if ( opts.boxAttach )
{
$('#'+opts.boxId).fadeOut('fast');
}
else if ( opts.remTextHideOnBlur )
{
var limitText = opts.limitText;
limitText = limitText.replace(/\%n/g, opts.limit);
limitText = limitText.replace(/\%s/g, ( opts.limit == 1?'':'s' ));
$('#'+opts.boxId).html(limitText);
}
});
});
};
$.fn.inputlimitor.defaults = {
limit: 255,
boxAttach: true,
boxId: 'limitorBox',
boxClass: 'limitorBox',
remText: '%n character%s remaining.',
remTextHideOnBlur: true,
limitTextShow: true,
limitText: 'Field limited to %n character%s.'
};
})(jQuery);

View File

@@ -0,0 +1,16 @@
(function($){$.fn.inputlimitor=function(options){var opts=$.extend({},$.fn.inputlimitor.defaults,options);if(opts.boxAttach&&!$('#'+opts.boxId).length)
{$('<div/>').appendTo("body").attr({id:opts.boxId,'class':opts.boxClass}).css({'position':'absolute'}).hide();if($.fn.bgiframe)
$('#'+opts.boxId).bgiframe();}
$(this).each(function(i){$(this).keyup(function(e){if($(this).val().length>opts.limit)
$(this).val($(this).val().substring(0,opts.limit));if(opts.boxAttach)
{$('#'+opts.boxId).css({'width':$(this).outerWidth()-($('#'+opts.boxId).outerWidth()-$('#'+opts.boxId).width())+'px','left':$(this).offset().left+'px','top':($(this).offset().top+$(this).outerHeight())-1+'px'});}
var remText=opts.remText;remText=remText.replace(/\%n/g,opts.limit-$(this).val().length);remText=remText.replace(/\%s/g,(opts.limit-$(this).val().length==1?'':'s'));var limitText=opts.limitText;limitText=limitText.replace(/\%n/g,opts.limit);limitText=limitText.replace(/\%s/g,(opts.limit==1?'':'s'));if(opts.limitTextShow)
{$('#'+opts.boxId).html(remText+' '+limitText);var textWidth=$("<span/>").appendTo("body").attr({id:'19cc9195583bfae1fad88e19d443be7a','class':opts.boxClass}).html(remText+' '+limitText).innerWidth();$("#19cc9195583bfae1fad88e19d443be7a").remove();if(textWidth>$('#'+opts.boxId).innerWidth()){$('#'+opts.boxId).html(remText+'<br />'+limitText);}
$('#'+opts.boxId).show();}
else
$('#'+opts.boxId).html(remText).show();});$(this).keypress(function(e){if((!e.keyCode||(e.keyCode>46&&e.keyCode<90))&&$(this).val().length>=opts.limit)
return false;});$(this).blur(function(){if(opts.boxAttach)
{$('#'+opts.boxId).fadeOut('fast');}
else if(opts.remTextHideOnBlur)
{var limitText=opts.limitText;limitText=limitText.replace(/\%n/g,opts.limit);limitText=limitText.replace(/\%s/g,(opts.limit==1?'':'s'));$('#'+opts.boxId).html(limitText);}});});};$.fn.inputlimitor.defaults={limit:255,boxAttach:true,boxId:'limitorBox',boxClass:'limitorBox',remText:'%n character%s remaining.',remTextHideOnBlur:true,limitTextShow:true,limitText:'Field limited to %n character%s.'};})(jQuery);

6
frontend/static/js/jquery.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,210 @@
/*!
* jQuery.scrollTo
* Copyright (c) 2007-2015 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
* Licensed under MIT
* http://flesler.blogspot.com/2007/10/jqueryscrollto.html
* @projectDescription Lightweight, cross-browser and highly customizable animated scrolling with jQuery
* @author Ariel Flesler
* @version 2.1.1
*/
;(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof module !== 'undefined' && module.exports) {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Global
factory(jQuery);
}
})(function($) {
'use strict';
var $scrollTo = $.scrollTo = function(target, duration, settings) {
return $(window).scrollTo(target, duration, settings);
};
$scrollTo.defaults = {
axis:'xy',
duration: 0,
limit:true
};
function isWin(elem) {
return !elem.nodeName ||
$.inArray(elem.nodeName.toLowerCase(), ['iframe','#document','html','body']) !== -1;
}
$.fn.scrollTo = function(target, duration, settings) {
if (typeof duration === 'object') {
settings = duration;
duration = 0;
}
if (typeof settings === 'function') {
settings = { onAfter:settings };
}
if (target === 'max') {
target = 9e9;
}
settings = $.extend({}, $scrollTo.defaults, settings);
// Speed is still recognized for backwards compatibility
duration = duration || settings.duration;
// Make sure the settings are given right
var queue = settings.queue && settings.axis.length > 1;
if (queue) {
// Let's keep the overall duration
duration /= 2;
}
settings.offset = both(settings.offset);
settings.over = both(settings.over);
return this.each(function() {
// Null target yields nothing, just like jQuery does
if (target === null) return;
var win = isWin(this),
elem = win ? this.contentWindow || window : this,
$elem = $(elem),
targ = target,
attr = {},
toff;
switch (typeof targ) {
// A number will pass the regex
case 'number':
case 'string':
if (/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(targ)) {
targ = both(targ);
// We are done
break;
}
// Relative/Absolute selector
targ = win ? $(targ) : $(targ, elem);
if (!targ.length) return;
/* falls through */
case 'object':
// DOMElement / jQuery
if (targ.is || targ.style) {
// Get the real position of the target
toff = (targ = $(targ)).offset();
}
}
var offset = $.isFunction(settings.offset) && settings.offset(elem, targ) || settings.offset;
$.each(settings.axis.split(''), function(i, axis) {
var Pos = axis === 'x' ? 'Left' : 'Top',
pos = Pos.toLowerCase(),
key = 'scroll' + Pos,
prev = $elem[key](),
max = $scrollTo.max(elem, axis);
if (toff) {// jQuery / DOMElement
attr[key] = toff[pos] + (win ? 0 : prev - $elem.offset()[pos]);
// If it's a dom element, reduce the margin
if (settings.margin) {
attr[key] -= parseInt(targ.css('margin'+Pos), 10) || 0;
attr[key] -= parseInt(targ.css('border'+Pos+'Width'), 10) || 0;
}
attr[key] += offset[pos] || 0;
if (settings.over[pos]) {
// Scroll to a fraction of its width/height
attr[key] += targ[axis === 'x'?'width':'height']() * settings.over[pos];
}
} else {
var val = targ[pos];
// Handle percentage values
attr[key] = val.slice && val.slice(-1) === '%' ?
parseFloat(val) / 100 * max
: val;
}
// Number or 'number'
if (settings.limit && /^\d+$/.test(attr[key])) {
// Check the limits
attr[key] = attr[key] <= 0 ? 0 : Math.min(attr[key], max);
}
// Don't waste time animating, if there's no need.
if (!i && settings.axis.length > 1) {
if (prev === attr[key]) {
// No animation needed
attr = {};
} else if (queue) {
// Intermediate animation
animate(settings.onAfterFirst);
// Don't animate this axis again in the next iteration.
attr = {};
}
}
});
animate(settings.onAfter);
function animate(callback) {
var opts = $.extend({}, settings, {
// The queue setting conflicts with animate()
// Force it to always be true
queue: true,
duration: duration,
complete: callback && function() {
callback.call(elem, targ, settings);
}
});
$elem.animate(attr, opts);
}
});
};
// Max scrolling position, works on quirks mode
// It only fails (not too badly) on IE, quirks mode.
$scrollTo.max = function(elem, axis) {
var Dim = axis === 'x' ? 'Width' : 'Height',
scroll = 'scroll'+Dim;
if (!isWin(elem))
return elem[scroll] - $(elem)[Dim.toLowerCase()]();
var size = 'client' + Dim,
doc = elem.ownerDocument || elem.document,
html = doc.documentElement,
body = doc.body;
return Math.max(html[scroll], body[scroll]) - Math.min(html[size], body[size]);
};
function both(val) {
return $.isFunction(val) || $.isPlainObject(val) ? val : { top:val, left:val };
}
// Add special hooks so that window scroll properties can be animated
$.Tween.propHooks.scrollLeft =
$.Tween.propHooks.scrollTop = {
get: function(t) {
return $(t.elem)[t.prop]();
},
set: function(t) {
var curr = this.get(t);
// If interrupt is true and user scrolled, stop animating
if (t.options.interrupt && t._last && t._last !== curr) {
return $(t.elem).stop();
}
var next = Math.round(t.now);
// Don't waste CPU
// Browsers don't render floating point scroll
if (curr !== next) {
$(t.elem)[t.prop](next);
t._last = this.get(t);
}
}
};
// AMD requirement
return $scrollTo;
});

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) 2007-2015 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
* Licensed under MIT
* @author Ariel Flesler
* @version 2.1.1
*/
;(function(f){"use strict";"function"===typeof define&&define.amd?define(["jquery"],f):"undefined"!==typeof module&&module.exports?module.exports=f(require("jquery")):f(jQuery)})(function($){"use strict";function n(a){return!a.nodeName||-1!==$.inArray(a.nodeName.toLowerCase(),["iframe","#document","html","body"])}function h(a){return $.isFunction(a)||$.isPlainObject(a)?a:{top:a,left:a}}var p=$.scrollTo=function(a,d,b){return $(window).scrollTo(a,d,b)};p.defaults={axis:"xy",duration:0,limit:!0};$.fn.scrollTo=function(a,d,b){"object"=== typeof d&&(b=d,d=0);"function"===typeof b&&(b={onAfter:b});"max"===a&&(a=9E9);b=$.extend({},p.defaults,b);d=d||b.duration;var u=b.queue&&1<b.axis.length;u&&(d/=2);b.offset=h(b.offset);b.over=h(b.over);return this.each(function(){function k(a){var k=$.extend({},b,{queue:!0,duration:d,complete:a&&function(){a.call(q,e,b)}});r.animate(f,k)}if(null!==a){var l=n(this),q=l?this.contentWindow||window:this,r=$(q),e=a,f={},t;switch(typeof e){case "number":case "string":if(/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(e)){e= h(e);break}e=l?$(e):$(e,q);if(!e.length)return;case "object":if(e.is||e.style)t=(e=$(e)).offset()}var v=$.isFunction(b.offset)&&b.offset(q,e)||b.offset;$.each(b.axis.split(""),function(a,c){var d="x"===c?"Left":"Top",m=d.toLowerCase(),g="scroll"+d,h=r[g](),n=p.max(q,c);t?(f[g]=t[m]+(l?0:h-r.offset()[m]),b.margin&&(f[g]-=parseInt(e.css("margin"+d),10)||0,f[g]-=parseInt(e.css("border"+d+"Width"),10)||0),f[g]+=v[m]||0,b.over[m]&&(f[g]+=e["x"===c?"width":"height"]()*b.over[m])):(d=e[m],f[g]=d.slice&& "%"===d.slice(-1)?parseFloat(d)/100*n:d);b.limit&&/^\d+$/.test(f[g])&&(f[g]=0>=f[g]?0:Math.min(f[g],n));!a&&1<b.axis.length&&(h===f[g]?f={}:u&&(k(b.onAfterFirst),f={}))});k(b.onAfter)}})};p.max=function(a,d){var b="x"===d?"Width":"Height",h="scroll"+b;if(!n(a))return a[h]-$(a)[b.toLowerCase()]();var b="client"+b,k=a.ownerDocument||a.document,l=k.documentElement,k=k.body;return Math.max(l[h],k[h])-Math.min(l[b],k[b])};$.Tween.propHooks.scrollLeft=$.Tween.propHooks.scrollTop={get:function(a){return $(a.elem)[a.prop]()}, set:function(a){var d=this.get(a);if(a.options.interrupt&&a._last&&a._last!==d)return $(a.elem).stop();var b=Math.round(a.now);d!==b&&($(a.elem)[a.prop](b),a._last=this.get(a))}};return p});

View File

@@ -0,0 +1,453 @@
/*!
* Lightbox v2.8.2
* by Lokesh Dhakar
*
* More info:
* http://lokeshdhakar.com/projects/lightbox2/
*
* Copyright 2007, 2015 Lokesh Dhakar
* Released under the MIT license
* https://github.com/lokesh/lightbox2/blob/master/LICENSE
*/
// Uses Node, AMD or browser globals to create a module.
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('jquery'));
} else {
// Browser globals (root is window)
root.lightbox = factory(root.jQuery);
}
}(this, function ($) {
function Lightbox(options) {
this.album = [];
this.currentImageIndex = void 0;
this.init();
// options
this.options = $.extend({}, this.constructor.defaults);
this.option(options);
}
// Descriptions of all options available on the demo site:
// http://lokeshdhakar.com/projects/lightbox2/index.html#options
Lightbox.defaults = {
albumLabel: 'Image %1 of %2',
alwaysShowNavOnTouchDevices: false,
fadeDuration: 500,
fitImagesInViewport: true,
// maxWidth: 800,
// maxHeight: 600,
positionFromTop: 50,
resizeDuration: 700,
showImageNumberLabel: true,
wrapAround: false,
disableScrolling: false
};
Lightbox.prototype.option = function(options) {
$.extend(this.options, options);
};
Lightbox.prototype.imageCountLabel = function(currentImageNum, totalImages) {
return this.options.albumLabel.replace(/%1/g, currentImageNum).replace(/%2/g, totalImages);
};
Lightbox.prototype.init = function() {
this.enable();
this.build();
};
// Loop through anchors and areamaps looking for either data-lightbox attributes or rel attributes
// that contain 'lightbox'. When these are clicked, start lightbox.
Lightbox.prototype.enable = function() {
var self = this;
$('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function(event) {
self.start($(event.currentTarget));
return false;
});
};
// Build html for the lightbox and the overlay.
// Attach event handlers to the new DOM elements. click click click
Lightbox.prototype.build = function() {
var self = this;
$('<div id="lightboxOverlay" class="lightboxOverlay"></div><div id="lightbox" class="lightbox"><div class="lb-outerContainer"><div class="lb-container"><img class="lb-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" /><div class="lb-nav"><a class="lb-prev" href="" ></a><a class="lb-next" href="" ></a></div><div class="lb-loader"><a class="lb-cancel"></a></div></div></div><div class="lb-dataContainer"><div class="lb-data"><div class="lb-details"><span class="lb-caption"></span><span class="lb-number"></span></div><div class="lb-closeContainer"><a class="lb-close"></a></div></div></div></div>').appendTo($('body'));
// Cache jQuery objects
this.$lightbox = $('#lightbox');
this.$overlay = $('#lightboxOverlay');
this.$outerContainer = this.$lightbox.find('.lb-outerContainer');
this.$container = this.$lightbox.find('.lb-container');
// Store css values for future lookup
this.containerTopPadding = parseInt(this.$container.css('padding-top'), 10);
this.containerRightPadding = parseInt(this.$container.css('padding-right'), 10);
this.containerBottomPadding = parseInt(this.$container.css('padding-bottom'), 10);
this.containerLeftPadding = parseInt(this.$container.css('padding-left'), 10);
// Attach event handlers to the newly minted DOM elements
this.$overlay.hide().on('click', function() {
self.end();
return false;
});
this.$lightbox.hide().on('click', function(event) {
if ($(event.target).attr('id') === 'lightbox') {
self.end();
}
return false;
});
this.$outerContainer.on('click', function(event) {
if ($(event.target).attr('id') === 'lightbox') {
self.end();
}
return false;
});
this.$lightbox.find('.lb-prev').on('click', function() {
if (self.currentImageIndex === 0) {
self.changeImage(self.album.length - 1);
} else {
self.changeImage(self.currentImageIndex - 1);
}
return false;
});
this.$lightbox.find('.lb-next').on('click', function() {
if (self.currentImageIndex === self.album.length - 1) {
self.changeImage(0);
} else {
self.changeImage(self.currentImageIndex + 1);
}
return false;
});
this.$lightbox.find('.lb-loader, .lb-close').on('click', function() {
self.end();
return false;
});
};
// Show overlay and lightbox. If the image is part of a set, add siblings to album array.
Lightbox.prototype.start = function($link) {
var self = this;
var $window = $(window);
$window.on('resize', $.proxy(this.sizeOverlay, this));
$('select, object, embed').css({
visibility: 'hidden'
});
this.sizeOverlay();
this.album = [];
var imageNumber = 0;
function addToAlbum($link) {
self.album.push({
link: $link.attr('href'),
title: $link.attr('data-title') || $link.attr('title')
});
}
// Support both data-lightbox attribute and rel attribute implementations
var dataLightboxValue = $link.attr('data-lightbox');
var $links;
if (dataLightboxValue) {
$links = $($link.prop('tagName') + '[data-lightbox="' + dataLightboxValue + '"]');
for (var i = 0; i < $links.length; i = ++i) {
addToAlbum($($links[i]));
if ($links[i] === $link[0]) {
imageNumber = i;
}
}
} else {
if ($link.attr('rel') === 'lightbox') {
// If image is not part of a set
addToAlbum($link);
} else {
// If image is part of a set
$links = $($link.prop('tagName') + '[rel="' + $link.attr('rel') + '"]');
for (var j = 0; j < $links.length; j = ++j) {
addToAlbum($($links[j]));
if ($links[j] === $link[0]) {
imageNumber = j;
}
}
}
}
// Position Lightbox
var top = $window.scrollTop() + this.options.positionFromTop;
var left = $window.scrollLeft();
this.$lightbox.css({
top: top + 'px',
left: left + 'px'
}).fadeIn(this.options.fadeDuration);
// Disable scrolling of the page while open
if (this.options.disableScrolling) {
$('body').addClass('lb-disable-scrolling');
}
this.changeImage(imageNumber);
};
// Hide most UI elements in preparation for the animated resizing of the lightbox.
Lightbox.prototype.changeImage = function(imageNumber) {
var self = this;
this.disableKeyboardNav();
var $image = this.$lightbox.find('.lb-image');
this.$overlay.fadeIn(this.options.fadeDuration);
$('.lb-loader').fadeIn('slow');
this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
this.$outerContainer.addClass('animating');
// When image to show is preloaded, we send the width and height to sizeContainer()
var preloader = new Image();
preloader.onload = function() {
var $preloader;
var imageHeight;
var imageWidth;
var maxImageHeight;
var maxImageWidth;
var windowHeight;
var windowWidth;
$image.attr('src', self.album[imageNumber].link);
$preloader = $(preloader);
$image.width(preloader.width);
$image.height(preloader.height);
if (self.options.fitImagesInViewport) {
// Fit image inside the viewport.
// Take into account the border around the image and an additional 10px gutter on each side.
windowWidth = $(window).width();
windowHeight = $(window).height();
maxImageWidth = windowWidth - self.containerLeftPadding - self.containerRightPadding - 20;
maxImageHeight = windowHeight - self.containerTopPadding - self.containerBottomPadding - 120;
// Check if image size is larger then maxWidth|maxHeight in settings
if (self.options.maxWidth && self.options.maxWidth < maxImageWidth) {
maxImageWidth = self.options.maxWidth;
}
if (self.options.maxHeight && self.options.maxHeight < maxImageWidth) {
maxImageHeight = self.options.maxHeight;
}
// Is there a fitting issue?
if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
imageWidth = maxImageWidth;
imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
$image.width(imageWidth);
$image.height(imageHeight);
} else {
imageHeight = maxImageHeight;
imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
$image.width(imageWidth);
$image.height(imageHeight);
}
}
}
self.sizeContainer($image.width(), $image.height());
};
preloader.src = this.album[imageNumber].link;
this.currentImageIndex = imageNumber;
};
// Stretch overlay to fit the viewport
Lightbox.prototype.sizeOverlay = function() {
this.$overlay
.width($(document).width())
.height($(document).height());
};
// Animate the size of the lightbox to fit the image we are showing
Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
var self = this;
var oldWidth = this.$outerContainer.outerWidth();
var oldHeight = this.$outerContainer.outerHeight();
var newWidth = imageWidth + this.containerLeftPadding + this.containerRightPadding;
var newHeight = imageHeight + this.containerTopPadding + this.containerBottomPadding;
function postResize() {
self.$lightbox.find('.lb-dataContainer').width(newWidth);
self.$lightbox.find('.lb-prevLink').height(newHeight);
self.$lightbox.find('.lb-nextLink').height(newHeight);
self.showImage();
}
if (oldWidth !== newWidth || oldHeight !== newHeight) {
this.$outerContainer.animate({
width: newWidth,
height: newHeight
}, this.options.resizeDuration, 'swing', function() {
postResize();
});
} else {
postResize();
}
};
// Display the image and its details and begin preload neighboring images.
Lightbox.prototype.showImage = function() {
this.$lightbox.find('.lb-loader').stop(true).hide();
this.$lightbox.find('.lb-image').fadeIn('slow');
this.updateNav();
this.updateDetails();
this.preloadNeighboringImages();
this.enableKeyboardNav();
};
// Display previous and next navigation if appropriate.
Lightbox.prototype.updateNav = function() {
// Check to see if the browser supports touch events. If so, we take the conservative approach
// and assume that mouse hover events are not supported and always show prev/next navigation
// arrows in image sets.
var alwaysShowNav = false;
try {
document.createEvent('TouchEvent');
alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices) ? true : false;
} catch (e) {}
this.$lightbox.find('.lb-nav').show();
if (this.album.length > 1) {
if (this.options.wrapAround) {
if (alwaysShowNav) {
this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1');
}
this.$lightbox.find('.lb-prev, .lb-next').show();
} else {
if (this.currentImageIndex > 0) {
this.$lightbox.find('.lb-prev').show();
if (alwaysShowNav) {
this.$lightbox.find('.lb-prev').css('opacity', '1');
}
}
if (this.currentImageIndex < this.album.length - 1) {
this.$lightbox.find('.lb-next').show();
if (alwaysShowNav) {
this.$lightbox.find('.lb-next').css('opacity', '1');
}
}
}
}
};
// Display caption, image number, and closing button.
Lightbox.prototype.updateDetails = function() {
var self = this;
// Enable anchor clicks in the injected caption html.
// Thanks Nate Wright for the fix. @https://github.com/NateWr
if (typeof this.album[this.currentImageIndex].title !== 'undefined' &&
this.album[this.currentImageIndex].title !== '') {
this.$lightbox.find('.lb-caption')
.html(this.album[this.currentImageIndex].title)
.fadeIn('fast')
.find('a').on('click', function(event) {
if ($(this).attr('target') !== undefined) {
window.open($(this).attr('href'), $(this).attr('target'));
} else {
location.href = $(this).attr('href');
}
});
}
if (this.album.length > 1 && this.options.showImageNumberLabel) {
var labelText = this.imageCountLabel(this.currentImageIndex + 1, this.album.length);
this.$lightbox.find('.lb-number').text(labelText).fadeIn('fast');
} else {
this.$lightbox.find('.lb-number').hide();
}
this.$outerContainer.removeClass('animating');
this.$lightbox.find('.lb-dataContainer').fadeIn(this.options.resizeDuration, function() {
return self.sizeOverlay();
});
};
// Preload previous and next images in set.
Lightbox.prototype.preloadNeighboringImages = function() {
if (this.album.length > this.currentImageIndex + 1) {
var preloadNext = new Image();
preloadNext.src = this.album[this.currentImageIndex + 1].link;
}
if (this.currentImageIndex > 0) {
var preloadPrev = new Image();
preloadPrev.src = this.album[this.currentImageIndex - 1].link;
}
};
Lightbox.prototype.enableKeyboardNav = function() {
$(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this));
};
Lightbox.prototype.disableKeyboardNav = function() {
$(document).off('.keyboard');
};
Lightbox.prototype.keyboardAction = function(event) {
var KEYCODE_ESC = 27;
var KEYCODE_LEFTARROW = 37;
var KEYCODE_RIGHTARROW = 39;
var keycode = event.keyCode;
var key = String.fromCharCode(keycode).toLowerCase();
if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) {
this.end();
} else if (key === 'p' || keycode === KEYCODE_LEFTARROW) {
if (this.currentImageIndex !== 0) {
this.changeImage(this.currentImageIndex - 1);
} else if (this.options.wrapAround && this.album.length > 1) {
this.changeImage(this.album.length - 1);
}
} else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
if (this.currentImageIndex !== this.album.length - 1) {
this.changeImage(this.currentImageIndex + 1);
} else if (this.options.wrapAround && this.album.length > 1) {
this.changeImage(0);
}
}
};
// Closing time. :-(
Lightbox.prototype.end = function() {
this.disableKeyboardNav();
$(window).off('resize', this.sizeOverlay);
this.$lightbox.fadeOut(this.options.fadeDuration);
this.$overlay.fadeOut(this.options.fadeDuration);
$('select, object, embed').css({
visibility: 'visible'
});
if (this.options.disableScrolling) {
$('body').removeClass('lb-disable-scrolling');
}
};
return new Lightbox();
}));

View File

@@ -0,0 +1,95 @@
$(document).ready(function() {
$('#changePassForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
oldpass: {
trigger: 'blur',
validators: {
notEmpty: {
message: '原密码还没有输噢'
},
stringLength: {
min: 6,
max: 20,
message: '6到20个字符'
}
}
},
newpass: {
trigger: 'blur',
validators: {
notEmpty: {
message: '快输个新密码吧'
},
stringLength: {
min: 6,
max: 20,
message: '6到20个字符'
}
}
},
newpass_confirm: {
trigger: 'blur',
validators: {
notEmpty: {
message: '再输一次新密码,别打错了'
},
identical: {
field: 'newpass',
message: '两次新密码输入的不一样'
},
stringLength: {
min: 6,
max: 20,
message: '6到20个字符'
}
}
}
}
});
});
$("button#submit").click(function(){
doChange();
});
$(document).keydown(function(e) {
if (e.keyCode == 13) {
doChange();
}
});
function doChange(){
var oldPass = $("#changePassForm #oldpass").val();
var newPass = $("#changePassForm #newpass").val();
$.ajax( {
url:'/home/users/changepassword',// 跳转到 action
data:JSON.stringify(
{
oldPassword : oldPass,
newPassword : newPass
}),
type:'post',
cache:false,
dataType:'json',
contentType:"application/json;charset=utf-8",
success:function(data) {
if(data.status=="success"){
alert("修改成功");
window.location.reload(true);
}else if(data.status=="fail"){
alert(data.data.errMessage);
}
},
error : function() {
// view("异常!");
alert("异常!");
}
});
}

View File

@@ -0,0 +1,38 @@
/**
* forget.js
*/
$("button#submit").click(function(){
doForget();
});
$(document).keydown(function(e) {
if (e.keyCode == 13) {
doForget();
}
});
function doForget(){
var email = $("#forgetForm #email").val();
if(email=="")
return;
$.ajax( {
url:'/home/users/forgetpassword',// 跳转到 action
data:$('#forgetForm').serialize(),
type:'POST',
processData:true,
contentType:"application/x-www-form-urlencoded",
success:function(data) {
alert(data.status);
if(data.status=="success"){
location.href = "/home/users/login";
}else if(data.status=="fail"){
alert(data.data.errMessage);
}
},
error : function(e) {
// view("异常!");
alert(e);
}
});
}

View File

@@ -0,0 +1,44 @@
/**
* login.js
*/
$("button#submit").click(function(){
doLogin();
});
$(document).keydown(function(e) {
if (e.keyCode == 13) {
doLogin();
}
});
function doLogin(){
var email = $("#loginForm #email").val();
var password = $("#loginForm #password").val();
//alert(email + " "+password);
if(email=="" || password=="")
return;
$.ajax( {
url:'/home/users/login',// 跳转到 action
data:JSON.stringify(
{
email : email,
password : password
}),
type:'post',
cache:false,
dataType:'json',
contentType:"application/json;charset=utf-8",
success:function(data) {
if(data.status=="success"){
location.href = "/home/index/index";
}else if(data.status=="fail"){
alert(data.data.errMessage);
}
},
error : function() {
// view("异常!");
alert("异常!");
}
});
}

View File

@@ -0,0 +1,49 @@
/**
* register.js
*/
$("button#submit").click(function(){
doRegister();
});
$(document).keydown(function(e) {
if (e.keyCode == 13) {
doRegister();
}
});
function doRegister(){
var email = $("#signinForm #email").val();
var password = $("#signinForm #password").val();
var domain = $("#signinForm #personalDomain").val();
var userName = $("#signinForm #userName").val();
if(email=="" || password=="" || domain=="" || userName=="")
return;
$.ajax( {
url:'/home/users/register',// 跳转到 action
data:JSON.stringify(
{
email : email,
password : password,
personalDomain : domain,
userName : userName
}),
type:'post',
cache:false,
dataType:'json',
contentType:"application/json;charset=utf-8",
success:function(data) {
if(data.status=="success"){
location.href = "/home/index/index";
}else if(data.status=="fail"){
alert(data.data.errMessage);
}
},
error : function() {
// view("异常!");
alert("异常!");
}
});
}

View File

@@ -0,0 +1,38 @@
/**
* reset.js
*/
$("button#submit").click(function(){
doReset();
});
$(document).keydown(function(e) {
if (e.keyCode == 13) {
doReset();
}
});
function doReset(){
var email = $("#resetForm #email").val();
if(email=="")
return;
$.ajax( {
url:'/home/users/resetpassword',// 跳转到 action
data:$('#resetForm').serialize(),
type:'POST',
processData:true,
contentType:"application/x-www-form-urlencoded",
success:function(data) {
alert(data.status);
if(data.status=="success"){
location.href = "/home/user/validate.jsp";
}else if(data.status=="fail"){
alert(data.data.errMessage);
}
},
error : function(e) {
// view("异常!");
alert(e);
}
});
}

View File

@@ -0,0 +1,183 @@
//表单验证
$(document).ready(function() {
$('#profileForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
nickname: {
trigger: 'blur',
validators: {
notEmpty: {
message: '快想个昵称'
},
stringLength: {
min: 2,
max: 20,
message: '2到20个字符'
}
}
},
domain: {
trigger: 'blur',
validators: {
stringLength: {
min: 1,
max: 200,
message: '最多200个字符'
}
}
},
intro: {
trigger: 'blur',
validators: {
stringLength: {
min: 1,
max: 140,
message: '最多140个字符'
}
}
}
}
});
$('#changePassForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
oldpass: {
trigger: 'blur',
validators: {
notEmpty: {
message: '原密码还没有输噢'
},
stringLength: {
min: 6,
max: 20,
message: '6到20个字符'
}
}
},
newpass: {
trigger: 'blur',
validators: {
notEmpty: {
message: '快输个新密码吧'
},
stringLength: {
min: 6,
max: 20,
message: '6到20个字符'
}
}
},
newpass_confirm: {
trigger: 'blur',
validators: {
notEmpty: {
message: '再输一次新密码,别打错了'
},
identical: {
field: 'newpass',
message: '两次新密码输入的不一样'
},
stringLength: {
min: 6,
max: 20,
message: '6到20个字符'
}
}
}
}
});
});
//个人资料的请求
$("button#submit_profile").click(function(){
doUpdate();
});
$(document).keydown(function(e) {
if (e.keyCode == 13 && $('#profile-panel').hasClass("active")) {
doUpdate();
}else if (e.keyCode == 13 && $('#password-panel').hasClass("active")) {
doChange();
}
});
function doUpdate(){
var nickname = $("#profileForm #nickname").val();
var domain = $("#profileForm #domain").val();
var intro = $("#profileForm #intro").val();
var avatarID = "";
$.ajax( {
url:'/home/users/usersetting',// 跳转到 action
data:JSON.stringify(
{
userName : nickname,
personalDomain : domain,
word : intro,
avatarId : avatarID
}),
type:'post',
cache:false,
dataType:'json',
contentType:"application/json;charset=utf-8",
success:function(data) {
if(data.status=="success"){
alert("资料修改成功!");
window.location.reload(true);
}else if(data.status=="fail"){
alert(data.data.errMessage);
}
},
error : function() {
// view("异常!");
alert("异常!");
}
});
}
//修改密码的请求
$("button#submit_password").click(function(){
doChange();
});
function doChange(){
var oldPass = $("#changePassForm #oldpass").val();
var newPass = $("#changePassForm #newpass").val();
$.ajax( {
url:'/home/users/changepassword',// 跳转到 action
data:JSON.stringify(
{
oldPassword : oldPass,
newPassword : newPass
}),
type:'post',
cache:false,
dataType:'json',
contentType:"application/json;charset=utf-8",
success:function(data) {
if(data.status=="success"){
alert("密码修改成功!");
window.location.reload(true);
}else if(data.status=="fail"){
alert(data.data.errMessage);
}
},
error : function() {
// view("异常!");
alert("异常!");
}
});
}

View File

@@ -0,0 +1,214 @@
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" ){
data = r.responseText;
var start = data.indexOf(">");
if(start != -1) {
var end = data.indexOf("<", start + 1);
if(end != -1) {
data = data.substring(start + 1, end);
}
}
eval( "data = " + data );
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
}
})

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,280 @@
/*!
* FormValidation (http://formvalidation.io)
* The best jQuery plugin to validate form fields. Support Bootstrap, Foundation, Pure, SemanticUI, UIKit and custom frameworks
*
* @version v0.6.2-dev, built on 2015-03-13 8:15:45 AM
* @author https://twitter.com/nghuuphuoc
* @copyright (c) 2013 - 2015 Nguyen Huu Phuoc
* @license http://formvalidation.io/license/
*/
/**
* This class supports validating Bootstrap form (http://getbootstrap.com/)
*/
(function($) {
FormValidation.Framework.Bootstrap = function(element, options, namespace) {
options = $.extend(true, {
button: {
selector: '[type="submit"]',
// The class of disabled button
// http://getbootstrap.com/css/#buttons-disabled
disabled: 'disabled'
},
err: {
// http://getbootstrap.com/css/#forms-help-text
clazz: 'help-block',
parent: '^(.*)col-(xs|sm|md|lg)-(offset-){0,1}[0-9]+(.*)$'
},
// This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
// Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
// In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
//
// Examples:
// - Use Glyphicons icons:
// icon: {
// valid: 'glyphicon glyphicon-ok',
// invalid: 'glyphicon glyphicon-remove',
// validating: 'glyphicon glyphicon-refresh',
// feedback: 'form-control-feedback'
// }
// - Use FontAwesome icons:
// icon: {
// valid: 'fa fa-check',
// invalid: 'fa fa-times',
// validating: 'fa fa-refresh',
// feedback: 'form-control-feedback'
// }
icon: {
valid: null,
invalid: null,
validating: null,
feedback: 'form-control-feedback'
},
row: {
// By default, each field is placed inside the <div class="form-group"></div>
// http://getbootstrap.com/css/#forms
selector: '.form-group',
valid: 'has-success',
invalid: 'has-error',
feedback: 'has-feedback'
}
}, options);
FormValidation.Base.apply(this, [element, options, namespace]);
};
FormValidation.Framework.Bootstrap.prototype = $.extend({}, FormValidation.Base.prototype, {
/**
* Specific framework might need to adjust the icon position
*
* @param {jQuery} $field The field element
* @param {jQuery} $icon The icon element
*/
_fixIcon: function($field, $icon) {
var ns = this._namespace,
type = $field.attr('type'),
field = $field.attr('data-' + ns + '-field'),
row = this.options.fields[field].row || this.options.row.selector,
$parent = $field.closest(row);
// Place it after the container of checkbox/radio
// so when clicking the icon, it doesn't effect to the checkbox/radio element
if ('checkbox' === type || 'radio' === type) {
var $fieldParent = $field.parent();
if ($fieldParent.hasClass(type)) {
$icon.insertAfter($fieldParent);
} else if ($fieldParent.parent().hasClass(type)) {
$icon.insertAfter($fieldParent.parent());
}
}
// The feedback icon does not render correctly if there is no label
// https://github.com/twbs/bootstrap/issues/12873
if ($parent.find('label').length === 0) {
$icon.addClass('fv-icon-no-label');
}
// Fix feedback icons in input-group
if ($parent.find('.input-group').length !== 0) {
$icon.addClass('fv-bootstrap-icon-input-group')
.insertAfter($parent.find('.input-group').eq(0));
}
},
/**
* Create a tooltip or popover
* It will be shown when focusing on the field
*
* @param {jQuery} $field The field element
* @param {String} message The message
* @param {String} type Can be 'tooltip' or 'popover'
*/
_createTooltip: function($field, message, type) {
var ns = this._namespace,
$icon = $field.data(ns + '.icon');
if ($icon) {
switch (type) {
case 'popover':
$icon
.css({
'cursor': 'pointer',
'pointer-events': 'auto'
})
.popover('destroy')
.popover({
container: 'body',
content: message,
html: true,
placement: 'auto top',
trigger: 'hover click'
});
break;
case 'tooltip':
/* falls through */
default:
$icon
.css({
'cursor': 'pointer',
'pointer-events': 'auto'
})
.tooltip('destroy')
.tooltip({
container: 'body',
html: true,
placement: 'auto top',
title: message
});
break;
}
}
},
/**
* Destroy the tooltip or popover
*
* @param {jQuery} $field The field element
* @param {String} type Can be 'tooltip' or 'popover'
*/
_destroyTooltip: function($field, type) {
var ns = this._namespace,
$icon = $field.data(ns + '.icon');
if ($icon) {
switch (type) {
case 'popover':
$icon
.css({
'cursor': '',
'pointer-events': 'none'
})
.popover('destroy');
break;
case 'tooltip':
/* falls through */
default:
$icon
.css({
'cursor': '',
'pointer-events': 'none'
})
.tooltip('destroy');
break;
}
}
},
/**
* Hide a tooltip or popover
*
* @param {jQuery} $field The field element
* @param {String} type Can be 'tooltip' or 'popover'
*/
_hideTooltip: function($field, type) {
var ns = this._namespace,
$icon = $field.data(ns + '.icon');
if ($icon) {
switch (type) {
case 'popover':
$icon.popover('hide');
break;
case 'tooltip':
/* falls through */
default:
$icon.tooltip('hide');
break;
}
}
},
/**
* Show a tooltip or popover
*
* @param {jQuery} $field The field element
* @param {String} type Can be 'tooltip' or 'popover'
*/
_showTooltip: function($field, type) {
var ns = this._namespace,
$icon = $field.data(ns + '.icon');
if ($icon) {
switch (type) {
case 'popover':
$icon.popover('show');
break;
case 'tooltip':
/* falls through */
default:
$icon.tooltip('show');
break;
}
}
}
});
/**
* Plugin definition
* Support backward
* @deprecated It will be removed soon. Instead of using $(form).bootstrapValidator(), use
* $(form).formValidation({
* framework: 'bootstrap' // It's equivalent to use data-fv-framework="bootstrap" for <form>
* });
*/
$.fn.bootstrapValidator = function(option) {
var params = arguments;
return this.each(function() {
var $this = $(this),
data = $this.data('formValidation') || $this.data('bootstrapValidator'),
options = 'object' === typeof option && option;
if (!data) {
data = new FormValidation.Framework.Bootstrap(this, $.extend({}, {
events: {
// Support backward
formInit: 'init.form.bv',
formError: 'error.form.bv',
formSuccess: 'success.form.bv',
fieldAdded: 'added.field.bv',
fieldRemoved: 'removed.field.bv',
fieldInit: 'init.field.bv',
fieldError: 'error.field.bv',
fieldSuccess: 'success.field.bv',
fieldStatus: 'status.field.bv',
localeChanged: 'changed.locale.bv',
validatorError: 'error.validator.bv',
validatorSuccess: 'success.validator.bv'
}
}, options), 'bv');
$this.addClass('fv-form-bootstrap')
.data('formValidation', data)
.data('bootstrapValidator', data);
}
// Allow to call plugin method
if ('string' === typeof option) {
data[option].apply(data, Array.prototype.slice.call(params, 1));
}
});
};
$.fn.bootstrapValidator.Constructor = FormValidation.Framework.Bootstrap;
}(jQuery));

View File

@@ -0,0 +1,379 @@
(function ($) {
/**
* Simplified Chinese language package
* Translated by @shamiao
*/
FormValidation.I18n = $.extend(true, FormValidation.I18n, {
'zh_CN': {
base64: {
'default': '请输入有效的Base64编码'
},
between: {
'default': '请输入在 %s 和 %s 之间的数值',
notInclusive: '请输入在 %s 和 %s 之间(不含两端)的数值'
},
bic: {
'default': '请输入有效的BIC商品编码'
},
callback: {
'default': '请输入有效的值'
},
choice: {
'default': '请输入有效的值',
less: '请至少选中 %s 个选项',
more: '最多只能选中 %s 个选项',
between: '请选择 %s 至 %s 个选项'
},
color: {
'default': '请输入有效的颜色值'
},
creditCard: {
'default': '请输入有效的信用卡号码'
},
cusip: {
'default': '请输入有效的美国CUSIP代码'
},
cvv: {
'default': '请输入有效的CVV代码'
},
date: {
'default': '请输入有效的日期',
min: '请输入 %s 或之后的日期',
max: '请输入 %s 或以前的日期',
range: '请输入 %s 和 %s 之间的日期'
},
different: {
'default': '请输入不同的值'
},
digits: {
'default': '请输入有效的数字'
},
ean: {
'default': '请输入有效的EAN商品编码'
},
ein: {
'default': '请输入有效的EIN商品编码'
},
emailAddress: {
'default': '请输入有效的邮件地址'
},
file: {
'default': '请选择有效的文件'
},
greaterThan: {
'default': '请输入大于等于 %s 的数值',
notInclusive: '请输入大于 %s 的数值'
},
grid: {
'default': '请输入有效的GRId编码'
},
hex: {
'default': '请输入有效的16进制数'
},
iban: {
'default': '请输入有效的IBAN(国际银行账户)号码',
country: '请输入有效的 %s 国家或地区的IBAN(国际银行账户)号码',
countries: {
AD: '安道​​尔',
AE: '阿联酋',
AL: '阿尔巴尼亚',
AO: '安哥拉',
AT: '奥地利',
AZ: '阿塞拜疆',
BA: '波斯尼亚和黑塞哥维那',
BE: '比利时',
BF: '布基纳法索',
BG: '保加利亚',
BH: '巴林',
BI: '布隆迪',
BJ: '贝宁',
BR: '巴西',
CH: '瑞士',
CI: '科特迪瓦',
CM: '喀麦隆',
CR: '哥斯达黎加',
CV: '佛得角',
CY: '塞浦路斯',
CZ: '捷克共和国',
DE: '德国',
DK: '丹麦',
DO: '多米尼加共和国',
DZ: '阿尔及利亚',
EE: '爱沙尼亚',
ES: '西班牙',
FI: '芬兰',
FO: '法罗群岛',
FR: '法国',
GB: '英国',
GE: '格鲁吉亚',
GI: '直布罗陀',
GL: '格陵兰岛',
GR: '希腊',
GT: '危地马拉',
HR: '克罗地亚',
HU: '匈牙利',
IE: '爱尔兰',
IL: '以色列',
IR: '伊朗',
IS: '冰岛',
IT: '意大利',
JO: '约旦',
KW: '科威特',
KZ: '哈萨克斯坦',
LB: '黎巴嫩',
LI: '列支敦士登',
LT: '立陶宛',
LU: '卢森堡',
LV: '拉脱维亚',
MC: '摩纳哥',
MD: '摩尔多瓦',
ME: '黑山',
MG: '马达加斯加',
MK: '马其顿',
ML: '马里',
MR: '毛里塔尼亚',
MT: '马耳他',
MU: '毛里求斯',
MZ: '莫桑比克',
NL: '荷兰',
NO: '挪威',
PK: '巴基斯坦',
PL: '波兰',
PS: '巴勒斯坦',
PT: '葡萄牙',
QA: '卡塔尔',
RO: '罗马尼亚',
RS: '塞尔维亚',
SA: '沙特阿拉伯',
SE: '瑞典',
SI: '斯洛文尼亚',
SK: '斯洛伐克',
SM: '圣马力诺',
SN: '塞内加尔',
TN: '突尼斯',
TR: '土耳其',
VG: '英属维尔京群岛'
}
},
id: {
'default': '请输入有效的身份证件号码',
country: '请输入有效的 %s 国家或地区的身份证件号码',
countries: {
BA: '波黑',
BG: '保加利亚',
BR: '巴西',
CH: '瑞士',
CL: '智利',
CN: '中国',
CZ: '捷克共和国',
DK: '丹麦',
EE: '爱沙尼亚',
ES: '西班牙',
FI: '芬兰',
HR: '克罗地亚',
IE: '爱尔兰',
IS: '冰岛',
LT: '立陶宛',
LV: '拉脱维亚',
ME: '黑山',
MK: '马其顿',
NL: '荷兰',
PL: '波兰',
RO: '罗马尼亚',
RS: '塞尔维亚',
SE: '瑞典',
SI: '斯洛文尼亚',
SK: '斯洛伐克',
SM: '圣马力诺',
TH: '泰国',
ZA: '南非'
}
},
identical: {
'default': '请输入相同的值'
},
imei: {
'default': '请输入有效的IMEI(手机串号)'
},
imo: {
'default': '请输入有效的国际海事组织(IMO)号码'
},
integer: {
'default': '请输入有效的整数值'
},
ip: {
'default': '请输入有效的IP地址',
ipv4: '请输入有效的IPv4地址',
ipv6: '请输入有效的IPv6地址'
},
isbn: {
'default': '请输入有效的ISBN(国际标准书号)'
},
isin: {
'default': '请输入有效的ISIN(国际证券编码)'
},
ismn: {
'default': '请输入有效的ISMN(印刷音乐作品编码)'
},
issn: {
'default': '请输入有效的ISSN(国际标准杂志书号)'
},
lessThan: {
'default': '请输入小于等于 %s 的数值',
notInclusive: '请输入小于 %s 的数值'
},
mac: {
'default': '请输入有效的MAC物理地址'
},
meid: {
'default': '请输入有效的MEID(移动设备识别码)'
},
notEmpty: {
'default': '请填写必填项目'
},
numeric: {
'default': '请输入有效的数值,允许小数'
},
phone: {
'default': '请输入有效的电话号码',
country: '请输入有效的 %s 国家或地区的电话号码',
countries: {
AE: '阿联酋',
BG: '保加利亚',
BR: '巴西',
CN: '中国',
CZ: '捷克共和国',
DE: '德国',
DK: '丹麦',
ES: '西班牙',
FR: '法国',
GB: '英国',
IN: '印度',
MA: '摩洛哥',
NL: '荷兰',
PK: '巴基斯坦',
RO: '罗马尼亚',
RU: '俄罗斯',
SK: '斯洛伐克',
TH: '泰国',
US: '美国',
VE: '委内瑞拉'
}
},
regexp: {
'default': '请输入符合正则表达式限制的值'
},
remote: {
'default': '请输入有效的值'
},
rtn: {
'default': '请输入有效的RTN号码'
},
sedol: {
'default': '请输入有效的SEDOL代码'
},
siren: {
'default': '请输入有效的SIREN号码'
},
siret: {
'default': '请输入有效的SIRET号码'
},
step: {
'default': '请输入在基础值上,增加 %s 的整数倍的数值'
},
stringCase: {
'default': '只能输入小写字母',
upper: '只能输入大写字母'
},
stringLength: {
'default': '请输入符合长度限制的值',
less: '最多只能输入 %s 个字符',
more: '需要输入至少 %s 个字符',
between: '请输入 %s 至 %s 个字符'
},
uri: {
'default': '请输入一个有效的URL地址'
},
uuid: {
'default': '请输入有效的UUID',
version: '请输入版本 %s 的UUID'
},
vat: {
'default': '请输入有效的VAT(税号)',
country: '请输入有效的 %s 国家或地区的VAT(税号)',
countries: {
AT: '奥地利',
BE: '比利时',
BG: '保加利亚',
BR: '巴西',
CH: '瑞士',
CY: '塞浦路斯',
CZ: '捷克共和国',
DE: '德国',
DK: '丹麦',
EE: '爱沙尼亚',
ES: '西班牙',
FI: '芬兰',
FR: '法语',
GB: '英国',
GR: '希腊',
EL: '希腊',
HU: '匈牙利',
HR: '克罗地亚',
IE: '爱尔兰',
IS: '冰岛',
IT: '意大利',
LT: '立陶宛',
LU: '卢森堡',
LV: '拉脱维亚',
MT: '马耳他',
NL: '荷兰',
NO: '挪威',
PL: '波兰',
PT: '葡萄牙',
RO: '罗马尼亚',
RU: '俄罗斯',
RS: '塞尔维亚',
SE: '瑞典',
SI: '斯洛文尼亚',
SK: '斯洛伐克',
VE: '委内瑞拉',
ZA: '南非'
}
},
vin: {
'default': '请输入有效的VIN(美国车辆识别号码)'
},
zipCode: {
'default': '请输入有效的邮政编码',
country: '请输入有效的 %s 国家或地区的邮政编码',
countries: {
AT: '奥地利',
BG: '保加利亚',
BR: '巴西',
CA: '加拿大',
CH: '瑞士',
CZ: '捷克共和国',
DE: '德国',
DK: '丹麦',
ES: '西班牙',
FR: '法国',
GB: '英国',
IE: '爱尔兰',
IN: '印度',
IT: '意大利',
MA: '摩洛哥',
NL: '荷兰',
PL: '波兰',
PT: '葡萄牙',
RO: '罗马尼亚',
RU: '俄罗斯',
SE: '瑞典',
SG: '新加坡',
SK: '斯洛伐克',
US: '美国'
}
}
}
});
}(jQuery));