code stringlengths 1 2.08M | language stringclasses 1
value |
|---|---|
$().ready(function () {
$("form").submit(function () {
if ($(this).valid()) {
$(".btn-container input").css("disable", "disable");
$(".btn-container input").val("saving……");
}
});
$(".degree-dropdown").change(function () {
if ($(this).val() == 'Other') {
$(".degree-other-textfield").show().val("");
} else {
$(".degree-other-textfield").hide().val($(this).val());
}
});
var init = function () {
if ($(".degree-dropdown").val() == 'Other') {
$(".degree-other-textfield").show();
}
}
init();
}); | JavaScript |
/*函数方法*/
$.fn.slide=function(){
return this.children("h2").click(function(){
$(this).next(".info_t").show();
$(this).parent().siblings().children(".info_t").hide();
})
} | JavaScript |
/**
* This jQuery plugin displays pagination links inside the selected elements.
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 1.2
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
*/
jQuery.fn.pagination = function(maxentries, opts){
opts = jQuery.extend({
items_per_page:10,
num_display_entries:10,
current_page:0,
num_edge_entries:0,
link_to:"#",
prev_text:"Prev",
next_text:"Next",
ellipse_text:"...",
prev_show_always:true,
next_show_always:true,
callback:function(){return false;}
},opts||{});
return this.each(function() {
/**
* Calculate the maximum number of pages
*/
function numPages() {
return Math.ceil(maxentries/opts.items_per_page);
}
/**
* Calculate start and end point of pagination links depending on
* current_page and num_display_entries.
* @return {Array}
*/
function getInterval() {
var ne_half = Math.ceil(opts.num_display_entries/2);
var np = numPages();
var upper_limit = np-opts.num_display_entries;
var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np);
return [start,end];
}
/**
* This is the event handling function for the pagination links.
* @param {int} page_id The new page number
*/
function pageSelected(page_id, evt){
current_page = page_id;
drawLinks();
var continuePropagation = opts.callback(page_id, panel);
if (!continuePropagation) {
if (evt.stopPropagation) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
}
return continuePropagation;
}
/**
* This function inserts the pagination links into the container element
*/
function drawLinks() {
panel.empty();
var interval = getInterval();
var np = numPages();
// This helper function returns a handler function that calls pageSelected with the right page_id
var getClickHandler = function(page_id) {
return function(evt){ return pageSelected(page_id,evt); }
}
// Helper function for generating a single link (or a span tag if it's the current page)
var appendItem = function(page_id, appendopts){
page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value
appendopts = jQuery.extend({text:page_id+1, classes:""}, appendopts||{});
if(page_id == current_page){
var lnk = jQuery("<span class='current'>"+(appendopts.text)+"</span>");
}
else
{
var lnk = jQuery("<a>"+(appendopts.text)+"</a>")
.bind("click", getClickHandler(page_id))
.attr('href', opts.link_to.replace(/__id__/,page_id));
}
if(appendopts.classes){lnk.addClass(appendopts.classes);}
panel.append(lnk);
}
// Generate "Previous"-Link
if(opts.prev_text && (current_page > 0 || opts.prev_show_always)){
appendItem(current_page-1,{text:opts.prev_text, classes:"prev"});
}
// Generate starting points
if (interval[0] > 0 && opts.num_edge_entries > 0)
{
var end = Math.min(opts.num_edge_entries, interval[0]);
for(var i=0; i<end; i++) {
appendItem(i);
}
if(opts.num_edge_entries < interval[0] && opts.ellipse_text)
{
jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
}
}
// Generate interval links
for(var i=interval[0]; i<interval[1]; i++) {
appendItem(i);
}
// Generate ending points
if (interval[1] < np && opts.num_edge_entries > 0)
{
if(np-opts.num_edge_entries > interval[1]&& opts.ellipse_text)
{
jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
}
var begin = Math.max(np-opts.num_edge_entries, interval[1]);
for(var i=begin; i<np; i++) {
appendItem(i);
}
}
// Generate "Next"-Link
if(opts.next_text && (current_page < np-1 || opts.next_show_always)){
appendItem(current_page+1,{text:opts.next_text, classes:"next"});
}
}
// Extract current_page from options
var current_page = opts.current_page;
// Create a sane value for maxentries and items_per_page
maxentries = (!maxentries || maxentries < 0)?1:maxentries;
opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
// Store DOM element for easy access from all inner functions
var panel = jQuery(this);
// Attach control functions to the DOM element
this.selectPage = function(page_id){ pageSelected(page_id);}
this.prevPage = function(){
if (current_page > 0) {
pageSelected(current_page - 1);
return true;
}
else {
return false;
}
}
this.nextPage = function(){
if(current_page < numPages()-1) {
pageSelected(current_page+1);
return true;
}
else {
return false;
}
}
// When all initialisation is done, draw the links
drawLinks();
// call callback function
opts.callback(current_page, this);
});
}
| JavaScript |
function scrolling(obj,s){
object=$(obj);
i=0;
size=object.size();
speed=s;
t=setInterval(animail_back,speed);
}
//向后方
function animail_back(){
if(i==size-1){
i=0;
object.eq(i).fadeIn(3000);
object.eq(i).siblings().fadeOut(3000);
}else{
i++;
object.eq(i).fadeIn(3000);
object.eq(i).siblings().fadeOut(3000);
}
}
//向前翻
function animail_font(){
if(i==0){
i=size-1;
object.eq(i).fadeIn(3000);
object.eq(i).siblings().fadeOut(3000);
}else{
i--;
object.eq(i).fadeIn(3000);
object.eq(i).siblings().fadeOut(3000);
}
}
/*左边滑动*/
$(".l_narrow").click(function(){
animail_font();
})
$(".l_narrow").hover(
function(){$(this).fadeTo(800,0.5);},
function(){$(this).fadeTo(800,1);}
)
$(".r_narrow").hover(
function(){$(this).fadeTo(800,0.5);},
function(){$(this).fadeTo(800,1);}
)
$(".r_narrow").click(function(){
animail_back();
})
$(".narrow").mouseover(function(){
clearInterval(t);
})
$(".narrow").mouseout(function(){
t=setInterval(animail_back,speed);
})
| JavaScript |
/*!
* jQuery Cycle Plugin (with Transition Definitions)
* Examples and documentation at: http://jquery.malsup.com/cycle/
* Copyright (c) 2007-2010 M. Alsup
* Version: 2.88 (08-JUN-2010)
* Dual licensed under the MIT and GPL licenses.
* http://jquery.malsup.com/license.html
* Requires: jQuery v1.2.6 or later
*/
;(function($) {
var ver = '2.88';
// if $.support is not defined (pre jQuery 1.3) add what I need
if ($.support == undefined) {
$.support = {
opacity: !($.browser.msie)
};
}
function debug(s) {
if ($.fn.cycle.debug)
log(s);
}
function log() {
if (window.console && window.console.log)
window.console.log('[cycle] ' + Array.prototype.join.call(arguments,' '));
};
// the options arg can be...
// a number - indicates an immediate transition should occur to the given slide index
// a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc)
// an object - properties to control the slideshow
//
// the arg2 arg can be...
// the name of an fx (only used in conjunction with a numeric value for 'options')
// the value true (only used in first arg == 'resume') and indicates
// that the resume should occur immediately (not wait for next timeout)
$.fn.cycle = function(options, arg2) {
var o = { s: this.selector, c: this.context };
// in 1.3+ we can fix mistakes with the ready state
if (this.length === 0 && options != 'stop') {
if (!$.isReady && o.s) {
log('DOM not ready, queuing slideshow');
$(function() {
$(o.s,o.c).cycle(options,arg2);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
// iterate the matched nodeset
return this.each(function() {
var opts = handleArguments(this, options, arg2);
if (opts === false)
return;
opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink;
// stop existing slideshow for this container (if there is one)
if (this.cycleTimeout)
clearTimeout(this.cycleTimeout);
this.cycleTimeout = this.cyclePause = 0;
var $cont = $(this);
var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children();
var els = $slides.get();
if (els.length < 2) {
log('terminating; too few slides: ' + els.length);
return;
}
var opts2 = buildOptions($cont, $slides, els, opts, o);
if (opts2 === false)
return;
var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.rev);
// if it's an auto slideshow, kick it off
if (startTime) {
startTime += (opts2.delay || 0);
if (startTime < 10)
startTime = 10;
debug('first timeout: ' + startTime);
this.cycleTimeout = setTimeout(function(){go(els,opts2,0,(!opts2.rev && !opts.backwards))}, startTime);
}
});
};
// process the args that were passed to the plugin fn
function handleArguments(cont, options, arg2) {
if (cont.cycleStop == undefined)
cont.cycleStop = 0;
if (options === undefined || options === null)
options = {};
if (options.constructor == String) {
switch(options) {
case 'destroy':
case 'stop':
var opts = $(cont).data('cycle.opts');
if (!opts)
return false;
cont.cycleStop++; // callbacks look for change
if (cont.cycleTimeout)
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
$(cont).removeData('cycle.opts');
if (options == 'destroy')
destroy(opts);
return false;
case 'toggle':
cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1;
checkInstantResume(cont.cyclePause, arg2, cont);
return false;
case 'pause':
cont.cyclePause = 1;
return false;
case 'resume':
cont.cyclePause = 0;
checkInstantResume(false, arg2, cont);
return false;
case 'prev':
case 'next':
var opts = $(cont).data('cycle.opts');
if (!opts) {
log('options not found, "prev/next" ignored');
return false;
}
$.fn.cycle[options](opts);
return false;
default:
options = { fx: options };
};
return options;
}
else if (options.constructor == Number) {
// go to the requested slide
var num = options;
options = $(cont).data('cycle.opts');
if (!options) {
log('options not found, can not advance slide');
return false;
}
if (num < 0 || num >= options.elements.length) {
log('invalid slide index: ' + num);
return false;
}
options.nextSlide = num;
if (cont.cycleTimeout) {
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
}
if (typeof arg2 == 'string')
options.oneTimeFx = arg2;
go(options.elements, options, 1, num >= options.currSlide);
return false;
}
return options;
function checkInstantResume(isPaused, arg2, cont) {
if (!isPaused && arg2 === true) { // resume now!
var options = $(cont).data('cycle.opts');
if (!options) {
log('options not found, can not resume');
return false;
}
if (cont.cycleTimeout) {
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
}
go(options.elements, options, 1, (!opts.rev && !opts.backwards));
}
}
};
function removeFilter(el, opts) {
if (!$.support.opacity && opts.cleartype && el.style.filter) {
try { el.style.removeAttribute('filter'); }
catch(smother) {} // handle old opera versions
}
};
// unbind event handlers
function destroy(opts) {
if (opts.next)
$(opts.next).unbind(opts.prevNextEvent);
if (opts.prev)
$(opts.prev).unbind(opts.prevNextEvent);
if (opts.pager || opts.pagerAnchorBuilder)
$.each(opts.pagerAnchors || [], function() {
this.unbind().remove();
});
opts.pagerAnchors = null;
if (opts.destroy) // callback
opts.destroy(opts);
};
// one-time initialization
function buildOptions($cont, $slides, els, options, o) {
// support metadata plugin (v1.0 and v2.0)
var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
if (opts.autostop)
opts.countdown = opts.autostopCount || els.length;
var cont = $cont[0];
$cont.data('cycle.opts', opts);
opts.$cont = $cont;
opts.stopCount = cont.cycleStop;
opts.elements = els;
opts.before = opts.before ? [opts.before] : [];
opts.after = opts.after ? [opts.after] : [];
opts.after.unshift(function(){ opts.busy=0; });
// push some after callbacks
if (!$.support.opacity && opts.cleartype)
opts.after.push(function() { removeFilter(this, opts); });
if (opts.continuous)
opts.after.push(function() { go(els,opts,0,(!opts.rev && !opts.backwards)); });
saveOriginalOpts(opts);
// clearType corrections
if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
clearTypeFix($slides);
// container requires non-static position so that slides can be position within
if ($cont.css('position') == 'static')
$cont.css('position', 'relative');
if (opts.width)
$cont.width(opts.width);
if (opts.height && opts.height != 'auto')
$cont.height(opts.height);
if (opts.startingSlide)
opts.startingSlide = parseInt(opts.startingSlide);
else if (opts.backwards)
opts.startingSlide = els.length - 1;
// if random, mix up the slide array
if (opts.random) {
opts.randomMap = [];
for (var i = 0; i < els.length; i++)
opts.randomMap.push(i);
opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
opts.randomIndex = 1;
opts.startingSlide = opts.randomMap[1];
}
else if (opts.startingSlide >= els.length)
opts.startingSlide = 0; // catch bogus input
opts.currSlide = opts.startingSlide || 0;
var first = opts.startingSlide;
// set position and zIndex on all the slides
$slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) {
var z;
if (opts.backwards)
z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i;
else
z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i;
$(this).css('z-index', z)
});
// make sure first slide is visible
$(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case
removeFilter(els[first], opts);
// stretch slides
if (opts.fit && opts.width)
$slides.width(opts.width);
if (opts.fit && opts.height && opts.height != 'auto')
$slides.height(opts.height);
// stretch container
var reshape = opts.containerResize && !$cont.innerHeight();
if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9
var maxw = 0, maxh = 0;
for(var j=0; j < els.length; j++) {
var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight();
if (!w) w = e.offsetWidth || e.width || $e.attr('width')
if (!h) h = e.offsetHeight || e.height || $e.attr('height');
maxw = w > maxw ? w : maxw;
maxh = h > maxh ? h : maxh;
}
if (maxw > 0 && maxh > 0)
$cont.css({width:maxw+'px',height:maxh+'px'});
}
if (opts.pause)
$cont.hover(function(){this.cyclePause++;},function(){this.cyclePause--;});
if (supportMultiTransitions(opts) === false)
return false;
// apparently a lot of people use image slideshows without height/width attributes on the images.
// Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that.
var requeue = false;
options.requeueAttempts = options.requeueAttempts || 0;
$slides.each(function() {
// try to get height/width of each slide
var $el = $(this);
this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0);
this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0);
if ( $el.is('img') ) {
// sigh.. sniffing, hacking, shrugging... this crappy hack tries to account for what browsers do when
// an image is being downloaded and the markup did not include sizing info (height/width attributes);
// there seems to be some "default" sizes used in this situation
var loadingIE = ($.browser.msie && this.cycleW == 28 && this.cycleH == 30 && !this.complete);
var loadingFF = ($.browser.mozilla && this.cycleW == 34 && this.cycleH == 19 && !this.complete);
var loadingOp = ($.browser.opera && ((this.cycleW == 42 && this.cycleH == 19) || (this.cycleW == 37 && this.cycleH == 17)) && !this.complete);
var loadingOther = (this.cycleH == 0 && this.cycleW == 0 && !this.complete);
// don't requeue for images that are still loading but have a valid size
if (loadingIE || loadingFF || loadingOp || loadingOther) {
if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever
log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH);
setTimeout(function() {$(o.s,o.c).cycle(options)}, opts.requeueTimeout);
requeue = true;
return false; // break each loop
}
else {
log('could not determine size of image: '+this.src, this.cycleW, this.cycleH);
}
}
}
return true;
});
if (requeue)
return false;
opts.cssBefore = opts.cssBefore || {};
opts.animIn = opts.animIn || {};
opts.animOut = opts.animOut || {};
$slides.not(':eq('+first+')').css(opts.cssBefore);
if (opts.cssFirst)
$($slides[first]).css(opts.cssFirst);
if (opts.timeout) {
opts.timeout = parseInt(opts.timeout);
// ensure that timeout and speed settings are sane
if (opts.speed.constructor == String)
opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed);
if (!opts.sync)
opts.speed = opts.speed / 2;
var buffer = opts.fx == 'shuffle' ? 500 : 250;
while((opts.timeout - opts.speed) < buffer) // sanitize timeout
opts.timeout += opts.speed;
}
if (opts.easing)
opts.easeIn = opts.easeOut = opts.easing;
if (!opts.speedIn)
opts.speedIn = opts.speed;
if (!opts.speedOut)
opts.speedOut = opts.speed;
opts.slideCount = els.length;
opts.currSlide = opts.lastSlide = first;
if (opts.random) {
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else if (opts.backwards)
opts.nextSlide = opts.startingSlide == 0 ? (els.length-1) : opts.startingSlide-1;
else
opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1;
// run transition init fn
if (!opts.multiFx) {
var init = $.fn.cycle.transitions[opts.fx];
if ($.isFunction(init))
init($cont, $slides, opts);
else if (opts.fx != 'custom' && !opts.multiFx) {
log('unknown transition: ' + opts.fx,'; slideshow terminating');
return false;
}
}
// fire artificial events
var e0 = $slides[first];
if (opts.before.length)
opts.before[0].apply(e0, [e0, e0, opts, true]);
if (opts.after.length > 1)
opts.after[1].apply(e0, [e0, e0, opts, true]);
if (opts.next)
$(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?-1:1)});
if (opts.prev)
$(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?1:-1)});
if (opts.pager || opts.pagerAnchorBuilder)
buildPager(els,opts);
exposeAddSlide(opts, els);
return opts;
};
// save off original opts so we can restore after clearing state
function saveOriginalOpts(opts) {
opts.original = { before: [], after: [] };
opts.original.cssBefore = $.extend({}, opts.cssBefore);
opts.original.cssAfter = $.extend({}, opts.cssAfter);
opts.original.animIn = $.extend({}, opts.animIn);
opts.original.animOut = $.extend({}, opts.animOut);
$.each(opts.before, function() { opts.original.before.push(this); });
$.each(opts.after, function() { opts.original.after.push(this); });
};
function supportMultiTransitions(opts) {
var i, tx, txs = $.fn.cycle.transitions;
// look for multiple effects
if (opts.fx.indexOf(',') > 0) {
opts.multiFx = true;
opts.fxs = opts.fx.replace(/\s*/g,'').split(',');
// discard any bogus effect names
for (i=0; i < opts.fxs.length; i++) {
var fx = opts.fxs[i];
tx = txs[fx];
if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) {
log('discarding unknown transition: ',fx);
opts.fxs.splice(i,1);
i--;
}
}
// if we have an empty list then we threw everything away!
if (!opts.fxs.length) {
log('No valid transitions named; slideshow terminating.');
return false;
}
}
else if (opts.fx == 'all') { // auto-gen the list of transitions
opts.multiFx = true;
opts.fxs = [];
for (p in txs) {
tx = txs[p];
if (txs.hasOwnProperty(p) && $.isFunction(tx))
opts.fxs.push(p);
}
}
if (opts.multiFx && opts.randomizeEffects) {
// munge the fxs array to make effect selection random
var r1 = Math.floor(Math.random() * 20) + 30;
for (i = 0; i < r1; i++) {
var r2 = Math.floor(Math.random() * opts.fxs.length);
opts.fxs.push(opts.fxs.splice(r2,1)[0]);
}
debug('randomized fx sequence: ',opts.fxs);
}
return true;
};
// provide a mechanism for adding slides after the slideshow has started
function exposeAddSlide(opts, els) {
opts.addSlide = function(newSlide, prepend) {
var $s = $(newSlide), s = $s[0];
if (!opts.autostopCount)
opts.countdown++;
els[prepend?'unshift':'push'](s);
if (opts.els)
opts.els[prepend?'unshift':'push'](s); // shuffle needs this
opts.slideCount = els.length;
$s.css('position','absolute');
$s[prepend?'prependTo':'appendTo'](opts.$cont);
if (prepend) {
opts.currSlide++;
opts.nextSlide++;
}
if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
clearTypeFix($s);
if (opts.fit && opts.width)
$s.width(opts.width);
if (opts.fit && opts.height && opts.height != 'auto')
$slides.height(opts.height);
s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height();
s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width();
$s.css(opts.cssBefore);
if (opts.pager || opts.pagerAnchorBuilder)
$.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts);
if ($.isFunction(opts.onAddSlide))
opts.onAddSlide($s);
else
$s.hide(); // default behavior
};
}
// reset internal state; we do this on every pass in order to support multiple effects
$.fn.cycle.resetState = function(opts, fx) {
fx = fx || opts.fx;
opts.before = []; opts.after = [];
opts.cssBefore = $.extend({}, opts.original.cssBefore);
opts.cssAfter = $.extend({}, opts.original.cssAfter);
opts.animIn = $.extend({}, opts.original.animIn);
opts.animOut = $.extend({}, opts.original.animOut);
opts.fxFn = null;
$.each(opts.original.before, function() { opts.before.push(this); });
$.each(opts.original.after, function() { opts.after.push(this); });
// re-init
var init = $.fn.cycle.transitions[fx];
if ($.isFunction(init))
init(opts.$cont, $(opts.elements), opts);
};
// this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt
function go(els, opts, manual, fwd) {
// opts.busy is true if we're in the middle of an animation
if (manual && opts.busy && opts.manualTrump) {
// let manual transitions requests trump active ones
debug('manualTrump in go(), stopping active transition');
$(els).stop(true,true);
opts.busy = false;
}
// don't begin another timeout-based transition if there is one active
if (opts.busy) {
debug('transition active, ignoring new tx request');
return;
}
var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide];
// stop cycling if we have an outstanding stop request
if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual)
return;
// check to see if we should stop cycling based on autostop options
if (!manual && !p.cyclePause && !opts.bounce &&
((opts.autostop && (--opts.countdown <= 0)) ||
(opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) {
if (opts.end)
opts.end(opts);
return;
}
// if slideshow is paused, only transition on a manual trigger
var changed = false;
if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) {
changed = true;
var fx = opts.fx;
// keep trying to get the slide size if we don't have it yet
curr.cycleH = curr.cycleH || $(curr).height();
curr.cycleW = curr.cycleW || $(curr).width();
next.cycleH = next.cycleH || $(next).height();
next.cycleW = next.cycleW || $(next).width();
// support multiple transition types
if (opts.multiFx) {
if (opts.lastFx == undefined || ++opts.lastFx >= opts.fxs.length)
opts.lastFx = 0;
fx = opts.fxs[opts.lastFx];
opts.currFx = fx;
}
// one-time fx overrides apply to: $('div').cycle(3,'zoom');
if (opts.oneTimeFx) {
fx = opts.oneTimeFx;
opts.oneTimeFx = null;
}
$.fn.cycle.resetState(opts, fx);
// run the before callbacks
if (opts.before.length)
$.each(opts.before, function(i,o) {
if (p.cycleStop != opts.stopCount) return;
o.apply(next, [curr, next, opts, fwd]);
});
// stage the after callacks
var after = function() {
$.each(opts.after, function(i,o) {
if (p.cycleStop != opts.stopCount) return;
o.apply(next, [curr, next, opts, fwd]);
});
};
debug('tx firing; currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide);
// get ready to perform the transition
opts.busy = 1;
if (opts.fxFn) // fx function provided?
opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ?
$.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent);
else
$.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
}
if (changed || opts.nextSlide == opts.currSlide) {
// calculate the next slide
opts.lastSlide = opts.currSlide;
if (opts.random) {
opts.currSlide = opts.nextSlide;
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
opts.nextSlide = opts.randomMap[opts.randomIndex];
if (opts.nextSlide == opts.currSlide)
opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1;
}
else if (opts.backwards) {
var roll = (opts.nextSlide - 1) < 0;
if (roll && opts.bounce) {
opts.backwards = !opts.backwards;
opts.nextSlide = 1;
opts.currSlide = 0;
}
else {
opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1;
opts.currSlide = roll ? 0 : opts.nextSlide+1;
}
}
else { // sequence
var roll = (opts.nextSlide + 1) == els.length;
if (roll && opts.bounce) {
opts.backwards = !opts.backwards;
opts.nextSlide = els.length-2;
opts.currSlide = els.length-1;
}
else {
opts.nextSlide = roll ? 0 : opts.nextSlide+1;
opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
}
}
}
if (changed && opts.pager)
opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass);
// stage the next transition
var ms = 0;
if (opts.timeout && !opts.continuous)
ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd);
else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic
ms = 10;
if (ms > 0)
p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, (!opts.rev && !opts.backwards)) }, ms);
};
// invoked after transition
$.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) {
$(pager).each(function() {
$(this).children().removeClass(clsName).eq(currSlide).addClass(clsName);
});
};
// calculate timeout value for current transition
function getTimeout(curr, next, opts, fwd) {
if (opts.timeoutFn) {
// call user provided calc fn
var t = opts.timeoutFn.call(curr,curr,next,opts,fwd);
while ((t - opts.speed) < 250) // sanitize timeout
t += opts.speed;
debug('calculated timeout: ' + t + '; speed: ' + opts.speed);
if (t !== false)
return t;
}
return opts.timeout;
};
// expose next/prev function, caller must pass in state
$.fn.cycle.next = function(opts) { advance(opts, opts.rev?-1:1); };
$.fn.cycle.prev = function(opts) { advance(opts, opts.rev?1:-1);};
// advance slide forward or back
function advance(opts, val) {
var els = opts.elements;
var p = opts.$cont[0], timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
if (opts.random && val < 0) {
// move back to the previously display slide
opts.randomIndex--;
if (--opts.randomIndex == -2)
opts.randomIndex = els.length-2;
else if (opts.randomIndex == -1)
opts.randomIndex = els.length-1;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else if (opts.random) {
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else {
opts.nextSlide = opts.currSlide + val;
if (opts.nextSlide < 0) {
if (opts.nowrap) return false;
opts.nextSlide = els.length - 1;
}
else if (opts.nextSlide >= els.length) {
if (opts.nowrap) return false;
opts.nextSlide = 0;
}
}
var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated
if ($.isFunction(cb))
cb(val > 0, opts.nextSlide, els[opts.nextSlide]);
go(els, opts, 1, val>=0);
return false;
};
function buildPager(els, opts) {
var $p = $(opts.pager);
$.each(els, function(i,o) {
$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);
});
opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass);
};
$.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) {
var a;
if ($.isFunction(opts.pagerAnchorBuilder)) {
a = opts.pagerAnchorBuilder(i,el);
debug('pagerAnchorBuilder('+i+', el) returned: ' + a);
}
else
a = '<a href="#">'+(i+1)+'</a>';
if (!a)
return;
var $a = $(a);
// don't reparent if anchor is in the dom
if ($a.parents('body').length === 0) {
var arr = [];
if ($p.length > 1) {
$p.each(function() {
var $clone = $a.clone(true);
$(this).append($clone);
arr.push($clone[0]);
});
$a = $(arr);
}
else {
$a.appendTo($p);
}
}
opts.pagerAnchors = opts.pagerAnchors || [];
opts.pagerAnchors.push($a);
$a.bind(opts.pagerEvent, function(e) {
e.preventDefault();
opts.nextSlide = i;
var p = opts.$cont[0], timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated
if ($.isFunction(cb))
cb(opts.nextSlide, els[opts.nextSlide]);
go(els,opts,1,opts.currSlide < i); // trigger the trans
// return false; // <== allow bubble
});
if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble)
$a.bind('click.cycle', function(){return false;}); // suppress click
if (opts.pauseOnPagerHover)
$a.hover(function() { opts.$cont[0].cyclePause++; }, function() { opts.$cont[0].cyclePause--; } );
};
// helper fn to calculate the number of slides between the current and the next
$.fn.cycle.hopsFromLast = function(opts, fwd) {
var hops, l = opts.lastSlide, c = opts.currSlide;
if (fwd)
hops = c > l ? c - l : opts.slideCount - l;
else
hops = c < l ? l - c : l + opts.slideCount - c;
return hops;
};
// fix clearType problems in ie6 by setting an explicit bg color
// (otherwise text slides look horrible during a fade transition)
function clearTypeFix($slides) {
debug('applying clearType background-color hack');
function hex(s) {
s = parseInt(s).toString(16);
return s.length < 2 ? '0'+s : s;
};
function getBg(e) {
for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {
var v = $.css(e,'background-color');
if (v.indexOf('rgb') >= 0 ) {
var rgb = v.match(/\d+/g);
return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
}
if (v && v != 'transparent')
return v;
}
return '#ffffff';
};
$slides.each(function() { $(this).css('background-color', getBg(this)); });
};
// reset common props before the next transition
$.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) {
$(opts.elements).not(curr).hide();
opts.cssBefore.opacity = 1;
opts.cssBefore.display = 'block';
if (w !== false && next.cycleW > 0)
opts.cssBefore.width = next.cycleW;
if (h !== false && next.cycleH > 0)
opts.cssBefore.height = next.cycleH;
opts.cssAfter = opts.cssAfter || {};
opts.cssAfter.display = 'none';
$(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0));
$(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1));
};
// the actual fn for effecting a transition
$.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) {
var $l = $(curr), $n = $(next);
var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut;
$n.css(opts.cssBefore);
if (speedOverride) {
if (typeof speedOverride == 'number')
speedIn = speedOut = speedOverride;
else
speedIn = speedOut = 1;
easeIn = easeOut = null;
}
var fn = function() {$n.animate(opts.animIn, speedIn, easeIn, cb)};
$l.animate(opts.animOut, speedOut, easeOut, function() {
if (opts.cssAfter) $l.css(opts.cssAfter);
if (!opts.sync) fn();
});
if (opts.sync) fn();
};
// transition definitions - only fade is defined here, transition pack defines the rest
$.fn.cycle.transitions = {
fade: function($cont, $slides, opts) {
$slides.not(':eq('+opts.currSlide+')').css('opacity',0);
opts.before.push(function(curr,next,opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.opacity = 0;
});
opts.animIn = { opacity: 1 };
opts.animOut = { opacity: 0 };
opts.cssBefore = { top: 0, left: 0 };
}
};
$.fn.cycle.ver = function() { return ver; };
// override these globally if you like (they are all optional)
$.fn.cycle.defaults = {
fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle')
timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance)
timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag)
continuous: 0, // true to start next transition immediately after current one completes
speed: 1000, // speed of the transition (any valid fx speed value)
speedIn: null, // speed of the 'in' transition
speedOut: null, // speed of the 'out' transition
next: null, // selector for element to use as event trigger for next slide
prev: null, // selector for element to use as event trigger for previous slide
// prevNextClick: null, // @deprecated; please use onPrevNextEvent instead
onPrevNextEvent: null, // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement)
prevNextEvent:'click.cycle',// event which drives the manual transition to the previous or next slide
pager: null, // selector for element to use as pager container
//pagerClick null, // @deprecated; please use onPagerEvent instead
onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement)
pagerEvent: 'click.cycle', // name of event which drives the pager navigation
allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling
pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement)
before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag)
after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag)
end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
easing: null, // easing method for both in and out transitions
easeIn: null, // easing for "in" transition
easeOut: null, // easing for "out" transition
shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 }
animIn: null, // properties that define how the slide animates in
animOut: null, // properties that define how the slide animates out
cssBefore: null, // properties that define the initial state of the slide before transitioning in
cssAfter: null, // properties that defined the state of the slide after transitioning out
fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
height: 'auto', // container height
startingSlide: 0, // zero-based index of the first slide to be displayed
sync: 1, // true if in/out transitions should occur simultaneously
random: 0, // true for random, false for sequence (not applicable to shuffle fx)
fit: 0, // force slides to fit container
containerResize: 1, // resize container to fit largest slide
pause: 0, // true to enable "pause on hover"
pauseOnPagerHover: 0, // true to pause when hovering over pager link
autostop: 0, // true to end slideshow after X transitions (where X == slide count)
autostopCount: 0, // number of transitions (optionally used with autostop to define X)
delay: 0, // additional delay (in ms) for first transition (hint: can be negative)
slideExpr: null, // expression for selecting slides (if something other than all children is required)
cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE)
cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
nowrap: 0, // true to prevent slideshow from wrapping
fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms
randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random
rev: 0, // causes animations to transition in reverse
manualTrump: true, // causes manual transition to stop an active transition instead of being ignored
requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded
requeueTimeout: 250, // ms delay for requeue
activePagerClass: 'activeSlide', // class name used for the active pager link
updateActivePagerLink: null, // callback fn invoked to update the active pager link (adds/removes activePagerClass style)
backwards: false // true to start slideshow at last slide and move backwards through the stack
};
})(jQuery);
/*!
* jQuery Cycle Plugin Transition Definitions
* This script is a plugin for the jQuery Cycle Plugin
* Examples and documentation at: http://malsup.com/jquery/cycle/
* Copyright (c) 2007-2010 M. Alsup
* Version: 2.72
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
//
// These functions define one-time slide initialization for the named
// transitions. To save file size feel free to remove any of these that you
// don't need.
//
$.fn.cycle.transitions.none = function($cont, $slides, opts) {
opts.fxFn = function(curr,next,opts,after){
$(next).show();
$(curr).hide();
after();
};
}
// scrollUp/Down/Left/Right
$.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var h = $cont.height();
opts.cssBefore ={ top: h, left: 0 };
opts.cssFirst = { top: 0 };
opts.animIn = { top: 0 };
opts.animOut = { top: -h };
};
$.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var h = $cont.height();
opts.cssFirst = { top: 0 };
opts.cssBefore= { top: -h, left: 0 };
opts.animIn = { top: 0 };
opts.animOut = { top: h };
};
$.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var w = $cont.width();
opts.cssFirst = { left: 0 };
opts.cssBefore= { left: w, top: 0 };
opts.animIn = { left: 0 };
opts.animOut = { left: 0-w };
};
$.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var w = $cont.width();
opts.cssFirst = { left: 0 };
opts.cssBefore= { left: -w, top: 0 };
opts.animIn = { left: 0 };
opts.animOut = { left: w };
};
$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
$cont.css('overflow','hidden').width();
opts.before.push(function(curr, next, opts, fwd) {
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW);
opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW;
});
opts.cssFirst = { left: 0 };
opts.cssBefore= { top: 0 };
opts.animIn = { left: 0 };
opts.animOut = { top: 0 };
};
$.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push(function(curr, next, opts, fwd) {
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1);
opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH;
});
opts.cssFirst = { top: 0 };
opts.cssBefore= { left: 0 };
opts.animIn = { top: 0 };
opts.animOut = { left: 0 };
};
// slideX/slideY
$.fn.cycle.transitions.slideX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(opts.elements).not(curr).hide();
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.animIn.width = next.cycleW;
});
opts.cssBefore = { left: 0, top: 0, width: 0 };
opts.animIn = { width: 'show' };
opts.animOut = { width: 0 };
};
$.fn.cycle.transitions.slideY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(opts.elements).not(curr).hide();
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.animIn.height = next.cycleH;
});
opts.cssBefore = { left: 0, top: 0, height: 0 };
opts.animIn = { height: 'show' };
opts.animOut = { height: 0 };
};
// shuffle
$.fn.cycle.transitions.shuffle = function($cont, $slides, opts) {
var i, w = $cont.css('overflow', 'visible').width();
$slides.css({left: 0, top: 0});
opts.before.push(function(curr,next,opts) {
$.fn.cycle.commonReset(curr,next,opts,true,true,true);
});
// only adjust speed once!
if (!opts.speedAdjusted) {
opts.speed = opts.speed / 2; // shuffle has 2 transitions
opts.speedAdjusted = true;
}
opts.random = 0;
opts.shuffle = opts.shuffle || {left:-w, top:15};
opts.els = [];
for (i=0; i < $slides.length; i++)
opts.els.push($slides[i]);
for (i=0; i < opts.currSlide; i++)
opts.els.push(opts.els.shift());
// custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!)
opts.fxFn = function(curr, next, opts, cb, fwd) {
var $el = fwd ? $(curr) : $(next);
$(next).css(opts.cssBefore);
var count = opts.slideCount;
$el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() {
var hops = $.fn.cycle.hopsFromLast(opts, fwd);
for (var k=0; k < hops; k++)
fwd ? opts.els.push(opts.els.shift()) : opts.els.unshift(opts.els.pop());
if (fwd) {
for (var i=0, len=opts.els.length; i < len; i++)
$(opts.els[i]).css('z-index', len-i+count);
}
else {
var z = $(curr).css('z-index');
$el.css('z-index', parseInt(z)+1+count);
}
$el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() {
$(fwd ? this : curr).hide();
if (cb) cb();
});
});
};
opts.cssBefore = { display: 'block', opacity: 1, top: 0, left: 0 };
};
// turnUp/Down/Left/Right
$.fn.cycle.transitions.turnUp = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.cssBefore.top = next.cycleH;
opts.animIn.height = next.cycleH;
});
opts.cssFirst = { top: 0 };
opts.cssBefore = { left: 0, height: 0 };
opts.animIn = { top: 0 };
opts.animOut = { height: 0 };
};
$.fn.cycle.transitions.turnDown = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.cssFirst = { top: 0 };
opts.cssBefore = { left: 0, top: 0, height: 0 };
opts.animOut = { height: 0 };
};
$.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.cssBefore.left = next.cycleW;
opts.animIn.width = next.cycleW;
});
opts.cssBefore = { top: 0, width: 0 };
opts.animIn = { left: 0 };
opts.animOut = { width: 0 };
};
$.fn.cycle.transitions.turnRight = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.animIn.width = next.cycleW;
opts.animOut.left = curr.cycleW;
});
opts.cssBefore = { top: 0, left: 0, width: 0 };
opts.animIn = { left: 0 };
opts.animOut = { width: 0 };
};
// zoom
$.fn.cycle.transitions.zoom = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,false,true);
opts.cssBefore.top = next.cycleH/2;
opts.cssBefore.left = next.cycleW/2;
opts.animIn = { top: 0, left: 0, width: next.cycleW, height: next.cycleH };
opts.animOut = { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 };
});
opts.cssFirst = { top:0, left: 0 };
opts.cssBefore = { width: 0, height: 0 };
};
// fadeZoom
$.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,false);
opts.cssBefore.left = next.cycleW/2;
opts.cssBefore.top = next.cycleH/2;
opts.animIn = { top: 0, left: 0, width: next.cycleW, height: next.cycleH };
});
opts.cssBefore = { width: 0, height: 0 };
opts.animOut = { opacity: 0 };
};
// blindX
$.fn.cycle.transitions.blindX = function($cont, $slides, opts) {
var w = $cont.css('overflow','hidden').width();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.animIn.width = next.cycleW;
opts.animOut.left = curr.cycleW;
});
opts.cssBefore = { left: w, top: 0 };
opts.animIn = { left: 0 };
opts.animOut = { left: w };
};
// blindY
$.fn.cycle.transitions.blindY = function($cont, $slides, opts) {
var h = $cont.css('overflow','hidden').height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.cssBefore = { top: h, left: 0 };
opts.animIn = { top: 0 };
opts.animOut = { top: h };
};
// blindZ
$.fn.cycle.transitions.blindZ = function($cont, $slides, opts) {
var h = $cont.css('overflow','hidden').height();
var w = $cont.width();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.cssBefore = { top: h, left: w };
opts.animIn = { top: 0, left: 0 };
opts.animOut = { top: h, left: w };
};
// growX - grow horizontally from centered 0 width
$.fn.cycle.transitions.growX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.cssBefore.left = this.cycleW/2;
opts.animIn = { left: 0, width: this.cycleW };
opts.animOut = { left: 0 };
});
opts.cssBefore = { width: 0, top: 0 };
};
// growY - grow vertically from centered 0 height
$.fn.cycle.transitions.growY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.cssBefore.top = this.cycleH/2;
opts.animIn = { top: 0, height: this.cycleH };
opts.animOut = { top: 0 };
});
opts.cssBefore = { height: 0, left: 0 };
};
// curtainX - squeeze in both edges horizontally
$.fn.cycle.transitions.curtainX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true,true);
opts.cssBefore.left = next.cycleW/2;
opts.animIn = { left: 0, width: this.cycleW };
opts.animOut = { left: curr.cycleW/2, width: 0 };
});
opts.cssBefore = { top: 0, width: 0 };
};
// curtainY - squeeze in both edges vertically
$.fn.cycle.transitions.curtainY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false,true);
opts.cssBefore.top = next.cycleH/2;
opts.animIn = { top: 0, height: next.cycleH };
opts.animOut = { top: curr.cycleH/2, height: 0 };
});
opts.cssBefore = { left: 0, height: 0 };
};
// cover - curr slide covered by next slide
$.fn.cycle.transitions.cover = function($cont, $slides, opts) {
var d = opts.direction || 'left';
var w = $cont.css('overflow','hidden').width();
var h = $cont.height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
if (d == 'right')
opts.cssBefore.left = -w;
else if (d == 'up')
opts.cssBefore.top = h;
else if (d == 'down')
opts.cssBefore.top = -h;
else
opts.cssBefore.left = w;
});
opts.animIn = { left: 0, top: 0};
opts.animOut = { opacity: 1 };
opts.cssBefore = { top: 0, left: 0 };
};
// uncover - curr slide moves off next slide
$.fn.cycle.transitions.uncover = function($cont, $slides, opts) {
var d = opts.direction || 'left';
var w = $cont.css('overflow','hidden').width();
var h = $cont.height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,true,true);
if (d == 'right')
opts.animOut.left = w;
else if (d == 'up')
opts.animOut.top = -h;
else if (d == 'down')
opts.animOut.top = h;
else
opts.animOut.left = -w;
});
opts.animIn = { left: 0, top: 0 };
opts.animOut = { opacity: 1 };
opts.cssBefore = { top: 0, left: 0 };
};
// toss - move top slide and fade away
$.fn.cycle.transitions.toss = function($cont, $slides, opts) {
var w = $cont.css('overflow','visible').width();
var h = $cont.height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,true,true);
// provide default toss settings if animOut not provided
if (!opts.animOut.left && !opts.animOut.top)
opts.animOut = { left: w*2, top: -h/2, opacity: 0 };
else
opts.animOut.opacity = 0;
});
opts.cssBefore = { left: 0, top: 0 };
opts.animIn = { left: 0 };
};
// wipe - clip animation
$.fn.cycle.transitions.wipe = function($cont, $slides, opts) {
var w = $cont.css('overflow','hidden').width();
var h = $cont.height();
opts.cssBefore = opts.cssBefore || {};
var clip;
if (opts.clip) {
if (/l2r/.test(opts.clip))
clip = 'rect(0px 0px '+h+'px 0px)';
else if (/r2l/.test(opts.clip))
clip = 'rect(0px '+w+'px '+h+'px '+w+'px)';
else if (/t2b/.test(opts.clip))
clip = 'rect(0px '+w+'px 0px 0px)';
else if (/b2t/.test(opts.clip))
clip = 'rect('+h+'px '+w+'px '+h+'px 0px)';
else if (/zoom/.test(opts.clip)) {
var top = parseInt(h/2);
var left = parseInt(w/2);
clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)';
}
}
opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)';
var d = opts.cssBefore.clip.match(/(\d+)/g);
var t = parseInt(d[0]), r = parseInt(d[1]), b = parseInt(d[2]), l = parseInt(d[3]);
opts.before.push(function(curr, next, opts) {
if (curr == next) return;
var $curr = $(curr), $next = $(next);
$.fn.cycle.commonReset(curr,next,opts,true,true,false);
opts.cssAfter.display = 'block';
var step = 1, count = parseInt((opts.speedIn / 13)) - 1;
(function f() {
var tt = t ? t - parseInt(step * (t/count)) : 0;
var ll = l ? l - parseInt(step * (l/count)) : 0;
var bb = b < h ? b + parseInt(step * ((h-b)/count || 1)) : h;
var rr = r < w ? r + parseInt(step * ((w-r)/count || 1)) : w;
$next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' });
(step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none');
})();
});
opts.cssBefore = { display: 'block', opacity: 1, top: 0, left: 0 };
opts.animIn = { left: 0 };
opts.animOut = { left: 0 };
};
})(jQuery);
| JavaScript |
function HtmlEncode(value) {
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
function HtmlDecode(value) {
return $('<div/>').html(value).text();
}
$(document).ready(function () {
$('[rel=tooltip]').tooltip();
});
function BindDDL(objects, ddl) {
$(ddl).html('');
if($(ddl).attr('multiple') != 'multiple')
$(ddl).append($('<option value="0">Please Select</option>'));
if (objects != null && objects.length > 0) {
for (i = 0; i < objects.length; i++) {
var type = objects[i];
$(ddl).append($('<option></option>').attr("value", type.ID).text(type.Name));
}
}
}
function ShowLoadingAnimation(shoBlockingContainer, message) {
message = typeof (message) == 'undefined' || message == null || message.length == 0 ? '' : message;
$('#divLoadingAnimation div').html(message);
$('#divLoadingAnimation').show();
if (shoBlockingContainer) {
$('#divBlockingContainer').width($(document).width()).height($(document).height()).show();
$(window).resize(function () {
$('#divBlockingContainer').width($(document).width()).height($(document).height());
});
}
}
function HideLoadingAnimation() {
$('#divLoadingAnimation').hide();
$('#divBlockingContainer').hide();
}
function ShowCenteredPopUp(pageURL, windowName, width, height, isScrolling) {
//alert(pageURL);
var scrollbars = isScrolling ? 'yes' : 'no';
var leftPosition = (screen.width) ? (screen.width - width) / 2 : 0;
var topPosition = (screen.height) ? (screen.height - height) / 2 : 0;
topPosition -= 30;
var settings = 'height=' + height + ',width=' + width + ',top=' + topPosition + ',left=' + leftPosition + ',resizable=no,scrollbars=' + scrollbars + ',menubar=no,toolbar=no,status=yes,location=no,directories=no,addressbar=no'
var page = pageURL;
win = window.open(page, windowName, settings);
if (win != null) {
win.window.focus();
}
return win;
}
function AddToFavoriteResume(resumeID, btn) {
if ($(btn).hasClass('disabled')) return;
ShowLoadingAnimation(false);
Ajax('/Ajax/AddToFavoriteResume', 'resumeID=' + resumeID, function (result) {
HideLoadingAnimation();
var status = parseInt(result);
if (status == 1) {
$(btn).addClass('disabled').html('<i class="icon-star"></i> Added to Favorite');
}
});
}
function AddToFavoriteJob(jobID, btn) {
if ($(btn).hasClass('disabled')) return;
ShowLoadingAnimation(false);
Ajax('/Ajax/AddToFavoriteJob', 'JobID=' + jobID + '&url=' + window.location, function (result) {
HideLoadingAnimation();
var status = parseInt(result);
if (status == -1)
window.location = '/Account/Logon';
else if (status == 1) {
$(btn).addClass('disabled').html('<i class="icon-star"></i> Added to Favorite');
}
});
}
function SuccessMessageBox(message, heading) {
if (typeof (heading) == 'undefined' || heading.length == 0)
heading = 'Success!';
return '<div class="alert alert-success">' +
'<button type="button" class="close" data-dismiss="alert">×</button>' +
'<h4>' + heading + '</h4>' +
message +
'</div>';
}
function WarningMessageBox(message, heading) {
if (typeof (heading) == 'undefined' || heading.length == 0)
heading = 'Warning!';
return '<div class="alert alert-block">' +
'<button type="button" class="close" data-dismiss="alert">×</button>' +
'<h4>' + heading + '</h4>' +
message +
'</div>';
}
function Ajax(url, data, successCallback) {
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (result) {
successCallback(result);
},
statusCode: {
404: function () {
alert('ERROR: Unable to complete the AJAX Request.\nRequested URL: ' + url + ' was not found.\nPlease contact with site administrator.');
}
}
});
}
function AjaxGET(url, successCallback) {
$.ajax({
type: 'GET',
url: url,
success: function (result) {
successCallback(result);
},
statusCode: {
404: function () {
alert('ERROR: Unable to complete the AJAX Request.\nRequested URL: ' + url + ' was not found.\nPlease contact with site administrator.');
}
}
});
} | JavaScript |
/*
* jQuery FlexSlider v2.1
* http://www.woothemes.com/flexslider/
*
* Copyright 2012 WooThemes
* Free to use under the GPLv2 license.
* http://www.gnu.org/licenses/gpl-2.0.html
*
* Contributing author: Tyler Smith (@mbmufffin)
*/
; (function ($) {
//FlexSlider: Object Instance
$.flexslider = function (el, options) {
var slider = $(el),
vars = $.extend({}, $.flexslider.defaults, options),
namespace = vars.namespace,
touch = ("ontouchstart" in window) || window.DocumentTouch && document instanceof DocumentTouch,
eventType = (touch) ? "touchend" : "click",
vertical = vars.direction === "vertical",
reverse = vars.reverse,
carousel = (vars.itemWidth > 0),
fade = vars.animation === "fade",
asNav = vars.asNavFor !== "",
methods = {};
// Store a reference to the slider object
$.data(el, "flexslider", slider);
// Privat slider methods
methods = {
init: function () {
slider.animating = false;
slider.currentSlide = vars.startAt;
slider.animatingTo = slider.currentSlide;
slider.atEnd = (slider.currentSlide === 0 || slider.currentSlide === slider.last);
slider.containerSelector = vars.selector.substr(0, vars.selector.search(' '));
slider.slides = $(vars.selector, slider);
slider.container = $(slider.containerSelector, slider);
slider.count = slider.slides.length;
// SYNC:
slider.syncExists = $(vars.sync).length > 0;
// SLIDE:
if (vars.animation === "slide") vars.animation = "swing";
slider.prop = (vertical) ? "top" : "marginLeft";
slider.args = {};
// SLIDESHOW:
slider.manualPause = false;
// TOUCH/USECSS:
slider.transitions = !vars.video && !fade && vars.useCSS && (function () {
var obj = document.createElement('div'),
props = ['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'];
for (var i in props) {
if (obj.style[props[i]] !== undefined) {
slider.pfx = props[i].replace('Perspective', '').toLowerCase();
slider.prop = "-" + slider.pfx + "-transform";
return true;
}
}
return false;
} ());
// CONTROLSCONTAINER:
if (vars.controlsContainer !== "") slider.controlsContainer = $(vars.controlsContainer).length > 0 && $(vars.controlsContainer);
// MANUAL:
if (vars.manualControls !== "") slider.manualControls = $(vars.manualControls).length > 0 && $(vars.manualControls);
// RANDOMIZE:
if (vars.randomize) {
slider.slides.sort(function () { return (Math.round(Math.random()) - 0.5); });
slider.container.empty().append(slider.slides);
}
slider.doMath();
// ASNAV:
if (asNav) methods.asNav.setup();
// INIT
slider.setup("init");
// CONTROLNAV:
if (vars.controlNav) methods.controlNav.setup();
// DIRECTIONNAV:
if (vars.directionNav) methods.directionNav.setup();
// KEYBOARD:
if (vars.keyboard && ($(slider.containerSelector).length === 1 || vars.multipleKeyboard)) {
$(document).bind('keyup', function (event) {
var keycode = event.keyCode;
if (!slider.animating && (keycode === 39 || keycode === 37)) {
var target = (keycode === 39) ? slider.getTarget('next') :
(keycode === 37) ? slider.getTarget('prev') : false;
slider.flexAnimate(target, vars.pauseOnAction);
}
});
}
// MOUSEWHEEL:
if (vars.mousewheel) {
slider.bind('mousewheel', function (event, delta, deltaX, deltaY) {
event.preventDefault();
var target = (delta < 0) ? slider.getTarget('next') : slider.getTarget('prev');
slider.flexAnimate(target, vars.pauseOnAction);
});
}
// PAUSEPLAY
if (vars.pausePlay) methods.pausePlay.setup();
// SLIDSESHOW
if (vars.slideshow) {
if (vars.pauseOnHover) {
slider.hover(function () {
if (!slider.manualPlay && !slider.manualPause) slider.pause();
}, function () {
if (!slider.manualPause && !slider.manualPlay) slider.play();
});
}
// initialize animation
(vars.initDelay > 0) ? setTimeout(slider.play, vars.initDelay) : slider.play();
}
// TOUCH
if (touch && vars.touch) methods.touch();
// FADE&&SMOOTHHEIGHT || SLIDE:
if (!fade || (fade && vars.smoothHeight)) $(window).bind("resize focus", methods.resize);
// API: start() Callback
setTimeout(function () {
vars.start(slider);
}, 200);
},
asNav: {
setup: function () {
slider.asNav = true;
slider.animatingTo = Math.floor(slider.currentSlide / slider.move);
slider.currentItem = slider.currentSlide;
slider.slides.removeClass(namespace + "active-slide").eq(slider.currentItem).addClass(namespace + "active-slide");
slider.slides.click(function (e) {
e.preventDefault();
var $slide = $(this),
target = $slide.index();
if (!$(vars.asNavFor).data('flexslider').animating && !$slide.hasClass('active')) {
slider.direction = (slider.currentItem < target) ? "next" : "prev";
slider.flexAnimate(target, vars.pauseOnAction, false, true, true);
}
});
}
},
controlNav: {
setup: function () {
if (!slider.manualControls) {
methods.controlNav.setupPaging();
} else { // MANUALCONTROLS:
methods.controlNav.setupManual();
}
},
setupPaging: function () {
var type = (vars.controlNav === "thumbnails") ? 'control-thumbs' : 'control-paging',
j = 1,
item;
slider.controlNavScaffold = $('<ol class="' + namespace + 'control-nav ' + namespace + type + '"></ol>');
if (slider.pagingCount > 1) {
for (var i = 0; i < slider.pagingCount; i++) {
item = (vars.controlNav === "thumbnails") ? '<img src="' + slider.slides.eq(i).attr("data-thumb") + '"/>' : '<a>' + j + '</a>';
slider.controlNavScaffold.append('<li>' + item + '</li>');
j++;
}
}
// CONTROLSCONTAINER:
(slider.controlsContainer) ? $(slider.controlsContainer).append(slider.controlNavScaffold) : slider.append(slider.controlNavScaffold);
methods.controlNav.set();
methods.controlNav.active();
slider.controlNavScaffold.delegate('a, img', eventType, function (event) {
event.preventDefault();
var $this = $(this),
target = slider.controlNav.index($this);
if (!$this.hasClass(namespace + 'active')) {
slider.direction = (target > slider.currentSlide) ? "next" : "prev";
slider.flexAnimate(target, vars.pauseOnAction);
}
});
// Prevent iOS click event bug
if (touch) {
slider.controlNavScaffold.delegate('a', "click touchstart", function (event) {
event.preventDefault();
});
}
},
setupManual: function () {
slider.controlNav = slider.manualControls;
methods.controlNav.active();
slider.controlNav.live(eventType, function (event) {
event.preventDefault();
var $this = $(this),
target = slider.controlNav.index($this);
if (!$this.hasClass(namespace + 'active')) {
(target > slider.currentSlide) ? slider.direction = "next" : slider.direction = "prev";
slider.flexAnimate(target, vars.pauseOnAction);
}
});
// Prevent iOS click event bug
if (touch) {
slider.controlNav.live("click touchstart", function (event) {
event.preventDefault();
});
}
},
set: function () {
var selector = (vars.controlNav === "thumbnails") ? 'img' : 'a';
slider.controlNav = $('.' + namespace + 'control-nav li ' + selector, (slider.controlsContainer) ? slider.controlsContainer : slider);
},
active: function () {
slider.controlNav.removeClass(namespace + "active").eq(slider.animatingTo).addClass(namespace + "active");
},
update: function (action, pos) {
if (slider.pagingCount > 1 && action === "add") {
slider.controlNavScaffold.append($('<li><a>' + slider.count + '</a></li>'));
} else if (slider.pagingCount === 1) {
slider.controlNavScaffold.find('li').remove();
} else {
slider.controlNav.eq(pos).closest('li').remove();
}
methods.controlNav.set();
(slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav.length) ? slider.update(pos, action) : methods.controlNav.active();
}
},
directionNav: {
setup: function () {
var directionNavScaffold = $('<ul class="' + namespace + 'direction-nav"><li><a class="' + namespace + 'prev" href="#">' + vars.prevText + '</a></li><li><a class="' + namespace + 'next" href="#">' + vars.nextText + '</a></li></ul>');
// CONTROLSCONTAINER:
if (slider.controlsContainer) {
$(slider.controlsContainer).append(directionNavScaffold);
slider.directionNav = $('.' + namespace + 'direction-nav li a', slider.controlsContainer);
} else {
slider.append(directionNavScaffold);
slider.directionNav = $('.' + namespace + 'direction-nav li a', slider);
}
methods.directionNav.update();
slider.directionNav.bind(eventType, function (event) {
event.preventDefault();
var target = ($(this).hasClass(namespace + 'next')) ? slider.getTarget('next') : slider.getTarget('prev');
slider.flexAnimate(target, vars.pauseOnAction);
});
// Prevent iOS click event bug
if (touch) {
slider.directionNav.bind("click touchstart", function (event) {
event.preventDefault();
});
}
},
update: function () {
var disabledClass = namespace + 'disabled';
if (slider.pagingCount === 1) {
slider.directionNav.addClass(disabledClass);
} else if (!vars.animationLoop) {
if (slider.animatingTo === 0) {
slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "prev").addClass(disabledClass);
} else if (slider.animatingTo === slider.last) {
slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "next").addClass(disabledClass);
} else {
slider.directionNav.removeClass(disabledClass);
}
} else {
slider.directionNav.removeClass(disabledClass);
}
}
},
pausePlay: {
setup: function () {
var pausePlayScaffold = $('<div class="' + namespace + 'pauseplay"><a></a></div>');
// CONTROLSCONTAINER:
if (slider.controlsContainer) {
slider.controlsContainer.append(pausePlayScaffold);
slider.pausePlay = $('.' + namespace + 'pauseplay a', slider.controlsContainer);
} else {
slider.append(pausePlayScaffold);
slider.pausePlay = $('.' + namespace + 'pauseplay a', slider);
}
methods.pausePlay.update((vars.slideshow) ? namespace + 'pause' : namespace + 'play');
slider.pausePlay.bind(eventType, function (event) {
event.preventDefault();
if ($(this).hasClass(namespace + 'pause')) {
slider.manualPause = true;
slider.manualPlay = false;
slider.pause();
} else {
slider.manualPause = false;
slider.manualPlay = true;
slider.play();
}
});
// Prevent iOS click event bug
if (touch) {
slider.pausePlay.bind("click touchstart", function (event) {
event.preventDefault();
});
}
},
update: function (state) {
(state === "play") ? slider.pausePlay.removeClass(namespace + 'pause').addClass(namespace + 'play').text(vars.playText) : slider.pausePlay.removeClass(namespace + 'play').addClass(namespace + 'pause').text(vars.pauseText);
}
},
touch: function () {
var startX,
startY,
offset,
cwidth,
dx,
startT,
scrolling = false;
el.addEventListener('touchstart', onTouchStart, false);
function onTouchStart(e) {
if (slider.animating) {
e.preventDefault();
} else if (e.touches.length === 1) {
slider.pause();
// CAROUSEL:
cwidth = (vertical) ? slider.h : slider.w;
startT = Number(new Date());
// CAROUSEL:
offset = (carousel && reverse && slider.animatingTo === slider.last) ? 0 :
(carousel && reverse) ? slider.limit - (((slider.itemW + vars.itemMargin) * slider.move) * slider.animatingTo) :
(carousel && slider.currentSlide === slider.last) ? slider.limit :
(carousel) ? ((slider.itemW + vars.itemMargin) * slider.move) * slider.currentSlide :
(reverse) ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth;
startX = (vertical) ? e.touches[0].pageY : e.touches[0].pageX;
startY = (vertical) ? e.touches[0].pageX : e.touches[0].pageY;
el.addEventListener('touchmove', onTouchMove, false);
el.addEventListener('touchend', onTouchEnd, false);
}
}
function onTouchMove(e) {
dx = (vertical) ? startX - e.touches[0].pageY : startX - e.touches[0].pageX;
scrolling = (vertical) ? (Math.abs(dx) < Math.abs(e.touches[0].pageX - startY)) : (Math.abs(dx) < Math.abs(e.touches[0].pageY - startY));
if (!scrolling || Number(new Date()) - startT > 500) {
e.preventDefault();
if (!fade && slider.transitions) {
if (!vars.animationLoop) {
dx = dx / ((slider.currentSlide === 0 && dx < 0 || slider.currentSlide === slider.last && dx > 0) ? (Math.abs(dx) / cwidth + 2) : 1);
}
slider.setProps(offset + dx, "setTouch");
}
}
}
function onTouchEnd(e) {
// finish the touch by undoing the touch session
el.removeEventListener('touchmove', onTouchMove, false);
if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) {
var updateDx = (reverse) ? -dx : dx,
target = (updateDx > 0) ? slider.getTarget('next') : slider.getTarget('prev');
if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth / 2)) {
slider.flexAnimate(target, vars.pauseOnAction);
} else {
if (!fade) slider.flexAnimate(slider.currentSlide, vars.pauseOnAction, true);
}
}
el.removeEventListener('touchend', onTouchEnd, false);
startX = null;
startY = null;
dx = null;
offset = null;
}
},
resize: function () {
if (!slider.animating && slider.is(':visible')) {
if (!carousel) slider.doMath();
if (fade) {
// SMOOTH HEIGHT:
methods.smoothHeight();
} else if (carousel) { //CAROUSEL:
slider.slides.width(slider.computedW);
slider.update(slider.pagingCount);
slider.setProps();
}
else if (vertical) { //VERTICAL:
slider.viewport.height(slider.h);
slider.setProps(slider.h, "setTotal");
} else {
// SMOOTH HEIGHT:
if (vars.smoothHeight) methods.smoothHeight();
slider.newSlides.width(slider.computedW);
slider.setProps(slider.computedW, "setTotal");
}
}
},
smoothHeight: function (dur) {
if (!vertical || fade) {
var $obj = (fade) ? slider : slider.viewport;
(dur) ? $obj.animate({ "height": slider.slides.eq(slider.animatingTo).height() }, dur) : $obj.height(slider.slides.eq(slider.animatingTo).height());
}
},
sync: function (action) {
var $obj = $(vars.sync).data("flexslider"),
target = slider.animatingTo;
switch (action) {
case "animate": $obj.flexAnimate(target, vars.pauseOnAction, false, true); break;
case "play": if (!$obj.playing && !$obj.asNav) { $obj.play(); } break;
case "pause": $obj.pause(); break;
}
}
}
// public methods
slider.flexAnimate = function (target, pause, override, withSync, fromNav) {
if (asNav && slider.pagingCount === 1) slider.direction = (slider.currentItem < target) ? "next" : "prev";
if (!slider.animating && (slider.canAdvance(target, fromNav) || override) && slider.is(":visible")) {
if (asNav && withSync) {
var master = $(vars.asNavFor).data('flexslider');
slider.atEnd = target === 0 || target === slider.count - 1;
master.flexAnimate(target, true, false, true, fromNav);
slider.direction = (slider.currentItem < target) ? "next" : "prev";
master.direction = slider.direction;
if (Math.ceil((target + 1) / slider.visible) - 1 !== slider.currentSlide && target !== 0) {
slider.currentItem = target;
slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
target = Math.floor(target / slider.visible);
} else {
slider.currentItem = target;
slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
return false;
}
}
slider.animating = true;
slider.animatingTo = target;
// API: before() animation Callback
vars.before(slider);
// SLIDESHOW:
if (pause) slider.pause();
// SYNC:
if (slider.syncExists && !fromNav) methods.sync("animate");
// CONTROLNAV
if (vars.controlNav) methods.controlNav.active();
// !CAROUSEL:
// CANDIDATE: slide active class (for add/remove slide)
if (!carousel) slider.slides.removeClass(namespace + 'active-slide').eq(target).addClass(namespace + 'active-slide');
// INFINITE LOOP:
// CANDIDATE: atEnd
slider.atEnd = target === 0 || target === slider.last;
// DIRECTIONNAV:
if (vars.directionNav) methods.directionNav.update();
if (target === slider.last) {
// API: end() of cycle Callback
vars.end(slider);
// SLIDESHOW && !INFINITE LOOP:
if (!vars.animationLoop) slider.pause();
}
// SLIDE:
if (!fade) {
var dimension = (vertical) ? slider.slides.filter(':first').height() : slider.computedW,
margin, slideString, calcNext;
// INFINITE LOOP / REVERSE:
if (carousel) {
margin = (vars.itemWidth > slider.w) ? vars.itemMargin * 2 : vars.itemMargin;
calcNext = ((slider.itemW + margin) * slider.move) * slider.animatingTo;
slideString = (calcNext > slider.limit && slider.visible !== 1) ? slider.limit : calcNext;
} else if (slider.currentSlide === 0 && target === slider.count - 1 && vars.animationLoop && slider.direction !== "next") {
slideString = (reverse) ? (slider.count + slider.cloneOffset) * dimension : 0;
} else if (slider.currentSlide === slider.last && target === 0 && vars.animationLoop && slider.direction !== "prev") {
slideString = (reverse) ? 0 : (slider.count + 1) * dimension;
} else {
slideString = (reverse) ? ((slider.count - 1) - target + slider.cloneOffset) * dimension : (target + slider.cloneOffset) * dimension;
}
slider.setProps(slideString, "", vars.animationSpeed);
if (slider.transitions) {
if (!vars.animationLoop || !slider.atEnd) {
slider.animating = false;
slider.currentSlide = slider.animatingTo;
}
slider.container.unbind("webkitTransitionEnd transitionend");
slider.container.bind("webkitTransitionEnd transitionend", function () {
slider.wrapup(dimension);
});
} else {
slider.container.animate(slider.args, vars.animationSpeed, vars.easing, function () {
slider.wrapup(dimension);
});
}
} else { // FADE:
if (!touch) {
slider.slides.eq(slider.currentSlide).fadeOut(vars.animationSpeed, vars.easing);
slider.slides.eq(target).fadeIn(vars.animationSpeed, vars.easing, slider.wrapup);
} else {
slider.slides.eq(slider.currentSlide).css({ "opacity": 0, "zIndex": 1 });
slider.slides.eq(target).css({ "opacity": 1, "zIndex": 2 });
slider.slides.unbind("webkitTransitionEnd transitionend");
slider.slides.eq(slider.currentSlide).bind("webkitTransitionEnd transitionend", function () {
// API: after() animation Callback
vars.after(slider);
});
slider.animating = false;
slider.currentSlide = slider.animatingTo;
}
}
// SMOOTH HEIGHT:
if (vars.smoothHeight) methods.smoothHeight(vars.animationSpeed);
}
}
slider.wrapup = function (dimension) {
// SLIDE:
if (!fade && !carousel) {
if (slider.currentSlide === 0 && slider.animatingTo === slider.last && vars.animationLoop) {
slider.setProps(dimension, "jumpEnd");
} else if (slider.currentSlide === slider.last && slider.animatingTo === 0 && vars.animationLoop) {
slider.setProps(dimension, "jumpStart");
}
}
slider.animating = false;
slider.currentSlide = slider.animatingTo;
// API: after() animation Callback
vars.after(slider);
}
// SLIDESHOW:
slider.animateSlides = function () {
if (!slider.animating) slider.flexAnimate(slider.getTarget("next"));
}
// SLIDESHOW:
slider.pause = function () {
clearInterval(slider.animatedSlides);
slider.playing = false;
// PAUSEPLAY:
if (vars.pausePlay) methods.pausePlay.update("play");
// SYNC:
if (slider.syncExists) methods.sync("pause");
}
// SLIDESHOW:
slider.play = function () {
slider.animatedSlides = setInterval(slider.animateSlides, vars.slideshowSpeed);
slider.playing = true;
// PAUSEPLAY:
if (vars.pausePlay) methods.pausePlay.update("pause");
// SYNC:
if (slider.syncExists) methods.sync("play");
}
slider.canAdvance = function (target, fromNav) {
// ASNAV:
var last = (asNav) ? slider.pagingCount - 1 : slider.last;
return (fromNav) ? true :
(asNav && slider.currentItem === slider.count - 1 && target === 0 && slider.direction === "prev") ? true :
(asNav && slider.currentItem === 0 && target === slider.pagingCount - 1 && slider.direction !== "next") ? false :
(target === slider.currentSlide && !asNav) ? false :
(vars.animationLoop) ? true :
(slider.atEnd && slider.currentSlide === 0 && target === last && slider.direction !== "next") ? false :
(slider.atEnd && slider.currentSlide === last && target === 0 && slider.direction === "next") ? false :
true;
}
slider.getTarget = function (dir) {
slider.direction = dir;
if (dir === "next") {
return (slider.currentSlide === slider.last) ? 0 : slider.currentSlide + 1;
} else {
return (slider.currentSlide === 0) ? slider.last : slider.currentSlide - 1;
}
}
// SLIDE:
slider.setProps = function (pos, special, dur) {
var target = (function () {
var posCheck = (pos) ? pos : ((slider.itemW + vars.itemMargin) * slider.move) * slider.animatingTo,
posCalc = (function () {
if (carousel) {
return (special === "setTouch") ? pos :
(reverse && slider.animatingTo === slider.last) ? 0 :
(reverse) ? slider.limit - (((slider.itemW + vars.itemMargin) * slider.move) * slider.animatingTo) :
(slider.animatingTo === slider.last) ? slider.limit : posCheck;
} else {
switch (special) {
case "setTotal": return (reverse) ? ((slider.count - 1) - slider.currentSlide + slider.cloneOffset) * pos : (slider.currentSlide + slider.cloneOffset) * pos;
case "setTouch": return (reverse) ? pos : pos;
case "jumpEnd": return (reverse) ? pos : slider.count * pos;
case "jumpStart": return (reverse) ? slider.count * pos : pos;
default: return pos;
}
}
} ());
return (posCalc * -1) + "px";
} ());
if (slider.transitions) {
target = (vertical) ? "translate3d(0," + target + ",0)" : "translate3d(" + target + ",0,0)";
dur = (dur !== undefined) ? (dur / 1000) + "s" : "0s";
slider.container.css("-" + slider.pfx + "-transition-duration", dur);
}
slider.args[slider.prop] = target;
if (slider.transitions || dur === undefined) slider.container.css(slider.args);
}
slider.setup = function (type) {
// SLIDE:
if (!fade) {
var sliderOffset, arr;
if (type === "init") {
slider.viewport = $('<div class="' + namespace + 'viewport"></div>').css({ "overflow": "hidden", "position": "relative" }).appendTo(slider).append(slider.container);
// INFINITE LOOP:
slider.cloneCount = 0;
slider.cloneOffset = 0;
// REVERSE:
if (reverse) {
arr = $.makeArray(slider.slides).reverse();
slider.slides = $(arr);
slider.container.empty().append(slider.slides);
}
}
// INFINITE LOOP && !CAROUSEL:
if (vars.animationLoop && !carousel) {
slider.cloneCount = 2;
slider.cloneOffset = 1;
// clear out old clones
if (type !== "init") slider.container.find('.clone').remove();
slider.container.append(slider.slides.first().clone().addClass('clone')).prepend(slider.slides.last().clone().addClass('clone'));
}
slider.newSlides = $(vars.selector, slider);
sliderOffset = (reverse) ? slider.count - 1 - slider.currentSlide + slider.cloneOffset : slider.currentSlide + slider.cloneOffset;
// VERTICAL:
if (vertical && !carousel) {
slider.container.height((slider.count + slider.cloneCount) * 200 + "%").css("position", "absolute").width("100%");
setTimeout(function () {
slider.newSlides.css({ "display": "block" });
slider.doMath();
slider.viewport.height(slider.h);
slider.setProps(sliderOffset * slider.h, "init");
}, (type === "init") ? 100 : 0);
} else {
slider.container.width((slider.count + slider.cloneCount) * 200 + "%");
slider.setProps(sliderOffset * slider.computedW, "init");
setTimeout(function () {
slider.doMath();
slider.newSlides.css({ "width": slider.computedW, "float": "left", "display": "block" });
// SMOOTH HEIGHT:
if (vars.smoothHeight) methods.smoothHeight();
}, (type === "init") ? 100 : 0);
}
} else { // FADE:
slider.slides.css({ "width": "100%", "float": "left", "marginRight": "-100%", "position": "relative" });
if (type === "init") {
if (!touch) {
slider.slides.eq(slider.currentSlide).fadeIn(vars.animationSpeed, vars.easing);
} else {
slider.slides.css({ "opacity": 0, "display": "block", "webkitTransition": "opacity " + vars.animationSpeed / 1000 + "s ease", "zIndex": 1 }).eq(slider.currentSlide).css({ "opacity": 1, "zIndex": 2 });
}
}
// SMOOTH HEIGHT:
if (vars.smoothHeight) methods.smoothHeight();
}
// !CAROUSEL:
// CANDIDATE: active slide
if (!carousel) slider.slides.removeClass(namespace + "active-slide").eq(slider.currentSlide).addClass(namespace + "active-slide");
}
slider.doMath = function () {
var slide = slider.slides.first(),
slideMargin = vars.itemMargin,
minItems = vars.minItems,
maxItems = vars.maxItems;
slider.w = slider.width();
slider.h = slide.height();
slider.boxPadding = slide.outerWidth() - slide.width();
// CAROUSEL:
if (carousel) {
slider.itemT = vars.itemWidth + slideMargin;
slider.minW = (minItems) ? minItems * slider.itemT : slider.w;
slider.maxW = (maxItems) ? maxItems * slider.itemT : slider.w;
slider.itemW = (slider.minW > slider.w) ? (slider.w - (slideMargin * minItems)) / minItems :
(slider.maxW < slider.w) ? (slider.w - (slideMargin * maxItems)) / maxItems :
(vars.itemWidth > slider.w) ? slider.w : vars.itemWidth;
slider.visible = Math.floor(slider.w / (slider.itemW + slideMargin));
slider.move = (vars.move > 0 && vars.move < slider.visible) ? vars.move : slider.visible;
slider.pagingCount = Math.ceil(((slider.count - slider.visible) / slider.move) + 1);
slider.last = slider.pagingCount - 1;
slider.limit = (slider.pagingCount === 1) ? 0 :
(vars.itemWidth > slider.w) ? ((slider.itemW + (slideMargin * 2)) * slider.count) - slider.w - slideMargin : ((slider.itemW + slideMargin) * slider.count) - slider.w - slideMargin;
} else {
slider.itemW = slider.w;
slider.pagingCount = slider.count;
slider.last = slider.count - 1;
}
slider.computedW = slider.itemW - slider.boxPadding;
}
slider.update = function (pos, action) {
slider.doMath();
// update currentSlide and slider.animatingTo if necessary
if (!carousel) {
if (pos < slider.currentSlide) {
slider.currentSlide += 1;
} else if (pos <= slider.currentSlide && pos !== 0) {
slider.currentSlide -= 1;
}
slider.animatingTo = slider.currentSlide;
}
// update controlNav
if (vars.controlNav && !slider.manualControls) {
if ((action === "add" && !carousel) || slider.pagingCount > slider.controlNav.length) {
methods.controlNav.update("add");
} else if ((action === "remove" && !carousel) || slider.pagingCount < slider.controlNav.length) {
if (carousel && slider.currentSlide > slider.last) {
slider.currentSlide -= 1;
slider.animatingTo -= 1;
}
methods.controlNav.update("remove", slider.last);
}
}
// update directionNav
if (vars.directionNav) methods.directionNav.update();
}
slider.addSlide = function (obj, pos) {
var $obj = $(obj);
slider.count += 1;
slider.last = slider.count - 1;
// append new slide
if (vertical && reverse) {
(pos !== undefined) ? slider.slides.eq(slider.count - pos).after($obj) : slider.container.prepend($obj);
} else {
(pos !== undefined) ? slider.slides.eq(pos).before($obj) : slider.container.append($obj);
}
// update currentSlide, animatingTo, controlNav, and directionNav
slider.update(pos, "add");
// update slider.slides
slider.slides = $(vars.selector + ':not(.clone)', slider);
// re-setup the slider to accomdate new slide
slider.setup();
//FlexSlider: added() Callback
vars.added(slider);
}
slider.removeSlide = function (obj) {
var pos = (isNaN(obj)) ? slider.slides.index($(obj)) : obj;
// update count
slider.count -= 1;
slider.last = slider.count - 1;
// remove slide
if (isNaN(obj)) {
$(obj, slider.slides).remove();
} else {
(vertical && reverse) ? slider.slides.eq(slider.last).remove() : slider.slides.eq(obj).remove();
}
// update currentSlide, animatingTo, controlNav, and directionNav
slider.doMath();
slider.update(pos, "remove");
// update slider.slides
slider.slides = $(vars.selector + ':not(.clone)', slider);
// re-setup the slider to accomdate new slide
slider.setup();
// FlexSlider: removed() Callback
vars.removed(slider);
}
//FlexSlider: Initialize
methods.init();
}
//FlexSlider: Default Settings
$.flexslider.defaults = {
namespace: "flex-", //{NEW} String: Prefix string attached to the class of every element generated by the plugin
selector: ".slides > li", //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril
animation: "fade", //String: Select your animation type, "fade" or "slide"
easing: "swing", //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported!
direction: "horizontal", //String: Select the sliding direction, "horizontal" or "vertical"
reverse: false, //{NEW} Boolean: Reverse the animation direction
animationLoop: true, //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
smoothHeight: false, //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode
startAt: 0, //Integer: The slide that the slider should start on. Array notation (0 = first slide)
slideshow: true, //Boolean: Animate slider automatically
slideshowSpeed: 7000, //Integer: Set the speed of the slideshow cycling, in milliseconds
animationSpeed: 600, //Integer: Set the speed of animations, in milliseconds
initDelay: 0, //{NEW} Integer: Set an initialization delay, in milliseconds
randomize: false, //Boolean: Randomize slide order
// Usability features
pauseOnAction: true, //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
pauseOnHover: false, //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
useCSS: true, //{NEW} Boolean: Slider will use CSS3 transitions if available
touch: true, //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices
video: false, //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches
// Primary Controls
controlNav: true, //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
directionNav: true, //Boolean: Create navigation for previous/next navigation? (true/false)
prevText: "Previous", //String: Set the text for the "previous" directionNav item
nextText: "Next", //String: Set the text for the "next" directionNav item
// Secondary Navigation
keyboard: true, //Boolean: Allow slider navigating via keyboard left/right keys
multipleKeyboard: false, //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present.
mousewheel: false, //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel
pausePlay: false, //Boolean: Create pause/play dynamic element
pauseText: "Pause", //String: Set the text for the "pause" pausePlay item
playText: "Play", //String: Set the text for the "play" pausePlay item
// Special properties
controlsContainer: "", //{UPDATED} jQuery Object/Selector: Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be $(".flexslider-container"). Property is ignored if given element is not found.
manualControls: "", //{UPDATED} jQuery Object/Selector: Declare custom control navigation. Examples would be $(".flex-control-nav li") or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
sync: "", //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care.
asNavFor: "", //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider
// Carousel Options
itemWidth: 0, //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding.
itemMargin: 0, //{NEW} Integer: Margin between carousel items.
minItems: 0, //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this.
maxItems: 0, //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit.
move: 0, //{NEW} Integer: Number of carousel items that should move on animation. If 0, slider will move all visible items.
// Callback API
start: function () { }, //Callback: function(slider) - Fires when the slider loads the first slide
before: function () { }, //Callback: function(slider) - Fires asynchronously with each slider animation
after: function () { }, //Callback: function(slider) - Fires after each slider animation completes
end: function () { }, //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
added: function () { }, //{NEW} Callback: function(slider) - Fires after a slide is added
removed: function () { } //{NEW} Callback: function(slider) - Fires after a slide is removed
}
//FlexSlider: Plugin Function
$.fn.flexslider = function (options) {
if (options === undefined) options = {};
if (typeof options === "object") {
return this.each(function () {
var $this = $(this),
selector = (options.selector) ? options.selector : ".slides > li",
$slides = $this.find(selector);
if ($slides.length === 1) {
$slides.fadeIn(400);
if (options.start) options.start($this);
} else if ($this.data('flexslider') == undefined) {
new $.flexslider(this, options);
}
});
} else {
// Helper strings to quickly perform functions on the slider
var $slider = $(this).data('flexslider');
switch (options) {
case "play": $slider.play(); break;
case "pause": $slider.pause(); break;
case "next": $slider.flexAnimate($slider.getTarget("next"), true); break;
case "prev":
case "previous": $slider.flexAnimate($slider.getTarget("prev"), true); break;
default: if (typeof options === "number") $slider.flexAnimate(options, true);
}
}
}
})(jQuery); | JavaScript |
/*
Lightbox v2.5
by Lokesh Dhakar - http://www.lokeshdhakar.com
For more information, visit:
http://lokeshdhakar.com/projects/lightbox2/
Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
- free for use in both personal and commercial projects
- attribution requires leaving author name, author link, and the license info intact
Thanks
- Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
- Artemy Tregubenko (arty.name) for cleanup and help in updating to latest proto-aculous in v2.05.
Table of Contents
=================
LightboxOptions
Lightbox
- constructor
- init
- enable
- build
- start
- changeImage
- sizeContainer
- showImage
- updateNav
- updateDetails
- preloadNeigbhoringImages
- enableKeyboardNav
- disableKeyboardNav
- keyboardAction
- end
options = new LightboxOptions
lightbox = new Lightbox options
*/
(function() {
var Lightbox, LightboxOptions;
LightboxOptions = (function() {
function LightboxOptions() {
this.fileLoadingImage = '/Content/Images/LightBox/loading.gif';
this.fileCloseImage = '/Content/Images/LightBox/close.png';
this.resizeDuration = 700;
this.fadeDuration = 500;
this.labelImage = "Image";
this.labelOf = "of";
}
return LightboxOptions;
})();
Lightbox = (function() {
function Lightbox(options) {
this.options = options;
this.album = [];
this.currentImageIndex = void 0;
this.init();
}
Lightbox.prototype.init = function() {
this.enable();
return this.build();
};
Lightbox.prototype.enable = function() {
var _this = this;
return $('a[rel^=lightbox], area[rel^=lightbox]').on('click', function(e) {
_this.start($(e.currentTarget));
return false;
});
};
Lightbox.prototype.build = function() {
var $lightbox,
_this = this;
$("<div>", {
id: 'lightboxOverlay'
}).after($('<div/>', {
id: 'lightbox'
}).append($('<div/>', {
"class": 'lb-outerContainer'
}).append($('<div/>', {
"class": 'lb-container'
}).append($('<img/>', {
"class": 'lb-image'
}), $('<div/>', {
"class": 'lb-nav'
}).append($('<a/>', {
"class": 'lb-prev'
}), $('<a/>', {
"class": 'lb-next'
})), $('<div/>', {
"class": 'lb-loader'
}).append($('<a/>', {
"class": 'lb-cancel'
}).append($('<img/>', {
src: this.options.fileLoadingImage
}))))), $('<div/>', {
"class": 'lb-dataContainer'
}).append($('<div/>', {
"class": 'lb-data'
}).append($('<div/>', {
"class": 'lb-details'
}).append($('<span/>', {
"class": 'lb-caption'
}), $('<span/>', {
"class": 'lb-number'
})), $('<div/>', {
"class": 'lb-closeContainer'
}).append($('<a/>', {
"class": 'lb-close'
}).append($('<img/>', {
src: this.options.fileCloseImage
}))))))).appendTo($('body'));
$('#lightboxOverlay').hide().on('click', function(e) {
_this.end();
return false;
});
$lightbox = $('#lightbox');
$lightbox.hide().on('click', function(e) {
if ($(e.target).attr('id') === 'lightbox') _this.end();
return false;
});
$lightbox.find('.lb-outerContainer').on('click', function(e) {
if ($(e.target).attr('id') === 'lightbox') _this.end();
return false;
});
$lightbox.find('.lb-prev').on('click', function(e) {
_this.changeImage(_this.currentImageIndex - 1);
return false;
});
$lightbox.find('.lb-next').on('click', function(e) {
_this.changeImage(_this.currentImageIndex + 1);
return false;
});
$lightbox.find('.lb-loader, .lb-close').on('click', function(e) {
_this.end();
return false;
});
};
Lightbox.prototype.start = function($link) {
var $lightbox, $window, a, i, imageNumber, left, top, _len, _ref;
$(window).on("resize", this.sizeOverlay);
$('select, object, embed').css({
visibility: "hidden"
});
$('#lightboxOverlay').width($(document).width()).height($(document).height()).fadeIn(this.options.fadeDuration);
this.album = [];
imageNumber = 0;
if ($link.attr('rel') === 'lightbox') {
this.album.push({
link: $link.attr('href'),
title: $link.attr('title')
});
} else {
_ref = $($link.prop("tagName") + '[rel="' + $link.attr('rel') + '"]');
for (i = 0, _len = _ref.length; i < _len; i++) {
a = _ref[i];
this.album.push({
link: $(a).attr('href'),
title: $(a).attr('title')
});
if ($(a).attr('href') === $link.attr('href')) imageNumber = i;
}
}
$window = $(window);
top = $window.scrollTop() + $window.height() / 10;
left = $window.scrollLeft();
$lightbox = $('#lightbox');
$lightbox.css({
top: top + 'px',
left: left + 'px'
}).fadeIn(this.options.fadeDuration);
this.changeImage(imageNumber);
};
Lightbox.prototype.changeImage = function(imageNumber) {
var $image, $lightbox, preloader,
_this = this;
this.disableKeyboardNav();
$lightbox = $('#lightbox');
$image = $lightbox.find('.lb-image');
this.sizeOverlay();
$('#lightboxOverlay').fadeIn(this.options.fadeDuration);
$('.loader').fadeIn('slow');
$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
$lightbox.find('.lb-outerContainer').addClass('animating');
preloader = new Image;
preloader.onload = function() {
$image.attr('src', _this.album[_this.currentImageIndex].link);
$image.width = preloader.width;
$image.height = preloader.height;
return _this.sizeContainer(preloader.width, preloader.height);
};
preloader.src = this.album[imageNumber].link;
this.currentImageIndex = imageNumber;
};
Lightbox.prototype.sizeOverlay = function() {
return $('#lightboxOverlay').width($(document).width()).height($(document).height());
};
Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
var $container, $lightbox, $outerContainer, containerBottomPadding, containerLeftPadding, containerRightPadding, containerTopPadding, newHeight, newWidth, oldHeight, oldWidth,
_this = this;
$lightbox = $('#lightbox');
$outerContainer = $lightbox.find('.lb-outerContainer');
oldWidth = $outerContainer.outerWidth();
oldHeight = $outerContainer.outerHeight();
$container = $lightbox.find('.lb-container');
containerTopPadding = parseInt($container.css('padding-top'), 10);
containerRightPadding = parseInt($container.css('padding-right'), 10);
containerBottomPadding = parseInt($container.css('padding-bottom'), 10);
containerLeftPadding = parseInt($container.css('padding-left'), 10);
newWidth = imageWidth + containerLeftPadding + containerRightPadding;
newHeight = imageHeight + containerTopPadding + containerBottomPadding;
if (newWidth !== oldWidth && newHeight !== oldHeight) {
$outerContainer.animate({
width: newWidth,
height: newHeight
}, this.options.resizeDuration, 'swing');
} else if (newWidth !== oldWidth) {
$outerContainer.animate({
width: newWidth
}, this.options.resizeDuration, 'swing');
} else if (newHeight !== oldHeight) {
$outerContainer.animate({
height: newHeight
}, this.options.resizeDuration, 'swing');
}
setTimeout(function() {
$lightbox.find('.lb-dataContainer').width(newWidth);
$lightbox.find('.lb-prevLink').height(newHeight);
$lightbox.find('.lb-nextLink').height(newHeight);
_this.showImage();
}, this.options.resizeDuration);
};
Lightbox.prototype.showImage = function() {
var $lightbox;
$lightbox = $('#lightbox');
$lightbox.find('.lb-loader').hide();
$lightbox.find('.lb-image').fadeIn('slow');
this.updateNav();
this.updateDetails();
this.preloadNeighboringImages();
this.enableKeyboardNav();
};
Lightbox.prototype.updateNav = function() {
var $lightbox;
$lightbox = $('#lightbox');
$lightbox.find('.lb-nav').show();
if (this.currentImageIndex > 0) $lightbox.find('.lb-prev').show();
if (this.currentImageIndex < this.album.length - 1) {
$lightbox.find('.lb-next').show();
}
};
Lightbox.prototype.updateDetails = function() {
var $lightbox,
_this = this;
$lightbox = $('#lightbox');
console.log(this.album[this.currentImageIndex].title !== "");
console.log(typeof this.album[this.currentImageIndex].title !== 'undefined');
if (typeof this.album[this.currentImageIndex].title !== 'undefined' && this.album[this.currentImageIndex].title !== "") {
$lightbox.find('.lb-caption').html(this.album[this.currentImageIndex].title).fadeIn('fast');
}
if (this.album.length > 1) {
$lightbox.find('.lb-number').html(this.options.labelImage + ' ' + (this.currentImageIndex + 1) + ' ' + this.options.labelOf + ' ' + this.album.length).fadeIn('fast');
} else {
$lightbox.find('.lb-number').hide();
}
$lightbox.find('.lb-outerContainer').removeClass('animating');
$lightbox.find('.lb-dataContainer').fadeIn(this.resizeDuration, function() {
return _this.sizeOverlay();
});
};
Lightbox.prototype.preloadNeighboringImages = function() {
var preloadNext, preloadPrev;
if (this.album.length > this.currentImageIndex + 1) {
preloadNext = new Image;
preloadNext.src = this.album[this.currentImageIndex + 1].link;
}
if (this.currentImageIndex > 0) {
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, KEYCODE_LEFTARROW, KEYCODE_RIGHTARROW, key, keycode;
KEYCODE_ESC = 27;
KEYCODE_LEFTARROW = 37;
KEYCODE_RIGHTARROW = 39;
keycode = event.keyCode;
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 (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
if (this.currentImageIndex !== this.album.length - 1) {
this.changeImage(this.currentImageIndex + 1);
}
}
};
Lightbox.prototype.end = function() {
this.disableKeyboardNav();
$(window).off("resize", this.sizeOverlay);
$('#lightbox').fadeOut(this.options.fadeDuration);
$('#lightboxOverlay').fadeOut(this.options.fadeDuration);
return $('select, object, embed').css({
visibility: "visible"
});
};
return Lightbox;
})();
$(function() {
var lightbox, options;
options = new LightboxOptions;
return lightbox = new Lightbox(options);
});
}).call(this);
| JavaScript |
(function () {
//var host = "192.168.0.100",
var host = window.location.hostname,
// Encapsulation of the vlc plugin
Stream = function (object,type,callbacks) {
var restarting = false, starting = false, error = false, restartTimer, startTimer,
// Register an event listener
registerEvent = function (object, event, handler) {
if (object.attachEvent) {
object.attachEvent (event, handler);
} else if (object.addEventListener) {
object.addEventListener (event, handler, false);
} else {
object["on" + event] = handler;
}
},
// Indicates if the camera/microphone is currently being used
inUse = function (callback) {
$.post('request.json',JSON.stringify({'action':'state'}),function (json) {
if (type==='audio') callback(json.state.microphoneInUse==='true');
else callback(json.state.cameraInUse==='true');
});
};
registerEvent(object,'MediaPlayerEncounteredError',function (event) {
error = true;
if (restarting) {
clearInterval(restartTimer);
restarting = false;
}
if (starting) {
clearInterval(startTimer);
starting = false;
}
callbacks.onError(type);
});
return {
restart: function () {
if (!restarting) {
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
// We wait 2 secs and restart the stream
restarting = true;
restartTimer = setInterval(function () {
inUse(function (b) {
if (!b) {
this.start();
clearInterval(restartTimer);
}
}.bind(this));
}.bind(this),1000);
}
},
start: function () {
if (!object.playlist.isPlaying) {
starting = true;
error = false;
startTimer = setInterval(function () {
if (object.playlist.isPlaying) {
restarting = false;
starting = false;
clearInterval(startTimer);
}
},300);
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
var item = generateURI(host,type);
object.playlist.add(type==='video'?item.uriv:item.uria,'',item.params);
object.playlist.playItem(0);
}
},
stop: function () {
error = false;
if (restarting) {
clearInterval(restartTimer);
restarting = false;
}
if (starting) {
clearInterval(startTimer);
starting = false;
}
if (object.playlist.isPlaying) {
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
}
},
getState: function() {
if (restarting) return 'restarting';
else if (starting) return 'starting'
else if (object.playlist.isPlaying) return 'streaming';
else if (error) return 'error';
else return 'idle';
},
isStreaming: function () {
return object.playlist.isPlaying;
}
}
},
generateURI = function (h,type) {
var audioEncoder, videoEncoder, cache, rotation, flash, camera, res;
// Audio conf
if ($('#audioEnabled').attr('checked')) {
audioEncoder = $('#audioEncoder').val()=='AMR-NB'?'amr':'aac';
} else {
audioEncoder = "nosound";
}
// Resolution
res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val());
// Video conf
if ($('#videoEnabled').attr('checked')) {
videoEncoder = ($('#videoEncoder').val()=='H.263'?'h263':'h264')+'='+
/[0-9]+/.exec($('#bitrate').val())[0]+'-'+
/[0-9]+/.exec($('#framerate').val())[0]+'-';
videoEncoder += res[1]+'-'+res[2];
} else {
videoEncoder = "novideo";
}
// Flash
if ($('#flashEnabled').val()==='1') flash = 'on'; else flash = 'off';
// Camera
camera = $('#cameraId').val();
// Params
cache = /[0-9]+/.exec($('#cache').val())[0];
return {
uria:"rtsp://"+h+":"+8086+"?"+audioEncoder,
uriv:"rtsp://"+h+":"+8086+"?"+videoEncoder+'&flash='+flash+'&camera='+camera,
params:[':network-caching='+cache]
}
},
testActivxAndMozillaPlugin = function () {
// TODO: console.log(object.VersionInfo);
// Test if the activx plugin is installed
if (typeof $('#xvlcv')[0].playlist != "undefined") {
return 1;
} else {
$('#xvlcv').css('display','none');
$('#vlcv').css('display','block');
}
// Test if the mozilla plugin is installed
if (typeof $('#vlca')[0].playlist == "undefined") {
// Plugin not detected, alert user !
$('#glass').fadeIn(1000);
$('#error-noplugin').fadeIn(1000);
return 0;
} else {
return 2;
}
},
loadSoundsList = function (sounds) {
var list = $('#soundslist'), category, name;
sounds.forEach(function (e) {
category = e.match(/([a-z0-9]+)_/)[1];
name = e.match(/[a-z0-9]+_([a-z0-9_]+)/)[1];
if ($('.category.'+category).length==0) list.append(
'<div class="category '+category+'"><span class="category-name">'+category+'</span><div class="category-separator"></div></div>'
);
$('.category.'+category).append('<div class="sound" id="'+e+'"><a>'+name.replace(/_/g,' ')+'</a></div>');
});
},
testScreenState = function (screenState) {
if (screenState==0) {
$('#error-screenoff').fadeIn(1000);
$('#glass').fadeIn(1000);
}
},
updateTooltip = function (title) {
$('#tooltip>div').hide();
$('#tooltip #'+title).show();
},
videoStream, videoPlugin, audioStream, oldVideoState = 'idle',oldAudioState = 'idle', lastError = 0,
updateStatus = function () {
var status = $('#status'), button = $('#connect>div>h1'), cover = $('#vlc-container #upper-layer'), error;
if (videoStream.getState()===oldVideoState && audioStream.getState()===oldAudioState && lastError===0) return;
// STATUS
if (videoStream.getState()==='starting' || videoStream.getState()==='restarting' ||
audioStream.getState()==='starting' || audioStream.getState()==='restarting') {
status.html(__('Trying to connect...'))
} else {
if (!videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('NOT CONNECTED'));
else if (videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('Streaming video but not audio'));
else if (!videoStream.isStreaming() && audioStream.isStreaming()) status.html(__('Streaming audio but not video'));
else status.html(__('Streaming audio and video'));
}
// BUTTON
if ((videoStream.getState()==='idle' || videoStream.getState()==='error') &&
(audioStream.getState()==='idle' || audioStream.getState()==='error')) {
button.html(__('Connect !!'));
} else button.text(__('Disconnect ?!'));
// WINDOW
if (lastError!==0) {
videoPlugin.css('visibility','hidden');
if (lastError===1) error = __('Retrieving error message...');
else if (lastError===2) error = __('Connection timed out !');
else if (lastError===0 || lastError===undefined) error = "";
else error = lastError;
lastError = 0;
cover.html('<div id="wrapper"><h1>'+__('An error occurred')+' :(</h1><p>'+error+'</p></div>');
} else if (videoStream.getState()==='restarting' || audioStream.getState()==='restarting') {
videoPlugin.css('visibility','hidden');
cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('UPDATING SETTINGS')+'</h1></div>').show();
} else if (videoStream.getState()==='streaming') {
videoPlugin.css('visibility','inherit');
cover.hide();
}
if (videoStream.getState()==='idle') {
if (audioStream.getState()==='streaming') {
videoPlugin.css('visibility','hidden');
cover.html('').css('background','url("images/speaker.png") center no-repeat').show();
} else if (audioStream.getState()==='idle') {
videoPlugin.css('visibility','hidden');
cover.html('').css('background','url("images/eye.png") center no-repeat').show();
}
}
oldVideoState = videoStream.getState();
oldAudioState = audioStream.getState();
},
// Called when an error occurs in spydroid
onError = function (type) {
lastError = 1;
$.ajax({type: 'POST', url: 'request.json',data: "[{'action':'state'},{'action':'clear'}]",
success: function (json) {
lastError = json.state.lastError;
try {
if (json.lastStackTrace.match("RuntimeException.+MediaStream.start")) {
// If a start failed happened we display additional information
lastError += "<br /><br />"+__("This generally happens when you are trying to use settings that are not supported by your phone.");
$("#quality").click();
}
} catch (ignore) {}
if (json.activityPaused==='0' && type==='video') {
testScreenState(0);
}
},
error: function () {
lastError = 2;
},
timeout: 1500
});
if (videoStream.getState()!=='error') videoStream.stop();
if (audioStream.getState()!=='error') audioStream.stop();
},
fetchSettings = function (config) {
$('#resolution,#framerate,#bitrate,#audioEncoder,#videoEncoder').children().each(function (c) {
if ($(this).val()===config.videoResolution ||
$(this).val()===config.videoFramerate ||
$(this).val()===config.videoBitrate ||
$(this).val()===config.audioEncoder ||
$(this).val()===config.videoEncoder ) {
$(this).parent().children().removeAttr('selected');
$(this).attr('selected','true');
}
});
if (config.streamAudio===false) $('#audioEnabled').removeAttr('checked');
if (config.streamVideo===false) $('#videoEnabled').removeAttr('checked');
},
saveSettings = function () {
var res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val());
var videoQuality = /[0-9]+/.exec($('#bitrate').val())[0]+'-'+/[0-9]+/.exec($('#framerate').val())[0]+'-'+res[1]+'-'+res[2];
var settings = {
'stream_video': $('#videoEnabled').attr('checked')=='checked',
'stream_audio': $('#audioEnabled').attr('checked')=='checked',
'video_encoder': $('#videoEncoder').val(),
'audio_encoder': $('#audioEncoder').val(),
'video_quality': videoQuality
};
$.post('request.json',JSON.stringify({'action':'set','settings':settings}));
},
// Disable input for one sec to prevent user from flooding the RTSP server by clicking around too quickly
disableAndEnable = function (input) {
input.attr('disabled','true');
setTimeout(function () {
input.removeAttr('disabled');
},1000);
},
setupEvents = function () {
var audioPlugin, test,
cover = $('#vlc-container #upper-layer'),
status = $('#status'),
button = $('#connect>div>h1');
$('.popup').each(function () {
$(this).css({'top':($(window).height()-$(this).height())/2,'left':($(window).width()-$(this).width())/2});
});
$('.popup #close').click(function (){
$('#glass').fadeOut();
$('.popup').fadeOut();
});
test = testActivxAndMozillaPlugin();
if (test===1) {
// Activx plugin detected
videoPlugin = $('#xvlcv');
audioPlugin = $('#xvlca');
} else if (test===2) {
// Mozilla plugin detected
videoPlugin = $('#vlcv');
audioPlugin = $('#vlca');
} else {
// No plugin installed, spydroid probably won't work
// We assume the Mozilla plugin is installed, just in case :/
videoPlugin = $('#vlcv');
audioPlugin = $('#vlca');
}
videoStream = Stream(videoPlugin[0],'video',{onError:function (type) {
onError(type);
}});
audioStream = Stream(audioPlugin[0],'audio',{onError:function (type) {
onError(type);
}});
setInterval(function () {updateStatus();},400);
$('#connect').click(function () {
if ($(this).attr('disabled')!==undefined) return;
disableAndEnable($(this));
if ((videoStream.getState()!=='idle' && videoStream.getState()!=='error') ||
(audioStream.getState()!=='idle' && audioStream.getState()!=='error')) {
videoStream.stop();
audioStream.stop();
} else {
if (!$('#videoEnabled').attr('checked') && !$('#audioEnabled').attr('checked')) return;
videoPlugin.css('visibility','hidden');
cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('CONNECTION')+'</h1></div>').show();
if ($('#videoEnabled').attr('checked')) videoStream.start(); else videoStream.stop();
if ($('#audioEnabled').attr('checked')) audioStream.start();
updateStatus();
}
});
$('#torch-button').click(function () {
if ($(this).attr('disabled')!==undefined || videoStream.getState()==='starting') return;
disableAndEnable($(this));
if ($('#flashEnabled').val()=='0') {
$('#flashEnabled').val('1');
$(this).addClass('torch-on');
} else {
$('#flashEnabled').val('0');
$(this).removeClass('torch-on');
}
if (videoStream.getState()==='streaming') videoStream.restart();
});
$('.camera-not-selected').live('click',function () {
if ($(this).attr('disabled')!==undefined || videoStream.getState()==='starting') return;
$('#cameras span').addClass('camera-not-selected');
$(this).removeClass('camera-not-selected');
disableAndEnable($('.camera-not-selected'));
$('#cameraId').val($(this).attr('data-id'));
if (videoStream.getState()==='streaming') videoStream.restart();
})
$('.audio select,').change(function () {
if (audioStream.isStreaming()) {
audioStream.restart();
}
});
$('.audio input').change(function () {
if (audioStream.isStreaming() || videoStream.isStreaming()) {
if ($('#audioEnabled').attr('checked')) audioStream.restart(); else audioStream.stop();
disableAndEnable($(this));
}
});
$('.video select').change(function () {
if (videoStream.isStreaming()) {
videoStream.restart();
}
});
$('.video input').change(function () {
if (audioStream.isStreaming() || videoStream.isStreaming()) {
if ($('#videoEnabled').attr('checked')) videoStream.restart(); else videoStream.stop();
disableAndEnable($(this));
}
});
$('.cache select').change(function () {
if (videoStream.isStreaming()) {
videoStream.restart();
}
if (audioStream.isStreaming()) {
audioStream.restart();
}
});
$('select,input').change(function () {
saveSettings();
});
$('.section').click(function () {
$('.section').removeClass('selected');
$(this).addClass('selected');
updateTooltip($(this).attr('id'));
});
$('.sound').live('click', function () {
$.post('request.json',JSON.stringify({'action':'play','name':$(this).attr('id')}));
});
$('#fullscreen').click(function () {
videoPlugin[0].video.toggleFullscreen();
});
$(document).keyup(function(e) {
if (e.keyCode == 27) {
videoPlugin[0].video.toggleFullscreen();
}
});
$('#hide-tooltip').click(function () {
$('body').width($('body').width() - $('#tooltip').width());
$('#tooltip').hide();
$('#need-help').show();
});
$('#tooltip').hide();
$('#need-help').show();
$('#need-help').click(function () {
$('body').width($('body').width() + $('#tooltip').width());
$('#tooltip').show();
$('#need-help').hide();
});
};
$(document).ready(function () {
$.post('request.json',"[{'action':'sounds'},{'action':'screen'},{'action':'get'}]", function (data) {
// Verify that the screen is not turned off
testScreenState(data.screen);
// Fetch the list of sounds available on the phone
loadSoundsList(data.sounds);
// Retrieve the configuration of Spydroid on the phone
fetchSettings(data.get);
});
// Translate the interface in the appropriate language
$('h1,h2,h3,span,p,a,em').translate();
// Bind DOM events to the js API
setupEvents();
});
}());
| JavaScript |
(function () {
var translations = {
en: {
1:"About",
2:"Return",
3:"Change quality settings",
4:"Toggle flash",
5:"Click on the torch to enable or disable the flash",
6:"Play a prerecorded sound",
7:"Connect !!",
8:"Disconnect ?!",
9:"STATUS",
10:"NOT CONNECTED",
11:"ERROR :(",
12:"CONNECTION",
13:"UPDATING SETTINGS",
14:"CONNECTED",
15:"Show some tips",
16:"Hide those tips",
17:"Those buttons will trigger sounds on your phone...",
18:"Use them to surprise your victim.",
19:"Or you could use this to surprise your victim !",
20:"This will simply toggle the led in front of you're phone, so that even in the deepest darkness, you will not be blind...",
21:"If the stream is choppy, try reducing the bitrate or increasing the cache size.",
22:"Try it instead of H.263 if video streaming is not working at all !",
23:"The H.264 compression algorithm is more efficient but may not work on your phone...",
24:"You need to install VLC first !",
25:"During the installation make sure to check the firefox plugin !",
26:"Close",
27:"You must leave the screen of your smartphone on !",
28:"Front facing camera",
29:"Back facing camera",
30:"Switch between cameras",
31:"Streaming video but not audio",
32:"Streaming audio but not video",
33:"Streaming audio and video",
34:"Trying to connect...",
35:"Stream sound",
36:"Stream video",
37:"Fullscreen",
38:"Encoder",
39:"Resolution",
40:"Cache size",
41:"This generally happens when you are trying to use settings that are not supported by your phone.",
42:"Retrieving error message...",
43:"An error occurred"
},
fr: {
1:"À propos",
2:"Retour",
3:"Changer la qualité du stream",
4:"Allumer/Éteindre le flash",
5:"Clique sur l'ampoule pour activer ou désactiver le flash",
6:"Jouer un son préenregistré",
7:"Connexion !!",
8:"Déconnecter ?!",
9:"STATUT",
10:"DÉCONNECTÉ",
11:"ERREUR :(",
12:"CONNEXION",
13:"M.A.J.",
14:"CONNECTÉ",
15:"Afficher l'aide",
16:"Masquer l'aide",
17:"Clique sur un de ces boutons pour lancer un son préenregistré sur ton smartphone !",
18:"Utilise les pour surprendre ta victime !!",
19:"Ça peut aussi servir à surprendre ta victime !",
20:"Clique sur l'ampoule pour allumer le flash de ton smartphone",
21:"Si le stream est saccadé essaye de réduire le bitrate ou d'augmenter la taille du cache.",
22:"Essaye le à la place du H.263 si le streaming de la vidéo ne marche pas du tout !",
23:"Le H.264 est un algo plus efficace pour compresser la vidéo mais il a moins de chance de marcher sur ton smartphone...",
24:"Tu dois d'abord installer VLC !!",
25:"Pendant l'installation laisse cochée l'option plugin mozilla !",
26:"Fermer",
27:"Tu dois laisser l'écran de ton smartphone allumé",
28:"Caméra face avant",
29:"Caméra face arrière",
30:"Choisir la caméra",
31:"Streaming de la vidéo",
32:"Streaming de l'audio",
33:"Streaming de l'audio et de la vidéo",
34:"Connexion en cours...",
35:"Streaming du son",
36:"Streaming de la vidéo",
37:"Plein écran",
38:"Encodeur",
39:"Résolution",
40:"Taille cache",
41:"En général, cette erreur se produit quand les paramètres sélectionnés ne sont pas compatibles avec le smartphone.",
42:"Attente du message d'erreur...",
43:"Une erreur s'est produite"
},
ru: {
1:"Спасибо",
2:"Вернуться",
3:"Изменить настройки качества",
4:"Переключатель вспышки",
5:"Нажмите здесь, чтобы включить или выключить вспышку",
6:"Проиграть звук на телефоне",
7:"Подключиться !!",
8:"Отключиться ?!",
9:"СОСТОЯНИЕ",
10:"НЕТ ПОДКЛЮЧЕНИЯ",
11:"ОШИБКА :(",
12:"ПОДКЛЮЧЕНИЕ",
13:"ОБНОВЛЕНИЕ НАСТРОЕК",
14:"ПОДКЛЮЧЕНО",
15:"Показать поясняющие советы",
16:"Спрятать эти советы",
17:"Эти кнопки будут проигрывать звуки на вашем телефоне...",
18:"Используйте их, чтобы удивить вашу жертву.",
19:"Или вы можете удивить свою жертву!",
20:"Это переключатель режима подсветки на передней части вашего телефона, так что даже в самой кромешной тьме, вы не будете слепы ...",
21:"Если поток прерывается, попробуйте уменьшить битрейт или увеличив размер кэша.",
22:"Если топоковое видео не работает совсем, попробуйте сжатие Н.263",
23:"Алгоритм сжатия H.264, является более эффективным, но может не работать на вашем телефоне ...",
24:"Вначале Вам необходимо установить VLC !",
25:"При установке убедитесь в наличии плагина для firefox !",
26:"Закрыть",
27:"Вам надо отойти от вашего смартфона.",
28:"Фронтальная камера",
29:"Камера с обратной стороны",
30:"Переключиться на другую камеру",
31:"Передача видео без звука",
32:"Передача звука без видео",
33:"Передача звука и видео",
34:"Пытаемся подключится",
35:"Аудио поток",
36:"Видео поток",
37:"На весь экран",
38:"Кодек",
39:"Разрешение",
40:"Размер кеша",
41:"Как правило, это происходит, когда вы пытаетесь использовать настройки, не поддерживаемые вашим телефоном.",
42:"Получение сообщения об ошибке ..."
},
de : {
1:"Apropos",
2:"Zurück",
3:"Qualität des Streams verändern",
4:"Fotolicht ein/aus",
5:"Klick die Glühbirne an, um das Fotolicht einzuschalten oder azufallen",
6:"Vereinbarten Ton spielen",
7:"Verbindung !!",
8:"Verbinden ?!",
9:"STATUS",
10:"NICHT VERBUNDEN",
11:"FEHLER :(",
12:"VERBINDUNG",
13:"UPDATE",
14:"VERBUNDEN",
15:"Hilfe anzeigen",
16:"Hilfe ausblenden",
17:"Klick diese Tasten an, um Töne auf deinem Smartphone spielen zu lassen !",
18:"Benutz sie, um deine Opfer zu überraschen !!",
19:"Das kann auch dein Opfer erschrecken !",
20:"Es wird die LED hinter deinem Handy anmachen, damit du nie blind bleibst, auch im tiefsten Dunkeln",
21:"Wenn das Stream ruckartig ist, versuch mal die Bitrate zu reduzieren oder die Größe vom Cache zu steigern.",
22:"Probier es ansatt H.263, wenn das Videostream überhaupt nicht funktionert !",
23:"Der H.264 Kompressionalgorithmus ist effizienter aber er wird auf deinem Handy vielleicht nicht funktionieren...",
24:"Du musst zuerst VLC installieren !!",
25:"Während der Installation, prüfe dass das Firefox plugin abgecheckt ist!",
26:"Zumachen",
27:"Du musst den Bildschirm deines Smartphones eingeschaltet lassen !",
28:"Frontkamera",
29:"Rückkamera",
30:"Kamera auswählen",
31:"Videostreaming",
32:"Audiostreaming",
33:"Video- und Audiostreaming",
34:"Ausstehende Verbindung...",
35:"Soundstreaming",
36:"Videostreaming",
37:"Ganzer Bildschirm",
38:"Encoder",
39:"Auflösung",
40:"Cachegröße",
41:"Dieser Fehler gescheht überhaupt, wenn die gewählten Einstellungen mit dem Smartphone nicht kompatibel sind.",
42:"Es wird auf die Fehlermeldung gewartet...",
43:"Ein Fehler ist geschehen..."
}
};
var lang = window.navigator.userLanguage || window.navigator.language;
//var lang = "ru";
var __ = function (text) {
var x,y=0,z;
if (lang.match(/en/i)!=null) return text;
for (x in translations) {
if (lang.match(new RegExp(x,"i"))!=null) {
for (z in translations.en) {
if (text==translations.en[z]) {
y = z;
break;
}
}
return translations[x][y]==undefined?text:translations[x][y];
}
}
return text;
};
$.fn.extend({
translate: function () {
return this.each(function () {
$(this).html(__($(this).html()));
});
}
});
window.__ = __;
}());
| JavaScript |
document.createElement('header');
document.createElement('nav');
document.createElement('section');
document.createElement('article');
document.createElement('aside');
document.createElement('footer');
document.createElement('hgroup');
$(document).ready(function () {
$('.section-content,#status-container').addClass('ie8-background');
$('.category-separator').hide();
}); | JavaScript |
//Menu
$(document).ready(function() {
$("ul.sf-menu").supersubs({
minWidth: 12, // minimum width of sub-menus in em units
maxWidth: 27, // maximum width of sub-menus in em units
extraWidth: 1 // extra width can ensure lines don't sometimes turn over
// due to slight rounding differences and font-family
}).superfish(); // call supersubs first, then superfish, so that subs are
// not display:none when measuring. Call before initialising
// containing tabs for same reason.
});
// Change language
function changeLanguage(value, to) {
var url = window.location.href;
if (url.indexOf('/' + value) > 0) {
url = url.replace('/' + value, '/' + to);
}
else {
url = url + to + '/';
}
window.location = url;
}
//// 3 - MESSAGE BOX FADING SCRIPTS ---------------------------------------------------------------------
$(document).ready(function() {
$(".close-yellow").click(function() {
$("#message-yellow").fadeOut("slow");
});
$(".close-red").click(function() {
$("#message-red").fadeOut("slow");
});
$(".close-blue").click(function() {
$("#message-blue").fadeOut("slow");
});
$(".close-green").click(function() {
$("#message-green").fadeOut("slow");
});
});
// END ----------------------------- 3
// 1 - START DROPDOWN SLIDER SCRIPTS ------------------------------------------------------------------------
$(document).ready(function() {
$(".showhide-account").click(function() {
$(".account-content").slideToggle("fast");
$(this).toggleClass("active");
return false;
});
});
$(document).ready(function() {
$(".action-slider").click(function() {
$("#actions-box-slider").slideToggle("fast");
$(this).toggleClass("activated");
return false;
});
});
// END ----------------------------- 1
$(function() {
$.ajaxSetup({ cache: false });
$('#toggle-all').click(function() {
//
if ($(this).attr('class') != "toggle-checked") {
$('#mainform input[type=checkbox]').attr('checked', false);
}
//alert($(this).attr('class'));
$('#mainform input').checkBox();
$('#toggle-all').toggleClass('toggle-checked');
$('#mainform input[type=checkbox]').checkBox('toggle');
return false;
});
$('#mainform input:checkbox:not(#toggle-all)').click(function() {
$('#toggle-all').removeClass('toggle-checked');
});
/* Custom javascripts for listing pages
============================================================*/
//prompt for delete button
$('.remove-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
if (confirm("Confirm removed the selected records?")) {
window.location = this.href;
}
});
//prompt for reject button
$('.reject-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
if (confirm("Confirm reject the selected Post Property Request?")) {
window.location = this.href;
}
});
//prompt for approve button
$('.approve-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
if (confirm("Confirm approving the selected Post Property Request?")) {
window.location = this.href;
}
});
//bulk process action
$('.action-invoke').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
alert('Please select at least one item.');
return false;
} else {
//submit form
$(".list_item_form").attr("action",this.href);
$(".list_item_form").submit();
}
});
//Sort by process action
$('.action-sort').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//submit form
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
});
//bulk process action
$('.remove-sidecontent-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//submit form
$("#delete_sidecontent_hook").attr("action", this.href);
$("#delete_sidecontent_hook").submit();
});
//bulk process delete action
$('.action-invoke-removed').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
alert('Please select at least one item.');
return false;
} else {
if (confirm("Confirm removed the selected records?")) {
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
}
}
});
//bulk process reject post property request action
$('.action-invoke-rejected').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected[]']").serializeArray();
if (fields.length == 0) {
alert('Please select at least one item.');
return false;
} else {
if (confirm("Confirm reject the selected Post Property Request(s)?")) {
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
}
}
});
//bulk process reject post property request action
$('.action-invoke-approved').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected[]']").serializeArray();
if (fields.length == 0) {
alert('Please select at least one item.');
return false;
} else {
if (confirm("Confirm approve the selected Post Property Request(s)?")) {
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
}
}
});
});
//Tooltips -->
$(function() {
$('a.info-tooltip ').tooltip({
track: true,
delay: 0,
fixPNG: true,
showURL: false,
showBody: " - ",
top: -35,
left: 5
});
});
function htmlspecialchars(str) {
if (typeof (str) == "string") {
str = str.replace(/&/g, "&");
str = str.replace(/"/g, """);
str = str.replace(/'/g, "’s");
str = str.replace(/</g, "<");
str = str.replace(/>/g, ">");
}
return str;
}
//set up
//Pretty Loader/
//styled select box script version 1
$(document).ready(function() {
$('.styledselect').selectbox({ inputClass: "selectbox_styled" });
//
$('.styledselect_form_2').selectbox({ inputClass: "styledselect_form_2" });
//
$('.styledselect_pages').selectbox({ inputClass: "styledselect_pages" });
}); | JavaScript |
/**
* Really Simple Color Picker in jQuery
*
* Licensed under the MIT (MIT-LICENSE.txt) licenses.
*
* Copyright (c) 2008-2012
* Lakshan Perera (www.laktek.com) & Daniel Lacy (daniellacy.com)
*
* 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 ($) {
/**
* Create a couple private variables.
**/
var selectorOwner,
activePalette,
cItterate = 0,
templates = {
control : $('<div class="colorPicker-picker"> </div>'),
palette : $('<div id="colorPicker_palette" class="colorPicker-palette" />'),
swatch : $('<div class="colorPicker-swatch"> </div>'),
hexLabel: $('<label for="colorPicker_hex">Hex</label>'),
hexField: $('<input type="text" id="colorPicker_hex" />')
},
transparent = "transparent",
lastColor;
/**
* Create our colorPicker function
**/
$.fn.colorPicker = function (options) {
return this.each(function () {
// Setup time. Clone new elements from our templates, set some IDs, make shortcuts, jazzercise.
var element = $(this),
opts = $.extend({}, $.fn.colorPicker.defaults, options),
defaultColor = $.fn.colorPicker.toHex(
(element.val().length > 0) ? element.val() : opts.pickerDefault
),
newControl = templates.control.clone(),
newPalette = templates.palette.clone().attr('id', 'colorPicker_palette-' + cItterate),
newHexLabel = templates.hexLabel.clone(),
newHexField = templates.hexField.clone(),
paletteId = newPalette[0].id,
swatch;
/**
* Build a color palette.
**/
$.each(opts.colors, function (i) {
swatch = templates.swatch.clone();
if (opts.colors[i] === transparent) {
swatch.addClass(transparent).text('X');
$.fn.colorPicker.bindPalette(newHexField, swatch, transparent);
} else {
swatch.css("background-color", "#" + this);
$.fn.colorPicker.bindPalette(newHexField, swatch);
}
swatch.appendTo(newPalette);
});
newHexLabel.attr('for', 'colorPicker_hex-' + cItterate);
newHexField.attr({
'id' : 'colorPicker_hex-' + cItterate,
'value' : defaultColor
});
newHexField.bind("keydown", function (event) {
if (event.keyCode === 13) {
var hexColor = $.fn.colorPicker.toHex($(this).val());
$.fn.colorPicker.changeColor(hexColor ? hexColor : element.val());
}
if (event.keyCode === 27) {
$.fn.colorPicker.hidePalette();
}
});
newHexField.bind("keyup", function (event) {
var hexColor = $.fn.colorPicker.toHex($(event.target).val());
$.fn.colorPicker.previewColor(hexColor ? hexColor : element.val());
});
$('<div class="colorPicker_hexWrap" />').append(newHexLabel).appendTo(newPalette);
newPalette.find('.colorPicker_hexWrap').append(newHexField);
$("body").append(newPalette);
newPalette.hide();
/**
* Build replacement interface for original color input.
**/
newControl.css("background-color", defaultColor);
newControl.bind("click", function () {
if( element.is( ':not(:disabled)' ) ) {
$.fn.colorPicker.togglePalette($('#' + paletteId), $(this));
}
});
if( options && options.onColorChange ) {
newControl.data('onColorChange', options.onColorChange);
} else {
newControl.data('onColorChange', function() {} );
}
element.after(newControl);
element.bind("change", function () {
element.next(".colorPicker-picker").css(
"background-color", $.fn.colorPicker.toHex($(this).val())
);
});
// Hide the original input.
element.val(defaultColor).hide();
cItterate++;
});
};
/**
* Extend colorPicker with... all our functionality.
**/
$.extend(true, $.fn.colorPicker, {
/**
* Return a Hex color, convert an RGB value and return Hex, or return false.
*
* Inspired by http://code.google.com/p/jquery-color-utils
**/
toHex : function (color) {
// If we have a standard or shorthand Hex color, return that value.
if (color.match(/[0-9A-F]{6}|[0-9A-F]{3}$/i)) {
return (color.charAt(0) === "#") ? color : ("#" + color);
// Alternatively, check for RGB color, then convert and return it as Hex.
} else if (color.match(/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/)) {
var c = ([parseInt(RegExp.$1, 10), parseInt(RegExp.$2, 10), parseInt(RegExp.$3, 10)]),
pad = function (str) {
if (str.length < 2) {
for (var i = 0, len = 2 - str.length; i < len; i++) {
str = '0' + str;
}
}
return str;
};
if (c.length === 3) {
var r = pad(c[0].toString(16)),
g = pad(c[1].toString(16)),
b = pad(c[2].toString(16));
return '#' + r + g + b;
}
// Otherwise we wont do anything.
} else {
return false;
}
},
/**
* Check whether user clicked on the selector or owner.
**/
checkMouse : function (event, paletteId) {
var selector = activePalette,
selectorParent = $(event.target).parents("#" + selector.attr('id')).length;
if (event.target === $(selector)[0] || event.target === selectorOwner[0] || selectorParent > 0) {
return;
}
$.fn.colorPicker.hidePalette();
},
/**
* Hide the color palette modal.
**/
hidePalette : function () {
$(document).unbind("mousedown", $.fn.colorPicker.checkMouse);
$('.colorPicker-palette').hide();
},
/**
* Show the color palette modal.
**/
showPalette : function (palette) {
var hexColor = selectorOwner.prev("input").val();
palette.css({
top: selectorOwner.offset().top + (selectorOwner.outerHeight()),
left: selectorOwner.offset().left
});
$("#color_value").val(hexColor);
palette.show();
$(document).bind("mousedown", $.fn.colorPicker.checkMouse);
},
/**
* Toggle visibility of the colorPicker palette.
**/
togglePalette : function (palette, origin) {
// selectorOwner is the clicked .colorPicker-picker.
if (origin) {
selectorOwner = origin;
}
activePalette = palette;
if (activePalette.is(':visible')) {
$.fn.colorPicker.hidePalette();
} else {
$.fn.colorPicker.showPalette(palette);
}
},
/**
* Update the input with a newly selected color.
**/
changeColor : function (value) {
selectorOwner.css("background-color", value);
selectorOwner.prev("input").val(value).change();
$.fn.colorPicker.hidePalette();
selectorOwner.data('onColorChange').call(selectorOwner, $(selectorOwner).prev("input").attr("id"), value);
},
/**
* Preview the input with a newly selected color.
**/
previewColor : function (value) {
selectorOwner.css("background-color", value);
},
/**
* Bind events to the color palette swatches.
*/
bindPalette : function (paletteInput, element, color) {
color = color ? color : $.fn.colorPicker.toHex(element.css("background-color"));
element.bind({
click : function (ev) {
lastColor = color;
$.fn.colorPicker.changeColor(color);
},
mouseover : function (ev) {
lastColor = paletteInput.val();
$(this).css("border-color", "#598FEF");
paletteInput.val(color);
$.fn.colorPicker.previewColor(color);
},
mouseout : function (ev) {
$(this).css("border-color", "#000");
paletteInput.val(selectorOwner.css("background-color"));
paletteInput.val(lastColor);
$.fn.colorPicker.previewColor(lastColor);
}
});
}
});
/**
* Default colorPicker options.
*
* These are publibly available for global modification using a setting such as:
*
* $.fn.colorPicker.defaults.colors = ['151337', '111111']
*
* They can also be applied on a per-bound element basis like so:
*
* $('#element1').colorPicker({pickerDefault: 'efefef', transparency: true});
* $('#element2').colorPicker({pickerDefault: '333333', colors: ['333333', '111111']});
*
**/
$.fn.colorPicker.defaults = {
// colorPicker default selected color.
pickerDefault : "FFFFFF",
// Default color set.
colors : [
'000000', '993300', '333300', '000080', '333399', '333333', '800000', 'FF6600',
'808000', '008000', '008080', '0000FF', '666699', '808080', 'FF0000', 'FF9900',
'99CC00', '339966', '33CCCC', '3366FF', '800080', '999999', 'FF00FF', 'FFCC00',
'FFFF00', '00FF00', '00FFFF', '00CCFF', '993366', 'C0C0C0', 'FF99CC', 'FFCC99',
'FFFF99', 'CCFFFF', '99CCFF', 'FFFFFF'
],
// If we want to simply add more colors to the default set, use addColors.
addColors : []
};
})(jQuery);
| JavaScript |
// jQuery List DragSort v0.5.1
// Website: http://dragsort.codeplex.com/
// License: http://dragsort.codeplex.com/license
(function($) {
$.fn.dragsort = function(options) {
if (options == "destroy") {
$(this.selector).trigger("dragsort-uninit");
return;
}
var opts = $.extend({}, $.fn.dragsort.defaults, options);
var lists = [];
var list = null, lastPos = null;
this.each(function(i, cont) {
//if list container is table, the browser automatically wraps rows in tbody if not specified so change list container to tbody so that children returns rows as user expected
if ($(cont).is("table") && $(cont).children().size() == 1 && $(cont).children().is("tbody"))
cont = $(cont).children().get(0);
var newList = {
draggedItem: null,
placeHolderItem: null,
pos: null,
offset: null,
offsetLimit: null,
scroll: null,
container: cont,
init: function() {
//set options to default values if not set
var tagName = $(this.container).children().size() == 0 ? "li" : $(this.container).children(":first").get(0).tagName.toLowerCase();
if (opts.itemSelector == "")
opts.itemSelector = tagName;
if (opts.dragSelector == "")
opts.dragSelector = tagName;
if (opts.placeHolderTemplate == "")
opts.placeHolderTemplate = "<" + tagName + "> </" + tagName + ">";
//listidx allows reference back to correct list variable instance
$(this.container).attr("data-listidx", i).mousedown(this.grabItem).bind("dragsort-uninit", this.uninit);
this.styleDragHandlers(true);
},
uninit: function() {
var list = lists[$(this).attr("data-listidx")];
$(list.container).unbind("mousedown", list.grabItem).unbind("dragsort-uninit");
list.styleDragHandlers(false);
},
getItems: function() {
return $(this.container).children(opts.itemSelector);
},
styleDragHandlers: function(cursor) {
this.getItems().map(function() { return $(this).is(opts.dragSelector) ? this : $(this).find(opts.dragSelector).get(); }).css("cursor", cursor ? "pointer" : "");
},
grabItem: function(e) {
//if not left click or if clicked on excluded element (e.g. text box) or not a moveable list item return
if (e.which != 1 || $(e.target).is(opts.dragSelectorExclude) || $(e.target).closest(opts.dragSelectorExclude).size() > 0 || $(e.target).closest(opts.itemSelector).size() == 0)
return;
//prevents selection, stops issue on Fx where dragging hyperlink doesn't work and on IE where it triggers mousemove even though mouse hasn't moved,
//does also stop being able to click text boxes hence dragging on text boxes by default is disabled in dragSelectorExclude
e.preventDefault();
//change cursor to move while dragging
var dragHandle = e.target;
while (!$(dragHandle).is(opts.dragSelector)) {
if (dragHandle == this) return;
dragHandle = dragHandle.parentNode;
}
$(dragHandle).attr("data-cursor", $(dragHandle).css("cursor"));
$(dragHandle).css("cursor", "move");
//on mousedown wait for movement of mouse before triggering dragsort script (dragStart) to allow clicking of hyperlinks to work
var list = lists[$(this).attr("data-listidx")];
var item = this;
var trigger = function() {
list.dragStart.call(item, e);
$(list.container).unbind("mousemove", trigger);
};
$(list.container).mousemove(trigger).mouseup(function() { $(list.container).unbind("mousemove", trigger); $(dragHandle).css("cursor", $(dragHandle).attr("data-cursor")); });
},
dragStart: function(e) {
if (list != null && list.draggedItem != null)
list.dropItem();
list = lists[$(this).attr("data-listidx")];
list.draggedItem = $(e.target).closest(opts.itemSelector);
//record current position so on dragend we know if the dragged item changed position or not
list.draggedItem.attr("data-origpos", $(this).attr("data-listidx") + "-" + list.getItems().index(list.draggedItem));
//calculate mouse offset relative to draggedItem
var mt = parseInt(list.draggedItem.css("marginTop"));
var ml = parseInt(list.draggedItem.css("marginLeft"));
list.offset = list.draggedItem.offset();
list.offset.top = e.pageY - list.offset.top + (isNaN(mt) ? 0 : mt) - 1;
list.offset.left = e.pageX - list.offset.left + (isNaN(ml) ? 0 : ml) - 1;
//calculate box the dragged item can't be dragged outside of
if (!opts.dragBetween) {
var containerHeight = $(list.container).outerHeight() == 0 ? Math.max(1, Math.round(0.5 + list.getItems().size() * list.draggedItem.outerWidth() / $(list.container).outerWidth())) * list.draggedItem.outerHeight() : $(list.container).outerHeight();
list.offsetLimit = $(list.container).offset();
list.offsetLimit.right = list.offsetLimit.left + $(list.container).outerWidth() - list.draggedItem.outerWidth();
list.offsetLimit.bottom = list.offsetLimit.top + containerHeight - list.draggedItem.outerHeight();
}
//create placeholder item
var h = list.draggedItem.height();
var w = list.draggedItem.width();
if (opts.itemSelector == "tr") {
list.draggedItem.children().each(function() { $(this).width($(this).width()); });
list.placeHolderItem = list.draggedItem.clone().attr("data-placeholder", true);
list.draggedItem.after(list.placeHolderItem);
list.placeHolderItem.children().each(function() { $(this).css({ borderWidth:0, width: $(this).width() + 1, height: $(this).height() + 1 }).html(" "); });
} else {
list.draggedItem.after(opts.placeHolderTemplate);
list.placeHolderItem = list.draggedItem.next().css({ height: h, width: w }).attr("data-placeholder", true);
}
if (opts.itemSelector == "td") {
var listTable = list.draggedItem.closest("table").get(0);
$("<table id='" + listTable.id + "' style='border-width: 0px;' class='dragSortItem " + listTable.className + "'><tr></tr></table>").appendTo("body").children().append(list.draggedItem);
}
//style draggedItem while dragging
var orig = list.draggedItem.attr("style");
list.draggedItem.attr("data-origstyle", orig ? orig : "");
list.draggedItem.css({ position: "absolute", opacity: 0.8, "z-index": 999, height: h, width: w });
//auto-scroll setup
list.scroll = { moveX: 0, moveY: 0, maxX: $(document).width() - $(window).width(), maxY: $(document).height() - $(window).height() };
list.scroll.scrollY = window.setInterval(function() {
if (opts.scrollContainer != window) {
$(opts.scrollContainer).scrollTop($(opts.scrollContainer).scrollTop() + list.scroll.moveY);
return;
}
var t = $(opts.scrollContainer).scrollTop();
if (list.scroll.moveY > 0 && t < list.scroll.maxY || list.scroll.moveY < 0 && t > 0) {
$(opts.scrollContainer).scrollTop(t + list.scroll.moveY);
list.draggedItem.css("top", list.draggedItem.offset().top + list.scroll.moveY + 1);
}
}, 10);
list.scroll.scrollX = window.setInterval(function() {
if (opts.scrollContainer != window) {
$(opts.scrollContainer).scrollLeft($(opts.scrollContainer).scrollLeft() + list.scroll.moveX);
return;
}
var l = $(opts.scrollContainer).scrollLeft();
if (list.scroll.moveX > 0 && l < list.scroll.maxX || list.scroll.moveX < 0 && l > 0) {
$(opts.scrollContainer).scrollLeft(l + list.scroll.moveX);
list.draggedItem.css("left", list.draggedItem.offset().left + list.scroll.moveX + 1);
}
}, 10);
//misc
$(lists).each(function(i, l) { l.createDropTargets(); l.buildPositionTable(); });
list.setPos(e.pageX, e.pageY);
$(document).bind("mousemove", list.swapItems);
$(document).bind("mouseup", list.dropItem);
if (opts.scrollContainer != window)
$(window).bind("DOMMouseScroll mousewheel", list.wheel);
},
//set position of draggedItem
setPos: function(x, y) {
//remove mouse offset so mouse cursor remains in same place on draggedItem instead of top left corner
var top = y - this.offset.top;
var left = x - this.offset.left;
//limit top, left to within box draggedItem can't be dragged outside of
if (!opts.dragBetween) {
top = Math.min(this.offsetLimit.bottom, Math.max(top, this.offsetLimit.top));
left = Math.min(this.offsetLimit.right, Math.max(left, this.offsetLimit.left));
}
//adjust top, left calculations to parent element instead of window if it's relative or absolute
this.draggedItem.parents().each(function() {
if ($(this).css("position") != "static" && (!$.browser.mozilla || $(this).css("display") != "table")) {
var offset = $(this).offset();
top -= offset.top;
left -= offset.left;
return false;
}
});
//set x or y auto-scroll amount
if (opts.scrollContainer == window) {
y -= $(window).scrollTop();
x -= $(window).scrollLeft();
y = Math.max(0, y - $(window).height() + 5) + Math.min(0, y - 5);
x = Math.max(0, x - $(window).width() + 5) + Math.min(0, x - 5);
} else {
var cont = $(opts.scrollContainer);
var offset = cont.offset();
y = Math.max(0, y - cont.height() - offset.top) + Math.min(0, y - offset.top);
x = Math.max(0, x - cont.width() - offset.left) + Math.min(0, x - offset.left);
}
list.scroll.moveX = x == 0 ? 0 : x * opts.scrollSpeed / Math.abs(x);
list.scroll.moveY = y == 0 ? 0 : y * opts.scrollSpeed / Math.abs(y);
//move draggedItem to new mouse cursor location
this.draggedItem.css({ top: top, left: left });
},
//if scroll container is a div allow mouse wheel to scroll div instead of window when mouse is hovering over
wheel: function(e) {
if (($.browser.safari || $.browser.mozilla) && list && opts.scrollContainer != window) {
var cont = $(opts.scrollContainer);
var offset = cont.offset();
if (e.pageX > offset.left && e.pageX < offset.left + cont.width() && e.pageY > offset.top && e.pageY < offset.top + cont.height()) {
var delta = e.detail ? e.detail * 5 : e.wheelDelta / -2;
cont.scrollTop(cont.scrollTop() + delta);
e.preventDefault();
}
}
},
//build a table recording all the positions of the moveable list items
buildPositionTable: function() {
var pos = [];
this.getItems().not([list.draggedItem[0], list.placeHolderItem[0]]).each(function(i) {
var loc = $(this).offset();
loc.right = loc.left + $(this).outerWidth();
loc.bottom = loc.top + $(this).outerHeight();
loc.elm = this;
pos[i] = loc;
});
this.pos = pos;
},
dropItem: function() {
if (list.draggedItem == null)
return;
//list.draggedItem.attr("style", "") doesn't work on IE8 and jQuery 1.5 or lower
//list.draggedItem.removeAttr("style") doesn't work on chrome and jQuery 1.6 (works jQuery 1.5 or lower)
var orig = list.draggedItem.attr("data-origstyle");
list.draggedItem.attr("style", orig);
if (orig == "")
list.draggedItem.removeAttr("style");
list.draggedItem.removeAttr("data-origstyle");
list.styleDragHandlers(true);
list.placeHolderItem.before(list.draggedItem);
list.placeHolderItem.remove();
$("[data-droptarget], .dragSortItem").remove();
window.clearInterval(list.scroll.scrollY);
window.clearInterval(list.scroll.scrollX);
//if position changed call dragEnd
if (list.draggedItem.attr("data-origpos") != $(lists).index(list) + "-" + list.getItems().index(list.draggedItem))
opts.dragEnd.apply(list.draggedItem);
list.draggedItem.removeAttr("data-origpos");
list.draggedItem = null;
$(document).unbind("mousemove", list.swapItems);
$(document).unbind("mouseup", list.dropItem);
if (opts.scrollContainer != window)
$(window).unbind("DOMMouseScroll mousewheel", list.wheel);
return false;
},
//swap the draggedItem (represented visually by placeholder) with the list item the it has been dragged on top of
swapItems: function(e) {
if (list.draggedItem == null)
return false;
//move draggedItem to mouse location
list.setPos(e.pageX, e.pageY);
//retrieve list and item position mouse cursor is over
var ei = list.findPos(e.pageX, e.pageY);
var nlist = list;
for (var i = 0; ei == -1 && opts.dragBetween && i < lists.length; i++) {
ei = lists[i].findPos(e.pageX, e.pageY);
nlist = lists[i];
}
//if not over another moveable list item return
if (ei == -1)
return false;
//save fixed items locations
var children = function() { return $(nlist.container).children().not(nlist.draggedItem); };
var fixed = children().not(opts.itemSelector).each(function(i) { this.idx = children().index(this); });
//if moving draggedItem up or left place placeHolder before list item the dragged item is hovering over otherwise place it after
if (lastPos == null || lastPos.top > list.draggedItem.offset().top || lastPos.left > list.draggedItem.offset().left)
$(nlist.pos[ei].elm).before(list.placeHolderItem);
else
$(nlist.pos[ei].elm).after(list.placeHolderItem);
//restore fixed items location
fixed.each(function() {
var elm = children().eq(this.idx).get(0);
if (this != elm && children().index(this) < this.idx)
$(this).insertAfter(elm);
else if (this != elm)
$(this).insertBefore(elm);
});
//misc
$(lists).each(function(i, l) { l.createDropTargets(); l.buildPositionTable(); });
lastPos = list.draggedItem.offset();
return false;
},
//returns the index of the list item the mouse is over
findPos: function(x, y) {
for (var i = 0; i < this.pos.length; i++) {
if (this.pos[i].left < x && this.pos[i].right > x && this.pos[i].top < y && this.pos[i].bottom > y)
return i;
}
return -1;
},
//create drop targets which are placeholders at the end of other lists to allow dragging straight to the last position
createDropTargets: function() {
if (!opts.dragBetween)
return;
$(lists).each(function() {
var ph = $(this.container).find("[data-placeholder]");
var dt = $(this.container).find("[data-droptarget]");
if (ph.size() > 0 && dt.size() > 0)
dt.remove();
else if (ph.size() == 0 && dt.size() == 0) {
if (opts.itemSelector == "td")
$(opts.placeHolderTemplate).attr("data-droptarget", true).appendTo(this.container);
else
//list.placeHolderItem.clone().removeAttr("data-placeholder") crashes in IE7 and jquery 1.5.1 (doesn't in jquery 1.4.2 or IE8)
$(this.container).append(list.placeHolderItem.removeAttr("data-placeholder").clone().attr("data-droptarget", true));
list.placeHolderItem.attr("data-placeholder", true);
}
});
}
};
newList.init();
lists.push(newList);
});
return this;
};
$.fn.dragsort.defaults = {
itemSelector: "",
dragSelector: "",
dragSelectorExclude: "input, textarea",
dragEnd: function() { },
dragBetween: false,
placeHolderTemplate: "",
scrollContainer: window,
scrollSpeed: 5
};
})(jQuery);
| JavaScript |
$(document).ready(function() {
// Our Confirm method
Confirm = function (question, callback) {
// Content will consist of the question and ok/cancel buttons
var message = $('<p />', { text: question }),
cancel = $('<button />', {
text: 'Yes',
click: function() { callback(true); }
}),
ok = $('<button />', {
text: 'No',
click: function() { callback(false); }
})
;
dialogue(message.add(ok).add(cancel), 'Confirm');
}
// Our Alert method
Alert = function (message) {
// Content will consist of the message and an ok button
var message = $('<p />', { text: message }),
ok = $('<button />', { text: 'Ok', 'class': 'full' });
dialogue(message.add(ok), 'Alert!');
}
// Our Prompt method
Prompt= function (question, initial, callback) {
// Content will consist of a question elem and input, with ok/cancel buttons
var message = $('<p />', { text: question }),
input = $('<input />', { val: initial }),
ok = $('<button />', {
text: 'Ok',
click: function() { callback(input.val()); }
}),
cancel = $('<button />', {
text: 'Cancel',
click: function() { callback(null); }
});
dialogue(message.add(input).add(ok).add(cancel), 'Attention!');
}
dialogue =function (content, title) {
/*
* Since the dialogue isn't really a tooltip as such, we'll use a dummy
* out-of-DOM element as our target instead of an actual element like document.body
*/
$('<div />').qtip(
{
content: {
text: content,
title: title
},
position: {
my: 'center', at: 'center', // Center it...
target: $(window) // ... in the window
},
show: {
ready: true, // Show it straight away
modal: {
on: true, // Make it modal (darken the rest of the page)...
blur: false // ... but don't close the tooltip when clicked
}
},
hide: false, // We'll hide it maunally so disable hide events
style: 'qtip-light qtip-rounded qtip-dialogue', // Add a few styles
events: {
// Hide the tooltip when any buttons in the dialogue are clicked
render: function(event, api) {
$('button', api.elements.content).click(api.hide);
},
// Destroy the tooltip once it's hidden as we no longer need it!
hide: function(event, api) { api.destroy(); }
}
});
}
//Checked
$('#toggle-all').click(function() {
//
if ($(this).attr('class') != "toggle-checked") {
$('#mainform input[type=checkbox]').attr('checked', false);
}
//alert($(this).attr('class'));
$('#mainform input').checkBox();
$('#toggle-all').toggleClass('toggle-checked');
$('#mainform input[type=checkbox]').checkBox('toggle');
return false;
});
$('#mainform input:checkbox:not(#toggle-all)').click(function() {
$('#toggle-all').removeClass('toggle-checked');
});
//prompt for delete button
$('.remove-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
var self = this;
Confirm("Confirm removed the selected records?", function(yes) {
if (yes) {
$("#content-outer").showLoading();
window.location = self.href;
}
});
});
//
$('.remove-btn-member-group').click(function(e) {
e.preventDefault(); //prevent default action for anchor
var self = this;
Confirm("Confirm removed the selected group and delete all user in this group? ", function(yes) {
if (yes) {
$("#content-outer").showLoading();
window.location = self.href;
}
});
});
//
//prompt for delete button
$('.remove-btn-ajax').click(function(e) {
e.preventDefault(); //prevent default action for anchor
var self = this;
Confirm("Confirm removed the selected records?", function(yes) {
if (yes) {
$.ajax({
url:self.href,
success:function(data) {
jSuccess(
'<div class="msgnotify"><b>Save successfully</b></div>',
{
autoHide: true, // added in v2.0
HorizontalPosition: 'center',
VerticalPosition: 'top',
onClosed: function() { // added in v2.0
window.location = window.location.href;
}
});
}
});
}
});
});
//prompt for delete button
$('.remove-btn-ajax-live').live('click',function(e) {
e.preventDefault(); //prevent default action for anchor
var self = this;
Confirm("Confirm removed the selected records?", function(yes) {
if (yes) {
$.ajax({
url: self.href,
success: function(data) {
jSuccess(
'<div class="msgnotify"><b>Save successfully</b></div>',
{
autoHide: true, // added in v2.0
HorizontalPosition: 'center',
VerticalPosition: 'top',
onClosed: function() { // added in v2.0
window.location = window.location.href;
}
});
}
});
}
});
});
//bulk process action
$('.action-invoke').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
Alert('Please select at least one item.');
return false;
} else {
$("#content-outer").showLoading();
//submit form
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
}
});
//bulk process delete action
$('.action-invoke-removed').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
Alert('Please select at least one item.');
return false;
} else {
var self = this;
Confirm("Confirm removed the selected records?", function(yes) {
if (yes) {
$("#content-outer").showLoading();
$(".list_item_form").attr("action", self.href);
$(".list_item_form").submit();
}
});
}
});
// 1 - START DROPDOWN SLIDER SCRIPTS ------------------------------------------------------------------------
$(".action-slider").click(function() {
$("#actions-box-slider").slideToggle("fast");
$(this).toggleClass("activated");
return false;
});
$('a[title]').qtip();
// END ----------------------------- 1
//-------------------------------
$(".pager a").click(function(e) {
e.preventDefault();
var linkpage = window.location.href.replace("display_show_page=","");
var pos = window.location.href.replace("display_show_page=", "").lastIndexOf("page");
var page = $(this).attr("href").replace("?", "");
if (pos > 0) {
linkpage = linkpage.substr(0, pos);
linkpage = linkpage + page;
window.location.href = linkpage;
} else {
var pos1 = window.location.href.lastIndexOf("?");
if (pos1 >= 0) {
window.location.href = linkpage + "&" + page;
} else {
window.location.href = linkpage + "?" + page;
}
}
});
//-------------------------------
});
| JavaScript |
(function($){
/* hoverIntent by Brian Cherne */
$.fn.hoverIntent = function(f,g) {
// default configuration options
var cfg = {
sensitivity: 7,
interval: 100,
timeout: 0
};
// override configuration options with user supplied object
cfg = $.extend(cfg, g ? { over: f, out: g } : f );
// instantiate variables
// cX, cY = current X and Y position of mouse, updated by mousemove event
// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
var cX, cY, pX, pY;
// A private function for getting mouse position
var track = function(ev) {
cX = ev.pageX;
cY = ev.pageY;
};
// A private function for comparing current and previous mouse position
var compare = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
// compare mouse positions to see if they've crossed the threshold
if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
$(ob).unbind("mousemove",track);
// set hoverIntent state to true (so mouseOut can be called)
ob.hoverIntent_s = 1;
return cfg.over.apply(ob,[ev]);
} else {
// set previous coordinates for next time
pX = cX; pY = cY;
// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
}
};
// A private function for delaying the mouseOut function
var delay = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
ob.hoverIntent_s = 0;
return cfg.out.apply(ob,[ev]);
};
// A private function for handling mouse 'hovering'
var handleHover = function(e) {
// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
if ( p == this ) { return false; }
// copy objects to be passed into t (required for event object to be passed in IE)
var ev = jQuery.extend({},e);
var ob = this;
// cancel hoverIntent timer if it exists
if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }
// else e.type == "onmouseover"
if (e.type == "mouseover") {
// set "previous" X and Y position based on initial entry point
pX = ev.pageX; pY = ev.pageY;
// update "current" X and Y position based on mousemove
$(ob).bind("mousemove",track);
// start polling interval (self-calling timeout) to compare mouse coordinates over time
if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}
// else e.type == "onmouseout"
} else {
// unbind expensive mousemove event
$(ob).unbind("mousemove",track);
// if hoverIntent state is true, then call the mouseOut function after the specified delay
if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
}
};
// bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
};
})(jQuery); | JavaScript |
/*
* Supersubs v0.2b - jQuery plugin
* Copyright (c) 2008 Joel Birch
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*
* This plugin automatically adjusts submenu widths of suckerfish-style menus to that of
* their longest list item children. If you use this, please expect bugs and report them
* to the jQuery Google Group with the word 'Superfish' in the subject line.
*
*/
;(function($){ // $ will refer to jQuery within this closure
$.fn.supersubs = function(options){
var opts = $.extend({}, $.fn.supersubs.defaults, options);
// return original object to support chaining
return this.each(function() {
// cache selections
var $$ = $(this);
// support metadata
var o = $.meta ? $.extend({}, opts, $$.data()) : opts;
// get the font size of menu.
// .css('fontSize') returns various results cross-browser, so measure an em dash instead
var fontsize = $('<li id="menu-fontsize">—</li>').css({
'padding' : 0,
'position' : 'absolute',
'top' : '-999em',
'width' : 'auto'
}).appendTo($$).width(); //clientWidth is faster, but was incorrect here
// remove em dash
$('#menu-fontsize').remove();
// cache all ul elements
$ULs = $$.find('ul');
// loop through each ul in menu
$ULs.each(function(i) {
// cache this ul
var $ul = $ULs.eq(i);
// get all (li) children of this ul
var $LIs = $ul.children();
// get all anchor grand-children
var $As = $LIs.children('a');
// force content to one line and save current float property
var liFloat = $LIs.css('white-space','nowrap').css('float');
// remove width restrictions and floats so elements remain vertically stacked
var emWidth = $ul.add($LIs).add($As).css({
'float' : 'none',
'width' : 'auto'
})
// this ul will now be shrink-wrapped to longest li due to position:absolute
// so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer
.end().end()[0].clientWidth / fontsize;
// add more width to ensure lines don't turn over at certain sizes in various browsers
emWidth += o.extraWidth;
// restrict to at least minWidth and at most maxWidth
if (emWidth > o.maxWidth) { emWidth = o.maxWidth; }
else if (emWidth < o.minWidth) { emWidth = o.minWidth; }
emWidth += 'em';
// set ul to width in ems
$ul.css('width',emWidth);
// restore li floats to avoid IE bugs
// set li width to full width of this ul
// revert white-space to normal
$LIs.css({
'float' : liFloat,
'width' : '100%',
'white-space' : 'normal'
})
// update offset position of descendant ul to reflect new width of parent
.each(function(){
var $childUl = $('>ul',this);
var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right';
$childUl.css(offsetDirection,emWidth);
});
});
});
};
// expose defaults
$.fn.supersubs.defaults = {
minWidth : 9, // requires em unit.
maxWidth : 25, // requires em unit.
extraWidth : 0 // extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values
};
})(jQuery); // plugin code ends
| JavaScript |
/*
* Superfish v1.4.8 - jQuery menu widget
* Copyright (c) 2008 Joel Birch
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
*/
;(function($){
$.fn.superfish = function(op){
var sf = $.fn.superfish,
c = sf.c,
$arrow = $(['<span class="',c.arrowClass,'"> »</span>'].join('')),
over = function(){
var $$ = $(this), menu = getMenu($$);
clearTimeout(menu.sfTimer);
$$.showSuperfishUl().siblings().hideSuperfishUl();
},
out = function(){
var $$ = $(this), menu = getMenu($$), o = sf.op;
clearTimeout(menu.sfTimer);
menu.sfTimer=setTimeout(function(){
o.retainPath=($.inArray($$[0],o.$path)>-1);
$$.hideSuperfishUl();
if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
},o.delay);
},
getMenu = function($menu){
var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
sf.op = sf.o[menu.serial];
return menu;
},
addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
return this.each(function() {
var s = this.serial = sf.o.length;
var o = $.extend({},sf.defaults,op);
o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
$(this).addClass([o.hoverClass,c.bcClass].join(' '))
.filter('li:has(ul)').removeClass(o.pathClass);
});
sf.o[s] = sf.op = o;
$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
if (o.autoArrows) addArrow( $('>a:first-child',this) );
})
.not('.'+c.bcClass)
.hideSuperfishUl();
var $a = $('a',this);
$a.each(function(i){
var $li = $a.eq(i).parents('li');
$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
});
o.onInit.call(this);
}).each(function() {
var menuClasses = [c.menuClass];
if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
$(this).addClass(menuClasses.join(' '));
});
};
var sf = $.fn.superfish;
sf.o = [];
sf.op = {};
sf.IE7fix = function(){
var o = sf.op;
if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
this.toggleClass(sf.c.shadowClass+'-off');
};
sf.c = {
bcClass : 'sf-breadcrumb',
menuClass : 'sf-js-enabled',
anchorClass : 'sf-with-ul',
arrowClass : 'sf-sub-indicator',
shadowClass : 'sf-shadow'
};
sf.defaults = {
hoverClass : 'sfHover',
pathClass : 'overideThisToUse',
pathLevels : 1,
delay : 800,
animation : {opacity:'show'},
speed : 'normal',
autoArrows : true,
dropShadows : true,
disableHI : false, // true disables hoverIntent detection
onInit : function(){}, // callback functions
onBeforeShow: function(){},
onShow : function(){},
onHide : function(){}
};
$.fn.extend({
hideSuperfishUl : function(){
var o = sf.op,
not = (o.retainPath===true) ? o.$path : '';
o.retainPath = false;
var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
.find('>ul').hide().css('visibility','hidden');
o.onHide.call($ul);
return this;
},
showSuperfishUl : function(){
var o = sf.op,
sh = sf.c.shadowClass+'-off',
$ul = this.addClass(o.hoverClass)
.find('>ul:hidden').css('visibility','visible');
sf.IE7fix.call($ul);
o.onBeforeShow.call($ul);
$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
return this;
}
});
})(jQuery);
| JavaScript |
/*
* jQuery selectbox plugin
*
* Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
* Licensed under the GPL license and MIT:
* http://www.opensource.org/licenses/GPL-license.php
* http://www.opensource.org/licenses/mit-license.php
*
* The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
*
* Revision: $Id$
* Version: 0.5
*
* Changelog :
* Version 0.5
* - separate css style for current selected element and hover element which solve the highlight issue
* Version 0.4
* - Fix width when the select is in a hidden div @Pawel Maziarz
* - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
*/
jQuery.fn.extend({
selectbox: function(options) {
return this.each(function() {
new jQuery.SelectBox(this, options);
});
}
});
/* pawel maziarz: work around for ie logging */
if (!window.console) {
var console = {
log: function(msg) {
}
}
}
/* */
jQuery.SelectBox = function(selectobj, options) {
var opt = options || {};
opt.inputClass = opt.inputClass || "selectbox3";
opt.containerClass = opt.containerClass || "selectbox-wrapper3";
opt.hoverClass = opt.hoverClass || "current3";
opt.currentClass = opt.selectedClass || "selected3"
opt.debug = opt.debug || false;
var elm_id = selectobj.id;
var active = -1;
var inFocus = false;
var hasfocus = 0;
//jquery object for select element
var $select = $(selectobj);
// jquery container object
var $container = setupContainer(opt);
//jquery input object
var $input = setupInput(opt);
// hide select and append newly created elements
$select.hide().before($input).before($container);
init();
$input
.click(function(){
if (!inFocus) {
$container.toggle();
}
})
.focus(function(){
if ($container.not(':visible')) {
inFocus = true;
$container.show();
}
})
.keydown(function(event) {
switch(event.keyCode) {
case 38: // up
event.preventDefault();
moveSelect(-1);
break;
case 40: // down
event.preventDefault();
moveSelect(1);
break;
//case 9: // tab
case 13: // return
event.preventDefault(); // seems not working in mac !
$('li.'+opt.hoverClass).trigger('click');
break;
case 27: //escape
hideMe();
break;
}
})
.blur(function() {
if ($container.is(':visible') && hasfocus > 0 ) {
if(opt.debug) console.log('container visible and has focus')
} else {
hideMe();
}
});
function hideMe() {
hasfocus = 0;
$container.hide();
}
function init() {
$container.append(getSelectOptions($input.attr('id'))).hide();
var width = $input.css('width');
$container.width(width);
}
function setupContainer(options) {
var container = document.createElement("div");
$container = $(container);
$container.attr('id', elm_id+'_container');
$container.addClass(options.containerClass);
return $container;
}
function setupInput(options) {
var input = document.createElement("input");
var $input = $(input);
$input.attr("id", elm_id+"_input");
$input.attr("type", "text");
$input.addClass(options.inputClass);
$input.attr("autocomplete", "off");
$input.attr("readonly", "readonly");
$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
return $input;
}
function moveSelect(step) {
var lis = $("li", $container);
if (!lis) return;
active += step;
if (active < 0) {
active = 0;
} else if (active >= lis.size()) {
active = lis.size() - 1;
}
lis.removeClass(opt.hoverClass);
$(lis[active]).addClass(opt.hoverClass);
}
function setCurrent() {
var li = $("li."+opt.currentClass, $container).get(0);
var ar = (''+li.id).split('_');
var el = ar[ar.length-1];
$select.val(el);
$input.val($(li).html());
return true;
}
// select value
function getCurrentSelected() {
return $select.val();
}
// input value
function getCurrentValue() {
return $input.val();
}
function getSelectOptions(parentid) {
var select_options = new Array();
var ul = document.createElement('ul');
$select.children('option').each(function() {
var li = document.createElement('li');
li.setAttribute('id', parentid + '_' + $(this).val());
li.innerHTML = $(this).html();
if ($(this).is(':selected')) {
$input.val($(this).html());
$(li).addClass(opt.currentClass);
}
ul.appendChild(li);
$(li)
.mouseover(function(event) {
hasfocus = 1;
if (opt.debug) console.log('over on : '+this.id);
jQuery(event.target, $container).addClass(opt.hoverClass);
})
.mouseout(function(event) {
hasfocus = -1;
if (opt.debug) console.log('out on : '+this.id);
jQuery(event.target, $container).removeClass(opt.hoverClass);
})
.click(function(event) {
var fl = $('li.'+opt.hoverClass, $container).get(0);
if (opt.debug) console.log('click on :'+this.id);
$('li.'+opt.currentClass).removeClass(opt.currentClass);
$(this).addClass(opt.currentClass);
setCurrent();
hideMe();
});
});
return ul;
}
};
| JavaScript |
/*!
* jQuery Templates Plugin 1.0.0pre
* http://github.com/jquery/jquery-tmpl
* Requires jQuery 1.4.2
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function( jQuery, undefined ){
var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];
function newTmplItem( options, parentItem, fn, data ) {
// Returns a template item data structure for a new rendered instance of a template (a 'template item').
// The content field is a hierarchical array of strings and nested items (to be
// removed and replaced by nodes field of dom elements, once inserted in DOM).
var newItem = {
data: data || (data === 0 || data === false) ? data : (parentItem ? parentItem.data : {}),
_wrap: parentItem ? parentItem._wrap : null,
tmpl: null,
parent: parentItem || null,
nodes: [],
calls: tiCalls,
nest: tiNest,
wrap: tiWrap,
html: tiHtml,
update: tiUpdate
};
if ( options ) {
jQuery.extend( newItem, options, { nodes: [], parent: parentItem });
}
if ( fn ) {
// Build the hierarchical content to be used during insertion into DOM
newItem.tmpl = fn;
newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem );
newItem.key = ++itemKey;
// Keep track of new template item, until it is stored as jQuery Data on DOM element
(stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
}
return newItem;
}
// Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems,
parent = this.length === 1 && this[0].parentNode;
appendToTmplItems = newTmplItems || {};
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
ret = this;
} else {
for ( i = 0, l = insert.length; i < l; i++ ) {
cloneIndex = i;
elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
cloneIndex = 0;
ret = this.pushStack( ret, name, insert.selector );
}
tmplItems = appendToTmplItems;
appendToTmplItems = null;
jQuery.tmpl.complete( tmplItems );
return ret;
};
});
jQuery.fn.extend({
// Use first wrapped element as template markup.
// Return wrapped set of template items, obtained by rendering template against data.
tmpl: function( data, options, parentItem ) {
return jQuery.tmpl( this[0], data, options, parentItem );
},
// Find which rendered template item the first wrapped DOM element belongs to
tmplItem: function() {
return jQuery.tmplItem( this[0] );
},
// Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
template: function( name ) {
return jQuery.template( name, this[0] );
},
domManip: function( args, table, callback, options ) {
if ( args[0] && jQuery.isArray( args[0] )) {
var dmArgs = jQuery.makeArray( arguments ), elems = args[0], elemsLength = elems.length, i = 0, tmplItem;
while ( i < elemsLength && !(tmplItem = jQuery.data( elems[i++], "tmplItem" ))) {}
if ( tmplItem && cloneIndex ) {
dmArgs[2] = function( fragClone ) {
// Handler called by oldManip when rendered template has been inserted into DOM.
jQuery.tmpl.afterManip( this, fragClone, callback );
};
}
oldManip.apply( this, dmArgs );
} else {
oldManip.apply( this, arguments );
}
cloneIndex = 0;
if ( !appendToTmplItems ) {
jQuery.tmpl.complete( newTmplItems );
}
return this;
}
});
jQuery.extend({
// Return wrapped set of template items, obtained by rendering template against data.
tmpl: function( tmpl, data, options, parentItem ) {
var ret, topLevel = !parentItem;
if ( topLevel ) {
// This is a top-level tmpl call (not from a nested template using {{tmpl}})
parentItem = topTmplItem;
tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
} else if ( !tmpl ) {
// The template item is already associated with DOM - this is a refresh.
// Re-evaluate rendered template for the parentItem
tmpl = parentItem.tmpl;
newTmplItems[parentItem.key] = parentItem;
parentItem.nodes = [];
if ( parentItem.wrapped ) {
updateWrapped( parentItem, parentItem.wrapped );
}
// Rebuild, without creating a new template item
return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
}
if ( !tmpl ) {
return []; // Could throw...
}
if ( typeof data === "function" ) {
data = data.call( parentItem || {} );
}
if ( options && options.wrapped ) {
updateWrapped( options, options.wrapped );
}
ret = jQuery.isArray( data ) ?
jQuery.map( data, function( dataItem ) {
return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
}) :
[ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
},
// Return rendered template item for an element.
tmplItem: function( elem ) {
var tmplItem;
if ( elem instanceof jQuery ) {
elem = elem[0];
}
while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
return tmplItem || topTmplItem;
},
// Set:
// Use $.template( name, tmpl ) to cache a named template,
// where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
// Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.
// Get:
// Use $.template( name ) to access a cached template.
// Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
// will return the compiled template, without adding a name reference.
// If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
// to $.template( null, templateString )
template: function( name, tmpl ) {
if (tmpl) {
// Compile template and associate with name
if ( typeof tmpl === "string" ) {
// This is an HTML string being passed directly in.
tmpl = buildTmplFn( tmpl )
} else if ( tmpl instanceof jQuery ) {
tmpl = tmpl[0] || {};
}
if ( tmpl.nodeType ) {
// If this is a template block, use cached copy, or generate tmpl function and cache.
tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML ));
// Issue: In IE, if the container element is not a script block, the innerHTML will remove quotes from attribute values whenever the value does not include white space.
// This means that foo="${x}" will not work if the value of x includes white space: foo="${x}" -> foo=value of x.
// To correct this, include space in tag: foo="${ x }" -> foo="value of x"
}
return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
}
// Return named compiled template
return name ? (typeof name !== "string" ? jQuery.template( null, name ):
(jQuery.template[name] ||
// If not in map, and not containing at least on HTML tag, treat as a selector.
// (If integrated with core, use quickExpr.exec)
jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null;
},
encode: function( text ) {
// Do HTML encoding replacing < > & and ' and " by corresponding entities.
return ("" + text).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'");
}
});
jQuery.extend( jQuery.tmpl, {
tag: {
"tmpl": {
_default: { $2: "null" },
open: "if($notnull_1){__=__.concat($item.nest($1,$2));}"
// tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
// This means that {{tmpl foo}} treats foo as a template (which IS a function).
// Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
},
"wrap": {
_default: { $2: "null" },
open: "$item.calls(__,$1,$2);__=[];",
close: "call=$item.calls();__=call._.concat($item.wrap(call,__));"
},
"each": {
_default: { $2: "$index, $value" },
open: "if($notnull_1){$.each($1a,function($2){with(this){",
close: "}});}"
},
"if": {
open: "if(($notnull_1) && $1a){",
close: "}"
},
"else": {
_default: { $1: "true" },
open: "}else if(($notnull_1) && $1a){"
},
"html": {
// Unecoded expression evaluation.
open: "if($notnull_1){__.push($1a);}"
},
"=": {
// Encoded expression evaluation. Abbreviated form is ${}.
_default: { $1: "$data" },
open: "if($notnull_1){__.push($.encode($1a));}"
},
"!": {
// Comment tag. Skipped by parser
open: ""
}
},
// This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
complete: function( items ) {
newTmplItems = {};
},
// Call this from code which overrides domManip, or equivalent
// Manage cloning/storing template items etc.
afterManip: function afterManip( elem, fragClone, callback ) {
// Provides cloned fragment ready for fixup prior to and after insertion into DOM
var content = fragClone.nodeType === 11 ?
jQuery.makeArray(fragClone.childNodes) :
fragClone.nodeType === 1 ? [fragClone] : [];
// Return fragment to original caller (e.g. append) for DOM insertion
callback.call( elem, fragClone );
// Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
storeTmplItems( content );
cloneIndex++;
}
});
//========================== Private helper functions, used by code above ==========================
function build( tmplItem, nested, content ) {
// Convert hierarchical content into flat string array
// and finally return array of fragments ready for DOM insertion
var frag, ret = content ? jQuery.map( content, function( item ) {
return (typeof item === "string") ?
// Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
(tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) :
// This is a child template item. Build nested template.
build( item, tmplItem, item._ctnt );
}) :
// If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}.
tmplItem;
if ( nested ) {
return ret;
}
// top-level template
ret = ret.join("");
// Support templates which have initial or final text nodes, or consist only of text
// Also support HTML entities within the HTML markup.
ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) {
frag = jQuery( middle ).get();
storeTmplItems( frag );
if ( before ) {
frag = unencode( before ).concat(frag);
}
if ( after ) {
frag = frag.concat(unencode( after ));
}
});
return frag ? frag : unencode( ret );
}
function unencode( text ) {
// Use createElement, since createTextNode will not render HTML entities correctly
var el = document.createElement( "div" );
el.innerHTML = text;
return jQuery.makeArray(el.childNodes);
}
// Generate a reusable function that will serve to render a template against data
function buildTmplFn( markup ) {
return new Function("jQuery","$item",
// Use the variable __ to hold a string array while building the compiled template. (See https://github.com/jquery/jquery-tmpl/issues#issue/10).
"var $=jQuery,call,__=[],$data=$item.data;" +
// Introduce the data as local variables using with(){}
"with($data){__.push('" +
// Convert the template into pure JavaScript
jQuery.trim(markup)
.replace( /([\\'])/g, "\\$1" )
.replace( /[\r\t\n]/g, " " )
.replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
.replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,
function( all, slash, type, fnargs, target, parens, args ) {
var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect;
if ( !tag ) {
throw "Unknown template tag: " + type;
}
def = tag._default || [];
if ( parens && !/\w$/.test(target)) {
target += parens;
parens = "";
}
if ( target ) {
target = unescape( target );
args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : "");
// Support for target being things like a.toLowerCase();
// In that case don't call with template item as 'this' pointer. Just evaluate...
expr = parens ? (target.indexOf(".") > -1 ? target + unescape( parens ) : ("(" + target + ").call($item" + args)) : target;
exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
} else {
exprAutoFnDetect = expr = def.$1 || "null";
}
fnargs = unescape( fnargs );
return "');" +
tag[ slash ? "close" : "open" ]
.split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" )
.split( "$1a" ).join( exprAutoFnDetect )
.split( "$1" ).join( expr )
.split( "$2" ).join( fnargs || def.$2 || "" ) +
"__.push('";
}) +
"');}return __;"
);
}
function updateWrapped( options, wrapped ) {
// Build the wrapped content.
options._wrap = build( options, true,
// Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()]
).join("");
}
function unescape( args ) {
return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
}
function outerHtml( elem ) {
var div = document.createElement("div");
div.appendChild( elem.cloneNode(true) );
return div.innerHTML;
}
// Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
function storeTmplItems( content ) {
var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
for ( i = 0, l = content.length; i < l; i++ ) {
if ( (elem = content[i]).nodeType !== 1 ) {
continue;
}
elems = elem.getElementsByTagName("*");
for ( m = elems.length - 1; m >= 0; m-- ) {
processItemKey( elems[m] );
}
processItemKey( elem );
}
function processItemKey( el ) {
var pntKey, pntNode = el, pntItem, tmplItem, key;
// Ensure that each rendered template inserted into the DOM has its own template item,
if ( (key = el.getAttribute( tmplItmAtt ))) {
while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { }
if ( pntKey !== key ) {
// The next ancestor with a _tmplitem expando is on a different key than this one.
// So this is a top-level element within this template item
// Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment.
pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0;
if ( !(tmplItem = newTmplItems[key]) ) {
// The item is for wrapped content, and was copied from the temporary parent wrappedItem.
tmplItem = wrappedItems[key];
tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode] );
tmplItem.key = ++itemKey;
newTmplItems[itemKey] = tmplItem;
}
if ( cloneIndex ) {
cloneTmplItem( key );
}
}
el.removeAttribute( tmplItmAtt );
} else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) {
// This was a rendered element, cloned during append or appendTo etc.
// TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
cloneTmplItem( tmplItem.key );
newTmplItems[tmplItem.key] = tmplItem;
pntNode = jQuery.data( el.parentNode, "tmplItem" );
pntNode = pntNode ? pntNode.key : 0;
}
if ( tmplItem ) {
pntItem = tmplItem;
// Find the template item of the parent element.
// (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
while ( pntItem && pntItem.key != pntNode ) {
// Add this element as a top-level node for this rendered template item, as well as for any
// ancestor items between this item and the item of its parent element
pntItem.nodes.push( el );
pntItem = pntItem.parent;
}
// Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
delete tmplItem._ctnt;
delete tmplItem._wrap;
// Store template item as jQuery data on the element
jQuery.data( el, "tmplItem", tmplItem );
}
function cloneTmplItem( key ) {
key = key + keySuffix;
tmplItem = newClonedItems[key] =
(newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent ));
}
}
}
//---- Helper functions for template item ----
function tiCalls( content, tmpl, data, options ) {
if ( !content ) {
return stack.pop();
}
stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
}
function tiNest( tmpl, data, options ) {
// nested template, using {{tmpl}} tag
return jQuery.tmpl( jQuery.template( tmpl ), data, options, this );
}
function tiWrap( call, wrapped ) {
// nested template, using {{wrap}} tag
var options = call.options || {};
options.wrapped = wrapped;
// Apply the template, which may incorporate wrapped content,
return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item );
}
function tiHtml( filter, textOnly ) {
var wrapped = this._wrap;
return jQuery.map(
jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ),
function(e) {
return textOnly ?
e.innerText || e.textContent :
e.outerHTML || outerHtml(e);
});
}
function tiUpdate() {
var coll = this.nodes;
jQuery.tmpl( null, null, null, this).insertBefore( coll[0] );
jQuery( coll ).remove();
}
})( jQuery );
| JavaScript |
/**!
* project-site: http://plugins.jquery.com/project/AjaxManager
* repository: http://github.com/aFarkas/Ajaxmanager
* @author Alexander Farkas
* @version 3.12
* Copyright 2010, Alexander Farkas
* Dual licensed under the MIT or GPL Version 2 licenses.
*/
(function($){
"use strict";
var managed = {},
cache = {}
;
$.manageAjax = (function(){
function create(name, opts){
managed[name] = new $.manageAjax._manager(name, opts);
return managed[name];
}
function destroy(name){
if(managed[name]){
managed[name].clear(true);
delete managed[name];
}
}
var publicFns = {
create: create,
destroy: destroy
};
return publicFns;
})();
$.manageAjax._manager = function(name, opts){
this.requests = {};
this.inProgress = 0;
this.name = name;
this.qName = name;
this.opts = $.extend({}, $.manageAjax.defaults, opts);
if(opts && opts.queue && opts.queue !== true && typeof opts.queue === 'string' && opts.queue !== 'clear'){
this.qName = opts.queue;
}
};
$.manageAjax._manager.prototype = {
add: function(url, o){
if(typeof url == 'object'){
o = url;
} else if(typeof url == 'string'){
o = $.extend(o || {}, {url: url});
}
o = $.extend({}, this.opts, o);
var origCom = o.complete || $.noop,
origSuc = o.success || $.noop,
beforeSend = o.beforeSend || $.noop,
origError = o.error || $.noop,
strData = (typeof o.data == 'string') ? o.data : $.param(o.data || {}),
xhrID = o.type + o.url + strData,
that = this,
ajaxFn = this._createAjax(xhrID, o, origSuc, origCom)
;
if(o.preventDoubleRequests && o.queueDuplicateRequests){
if(o.preventDoubleRequests){
o.queueDuplicateRequests = false;
}
setTimeout(function(){
throw("preventDoubleRequests and queueDuplicateRequests can't be both true");
}, 0);
}
if(this.requests[xhrID] && o.preventDoubleRequests){
return;
}
ajaxFn.xhrID = xhrID;
o.xhrID = xhrID;
o.beforeSend = function(xhr, opts){
var ret = beforeSend.call(this, xhr, opts);
if(ret === false){
that._removeXHR(xhrID);
}
xhr = null;
return ret;
};
o.complete = function(xhr, status){
that._complete.call(that, this, origCom, xhr, status, xhrID, o);
xhr = null;
};
o.success = function(data, status, xhr){
that._success.call(that, this, origSuc, data, status, xhr, o);
xhr = null;
};
//always add some error callback
o.error = function(ahr, status, errorStr){
var httpStatus = '',
content = ''
;
if(status !== 'timeout' && ahr){
httpStatus = ahr.status;
content = ahr.responseXML || ahr.responseText;
}
if(origError) {
origError.call(this, ahr, status, errorStr, o);
} else {
setTimeout(function(){
throw status + '| status: ' + httpStatus + ' | URL: ' + o.url + ' | data: '+ strData + ' | thrown: '+ errorStr + ' | response: '+ content;
}, 0);
}
ahr = null;
};
if(o.queue === 'clear'){
$(document).clearQueue(this.qName);
}
if(o.queue || (o.queueDuplicateRequests && this.requests[xhrID])){
$.queue(document, this.qName, ajaxFn);
if(this.inProgress < o.maxRequests && (!this.requests[xhrID] || !o.queueDuplicateRequests)){
$.dequeue(document, this.qName);
}
return xhrID;
}
return ajaxFn();
},
_createAjax: function(id, o, origSuc, origCom){
var that = this;
return function(){
if(o.beforeCreate.call(o.context || that, id, o) === false){return;}
that.inProgress++;
if(that.inProgress === 1){
$.event.trigger(that.name +'AjaxStart');
}
if(o.cacheResponse && cache[id]){
if(!cache[id].cacheTTL || cache[id].cacheTTL < 0 || ((new Date().getTime() - cache[id].timestamp) < cache[id].cacheTTL)){
that.requests[id] = {};
setTimeout(function(){
that._success.call(that, o.context || o, origSuc, cache[id]._successData, 'success', cache[id], o);
that._complete.call(that, o.context || o, origCom, cache[id], 'success', id, o);
}, 0);
} else {
delete cache[id];
}
}
if(!o.cacheResponse || !cache[id]) {
if (o.async) {
that.requests[id] = $.ajax(o);
} else {
$.ajax(o);
}
}
return id;
};
},
_removeXHR: function(xhrID){
if(this.opts.queue || this.opts.queueDuplicateRequests){
$.dequeue(document, this.qName);
}
this.inProgress--;
this.requests[xhrID] = null;
delete this.requests[xhrID];
},
clearCache: function () {
cache = {};
},
_isAbort: function(xhr, status, o){
if(!o.abortIsNoSuccess || (!xhr && !status)){
return false;
}
var ret = !!( ( !xhr || xhr.readyState === 0 || this.lastAbort === o.xhrID ) );
xhr = null;
return ret;
},
_complete: function(context, origFn, xhr, status, xhrID, o){
if(this._isAbort(xhr, status, o)){
status = 'abort';
o.abort.call(context, xhr, status, o);
}
origFn.call(context, xhr, status, o);
$.event.trigger(this.name +'AjaxComplete', [xhr, status, o]);
if(o.domCompleteTrigger){
$(o.domCompleteTrigger)
.trigger(this.name +'DOMComplete', [xhr, status, o])
.trigger('DOMComplete', [xhr, status, o])
;
}
this._removeXHR(xhrID);
if(!this.inProgress){
$.event.trigger(this.name +'AjaxStop');
}
xhr = null;
},
_success: function(context, origFn, data, status, xhr, o){
var that = this;
if(this._isAbort(xhr, status, o)){
xhr = null;
return;
}
if(o.abortOld){
$.each(this.requests, function(name){
if(name === o.xhrID){
return false;
}
that.abort(name);
});
}
if(o.cacheResponse && !cache[o.xhrID]){
if(!xhr){
xhr = {};
}
cache[o.xhrID] = {
status: xhr.status,
statusText: xhr.statusText,
responseText: xhr.responseText,
responseXML: xhr.responseXML,
_successData: data,
cacheTTL: o.cacheTTL,
timestamp: new Date().getTime()
};
if('getAllResponseHeaders' in xhr){
var responseHeaders = xhr.getAllResponseHeaders();
var parsedHeaders;
var parseHeaders = function(){
if(parsedHeaders){return;}
parsedHeaders = {};
$.each(responseHeaders.split("\n"), function(i, headerLine){
var delimiter = headerLine.indexOf(":");
parsedHeaders[headerLine.substr(0, delimiter)] = headerLine.substr(delimiter + 2);
});
};
$.extend(cache[o.xhrID], {
getAllResponseHeaders: function() {return responseHeaders;},
getResponseHeader: function(name) {
parseHeaders();
return (name in parsedHeaders) ? parsedHeaders[name] : null;
}
});
}
}
origFn.call(context, data, status, xhr, o);
$.event.trigger(this.name +'AjaxSuccess', [xhr, o, data]);
if(o.domSuccessTrigger){
$(o.domSuccessTrigger)
.trigger(this.name +'DOMSuccess', [data, o])
.trigger('DOMSuccess', [data, o])
;
}
xhr = null;
},
getData: function(id){
if( id ){
var ret = this.requests[id];
if(!ret && this.opts.queue) {
ret = $.grep($(document).queue(this.qName), function(fn, i){
return (fn.xhrID === id);
})[0];
}
return ret;
}
return {
requests: this.requests,
queue: (this.opts.queue) ? $(document).queue(this.qName) : [],
inProgress: this.inProgress
};
},
abort: function(id){
var xhr;
if(id){
xhr = this.getData(id);
if(xhr && xhr.abort){
this.lastAbort = id;
xhr.abort();
this.lastAbort = false;
} else {
$(document).queue(
this.qName, $.grep($(document).queue(this.qName), function(fn, i){
return (fn !== xhr);
})
);
}
xhr = null;
return;
}
var that = this,
ids = []
;
$.each(this.requests, function(id){
ids.push(id);
});
$.each(ids, function(i, id){
that.abort(id);
});
},
clear: function(shouldAbort){
$(document).clearQueue(this.qName);
if(shouldAbort){
this.abort();
}
}
};
$.manageAjax._manager.prototype.getXHR = $.manageAjax._manager.prototype.getData;
$.manageAjax.defaults = {
beforeCreate: $.noop,
abort: $.noop,
abortIsNoSuccess: true,
maxRequests: 1,
cacheResponse: false,
async: true,
domCompleteTrigger: false,
domSuccessTrigger: false,
preventDoubleRequests: true,
queueDuplicateRequests: false,
cacheTTL: -1,
queue: false // true, false, clear
};
$.each($.manageAjax._manager.prototype, function(n, fn){
if(n.indexOf('_') === 0 || !$.isFunction(fn)){return;}
$.manageAjax[n] = function(name, o){
if(!managed[name]){
if(n === 'add'){
$.manageAjax.create(name, o);
} else {
return;
}
}
var args = Array.prototype.slice.call(arguments, 1);
managed[name][n].apply(managed[name], args);
};
});
})(jQuery); | JavaScript |
/********************************************************************************/
// <copyright file="Utility.js" company="Asia E-Business Solutions">
// Copyright © 2012. All right reserved
// </copyright>
//
// <history>
// <change who="Hieu Nguyen" date="20/12/2012 2:53:02 PM">Created</change>
// <history>
/********************************************************************************/
/**
* Create Namespace Object
**/
var Namespace = {
Register: function(_Name) {
var chk = false;
var cob = "";
var spc = _Name.split(".");
for (var i = 0; i < spc.length; i++) {
if (cob != "") { cob += "." }
cob += spc[i];
chk = this.Exists(cob);
if (!chk) { this.Create(cob); }
}
if (chk) { throw "Namespace: " + _Name + " is already defined."; }
},
Create: function(_Src) {
eval("window." + _Src + " = new Object(); ");
},
Exists: function(_Src) {
eval("var NE = false;try{if(" + _Src + "){NE = true;}else{ NE = false;}} catch(err){}");
return NE;
}
}
/**
* Dump Object
**/
var dump_js = function(variable, maxDeep) {
var deep = 0;
var maxDeep = maxDeep || 0;
function fetch(object, parent) {
var buffer = '';
deep++;
for (var i in object) {
if (parent) {
objectPath = parent + '.' + i;
} else {
objectPath = i;
}
buffer += objectPath + ' (' + typeof object[i] + ')';
if (typeof object[i] == 'object') {
buffer += "\n";
if (deep < maxDeep) {
buffer += fetch(object[i], objectPath);
}
} else if (typeof object[i] == 'function') {
buffer += "\n";
} else if (typeof object[i] == 'string') {
buffer += ': "' + object[i] + "\"\n";
} else {
buffer += ': ' + object[i] + "\n";
}
}
deep--;
return buffer;
}
if (typeof variable == 'object') {
return fetch(variable);
}
return '(' + typeof variable + '): ' + variable + "-";
}
/**
*Load Dynamic Css
**/
function loadcssfile(filename) {
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
if (typeof fileref != "undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
function openWindow(website) {
var winwidth = window.screen.availWidth;
var winheight = window.screen.availHeight;
var windowprops = 'width=' + winwidth + ',height=' + winheight + ',scrollbars=yes,status=yes,resizable=yes,'
var left = 0;
var top = 0;
if (window.resizeTo && navigator.userAgent.indexOf("Opera") == -1) {
var sizer = window.open("", "", "left=" + left + ",top=" + top + "," + windowprops);
sizer.location = website;
}
else
window.open(website, 'mywindow');
} | JavaScript |
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;b.axis!==void 0&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);b.wheelDeltaY!==void 0&&(g=b.wheelDeltaY/120);b.wheelDeltaX!==void 0&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]=
d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,false);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery); | JavaScript |
/**
* jQuery Geocoding and Places Autocomplete Plugin - V 1.4
*
* @author Martin Kleppe <kleppe@ubilabs.net>, 2012
* @author Ubilabs http://ubilabs.net, 2012
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
// # $.geocomplete()
// ## jQuery Geocoding and Places Autocomplete Plugin - V 1.4
//
// * https://github.com/ubilabs/geocomplete/
// * by Martin Kleppe <kleppe@ubilabs.net>
;(function($, window, document, undefined){
// ## Options
// The default options for this plugin.
//
// * `map` - Might be a selector, an jQuery object or a DOM element. Default is `false` which shows no map.
// * `details` - The container that should be populated with data. Defaults to `false` which ignores the setting.
// * `location` - Location to initialize the map on. Might be an address `string` or an `array` with [latitude, longitude] or a `google.maps.LatLng`object. Default is `false` which shows a blank map.
// * `bounds` - Whether to snap geocode search to map bounds. Default: `true` if false search globally. Alternatively pass a custom `LatLngBounds object.
// * `detailsAttribute` - The attribute's name to use as an indicator. Default: `"name"`
// * `mapOptions` - Options to pass to the `google.maps.Map` constructor. See the full list [here](http://code.google.com/apis/maps/documentation/javascript/reference.html#MapOptions).
// * `mapOptions.zoom` - The inital zoom level. Default: `14`
// * `mapOptions.scrollwheel` - Whether to enable the scrollwheel to zoom the map. Default: `false`
// * `mapOptions.mapTypeId` - The map type. Default: `"roadmap"`
// * `markerOptions` - The options to pass to the `google.maps.Marker` constructor. See the full list [here](http://code.google.com/apis/maps/documentation/javascript/reference.html#MarkerOptions).
// * `markerOptions.draggable` - If the marker is draggable. Default: `false`. Set to true to enable dragging.
// * `markerOptions.disabled` - Do not show marker. Default: `false`. Set to true to disable marker.
// * `maxZoom` - The maximum zoom level too zoom in after a geocoding response. Default: `16`
// * `types` - An array containing one or more of the supported types for the places request. Default: `['geocode']` See the full list [here](http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_requests).
var defaults = {
bounds: true,
country: null,
map: false,
details: false,
detailsAttribute: "name",
location: false,
mapOptions: {
zoom: 14,
scrollwheel: false,
mapTypeId: "roadmap"
},
markerOptions: {
draggable: false
},
maxZoom: 16,
types: ['geocode']
};
// See: [Geocoding Types](https://developers.google.com/maps/documentation/geocoding/#Types)
// on Google Developers.
var componentTypes = ("street_address route intersection political " +
"country administrative_area_level_1 administrative_area_level_2 " +
"administrative_area_level_3 colloquial_area locality sublocality " +
"neighborhood premise subpremise postal_code natural_feature airport " +
"park point_of_interest post_box street_number floor room " +
"lat lng viewport location " +
"formatted_address location_type bounds").split(" ");
// See: [Places Details Responses](https://developers.google.com/maps/documentation/javascript/places#place_details_responses)
// on Google Developers.
var placesDetails = ("id url website vicinity reference name rating " +
"international_phone_number icon formatted_phone_number").split(" ");
// The actual plugin constructor.
function GeoComplete(input, options) {
this.options = $.extend(true, {}, defaults, options);
this.input = input;
this.$input = $(input);
this._defaults = defaults;
this._name = 'geocomplete';
this.init();
}
// Initialize all parts of the plugin.
$.extend(GeoComplete.prototype, {
init: function(){
this.initMap();
this.initMarker();
this.initGeocoder();
this.initDetails();
this.initLocation();
},
// Initialize the map but only if the option `map` was set.
// This will create a `map` within the given container
// using the provided `mapOptions` or link to the existing map instance.
initMap: function(){
if (!this.options.map){ return; }
if (typeof this.options.map.setCenter == "function"){
this.map = this.options.map;
return;
}
this.map = new google.maps.Map(
$(this.options.map)[0],
this.options.mapOptions
);
},
// Add a marker with the provided `markerOptions` but only
// if the option was set. Additionally it listens for the `dragend` event
// to notify the plugin about changes.
initMarker: function(){
if (!this.map){ return; }
var options = $.extend(this.options.markerOptions, { map: this.map });
if (options.disabled){ return; }
this.marker = new google.maps.Marker(options);
google.maps.event.addListener(
this.marker,
'dragend',
$.proxy(this.markerDragged, this)
);
},
// Associate the input with the autocompleter and create a geocoder
// to fall back when the autocompleter does not return a value.
initGeocoder: function(){
var options = {
types: this.options.types,
bounds: this.options.bounds === true ? null : this.options.bounds,
componentRestrictions: this.options.componentRestrictions
};
if (this.options.country){
options.componentRestrictions = {country: this.options.country}
}
this.autocomplete = new google.maps.places.Autocomplete(
this.input, options
);
this.geocoder = new google.maps.Geocoder();
// Bind autocomplete to map bounds but only if there is a map
// and `options.bindToMap` is set to true.
if (this.map && this.options.bounds === true){
this.autocomplete.bindTo('bounds', this.map);
}
// Watch `place_changed` events on the autocomplete input field.
google.maps.event.addListener(
this.autocomplete,
'place_changed',
$.proxy(this.placeChanged, this)
);
// Prevent parent form from being submitted if user hit enter.
this.$input.keypress(function(event){
if (event.keyCode === 13){ return false; }
});
// Listen for "geocode" events and trigger find action.
this.$input.bind("geocode", $.proxy(function(){
this.find();
}, this));
},
// Prepare a given DOM structure to be populated when we got some data.
// This will cycle through the list of component types and map the
// corresponding elements.
initDetails: function(){
if (!this.options.details){ return; }
var $details = $(this.options.details),
attribute = this.options.detailsAttribute,
details = {};
function setDetail(value){
details[value] = $details.find("[" + attribute + "=" + value + "]");
}
$.each(componentTypes, function(index, key){
setDetail(key);
setDetail(key + "_short");
});
$.each(placesDetails, function(index, key){
setDetail(key);
});
this.$details = $details;
this.details = details;
},
// Set the initial location of the plugin if the `location` options was set.
// This method will care about converting the value into the right format.
initLocation: function() {
var location = this.options.location, latLng;
if (!location) { return; }
if (typeof location == 'string') {
this.find(location);
return;
}
if (location instanceof Array) {
latLng = new google.maps.LatLng(location[0], location[1]);
}
if (location instanceof google.maps.LatLng){
latLng = location;
}
if (latLng){
if (this.map){ this.map.setCenter(latLng); }
}
},
// Look up a given address. If no `address` was specified it uses
// the current value of the input.
find: function(address){
this.geocode({
address: address || this.$input.val()
});
},
// Requests details about a given location.
// Additionally it will bias the requests to the provided bounds.
geocode: function(request){
if (this.options.bounds && !request.bounds){
if (this.options.bounds === true){
request.bounds = this.map && this.map.getBounds();
} else {
request.bounds = this.options.bounds;
}
}
if (this.options.country){
request.region = this.options.country;
}
this.geocoder.geocode(request, $.proxy(this.handleGeocode, this));
},
// Handles the geocode response. If more than one results was found
// it triggers the "geocode:multiple" events. If there was an error
// the "geocode:error" event is fired.
handleGeocode: function(results, status){
if (status === google.maps.GeocoderStatus.OK) {
var result = results[0];
this.$input.val(result.formatted_address);
this.update(result);
if (results.length > 1){
this.trigger("geocode:multiple", results);
}
} else {
this.trigger("geocode:error", status);
}
},
// Triggers a given `event` with optional `arguments` on the input.
trigger: function(event, argument){
this.$input.trigger(event, [argument]);
},
// Set the map to a new center by passing a `geometry`.
// If the geometry has a viewport, the map zooms out to fit the bounds.
// Additionally it updates the marker position.
center: function(geometry){
if (geometry.viewport){
this.map.fitBounds(geometry.viewport);
if (this.map.getZoom() > this.options.maxZoom){
this.map.setZoom(this.options.maxZoom);
}
} else {
this.map.setZoom(this.options.maxZoom);
this.map.setCenter(geometry.location);
}
if (this.marker){
this.marker.setPosition(geometry.location);
this.marker.setAnimation(this.options.markerOptions.animation);
}
},
// Update the elements based on a single places or geoocoding response
// and trigger the "geocode:result" event on the input.
update: function(result){
if (this.map){
this.center(result.geometry);
}
if (this.$details){
this.fillDetails(result);
}
this.trigger("geocode:result", result);
},
// Populate the provided elements with new `result` data.
// This will lookup all elements that has an attribute with the given
// component type.
fillDetails: function(result){
var data = {},
geometry = result.geometry,
viewport = geometry.viewport,
bounds = geometry.bounds;
// Create a simplified version of the address components.
$.each(result.address_components, function(index, object){
var name = object.types[0];
data[name] = object.long_name;
data[name + "_short"] = object.short_name;
});
// Add properties of the places details.
$.each(placesDetails, function(index, key){
data[key] = result[key];
});
// Add infos about the address and geometry.
$.extend(data, {
formatted_address: result.formatted_address,
location_type: geometry.location_type || "PLACES",
viewport: viewport,
bounds: bounds,
location: geometry.location,
lat: geometry.location.lat(),
lng: geometry.location.lng()
});
// Set the values for all details.
$.each(this.details, $.proxy(function(key, $detail){
var value = data[key];
this.setDetail($detail, value);
}, this));
this.data = data;
},
// Assign a given `value` to a single `$element`.
// If the element is an input, the value is set, otherwise it updates
// the text content.
setDetail: function($element, value){
if (value === undefined){
value = "";
} else if (typeof value.toUrlValue == "function"){
value = value.toUrlValue();
}
if ($element.is(":input")){
$element.val(value);
} else {
$element.text(value);
}
},
// Fire the "geocode:dragged" event and pass the new position.
markerDragged: function(event){
this.trigger("geocode:dragged", event.latLng);
},
// Restore the old position of the marker to the last now location.
resetMarker: function(){
this.marker.setPosition(this.data.location);
this.setDetail(this.details.lat, this.data.location.lat());
this.setDetail(this.details.lng, this.data.location.lng());
},
// Update the plugin after the user has selected an autocomplete entry.
// If the place has no geometry it passes it to the geocoder.
placeChanged: function(){
var place = this.autocomplete.getPlace();
if (!place.geometry){
this.find(place.name);
} else {
this.update(place);
}
}
});
// A plugin wrapper around the constructor.
// Pass `options` with all settings that are different from the default.
// The attribute is used to prevent multiple instantiations of the plugin.
$.fn.geocomplete = function(options) {
var attribute = 'plugin_geocomplete';
// If you call `.geocomplete()` with a string as the first parameter
// it returns the corresponding property or calls the method with the
// following arguments.
if (typeof options == "string"){
var instance = $(this).data(attribute) || $(this).geocomplete().data(attribute),
prop = instance[options];
if (typeof prop == "function"){
prop.apply(instance, Array.prototype.slice.call(arguments, 1));
return $(this);
} else {
if (arguments.length == 2){
prop = arguments[1];
}
return prop;
}
} else {
return this.each(function() {
// Prevent against multiple instantiations.
var instance = $.data(this, attribute);
if (!instance) {
instance = new GeoComplete( this, options )
$.data(this, attribute, instance);
}
});
}
};
})( jQuery, window, document );
| JavaScript |
/************************
jquery-timepicker
http://jonthornton.github.com/jquery-timepicker/
requires jQuery 1.7+
************************/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var _baseDate = _generateBaseDate();
var _ONE_DAY = 86400;
var _defaults = {
className: null,
minTime: null,
maxTime: null,
durationTime: null,
step: 30,
showDuration: false,
timeFormat: 'g:ia',
scrollDefaultNow: false,
scrollDefaultTime: false,
selectOnBlur: false,
forceRoundTime: false,
appendTo: 'body'
};
var _lang = {
decimal: '.',
mins: 'mins',
hr: 'hr',
hrs: 'hrs'
};
var methods =
{
init: function(options)
{
return this.each(function()
{
var self = $(this);
// convert dropdowns to text input
if (self[0].tagName == 'SELECT') {
var attrs = { 'type': 'text', 'value': self.val() };
var raw_attrs = self[0].attributes;
for (var i=0; i < raw_attrs.length; i++) {
attrs[raw_attrs[i].nodeName] = raw_attrs[i].nodeValue;
}
var input = $('<input />', attrs);
self.replaceWith(input);
self = input;
}
var settings = $.extend({}, _defaults);
if (options) {
settings = $.extend(settings, options);
}
if (settings.minTime) {
settings.minTime = _time2int(settings.minTime);
}
if (settings.maxTime) {
settings.maxTime = _time2int(settings.maxTime);
}
if (settings.durationTime) {
settings.durationTime = _time2int(settings.durationTime);
}
if (settings.lang) {
_lang = $.extend(_lang, settings.lang);
}
self.data('timepicker-settings', settings);
self.prop('autocomplete', 'off');
self.on('click.timepicker focus.timepicker', methods.show);
self.on('blur.timepicker', _formatValue);
self.on('keydown.timepicker', _keyhandler);
self.addClass('ui-timepicker-input');
_formatValue.call(self.get(0));
});
},
show: function(e)
{
var self = $(this);
if ('ontouchstart' in document) {
// block the keyboard on mobile devices
self.blur();
}
var list = self.data('timepicker-list');
// check if input is readonly
if (self.prop('readonly')) {
return;
}
// check if list needs to be rendered
if (!list || list.length === 0) {
_render(self);
list = self.data('timepicker-list');
}
// check if a flag was set to close this picker
if (self.hasClass('ui-timepicker-hideme')) {
self.removeClass('ui-timepicker-hideme');
list.hide();
return;
}
if (list.is(':visible')) {
return;
}
// make sure other pickers are hidden
methods.hide();
if ((self.offset().top + self.outerHeight(true) + list.outerHeight()) > $(window).height() + $(window).scrollTop()) {
// position the dropdown on top
list.css({ 'left':(self.offset().left), 'top': self.offset().top - list.outerHeight() });
} else {
// put it under the input
list.css({ 'left':(self.offset().left), 'top': self.offset().top + self.outerHeight() });
}
list.show();
var settings = self.data('timepicker-settings');
// position scrolling
var selected = list.find('.ui-timepicker-selected');
if (!selected.length) {
if (self.val()) {
selected = _findRow(self, list, _time2int(self.val()));
} else if (settings.scrollDefaultNow) {
selected = _findRow(self, list, _time2int(new Date()));
} else if (settings.scrollDefaultTime !== false) {
selected = _findRow(self, list, _time2int(settings.scrollDefaultTime));
}
}
if (selected && selected.length) {
var topOffset = list.scrollTop() + selected.position().top - selected.outerHeight();
list.scrollTop(topOffset);
} else {
list.scrollTop(0);
}
_attachCloseHandler();
self.trigger('showTimepicker');
},
hide: function(e)
{
$('.ui-timepicker-list:visible').each(function() {
var list = $(this);
var self = list.data('timepicker-input');
var settings = self.data('timepicker-settings');
if (settings && settings.selectOnBlur) {
_selectValue(self);
}
list.hide();
self.trigger('hideTimepicker');
});
},
option: function(key, value)
{
var self = $(this);
var settings = self.data('timepicker-settings');
var list = self.data('timepicker-list');
if (typeof key == 'object') {
settings = $.extend(settings, key);
} else if (typeof key == 'string' && typeof value != 'undefined') {
settings[key] = value;
} else if (typeof key == 'string') {
return settings[key];
}
if (settings.minTime) {
settings.minTime = _time2int(settings.minTime);
}
if (settings.maxTime) {
settings.maxTime = _time2int(settings.maxTime);
}
if (settings.durationTime) {
settings.durationTime = _time2int(settings.durationTime);
}
self.data('timepicker-settings', settings);
if (list) {
list.remove();
self.data('timepicker-list', false);
}
},
getSecondsFromMidnight: function()
{
return _time2int($(this).val());
},
getTime: function()
{
return new Date(_baseDate.valueOf() + (_time2int($(this).val())*1000));
},
setTime: function(value)
{
var self = $(this);
var prettyTime = _int2time(_time2int(value), self.data('timepicker-settings').timeFormat);
self.val(prettyTime);
},
remove: function()
{
var self = $(this);
// check if this element is a timepicker
if (!self.hasClass('ui-timepicker-input')) {
return;
}
self.removeAttr('autocomplete', 'off');
self.removeClass('ui-timepicker-input');
self.removeData('timepicker-settings');
self.off('.timepicker');
// timepicker-list won't be present unless the user has interacted with this timepicker
if (self.data('timepicker-list')) {
self.data('timepicker-list').remove();
}
self.removeData('timepicker-list');
}
};
// private methods
function _render(self)
{
var settings = self.data('timepicker-settings');
var list = self.data('timepicker-list');
if (list && list.length) {
list.remove();
self.data('timepicker-list', false);
}
list = $('<ul />', {
'tabindex': -1,
'class': 'ui-timepicker-list'
});
if (settings.className) {
list.addClass(settings.className);
}
list.css({'display':'none', 'position': 'absolute' });
if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) {
list.addClass('ui-timepicker-with-duration');
}
var durStart = (settings.durationTime !== null) ? settings.durationTime : settings.minTime;
var start = (settings.minTime !== null) ? settings.minTime : 0;
var end = (settings.maxTime !== null) ? settings.maxTime : (start + _ONE_DAY - 1);
if (end <= start) {
// make sure the end time is greater than start time, otherwise there will be no list to show
end += _ONE_DAY;
}
for (var i=start; i <= end; i += settings.step*60) {
var timeInt = i%_ONE_DAY;
var row = $('<li />');
row.data('time', timeInt);
row.text(_int2time(timeInt, settings.timeFormat));
if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) {
var duration = $('<span />');
duration.addClass('ui-timepicker-duration');
duration.text(' ('+_int2duration(i - durStart)+')');
row.append(duration);
}
list.append(row);
}
list.data('timepicker-input', self);
self.data('timepicker-list', list);
var appendTo = settings.appendTo;
if (typeof appendTo === 'string') {
appendTo = $(appendTo);
} else if (typeof appendTo === 'function') {
appendTo = appendTo(self);
}
appendTo.append(list);
_setSelected(self, list);
list.on('click', 'li', function(e) {
self.addClass('ui-timepicker-hideme');
self[0].focus();
// make sure only the clicked row is selected
list.find('li').removeClass('ui-timepicker-selected');
$(this).addClass('ui-timepicker-selected');
_selectValue(self);
list.hide();
});
}
function _generateBaseDate()
{
var _baseDate = new Date();
var _currentTimezoneOffset = _baseDate.getTimezoneOffset()*60000;
_baseDate.setHours(0); _baseDate.setMinutes(0); _baseDate.setSeconds(0);
var _baseDateTimezoneOffset = _baseDate.getTimezoneOffset()*60000;
return new Date(_baseDate.valueOf() - _baseDateTimezoneOffset + _currentTimezoneOffset);
}
function _attachCloseHandler()
{
if ('ontouchstart' in document) {
$('body').on('touchstart.ui-timepicker', _closeHandler);
} else {
$('body').on('mousedown.ui-timepicker', _closeHandler);
$(window).on('scroll.ui-timepicker', _closeHandler);
}
}
// event handler to decide whether to close timepicker
function _closeHandler(e)
{
var target = $(e.target);
var input = target.closest('.ui-timepicker-input');
if (input.length === 0 && target.closest('.ui-timepicker-list').length === 0) {
methods.hide();
}
$('body').unbind('.ui-timepicker');
$(window).unbind('.ui-timepicker');
}
function _findRow(self, list, value)
{
if (!value && value !== 0) {
return false;
}
var settings = self.data('timepicker-settings');
var out = false;
var halfStep = settings.step*30;
// loop through the menu items
list.find('li').each(function(i, obj) {
var jObj = $(obj);
var offset = jObj.data('time') - value;
// check if the value is less than half a step from each row
if (Math.abs(offset) < halfStep || offset == halfStep) {
out = jObj;
return false;
}
});
return out;
}
function _setSelected(self, list)
{
var timeValue = _time2int(self.val());
var selected = _findRow(self, list, timeValue);
if (selected) selected.addClass('ui-timepicker-selected');
}
function _formatValue()
{
if (this.value === '') {
return;
}
var self = $(this);
var seconds = _time2int(this.value);
if (seconds === null) {
self.trigger('timeFormatError');
return;
}
var settings = self.data('timepicker-settings');
if (settings.forceRoundTime) {
var offset = seconds % (settings.step*60); // step is in minutes
if (offset >= settings.step*30) {
// if offset is larger than a half step, round up
seconds += (settings.step*60) - offset;
} else {
// round down
seconds -= offset;
}
}
var prettyTime = _int2time(seconds, settings.timeFormat);
self.val(prettyTime);
}
function _keyhandler(e)
{
var self = $(this);
var list = self.data('timepicker-list');
if (!list.is(':visible')) {
if (e.keyCode == 40) {
self.focus();
} else {
return true;
}
}
switch (e.keyCode) {
case 13: // return
_selectValue(self);
methods.hide.apply(this);
e.preventDefault();
return false;
case 38: // up
var selected = list.find('.ui-timepicker-selected');
if (!selected.length) {
list.children().each(function(i, obj) {
if ($(obj).position().top > 0) {
selected = $(obj);
return false;
}
});
selected.addClass('ui-timepicker-selected');
} else if (!selected.is(':first-child')) {
selected.removeClass('ui-timepicker-selected');
selected.prev().addClass('ui-timepicker-selected');
if (selected.prev().position().top < selected.outerHeight()) {
list.scrollTop(list.scrollTop() - selected.outerHeight());
}
}
break;
case 40: // down
selected = list.find('.ui-timepicker-selected');
if (selected.length === 0) {
list.children().each(function(i, obj) {
if ($(obj).position().top > 0) {
selected = $(obj);
return false;
}
});
selected.addClass('ui-timepicker-selected');
} else if (!selected.is(':last-child')) {
selected.removeClass('ui-timepicker-selected');
selected.next().addClass('ui-timepicker-selected');
if (selected.next().position().top + 2*selected.outerHeight() > list.outerHeight()) {
list.scrollTop(list.scrollTop() + selected.outerHeight());
}
}
break;
case 27: // escape
list.find('li').removeClass('ui-timepicker-selected');
list.hide();
break;
case 9: //tab
methods.hide();
break;
case 16:
case 17:
case 18:
case 19:
case 20:
case 33:
case 34:
case 35:
case 36:
case 37:
case 39:
case 45:
return;
default:
list.find('li').removeClass('ui-timepicker-selected');
return;
}
}
function _selectValue(self)
{
var settings = self.data('timepicker-settings');
var list = self.data('timepicker-list');
var timeValue = null;
var cursor = list.find('.ui-timepicker-selected');
if (cursor.length) {
// selected value found
timeValue = cursor.data('time');
} else if (self.val()) {
// no selected value; fall back on input value
timeValue = _time2int(self.val());
_setSelected(self, list);
}
if (timeValue !== null) {
var timeString = _int2time(timeValue, settings.timeFormat);
self.val(timeString);
}
self.trigger('change').trigger('changeTime');
}
function _int2duration(seconds)
{
var minutes = Math.round(seconds/60);
var duration;
if (Math.abs(minutes) < 60) {
duration = [minutes, _lang.mins];
} else if (minutes == 60) {
duration = ['1', _lang.hr];
} else {
var hours = (minutes/60).toFixed(1);
if (_lang.decimal != '.') hours = hours.replace('.', _lang.decimal);
duration = [hours, _lang.hrs];
}
return duration.join(' ');
}
function _int2time(seconds, format)
{
if (seconds === null) {
return;
}
var time = new Date(_baseDate.valueOf() + (seconds*1000));
var output = '';
var hour, code;
for (var i=0; i<format.length; i++) {
code = format.charAt(i);
switch (code) {
case 'a':
output += (time.getHours() > 11) ? 'pm' : 'am';
break;
case 'A':
output += (time.getHours() > 11) ? 'PM' : 'AM';
break;
case 'g':
hour = time.getHours() % 12;
output += (hour === 0) ? '12' : hour;
break;
case 'G':
output += time.getHours();
break;
case 'h':
hour = time.getHours() % 12;
if (hour !== 0 && hour < 10) {
hour = '0'+hour;
}
output += (hour === 0) ? '12' : hour;
break;
case 'H':
hour = time.getHours();
output += (hour > 9) ? hour : '0'+hour;
break;
case 'i':
var minutes = time.getMinutes();
output += (minutes > 9) ? minutes : '0'+minutes;
break;
case 's':
seconds = time.getSeconds();
output += (seconds > 9) ? seconds : '0'+seconds;
break;
default:
output += code;
}
}
return output;
}
function _time2int(timeString)
{
if (timeString === '') return null;
if (timeString+0 == timeString) return timeString;
if (typeof(timeString) == 'object') {
timeString = timeString.getHours()+':'+timeString.getMinutes()+':'+timeString.getSeconds();
}
var d = new Date(0);
var time = timeString.toLowerCase().match(/(\d{1,2})(?::(\d{1,2}))?(?::(\d{2}))?\s*([pa]?)/);
if (!time) {
return null;
}
var hour = parseInt(time[1]*1, 10);
var hours;
if (time[4]) {
if (hour == 12) {
hours = (time[4] == 'p') ? 12 : 0;
} else {
hours = (hour + (time[4] == 'p' ? 12 : 0));
}
} else {
hours = hour;
}
var minutes = ( time[2]*1 || 0 );
var seconds = ( time[3]*1 || 0 );
return hours*3600 + minutes*60 + seconds;
}
// Plugin entry
$.fn.timepicker = function(method)
{
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.timepicker"); }
};
}));
| JavaScript |
/*!
* Thumbnail helper for fancyBox
* version: 1.0.7 (Mon, 01 Oct 2012)
* @requires fancyBox v2.0 or later
*
* Usage:
* $(".fancybox").fancybox({
* helpers : {
* thumbs: {
* width : 50,
* height : 50
* }
* }
* });
*
*/
(function ($) {
//Shortcut for fancyBox object
var F = $.fancybox;
//Add helper object
F.helpers.thumbs = {
defaults : {
width : 50, // thumbnail width
height : 50, // thumbnail height
position : 'bottom', // 'top' or 'bottom'
source : function ( item ) { // function to obtain the URL of the thumbnail image
var href;
if (item.element) {
href = $(item.element).find('img').attr('src');
}
if (!href && item.type === 'image' && item.href) {
href = item.href;
}
return href;
}
},
wrap : null,
list : null,
width : 0,
init: function (opts, obj) {
var that = this,
list,
thumbWidth = opts.width,
thumbHeight = opts.height,
thumbSource = opts.source;
//Build list structure
list = '';
for (var n = 0; n < obj.group.length; n++) {
list += '<li><a style="width:' + thumbWidth + 'px;height:' + thumbHeight + 'px;" href="javascript:jQuery.fancybox.jumpto(' + n + ');"></a></li>';
}
this.wrap = $('<div id="fancybox-thumbs"></div>').addClass(opts.position).appendTo('body');
this.list = $('<ul>' + list + '</ul>').appendTo(this.wrap);
//Load each thumbnail
$.each(obj.group, function (i) {
var href = thumbSource( obj.group[ i ] );
if (!href) {
return;
}
$("<img />").load(function () {
var width = this.width,
height = this.height,
widthRatio, heightRatio, parent;
if (!that.list || !width || !height) {
return;
}
//Calculate thumbnail width/height and center it
widthRatio = width / thumbWidth;
heightRatio = height / thumbHeight;
parent = that.list.children().eq(i).find('a');
if (widthRatio >= 1 && heightRatio >= 1) {
if (widthRatio > heightRatio) {
width = Math.floor(width / heightRatio);
height = thumbHeight;
} else {
width = thumbWidth;
height = Math.floor(height / widthRatio);
}
}
$(this).css({
width : width,
height : height,
top : Math.floor(thumbHeight / 2 - height / 2),
left : Math.floor(thumbWidth / 2 - width / 2)
});
parent.width(thumbWidth).height(thumbHeight);
$(this).hide().appendTo(parent).fadeIn(300);
}).attr('src', href);
});
//Set initial width
this.width = this.list.children().eq(0).outerWidth(true);
this.list.width(this.width * (obj.group.length + 1)).css('left', Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5)));
},
beforeLoad: function (opts, obj) {
//Remove self if gallery do not have at least two items
if (obj.group.length < 2) {
obj.helpers.thumbs = false;
return;
}
//Increase bottom margin to give space for thumbs
obj.margin[ opts.position === 'top' ? 0 : 2 ] += ((opts.height) + 15);
},
afterShow: function (opts, obj) {
//Check if exists and create or update list
if (this.list) {
this.onUpdate(opts, obj);
} else {
this.init(opts, obj);
}
//Set active element
this.list.children().removeClass('active').eq(obj.index).addClass('active');
},
//Center list
onUpdate: function (opts, obj) {
if (this.list) {
this.list.stop(true).animate({
'left': Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5))
}, 150);
}
},
beforeClose: function () {
if (this.wrap) {
this.wrap.remove();
}
this.wrap = null;
this.list = null;
this.width = 0;
}
}
}(jQuery)); | JavaScript |
/*!
* Media helper for fancyBox
* version: 1.0.5 (Tue, 23 Oct 2012)
* @requires fancyBox v2.0 or later
*
* Usage:
* $(".fancybox").fancybox({
* helpers : {
* media: true
* }
* });
*
* Set custom URL parameters:
* $(".fancybox").fancybox({
* helpers : {
* media: {
* youtube : {
* params : {
* autoplay : 0
* }
* }
* }
* }
* });
*
* Or:
* $(".fancybox").fancybox({,
* helpers : {
* media: true
* },
* youtube : {
* autoplay: 0
* }
* });
*
* Supports:
*
* Youtube
* http://www.youtube.com/watch?v=opj24KnzrWo
* http://www.youtube.com/embed/opj24KnzrWo
* http://youtu.be/opj24KnzrWo
* Vimeo
* http://vimeo.com/40648169
* http://vimeo.com/channels/staffpicks/38843628
* http://vimeo.com/groups/surrealism/videos/36516384
* http://player.vimeo.com/video/45074303
* Metacafe
* http://www.metacafe.com/watch/7635964/dr_seuss_the_lorax_movie_trailer/
* http://www.metacafe.com/watch/7635964/
* Dailymotion
* http://www.dailymotion.com/video/xoytqh_dr-seuss-the-lorax-premiere_people
* Twitvid
* http://twitvid.com/QY7MD
* Twitpic
* http://twitpic.com/7p93st
* Instagram
* http://instagr.am/p/IejkuUGxQn/
* http://instagram.com/p/IejkuUGxQn/
* Google maps
* http://maps.google.com/maps?q=Eiffel+Tower,+Avenue+Gustave+Eiffel,+Paris,+France&t=h&z=17
* http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16
* http://maps.google.com/?ll=48.859463,2.292626&spn=0.000965,0.002642&t=m&z=19&layer=c&cbll=48.859524,2.292532&panoid=YJ0lq28OOy3VT2IqIuVY0g&cbp=12,151.58,,0,-15.56
*/
(function ($) {
"use strict";
//Shortcut for fancyBox object
var F = $.fancybox,
format = function( url, rez, params ) {
params = params || '';
if ( $.type( params ) === "object" ) {
params = $.param(params, true);
}
$.each(rez, function(key, value) {
url = url.replace( '$' + key, value || '' );
});
if (params.length) {
url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params;
}
return url;
};
//Add helper object
F.helpers.media = {
defaults : {
youtube : {
matcher : /(youtube\.com|youtu\.be)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i,
params : {
autoplay : 1,
autohide : 1,
fs : 1,
rel : 0,
hd : 1,
wmode : 'opaque',
enablejsapi : 1
},
type : 'iframe',
url : '//www.youtube.com/embed/$3'
},
vimeo : {
matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/,
params : {
autoplay : 1,
hd : 1,
show_title : 1,
show_byline : 1,
show_portrait : 0,
fullscreen : 1
},
type : 'iframe',
url : '//player.vimeo.com/video/$1'
},
metacafe : {
matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/,
params : {
autoPlay : 'yes'
},
type : 'swf',
url : function( rez, params, obj ) {
obj.swf.flashVars = 'playerVars=' + $.param( params, true );
return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf';
}
},
dailymotion : {
matcher : /dailymotion.com\/video\/(.*)\/?(.*)/,
params : {
additionalInfos : 0,
autoStart : 1
},
type : 'swf',
url : '//www.dailymotion.com/swf/video/$1'
},
twitvid : {
matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i,
params : {
autoplay : 0
},
type : 'iframe',
url : '//www.twitvid.com/embed.php?guid=$1'
},
twitpic : {
matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i,
type : 'image',
url : '//twitpic.com/show/full/$1/'
},
instagram : {
matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i,
type : 'image',
url : '//$1/p/$2/media/'
},
google_maps : {
matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i,
type : 'iframe',
url : function( rez ) {
return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed');
}
}
},
beforeLoad : function(opts, obj) {
var url = obj.href || '',
type = false,
what,
item,
rez,
params;
for (what in opts) {
item = opts[ what ];
rez = url.match( item.matcher );
if (rez) {
type = item.type;
params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null));
url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params );
break;
}
}
if (type) {
obj.href = url;
obj.type = type;
obj.autoHeight = false;
}
}
};
}(jQuery)); | JavaScript |
/*!
* Buttons helper for fancyBox
* version: 1.0.5 (Mon, 15 Oct 2012)
* @requires fancyBox v2.0 or later
*
* Usage:
* $(".fancybox").fancybox({
* helpers : {
* buttons: {
* position : 'top'
* }
* }
* });
*
*/
(function ($) {
//Shortcut for fancyBox object
var F = $.fancybox;
//Add helper object
F.helpers.buttons = {
defaults : {
skipSingle : false, // disables if gallery contains single image
position : 'top', // 'top' or 'bottom'
tpl : '<div id="fancybox-buttons"><ul><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnToggle" title="Toggle size" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:jQuery.fancybox.close();"></a></li></ul></div>'
},
list : null,
buttons: null,
beforeLoad: function (opts, obj) {
//Remove self if gallery do not have at least two items
if (opts.skipSingle && obj.group.length < 2) {
obj.helpers.buttons = false;
obj.closeBtn = true;
return;
}
//Increase top margin to give space for buttons
obj.margin[ opts.position === 'bottom' ? 2 : 0 ] += 30;
},
onPlayStart: function () {
if (this.buttons) {
this.buttons.play.attr('title', 'Pause slideshow').addClass('btnPlayOn');
}
},
onPlayEnd: function () {
if (this.buttons) {
this.buttons.play.attr('title', 'Start slideshow').removeClass('btnPlayOn');
}
},
afterShow: function (opts, obj) {
var buttons = this.buttons;
if (!buttons) {
this.list = $(opts.tpl).addClass(opts.position).appendTo('body');
buttons = {
prev : this.list.find('.btnPrev').click( F.prev ),
next : this.list.find('.btnNext').click( F.next ),
play : this.list.find('.btnPlay').click( F.play ),
toggle : this.list.find('.btnToggle').click( F.toggle )
}
}
//Prev
if (obj.index > 0 || obj.loop) {
buttons.prev.removeClass('btnDisabled');
} else {
buttons.prev.addClass('btnDisabled');
}
//Next / Play
if (obj.loop || obj.index < obj.group.length - 1) {
buttons.next.removeClass('btnDisabled');
buttons.play.removeClass('btnDisabled');
} else {
buttons.next.addClass('btnDisabled');
buttons.play.addClass('btnDisabled');
}
this.buttons = buttons;
this.onUpdate(opts, obj);
},
onUpdate: function (opts, obj) {
var toggle;
if (!this.buttons) {
return;
}
toggle = this.buttons.toggle.removeClass('btnDisabled btnToggleOn');
//Size toggle button
if (obj.canShrink) {
toggle.addClass('btnToggleOn');
} else if (!obj.canExpand) {
toggle.addClass('btnDisabled');
}
},
beforeClose: function () {
if (this.list) {
this.list.remove();
}
this.list = null;
this.buttons = null;
}
};
}(jQuery)); | JavaScript |
/*
SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
;var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;
if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;
X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);
ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0;}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");
if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac};
}(),k=function(){if(!M.w3){return;}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f();
}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false);}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);
f();}});if(O==top){(function(){if(J){return;}try{j.documentElement.doScroll("left");}catch(X){setTimeout(arguments.callee,0);return;}f();})();}}if(M.wk){(function(){if(J){return;
}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return;}f();})();}s(f);}}();function f(){if(J){return;}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));
Z.parentNode.removeChild(Z);}catch(aa){return;}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]();}}function K(X){if(J){X();}else{U[U.length]=X;}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false);
}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false);}else{if(typeof O.attachEvent!=D){i(O,"onload",Y);}else{if(typeof O.onload=="function"){var X=O.onload;
O.onload=function(){X();Y();};}else{O.onload=Y;}}}}}function h(){if(T){V();}else{H();}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);
aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");
M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return;}}X.removeChild(aa);Z=null;H();
})();}else{H();}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);
if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa);}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;
ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class");}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align");
}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value");
}}P(ai,ah,Y,ab);}else{p(ae);if(ab){ab(aa);}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z;}ab(aa);}}}}}function z(aa){var X=null;
var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y;}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z;}}}return X;}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312);
}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null;}else{l=ae;Q=X;}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310";
}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137";}j.title=j.title.slice(0,47)+" - Flash Player Installation";
var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac;
}else{ab.flashvars=ac;}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";
(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae);}else{setTimeout(arguments.callee,10);}})();}u(aa,ab,X);}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");
Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y);}else{setTimeout(arguments.callee,10);
}})();}else{Y.parentNode.replaceChild(g(Y),Y);}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML;}else{var Y=ab.getElementsByTagName(r)[0];
if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true));
}}}}}return aa;}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X;}if(aa){if(typeof ai.id==D){ai.id=Y;}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae];
}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"';}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"';}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />';
}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id);}else{var Z=C(r);Z.setAttribute("type",q);
for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac]);}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac]);
}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab]);}}aa.parentNode.replaceChild(Z,aa);X=Z;}}return X;}function e(Z,X,Y){var aa=C("param");
aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa);}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";
(function(){if(X.readyState==4){b(Y);}else{setTimeout(arguments.callee,10);}})();}else{X.parentNode.removeChild(X);}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null;
}}Y.parentNode.removeChild(Y);}}function c(Z){var X=null;try{X=j.getElementById(Z);}catch(Y){}return X;}function C(X){return j.createElement(X);}function i(Z,X,Y){Z.attachEvent(X,Y);
I[I.length]=[Z,X,Y];}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false;
}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return;}var aa=j.getElementsByTagName("head")[0];if(!aa){return;}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;
G=null;}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1];
}G=X;}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y);}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"));
}}}function w(Z,X){if(!m){return;}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y;}else{v("#"+Z,"visibility:"+Y);}}function L(Y){var Z=/[\\\"<>\.;]/;
var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y;}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;
for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2]);}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa]);}for(var Y in M){M[Y]=null;}M=null;for(var X in swfobject){swfobject[X]=null;
}swfobject=null;});}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;
w(ab,false);}else{if(Z){Z({success:false,id:ab});}}},getObjectById:function(X){if(M.w3){return z(X);}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};
if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al];}}aj.data=ab;
aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak];}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai];
}else{am.flashvars=ai+"="+Z[ai];}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true);}X.success=true;X.ref=an;}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);
return;}else{w(ah,true);}}if(ac){ac(X);}});}else{if(ac){ac(X);}}},switchOffAutoHideShow:function(){m=false;},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]};
},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X);}else{return undefined;}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y);
}},removeSWF:function(X){if(M.w3){y(X);}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X);}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;
if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1];}if(aa==null){return L(Z);}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)));
}}}return"";},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block";
}}if(E){E(B);}}a=false;}}};}();
/*
SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
*/
var SWFUpload;if(SWFUpload==undefined){SWFUpload=function(a){this.initSWFUpload(a)}}SWFUpload.prototype.initSWFUpload=function(b){try{this.customSettings={};this.settings=b;this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings();this.loadFlash();this.displayDebugInfo()}catch(a){delete SWFUpload.instances[this.movieName];throw a}};SWFUpload.instances={};SWFUpload.movieCount=0;SWFUpload.version="2.2.0 2009-03-25";SWFUpload.QUEUE_ERROR={QUEUE_LIMIT_EXCEEDED:-100,FILE_EXCEEDS_SIZE_LIMIT:-110,ZERO_BYTE_FILE:-120,INVALID_FILETYPE:-130};SWFUpload.UPLOAD_ERROR={HTTP_ERROR:-200,MISSING_UPLOAD_URL:-210,IO_ERROR:-220,SECURITY_ERROR:-230,UPLOAD_LIMIT_EXCEEDED:-240,UPLOAD_FAILED:-250,SPECIFIED_FILE_ID_NOT_FOUND:-260,FILE_VALIDATION_FAILED:-270,FILE_CANCELLED:-280,UPLOAD_STOPPED:-290};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.BUTTON_ACTION={SELECT_FILE:-100,SELECT_FILES:-110,START_UPLOAD:-120};SWFUpload.CURSOR={ARROW:-1,HAND:-2};SWFUpload.WINDOW_MODE={WINDOW:"window",TRANSPARENT:"transparent",OPAQUE:"opaque"};SWFUpload.completeURL=function(a){if(typeof(a)!=="string"||a.match(/^https?:\/\//i)||a.match(/^\//)){return a}var c=window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"");var b=window.location.pathname.lastIndexOf("/");if(b<=0){path="/"}else{path=window.location.pathname.substr(0,b)+"/"}return path+a};SWFUpload.prototype.initSettings=function(){this.ensureDefault=function(b,a){this.settings[b]=(this.settings[b]==undefined)?a:this.settings[b]};this.ensureDefault("upload_url","");this.ensureDefault("preserve_relative_urls",false);this.ensureDefault("file_post_name","Filedata");this.ensureDefault("post_params",{});this.ensureDefault("use_query_string",false);this.ensureDefault("requeue_on_error",false);this.ensureDefault("http_success",[]);this.ensureDefault("assume_success_timeout",0);this.ensureDefault("file_types","*.*");this.ensureDefault("file_types_description","All Files");this.ensureDefault("file_size_limit",0);this.ensureDefault("file_upload_limit",0);this.ensureDefault("file_queue_limit",0);this.ensureDefault("flash_url","swfupload.swf");this.ensureDefault("prevent_swf_caching",true);this.ensureDefault("button_image_url","");this.ensureDefault("button_width",1);this.ensureDefault("button_height",1);this.ensureDefault("button_text","");this.ensureDefault("button_text_style","color: #000000; font-size: 16pt;");this.ensureDefault("button_text_top_padding",0);this.ensureDefault("button_text_left_padding",0);this.ensureDefault("button_action",SWFUpload.BUTTON_ACTION.SELECT_FILES);this.ensureDefault("button_disabled",false);this.ensureDefault("button_placeholder_id","");this.ensureDefault("button_placeholder",null);this.ensureDefault("button_cursor",SWFUpload.CURSOR.ARROW);this.ensureDefault("button_window_mode",SWFUpload.WINDOW_MODE.WINDOW);this.ensureDefault("debug",false);this.settings.debug_enabled=this.settings.debug;this.settings.return_upload_start_handler=this.returnUploadStart;this.ensureDefault("swfupload_loaded_handler",null);this.ensureDefault("file_dialog_start_handler",null);this.ensureDefault("file_queued_handler",null);this.ensureDefault("file_queue_error_handler",null);this.ensureDefault("file_dialog_complete_handler",null);this.ensureDefault("upload_start_handler",null);this.ensureDefault("upload_progress_handler",null);this.ensureDefault("upload_error_handler",null);this.ensureDefault("upload_success_handler",null);this.ensureDefault("upload_complete_handler",null);this.ensureDefault("debug_handler",this.debugMessage);this.ensureDefault("custom_settings",{});this.customSettings=this.settings.custom_settings;if(!!this.settings.prevent_swf_caching){this.settings.flash_url=this.settings.flash_url+(this.settings.flash_url.indexOf("?")<0?"?":"&")+"preventswfcaching="+new Date().getTime()}if(!this.settings.preserve_relative_urls){this.settings.upload_url=SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url=SWFUpload.completeURL(this.settings.button_image_url)}delete this.ensureDefault};SWFUpload.prototype.loadFlash=function(){var a,b;if(document.getElementById(this.movieName)!==null){throw"ID "+this.movieName+" is already in use. The Flash Object could not be added"}a=document.getElementById(this.settings.button_placeholder_id)||this.settings.button_placeholder;if(a==undefined){throw"Could not find the placeholder element: "+this.settings.button_placeholder_id}b=document.createElement("div");b.innerHTML=this.getFlashHTML();a.parentNode.replaceChild(b.firstChild,a);if(window[this.movieName]==undefined){window[this.movieName]=this.getMovieElement()}};SWFUpload.prototype.getFlashHTML=function(){return['<object id="',this.movieName,'" type="application/x-shockwave-flash" data="',this.settings.flash_url,'" width="',this.settings.button_width,'" height="',this.settings.button_height,'" class="swfupload">','<param name="wmode" value="',this.settings.button_window_mode,'" />','<param name="movie" value="',this.settings.flash_url,'" />','<param name="quality" value="high" />','<param name="menu" value="false" />','<param name="allowScriptAccess" value="always" />','<param name="flashvars" value="'+this.getFlashVars()+'" />',"</object>"].join("")};SWFUpload.prototype.getFlashVars=function(){var b=this.buildParamString();var a=this.settings.http_success.join(",");return["movieName=",encodeURIComponent(this.movieName),"&uploadURL=",encodeURIComponent(this.settings.upload_url),"&useQueryString=",encodeURIComponent(this.settings.use_query_string),"&requeueOnError=",encodeURIComponent(this.settings.requeue_on_error),"&httpSuccess=",encodeURIComponent(a),"&assumeSuccessTimeout=",encodeURIComponent(this.settings.assume_success_timeout),"&params=",encodeURIComponent(b),"&filePostName=",encodeURIComponent(this.settings.file_post_name),"&fileTypes=",encodeURIComponent(this.settings.file_types),"&fileTypesDescription=",encodeURIComponent(this.settings.file_types_description),"&fileSizeLimit=",encodeURIComponent(this.settings.file_size_limit),"&fileUploadLimit=",encodeURIComponent(this.settings.file_upload_limit),"&fileQueueLimit=",encodeURIComponent(this.settings.file_queue_limit),"&debugEnabled=",encodeURIComponent(this.settings.debug_enabled),"&buttonImageURL=",encodeURIComponent(this.settings.button_image_url),"&buttonWidth=",encodeURIComponent(this.settings.button_width),"&buttonHeight=",encodeURIComponent(this.settings.button_height),"&buttonText=",encodeURIComponent(this.settings.button_text),"&buttonTextTopPadding=",encodeURIComponent(this.settings.button_text_top_padding),"&buttonTextLeftPadding=",encodeURIComponent(this.settings.button_text_left_padding),"&buttonTextStyle=",encodeURIComponent(this.settings.button_text_style),"&buttonAction=",encodeURIComponent(this.settings.button_action),"&buttonDisabled=",encodeURIComponent(this.settings.button_disabled),"&buttonCursor=",encodeURIComponent(this.settings.button_cursor)].join("")};SWFUpload.prototype.getMovieElement=function(){if(this.movieElement==undefined){this.movieElement=document.getElementById(this.movieName)}if(this.movieElement===null){throw"Could not find Flash element"}return this.movieElement};SWFUpload.prototype.buildParamString=function(){var c=this.settings.post_params;var b=[];if(typeof(c)==="object"){for(var a in c){if(c.hasOwnProperty(a)){b.push(encodeURIComponent(a.toString())+"="+encodeURIComponent(c[a].toString()))}}}return b.join("&")};SWFUpload.prototype.destroy=function(){try{this.cancelUpload(null,false);var a=null;a=this.getMovieElement();if(a&&typeof(a.CallFunction)==="unknown"){for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(e){}}try{a.parentNode.removeChild(a)}catch(b){}}window[this.movieName]=null;SWFUpload.instances[this.movieName]=null;delete SWFUpload.instances[this.movieName];this.movieElement=null;this.settings=null;this.customSettings=null;this.eventQueue=null;this.movieName=null;return true}catch(d){return false}};SWFUpload.prototype.displayDebugInfo=function(){this.debug(["---SWFUpload Instance Info---\n","Version: ",SWFUpload.version,"\n","Movie Name: ",this.movieName,"\n","Settings:\n","\t","upload_url: ",this.settings.upload_url,"\n","\t","flash_url: ",this.settings.flash_url,"\n","\t","use_query_string: ",this.settings.use_query_string.toString(),"\n","\t","requeue_on_error: ",this.settings.requeue_on_error.toString(),"\n","\t","http_success: ",this.settings.http_success.join(", "),"\n","\t","assume_success_timeout: ",this.settings.assume_success_timeout,"\n","\t","file_post_name: ",this.settings.file_post_name,"\n","\t","post_params: ",this.settings.post_params.toString(),"\n","\t","file_types: ",this.settings.file_types,"\n","\t","file_types_description: ",this.settings.file_types_description,"\n","\t","file_size_limit: ",this.settings.file_size_limit,"\n","\t","file_upload_limit: ",this.settings.file_upload_limit,"\n","\t","file_queue_limit: ",this.settings.file_queue_limit,"\n","\t","debug: ",this.settings.debug.toString(),"\n","\t","prevent_swf_caching: ",this.settings.prevent_swf_caching.toString(),"\n","\t","button_placeholder_id: ",this.settings.button_placeholder_id.toString(),"\n","\t","button_placeholder: ",(this.settings.button_placeholder?"Set":"Not Set"),"\n","\t","button_image_url: ",this.settings.button_image_url.toString(),"\n","\t","button_width: ",this.settings.button_width.toString(),"\n","\t","button_height: ",this.settings.button_height.toString(),"\n","\t","button_text: ",this.settings.button_text.toString(),"\n","\t","button_text_style: ",this.settings.button_text_style.toString(),"\n","\t","button_text_top_padding: ",this.settings.button_text_top_padding.toString(),"\n","\t","button_text_left_padding: ",this.settings.button_text_left_padding.toString(),"\n","\t","button_action: ",this.settings.button_action.toString(),"\n","\t","button_disabled: ",this.settings.button_disabled.toString(),"\n","\t","custom_settings: ",this.settings.custom_settings.toString(),"\n","Event Handlers:\n","\t","swfupload_loaded_handler assigned: ",(typeof this.settings.swfupload_loaded_handler==="function").toString(),"\n","\t","file_dialog_start_handler assigned: ",(typeof this.settings.file_dialog_start_handler==="function").toString(),"\n","\t","file_queued_handler assigned: ",(typeof this.settings.file_queued_handler==="function").toString(),"\n","\t","file_queue_error_handler assigned: ",(typeof this.settings.file_queue_error_handler==="function").toString(),"\n","\t","upload_start_handler assigned: ",(typeof this.settings.upload_start_handler==="function").toString(),"\n","\t","upload_progress_handler assigned: ",(typeof this.settings.upload_progress_handler==="function").toString(),"\n","\t","upload_error_handler assigned: ",(typeof this.settings.upload_error_handler==="function").toString(),"\n","\t","upload_success_handler assigned: ",(typeof this.settings.upload_success_handler==="function").toString(),"\n","\t","upload_complete_handler assigned: ",(typeof this.settings.upload_complete_handler==="function").toString(),"\n","\t","debug_handler assigned: ",(typeof this.settings.debug_handler==="function").toString(),"\n"].join(""))};SWFUpload.prototype.addSetting=function(b,c,a){if(c==undefined){return(this.settings[b]=a)}else{return(this.settings[b]=c)}};SWFUpload.prototype.getSetting=function(a){if(this.settings[a]!=undefined){return this.settings[a]}return""};SWFUpload.prototype.callFlash=function(functionName,argumentArray){argumentArray=argumentArray||[];var movieElement=this.getMovieElement();var returnValue,returnString;try{returnString=movieElement.CallFunction('<invoke name="'+functionName+'" returntype="javascript">'+__flash__argumentsToXML(argumentArray,0)+"</invoke>");returnValue=eval(returnString)}catch(ex){throw"Call to "+functionName+" failed"}if(returnValue!=undefined&&typeof returnValue.post==="object"){returnValue=this.unescapeFilePostParams(returnValue)}return returnValue};SWFUpload.prototype.selectFile=function(){this.callFlash("SelectFile")};SWFUpload.prototype.selectFiles=function(){this.callFlash("SelectFiles")};SWFUpload.prototype.startUpload=function(a){this.callFlash("StartUpload",[a])};SWFUpload.prototype.cancelUpload=function(a,b){if(b!==false){b=true}this.callFlash("CancelUpload",[a,b])};SWFUpload.prototype.stopUpload=function(){this.callFlash("StopUpload")};SWFUpload.prototype.getStats=function(){return this.callFlash("GetStats")};SWFUpload.prototype.setStats=function(a){this.callFlash("SetStats",[a])};SWFUpload.prototype.getFile=function(a){if(typeof(a)==="number"){return this.callFlash("GetFileByIndex",[a])}else{return this.callFlash("GetFile",[a])}};SWFUpload.prototype.addFileParam=function(a,b,c){return this.callFlash("AddFileParam",[a,b,c])};SWFUpload.prototype.removeFileParam=function(a,b){this.callFlash("RemoveFileParam",[a,b])};SWFUpload.prototype.setUploadURL=function(a){this.settings.upload_url=a.toString();this.callFlash("SetUploadURL",[a])};SWFUpload.prototype.setPostParams=function(a){this.settings.post_params=a;this.callFlash("SetPostParams",[a])};SWFUpload.prototype.addPostParam=function(a,b){this.settings.post_params[a]=b;this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.removePostParam=function(a){delete this.settings.post_params[a];this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.setFileTypes=function(a,b){this.settings.file_types=a;this.settings.file_types_description=b;this.callFlash("SetFileTypes",[a,b])};SWFUpload.prototype.setFileSizeLimit=function(a){this.settings.file_size_limit=a;this.callFlash("SetFileSizeLimit",[a])};SWFUpload.prototype.setFileUploadLimit=function(a){this.settings.file_upload_limit=a;this.callFlash("SetFileUploadLimit",[a])};SWFUpload.prototype.setFileQueueLimit=function(a){this.settings.file_queue_limit=a;this.callFlash("SetFileQueueLimit",[a])};SWFUpload.prototype.setFilePostName=function(a){this.settings.file_post_name=a;this.callFlash("SetFilePostName",[a])};SWFUpload.prototype.setUseQueryString=function(a){this.settings.use_query_string=a;this.callFlash("SetUseQueryString",[a])};SWFUpload.prototype.setRequeueOnError=function(a){this.settings.requeue_on_error=a;this.callFlash("SetRequeueOnError",[a])};SWFUpload.prototype.setHTTPSuccess=function(a){if(typeof a==="string"){a=a.replace(" ","").split(",")}this.settings.http_success=a;this.callFlash("SetHTTPSuccess",[a])};SWFUpload.prototype.setAssumeSuccessTimeout=function(a){this.settings.assume_success_timeout=a;this.callFlash("SetAssumeSuccessTimeout",[a])};SWFUpload.prototype.setDebugEnabled=function(a){this.settings.debug_enabled=a;this.callFlash("SetDebugEnabled",[a])};SWFUpload.prototype.setButtonImageURL=function(a){if(a==undefined){a=""}this.settings.button_image_url=a;this.callFlash("SetButtonImageURL",[a])};SWFUpload.prototype.setButtonDimensions=function(c,a){this.settings.button_width=c;this.settings.button_height=a;var b=this.getMovieElement();if(b!=undefined){b.style.width=c+"px";b.style.height=a+"px"}this.callFlash("SetButtonDimensions",[c,a])};SWFUpload.prototype.setButtonText=function(a){this.settings.button_text=a;this.callFlash("SetButtonText",[a])};SWFUpload.prototype.setButtonTextPadding=function(b,a){this.settings.button_text_top_padding=a;this.settings.button_text_left_padding=b;this.callFlash("SetButtonTextPadding",[b,a])};SWFUpload.prototype.setButtonTextStyle=function(a){this.settings.button_text_style=a;this.callFlash("SetButtonTextStyle",[a])};SWFUpload.prototype.setButtonDisabled=function(a){this.settings.button_disabled=a;this.callFlash("SetButtonDisabled",[a])};SWFUpload.prototype.setButtonAction=function(a){this.settings.button_action=a;this.callFlash("SetButtonAction",[a])};SWFUpload.prototype.setButtonCursor=function(a){this.settings.button_cursor=a;this.callFlash("SetButtonCursor",[a])};SWFUpload.prototype.queueEvent=function(b,c){if(c==undefined){c=[]}else{if(!(c instanceof Array)){c=[c]}}var a=this;if(typeof this.settings[b]==="function"){this.eventQueue.push(function(){this.settings[b].apply(this,c)});setTimeout(function(){a.executeNextEvent()},0)}else{if(this.settings[b]!==null){throw"Event handler "+b+" is unknown or is not a function"}}};SWFUpload.prototype.executeNextEvent=function(){var a=this.eventQueue?this.eventQueue.shift():null;if(typeof(a)==="function"){a.apply(this)}};SWFUpload.prototype.unescapeFilePostParams=function(c){var e=/[$]([0-9a-f]{4})/i;var f={};var d;if(c!=undefined){for(var a in c.post){if(c.post.hasOwnProperty(a)){d=a;var b;while((b=e.exec(d))!==null){d=d.replace(b[0],String.fromCharCode(parseInt("0x"+b[1],16)))}f[d]=c.post[a]}}c.post=f}return c};SWFUpload.prototype.testExternalInterface=function(){try{return this.callFlash("TestExternalInterface")}catch(a){return false}};SWFUpload.prototype.flashReady=function(){var a=this.getMovieElement();if(!a){this.debug("Flash called back ready but the flash movie can't be found.");return}this.cleanUp(a);this.queueEvent("swfupload_loaded_handler")};SWFUpload.prototype.cleanUp=function(a){try{if(this.movieElement&&typeof(a.CallFunction)==="unknown"){this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(b){}}}}catch(d){}window.__flash__removeCallback=function(e,f){try{if(e){e[f]=null}}catch(g){}}};SWFUpload.prototype.fileDialogStart=function(){this.queueEvent("file_dialog_start_handler")};SWFUpload.prototype.fileQueued=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("file_queued_handler",a)};SWFUpload.prototype.fileQueueError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("file_queue_error_handler",[a,c,b])};SWFUpload.prototype.fileDialogComplete=function(b,c,a){this.queueEvent("file_dialog_complete_handler",[b,c,a])};SWFUpload.prototype.uploadStart=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("return_upload_start_handler",a)};SWFUpload.prototype.returnUploadStart=function(a){var b;if(typeof this.settings.upload_start_handler==="function"){a=this.unescapeFilePostParams(a);b=this.settings.upload_start_handler.call(this,a)}else{if(this.settings.upload_start_handler!=undefined){throw"upload_start_handler must be a function"}}if(b===undefined){b=true}b=!!b;this.callFlash("ReturnUploadStart",[b])};SWFUpload.prototype.uploadProgress=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_progress_handler",[a,c,b])};SWFUpload.prototype.uploadError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_error_handler",[a,c,b])};SWFUpload.prototype.uploadSuccess=function(b,a,c){b=this.unescapeFilePostParams(b);this.queueEvent("upload_success_handler",[b,a,c])};SWFUpload.prototype.uploadComplete=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("upload_complete_handler",a)};SWFUpload.prototype.debug=function(a){this.queueEvent("debug_handler",a)};SWFUpload.prototype.debugMessage=function(c){if(this.settings.debug){var a,d=[];if(typeof c==="object"&&typeof c.name==="string"&&typeof c.message==="string"){for(var b in c){if(c.hasOwnProperty(b)){d.push(b+": "+c[b])}}a=d.join("\n")||"";d=a.split("\n");a="EXCEPTION: "+d.join("\nEXCEPTION: ");SWFUpload.Console.writeLine(a)}else{SWFUpload.Console.writeLine(c)}}};SWFUpload.Console={};SWFUpload.Console.writeLine=function(d){var b,a;try{b=document.getElementById("SWFUpload_Console");if(!b){a=document.createElement("form");document.getElementsByTagName("body")[0].appendChild(a);b=document.createElement("textarea");b.id="SWFUpload_Console";b.style.fontFamily="monospace";b.setAttribute("wrap","off");b.wrap="off";b.style.overflow="auto";b.style.width="700px";b.style.height="350px";b.style.margin="5px";a.appendChild(b)}b.value+=d+"\n";b.scrollTop=b.scrollHeight-b.clientHeight}catch(c){alert("Exception: "+c.name+" Message: "+c.message)}};
/*
Uploadify v3.2
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
(function($) {
// These methods can be called by adding them as the first argument in the uploadify plugin call
var methods = {
init : function(options, swfUploadOptions) {
return this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this);
// Clone the original DOM object
var $clone = $this.clone();
// Setup the default options
var settings = $.extend({
// Required Settings
id : $this.attr('id'), // The ID of the DOM object
swf : 'uploadify.swf', // The path to the uploadify SWF file
uploader : 'uploadify.php', // The path to the server-side upload script
// Options
auto : true, // Automatically upload files when added to the queue
buttonClass : '', // A class name to add to the browse button DOM object
buttonCursor : 'hand', // The cursor to use with the browse button
buttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button
buttonText : 'SELECT FILES', // The text to use for the browse button
checkExisting : false, // The path to a server-side script that checks for existing files on the server
debug : false, // Turn on swfUpload debugging mode
fileObjName : 'Filedata', // The name of the file object to use in your server-side script
fileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)
fileTypeDesc : 'All Files', // The description for file types in the browse dialog
fileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used)
height : 30, // The height of the browse button
itemTemplate : false, // The template for the file item in the queue
method : 'post', // The method to use when sending files to the server-side upload script
multi : true, // Allow multiple file selection in the browse dialog
formData : {}, // An object with additional data to send to the server-side upload script with every file upload
preventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file upload
queueID : false, // The ID of the DOM object to use as a file queue (without the #)
queueSizeLimit : 999, // The maximum number of files that can be in the queue at one time
removeCompleted : true, // Remove queue items from the queue when they are done uploading
removeTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to true
requeueErrors : false, // Keep errored files in the queue and keep trying to upload them
successTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
uploadLimit : 0, // The maximum number of files you can upload
width : 120, // The width of the browse button
// Events
overrideEvents : [] // (Array) A list of default event handlers to skip
/*
onCancel // Triggered when a file is cancelled from the queue
onClearQueue // Triggered during the 'clear queue' method
onDestroy // Triggered when the uploadify object is destroyed
onDialogClose // Triggered when the browse dialog is closed
onDialogOpen // Triggered when the browse dialog is opened
onDisable // Triggered when the browse button gets disabled
onEnable // Triggered when the browse button gets enabled
onFallback // Triggered is Flash is not detected
onInit // Triggered when Uploadify is initialized
onQueueComplete // Triggered when all files in the queue have been uploaded
onSelectError // Triggered when an error occurs while selecting a file (file size, queue size limit, etc.)
onSelect // Triggered for each file that is selected
onSWFReady // Triggered when the SWF button is loaded
onUploadComplete // Triggered when a file upload completes (success or error)
onUploadError // Triggered when a file upload returns an error
onUploadSuccess // Triggered when a file is uploaded successfully
onUploadProgress // Triggered every time a file progress is updated
onUploadStart // Triggered immediately before a file upload starts
*/
}, options);
// Prepare settings for SWFUpload
var swfUploadSettings = {
assume_success_timeout : settings.successTimeout,
button_placeholder_id : settings.id,
button_width : settings.width,
button_height : settings.height,
button_text : null,
button_text_style : null,
button_text_top_padding : 0,
button_text_left_padding : 0,
button_action : (settings.multi ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE),
button_disabled : false,
button_cursor : (settings.buttonCursor == 'arrow' ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND),
button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
debug : settings.debug,
requeue_on_error : settings.requeueErrors,
file_post_name : settings.fileObjName,
file_size_limit : settings.fileSizeLimit,
file_types : settings.fileTypeExts,
file_types_description : settings.fileTypeDesc,
file_queue_limit : settings.queueSizeLimit,
file_upload_limit : settings.uploadLimit,
flash_url : settings.swf,
prevent_swf_caching : settings.preventCaching,
post_params : settings.formData,
upload_url : settings.uploader,
use_query_string : (settings.method == 'get'),
// Event Handlers
file_dialog_complete_handler : handlers.onDialogClose,
file_dialog_start_handler : handlers.onDialogOpen,
file_queued_handler : handlers.onSelect,
file_queue_error_handler : handlers.onSelectError,
swfupload_loaded_handler : settings.onSWFReady,
upload_complete_handler : handlers.onUploadComplete,
upload_error_handler : handlers.onUploadError,
upload_progress_handler : handlers.onUploadProgress,
upload_start_handler : handlers.onUploadStart,
upload_success_handler : handlers.onUploadSuccess
}
// Merge the user-defined options with the defaults
if (swfUploadOptions) {
swfUploadSettings = $.extend(swfUploadSettings, swfUploadOptions);
}
// Add the user-defined settings to the swfupload object
swfUploadSettings = $.extend(swfUploadSettings, settings);
// Detect if Flash is available
var playerVersion = swfobject.getFlashPlayerVersion();
var flashInstalled = (playerVersion.major >= 9);
if (flashInstalled) {
// Create the swfUpload instance
window['uploadify_' + settings.id] = new SWFUpload(swfUploadSettings);
var swfuploadify = window['uploadify_' + settings.id];
// Add the SWFUpload object to the elements data object
$this.data('uploadify', swfuploadify);
// Wrap the instance
var $wrapper = $('<div />', {
'id' : settings.id,
'class' : 'uploadify',
'css' : {
'height' : settings.height + 'px',
'width' : settings.width + 'px'
}
});
$('#' + swfuploadify.movieName).wrap($wrapper);
// Recreate the reference to wrapper
$wrapper = $('#' + settings.id);
// Add the data object to the wrapper
$wrapper.data('uploadify', swfuploadify);
// Create the button
var $button = $('<div />', {
'id' : settings.id + '-button',
'class' : 'uploadify-button ' + settings.buttonClass
});
if (settings.buttonImage) {
$button.css({
'background-image' : "url('" + settings.buttonImage + "')",
'text-indent' : '-9999px'
});
}
$button.html('<span class="uploadify-button-text">' + settings.buttonText + '</span>')
.css({
'height' : settings.height + 'px',
'line-height' : settings.height + 'px',
'width' : settings.width + 'px'
});
// Append the button to the wrapper
$wrapper.append($button);
// Adjust the styles of the movie
$('#' + swfuploadify.movieName).css({
'position' : 'absolute',
'z-index' : 1
});
// Create the file queue
if (!settings.queueID) {
var $queue = $('<div />', {
'id' : settings.id + '-queue',
'class' : 'uploadify-queue'
});
$wrapper.after($queue);
swfuploadify.settings.queueID = settings.id + '-queue';
swfuploadify.settings.defaultQueue = true;
}
// Create some queue related objects and variables
swfuploadify.queueData = {
files : {}, // The files in the queue
filesSelected : 0, // The number of files selected in the last select operation
filesQueued : 0, // The number of files added to the queue in the last select operation
filesReplaced : 0, // The number of files replaced in the last select operation
filesCancelled : 0, // The number of files that were cancelled instead of replaced
filesErrored : 0, // The number of files that caused error in the last select operation
uploadsSuccessful : 0, // The number of files that were successfully uploaded
uploadsErrored : 0, // The number of files that returned errors during upload
averageSpeed : 0, // The average speed of the uploads in KB
queueLength : 0, // The number of files in the queue
queueSize : 0, // The size in bytes of the entire queue
uploadSize : 0, // The size in bytes of the upload queue
queueBytesUploaded : 0, // The size in bytes that have been uploaded for the current upload queue
uploadQueue : [], // The files currently to be uploaded
errorMsg : 'Some files were not added to the queue:'
};
// Save references to all the objects
swfuploadify.original = $clone;
swfuploadify.wrapper = $wrapper;
swfuploadify.button = $button;
swfuploadify.queue = $queue;
// Call the user-defined init event handler
if (settings.onInit) settings.onInit.call($this, swfuploadify);
} else {
// Call the fallback function
if (settings.onFallback) settings.onFallback.call($this);
}
});
},
// Stop a file upload and remove it from the queue
cancel : function(fileID, supressEvent) {
var args = arguments;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings,
delay = -1;
if (args[0]) {
// Clear the queue
if (args[0] == '*') {
var queueItemCount = swfuploadify.queueData.queueLength;
$('#' + settings.queueID).find('.uploadify-queue-item').each(function() {
delay++;
if (args[1] === true) {
swfuploadify.cancelUpload($(this).attr('id'), false);
} else {
swfuploadify.cancelUpload($(this).attr('id'));
}
$(this).find('.data').removeClass('data').html(' - Cancelled');
$(this).find('.uploadify-progress-bar').remove();
$(this).delay(1000 + 100 * delay).fadeOut(500, function() {
$(this).remove();
});
});
swfuploadify.queueData.queueSize = 0;
swfuploadify.queueData.queueLength = 0;
// Trigger the onClearQueue event
if (settings.onClearQueue) settings.onClearQueue.call($this, queueItemCount);
} else {
for (var n = 0; n < args.length; n++) {
swfuploadify.cancelUpload(args[n]);
$('#' + args[n]).find('.data').removeClass('data').html(' - Cancelled');
$('#' + args[n]).find('.uploadify-progress-bar').remove();
$('#' + args[n]).delay(1000 + 100 * n).fadeOut(500, function() {
$(this).remove();
});
}
}
} else {
var item = $('#' + settings.queueID).find('.uploadify-queue-item').get(0);
$item = $(item);
swfuploadify.cancelUpload($item.attr('id'));
$item.find('.data').removeClass('data').html(' - Cancelled');
$item.find('.uploadify-progress-bar').remove();
$item.delay(1000).fadeOut(500, function() {
$(this).remove();
});
}
});
},
// Revert the DOM object back to its original state
destroy : function() {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
// Destroy the SWF object and
swfuploadify.destroy();
// Destroy the queue
if (settings.defaultQueue) {
$('#' + settings.queueID).remove();
}
// Reload the original DOM element
$('#' + settings.id).replaceWith(swfuploadify.original);
// Call the user-defined event handler
if (settings.onDestroy) settings.onDestroy.call(this);
delete swfuploadify;
});
},
// Disable the select button
disable : function(isDisabled) {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
// Call the user-defined event handlers
if (isDisabled) {
swfuploadify.button.addClass('disabled');
if (settings.onDisable) settings.onDisable.call(this);
} else {
swfuploadify.button.removeClass('disabled');
if (settings.onEnable) settings.onEnable.call(this);
}
// Enable/disable the browse button
swfuploadify.setButtonDisabled(isDisabled);
});
},
// Get or set the settings data
settings : function(name, value, resetObjects) {
var args = arguments;
var returnValue = value;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
if (typeof(args[0]) == 'object') {
for (var n in value) {
setData(n,value[n]);
}
}
if (args.length === 1) {
returnValue = settings[name];
} else {
switch (name) {
case 'uploader':
swfuploadify.setUploadURL(value);
break;
case 'formData':
if (!resetObjects) {
value = $.extend(settings.formData, value);
}
swfuploadify.setPostParams(settings.formData);
break;
case 'method':
if (value == 'get') {
swfuploadify.setUseQueryString(true);
} else {
swfuploadify.setUseQueryString(false);
}
break;
case 'fileObjName':
swfuploadify.setFilePostName(value);
break;
case 'fileTypeExts':
swfuploadify.setFileTypes(value, settings.fileTypeDesc);
break;
case 'fileTypeDesc':
swfuploadify.setFileTypes(settings.fileTypeExts, value);
break;
case 'fileSizeLimit':
swfuploadify.setFileSizeLimit(value);
break;
case 'uploadLimit':
swfuploadify.setFileUploadLimit(value);
break;
case 'queueSizeLimit':
swfuploadify.setFileQueueLimit(value);
break;
case 'buttonImage':
swfuploadify.button.css('background-image', settingValue);
break;
case 'buttonCursor':
if (value == 'arrow') {
swfuploadify.setButtonCursor(SWFUpload.CURSOR.ARROW);
} else {
swfuploadify.setButtonCursor(SWFUpload.CURSOR.HAND);
}
break;
case 'buttonText':
$('#' + settings.id + '-button').find('.uploadify-button-text').html(value);
break;
case 'width':
swfuploadify.setButtonDimensions(value, settings.height);
break;
case 'height':
swfuploadify.setButtonDimensions(settings.width, value);
break;
case 'multi':
if (value) {
swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILES);
} else {
swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILE);
}
break;
}
settings[name] = value;
}
});
if (args.length === 1) {
return returnValue;
}
},
// Stop the current uploads and requeue what is in progress
stop : function() {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify');
// Reset the queue information
swfuploadify.queueData.averageSpeed = 0;
swfuploadify.queueData.uploadSize = 0;
swfuploadify.queueData.bytesUploaded = 0;
swfuploadify.queueData.uploadQueue = [];
swfuploadify.stopUpload();
});
},
// Start uploading files in the queue
upload : function() {
var args = arguments;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify');
// Reset the queue information
swfuploadify.queueData.averageSpeed = 0;
swfuploadify.queueData.uploadSize = 0;
swfuploadify.queueData.bytesUploaded = 0;
swfuploadify.queueData.uploadQueue = [];
// Upload the files
if (args[0]) {
if (args[0] == '*') {
swfuploadify.queueData.uploadSize = swfuploadify.queueData.queueSize;
swfuploadify.queueData.uploadQueue.push('*');
swfuploadify.startUpload();
} else {
for (var n = 0; n < args.length; n++) {
swfuploadify.queueData.uploadSize += swfuploadify.queueData.files[args[n]].size;
swfuploadify.queueData.uploadQueue.push(args[n]);
}
swfuploadify.startUpload(swfuploadify.queueData.uploadQueue.shift());
}
} else {
swfuploadify.startUpload();
}
});
}
}
// These functions handle all the events that occur with the file uploader
var handlers = {
// Triggered when the file dialog is opened
onDialogOpen : function() {
// Load the swfupload settings
var settings = this.settings;
// Reset some queue info
this.queueData.errorMsg = 'Some files were not added to the queue:';
this.queueData.filesReplaced = 0;
this.queueData.filesCancelled = 0;
// Call the user-defined event handler
if (settings.onDialogOpen) settings.onDialogOpen.call(this);
},
// Triggered when the browse dialog is closed
onDialogClose : function(filesSelected, filesQueued, queueLength) {
// Load the swfupload settings
var settings = this.settings;
// Update the queue information
this.queueData.filesErrored = filesSelected - filesQueued;
this.queueData.filesSelected = filesSelected;
this.queueData.filesQueued = filesQueued - this.queueData.filesCancelled;
this.queueData.queueLength = queueLength;
// Run the default event handler
if ($.inArray('onDialogClose', settings.overrideEvents) < 0) {
if (this.queueData.filesErrored > 0) {
alert(this.queueData.errorMsg);
}
}
// Call the user-defined event handler
if (settings.onDialogClose) settings.onDialogClose.call(this, this.queueData);
// Upload the files if auto is true
if (settings.auto) $('#' + settings.id).uploadify('upload', '*');
},
// Triggered once for each file added to the queue
onSelect : function(file) {
// Load the swfupload settings
var settings = this.settings;
// Check if a file with the same name exists in the queue
var queuedFile = {};
for (var n in this.queueData.files) {
queuedFile = this.queueData.files[n];
if (queuedFile.uploaded != true && queuedFile.name == file.name) {
var replaceQueueItem = confirm('The file named "' + file.name + '" is already in the queue.\nDo you want to replace the existing item in the queue?');
if (!replaceQueueItem) {
this.cancelUpload(file.id);
this.queueData.filesCancelled++;
return false;
} else {
$('#' + queuedFile.id).remove();
this.cancelUpload(queuedFile.id);
this.queueData.filesReplaced++;
}
}
}
// Get the size of the file
var fileSize = Math.round(file.size / 1024);
var suffix = 'KB';
if (fileSize > 1000) {
fileSize = Math.round(fileSize / 1000);
suffix = 'MB';
}
var fileSizeParts = fileSize.toString().split('.');
fileSize = fileSizeParts[0];
if (fileSizeParts.length > 1) {
fileSize += '.' + fileSizeParts[1].substr(0,2);
}
fileSize += suffix;
// Truncate the filename if it's too long
var fileName = file.name;
if (fileName.length > 25) {
fileName = fileName.substr(0,25) + '...';
}
// Create the file data object
itemData = {
'fileID' : file.id,
'instanceID' : settings.id,
'fileName' : fileName,
'fileSize' : fileSize
}
// Create the file item template
if (settings.itemTemplate == false) {
settings.itemTemplate = '<div id="${fileID}" class="uploadify-queue-item">\
<div class="cancel">\
<a href="javascript:$(\'#${instanceID}\').uploadify(\'cancel\', \'${fileID}\')">X</a>\
</div>\
<span class="fileName">${fileName} (${fileSize})</span><span class="data"></span>\
<div class="uploadify-progress">\
<div class="uploadify-progress-bar"><!--Progress Bar--></div>\
</div>\
</div>';
}
// Run the default event handler
if ($.inArray('onSelect', settings.overrideEvents) < 0) {
// Replace the item data in the template
itemHTML = settings.itemTemplate;
for (var d in itemData) {
itemHTML = itemHTML.replace(new RegExp('\\$\\{' + d + '\\}', 'g'), itemData[d]);
}
// Add the file item to the queue
$('#' + settings.queueID).append(itemHTML);
}
this.queueData.queueSize += file.size;
this.queueData.files[file.id] = file;
// Call the user-defined event handler
if (settings.onSelect) settings.onSelect.apply(this, arguments);
},
// Triggered when a file is not added to the queue
onSelectError : function(file, errorCode, errorMsg) {
// Load the swfupload settings
var settings = this.settings;
// Run the default event handler
if ($.inArray('onSelectError', settings.overrideEvents) < 0) {
switch(errorCode) {
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
if (settings.queueSizeLimit > errorMsg) {
this.queueData.errorMsg += '\nThe number of files selected exceeds the remaining upload limit (' + errorMsg + ').';
} else {
this.queueData.errorMsg += '\nThe number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').';
}
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
this.queueData.errorMsg += '\nThe file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').';
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
this.queueData.errorMsg += '\nThe file "' + file.name + '" is empty.';
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
this.queueData.errorMsg += '\nThe file "' + file.name + '" is not an accepted file type (' + settings.fileTypeDesc + ').';
break;
}
}
if (errorCode != SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
delete this.queueData.files[file.id];
}
// Call the user-defined event handler
if (settings.onSelectError) settings.onSelectError.apply(this, arguments);
},
// Triggered when all the files in the queue have been processed
onQueueComplete : function() {
if (this.settings.onQueueComplete) this.settings.onQueueComplete.call(this, this.settings.queueData);
},
// Triggered when a file upload successfully completes
onUploadComplete : function(file) {
// Load the swfupload settings
var settings = this.settings,
swfuploadify = this;
// Check if all the files have completed uploading
var stats = this.getStats();
this.queueData.queueLength = stats.files_queued;
if (this.queueData.uploadQueue[0] == '*') {
if (this.queueData.queueLength > 0) {
this.startUpload();
} else {
this.queueData.uploadQueue = [];
// Call the user-defined event handler for queue complete
if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
}
} else {
if (this.queueData.uploadQueue.length > 0) {
this.startUpload(this.queueData.uploadQueue.shift());
} else {
this.queueData.uploadQueue = [];
// Call the user-defined event handler for queue complete
if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
}
}
// Call the default event handler
if ($.inArray('onUploadComplete', settings.overrideEvents) < 0) {
if (settings.removeCompleted) {
switch (file.filestatus) {
case SWFUpload.FILE_STATUS.COMPLETE:
setTimeout(function() {
if ($('#' + file.id)) {
swfuploadify.queueData.queueSize -= file.size;
swfuploadify.queueData.queueLength -= 1;
delete swfuploadify.queueData.files[file.id]
$('#' + file.id).fadeOut(500, function() {
$(this).remove();
});
}
}, settings.removeTimeout * 1000);
break;
case SWFUpload.FILE_STATUS.ERROR:
if (!settings.requeueErrors) {
setTimeout(function() {
if ($('#' + file.id)) {
swfuploadify.queueData.queueSize -= file.size;
swfuploadify.queueData.queueLength -= 1;
delete swfuploadify.queueData.files[file.id];
$('#' + file.id).fadeOut(500, function() {
$(this).remove();
});
}
}, settings.removeTimeout * 1000);
}
break;
}
} else {
file.uploaded = true;
}
}
// Call the user-defined event handler
if (settings.onUploadComplete) settings.onUploadComplete.call(this, file);
},
// Triggered when a file upload returns an error
onUploadError : function(file, errorCode, errorMsg) {
// Load the swfupload settings
var settings = this.settings;
// Set the error string
var errorString = 'Error';
switch(errorCode) {
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
errorString = 'HTTP Error (' + errorMsg + ')';
break;
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
errorString = 'Missing Upload URL';
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
errorString = 'IO Error';
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
errorString = 'Security Error';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
alert('The upload limit has been reached (' + errorMsg + ').');
errorString = 'Exceeds Upload Limit';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
errorString = 'Failed';
break;
case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
break;
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
errorString = 'Validation Error';
break;
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
errorString = 'Cancelled';
this.queueData.queueSize -= file.size;
this.queueData.queueLength -= 1;
if (file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) {
this.queueData.uploadSize -= file.size;
}
// Trigger the onCancel event
if (settings.onCancel) settings.onCancel.call(this, file);
delete this.queueData.files[file.id];
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
errorString = 'Stopped';
break;
}
// Call the default event handler
if ($.inArray('onUploadError', settings.overrideEvents) < 0) {
if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED && errorCode != SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
$('#' + file.id).addClass('uploadify-error');
}
// Reset the progress bar
$('#' + file.id).find('.uploadify-progress-bar').css('width','1px');
// Add the error message to the queue item
if (errorCode != SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND && file.status != SWFUpload.FILE_STATUS.COMPLETE) {
$('#' + file.id).find('.data').html(' - ' + errorString);
}
}
var stats = this.getStats();
this.queueData.uploadsErrored = stats.upload_errors;
// Call the user-defined event handler
if (settings.onUploadError) settings.onUploadError.call(this, file, errorCode, errorMsg, errorString);
},
// Triggered periodically during a file upload
onUploadProgress : function(file, fileBytesLoaded, fileTotalBytes) {
// Load the swfupload settings
var settings = this.settings;
// Setup all the variables
var timer = new Date();
var newTime = timer.getTime();
var lapsedTime = newTime - this.timer;
if (lapsedTime > 500) {
this.timer = newTime;
}
var lapsedBytes = fileBytesLoaded - this.bytesLoaded;
this.bytesLoaded = fileBytesLoaded;
var queueBytesLoaded = this.queueData.queueBytesUploaded + fileBytesLoaded;
var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100);
// Calculate the average speed
var suffix = 'KB/s';
var mbs = 0;
var kbs = (lapsedBytes / 1024) / (lapsedTime / 1000);
kbs = Math.floor(kbs * 10) / 10;
if (this.queueData.averageSpeed > 0) {
this.queueData.averageSpeed = Math.floor((this.queueData.averageSpeed + kbs) / 2);
} else {
this.queueData.averageSpeed = Math.floor(kbs);
}
if (kbs > 1000) {
mbs = (kbs * .001);
this.queueData.averageSpeed = Math.floor(mbs);
suffix = 'MB/s';
}
// Call the default event handler
if ($.inArray('onUploadProgress', settings.overrideEvents) < 0) {
if (settings.progressData == 'percentage') {
$('#' + file.id).find('.data').html(' - ' + percentage + '%');
} else if (settings.progressData == 'speed' && lapsedTime > 500) {
$('#' + file.id).find('.data').html(' - ' + this.queueData.averageSpeed + suffix);
}
$('#' + file.id).find('.uploadify-progress-bar').css('width', percentage + '%');
}
// Call the user-defined event handler
if (settings.onUploadProgress) settings.onUploadProgress.call(this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize);
},
// Triggered right before a file is uploaded
onUploadStart : function(file) {
// Load the swfupload settings
var settings = this.settings;
var timer = new Date();
this.timer = timer.getTime();
this.bytesLoaded = 0;
if (this.queueData.uploadQueue.length == 0) {
this.queueData.uploadSize = file.size;
}
if (settings.checkExisting) {
$.ajax({
type : 'POST',
async : false,
url : settings.checkExisting,
data : {filename: file.name},
success : function(data) {
if (data == 1) {
var overwrite = confirm('A file with the name "' + file.name + '" already exists on the server.\nWould you like to replace the existing file?');
if (!overwrite) {
this.cancelUpload(file.id);
$('#' + file.id).remove();
if (this.queueData.uploadQueue.length > 0 && this.queueData.queueLength > 0) {
if (this.queueData.uploadQueue[0] == '*') {
this.startUpload();
} else {
this.startUpload(this.queueData.uploadQueue.shift());
}
}
}
}
}
});
}
// Call the user-defined event handler
if (settings.onUploadStart) settings.onUploadStart.call(this, file);
},
// Triggered when a file upload returns a successful code
onUploadSuccess : function(file, data, response) {
// Load the swfupload settings
var settings = this.settings;
var stats = this.getStats();
this.queueData.uploadsSuccessful = stats.successful_uploads;
this.queueData.queueBytesUploaded += file.size;
// Call the default event handler
if ($.inArray('onUploadSuccess', settings.overrideEvents) < 0) {
$('#' + file.id).find('.data').html(' - Complete');
}
// Call the user-defined event handler
if (settings.onUploadSuccess) settings.onUploadSuccess.call(this, file, data, response);
}
}
$.fn.uploadify = function(method) {
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('The method ' + method + ' does not exist in $.uploadify');
}
}
})($); | JavaScript |
/*!
* FullCalendar v1.6.0 Google Calendar Plugin
* Docs & License: http://arshaw.com/fullcalendar/
* (c) 2013 Adam Shaw
*/
(function($) {
var fc = $.fullCalendar;
var formatDate = fc.formatDate;
var parseISO8601 = fc.parseISO8601;
var addDays = fc.addDays;
var applyAll = fc.applyAll;
fc.sourceNormalizers.push(function(sourceOptions) {
if (sourceOptions.dataType == 'gcal' ||
sourceOptions.dataType === undefined &&
(sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) {
sourceOptions.dataType = 'gcal';
if (sourceOptions.editable === undefined) {
sourceOptions.editable = false;
}
}
});
fc.sourceFetchers.push(function(sourceOptions, start, end) {
if (sourceOptions.dataType == 'gcal') {
return transformOptions(sourceOptions, start, end);
}
});
function transformOptions(sourceOptions, start, end) {
var success = sourceOptions.success;
var data = $.extend({}, sourceOptions.data || {}, {
'start-min': formatDate(start, 'u'),
'start-max': formatDate(end, 'u'),
'singleevents': true,
'max-results': 9999
});
var ctz = sourceOptions.currentTimezone;
if (ctz) {
data.ctz = ctz = ctz.replace(' ', '_');
}
return $.extend({}, sourceOptions, {
url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?',
dataType: 'jsonp',
data: data,
startParam: false,
endParam: false,
success: function(data) {
var events = [];
if (data.feed.entry) {
$.each(data.feed.entry, function(i, entry) {
var startStr = entry['gd$when'][0]['startTime'];
var start = parseISO8601(startStr, true);
var end = parseISO8601(entry['gd$when'][0]['endTime'], true);
var allDay = startStr.indexOf('T') == -1;
var url;
$.each(entry.link, function(i, link) {
if (link.type == 'text/html') {
url = link.href;
if (ctz) {
url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz;
}
}
});
if (allDay) {
addDays(end, -1); // make inclusive
}
events.push({
id: entry['gCal$uid']['value'],
title: entry['title']['$t'],
url: url,
start: start,
end: end,
allDay: allDay,
location: entry['gd$where'][0]['valueString'],
description: entry['content']['$t']
});
});
}
var args = [events].concat(Array.prototype.slice.call(arguments, 1));
var res = applyAll(success, this, args);
if ($.isArray(res)) {
return res;
}
return events;
}
});
}
// legacy
fc.gcalFeed = function(url, sourceOptions) {
return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' });
};
})(jQuery);
| JavaScript |
/*
* Copyright (c) 2011 Lyconic, LLC.
*
* 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.
*/
//todo should attach reset to changeview method in certain situations
(function ($, undefined) {
$.fn.limitEvents = function(opts){
if (opts.constructor === Number) opts = { maxEvents: opts };
return this.each(function(){
var limit = new $.fn.limitEvents.constructor($(this));
$.extend({ maxEvents: 4 }, opts); //defaults
$(this).fullCalendar('limitEvents', opts);
});
};
$.fn.limitEvents.constructor = function(calendar){
if (!(this instanceof arguments.callee)) return new arguments.callee(calendar);
var self = this;
self.calendar = calendar;
self.calendar.data('fullCalendar').limitEvents = function(opts){
self.opts = opts;
self.observers();
self.increaseHeight(25);
self.extendCallbacks();
}
};
})(jQuery);
(function ($, undefined) {
this.observers = function(){
var self = this;
$(document).mouseup(function(e){ //deselect when clicking outside of calendar or formbubble
var $target = $(e.target),
isFormBubble = $target.parents('.form-bubble').length || $target.hasClass('form-bubble'),
isInsideOfCalendar = $target.parents('.fc-content').length || $target.hasClass('fc-content');
if (!isInsideOfCalendar && !isFormBubble) self.calendar.fullCalendar('unselect');
});
self.calendar.delegate('.fc-event','mousedown', function(){ //close currently open form bubbles when user clicks an existing event
$.fn.formBubble.close();
});
self.calendar.delegate('.fc-button-prev, .fc-button-next', 'click', function(){
resetEventsRangeCounts();
});
};
this.increaseHeight = function(height, windowResized, td){
var cal = this.calendar,
cells = td || cal.find('.fc-view-month tbody tr td'),
fcDayContent = cells.find('.fc-day-content'),
cellHeight, fcDayContentHeight;
if (windowResized) fcDayContent.height(1);
cellHeight = cells.eq(0).height(),
fcDayContentHeight = cellHeight - cells.eq(0).find('.fc-day-number').height();
fcDayContent.height(fcDayContentHeight);
};
this.extendCallbacks = function(){
var self = this,
opt = self.calendar.fullCalendar('getView').calendar.options,
_eventRender = opt.eventRender,
_eventDrop = opt.eventDrop,
_eventResize = opt.eventResize,
_viewDisplay = opt.viewDisplay,
_events = opt.events,
_windowResize = opt.windowResize;
$.extend(opt, {
eventRender: function(event, element){
var currentView = self.calendar.fullCalendar('getView').name,
dateFormat = (event.allDay) ? 'MM/dd/yyyy' : 'hh:mmtt',
startDateLink = $.fullCalendar.formatDate(event.start, dateFormat),
endDateLink = $.fullCalendar.formatDate(event.end, dateFormat),
maxEvents = self.opts.maxEvents,
allEvents = self.calendar.fullCalendar('clientEvents'),
eventDate = $.fullCalendar.formatDate(event.end || event.start,'MM/dd/yy'),
td, viewMoreButton;
event.element = element;
event.startDateLink = startDateLink;
event.endDateLink = endDateLink;
if (currentView === 'month') {
doEventsRangeCount(event, self.calendar); //add event quantity to range for event and day
td = getCellFromDate(eventDate, self.calendar);
if (td.data('apptCount') > maxEvents) {
if (!td.find('.events-view-more').length) {
viewMoreButton = $('<div class="events-view-more"><a href="#view-more"><span>View More</span></a></div>')
.appendTo(td)
.click(function () {
var viewMoreClick = self.opts.viewMoreClick;
if (viewMoreClick && $.isFunction(viewMoreClick)) self.opts.viewMoreClick();
else viewMore(td, self.calendar); //show events in formBubble overlay
return false;
});
self.increaseHeight(25, false, td);
}
if ($.isFunction(_eventRender)) _eventRender(event, element);
return false; //prevents event from being rendered
}
}
if ($.isFunction(_eventRender)) _eventRender(event, element);
return true; //renders event
},
eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc) {
resetEventsRangeCounts();
if ($.isFunction(_eventDrop)) _eventDrop(event, dayDelta, minuteDelta, allDay, revertFunc);
},
eventResize: function(event){
resetEventsRangeCounts();
if ($.isFunction(_eventResize)) _eventResize(event);
},
viewDisplay: function(view){
$.fn.formBubble.close();
if (view.name !== 'month') resetEventsRangeCounts();
if ($.isFunction(_viewDisplay)) _viewDisplay(view);
},
events: function(start, end, callback) {
resetEventsRangeCounts();
if ($.isFunction(_events)) _events(start, end, callback);
},
windowResize: function(view){ //fired AFTER events are rendered
if ($.isFunction(_windowResize)) _windowResize(view);
self.increaseHeight(25, true);
resetEventsRangeCounts();
self.calendar.fullCalendar('render'); //manually render to avoid layout bug
}
});
};
function doEventsRangeCount(event, calInstance){
var eventStart = event._start,
eventEnd = event._end || event._start,
dateRange = expandDateRange(eventStart, eventEnd),
eventElement = event.element;
$(dateRange).each(function(i){
var td = getCellFromDate($.fullCalendar.formatDate(dateRange[i],'MM/dd/yy'), calInstance),
currentCount = (td.data('apptCount') || 0) + 1;
td.data('apptCount', currentCount);
if (td.data().appointments === undefined) td.data().appointments = [event];
else td.data().appointments.push(event);
});
}
function expandDateRange(start, end){
var value = new Date(start.getFullYear(), start.getMonth(), start.getDate()),
values = [];
end = new Date(end.getFullYear(), end.getMonth(), end.getDate());
if (value > end) throw "InvalidRange";
while (value <= end) {
values.push(value);
value = new Date(value.getFullYear(), value.getMonth(), value.getDate() + 1);
}
return values;
}
function resetEventsRangeCounts(){
$('.fc-view-month td').each(function(i){
$(this).find('.events-view-more').remove();
$.removeData(this, "apptCount");
$.removeData(this, "appointments");
});
}
function viewMore(day, calInstance){
var appointments = day.data('appointments'),
elemWidth = day.outerWidth() + 1,
self = this;
day.formBubble({
graphics: {
close: true,
pointer: false
},
offset: {
x: -elemWidth,
y: 0
},
animation: {
slide: false,
speed: 0
},
callbacks: {
onOpen: function(){
var bubble = $.fn.formBubble.bubbleObject;
bubble.addClass('overlay');
},
onClose: function(){
calInstance.fullCalendar('unselect');
}
},
content: function(){
var startDate = getDateFromCell(day, calInstance),
startDateLabel = startDate.toString("MMM dS"),
dayValue = parseInt(day.find('.fc-day-number').text()),
eventList=$('<ul></ul>').prepend('<li><h5>' + startDateLabel + '</h5></li>');
elemWidth = elemWidth - 30;
$(appointments).each(function(){
var apptStartDay = parseInt($.fullCalendar.formatDate(this.start,'d')), //should be comparing date instead of day (bug with gray dates) <-- fix
apptEndDay = parseInt($.fullCalendar.formatDate(this.end,'d')),
event = this.element.clone(false).attr('style', '').css('width', elemWidth);
if (apptStartDay < dayValue) $(event).addClass('arrow-left');
if (apptEndDay > dayValue) $(event).addClass('arrow-right');
event.appendTo(eventList).wrap('<li>');
});
eventList.wrap('<div>');
return eventList.parent('div').html();
}
});
}
function getCellFromDate(thisDate, calInstance){ //ties events to actual table cells, and also differentiates between "gray" dates and "black" dates
var start = calInstance.fullCalendar('getView').start,
end = calInstance.fullCalendar('getView').end,
td;
thisDate = Date.parse(thisDate);
td = $('.fc-day-number').filter(function(){
return $(this).text()===$.fullCalendar.formatDate(thisDate,'d')
}).parent('td');
if (thisDate < start){ //date is in last month
td = td.filter(':first');
}else if (thisDate >= end){ //date is in next month
td = td.filter(':last');
}else{ //date is in this month
td = td.filter(function(){
return $(this).hasClass('fc-other-month')===false;
});
}
return td;
}
function getDateFromCell(td, calInstance){
var cellPos = {
row: td.parent().parent().children().index(td.parent()),
col: td.parent().children().index(td)
};
return calInstance.fullCalendar('getView').cellDate(cellPos);
}
}).call(jQuery.fn.limitEvents.constructor.prototype, jQuery);
| JavaScript |
/*!
* FullCalendar v1.6.0
* Docs & License: http://arshaw.com/fullcalendar/
* (c) 2013 Adam Shaw
*/
/*
* Use fullcalendar.css for basic styling.
* For event drag & drop, requires jQuery UI draggable.
* For event resizing, requires jQuery UI resizable.
*/
(function($, undefined) {
;;
var defaults = {
// display
defaultView: 'month',
aspectRatio: 1.35,
header: {
left: 'title',
center: '',
right: 'today prev,next'
},
weekends: true,
weekNumbers: false,
weekNumberCalculation: 'iso',
weekNumberTitle: 'W',
// editing
//editable: false,
//disableDragging: false,
//disableResizing: false,
allDayDefault: true,
ignoreTimezone: true,
// event ajax
lazyFetching: true,
startParam: 'start',
endParam: 'end',
// time formats
titleFormat: {
month: 'MMMM yyyy',
week: "MMM d[ yyyy]{ '—'[ MMM] d yyyy}",
day: 'dddd, MMM d, yyyy'
},
columnFormat: {
month: 'ddd',
week: 'ddd M/d',
day: 'dddd M/d'
},
timeFormat: { // for event elements
'': 'h(:mm)t' // default
},
// locale
isRTL: false,
firstDay: 0,
monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
buttonText: {
prev: "<span class='fc-text-arrow'>‹</span>",
next: "<span class='fc-text-arrow'>›</span>",
prevYear: "<span class='fc-text-arrow'>«</span>",
nextYear: "<span class='fc-text-arrow'>»</span>",
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
// jquery-ui theming
theme: false,
buttonIcons: {
prev: 'circle-triangle-w',
next: 'circle-triangle-e'
},
//selectable: false,
unselectAuto: true,
dropAccept: '*'
};
// right-to-left defaults
var rtlDefaults = {
header: {
left: 'next,prev today',
center: '',
right: 'title'
},
buttonText: {
prev: "<span class='fc-text-arrow'>›</span>",
next: "<span class='fc-text-arrow'>‹</span>",
prevYear: "<span class='fc-text-arrow'>»</span>",
nextYear: "<span class='fc-text-arrow'>«</span>"
},
buttonIcons: {
prev: 'circle-triangle-e',
next: 'circle-triangle-w'
}
};
;;
var fc = $.fullCalendar = { version: "1.6.0" };
var fcViews = fc.views = {};
$.fn.fullCalendar = function(options) {
// method calling
if (typeof options == 'string') {
var args = Array.prototype.slice.call(arguments, 1);
var res;
this.each(function() {
var calendar = $.data(this, 'fullCalendar');
if (calendar && $.isFunction(calendar[options])) {
var r = calendar[options].apply(calendar, args);
if (res === undefined) {
res = r;
}
if (options == 'destroy') {
$.removeData(this, 'fullCalendar');
}
}
});
if (res !== undefined) {
return res;
}
return this;
}
// would like to have this logic in EventManager, but needs to happen before options are recursively extended
var eventSources = options.eventSources || [];
delete options.eventSources;
if (options.events) {
eventSources.push(options.events);
delete options.events;
}
options = $.extend(true, {},
defaults,
(options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {},
options
);
this.each(function(i, _element) {
var element = $(_element);
var calendar = new Calendar(element, options, eventSources);
element.data('fullCalendar', calendar); // TODO: look into memory leak implications
calendar.render();
});
return this;
};
// function for adding/overriding defaults
function setDefaults(d) {
$.extend(true, defaults, d);
}
;;
function Calendar(element, options, eventSources) {
var t = this;
// exports
t.options = options;
t.render = render;
t.destroy = destroy;
t.refetchEvents = refetchEvents;
t.reportEvents = reportEvents;
t.reportEventChange = reportEventChange;
t.rerenderEvents = rerenderEvents;
t.changeView = changeView;
t.select = select;
t.unselect = unselect;
t.prev = prev;
t.next = next;
t.prevYear = prevYear;
t.nextYear = nextYear;
t.today = today;
t.gotoDate = gotoDate;
t.incrementDate = incrementDate;
t.formatDate = function(format, date) { return formatDate(format, date, options) };
t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) };
t.getDate = getDate;
t.getView = getView;
t.option = option;
t.trigger = trigger;
// imports
EventManager.call(t, options, eventSources);
var isFetchNeeded = t.isFetchNeeded;
var fetchEvents = t.fetchEvents;
// locals
var _element = element[0];
var header;
var headerElement;
var content;
var tm; // for making theme classes
var currentView;
var viewInstances = {};
var elementOuterWidth;
var suggestedViewHeight;
var absoluteViewElement;
var resizeUID = 0;
var ignoreWindowResize = 0;
var date = new Date();
var events = [];
var _dragElement;
/* Main Rendering
-----------------------------------------------------------------------------*/
setYMD(date, options.year, options.month, options.date);
function render(inc) {
if (!content) {
initialRender();
}else{
calcSize();
markSizesDirty();
markEventsDirty();
renderView(inc);
}
}
function initialRender() {
tm = options.theme ? 'ui' : 'fc';
element.addClass('fc');
if (options.isRTL) {
element.addClass('fc-rtl');
}
else {
element.addClass('fc-ltr');
}
if (options.theme) {
element.addClass('ui-widget');
}
content = $("<div class='fc-content' style='position:relative'/>")
.prependTo(element);
header = new Header(t, options);
headerElement = header.render();
if (headerElement) {
element.prepend(headerElement);
}
changeView(options.defaultView);
$(window).resize(windowResize);
// needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
if (!bodyVisible()) {
lateRender();
}
}
// called when we know the calendar couldn't be rendered when it was initialized,
// but we think it's ready now
function lateRender() {
setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
renderView();
}
},0);
}
function destroy() {
$(window).unbind('resize', windowResize);
header.destroy();
content.remove();
element.removeClass('fc fc-rtl ui-widget');
}
function elementVisible() {
return _element.offsetWidth !== 0;
}
function bodyVisible() {
return $('body')[0].offsetWidth !== 0;
}
/* View Rendering
-----------------------------------------------------------------------------*/
// TODO: improve view switching (still weird transition in IE, and FF has whiteout problem)
function changeView(newViewName) {
if (!currentView || newViewName != currentView.name) {
ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached
unselect();
var oldView = currentView;
var newViewElement;
if (oldView) {
(oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera)
setMinHeight(content, content.height());
oldView.element.hide();
}else{
setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated
}
content.css('overflow', 'hidden');
currentView = viewInstances[newViewName];
if (currentView) {
currentView.element.show();
}else{
currentView = viewInstances[newViewName] = new fcViews[newViewName](
newViewElement = absoluteViewElement =
$("<div class='fc-view fc-view-" + newViewName + "' style='position:absolute'/>")
.appendTo(content),
t // the calendar object
);
}
if (oldView) {
header.deactivateButton(oldView.name);
}
header.activateButton(newViewName);
renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null
content.css('overflow', '');
if (oldView) {
setMinHeight(content, 1);
}
if (!newViewElement) {
(currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera)
}
ignoreWindowResize--;
}
}
function renderView(inc) {
if (elementVisible()) {
ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached
unselect();
if (suggestedViewHeight === undefined) {
calcSize();
}
var forceEventRender = false;
if (!currentView.start || inc || date < currentView.start || date >= currentView.end) {
// view must render an entire new date range (and refetch/render events)
currentView.render(date, inc || 0); // responsible for clearing events
setSize(true);
forceEventRender = true;
}
else if (currentView.sizeDirty) {
// view must resize (and rerender events)
currentView.clearEvents();
setSize();
forceEventRender = true;
}
else if (currentView.eventsDirty) {
currentView.clearEvents();
forceEventRender = true;
}
currentView.sizeDirty = false;
currentView.eventsDirty = false;
updateEvents(forceEventRender);
elementOuterWidth = element.outerWidth();
header.updateTitle(currentView.title);
var today = new Date();
if (today >= currentView.start && today < currentView.end) {
header.disableButton('today');
}else{
header.enableButton('today');
}
ignoreWindowResize--;
currentView.trigger('viewDisplay', _element);
}
}
/* Resizing
-----------------------------------------------------------------------------*/
function updateSize() {
markSizesDirty();
if (elementVisible()) {
calcSize();
setSize();
unselect();
currentView.clearEvents();
currentView.renderEvents(events);
currentView.sizeDirty = false;
}
}
function markSizesDirty() {
$.each(viewInstances, function(i, inst) {
inst.sizeDirty = true;
});
}
function calcSize() {
if (options.contentHeight) {
suggestedViewHeight = options.contentHeight;
}
else if (options.height) {
suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
}
else {
suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
}
}
function setSize(dateChanged) { // todo: dateChanged?
ignoreWindowResize++;
currentView.setHeight(suggestedViewHeight, dateChanged);
if (absoluteViewElement) {
absoluteViewElement.css('position', 'relative');
absoluteViewElement = null;
}
currentView.setWidth(content.width(), dateChanged);
ignoreWindowResize--;
}
function windowResize() {
if (!ignoreWindowResize) {
if (currentView.start) { // view has already been rendered
var uid = ++resizeUID;
setTimeout(function() { // add a delay
if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
ignoreWindowResize++; // in case the windowResize callback changes the height
updateSize();
currentView.trigger('windowResize', _element);
ignoreWindowResize--;
}
}
}, 200);
}else{
// calendar must have been initialized in a 0x0 iframe that has just been resized
lateRender();
}
}
}
/* Event Fetching/Rendering
-----------------------------------------------------------------------------*/
// fetches events if necessary, rerenders events if necessary (or if forced)
function updateEvents(forceRender) {
if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
refetchEvents();
}
else if (forceRender) {
rerenderEvents();
}
}
function refetchEvents() {
fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents
}
// called when event data arrives
function reportEvents(_events) {
events = _events;
rerenderEvents();
}
// called when a single event's data has been changed
function reportEventChange(eventID) {
rerenderEvents(eventID);
}
// attempts to rerenderEvents
function rerenderEvents(modifiedEventID) {
markEventsDirty();
if (elementVisible()) {
currentView.clearEvents();
currentView.renderEvents(events, modifiedEventID);
currentView.eventsDirty = false;
}
}
function markEventsDirty() {
$.each(viewInstances, function(i, inst) {
inst.eventsDirty = true;
});
}
/* Selection
-----------------------------------------------------------------------------*/
function select(start, end, allDay) {
currentView.select(start, end, allDay===undefined ? true : allDay);
}
function unselect() { // safe to be called before renderView
if (currentView) {
currentView.unselect();
}
}
/* Date
-----------------------------------------------------------------------------*/
function prev() {
renderView(-1);
}
function next() {
renderView(1);
}
function prevYear() {
addYears(date, -1);
renderView();
}
function nextYear() {
addYears(date, 1);
renderView();
}
function today() {
date = new Date();
renderView();
}
function gotoDate(year, month, dateOfMonth) {
if (year instanceof Date) {
date = cloneDate(year); // provided 1 argument, a Date
}else{
setYMD(date, year, month, dateOfMonth);
}
renderView();
}
function incrementDate(years, months, days) {
if (years !== undefined) {
addYears(date, years);
}
if (months !== undefined) {
addMonths(date, months);
}
if (days !== undefined) {
addDays(date, days);
}
renderView();
}
function getDate() {
return cloneDate(date);
}
/* Misc
-----------------------------------------------------------------------------*/
function getView() {
return currentView;
}
function option(name, value) {
if (value === undefined) {
return options[name];
}
if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
options[name] = value;
updateSize();
}
}
function trigger(name, thisObj) {
if (options[name]) {
return options[name].apply(
thisObj || _element,
Array.prototype.slice.call(arguments, 2)
);
}
}
/* External Dragging
------------------------------------------------------------------------*/
if (options.droppable) {
$(document)
.bind('dragstart', function(ev, ui) {
var _e = ev.target;
var e = $(_e);
if (!e.parents('.fc').length) { // not already inside a calendar
var accept = options.dropAccept;
if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
_dragElement = _e;
currentView.dragStart(_dragElement, ev, ui);
}
}
})
.bind('dragstop', function(ev, ui) {
if (_dragElement) {
currentView.dragStop(_dragElement, ev, ui);
_dragElement = null;
}
});
}
}
;;
function Header(calendar, options) {
var t = this;
// exports
t.render = render;
t.destroy = destroy;
t.updateTitle = updateTitle;
t.activateButton = activateButton;
t.deactivateButton = deactivateButton;
t.disableButton = disableButton;
t.enableButton = enableButton;
// locals
var element = $([]);
var tm;
function render() {
tm = options.theme ? 'ui' : 'fc';
var sections = options.header;
if (sections) {
element = $("<table class='fc-header' style='width:100%'/>")
.append(
$("<tr/>")
.append(renderSection('left'))
.append(renderSection('center'))
.append(renderSection('right'))
);
return element;
}
}
function destroy() {
element.remove();
}
function renderSection(position) {
var e = $("<td class='fc-header-" + position + "'/>");
var buttonStr = options.header[position];
if (buttonStr) {
$.each(buttonStr.split(' '), function(i) {
if (i > 0) {
e.append("<span class='fc-header-space'/>");
}
var prevButton;
$.each(this.split(','), function(j, buttonName) {
if (buttonName == 'title') {
e.append("<span class='fc-header-title'><h2> </h2></span>");
if (prevButton) {
prevButton.addClass(tm + '-corner-right');
}
prevButton = null;
}else{
var buttonClick;
if (calendar[buttonName]) {
buttonClick = calendar[buttonName]; // calendar method
}
else if (fcViews[buttonName]) {
buttonClick = function() {
button.removeClass(tm + '-state-hover'); // forget why
calendar.changeView(buttonName);
};
}
if (buttonClick) {
var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here?
var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here?
var button = $(
"<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" +
(icon ?
"<span class='fc-icon-wrap'>" +
"<span class='ui-icon ui-icon-" + icon + "'/>" +
"</span>" :
text
) +
"</span>"
)
.click(function() {
if (!button.hasClass(tm + '-state-disabled')) {
buttonClick();
}
})
.mousedown(function() {
button
.not('.' + tm + '-state-active')
.not('.' + tm + '-state-disabled')
.addClass(tm + '-state-down');
})
.mouseup(function() {
button.removeClass(tm + '-state-down');
})
.hover(
function() {
button
.not('.' + tm + '-state-active')
.not('.' + tm + '-state-disabled')
.addClass(tm + '-state-hover');
},
function() {
button
.removeClass(tm + '-state-hover')
.removeClass(tm + '-state-down');
}
)
.appendTo(e);
disableTextSelection(button);
if (!prevButton) {
button.addClass(tm + '-corner-left');
}
prevButton = button;
}
}
});
if (prevButton) {
prevButton.addClass(tm + '-corner-right');
}
});
}
return e;
}
function updateTitle(html) {
element.find('h2')
.html(html);
}
function activateButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.addClass(tm + '-state-active');
}
function deactivateButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.removeClass(tm + '-state-active');
}
function disableButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.addClass(tm + '-state-disabled');
}
function enableButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.removeClass(tm + '-state-disabled');
}
}
;;
fc.sourceNormalizers = [];
fc.sourceFetchers = [];
var ajaxDefaults = {
dataType: 'json',
cache: false
};
var eventGUID = 1;
function EventManager(options, _sources) {
var t = this;
// exports
t.isFetchNeeded = isFetchNeeded;
t.fetchEvents = fetchEvents;
t.addEventSource = addEventSource;
t.removeEventSource = removeEventSource;
t.updateEvent = updateEvent;
t.renderEvent = renderEvent;
t.removeEvents = removeEvents;
t.clientEvents = clientEvents;
t.normalizeEvent = normalizeEvent;
// imports
var trigger = t.trigger;
var getView = t.getView;
var reportEvents = t.reportEvents;
// locals
var stickySource = { events: [] };
var sources = [ stickySource ];
var rangeStart, rangeEnd;
var currentFetchID = 0;
var pendingSourceCnt = 0;
var loadingLevel = 0;
var cache = [];
for (var i=0; i<_sources.length; i++) {
_addEventSource(_sources[i]);
}
/* Fetching
-----------------------------------------------------------------------------*/
function isFetchNeeded(start, end) {
return !rangeStart || start < rangeStart || end > rangeEnd;
}
function fetchEvents(start, end) {
rangeStart = start;
rangeEnd = end;
cache = [];
var fetchID = ++currentFetchID;
var len = sources.length;
pendingSourceCnt = len;
for (var i=0; i<len; i++) {
fetchEventSource(sources[i], fetchID);
}
}
function fetchEventSource(source, fetchID) {
_fetchEventSource(source, function(events) {
if (fetchID == currentFetchID) {
if (events) {
if (options.eventDataTransform) {
events = $.map(events, options.eventDataTransform);
}
if (source.eventDataTransform) {
events = $.map(events, source.eventDataTransform);
}
// TODO: this technique is not ideal for static array event sources.
// For arrays, we'll want to process all events right in the beginning, then never again.
for (var i=0; i<events.length; i++) {
events[i].source = source;
normalizeEvent(events[i]);
}
cache = cache.concat(events);
}
pendingSourceCnt--;
if (!pendingSourceCnt) {
reportEvents(cache);
}
}
});
}
function _fetchEventSource(source, callback) {
var i;
var fetchers = fc.sourceFetchers;
var res;
for (i=0; i<fetchers.length; i++) {
res = fetchers[i](source, rangeStart, rangeEnd, callback);
if (res === true) {
// the fetcher is in charge. made its own async request
return;
}
else if (typeof res == 'object') {
// the fetcher returned a new source. process it
_fetchEventSource(res, callback);
return;
}
}
var events = source.events;
if (events) {
if ($.isFunction(events)) {
pushLoading();
events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) {
callback(events);
popLoading();
});
}
else if ($.isArray(events)) {
callback(events);
}
else {
callback();
}
}else{
var url = source.url;
if (url) {
var success = source.success;
var error = source.error;
var complete = source.complete;
var data = $.extend({}, source.data || {});
var startParam = firstDefined(source.startParam, options.startParam);
var endParam = firstDefined(source.endParam, options.endParam);
if (startParam) {
data[startParam] = Math.round(+rangeStart / 1000);
}
if (endParam) {
data[endParam] = Math.round(+rangeEnd / 1000);
}
pushLoading();
$.ajax($.extend({}, ajaxDefaults, source, {
data: data,
success: function(events) {
events = events || [];
var res = applyAll(success, this, arguments);
if ($.isArray(res)) {
events = res;
}
callback(events);
},
error: function() {
applyAll(error, this, arguments);
callback();
},
complete: function() {
applyAll(complete, this, arguments);
popLoading();
}
}));
}else{
callback();
}
}
}
/* Sources
-----------------------------------------------------------------------------*/
function addEventSource(source) {
source = _addEventSource(source);
if (source) {
pendingSourceCnt++;
fetchEventSource(source, currentFetchID); // will eventually call reportEvents
}
}
function _addEventSource(source) {
if ($.isFunction(source) || $.isArray(source)) {
source = { events: source };
}
else if (typeof source == 'string') {
source = { url: source };
}
if (typeof source == 'object') {
normalizeSource(source);
sources.push(source);
return source;
}
}
function removeEventSource(source) {
sources = $.grep(sources, function(src) {
return !isSourcesEqual(src, source);
});
// remove all client events from that source
cache = $.grep(cache, function(e) {
return !isSourcesEqual(e.source, source);
});
reportEvents(cache);
}
/* Manipulation
-----------------------------------------------------------------------------*/
function updateEvent(event) { // update an existing event
var i, len = cache.length, e,
defaultEventEnd = getView().defaultEventEnd, // getView???
startDelta = event.start - event._start,
endDelta = event.end ?
(event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end
: 0; // was null and event was just resized
for (i=0; i<len; i++) {
e = cache[i];
if (e._id == event._id && e != event) {
e.start = new Date(+e.start + startDelta);
if (event.end) {
if (e.end) {
e.end = new Date(+e.end + endDelta);
}else{
e.end = new Date(+defaultEventEnd(e) + endDelta);
}
}else{
e.end = null;
}
e.title = event.title;
e.url = event.url;
e.allDay = event.allDay;
e.className = event.className;
e.editable = event.editable;
e.color = event.color;
e.backgroudColor = event.backgroudColor;
e.borderColor = event.borderColor;
e.textColor = event.textColor;
normalizeEvent(e);
}
}
normalizeEvent(event);
reportEvents(cache);
}
function renderEvent(event, stick) {
normalizeEvent(event);
if (!event.source) {
if (stick) {
stickySource.events.push(event);
event.source = stickySource;
}
cache.push(event);
}
reportEvents(cache);
}
function removeEvents(filter) {
if (!filter) { // remove all
cache = [];
// clear all array sources
for (var i=0; i<sources.length; i++) {
if ($.isArray(sources[i].events)) {
sources[i].events = [];
}
}
}else{
if (!$.isFunction(filter)) { // an event ID
var id = filter + '';
filter = function(e) {
return e._id == id;
};
}
cache = $.grep(cache, filter, true);
// remove events from array sources
for (var i=0; i<sources.length; i++) {
if ($.isArray(sources[i].events)) {
sources[i].events = $.grep(sources[i].events, filter, true);
}
}
}
reportEvents(cache);
}
function clientEvents(filter) {
if ($.isFunction(filter)) {
return $.grep(cache, filter);
}
else if (filter) { // an event ID
filter += '';
return $.grep(cache, function(e) {
return e._id == filter;
});
}
return cache; // else, return all
}
/* Loading State
-----------------------------------------------------------------------------*/
function pushLoading() {
if (!loadingLevel++) {
trigger('loading', null, true);
}
}
function popLoading() {
if (!--loadingLevel) {
trigger('loading', null, false);
}
}
/* Event Normalization
-----------------------------------------------------------------------------*/
function normalizeEvent(event) {
var source = event.source || {};
var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone);
event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + '');
if (event.date) {
if (!event.start) {
event.start = event.date;
}
delete event.date;
}
event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone));
event.end = parseDate(event.end, ignoreTimezone);
if (event.end && event.end <= event.start) {
event.end = null;
}
event._end = event.end ? cloneDate(event.end) : null;
if (event.allDay === undefined) {
event.allDay = firstDefined(source.allDayDefault, options.allDayDefault);
}
if (event.className) {
if (typeof event.className == 'string') {
event.className = event.className.split(/\s+/);
}
}else{
event.className = [];
}
// TODO: if there is no start date, return false to indicate an invalid event
}
/* Utils
------------------------------------------------------------------------------*/
function normalizeSource(source) {
if (source.className) {
// TODO: repeat code, same code for event classNames
if (typeof source.className == 'string') {
source.className = source.className.split(/\s+/);
}
}else{
source.className = [];
}
var normalizers = fc.sourceNormalizers;
for (var i=0; i<normalizers.length; i++) {
normalizers[i](source);
}
}
function isSourcesEqual(source1, source2) {
return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
}
function getSourcePrimitive(source) {
return ((typeof source == 'object') ? (source.events || source.url) : '') || source;
}
}
;;
fc.addDays = addDays;
fc.cloneDate = cloneDate;
fc.parseDate = parseDate;
fc.parseISO8601 = parseISO8601;
fc.parseTime = parseTime;
fc.formatDate = formatDate;
fc.formatDates = formatDates;
/* Date Math
-----------------------------------------------------------------------------*/
var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
DAY_MS = 86400000,
HOUR_MS = 3600000,
MINUTE_MS = 60000;
function addYears(d, n, keepTime) {
d.setFullYear(d.getFullYear() + n);
if (!keepTime) {
clearTime(d);
}
return d;
}
function addMonths(d, n, keepTime) { // prevents day overflow/underflow
if (+d) { // prevent infinite looping on invalid dates
var m = d.getMonth() + n,
check = cloneDate(d);
check.setDate(1);
check.setMonth(m);
d.setMonth(m);
if (!keepTime) {
clearTime(d);
}
while (d.getMonth() != check.getMonth()) {
d.setDate(d.getDate() + (d < check ? 1 : -1));
}
}
return d;
}
function addDays(d, n, keepTime) { // deals with daylight savings
if (+d) {
var dd = d.getDate() + n,
check = cloneDate(d);
check.setHours(9); // set to middle of day
check.setDate(dd);
d.setDate(dd);
if (!keepTime) {
clearTime(d);
}
fixDate(d, check);
}
return d;
}
function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes
if (+d) { // prevent infinite looping on invalid dates
while (d.getDate() != check.getDate()) {
d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS);
}
}
}
function addMinutes(d, n) {
d.setMinutes(d.getMinutes() + n);
return d;
}
function clearTime(d) {
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
return d;
}
function cloneDate(d, dontKeepTime) {
if (dontKeepTime) {
return clearTime(new Date(+d));
}
return new Date(+d);
}
function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1
var i=0, d;
do {
d = new Date(1970, i++, 1);
} while (d.getHours()); // != 0
return d;
}
function skipWeekend(date, inc, excl) {
inc = inc || 1;
while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) {
addDays(date, inc);
}
return date;
}
function dayDiff(d1, d2) { // d1 - d2
return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS);
}
function setYMD(date, y, m, d) {
if (y !== undefined && y != date.getFullYear()) {
date.setDate(1);
date.setMonth(0);
date.setFullYear(y);
}
if (m !== undefined && m != date.getMonth()) {
date.setDate(1);
date.setMonth(m);
}
if (d !== undefined) {
date.setDate(d);
}
}
/* Date Parsing
-----------------------------------------------------------------------------*/
function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true
if (typeof s == 'object') { // already a Date object
return s;
}
if (typeof s == 'number') { // a UNIX timestamp
return new Date(s * 1000);
}
if (typeof s == 'string') {
if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp
return new Date(parseFloat(s) * 1000);
}
if (ignoreTimezone === undefined) {
ignoreTimezone = true;
}
return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null);
}
// TODO: never return invalid dates (like from new Date(<string>)), return null instead
return null;
}
function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false
// derived from http://delete.me.uk/2005/03/iso8601.html
// TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html
var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/);
if (!m) {
return null;
}
var date = new Date(m[1], 0, 1);
if (ignoreTimezone || !m[13]) {
var check = new Date(m[1], 0, 1, 9, 0);
if (m[3]) {
date.setMonth(m[3] - 1);
check.setMonth(m[3] - 1);
}
if (m[5]) {
date.setDate(m[5]);
check.setDate(m[5]);
}
fixDate(date, check);
if (m[7]) {
date.setHours(m[7]);
}
if (m[8]) {
date.setMinutes(m[8]);
}
if (m[10]) {
date.setSeconds(m[10]);
}
if (m[12]) {
date.setMilliseconds(Number("0." + m[12]) * 1000);
}
fixDate(date, check);
}else{
date.setUTCFullYear(
m[1],
m[3] ? m[3] - 1 : 0,
m[5] || 1
);
date.setUTCHours(
m[7] || 0,
m[8] || 0,
m[10] || 0,
m[12] ? Number("0." + m[12]) * 1000 : 0
);
if (m[14]) {
var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0);
offset *= m[15] == '-' ? 1 : -1;
date = new Date(+date + (offset * 60 * 1000));
}
}
return date;
}
function parseTime(s) { // returns minutes since start of day
if (typeof s == 'number') { // an hour
return s * 60;
}
if (typeof s == 'object') { // a Date object
return s.getHours() * 60 + s.getMinutes();
}
var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/);
if (m) {
var h = parseInt(m[1], 10);
if (m[3]) {
h %= 12;
if (m[3].toLowerCase().charAt(0) == 'p') {
h += 12;
}
}
return h * 60 + (m[2] ? parseInt(m[2], 10) : 0);
}
}
/* Date Formatting
-----------------------------------------------------------------------------*/
// TODO: use same function formatDate(date, [date2], format, [options])
function formatDate(date, format, options) {
return formatDates(date, null, format, options);
}
function formatDates(date1, date2, format, options) {
options = options || defaults;
var date = date1,
otherDate = date2,
i, len = format.length, c,
i2, formatter,
res = '';
for (i=0; i<len; i++) {
c = format.charAt(i);
if (c == "'") {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == "'") {
if (date) {
if (i2 == i+1) {
res += "'";
}else{
res += format.substring(i+1, i2);
}
i = i2;
}
break;
}
}
}
else if (c == '(') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ')') {
var subres = formatDate(date, format.substring(i+1, i2), options);
if (parseInt(subres.replace(/\D/, ''), 10)) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '[') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ']') {
var subformat = format.substring(i+1, i2);
var subres = formatDate(date, subformat, options);
if (subres != formatDate(otherDate, subformat, options)) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '{') {
date = date2;
otherDate = date1;
}
else if (c == '}') {
date = date1;
otherDate = date2;
}
else {
for (i2=len; i2>i; i2--) {
if (formatter = dateFormatters[format.substring(i, i2)]) {
if (date) {
res += formatter(date, options);
}
i = i2 - 1;
break;
}
}
if (i2 == i) {
if (date) {
res += c;
}
}
}
}
return res;
};
var dateFormatters = {
s : function(d) { return d.getSeconds() },
ss : function(d) { return zeroPad(d.getSeconds()) },
m : function(d) { return d.getMinutes() },
mm : function(d) { return zeroPad(d.getMinutes()) },
h : function(d) { return d.getHours() % 12 || 12 },
hh : function(d) { return zeroPad(d.getHours() % 12 || 12) },
H : function(d) { return d.getHours() },
HH : function(d) { return zeroPad(d.getHours()) },
d : function(d) { return d.getDate() },
dd : function(d) { return zeroPad(d.getDate()) },
ddd : function(d,o) { return o.dayNamesShort[d.getDay()] },
dddd: function(d,o) { return o.dayNames[d.getDay()] },
M : function(d) { return d.getMonth() + 1 },
MM : function(d) { return zeroPad(d.getMonth() + 1) },
MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] },
MMMM: function(d,o) { return o.monthNames[d.getMonth()] },
yy : function(d) { return (d.getFullYear()+'').substring(2) },
yyyy: function(d) { return d.getFullYear() },
t : function(d) { return d.getHours() < 12 ? 'a' : 'p' },
tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' },
T : function(d) { return d.getHours() < 12 ? 'A' : 'P' },
TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' },
u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") },
S : function(d) {
var date = d.getDate();
if (date > 10 && date < 20) {
return 'th';
}
return ['st', 'nd', 'rd'][date%10-1] || 'th';
},
w : function(d, o) { // local
return o.weekNumberCalculation(d);
},
W : function(d) { // ISO
return iso8601Week(d);
}
};
fc.dateFormatters = dateFormatters;
/* thanks jQuery UI (https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js)
*
* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* @param date Date - the date to get the week for
* @return number - the number of the week within the year that contains this date
*/
function iso8601Week(date) {
var time;
var checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}
;;
fc.applyAll = applyAll;
/* Event Date Math
-----------------------------------------------------------------------------*/
function exclEndDay(event) {
if (event.end) {
return _exclEndDay(event.end, event.allDay);
}else{
return addDays(cloneDate(event.start), 1);
}
}
function _exclEndDay(end, allDay) {
end = cloneDate(end);
return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end);
}
function segCmp(a, b) {
return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start);
}
function segsCollide(seg1, seg2) {
return seg1.end > seg2.start && seg1.start < seg2.end;
}
/* Event Sorting
-----------------------------------------------------------------------------*/
// event rendering utilities
function sliceSegs(events, visEventEnds, start, end) {
var segs = [],
i, len=events.length, event,
eventStart, eventEnd,
segStart, segEnd,
isStart, isEnd;
for (i=0; i<len; i++) {
event = events[i];
eventStart = event.start;
eventEnd = visEventEnds[i];
if (eventEnd > start && eventStart < end) {
if (eventStart < start) {
segStart = cloneDate(start);
isStart = false;
}else{
segStart = eventStart;
isStart = true;
}
if (eventEnd > end) {
segEnd = cloneDate(end);
isEnd = false;
}else{
segEnd = eventEnd;
isEnd = true;
}
segs.push({
event: event,
start: segStart,
end: segEnd,
isStart: isStart,
isEnd: isEnd,
msLength: segEnd - segStart
});
}
}
return segs.sort(segCmp);
}
// event rendering calculation utilities
function stackSegs(segs) {
var levels = [],
i, len = segs.length, seg,
j, collide, k;
for (i=0; i<len; i++) {
seg = segs[i];
j = 0; // the level index where seg should belong
while (true) {
collide = false;
if (levels[j]) {
for (k=0; k<levels[j].length; k++) {
if (segsCollide(levels[j][k], seg)) {
collide = true;
break;
}
}
}
if (collide) {
j++;
}else{
break;
}
}
if (levels[j]) {
levels[j].push(seg);
}else{
levels[j] = [seg];
}
}
return levels;
}
/* Event Element Binding
-----------------------------------------------------------------------------*/
function lazySegBind(container, segs, bindHandlers) {
container.unbind('mouseover').mouseover(function(ev) {
var parent=ev.target, e,
i, seg;
while (parent != this) {
e = parent;
parent = parent.parentNode;
}
if ((i = e._fci) !== undefined) {
e._fci = undefined;
seg = segs[i];
bindHandlers(seg.event, seg.element, seg);
$(ev.target).trigger(ev);
}
ev.stopPropagation();
});
}
/* Element Dimensions
-----------------------------------------------------------------------------*/
function setOuterWidth(element, width, includeMargins) {
for (var i=0, e; i<element.length; i++) {
e = $(element[i]);
e.width(Math.max(0, width - hsides(e, includeMargins)));
}
}
function setOuterHeight(element, height, includeMargins) {
for (var i=0, e; i<element.length; i++) {
e = $(element[i]);
e.height(Math.max(0, height - vsides(e, includeMargins)));
}
}
function hsides(element, includeMargins) {
return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0);
}
function hpadding(element) {
return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) +
(parseFloat($.css(element[0], 'paddingRight', true)) || 0);
}
function hmargins(element) {
return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) +
(parseFloat($.css(element[0], 'marginRight', true)) || 0);
}
function hborders(element) {
return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) +
(parseFloat($.css(element[0], 'borderRightWidth', true)) || 0);
}
function vsides(element, includeMargins) {
return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0);
}
function vpadding(element) {
return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) +
(parseFloat($.css(element[0], 'paddingBottom', true)) || 0);
}
function vmargins(element) {
return (parseFloat($.css(element[0], 'marginTop', true)) || 0) +
(parseFloat($.css(element[0], 'marginBottom', true)) || 0);
}
function vborders(element) {
return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) +
(parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0);
}
function setMinHeight(element, height) {
height = (typeof height == 'number' ? height + 'px' : height);
element.each(function(i, _element) {
_element.style.cssText += ';min-height:' + height + ';_height:' + height;
// why can't we just use .css() ? i forget
});
}
/* Misc Utils
-----------------------------------------------------------------------------*/
//TODO: arraySlice
//TODO: isFunction, grep ?
function noop() { }
function cmp(a, b) {
return a - b;
}
function arrayMax(a) {
return Math.max.apply(Math, a);
}
function zeroPad(n) {
return (n < 10 ? '0' : '') + n;
}
function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
if (obj[name] !== undefined) {
return obj[name];
}
var parts = name.split(/(?=[A-Z])/),
i=parts.length-1, res;
for (; i>=0; i--) {
res = obj[parts[i].toLowerCase()];
if (res !== undefined) {
return res;
}
}
return obj[''];
}
function htmlEscape(s) {
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/\n/g, '<br />');
}
function cssKey(_element) {
return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, '');
}
function disableTextSelection(element) {
element
.attr('unselectable', 'on')
.css('MozUserSelect', 'none')
.bind('selectstart.ui', function() { return false; });
}
/*
function enableTextSelection(element) {
element
.attr('unselectable', 'off')
.css('MozUserSelect', '')
.unbind('selectstart.ui');
}
*/
function markFirstLast(e) {
e.children()
.removeClass('fc-first fc-last')
.filter(':first-child')
.addClass('fc-first')
.end()
.filter(':last-child')
.addClass('fc-last');
}
function setDayID(cell, date) {
cell.each(function(i, _cell) {
_cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]);
// TODO: make a way that doesn't rely on order of classes
});
}
function getSkinCss(event, opt) {
var source = event.source || {};
var eventColor = event.color;
var sourceColor = source.color;
var optionColor = opt('eventColor');
var backgroundColor =
event.backgroundColor ||
eventColor ||
source.backgroundColor ||
sourceColor ||
opt('eventBackgroundColor') ||
optionColor;
var borderColor =
event.borderColor ||
eventColor ||
source.borderColor ||
sourceColor ||
opt('eventBorderColor') ||
optionColor;
var textColor =
event.textColor ||
source.textColor ||
opt('eventTextColor');
var statements = [];
if (backgroundColor) {
statements.push('background-color:' + backgroundColor);
}
if (borderColor) {
statements.push('border-color:' + borderColor);
}
if (textColor) {
statements.push('color:' + textColor);
}
return statements.join(';');
}
function applyAll(functions, thisObj, args) {
if ($.isFunction(functions)) {
functions = [ functions ];
}
if (functions) {
var i;
var ret;
for (i=0; i<functions.length; i++) {
ret = functions[i].apply(thisObj, args) || ret;
}
return ret;
}
}
function firstDefined() {
for (var i=0; i<arguments.length; i++) {
if (arguments[i] !== undefined) {
return arguments[i];
}
}
}
;;
fcViews.month = MonthView;
function MonthView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'month');
var opt = t.opt;
var renderBasic = t.renderBasic;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addMonths(date, delta);
date.setDate(1);
}
var start = cloneDate(date, true);
start.setDate(1);
var end = addMonths(cloneDate(start), 1);
var visStart = cloneDate(start);
var visEnd = cloneDate(end);
var firstDay = opt('firstDay');
var nwe = opt('weekends') ? 0 : 1;
if (nwe) {
skipWeekend(visStart);
skipWeekend(visEnd, -1, true);
}
addDays(visStart, -((visStart.getDay() - Math.max(firstDay, nwe) + 7) % 7));
addDays(visEnd, (7 - visEnd.getDay() + Math.max(firstDay, nwe)) % 7);
var rowCnt = Math.round((visEnd - visStart) / (DAY_MS * 7));
if (opt('weekMode') == 'fixed') {
addDays(visEnd, (6 - rowCnt) * 7);
rowCnt = 6;
}
t.title = formatDate(start, opt('titleFormat'));
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
renderBasic(rowCnt, nwe ? 5 : 7, true);
}
}
;;
fcViews.basicWeek = BasicWeekView;
function BasicWeekView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'basicWeek');
var opt = t.opt;
var renderBasic = t.renderBasic;
var formatDates = calendar.formatDates;
function render(date, delta) {
if (delta) {
addDays(date, delta * 7);
}
var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
var end = addDays(cloneDate(start), 7);
var visStart = cloneDate(start);
var visEnd = cloneDate(end);
var weekends = opt('weekends');
if (!weekends) {
skipWeekend(visStart);
skipWeekend(visEnd, -1, true);
}
t.title = formatDates(
visStart,
addDays(cloneDate(visEnd), -1),
opt('titleFormat')
);
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
renderBasic(1, weekends ? 7 : 5, false);
}
}
;;
fcViews.basicDay = BasicDayView;
//TODO: when calendar's date starts out on a weekend, shouldn't happen
function BasicDayView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'basicDay');
var opt = t.opt;
var renderBasic = t.renderBasic;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addDays(date, delta);
if (!opt('weekends')) {
skipWeekend(date, delta < 0 ? -1 : 1);
}
}
t.title = formatDate(date, opt('titleFormat'));
t.start = t.visStart = cloneDate(date, true);
t.end = t.visEnd = addDays(cloneDate(t.start), 1);
renderBasic(1, 1, false);
}
}
;;
setDefaults({
weekMode: 'fixed'
});
function BasicView(element, calendar, viewName) {
var t = this;
// exports
t.renderBasic = renderBasic;
t.setHeight = setHeight;
t.setWidth = setWidth;
t.renderDayOverlay = renderDayOverlay;
t.defaultSelectionEnd = defaultSelectionEnd;
t.renderSelection = renderSelection;
t.clearSelection = clearSelection;
t.reportDayClick = reportDayClick; // for selection (kinda hacky)
t.dragStart = dragStart;
t.dragStop = dragStop;
t.defaultEventEnd = defaultEventEnd;
t.getHoverListener = function() { return hoverListener };
t.colContentLeft = colContentLeft;
t.colContentRight = colContentRight;
t.dayOfWeekCol = dayOfWeekCol;
t.dateCell = dateCell;
t.cellDate = cellDate;
t.cellIsAllDay = function() { return true };
t.allDayRow = allDayRow;
t.allDayBounds = allDayBounds;
t.getRowCnt = function() { return rowCnt };
t.getColCnt = function() { return colCnt };
t.getColWidth = function() { return colWidth };
t.getDaySegmentContainer = function() { return daySegmentContainer };
// imports
View.call(t, element, calendar, viewName);
OverlayManager.call(t);
SelectionManager.call(t);
BasicEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var clearEvents = t.clearEvents;
var renderOverlay = t.renderOverlay;
var clearOverlays = t.clearOverlays;
var daySelectionMousedown = t.daySelectionMousedown;
var formatDate = calendar.formatDate;
// locals
var table;
var head;
var headCells;
var body;
var bodyRows;
var bodyCells;
var bodyFirstCells;
var bodyCellTopInners;
var daySegmentContainer;
var viewWidth;
var viewHeight;
var colWidth;
var weekNumberWidth;
var rowCnt, colCnt;
var coordinateGrid;
var hoverListener;
var colContentPositions;
var rtl, dis, dit;
var firstDay;
var nwe; // no weekends? a 0 or 1 for easy computations
var tm;
var colFormat;
var showWeekNumbers;
var weekNumberTitle;
var weekNumberFormat;
/* Rendering
------------------------------------------------------------*/
disableTextSelection(element.addClass('fc-grid'));
function renderBasic(r, c, showNumbers) {
rowCnt = r;
colCnt = c;
updateOptions();
var firstTime = !body;
if (firstTime) {
buildEventContainer();
}else{
clearEvents();
}
buildTable(showNumbers);
}
function updateOptions() {
rtl = opt('isRTL');
if (rtl) {
dis = -1;
dit = colCnt - 1;
}else{
dis = 1;
dit = 0;
}
firstDay = opt('firstDay');
nwe = opt('weekends') ? 0 : 1;
tm = opt('theme') ? 'ui' : 'fc';
colFormat = opt('columnFormat');
// week # options. (TODO: bad, logic also in other views)
showWeekNumbers = opt('weekNumbers');
weekNumberTitle = opt('weekNumberTitle');
if (opt('weekNumberCalculation') != 'iso') {
weekNumberFormat = "w";
}
else {
weekNumberFormat = "W";
}
}
function buildEventContainer() {
daySegmentContainer =
$("<div style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(element);
}
function buildTable(showNumbers) {
var html = '';
var i, j;
var headerClass = tm + "-widget-header";
var contentClass = tm + "-widget-content";
var month = t.start.getMonth();
var today = clearTime(new Date());
var cellDate; // not to be confused with local function. TODO: better names
var cellClasses;
var cell;
html += "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" +
"<thead>" +
"<tr>";
if (showWeekNumbers) {
html += "<th class='fc-week-number " + headerClass + "'/>";
}
for (i=0; i<colCnt; i++) {
html += "<th class='fc-day-header fc-" + dayIDs[i] + " " + headerClass + "'/>";
}
html += "</tr>" +
"</thead>" +
"<tbody>";
for (i=0; i<rowCnt; i++) {
html += "<tr class='fc-week'>";
if (showWeekNumbers) {
html += "<td class='fc-week-number " + contentClass + "'>" +
"<div/>" +
"</td>";
}
for (j=0; j<colCnt; j++) {
cellDate = _cellDate(i, j); // a little confusing. cellDate is local variable. _cellDate is private function
cellClasses = [
'fc-day',
'fc-' + dayIDs[cellDate.getDay()],
contentClass
];
if (cellDate.getMonth() != month) {
cellClasses.push('fc-other-month');
}
if (+cellDate == +today) {
cellClasses.push('fc-today');
cellClasses.push(tm + '-state-highlight');
}
html += "<td" +
" class='" + cellClasses.join(' ') + "'" +
" data-date='" + formatDate(cellDate, 'yyyy-MM-dd') + "'" +
">" +
"<div>";
if (showNumbers) {
html += "<div class='fc-day-number'>" + cellDate.getDate() + "</div>";
}
html += "<div class='fc-day-content'>" +
"<div style='position:relative'> </div>" +
"</div>" +
"</div>" +
"</td>";
}
html += "</tr>";
}
html += "</tbody>" +
"</table>";
lockHeight(); // the unlock happens later, in setHeight()...
if (table) {
table.remove();
}
table = $(html).appendTo(element);
head = table.find('thead');
headCells = head.find('.fc-day-header');
body = table.find('tbody');
bodyRows = body.find('tr');
bodyCells = body.find('.fc-day');
bodyFirstCells = bodyRows.find('td:first-child');
bodyCellTopInners = bodyRows.eq(0).find('.fc-day-content > div');
markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's
markFirstLast(bodyRows); // marks first+last td's
bodyRows.eq(0).addClass('fc-first');
bodyRows.filter(':last').addClass('fc-last');
if (showWeekNumbers) {
head.find('.fc-week-number').text(weekNumberTitle);
}
headCells.each(function(i, _cell) {
var date = indexDate(i);
$(_cell).text(formatDate(date, colFormat));
});
if (showWeekNumbers) {
body.find('.fc-week-number > div').each(function(i, _cell) {
var weekStart = _cellDate(i, 0);
$(_cell).text(formatDate(weekStart, weekNumberFormat));
});
}
bodyCells.each(function(i, _cell) {
var date = indexDate(i);
trigger('dayRender', t, date, $(_cell));
});
dayBind(bodyCells);
}
function setHeight(height) {
viewHeight = height;
var bodyHeight = viewHeight - head.height();
var rowHeight;
var rowHeightLast;
var cell;
if (opt('weekMode') == 'variable') {
rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6));
}else{
rowHeight = Math.floor(bodyHeight / rowCnt);
rowHeightLast = bodyHeight - rowHeight * (rowCnt-1);
}
bodyFirstCells.each(function(i, _cell) {
if (i < rowCnt) {
cell = $(_cell);
setMinHeight(
cell.find('> div'),
(i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell)
);
}
});
unlockHeight();
}
function setWidth(width) {
viewWidth = width;
colContentPositions.clear();
weekNumberWidth = 0;
if (showWeekNumbers) {
weekNumberWidth = head.find('th.fc-week-number').outerWidth();
}
colWidth = Math.floor((viewWidth - weekNumberWidth) / colCnt);
setOuterWidth(headCells.slice(0, -1), colWidth);
}
/* Day clicking and binding
-----------------------------------------------------------*/
function dayBind(days) {
days.click(dayClick)
.mousedown(daySelectionMousedown);
}
function dayClick(ev) {
if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
var date = parseISO8601($(this).data('date'));
trigger('dayClick', this, date, true, ev);
}
}
/* Semi-transparent Overlay Helpers
------------------------------------------------------*/
function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
if (refreshCoordinateGrid) {
coordinateGrid.build();
}
var rowStart = cloneDate(t.visStart);
var rowEnd = addDays(cloneDate(rowStart), colCnt);
for (var i=0; i<rowCnt; i++) {
var stretchStart = new Date(Math.max(rowStart, overlayStart));
var stretchEnd = new Date(Math.min(rowEnd, overlayEnd));
if (stretchStart < stretchEnd) {
var colStart, colEnd;
if (rtl) {
colStart = dayDiff(stretchEnd, rowStart)*dis+dit+1;
colEnd = dayDiff(stretchStart, rowStart)*dis+dit+1;
}else{
colStart = dayDiff(stretchStart, rowStart);
colEnd = dayDiff(stretchEnd, rowStart);
}
dayBind(
renderCellOverlay(i, colStart, i, colEnd-1)
);
}
addDays(rowStart, 7);
addDays(rowEnd, 7);
}
}
function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive
var rect = coordinateGrid.rect(row0, col0, row1, col1, element);
return renderOverlay(rect, element);
}
/* Selection
-----------------------------------------------------------------------*/
function defaultSelectionEnd(startDate, allDay) {
return cloneDate(startDate);
}
function renderSelection(startDate, endDate, allDay) {
renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time???
}
function clearSelection() {
clearOverlays();
}
function reportDayClick(date, allDay, ev) {
var cell = dateCell(date);
var _element = bodyCells[cell.row*colCnt + cell.col];
trigger('dayClick', _element, date, allDay, ev);
}
/* External Dragging
-----------------------------------------------------------------------*/
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function(cell) {
clearOverlays();
if (cell) {
renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
}
}, ev);
}
function dragStop(_dragElement, ev, ui) {
var cell = hoverListener.stop();
clearOverlays();
if (cell) {
var d = cellDate(cell);
trigger('drop', _dragElement, d, true, ev, ui);
}
}
/* Utilities
--------------------------------------------------------*/
function defaultEventEnd(event) {
return cloneDate(event.start);
}
coordinateGrid = new CoordinateGrid(function(rows, cols) {
var e, n, p;
headCells.each(function(i, _e) {
e = $(_e);
n = e.offset().left;
if (i) {
p[1] = n;
}
p = [n];
cols[i] = p;
});
p[1] = n + e.outerWidth();
bodyRows.each(function(i, _e) {
if (i < rowCnt) {
e = $(_e);
n = e.offset().top;
if (i) {
p[1] = n;
}
p = [n];
rows[i] = p;
}
});
p[1] = n + e.outerHeight();
});
hoverListener = new HoverListener(coordinateGrid);
colContentPositions = new HorizontalPositionCache(function(col) {
return bodyCellTopInners.eq(col);
});
function colContentLeft(col) {
return colContentPositions.left(col);
}
function colContentRight(col) {
return colContentPositions.right(col);
}
function dateCell(date) {
return {
row: Math.floor(dayDiff(date, t.visStart) / 7),
col: dayOfWeekCol(date.getDay())
};
}
function cellDate(cell) {
return _cellDate(cell.row, cell.col);
}
function _cellDate(row, col) {
return addDays(cloneDate(t.visStart), row*7 + col*dis+dit);
// what about weekends in middle of week?
}
function indexDate(index) {
return _cellDate(Math.floor(index/colCnt), index%colCnt);
}
function dayOfWeekCol(dayOfWeek) {
return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt) * dis + dit;
}
function allDayRow(i) {
return bodyRows.eq(i);
}
function allDayBounds(i) {
var left = 0;
if (showWeekNumbers) {
left += weekNumberWidth;
}
return {
left: left,
right: viewWidth
};
}
// makes sure height doesn't collapse while we destroy/render new cells
// (this causes a bad end-user scrollbar jump)
// TODO: generalize this for all view rendering. (also in Calendar.js)
function lockHeight() {
setMinHeight(element, element.height());
}
function unlockHeight() {
setMinHeight(element, 1);
}
}
;;
function BasicEventRenderer() {
var t = this;
// exports
t.renderEvents = renderEvents;
t.compileDaySegs = compileSegs; // for DayEventRenderer
t.clearEvents = clearEvents;
t.bindDaySeg = bindDaySeg;
// imports
DayEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
//var setOverflowHidden = t.setOverflowHidden;
var isEventDraggable = t.isEventDraggable;
var isEventResizable = t.isEventResizable;
var reportEvents = t.reportEvents;
var reportEventClear = t.reportEventClear;
var eventElementHandlers = t.eventElementHandlers;
var showEvents = t.showEvents;
var hideEvents = t.hideEvents;
var eventDrop = t.eventDrop;
var getDaySegmentContainer = t.getDaySegmentContainer;
var getHoverListener = t.getHoverListener;
var renderDayOverlay = t.renderDayOverlay;
var clearOverlays = t.clearOverlays;
var getRowCnt = t.getRowCnt;
var getColCnt = t.getColCnt;
var renderDaySegs = t.renderDaySegs;
var resizableDayEvent = t.resizableDayEvent;
/* Rendering
--------------------------------------------------------------------*/
function renderEvents(events, modifiedEventId) {
reportEvents(events);
renderDaySegs(compileSegs(events), modifiedEventId);
trigger('eventAfterAllRender');
}
function clearEvents() {
reportEventClear();
getDaySegmentContainer().empty();
}
function compileSegs(events) {
var rowCnt = getRowCnt(),
colCnt = getColCnt(),
d1 = cloneDate(t.visStart),
d2 = addDays(cloneDate(d1), colCnt),
visEventsEnds = $.map(events, exclEndDay),
i, row,
j, level,
k, seg,
segs=[];
for (i=0; i<rowCnt; i++) {
row = stackSegs(sliceSegs(events, visEventsEnds, d1, d2));
for (j=0; j<row.length; j++) {
level = row[j];
for (k=0; k<level.length; k++) {
seg = level[k];
seg.row = i;
seg.level = j; // not needed anymore
segs.push(seg);
}
}
addDays(d1, 7);
addDays(d2, 7);
}
return segs;
}
function bindDaySeg(event, eventElement, seg) {
if (isEventDraggable(event)) {
draggableDayEvent(event, eventElement);
}
if (seg.isEnd && isEventResizable(event)) {
resizableDayEvent(event, eventElement, seg);
}
eventElementHandlers(event, eventElement);
// needs to be after, because resizableDayEvent might stopImmediatePropagation on click
}
/* Dragging
----------------------------------------------------------------------------*/
function draggableDayEvent(event, eventElement) {
var hoverListener = getHoverListener();
var dayDelta;
eventElement.draggable({
zIndex: 9,
delay: 50,
opacity: opt('dragOpacity'),
revertDuration: opt('dragRevertDuration'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta);
clearOverlays();
if (cell) {
//setOverflowHidden(true);
dayDelta = rowDelta*7 + colDelta * (opt('isRTL') ? -1 : 1);
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
}else{
//setOverflowHidden(false);
dayDelta = 0;
}
}, ev, 'drag');
},
stop: function(ev, ui) {
hoverListener.stop();
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (dayDelta) {
eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui);
}else{
eventElement.css('filter', ''); // clear IE opacity side-effects
showEvents(event, eventElement);
}
//setOverflowHidden(false);
}
});
}
}
;;
fcViews.agendaWeek = AgendaWeekView;
function AgendaWeekView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
AgendaView.call(t, element, calendar, 'agendaWeek');
var opt = t.opt;
var renderAgenda = t.renderAgenda;
var formatDates = calendar.formatDates;
function render(date, delta) {
if (delta) {
addDays(date, delta * 7);
}
var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
var end = addDays(cloneDate(start), 7);
var visStart = cloneDate(start);
var visEnd = cloneDate(end);
var weekends = opt('weekends');
if (!weekends) {
skipWeekend(visStart);
skipWeekend(visEnd, -1, true);
}
t.title = formatDates(
visStart,
addDays(cloneDate(visEnd), -1),
opt('titleFormat')
);
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
renderAgenda(weekends ? 7 : 5);
}
}
;;
fcViews.agendaDay = AgendaDayView;
function AgendaDayView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
AgendaView.call(t, element, calendar, 'agendaDay');
var opt = t.opt;
var renderAgenda = t.renderAgenda;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addDays(date, delta);
if (!opt('weekends')) {
skipWeekend(date, delta < 0 ? -1 : 1);
}
}
var start = cloneDate(date, true);
var end = addDays(cloneDate(start), 1);
t.title = formatDate(date, opt('titleFormat'));
t.start = t.visStart = start;
t.end = t.visEnd = end;
renderAgenda(1);
}
}
;;
setDefaults({
allDaySlot: true,
allDayText: 'all-day',
firstHour: 6,
slotMinutes: 30,
defaultEventMinutes: 120,
axisFormat: 'h(:mm)tt',
timeFormat: {
agenda: 'h:mm{ - h:mm}'
},
dragOpacity: {
agenda: .5
},
minTime: 0,
maxTime: 24
});
// TODO: make it work in quirks mode (event corners, all-day height)
// TODO: test liquid width, especially in IE6
function AgendaView(element, calendar, viewName) {
var t = this;
// exports
t.renderAgenda = renderAgenda;
t.setWidth = setWidth;
t.setHeight = setHeight;
t.beforeHide = beforeHide;
t.afterShow = afterShow;
t.defaultEventEnd = defaultEventEnd;
t.timePosition = timePosition;
t.dayOfWeekCol = dayOfWeekCol;
t.dateCell = dateCell;
t.cellDate = cellDate;
t.cellIsAllDay = cellIsAllDay;
t.allDayRow = getAllDayRow;
t.allDayBounds = allDayBounds;
t.getHoverListener = function() { return hoverListener };
t.colContentLeft = colContentLeft;
t.colContentRight = colContentRight;
t.getDaySegmentContainer = function() { return daySegmentContainer };
t.getSlotSegmentContainer = function() { return slotSegmentContainer };
t.getMinMinute = function() { return minMinute };
t.getMaxMinute = function() { return maxMinute };
t.getBodyContent = function() { return slotContent }; // !!??
t.getRowCnt = function() { return 1 };
t.getColCnt = function() { return colCnt };
t.getColWidth = function() { return colWidth };
t.getSnapHeight = function() { return snapHeight };
t.getSnapMinutes = function() { return snapMinutes };
t.defaultSelectionEnd = defaultSelectionEnd;
t.renderDayOverlay = renderDayOverlay;
t.renderSelection = renderSelection;
t.clearSelection = clearSelection;
t.reportDayClick = reportDayClick; // selection mousedown hack
t.dragStart = dragStart;
t.dragStop = dragStop;
// imports
View.call(t, element, calendar, viewName);
OverlayManager.call(t);
SelectionManager.call(t);
AgendaEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var clearEvents = t.clearEvents;
var renderOverlay = t.renderOverlay;
var clearOverlays = t.clearOverlays;
var reportSelection = t.reportSelection;
var unselect = t.unselect;
var daySelectionMousedown = t.daySelectionMousedown;
var slotSegHtml = t.slotSegHtml;
var formatDate = calendar.formatDate;
// locals
var dayTable;
var dayHead;
var dayHeadCells;
var dayBody;
var dayBodyCells;
var dayBodyCellInners;
var dayBodyFirstCell;
var dayBodyFirstCellStretcher;
var slotLayer;
var daySegmentContainer;
var allDayTable;
var allDayRow;
var slotScroller;
var slotContent;
var slotSegmentContainer;
var slotTable;
var slotTableFirstInner;
var axisFirstCells;
var gutterCells;
var selectionHelper;
var viewWidth;
var viewHeight;
var axisWidth;
var colWidth;
var gutterWidth;
var slotHeight; // TODO: what if slotHeight changes? (see issue 650)
var snapMinutes;
var snapRatio; // ratio of number of "selection" slots to normal slots. (ex: 1, 2, 4)
var snapHeight; // holds the pixel hight of a "selection" slot
var colCnt;
var slotCnt;
var coordinateGrid;
var hoverListener;
var colContentPositions;
var slotTopCache = {};
var savedScrollTop;
var tm;
var firstDay;
var nwe; // no weekends (int)
var rtl, dis, dit; // day index sign / translate
var minMinute, maxMinute;
var colFormat;
var showWeekNumbers;
var weekNumberTitle;
var weekNumberFormat;
/* Rendering
-----------------------------------------------------------------------------*/
disableTextSelection(element.addClass('fc-agenda'));
function renderAgenda(c) {
colCnt = c;
updateOptions();
if (!dayTable) {
buildSkeleton();
}else{
clearEvents();
}
updateCells();
}
function updateOptions() {
tm = opt('theme') ? 'ui' : 'fc';
nwe = opt('weekends') ? 0 : 1;
firstDay = opt('firstDay');
if (rtl = opt('isRTL')) {
dis = -1;
dit = colCnt - 1;
}else{
dis = 1;
dit = 0;
}
minMinute = parseTime(opt('minTime'));
maxMinute = parseTime(opt('maxTime'));
colFormat = opt('columnFormat');
// week # options. (TODO: bad, logic also in other views)
showWeekNumbers = opt('weekNumbers');
weekNumberTitle = opt('weekNumberTitle');
if (opt('weekNumberCalculation') != 'iso') {
weekNumberFormat = "w";
}
else {
weekNumberFormat = "W";
}
snapMinutes = opt('snapMinutes') || opt('slotMinutes');
}
function buildSkeleton() {
var headerClass = tm + "-widget-header";
var contentClass = tm + "-widget-content";
var s;
var i;
var d;
var maxd;
var minutes;
var slotNormal = opt('slotMinutes') % 15 == 0;
s =
"<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" +
"<thead>" +
"<tr>";
if (showWeekNumbers) {
s += "<th class='fc-agenda-axis fc-week-number " + headerClass + "'/>";
}
else {
s += "<th class='fc-agenda-axis " + headerClass + "'> </th>";
}
for (i=0; i<colCnt; i++) {
s +=
"<th class='fc- fc-col" + i + ' ' + headerClass + "'/>"; // fc- needed for setDayID
}
s +=
"<th class='fc-agenda-gutter " + headerClass + "'> </th>" +
"</tr>" +
"</thead>" +
"<tbody>" +
"<tr>" +
"<th class='fc-agenda-axis " + headerClass + "'> </th>";
for (i=0; i<colCnt; i++) {
s +=
"<td class='fc- fc-col" + i + ' ' + contentClass + "'>" + // fc- needed for setDayID
"<div>" +
"<div class='fc-day-content'>" +
"<div style='position:relative'> </div>" +
"</div>" +
"</div>" +
"</td>";
}
s +=
"<td class='fc-agenda-gutter " + contentClass + "'> </td>" +
"</tr>" +
"</tbody>" +
"</table>";
dayTable = $(s).appendTo(element);
dayHead = dayTable.find('thead');
dayHeadCells = dayHead.find('th').slice(1, -1);
dayBody = dayTable.find('tbody');
dayBodyCells = dayBody.find('td').slice(0, -1);
dayBodyCellInners = dayBodyCells.find('div.fc-day-content div');
dayBodyFirstCell = dayBodyCells.eq(0);
dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div');
markFirstLast(dayHead.add(dayHead.find('tr')));
markFirstLast(dayBody.add(dayBody.find('tr')));
axisFirstCells = dayHead.find('th:first');
gutterCells = dayTable.find('.fc-agenda-gutter');
slotLayer =
$("<div style='position:absolute;z-index:2;left:0;width:100%'/>")
.appendTo(element);
if (opt('allDaySlot')) {
daySegmentContainer =
$("<div style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(slotLayer);
s =
"<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" +
"<tr>" +
"<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" +
"<td>" +
"<div class='fc-day-content'><div style='position:relative'/></div>" +
"</td>" +
"<th class='" + headerClass + " fc-agenda-gutter'> </th>" +
"</tr>" +
"</table>";
allDayTable = $(s).appendTo(slotLayer);
allDayRow = allDayTable.find('tr');
dayBind(allDayRow.find('td'));
axisFirstCells = axisFirstCells.add(allDayTable.find('th:first'));
gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter'));
slotLayer.append(
"<div class='fc-agenda-divider " + headerClass + "'>" +
"<div class='fc-agenda-divider-inner'/>" +
"</div>"
);
}else{
daySegmentContainer = $([]); // in jQuery 1.4, we can just do $()
}
slotScroller =
$("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>")
.appendTo(slotLayer);
slotContent =
$("<div style='position:relative;width:100%;overflow:hidden'/>")
.appendTo(slotScroller);
slotSegmentContainer =
$("<div style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(slotContent);
s =
"<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" +
"<tbody>";
d = zeroDate();
maxd = addMinutes(cloneDate(d), maxMinute);
addMinutes(d, minMinute);
slotCnt = 0;
for (i=0; d < maxd; i++) {
minutes = d.getMinutes();
s +=
"<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
"<th class='fc-agenda-axis " + headerClass + "'>" +
((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : ' ') +
"</th>" +
"<td class='" + contentClass + "'>" +
"<div style='position:relative'> </div>" +
"</td>" +
"</tr>";
addMinutes(d, opt('slotMinutes'));
slotCnt++;
}
s +=
"</tbody>" +
"</table>";
slotTable = $(s).appendTo(slotContent);
slotTableFirstInner = slotTable.find('div:first');
slotBind(slotTable.find('td'));
axisFirstCells = axisFirstCells.add(slotTable.find('th:first'));
}
function updateCells() {
var i;
var headCell;
var bodyCell;
var date;
var today = clearTime(new Date());
if (showWeekNumbers) {
var weekText = formatDate(colDate(0), weekNumberFormat);
if (rtl) {
weekText = weekText + weekNumberTitle;
}
else {
weekText = weekNumberTitle + weekText;
}
dayHead.find('.fc-week-number').text(weekText);
}
for (i=0; i<colCnt; i++) {
date = colDate(i);
headCell = dayHeadCells.eq(i);
headCell.html(formatDate(date, colFormat));
bodyCell = dayBodyCells.eq(i);
if (+date == +today) {
bodyCell.addClass(tm + '-state-highlight fc-today');
}else{
bodyCell.removeClass(tm + '-state-highlight fc-today');
}
setDayID(headCell.add(bodyCell), date);
}
}
function setHeight(height, dateChanged) {
if (height === undefined) {
height = viewHeight;
}
viewHeight = height;
slotTopCache = {};
var headHeight = dayBody.position().top;
var allDayHeight = slotScroller.position().top; // including divider
var bodyHeight = Math.min( // total body height, including borders
height - headHeight, // when scrollbars
slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border
);
dayBodyFirstCellStretcher
.height(bodyHeight - vsides(dayBodyFirstCell));
slotLayer.css('top', headHeight);
slotScroller.height(bodyHeight - allDayHeight - 1);
slotHeight = slotTableFirstInner.height() + 1; // +1 for border
snapRatio = opt('slotMinutes') / snapMinutes;
snapHeight = slotHeight / snapRatio;
if (dateChanged) {
resetScroll();
}
}
function setWidth(width) {
viewWidth = width;
colContentPositions.clear();
axisWidth = 0;
setOuterWidth(
axisFirstCells
.width('')
.each(function(i, _cell) {
axisWidth = Math.max(axisWidth, $(_cell).outerWidth());
}),
axisWidth
);
var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7)
//slotTable.width(slotTableWidth);
gutterWidth = slotScroller.width() - slotTableWidth;
if (gutterWidth) {
setOuterWidth(gutterCells, gutterWidth);
gutterCells
.show()
.prev()
.removeClass('fc-last');
}else{
gutterCells
.hide()
.prev()
.addClass('fc-last');
}
colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt);
setOuterWidth(dayHeadCells.slice(0, -1), colWidth);
}
function resetScroll() {
var d0 = zeroDate();
var scrollDate = cloneDate(d0);
scrollDate.setHours(opt('firstHour'));
var top = timePosition(d0, scrollDate) + 1; // +1 for the border
function scroll() {
slotScroller.scrollTop(top);
}
scroll();
setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
}
function beforeHide() {
savedScrollTop = slotScroller.scrollTop();
}
function afterShow() {
slotScroller.scrollTop(savedScrollTop);
}
/* Slot/Day clicking and binding
-----------------------------------------------------------------------*/
function dayBind(cells) {
cells.click(slotClick)
.mousedown(daySelectionMousedown);
}
function slotBind(cells) {
cells.click(slotClick)
.mousedown(slotSelectionMousedown);
}
function slotClick(ev) {
if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
var date = colDate(col);
var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
if (rowMatch) {
var mins = parseInt(rowMatch[1]) * opt('slotMinutes');
var hours = Math.floor(mins/60);
date.setHours(hours);
date.setMinutes(mins%60 + minMinute);
trigger('dayClick', dayBodyCells[col], date, false, ev);
}else{
trigger('dayClick', dayBodyCells[col], date, true, ev);
}
}
}
/* Semi-transparent Overlay Helpers
-----------------------------------------------------*/
function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive
if (refreshCoordinateGrid) {
coordinateGrid.build();
}
var visStart = cloneDate(t.visStart);
var startCol, endCol;
if (rtl) {
startCol = dayDiff(endDate, visStart)*dis+dit+1;
endCol = dayDiff(startDate, visStart)*dis+dit+1;
}else{
startCol = dayDiff(startDate, visStart);
endCol = dayDiff(endDate, visStart);
}
startCol = Math.max(0, startCol);
endCol = Math.min(colCnt, endCol);
if (startCol < endCol) {
dayBind(
renderCellOverlay(0, startCol, 0, endCol-1)
);
}
}
function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
return renderOverlay(rect, slotLayer);
}
function renderSlotOverlay(overlayStart, overlayEnd) {
var dayStart = cloneDate(t.visStart);
var dayEnd = addDays(cloneDate(dayStart), 1);
for (var i=0; i<colCnt; i++) {
var stretchStart = new Date(Math.max(dayStart, overlayStart));
var stretchEnd = new Date(Math.min(dayEnd, overlayEnd));
if (stretchStart < stretchEnd) {
var col = i*dis+dit;
var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only use it for horizontal coords
var top = timePosition(dayStart, stretchStart);
var bottom = timePosition(dayStart, stretchEnd);
rect.top = top;
rect.height = bottom - top;
slotBind(
renderOverlay(rect, slotContent)
);
}
addDays(dayStart, 1);
addDays(dayEnd, 1);
}
}
/* Coordinate Utilities
-----------------------------------------------------------------------------*/
coordinateGrid = new CoordinateGrid(function(rows, cols) {
var e, n, p;
dayHeadCells.each(function(i, _e) {
e = $(_e);
n = e.offset().left;
if (i) {
p[1] = n;
}
p = [n];
cols[i] = p;
});
p[1] = n + e.outerWidth();
if (opt('allDaySlot')) {
e = allDayRow;
n = e.offset().top;
rows[0] = [n, n+e.outerHeight()];
}
var slotTableTop = slotContent.offset().top;
var slotScrollerTop = slotScroller.offset().top;
var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight();
function constrain(n) {
return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n));
}
for (var i=0; i<slotCnt*snapRatio; i++) { // adapt slot count to increased/decreased selection slot count
rows.push([
constrain(slotTableTop + snapHeight*i),
constrain(slotTableTop + snapHeight*(i+1))
]);
}
});
hoverListener = new HoverListener(coordinateGrid);
colContentPositions = new HorizontalPositionCache(function(col) {
return dayBodyCellInners.eq(col);
});
function colContentLeft(col) {
return colContentPositions.left(col);
}
function colContentRight(col) {
return colContentPositions.right(col);
}
function dateCell(date) { // "cell" terminology is now confusing
return {
row: Math.floor(dayDiff(date, t.visStart) / 7),
col: dayOfWeekCol(date.getDay())
};
}
function cellDate(cell) {
var d = colDate(cell.col);
var slotIndex = cell.row;
if (opt('allDaySlot')) {
slotIndex--;
}
if (slotIndex >= 0) {
addMinutes(d, minMinute + slotIndex * snapMinutes);
}
return d;
}
function colDate(col) { // returns dates with 00:00:00
return addDays(cloneDate(t.visStart), col*dis+dit);
}
function cellIsAllDay(cell) {
return opt('allDaySlot') && !cell.row;
}
function dayOfWeekCol(dayOfWeek) {
return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit;
}
// get the Y coordinate of the given time on the given day (both Date objects)
function timePosition(day, time) { // both date objects. day holds 00:00 of current day
day = cloneDate(day, true);
if (time < addMinutes(cloneDate(day), minMinute)) {
return 0;
}
if (time >= addMinutes(cloneDate(day), maxMinute)) {
return slotTable.height();
}
var slotMinutes = opt('slotMinutes'),
minutes = time.getHours()*60 + time.getMinutes() - minMinute,
slotI = Math.floor(minutes / slotMinutes),
slotTop = slotTopCache[slotI];
if (slotTop === undefined) {
slotTop = slotTopCache[slotI] = slotTable.find('tr:eq(' + slotI + ') td div')[0].offsetTop; //.position().top; // need this optimization???
}
return Math.max(0, Math.round(
slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes)
));
}
function allDayBounds() {
return {
left: axisWidth,
right: viewWidth - gutterWidth
}
}
function getAllDayRow(index) {
return allDayRow;
}
function defaultEventEnd(event) {
var start = cloneDate(event.start);
if (event.allDay) {
return start;
}
return addMinutes(start, opt('defaultEventMinutes'));
}
/* Selection
---------------------------------------------------------------------------------*/
function defaultSelectionEnd(startDate, allDay) {
if (allDay) {
return cloneDate(startDate);
}
return addMinutes(cloneDate(startDate), opt('slotMinutes'));
}
function renderSelection(startDate, endDate, allDay) { // only for all-day
if (allDay) {
if (opt('allDaySlot')) {
renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true);
}
}else{
renderSlotSelection(startDate, endDate);
}
}
function renderSlotSelection(startDate, endDate) {
var helperOption = opt('selectHelper');
coordinateGrid.build();
if (helperOption) {
var col = dayDiff(startDate, t.visStart) * dis + dit;
if (col >= 0 && col < colCnt) { // only works when times are on same day
var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords
var top = timePosition(startDate, startDate);
var bottom = timePosition(startDate, endDate);
if (bottom > top) { // protect against selections that are entirely before or after visible range
rect.top = top;
rect.height = bottom - top;
rect.left += 2;
rect.width -= 5;
if ($.isFunction(helperOption)) {
var helperRes = helperOption(startDate, endDate);
if (helperRes) {
rect.position = 'absolute';
rect.zIndex = 8;
selectionHelper = $(helperRes)
.css(rect)
.appendTo(slotContent);
}
}else{
rect.isStart = true; // conside rect a "seg" now
rect.isEnd = true; //
selectionHelper = $(slotSegHtml(
{
title: '',
start: startDate,
end: endDate,
className: ['fc-select-helper'],
editable: false
},
rect
));
selectionHelper.css('opacity', opt('dragOpacity'));
}
if (selectionHelper) {
slotBind(selectionHelper);
slotContent.append(selectionHelper);
setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended
setOuterHeight(selectionHelper, rect.height, true);
}
}
}
}else{
renderSlotOverlay(startDate, endDate);
}
}
function clearSelection() {
clearOverlays();
if (selectionHelper) {
selectionHelper.remove();
selectionHelper = null;
}
}
function slotSelectionMousedown(ev) {
if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button
unselect(ev);
var dates;
hoverListener.start(function(cell, origCell) {
clearSelection();
if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) {
var d1 = cellDate(origCell);
var d2 = cellDate(cell);
dates = [
d1,
addMinutes(cloneDate(d1), snapMinutes), // calculate minutes depending on selection slot minutes
d2,
addMinutes(cloneDate(d2), snapMinutes)
].sort(cmp);
renderSlotSelection(dates[0], dates[3]);
}else{
dates = null;
}
}, ev);
$(document).one('mouseup', function(ev) {
hoverListener.stop();
if (dates) {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], false, ev);
}
reportSelection(dates[0], dates[3], false, ev);
}
});
}
}
function reportDayClick(date, allDay, ev) {
trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev);
}
/* External Dragging
--------------------------------------------------------------------------------*/
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function(cell) {
clearOverlays();
if (cell) {
if (cellIsAllDay(cell)) {
renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
}else{
var d1 = cellDate(cell);
var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes'));
renderSlotOverlay(d1, d2);
}
}
}, ev);
}
function dragStop(_dragElement, ev, ui) {
var cell = hoverListener.stop();
clearOverlays();
if (cell) {
trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui);
}
}
}
;;
function AgendaEventRenderer() {
var t = this;
// exports
t.renderEvents = renderEvents;
t.compileDaySegs = compileDaySegs; // for DayEventRenderer
t.clearEvents = clearEvents;
t.slotSegHtml = slotSegHtml;
t.bindDaySeg = bindDaySeg;
// imports
DayEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
//var setOverflowHidden = t.setOverflowHidden;
var isEventDraggable = t.isEventDraggable;
var isEventResizable = t.isEventResizable;
var eventEnd = t.eventEnd;
var reportEvents = t.reportEvents;
var reportEventClear = t.reportEventClear;
var eventElementHandlers = t.eventElementHandlers;
var setHeight = t.setHeight;
var getDaySegmentContainer = t.getDaySegmentContainer;
var getSlotSegmentContainer = t.getSlotSegmentContainer;
var getHoverListener = t.getHoverListener;
var getMaxMinute = t.getMaxMinute;
var getMinMinute = t.getMinMinute;
var timePosition = t.timePosition;
var colContentLeft = t.colContentLeft;
var colContentRight = t.colContentRight;
var renderDaySegs = t.renderDaySegs;
var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture
var getColCnt = t.getColCnt;
var getColWidth = t.getColWidth;
var getSnapHeight = t.getSnapHeight;
var getSnapMinutes = t.getSnapMinutes;
var getBodyContent = t.getBodyContent;
var reportEventElement = t.reportEventElement;
var showEvents = t.showEvents;
var hideEvents = t.hideEvents;
var eventDrop = t.eventDrop;
var eventResize = t.eventResize;
var renderDayOverlay = t.renderDayOverlay;
var clearOverlays = t.clearOverlays;
var calendar = t.calendar;
var formatDate = calendar.formatDate;
var formatDates = calendar.formatDates;
/* Rendering
----------------------------------------------------------------------------*/
function renderEvents(events, modifiedEventId) {
reportEvents(events);
var i, len=events.length,
dayEvents=[],
slotEvents=[];
for (i=0; i<len; i++) {
if (events[i].allDay) {
dayEvents.push(events[i]);
}else{
slotEvents.push(events[i]);
}
}
if (opt('allDaySlot')) {
renderDaySegs(compileDaySegs(dayEvents), modifiedEventId);
setHeight(); // no params means set to viewHeight
}
renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId);
trigger('eventAfterAllRender');
}
function clearEvents() {
reportEventClear();
getDaySegmentContainer().empty();
getSlotSegmentContainer().empty();
}
function compileDaySegs(events) {
var levels = stackSegs(sliceSegs(events, $.map(events, exclEndDay), t.visStart, t.visEnd)),
i, levelCnt=levels.length, level,
j, seg,
segs=[];
for (i=0; i<levelCnt; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
seg = level[j];
seg.row = 0;
seg.level = i; // not needed anymore
segs.push(seg);
}
}
return segs;
}
function compileSlotSegs(events) {
var colCnt = getColCnt(),
minMinute = getMinMinute(),
maxMinute = getMaxMinute(),
d = addMinutes(cloneDate(t.visStart), minMinute),
visEventEnds = $.map(events, slotEventEnd),
i, col,
j, level,
k, seg,
segs=[];
for (i=0; i<colCnt; i++) {
col = stackSegs(sliceSegs(events, visEventEnds, d, addMinutes(cloneDate(d), maxMinute-minMinute)));
countForwardSegs(col);
for (j=0; j<col.length; j++) {
level = col[j];
for (k=0; k<level.length; k++) {
seg = level[k];
seg.col = i;
seg.level = j;
segs.push(seg);
}
}
addDays(d, 1, true);
}
return segs;
}
function slotEventEnd(event) {
if (event.end) {
return cloneDate(event.end);
}else{
return addMinutes(cloneDate(event.start), opt('defaultEventMinutes'));
}
}
// renders events in the 'time slots' at the bottom
function renderSlotSegs(segs, modifiedEventId) {
var i, segCnt=segs.length, seg,
event,
classes,
top, bottom,
colI, levelI, forward,
leftmost,
availWidth,
outerWidth,
left,
html='',
eventElements,
eventElement,
triggerRes,
vsideCache={},
hsideCache={},
key, val,
titleElement,
height,
slotSegmentContainer = getSlotSegmentContainer(),
rtl, dis, dit,
colCnt = getColCnt();
if (rtl = opt('isRTL')) {
dis = -1;
dit = colCnt - 1;
}else{
dis = 1;
dit = 0;
}
// calculate position/dimensions, create html
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
top = timePosition(seg.start, seg.start);
bottom = timePosition(seg.start, seg.end);
colI = seg.col;
levelI = seg.level;
forward = seg.forward || 0;
leftmost = colContentLeft(colI*dis + dit);
availWidth = colContentRight(colI*dis + dit) - leftmost;
availWidth = Math.min(availWidth-6, availWidth*.95); // TODO: move this to CSS
if (levelI) {
// indented and thin
outerWidth = availWidth / (levelI + forward + 1);
}else{
if (forward) {
// moderately wide, aligned left still
outerWidth = ((availWidth / (forward + 1)) - (12/2)) * 2; // 12 is the predicted width of resizer =
}else{
// can be entire width, aligned left
outerWidth = availWidth;
}
}
left = leftmost + // leftmost possible
(availWidth / (levelI + forward + 1) * levelI) // indentation
* dis + (rtl ? availWidth - outerWidth : 0); // rtl
seg.top = top;
seg.left = left;
seg.outerWidth = outerWidth;
seg.outerHeight = bottom - top;
html += slotSegHtml(event, seg);
}
slotSegmentContainer[0].innerHTML = html; // faster than html()
eventElements = slotSegmentContainer.children();
// retrieve elements, run through eventRender callback, bind event handlers
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
eventElement = $(eventElements[i]); // faster than eq()
triggerRes = trigger('eventRender', event, event, eventElement);
if (triggerRes === false) {
eventElement.remove();
}else{
if (triggerRes && triggerRes !== true) {
eventElement.remove();
eventElement = $(triggerRes)
.css({
position: 'absolute',
top: seg.top,
left: seg.left
})
.appendTo(slotSegmentContainer);
}
seg.element = eventElement;
if (event._id === modifiedEventId) {
bindSlotSeg(event, eventElement, seg);
}else{
eventElement[0]._fci = i; // for lazySegBind
}
reportEventElement(event, eventElement);
}
}
lazySegBind(slotSegmentContainer, segs, bindSlotSeg);
// record event sides and title positions
for (i=0; i<segCnt; i++) {
seg = segs[i];
if (eventElement = seg.element) {
val = vsideCache[key = seg.key = cssKey(eventElement[0])];
seg.vsides = val === undefined ? (vsideCache[key] = vsides(eventElement, true)) : val;
val = hsideCache[key];
seg.hsides = val === undefined ? (hsideCache[key] = hsides(eventElement, true)) : val;
titleElement = eventElement.find('.fc-event-title');
if (titleElement.length) {
seg.contentTop = titleElement[0].offsetTop;
}
}
}
// set all positions/dimensions at once
for (i=0; i<segCnt; i++) {
seg = segs[i];
if (eventElement = seg.element) {
eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
height = Math.max(0, seg.outerHeight - seg.vsides);
eventElement[0].style.height = height + 'px';
event = seg.event;
if (seg.contentTop !== undefined && height - seg.contentTop < 10) {
// not enough room for title, put it in the time (TODO: maybe make both display:inline instead)
eventElement.find('div.fc-event-time')
.text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title);
eventElement.find('div.fc-event-title')
.remove();
}
trigger('eventAfterRender', event, event, eventElement);
}
}
}
function slotSegHtml(event, seg) {
var html = "<";
var url = event.url;
var skinCss = getSkinCss(event, opt);
var classes = ['fc-event', 'fc-event-vert'];
if (isEventDraggable(event)) {
classes.push('fc-event-draggable');
}
if (seg.isStart) {
classes.push('fc-event-start');
}
if (seg.isEnd) {
classes.push('fc-event-end');
}
classes = classes.concat(event.className);
if (event.source) {
classes = classes.concat(event.source.className || []);
}
if (url) {
html += "a href='" + htmlEscape(event.url) + "'";
}else{
html += "div";
}
html +=
" class='" + classes.join(' ') + "'" +
" style='position:absolute;z-index:8;top:" + seg.top + "px;left:" + seg.left + "px;" + skinCss + "'" +
">" +
"<div class='fc-event-inner'>" +
"<div class='fc-event-time'>" +
htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
"</div>" +
"<div class='fc-event-title'>" +
htmlEscape(event.title) +
"</div>" +
"</div>" +
"<div class='fc-event-bg'></div>";
if (seg.isEnd && isEventResizable(event)) {
html +=
"<div class='ui-resizable-handle ui-resizable-s'>=</div>";
}
html +=
"</" + (url ? "a" : "div") + ">";
return html;
}
function bindDaySeg(event, eventElement, seg) {
if (isEventDraggable(event)) {
draggableDayEvent(event, eventElement, seg.isStart);
}
if (seg.isEnd && isEventResizable(event)) {
resizableDayEvent(event, eventElement, seg);
}
eventElementHandlers(event, eventElement);
// needs to be after, because resizableDayEvent might stopImmediatePropagation on click
}
function bindSlotSeg(event, eventElement, seg) {
var timeElement = eventElement.find('div.fc-event-time');
if (isEventDraggable(event)) {
draggableSlotEvent(event, eventElement, timeElement);
}
if (seg.isEnd && isEventResizable(event)) {
resizableSlotEvent(event, eventElement, timeElement);
}
eventElementHandlers(event, eventElement);
}
/* Dragging
-----------------------------------------------------------------------------------*/
// when event starts out FULL-DAY
function draggableDayEvent(event, eventElement, isStart) {
var origWidth;
var revert;
var allDay=true;
var dayDelta;
var dis = opt('isRTL') ? -1 : 1;
var hoverListener = getHoverListener();
var colWidth = getColWidth();
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
var minMinute = getMinMinute();
eventElement.draggable({
zIndex: 9,
opacity: opt('dragOpacity', 'month'), // use whatever the month view was using
revertDuration: opt('dragRevertDuration'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
origWidth = eventElement.width();
hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
clearOverlays();
if (cell) {
//setOverflowHidden(true);
revert = false;
dayDelta = colDelta * dis;
if (!cell.row) {
// on full-days
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
resetElement();
}else{
// mouse is over bottom slots
if (isStart) {
if (allDay) {
// convert event to temporary slot-event
eventElement.width(colWidth - 10); // don't use entire width
setOuterHeight(
eventElement,
snapHeight * Math.round(
(event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) /
snapMinutes
)
);
eventElement.draggable('option', 'grid', [colWidth, 1]);
allDay = false;
}
}else{
revert = true;
}
}
revert = revert || (allDay && !dayDelta);
}else{
resetElement();
//setOverflowHidden(false);
revert = true;
}
eventElement.draggable('option', 'revert', revert);
}, ev, 'drag');
},
stop: function(ev, ui) {
hoverListener.stop();
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (revert) {
// hasn't moved or is out of bounds (draggable has already reverted)
resetElement();
eventElement.css('filter', ''); // clear IE opacity side-effects
showEvents(event, eventElement);
}else{
// changed!
var minuteDelta = 0;
if (!allDay) {
minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / snapHeight)
* snapMinutes
+ minMinute
- (event.start.getHours() * 60 + event.start.getMinutes());
}
eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);
}
//setOverflowHidden(false);
}
});
function resetElement() {
if (!allDay) {
eventElement
.width(origWidth)
.height('')
.draggable('option', 'grid', null);
allDay = true;
}
}
}
// when event starts out IN TIMESLOTS
function draggableSlotEvent(event, eventElement, timeElement) {
var origPosition;
var allDay=false;
var dayDelta;
var minuteDelta;
var prevMinuteDelta;
var dis = opt('isRTL') ? -1 : 1;
var hoverListener = getHoverListener();
var colCnt = getColCnt();
var colWidth = getColWidth();
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
eventElement.draggable({
zIndex: 9,
scroll: false,
grid: [colWidth, snapHeight],
axis: colCnt==1 ? 'y' : false,
opacity: opt('dragOpacity'),
revertDuration: opt('dragRevertDuration'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
origPosition = eventElement.position();
minuteDelta = prevMinuteDelta = 0;
hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
eventElement.draggable('option', 'revert', !cell);
clearOverlays();
if (cell) {
dayDelta = colDelta * dis;
if (opt('allDaySlot') && !cell.row) {
// over full days
if (!allDay) {
// convert to temporary all-day event
allDay = true;
timeElement.hide();
eventElement.draggable('option', 'grid', null);
}
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
}else{
// on slots
resetElement();
}
}
}, ev, 'drag');
},
drag: function(ev, ui) {
minuteDelta = Math.round((ui.position.top - origPosition.top) / snapHeight) * snapMinutes;
if (minuteDelta != prevMinuteDelta) {
if (!allDay) {
updateTimeText(minuteDelta);
}
prevMinuteDelta = minuteDelta;
}
},
stop: function(ev, ui) {
var cell = hoverListener.stop();
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (cell && (dayDelta || minuteDelta || allDay)) {
// changed!
eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui);
}else{
// either no change or out-of-bounds (draggable has already reverted)
resetElement();
eventElement.css('filter', ''); // clear IE opacity side-effects
eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position
updateTimeText(0);
showEvents(event, eventElement);
}
}
});
function updateTimeText(minuteDelta) {
var newStart = addMinutes(cloneDate(event.start), minuteDelta);
var newEnd;
if (event.end) {
newEnd = addMinutes(cloneDate(event.end), minuteDelta);
}
timeElement.text(formatDates(newStart, newEnd, opt('timeFormat')));
}
function resetElement() {
// convert back to original slot-event
if (allDay) {
timeElement.css('display', ''); // show() was causing display=inline
eventElement.draggable('option', 'grid', [colWidth, snapHeight]);
allDay = false;
}
}
}
/* Resizing
--------------------------------------------------------------------------------------*/
function resizableSlotEvent(event, eventElement, timeElement) {
var snapDelta, prevSnapDelta;
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
eventElement.resizable({
handles: {
s: '.ui-resizable-handle'
},
grid: snapHeight,
start: function(ev, ui) {
snapDelta = prevSnapDelta = 0;
hideEvents(event, eventElement);
eventElement.css('z-index', 9);
trigger('eventResizeStart', this, event, ev, ui);
},
resize: function(ev, ui) {
// don't rely on ui.size.height, doesn't take grid into account
snapDelta = Math.round((Math.max(snapHeight, eventElement.height()) - ui.originalSize.height) / snapHeight);
if (snapDelta != prevSnapDelta) {
timeElement.text(
formatDates(
event.start,
(!snapDelta && !event.end) ? null : // no change, so don't display time range
addMinutes(eventEnd(event), snapMinutes*snapDelta),
opt('timeFormat')
)
);
prevSnapDelta = snapDelta;
}
},
stop: function(ev, ui) {
trigger('eventResizeStop', this, event, ev, ui);
if (snapDelta) {
eventResize(this, event, 0, snapMinutes*snapDelta, ev, ui);
}else{
eventElement.css('z-index', 8);
showEvents(event, eventElement);
// BUG: if event was really short, need to put title back in span
}
}
});
}
}
function countForwardSegs(levels) {
var i, j, k, level, segForward, segBack;
for (i=levels.length-1; i>0; i--) {
level = levels[i];
for (j=0; j<level.length; j++) {
segForward = level[j];
for (k=0; k<levels[i-1].length; k++) {
segBack = levels[i-1][k];
if (segsCollide(segForward, segBack)) {
segBack.forward = Math.max(segBack.forward||0, (segForward.forward||0)+1);
}
}
}
}
}
;;
function View(element, calendar, viewName) {
var t = this;
// exports
t.element = element;
t.calendar = calendar;
t.name = viewName;
t.opt = opt;
t.trigger = trigger;
//t.setOverflowHidden = setOverflowHidden;
t.isEventDraggable = isEventDraggable;
t.isEventResizable = isEventResizable;
t.reportEvents = reportEvents;
t.eventEnd = eventEnd;
t.reportEventElement = reportEventElement;
t.reportEventClear = reportEventClear;
t.eventElementHandlers = eventElementHandlers;
t.showEvents = showEvents;
t.hideEvents = hideEvents;
t.eventDrop = eventDrop;
t.eventResize = eventResize;
// t.title
// t.start, t.end
// t.visStart, t.visEnd
// imports
var defaultEventEnd = t.defaultEventEnd;
var normalizeEvent = calendar.normalizeEvent; // in EventManager
var reportEventChange = calendar.reportEventChange;
// locals
var eventsByID = {};
var eventElements = [];
var eventElementsByID = {};
var options = calendar.options;
function opt(name, viewNameOverride) {
var v = options[name];
if (typeof v == 'object') {
return smartProperty(v, viewNameOverride || viewName);
}
return v;
}
function trigger(name, thisObj) {
return calendar.trigger.apply(
calendar,
[name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
);
}
/*
function setOverflowHidden(bool) {
element.css('overflow', bool ? 'hidden' : '');
}
*/
function isEventDraggable(event) {
return isEventEditable(event) && !opt('disableDragging');
}
function isEventResizable(event) { // but also need to make sure the seg.isEnd == true
return isEventEditable(event) && !opt('disableResizing');
}
function isEventEditable(event) {
return firstDefined(event.editable, (event.source || {}).editable, opt('editable'));
}
/* Event Data
------------------------------------------------------------------------------*/
// report when view receives new events
function reportEvents(events) { // events are already normalized at this point
eventsByID = {};
var i, len=events.length, event;
for (i=0; i<len; i++) {
event = events[i];
if (eventsByID[event._id]) {
eventsByID[event._id].push(event);
}else{
eventsByID[event._id] = [event];
}
}
}
// returns a Date object for an event's end
function eventEnd(event) {
return event.end ? cloneDate(event.end) : defaultEventEnd(event);
}
/* Event Elements
------------------------------------------------------------------------------*/
// report when view creates an element for an event
function reportEventElement(event, element) {
eventElements.push(element);
if (eventElementsByID[event._id]) {
eventElementsByID[event._id].push(element);
}else{
eventElementsByID[event._id] = [element];
}
}
function reportEventClear() {
eventElements = [];
eventElementsByID = {};
}
// attaches eventClick, eventMouseover, eventMouseout
function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
if (!eventElement.hasClass('ui-draggable-dragging') &&
!eventElement.hasClass('ui-resizable-resizing')) {
return trigger('eventClick', this, event, ev);
}
})
.hover(
function(ev) {
trigger('eventMouseover', this, event, ev);
},
function(ev) {
trigger('eventMouseout', this, event, ev);
}
);
// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
// TODO: same for resizing
}
function showEvents(event, exceptElement) {
eachEventElement(event, exceptElement, 'show');
}
function hideEvents(event, exceptElement) {
eachEventElement(event, exceptElement, 'hide');
}
function eachEventElement(event, exceptElement, funcName) {
var elements = eventElementsByID[event._id],
i, len = elements.length;
for (i=0; i<len; i++) {
if (!exceptElement || elements[i][0] != exceptElement[0]) {
elements[i][funcName]();
}
}
}
/* Event Modification Reporting
---------------------------------------------------------------------------------*/
function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui) {
var oldAllDay = event.allDay;
var eventId = event._id;
moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay);
trigger(
'eventDrop',
e,
event,
dayDelta,
minuteDelta,
allDay,
function() {
// TODO: investigate cases where this inverse technique might not work
moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay);
reportEventChange(eventId);
},
ev,
ui
);
reportEventChange(eventId);
}
function eventResize(e, event, dayDelta, minuteDelta, ev, ui) {
var eventId = event._id;
elongateEvents(eventsByID[eventId], dayDelta, minuteDelta);
trigger(
'eventResize',
e,
event,
dayDelta,
minuteDelta,
function() {
// TODO: investigate cases where this inverse technique might not work
elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta);
reportEventChange(eventId);
},
ev,
ui
);
reportEventChange(eventId);
}
/* Event Modification Math
---------------------------------------------------------------------------------*/
function moveEvents(events, dayDelta, minuteDelta, allDay) {
minuteDelta = minuteDelta || 0;
for (var e, len=events.length, i=0; i<len; i++) {
e = events[i];
if (allDay !== undefined) {
e.allDay = allDay;
}
addMinutes(addDays(e.start, dayDelta, true), minuteDelta);
if (e.end) {
e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta);
}
normalizeEvent(e, options);
}
}
function elongateEvents(events, dayDelta, minuteDelta) {
minuteDelta = minuteDelta || 0;
for (var e, len=events.length, i=0; i<len; i++) {
e = events[i];
e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta);
normalizeEvent(e, options);
}
}
}
;;
function DayEventRenderer() {
var t = this;
// exports
t.renderDaySegs = renderDaySegs;
t.resizableDayEvent = resizableDayEvent;
// imports
var opt = t.opt;
var trigger = t.trigger;
var isEventDraggable = t.isEventDraggable;
var isEventResizable = t.isEventResizable;
var eventEnd = t.eventEnd;
var reportEventElement = t.reportEventElement;
var showEvents = t.showEvents;
var hideEvents = t.hideEvents;
var eventResize = t.eventResize;
var getRowCnt = t.getRowCnt;
var getColCnt = t.getColCnt;
var getColWidth = t.getColWidth;
var allDayRow = t.allDayRow;
var allDayBounds = t.allDayBounds;
var colContentLeft = t.colContentLeft;
var colContentRight = t.colContentRight;
var dayOfWeekCol = t.dayOfWeekCol;
var dateCell = t.dateCell;
var compileDaySegs = t.compileDaySegs;
var getDaySegmentContainer = t.getDaySegmentContainer;
var bindDaySeg = t.bindDaySeg; //TODO: streamline this
var formatDates = t.calendar.formatDates;
var renderDayOverlay = t.renderDayOverlay;
var clearOverlays = t.clearOverlays;
var clearSelection = t.clearSelection;
/* Rendering
-----------------------------------------------------------------------------*/
function renderDaySegs(segs, modifiedEventId) {
var segmentContainer = getDaySegmentContainer();
var rowDivs;
var rowCnt = getRowCnt();
var colCnt = getColCnt();
var i = 0;
var rowI;
var levelI;
var colHeights;
var j;
var segCnt = segs.length;
var seg;
var top;
var k;
segmentContainer[0].innerHTML = daySegHTML(segs); // faster than .html()
daySegElementResolve(segs, segmentContainer.children());
daySegElementReport(segs);
daySegHandlers(segs, segmentContainer, modifiedEventId);
daySegCalcHSides(segs);
daySegSetWidths(segs);
daySegCalcHeights(segs);
rowDivs = getRowDivs();
// set row heights, calculate event tops (in relation to row top)
for (rowI=0; rowI<rowCnt; rowI++) {
levelI = 0;
colHeights = [];
for (j=0; j<colCnt; j++) {
colHeights[j] = 0;
}
while (i<segCnt && (seg = segs[i]).row == rowI) {
// loop through segs in a row
top = arrayMax(colHeights.slice(seg.startCol, seg.endCol));
seg.top = top;
top += seg.outerHeight;
for (k=seg.startCol; k<seg.endCol; k++) {
colHeights[k] = top;
}
i++;
}
rowDivs[rowI].height(arrayMax(colHeights));
}
daySegSetTops(segs, getRowTops(rowDivs));
}
function renderTempDaySegs(segs, adjustRow, adjustTop) {
var tempContainer = $("<div/>");
var elements;
var segmentContainer = getDaySegmentContainer();
var i;
var segCnt = segs.length;
var element;
tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html()
elements = tempContainer.children();
segmentContainer.append(elements);
daySegElementResolve(segs, elements);
daySegCalcHSides(segs);
daySegSetWidths(segs);
daySegCalcHeights(segs);
daySegSetTops(segs, getRowTops(getRowDivs()));
elements = [];
for (i=0; i<segCnt; i++) {
element = segs[i].element;
if (element) {
if (segs[i].row === adjustRow) {
element.css('top', adjustTop);
}
elements.push(element[0]);
}
}
return $(elements);
}
function daySegHTML(segs) { // also sets seg.left and seg.outerWidth
var rtl = opt('isRTL');
var i;
var segCnt=segs.length;
var seg;
var event;
var url;
var classes;
var bounds = allDayBounds();
var minLeft = bounds.left;
var maxLeft = bounds.right;
var leftCol;
var rightCol;
var left;
var right;
var skinCss;
var html = '';
// calculate desired position/dimensions, create html
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
classes = ['fc-event', 'fc-event-hori'];
if (isEventDraggable(event)) {
classes.push('fc-event-draggable');
}
if (seg.isStart) {
classes.push('fc-event-start');
}
if (seg.isEnd) {
classes.push('fc-event-end');
}
if (rtl) {
leftCol = dayOfWeekCol(seg.end.getDay()-1);
rightCol = dayOfWeekCol(seg.start.getDay());
left = seg.isEnd ? colContentLeft(leftCol) : minLeft;
right = seg.isStart ? colContentRight(rightCol) : maxLeft;
}else{
leftCol = dayOfWeekCol(seg.start.getDay());
rightCol = dayOfWeekCol(seg.end.getDay()-1);
left = seg.isStart ? colContentLeft(leftCol) : minLeft;
right = seg.isEnd ? colContentRight(rightCol) : maxLeft;
}
classes = classes.concat(event.className);
if (event.source) {
classes = classes.concat(event.source.className || []);
}
url = event.url;
skinCss = getSkinCss(event, opt);
if (url) {
html += "<a href='" + htmlEscape(url) + "'";
}else{
html += "<div";
}
html +=
" class='" + classes.join(' ') + "'" +
" style='position:absolute;z-index:8;left:"+left+"px;" + skinCss + "'" +
">" +
"<div class='fc-event-inner'>";
if (!event.allDay && seg.isStart) {
html +=
"<span class='fc-event-time'>" +
htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
"</span>";
}
html +=
"<span class='fc-event-title'>" + htmlEscape(event.title) + "</span>" +
"</div>";
if (seg.isEnd && isEventResizable(event)) {
html +=
"<div class='ui-resizable-handle ui-resizable-" + (rtl ? 'w' : 'e') + "'>" +
" " + // makes hit area a lot better for IE6/7
"</div>";
}
html +=
"</" + (url ? "a" : "div" ) + ">";
seg.left = left;
seg.outerWidth = right - left;
seg.startCol = leftCol;
seg.endCol = rightCol + 1; // needs to be exclusive
}
return html;
}
function daySegElementResolve(segs, elements) { // sets seg.element
var i;
var segCnt = segs.length;
var seg;
var event;
var element;
var triggerRes;
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
element = $(elements[i]); // faster than .eq()
triggerRes = trigger('eventRender', event, event, element);
if (triggerRes === false) {
element.remove();
}else{
if (triggerRes && triggerRes !== true) {
triggerRes = $(triggerRes)
.css({
position: 'absolute',
left: seg.left
});
element.replaceWith(triggerRes);
element = triggerRes;
}
seg.element = element;
}
}
}
function daySegElementReport(segs) {
var i;
var segCnt = segs.length;
var seg;
var element;
for (i=0; i<segCnt; i++) {
seg = segs[i];
element = seg.element;
if (element) {
reportEventElement(seg.event, element);
}
}
}
function daySegHandlers(segs, segmentContainer, modifiedEventId) {
var i;
var segCnt = segs.length;
var seg;
var element;
var event;
// retrieve elements, run through eventRender callback, bind handlers
for (i=0; i<segCnt; i++) {
seg = segs[i];
element = seg.element;
if (element) {
event = seg.event;
if (event._id === modifiedEventId) {
bindDaySeg(event, element, seg);
}else{
element[0]._fci = i; // for lazySegBind
}
}
}
lazySegBind(segmentContainer, segs, bindDaySeg);
}
function daySegCalcHSides(segs) { // also sets seg.key
var i;
var segCnt = segs.length;
var seg;
var element;
var key, val;
var hsideCache = {};
// record event horizontal sides
for (i=0; i<segCnt; i++) {
seg = segs[i];
element = seg.element;
if (element) {
key = seg.key = cssKey(element[0]);
val = hsideCache[key];
if (val === undefined) {
val = hsideCache[key] = hsides(element, true);
}
seg.hsides = val;
}
}
}
function daySegSetWidths(segs) {
var i;
var segCnt = segs.length;
var seg;
var element;
for (i=0; i<segCnt; i++) {
seg = segs[i];
element = seg.element;
if (element) {
element[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
}
}
}
function daySegCalcHeights(segs) {
var i;
var segCnt = segs.length;
var seg;
var element;
var key, val;
var vmarginCache = {};
// record event heights
for (i=0; i<segCnt; i++) {
seg = segs[i];
element = seg.element;
if (element) {
key = seg.key; // created in daySegCalcHSides
val = vmarginCache[key];
if (val === undefined) {
val = vmarginCache[key] = vmargins(element);
}
seg.outerHeight = element[0].offsetHeight + val;
}
}
}
function getRowDivs() {
var i;
var rowCnt = getRowCnt();
var rowDivs = [];
for (i=0; i<rowCnt; i++) {
rowDivs[i] = allDayRow(i)
.find('div.fc-day-content > div'); // optimal selector?
}
return rowDivs;
}
function getRowTops(rowDivs) {
var i;
var rowCnt = rowDivs.length;
var tops = [];
for (i=0; i<rowCnt; i++) {
tops[i] = rowDivs[i][0].offsetTop; // !!?? but this means the element needs position:relative if in a table cell!!!!
}
return tops;
}
function daySegSetTops(segs, rowTops) { // also triggers eventAfterRender
var i;
var segCnt = segs.length;
var seg;
var element;
var event;
for (i=0; i<segCnt; i++) {
seg = segs[i];
element = seg.element;
if (element) {
element[0].style.top = rowTops[seg.row] + (seg.top||0) + 'px';
event = seg.event;
trigger('eventAfterRender', event, event, element);
}
}
}
/* Resizing
-----------------------------------------------------------------------------------*/
function resizableDayEvent(event, element, seg) {
var rtl = opt('isRTL');
var direction = rtl ? 'w' : 'e';
var handle = element.find('.ui-resizable-' + direction); // TODO: stop using this class because we aren't using jqui for this
var isResizing = false;
// TODO: look into using jquery-ui mouse widget for this stuff
disableTextSelection(element); // prevent native <a> selection for IE
element
.mousedown(function(ev) { // prevent native <a> selection for others
ev.preventDefault();
})
.click(function(ev) {
if (isResizing) {
ev.preventDefault(); // prevent link from being visited (only method that worked in IE6)
ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called
// (eventElementHandlers needs to be bound after resizableDayEvent)
}
});
handle.mousedown(function(ev) {
if (ev.which != 1) {
return; // needs to be left mouse button
}
isResizing = true;
var hoverListener = t.getHoverListener();
var rowCnt = getRowCnt();
var colCnt = getColCnt();
var dis = rtl ? -1 : 1;
var dit = rtl ? colCnt-1 : 0;
var elementTop = element.css('top');
var dayDelta;
var helpers;
var eventCopy = $.extend({}, event);
var minCell = dateCell(event.start);
clearSelection();
$('body')
.css('cursor', direction + '-resize')
.one('mouseup', mouseup);
trigger('eventResizeStart', this, event, ev);
hoverListener.start(function(cell, origCell) {
if (cell) {
var r = Math.max(minCell.row, cell.row);
var c = cell.col;
if (rowCnt == 1) {
r = 0; // hack for all-day area in agenda views
}
if (r == minCell.row) {
if (rtl) {
c = Math.min(minCell.col, c);
}else{
c = Math.max(minCell.col, c);
}
}
dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit);
var newEnd = addDays(eventEnd(event), dayDelta, true);
if (dayDelta) {
eventCopy.end = newEnd;
var oldHelpers = helpers;
helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop);
helpers.find('*').css('cursor', direction + '-resize');
if (oldHelpers) {
oldHelpers.remove();
}
hideEvents(event);
}else{
if (helpers) {
showEvents(event);
helpers.remove();
helpers = null;
}
}
clearOverlays();
renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start
}
}, ev);
function mouseup(ev) {
trigger('eventResizeStop', this, event, ev);
$('body').css('cursor', '');
hoverListener.stop();
clearOverlays();
if (dayDelta) {
eventResize(this, event, dayDelta, 0, ev);
// event redraw will clear helpers
}
// otherwise, the drag handler already restored the old events
setTimeout(function() { // make this happen after the element's click event
isResizing = false;
},0);
}
});
}
}
;;
//BUG: unselect needs to be triggered when events are dragged+dropped
function SelectionManager() {
var t = this;
// exports
t.select = select;
t.unselect = unselect;
t.reportSelection = reportSelection;
t.daySelectionMousedown = daySelectionMousedown;
// imports
var opt = t.opt;
var trigger = t.trigger;
var defaultSelectionEnd = t.defaultSelectionEnd;
var renderSelection = t.renderSelection;
var clearSelection = t.clearSelection;
// locals
var selected = false;
// unselectAuto
if (opt('selectable') && opt('unselectAuto')) {
$(document).mousedown(function(ev) {
var ignore = opt('unselectCancel');
if (ignore) {
if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
return;
}
}
unselect(ev);
});
}
function select(startDate, endDate, allDay) {
unselect();
if (!endDate) {
endDate = defaultSelectionEnd(startDate, allDay);
}
renderSelection(startDate, endDate, allDay);
reportSelection(startDate, endDate, allDay);
}
function unselect(ev) {
if (selected) {
selected = false;
clearSelection();
trigger('unselect', null, ev);
}
}
function reportSelection(startDate, endDate, allDay, ev) {
selected = true;
trigger('select', null, startDate, endDate, allDay, ev);
}
function daySelectionMousedown(ev) { // not really a generic manager method, oh well
var cellDate = t.cellDate;
var cellIsAllDay = t.cellIsAllDay;
var hoverListener = t.getHoverListener();
var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
unselect(ev);
var _mousedownElement = this;
var dates;
hoverListener.start(function(cell, origCell) { // TODO: maybe put cellDate/cellIsAllDay info in cell
clearSelection();
if (cell && cellIsAllDay(cell)) {
dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp);
renderSelection(dates[0], dates[1], true);
}else{
dates = null;
}
}, ev);
$(document).one('mouseup', function(ev) {
hoverListener.stop();
if (dates) {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], true, ev);
}
reportSelection(dates[0], dates[1], true, ev);
}
});
}
}
}
;;
function OverlayManager() {
var t = this;
// exports
t.renderOverlay = renderOverlay;
t.clearOverlays = clearOverlays;
// locals
var usedOverlays = [];
var unusedOverlays = [];
function renderOverlay(rect, parent) {
var e = unusedOverlays.shift();
if (!e) {
e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>");
}
if (e[0].parentNode != parent[0]) {
e.appendTo(parent);
}
usedOverlays.push(e.css(rect).show());
return e;
}
function clearOverlays() {
var e;
while (e = usedOverlays.shift()) {
unusedOverlays.push(e.hide().unbind());
}
}
}
;;
function CoordinateGrid(buildFunc) {
var t = this;
var rows;
var cols;
t.build = function() {
rows = [];
cols = [];
buildFunc(rows, cols);
};
t.cell = function(x, y) {
var rowCnt = rows.length;
var colCnt = cols.length;
var i, r=-1, c=-1;
for (i=0; i<rowCnt; i++) {
if (y >= rows[i][0] && y < rows[i][1]) {
r = i;
break;
}
}
for (i=0; i<colCnt; i++) {
if (x >= cols[i][0] && x < cols[i][1]) {
c = i;
break;
}
}
return (r>=0 && c>=0) ? { row:r, col:c } : null;
};
t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive
var origin = originElement.offset();
return {
top: rows[row0][0] - origin.top,
left: cols[col0][0] - origin.left,
width: cols[col1][1] - cols[col0][0],
height: rows[row1][1] - rows[row0][0]
};
};
}
;;
function HoverListener(coordinateGrid) {
var t = this;
var bindType;
var change;
var firstCell;
var cell;
t.start = function(_change, ev, _bindType) {
change = _change;
firstCell = cell = null;
coordinateGrid.build();
mouse(ev);
bindType = _bindType || 'mousemove';
$(document).bind(bindType, mouse);
};
function mouse(ev) {
_fixUIEvent(ev); // see below
var newCell = coordinateGrid.cell(ev.pageX, ev.pageY);
if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) {
if (newCell) {
if (!firstCell) {
firstCell = newCell;
}
change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col);
}else{
change(newCell, firstCell);
}
cell = newCell;
}
}
t.stop = function() {
$(document).unbind(bindType, mouse);
return cell;
};
}
// this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1)
// upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem
// but keep this in here for 1.8.16 users
// and maybe remove it down the line
function _fixUIEvent(event) { // for issue 1168
if (event.pageX === undefined) {
event.pageX = event.originalEvent.pageX;
event.pageY = event.originalEvent.pageY;
}
}
;;
function HorizontalPositionCache(getElement) {
var t = this,
elements = {},
lefts = {},
rights = {};
function e(i) {
return elements[i] = elements[i] || getElement(i);
}
t.left = function(i) {
return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i];
};
t.right = function(i) {
return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i];
};
t.clear = function() {
elements = {};
lefts = {};
rights = {};
};
}
;;
})(jQuery); | JavaScript |
/**
* @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time at http://ckeditor.com/builder to build CKEditor again.
*
* NOTE:
* This file is not used by CKEditor, you may remove it.
* Changing this file will not change your CKEditor configuration.
*/
var CKBUILDER_CONFIG = {
skin: 'moono',
preset: 'standard',
ignore: [
'dev',
'.gitignore',
'.gitattributes',
'README.md',
'.mailmap'
],
plugins : {
'about' : 1,
'a11yhelp' : 1,
'basicstyles' : 1,
'blockquote' : 1,
'clipboard' : 1,
'contextmenu' : 1,
'resize' : 1,
'toolbar' : 1,
'elementspath' : 1,
'enterkey' : 1,
'entities' : 1,
'filebrowser' : 1,
'floatingspace' : 1,
'format' : 1,
'htmlwriter' : 1,
'horizontalrule' : 1,
'wysiwygarea' : 1,
'image' : 1,
'indent' : 1,
'link' : 1,
'list' : 1,
'magicline' : 1,
'maximize' : 1,
'pastetext' : 1,
'pastefromword' : 1,
'removeformat' : 1,
'sourcearea' : 1,
'specialchar' : 1,
'stylescombo' : 1,
'tab' : 1,
'table' : 1,
'tabletools' : 1,
'undo' : 1,
'dialog' : 1,
'dialogui' : 1,
'menu' : 1,
'floatpanel' : 1,
'panel' : 1,
'button' : 1,
'popup' : 1,
'richcombo' : 1,
'listblock' : 1,
'fakeobjects' : 1
},
languages : {
'af' : 1,
'ar' : 1,
'eu' : 1,
'bn' : 1,
'bs' : 1,
'bg' : 1,
'ca' : 1,
'zh-cn' : 1,
'zh' : 1,
'hr' : 1,
'cs' : 1,
'da' : 1,
'nl' : 1,
'en' : 1,
'en-au' : 1,
'en-ca' : 1,
'en-gb' : 1,
'eo' : 1,
'et' : 1,
'fo' : 1,
'fi' : 1,
'fr' : 1,
'fr-ca' : 1,
'gl' : 1,
'ka' : 1,
'de' : 1,
'el' : 1,
'gu' : 1,
'he' : 1,
'hi' : 1,
'hu' : 1,
'is' : 1,
'it' : 1,
'ja' : 1,
'km' : 1,
'ko' : 1,
'ku' : 1,
'lv' : 1,
'lt' : 1,
'mk' : 1,
'ms' : 1,
'mn' : 1,
'no' : 1,
'nb' : 1,
'fa' : 1,
'pl' : 1,
'pt-br' : 1,
'pt' : 1,
'ro' : 1,
'ru' : 1,
'sr' : 1,
'sr-latn' : 1,
'sk' : 1,
'sl' : 1,
'es' : 1,
'sv' : 1,
'th' : 1,
'tr' : 1,
'ug' : 1,
'uk' : 1,
'vi' : 1,
'cy' : 1,
}
}; | JavaScript |
/**
* @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here.
// For the complete reference:
// http://docs.ckeditor.com/#!/api/CKEDITOR.config
// The toolbar groups arrangement, optimized for two toolbar rows.
config.toolbarGroups = [
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
{ name: 'links' },
{ name: 'insert' },
{ name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ] },
{ name: 'styles' },
{ name: 'colors',items: ['TextColor', 'BGColor'] }
];
// Remove some buttons, provided by the standard plugins, which we don't
// need to have in the Standard(s) toolbar.
config.removeButtons = 'Underline,Subscript,Superscript';
};
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
/**
* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// This file contains style definitions that can be used by CKEditor plugins.
//
// The most common use for it is the "stylescombo" plugin, which shows a combo
// in the editor toolbar, containing all styles. Other plugins instead, like
// the div plugin, use a subset of the styles on their feature.
//
// If you don't have plugins that depend on this file, you can simply ignore it.
// Otherwise it is strongly recommended to customize this file to match your
// website requirements and design properly.
CKEDITOR.stylesSet.add( 'default', [
/* Block Styles */
// These styles are already available in the "Format" combo ("format" plugin),
// so they are not needed here by default. You may enable them to avoid
// placing the "Format" combo in the toolbar, maintaining the same features.
/*
{ name: 'Paragraph', element: 'p' },
{ name: 'Heading 1', element: 'h1' },
{ name: 'Heading 2', element: 'h2' },
{ name: 'Heading 3', element: 'h3' },
{ name: 'Heading 4', element: 'h4' },
{ name: 'Heading 5', element: 'h5' },
{ name: 'Heading 6', element: 'h6' },
{ name: 'Preformatted Text',element: 'pre' },
{ name: 'Address', element: 'address' },
*/
{ name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } },
{ name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } },
{
name: 'Special Container',
element: 'div',
styles: {
padding: '5px 10px',
background: '#eee',
border: '1px solid #ccc'
}
},
/* Inline Styles */
// These are core styles available as toolbar buttons. You may opt enabling
// some of them in the Styles combo, removing them from the toolbar.
// (This requires the "stylescombo" plugin)
/*
{ name: 'Strong', element: 'strong', overrides: 'b' },
{ name: 'Emphasis', element: 'em' , overrides: 'i' },
{ name: 'Underline', element: 'u' },
{ name: 'Strikethrough', element: 'strike' },
{ name: 'Subscript', element: 'sub' },
{ name: 'Superscript', element: 'sup' },
*/
{ name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } },
{ name: 'Marker: Green', element: 'span', styles: { 'background-color': 'Lime' } },
{ name: 'Big', element: 'big' },
{ name: 'Small', element: 'small' },
{ name: 'Typewriter', element: 'tt' },
{ name: 'Computer Code', element: 'code' },
{ name: 'Keyboard Phrase', element: 'kbd' },
{ name: 'Sample Text', element: 'samp' },
{ name: 'Variable', element: 'var' },
{ name: 'Deleted Text', element: 'del' },
{ name: 'Inserted Text', element: 'ins' },
{ name: 'Cited Work', element: 'cite' },
{ name: 'Inline Quotation', element: 'q' },
{ name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } },
{ name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } },
/* Object Styles */
{
name: 'Styled image (left)',
element: 'img',
attributes: { 'class': 'left' }
},
{
name: 'Styled image (right)',
element: 'img',
attributes: { 'class': 'right' }
},
{
name: 'Compact table',
element: 'table',
attributes: {
cellpadding: '5',
cellspacing: '0',
border: '1',
bordercolor: '#ccc'
},
styles: {
'border-collapse': 'collapse'
}
},
{ name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } },
{ name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } }
]);
| JavaScript |
/*
* jQuery Tooltip plugin 1.2
*
* http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
* http://docs.jquery.com/Plugins/Tooltip
*
* Copyright (c) 2006 - 2008 Jörn Zaefferer
*
* $Id: jquery.tooltip.js 4569 2008-01-31 19:36:35Z joern.zaefferer $
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function($) {
// the tooltip element
var helper = {},
// the current tooltipped element
current,
// the title of the current element, used for restoring
title,
// timeout id for delayed tooltips
tID,
// IE 5.5 or 6
IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
// flag for mouse tracking
track = false;
$.tooltip = {
blocked: false,
defaults: {
delay: 200,
showURL: true,
extraClass: "",
top: 15,
left: 15,
id: "tooltip"
},
block: function() {
$.tooltip.blocked = !$.tooltip.blocked;
}
};
$.fn.extend({
tooltip: function(settings) {
settings = $.extend({}, $.tooltip.defaults, settings);
createHelper(settings);
return this.each(function() {
$.data(this, "tooltip-settings", settings);
// copy tooltip into its own expando and remove the title
this.tooltipText = this.title;
$(this).removeAttr("title");
// also remove alt attribute to prevent default tooltip in IE
this.alt = "";
})
.hover(save, hide)
.click(hide);
},
fixPNG: IE ? function() {
return this.each(function () {
var image = $(this).css('backgroundImage');
if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
image = RegExp.$1;
$(this).css({
'backgroundImage': 'none',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
}).each(function () {
var position = $(this).css('position');
if (position != 'absolute' && position != 'relative')
$(this).css('position', 'relative');
});
}
});
} : function() { return this; },
unfixPNG: IE ? function() {
return this.each(function () {
$(this).css({'filter': '', backgroundImage: ''});
});
} : function() { return this; },
hideWhenEmpty: function() {
return this.each(function() {
$(this)[ $(this).html() ? "show" : "hide" ]();
});
},
url: function() {
return this.attr('href') || this.attr('src');
}
});
function createHelper(settings) {
// there can be only one tooltip helper
if( helper.parent )
return;
// create the helper, h3 for title, div for url
helper.parent = $('<div id="' + settings.id + '"><h6></h6><div class="body"></div><div class="url"></div></div>')
// add to document
.appendTo(document.body)
// hide it at first
.hide();
// apply bgiframe if available
if ( $.fn.bgiframe )
helper.parent.bgiframe();
// save references to title and url elements
helper.title = $('h6', helper.parent);
helper.body = $('div.body', helper.parent);
helper.url = $('div.url', helper.parent);
}
function settings(element) {
return $.data(element, "tooltip-settings");
}
// main event handler to start showing tooltips
function handle(event) {
// show helper, either with timeout or on instant
if( settings(this).delay )
tID = setTimeout(show, settings(this).delay);
else
show();
// if selected, update the helper position when the mouse moves
track = !!settings(this).track;
$(document.body).bind('mousemove', update);
// update at least once
update(event);
}
// save elements title before the tooltip is displayed
function save() {
// if this is the current source, or it has no title (occurs with click event), stop
if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
return;
// save current
current = this;
title = this.tooltipText;
if ( settings(this).bodyHandler ) {
helper.title.hide();
var bodyContent = settings(this).bodyHandler.call(this);
if (bodyContent.nodeType || bodyContent.jquery) {
helper.body.empty().append(bodyContent)
} else {
helper.body.html( bodyContent );
}
helper.body.show();
} else if ( settings(this).showBody ) {
var parts = title.split(settings(this).showBody);
helper.title.html(parts.shift()).show();
helper.body.empty();
for(var i = 0, part; part = parts[i]; i++) {
if(i > 0)
helper.body.append("<br/>");
helper.body.append(part);
}
helper.body.hideWhenEmpty();
} else {
helper.title.html(title).show();
helper.body.hide();
}
// if element has href or src, add and show it, otherwise hide it
if( settings(this).showURL && $(this).url() )
helper.url.html( $(this).url().replace('http://', '') ).show();
else
helper.url.hide();
// add an optional class for this tip
helper.parent.addClass(settings(this).extraClass);
// fix PNG background for IE
if (settings(this).fixPNG )
helper.parent.fixPNG();
handle.apply(this, arguments);
}
// delete timeout and show helper
function show() {
tID = null;
helper.parent.show();
update();
}
/**
* callback for mousemove
* updates the helper position
* removes itself when no current element
*/
function update(event) {
if($.tooltip.blocked)
return;
// stop updating when tracking is disabled and the tooltip is visible
if ( !track && helper.parent.is(":visible")) {
$(document.body).unbind('mousemove', update)
}
// if no current element is available, remove this listener
if( current == null ) {
$(document.body).unbind('mousemove', update);
return;
}
// remove position helper classes
helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
var left = helper.parent[0].offsetLeft;
var top = helper.parent[0].offsetTop;
if(event) {
// position the helper 15 pixel to bottom right, starting from mouse position
left = event.pageX + settings(current).left;
top = event.pageY + settings(current).top;
helper.parent.css({
left: left + 'px',
top: top + 'px'
});
}
var v = viewport(),
h = helper.parent[0];
// check horizontal position
if(v.x + v.cx < h.offsetLeft + h.offsetWidth) {
left -= h.offsetWidth + 20 + settings(current).left;
helper.parent.css({left: left + 'px'}).addClass("viewport-right");
}
// check vertical position
if(v.y + v.cy < h.offsetTop + h.offsetHeight) {
top -= h.offsetHeight + 20 + settings(current).top;
helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
}
}
function viewport() {
return {
x: $(window).scrollLeft(),
y: $(window).scrollTop(),
cx: $(window).width(),
cy: $(window).height()
};
}
// hide helper and restore added classes and the title
function hide(event) {
if($.tooltip.blocked)
return;
// clear timeout if possible
if(tID)
clearTimeout(tID);
// no more current element
current = null;
helper.parent.hide().removeClass( settings(this).extraClass );
if( settings(this).fixPNG )
helper.parent.unfixPNG();
}
$.fn.Tooltip = $.fn.tooltip;
})(jQuery);
| JavaScript |
/*
* jQuery showLoading plugin v1.0
*
* Copyright (c) 2009 Jim Keller
* Context - http://www.contextllc.com
*
* Dual licensed under the MIT and GPL licenses.
*
*/
jQuery.fn.showLoading = function(options) {
var indicatorID;
var settings = {
'addClass': '',
'beforeShow': '',
'afterShow': '',
'hPos': 'center',
'vPos': 'center',
'indicatorZIndex' : 5001,
'overlayZIndex': 5000,
'parent': '',
'marginTop': 0,
'marginLeft': 0,
'overlayWidth': null,
'overlayHeight': null
};
jQuery.extend(settings, options);
var loadingDiv = jQuery('<div></div>');
var overlayDiv = jQuery('<div></div>');
//
// Set up ID and classes
//
if ( settings.indicatorID ) {
indicatorID = settings.indicatorID;
}
else {
indicatorID = jQuery(this).attr('id');
}
jQuery(loadingDiv).attr('id', 'loading-indicator-' + indicatorID );
jQuery(loadingDiv).addClass('loading-indicator');
if ( settings.addClass ){
jQuery(loadingDiv).addClass(settings.addClass);
}
//
// Create the overlay
//
jQuery(overlayDiv).css('display', 'none');
// Append to body, otherwise position() doesn't work on Webkit-based browsers
jQuery(document.body).append(overlayDiv);
//
// Set overlay classes
//
jQuery(overlayDiv).attr('id', 'loading-indicator-' + indicatorID + '-overlay');
jQuery(overlayDiv).addClass('loading-indicator-overlay');
if ( settings.addClass ){
jQuery(overlayDiv).addClass(settings.addClass + '-overlay');
}
//
// Set overlay position
//
var overlay_width;
var overlay_height;
var border_top_width = jQuery(this).css('border-top-width');
var border_left_width = jQuery(this).css('border-left-width');
//
// IE will return values like 'medium' as the default border,
// but we need a number
//
border_top_width = isNaN(parseInt(border_top_width)) ? 0 : border_top_width;
border_left_width = isNaN(parseInt(border_left_width)) ? 0 : border_left_width;
var overlay_left_pos = jQuery(this).offset().left + parseInt(border_left_width);
var overlay_top_pos = jQuery(this).offset().top + parseInt(border_top_width);
if ( settings.overlayWidth !== null ) {
overlay_width = settings.overlayWidth;
}
else {
overlay_width = parseInt(jQuery(this).width()) + parseInt(jQuery(this).css('padding-right')) + parseInt(jQuery(this).css('padding-left'));
}
if ( settings.overlayHeight !== null ) {
overlay_height = settings.overlayWidth;
}
else {
overlay_height = parseInt(jQuery(this).height()) + parseInt(jQuery(this).css('padding-top')) + parseInt(jQuery(this).css('padding-bottom'));
}
jQuery(overlayDiv).css('width', overlay_width.toString() + 'px');
jQuery(overlayDiv).css('height', overlay_height.toString() + 'px');
jQuery(overlayDiv).css('left', overlay_left_pos.toString() + 'px');
jQuery(overlayDiv).css('position', 'absolute');
jQuery(overlayDiv).css('top', overlay_top_pos.toString() + 'px' );
jQuery(overlayDiv).css('z-index', settings.overlayZIndex);
//
// Set any custom overlay CSS
//
if ( settings.overlayCSS ) {
jQuery(overlayDiv).css ( settings.overlayCSS );
}
//
// We have to append the element to the body first
// or .width() won't work in Webkit-based browsers (e.g. Chrome, Safari)
//
jQuery(loadingDiv).css('display', 'none');
jQuery(document.body).append(loadingDiv);
jQuery(loadingDiv).css('position', 'absolute');
jQuery(loadingDiv).css('z-index', settings.indicatorZIndex);
//
// Set top margin
//
var indicatorTop = overlay_top_pos;
if ( settings.marginTop ) {
indicatorTop += parseInt(settings.marginTop);
}
var indicatorLeft = overlay_left_pos;
if ( settings.marginLeft ) {
indicatorLeft += parseInt(settings.marginTop);
}
//
// set horizontal position
//
if ( settings.hPos.toString().toLowerCase() == 'center' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + ((jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width())) / 2)).toString() + 'px');
}
else if ( settings.hPos.toString().toLowerCase() == 'left' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(jQuery(overlayDiv).css('margin-left'))).toString() + 'px');
}
else if ( settings.hPos.toString().toLowerCase() == 'right' ) {
jQuery(loadingDiv).css('left', (indicatorLeft + (jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width()))).toString() + 'px');
}
else {
jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(settings.hPos)).toString() + 'px');
}
//
// set vertical position
//
if ( settings.vPos.toString().toLowerCase() == 'center' ) {
jQuery(loadingDiv).css('top', (indicatorTop + ((jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height())) / 2)).toString() + 'px');
}
else if ( settings.vPos.toString().toLowerCase() == 'top' ) {
jQuery(loadingDiv).css('top', indicatorTop.toString() + 'px');
}
else if ( settings.vPos.toString().toLowerCase() == 'bottom' ) {
jQuery(loadingDiv).css('top', (indicatorTop + (jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height()))).toString() + 'px');
}
else {
jQuery(loadingDiv).css('top', (indicatorTop + parseInt(settings.vPos)).toString() + 'px' );
}
//
// Set any custom css for loading indicator
//
if ( settings.css ) {
jQuery(loadingDiv).css ( settings.css );
}
//
// Set up callback options
//
var callback_options =
{
'overlay': overlayDiv,
'indicator': loadingDiv,
'element': this
};
//
// beforeShow callback
//
if ( typeof(settings.beforeShow) == 'function' ) {
settings.beforeShow( callback_options );
}
//
// Show the overlay
//
jQuery(overlayDiv).show();
//
// Show the loading indicator
//
jQuery(loadingDiv).show();
//
// afterShow callback
//
if ( typeof(settings.afterShow) == 'function' ) {
settings.afterShow( callback_options );
}
return this;
};
jQuery.fn.hideLoading = function(options) {
var settings = {};
jQuery.extend(settings, options);
if ( settings.indicatorID ) {
indicatorID = settings.indicatorID;
}
else {
indicatorID = jQuery(this).attr('id');
}
jQuery(document.body).find('#loading-indicator-' + indicatorID ).remove();
jQuery(document.body).find('#loading-indicator-' + indicatorID + '-overlay' ).remove();
return this;
};
| JavaScript |
$(document).ready(function() {
// Our Confirm method
function Confirm(question, callback) {
// Content will consist of the question and ok/cancel buttons
var message = $('<p />', { text: question }),
ok = $('<button />', {
text: 'Ok',
click: function() { callback(true); }
}),
cancel = $('<button />', {
text: 'Cancel',
click: function() { callback(false); }
});
dialogue(message.add(ok).add(cancel), 'Do you agree?');
}
// Our Alert method
function Alert(message) {
// Content will consist of the message and an ok button
var message = $('<p />', { text: message }),
ok = $('<button />', { text: 'Ok', 'class': 'full' });
dialogue(message.add(ok), 'Alert!');
}
// Our Prompt method
function Prompt(question, initial, callback) {
// Content will consist of a question elem and input, with ok/cancel buttons
var message = $('<p />', { text: question }),
input = $('<input />', { val: initial }),
ok = $('<button />', {
text: 'Ok',
click: function() { callback(input.val()); }
}),
cancel = $('<button />', {
text: 'Cancel',
click: function() { callback(null); }
});
dialogue(message.add(input).add(ok).add(cancel), 'Attention!');
}
function dialogue(content, title) {
/*
* Since the dialogue isn't really a tooltip as such, we'll use a dummy
* out-of-DOM element as our target instead of an actual element like document.body
*/
$('<div />').qtip(
{
content: {
text: content,
title: title
},
position: {
my: 'center', at: 'center', // Center it...
target: $(window) // ... in the window
},
show: {
ready: true, // Show it straight away
modal: {
on: true, // Make it modal (darken the rest of the page)...
blur: false // ... but don't close the tooltip when clicked
}
},
hide: false, // We'll hide it maunally so disable hide events
style: 'qtip-light qtip-rounded qtip-dialogue', // Add a few styles
events: {
// Hide the tooltip when any buttons in the dialogue are clicked
render: function(event, api) {
$('button', api.elements.content).click(api.hide);
},
// Destroy the tooltip once it's hidden as we no longer need it!
hide: function(event, api) { api.destroy(); }
}
});
}
//Checked
$('#toggle-all-pending').click(function() {
//
if ($(this).attr('class') != "toggle-checked") {
$('#mainformpending input[type=checkbox]').attr('checked', false);
}
$('#mainformpending input').checkBox();
$('#toggle-all-pending').toggleClass('toggle-checked');
$('#mainformpending input[type=checkbox]').checkBox('toggle');
return false;
});
$('#mainformpending input:checkbox:not(#toggle-all-pending)').click(function() {
$('#toggle-all-pending').removeClass('toggle-checked');
});
//Checked
$('#toggle-all-rejected').click(function() {
//
if ($(this).attr('class') != "toggle-checked") {
$('#mainformrejected input[type=checkbox]').attr('checked', false);
}
$('#mainformrejected input').checkBox();
$('#toggle-all-rejected').toggleClass('toggle-checked');
$('#mainformrejected input[type=checkbox]').checkBox('toggle');
return false;
});
$('#mainformrejected input:checkbox:not(#toggle-all-rejected)').click(function() {
$('#toggle-all-rejected').removeClass('toggle-checked');
});
//
//prompt for delete button
$('.remove-btn').click(function(e) {
e.preventDefault(); //prevent default action for anchor
var self = this;
Confirm("Confirm removed the selected records?", function(yes) {
if (yes) {
window.location = self.href;
}
});
});
//bulk process action
$('.action-invoke').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
Alert('Please select at least one item.');
return false;
} else {
//submit form
$(".list_item_form").attr("action", this.href);
$(".list_item_form").submit();
}
});
//bulk process delete action
$('.action-invoke-removed').click(function(e) {
e.preventDefault(); //prevent default action for anchor
//ensure at least one item is checked
var fields = $("input[name='selected']").serializeArray();
if (fields.length == 0) {
Alert('Please select at least one item.');
return false;
} else {
var self = this;
Confirm("Confirm removed the selected records?", function(yes) {
if (yes) {
$(".list_item_form").attr("action", self.href);
$(".list_item_form").submit();
}
});
}
});
// 1 - START DROPDOWN SLIDER SCRIPTS ------------------------------------------------------------------------
$(".action-slider").click(function() {
$("#actions-box-slider").slideToggle("fast");
$(this).toggleClass("activated");
return false;
});
$(".action-slider-reject").click(function() {
$("#actions-box-slider-reject").slideToggle("fast");
$(this).toggleClass("activated");
return false;
});
// END ----------------------------- 1
});
| JavaScript |
//Load JS
var jspath = BASE_URL + "Scripts/";
var csspath = BASE_URL + "Content/css/";
//head.js(jspath + "Utility.js"); | JavaScript |
var config = {
language: 'en-gb',
scayt_autoStartup: true,
toolbar:
[
['Print', 'Templates', 'Bold', 'Italic', 'Underline', 'TextColor', 'Table', 'SpecialChar', '-', 'NumberedList', 'BulletedList', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['Cut', 'Copy', 'Off', 'PasteText', 'PasteFromWord', 'Link', 'Unlink'], ['Undo', 'Redo', '-', 'SelectAll'],
['Font', 'FontSize']
],
coreStyles_bold: { element: 'b', overrides: 'strong' }
}
$('textarea.ckeditors').ckeditor(config);
| JavaScript |
head.ready(function() {
// Create namespace System.Data
// Intergrate with Jquery
System.Data.ProjectNameModel = function() {
var self = this;
//
self.availableProjects = ko.observableArray([]);
self.selected = ko.observableArray([]);
//save
self.save = function(form) {
alert("Ok");
};
self.loadProjectName = function() {
$.getJSON(BASE_URL + "Listings/Ajax/getProjectname", function(result) {
self.availableProjects(result.Data);
$("#project-name").chosen({
allow_single_deselect: true
});
$("#project-name").removeClass("hide");
});
};
}
});
| JavaScript |
/**
* @author trixta
*/
(function($){
$.bind = function(object, method){
var args = Array.prototype.slice.call(arguments, 2);
if(args.length){
return function() {
var args2 = [this].concat(args, $.makeArray( arguments ));
return method.apply(object, args2);
};
} else {
return function() {
var args2 = [this].concat($.makeArray( arguments ));
return method.apply(object, args2);
};
}
};
})(jQuery);
| JavaScript |
/**
* @author alexander.farkas
* @version 1.3
*/
(function($){
$.widget('ui.checkBox', {
_init: function(){
var that = this,
opts = this.options,
toggleHover = function(e){
if(this.disabledStatus){
return false;
}
that.hover = (e.type == 'focus' || e.type == 'mouseenter');
that._changeStateClassChain();
};
if(!this.element.is(':radio,:checkbox')){
return false;
}
this.labels = $([]);
this.checkedStatus = false;
this.disabledStatus = false;
this.hoverStatus = false;
this.radio = (this.element.is(':radio'));
this.visualElement = $('<span />')
.addClass(this.radio ? 'ui-radio' : 'ui-checkbox')
.bind('mouseenter.checkBox mouseleave.checkBox', toggleHover)
.bind('click.checkBox', function(e){
that.element[0].click();
//that.element.trigger('click');
return false;
});
if (opts.replaceInput) {
this.element
.addClass('ui-helper-hidden-accessible')
.after(this.visualElement[0])
.bind('usermode', function(e){
(e.enabled &&
that.destroy.call(that, true));
});
}
this.element
.bind('click.checkBox', $.bind(this, this.reflectUI))
.bind('focus.checkBox blur.checkBox', toggleHover);
if(opts.addLabel){
//ToDo: Add Closest Ancestor
this.labels = $('label[for=' + this.element.attr('id') + ']')
.bind('mouseenter.checkBox mouseleave.checkBox', toggleHover);
}
this.reflectUI({type: 'initialReflect'});
},
_changeStateClassChain: function(){
var stateClass = (this.checkedStatus) ? '-checked' : '',
baseClass = 'ui-'+((this.radio) ? 'radio' : 'checkbox')+'-state';
stateClass += (this.disabledStatus) ? '-disabled' : '';
stateClass += (this.hover) ? '-hover' : '';
if(stateClass){
stateClass = baseClass + stateClass;
}
function switchStateClass(){
var classes = this.className.split(' '),
found = false;
$.each(classes, function(i, classN){
if(classN.indexOf(baseClass) === 0){
found = true;
classes[i] = stateClass;
return false;
}
});
if(!found){
classes.push(stateClass);
}
this.className = classes.join(' ');
}
this.labels.each(switchStateClass);
this.visualElement.each(switchStateClass);
},
destroy: function(onlyCss){
this.element.removeClass('ui-helper-hidden-accessible');
this.visualElement.addClass('ui-helper-hidden');
if (!onlyCss) {
var o = this.options;
this.element.unbind('.checkBox');
this.visualElement.remove();
this.labels
.unbind('.checkBox')
.removeClass('ui-state-hover ui-state-checked ui-state-disabled');
}
},
disable: function(){
this.element[0].disabled = true;
this.reflectUI({type: 'manuallyDisabled'});
},
enable: function(){
this.element[0].disabled = false;
this.reflectUI({type: 'manuallyenabled'});
},
toggle: function(e){
this.changeCheckStatus((this.element.is(':checked')) ? false : true, e);
},
changeCheckStatus: function(status, e){
if(e && e.type == 'click' && this.element[0].disabled){
return false;
}
this.element.attr({'checked': status});
this.reflectUI(e || {
type: 'changeCheckStatus'
});
},
propagate: function(n, e, _noGroupReflect){
if(!e || e.type != 'initialReflect'){
if (this.radio && !_noGroupReflect) {
//dynamic
$(document.getElementsByName(this.element.attr('name')))
.checkBox('reflectUI', e, true);
}
return this._trigger(n, e, {
options: this.options,
checked: this.checkedStatus,
labels: this.labels,
disabled: this.disabledStatus
});
}
},
reflectUI: function(elm, e){
var oldChecked = this.checkedStatus,
oldDisabledStatus = this.disabledStatus;
e = e ||
elm;
this.disabledStatus = this.element.is(':disabled');
this.checkedStatus = this.element.is(':checked');
if (this.disabledStatus != oldDisabledStatus || this.checkedStatus !== oldChecked) {
this._changeStateClassChain();
(this.disabledStatus != oldDisabledStatus &&
this.propagate('disabledChange', e));
(this.checkedStatus !== oldChecked &&
this.propagate('change', e));
}
}
});
$.ui.checkBox.defaults = {
replaceInput: true,
addLabel: true
};
})(jQuery);
| JavaScript |
/*
* jQuery EasIng v1.1.2 - http://gsgd.co.uk/sandbox/jquery.easIng.php
*
* Uses the built In easIng capabilities added In jQuery 1.1
* to offer multiple easIng options
*
* Copyright (c) 2007 George Smith
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.extend( jQuery.easing,
{
easeInQuad: function (x, t, b, c, d) {
return c*(t/=d)*t + b;
},
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic: function (x, t, b, c, d) {
return c*(t/=d)*t*t + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart: function (x, t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine: function (x, t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine: function (x, t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo: function (x, t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo: function (x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo: function (x, t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc: function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc: function (x, t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeInBounce: function (x, t, b, c, d) {
return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
},
easeOutBounce: function (x, t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
easeInOutBounce: function (x, t, b, c, d) {
if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
}
});
| JavaScript |
/*
* jQuery selectbox plugin
*
* Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
* Licensed under the GPL license and MIT:
* http://www.opensource.org/licenses/GPL-license.php
* http://www.opensource.org/licenses/mit-license.php
*
* The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
*
* Revision: $Id$
* Version: 0.5
*
* Changelog :
* Version 0.5
* - separate css style for current selected element and hover element which solve the highlight issue
* Version 0.4
* - Fix width when the select is in a hidden div @Pawel Maziarz
* - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
*/
jQuery.fn.extend({
selectbox: function(options) {
return this.each(function() {
new jQuery.SelectBox(this, options);
});
}
});
/* pawel maziarz: work around for ie logging */
if (!window.console) {
var console = {
log: function(msg) {
}
}
}
/* */
jQuery.SelectBox = function(selectobj, options) {
var opt = options || {};
opt.inputClass = opt.inputClass || "selectbox";
opt.containerClass = opt.containerClass || "selectbox-wrapper";
opt.hoverClass = opt.hoverClass || "current";
opt.currentClass = opt.selectedClass || "selected"
opt.debug = opt.debug || false;
var elm_id = selectobj.id;
var active = -1;
var inFocus = false;
var hasfocus = 0;
//jquery object for select element
var $select = $(selectobj);
// jquery container object
var $container = setupContainer(opt);
//jquery input object
var $input = setupInput(opt);
// hide select and append newly created elements
$select.hide().before($input).before($container);
init();
$input
.click(function(){
if (!inFocus) {
$container.toggle();
}
})
.focus(function(){
if ($container.not(':visible')) {
inFocus = true;
$container.show();
}
})
.keydown(function(event) {
switch(event.keyCode) {
case 38: // up
event.preventDefault();
moveSelect(-1);
break;
case 40: // down
event.preventDefault();
moveSelect(1);
break;
//case 9: // tab
case 13: // return
event.preventDefault(); // seems not working in mac !
$('li.'+opt.hoverClass).trigger('click');
break;
case 27: //escape
hideMe();
break;
}
})
.blur(function() {
if ($container.is(':visible') && hasfocus > 0 ) {
if(opt.debug) console.log('container visible and has focus')
} else {
hideMe();
}
});
function hideMe() {
hasfocus = 0;
$container.hide();
}
function init() {
$container.append(getSelectOptions($input.attr('id'))).hide();
var width = $input.css('width');
$container.width(width);
}
function setupContainer(options) {
var container = document.createElement("div");
$container = $(container);
$container.attr('id', elm_id+'_container');
$container.addClass(options.containerClass);
return $container;
}
function setupInput(options) {
var input = document.createElement("input");
var $input = $(input);
$input.attr("id", elm_id+"_input");
$input.attr("type", "text");
$input.addClass(options.inputClass);
$input.attr("autocomplete", "off");
$input.attr("readonly", "readonly");
$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
return $input;
}
function moveSelect(step) {
var lis = $("li", $container);
if (!lis) return;
active += step;
if (active < 0) {
active = 0;
} else if (active >= lis.size()) {
active = lis.size() - 1;
}
lis.removeClass(opt.hoverClass);
$(lis[active]).addClass(opt.hoverClass);
}
function setCurrent() {
var li = $("li."+opt.currentClass, $container).get(0);
var ar = (''+li.id).split('_');
var el = ar[ar.length-1];
$select.val(el);
$input.val($(li).html());
return true;
}
// select value
function getCurrentSelected() {
return $select.val();
}
// input value
function getCurrentValue() {
return $input.val();
}
function getSelectOptions(parentid) {
var select_options = new Array();
var ul = document.createElement('ul');
$select.children('option').each(function() {
var li = document.createElement('li');
li.setAttribute('id', parentid + '_' + $(this).val());
li.innerHTML = $(this).html();
if ($(this).is(':selected')) {
$input.val($(this).html());
$(li).addClass(opt.currentClass);
}
ul.appendChild(li);
$(li)
.mouseover(function(event) {
hasfocus = 1;
if (opt.debug) console.log('over on : '+this.id);
jQuery(event.target, $container).addClass(opt.hoverClass);
})
.mouseout(function(event) {
hasfocus = -1;
if (opt.debug) console.log('out on : '+this.id);
jQuery(event.target, $container).removeClass(opt.hoverClass);
})
.click(function(event) {
var fl = $('li.'+opt.hoverClass, $container).get(0);
if (opt.debug) console.log('click on :'+this.id);
$('li.'+opt.currentClass).removeClass(opt.currentClass);
$(this).addClass(opt.currentClass);
setCurrent();
hideMe();
});
});
return ul;
}
};
| JavaScript |
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* This field is required",
"alertTextCheckboxMultiple": "* Please select an option",
"alertTextCheckboxe": "* This checkbox is required",
"alertTextDateRange": "* Both date range fields are required"
},
"requiredInFunction": {
"func": function(field, rules, i, options){
return (field.val() == "test") ? true : false;
},
"alertText": "* Field must equal test"
},
"dateRange": {
"regex": "none",
"alertText": "* Invalid ",
"alertText2": "Date Range"
},
"dateTimeRange": {
"regex": "none",
"alertText": "* Invalid ",
"alertText2": "Date Time Range"
},
"minSize": {
"regex": "none",
"alertText": "* Minimum ",
"alertText2": " characters required"
},
"maxSize": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " characters allowed"
},
"groupRequired": {
"regex": "none",
"alertText": "* You must fill one of the following fields"
},
"min": {
"regex": "none",
"alertText": "* Minimum value is "
},
"max": {
"regex": "none",
"alertText": "* Maximum value is "
},
"past": {
"regex": "none",
"alertText": "* Date prior to "
},
"future": {
"regex": "none",
"alertText": "* Date past "
},
"maxCheckbox": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " options allowed"
},
"minCheckbox": {
"regex": "none",
"alertText": "* Please select ",
"alertText2": " options"
},
"equals": {
"regex": "none",
"alertText": "* Fields do not match"
},
"creditCard": {
"regex": "none",
"alertText": "* Invalid credit card number"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/,
"alertText": "* Invalid phone number"
},
"email": {
// HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 )
"regex": /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
"alertText": "* Invalid email address"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* Not a valid integer"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/,
"alertText": "* Invalid floating decimal number"
},
"date": {
// Check if date is valid by leap year
"func": function (field) {
var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
var match = pattern.exec(field.val());
if (match == null)
return false;
var year = match[1];
var month = match[2]*1;
var day = match[3]*1;
var date = new Date(year, month - 1, day); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in YYYY-MM-DD format"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* Invalid IP address"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
"alertText": "* Invalid URL"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* Numbers only"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* Letters only"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z]+$/,
"alertText": "* No special characters allowed"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxUserCallPhp": {
"url": "phpajax/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCall": {
// remote json service location
"url": "ajaxValidateFieldName",
// error
"alertText": "* This name is already taken",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This name is available",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCallPhp": {
// remote json service location
"url": "phpajax/ajaxValidateFieldName.php",
// error
"alertText": "* This name is already taken",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"validate2fields": {
"alertText": "* Please input HELLO"
},
//tls warning:homegrown not fielded
"dateFormat":{
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/,
"alertText": "* Invalid Date"
},
//tls warning:homegrown not fielded
"dateTimeFormat": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/,
"alertText": "* Invalid Date or Date Format",
"alertText2": "Expected Format: ",
"alertText3": "mm/dd/yyyy hh:mm:ss AM|PM or ",
"alertText4": "yyyy-mm-dd hh:mm:ss AM|PM"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery);
| JavaScript |
/*
* Inline Form Validation Engine 2.6, jQuery plugin
*
* Copyright(c) 2010, Cedric Dugas
* http://www.position-absolute.com
*
* 2.0 Rewrite by Olivier Refalo
* http://www.crionics.com
*
* Form validation engine allowing custom regex rules to be added.
* Licensed under the MIT License
*/
(function($) {
"use strict";
var methods = {
/**
* Kind of the constructor, called before any action
* @param {Map} user options
*/
init: function(options) {
var form = this;
if (!form.data('jqv') || form.data('jqv') == null) {
options = methods._saveOptions(form, options);
// bind all formError elements to close on click
$(".formError").live("click", function() {
$(this).fadeOut(150, function() {
// remove prompt once invisible
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
});
}
return this;
},
/**
* Attachs jQuery.validationEngine to form.submit and field.blur events
* Takes an optional params: a list of options
* ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"});
*/
attach: function(userOptions) {
if (!$(this).is("form")) {
alert("Sorry, jqv.attach() only applies to a form");
return this;
}
var form = this;
var options;
if (userOptions)
options = methods._saveOptions(form, userOptions);
else
options = form.data('jqv');
options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class";
if (options.binded) {
// bind fields
form.find("[" + options.validateAttribute + "*=validate]").not("[type=checkbox]").not("[type=radio]").not(".datepicker").bind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[" + options.validateAttribute + "*=validate][type=checkbox],[" + options.validateAttribute + "*=validate][type=radio]").bind("click", methods._onFieldEvent);
form.find("[" + options.validateAttribute + "*=validate][class*=datepicker]").bind(options.validationEventTrigger, { "delay": 300 }, methods._onFieldEvent);
}
if (options.autoPositionUpdate) {
$(window).bind("resize", {
"noAnimation": true,
"formElem": form
}, methods.updatePromptsPosition);
}
// bind form.submit
form.bind("submit", methods._onSubmitEvent);
return this;
},
/**
* Unregisters any bindings that may point to jQuery.validaitonEngine
*/
detach: function() {
if (!$(this).is("form")) {
alert("Sorry, jqv.detach() only applies to a form");
return this;
}
var form = this;
var options = form.data('jqv');
// unbind fields
form.find("[" + options.validateAttribute + "*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[" + options.validateAttribute + "*=validate][type=checkbox],[class*=validate][type=radio]").unbind("click", methods._onFieldEvent);
// unbind form.submit
form.unbind("submit", methods.onAjaxFormComplete);
// unbind live fields (kill)
form.find("[" + options.validateAttribute + "*=validate]").not("[type=checkbox]").die(options.validationEventTrigger, methods._onFieldEvent);
form.find("[" + options.validateAttribute + "*=validate][type=checkbox]").die("click", methods._onFieldEvent);
// unbind form.submit
form.die("submit", methods.onAjaxFormComplete);
form.removeData('jqv');
if (options.autoPositionUpdate)
$(window).unbind("resize", methods.updatePromptsPosition);
return this;
},
/**
* Validates either a form or a list of fields, shows prompts accordingly.
* Note: There is no ajax form validation with this method, only field ajax validation are evaluated
*
* @return true if the form validates, false if it fails
*/
validate: function() {
var element = $(this);
var valid = null;
if (element.is("form") && !element.hasClass('validating')) {
element.addClass('validating');
var options = element.data('jqv');
valid = methods._validateFields(this);
// If the form doesn't validate, clear the 'validating' class before the user has a chance to submit again
setTimeout(function() {
element.removeClass('validating');
}, 100);
if (valid && options.onFormSuccess) {
options.onFormSuccess();
} else if (!valid && options.onFormFailure) {
options.onFormFailure();
}
} else if (element.is('form')) {
element.removeClass('validating');
} else {
// field validation
var form = element.closest('form');
var options = form.data('jqv');
valid = methods._validateField(element, options);
if (valid && options.onFieldSuccess)
options.onFieldSuccess();
else if (options.onFieldFailure && options.InvalidFields.length > 0) {
options.onFieldFailure();
}
}
return valid;
},
/**
* Redraw prompts position, useful when you change the DOM state when validating
*/
updatePromptsPosition: function(event) {
if (event && this == window) {
var form = event.data.formElem;
var noAnimation = event.data.noAnimation;
}
else
var form = $(this.closest('form'));
var options = form.data('jqv');
// No option, take default one
form.find('[' + options.validateAttribute + '*=validate]').not(":disabled").each(function() {
var field = $(this);
if (options.prettySelect && field.is(":hidden"))
field = form.find("#" + options.usePrefix + field.attr('id') + options.useSuffix);
var prompt = methods._getPrompt(field);
var promptText = $(prompt).find(".formErrorContent").html();
if (prompt)
methods._updatePrompt(field, $(prompt), promptText, undefined, false, options, noAnimation);
});
return this;
},
/**
* Displays a prompt on a element.
* Note that the element needs an id!
*
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight
*/
showPrompt: function(promptText, type, promptPosition, showArrow) {
var form = this.closest('form');
var options = form.data('jqv');
// No option, take default one
if (!options)
options = methods._saveOptions(this, options);
if (promptPosition)
options.promptPosition = promptPosition;
options.showArrow = showArrow == true;
methods._showPrompt(this, promptText, type, false, options);
return this;
},
/**
* Closes form error prompts, CAN be invidual
*/
hide: function() {
var form = $(this).closest('form');
var options = form.data('jqv');
var fadeDuration = (options && options.fadeDuration) ? options.fadeDuration : 0.3;
var closingtag;
if ($(this).is("form")) {
closingtag = "parentForm" + methods._getClassName($(this).attr("id"));
} else {
closingtag = methods._getClassName($(this).attr("id")) + "formError";
}
$('.' + closingtag).fadeTo(fadeDuration, 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Closes all error prompts on the page
*/
hideAll: function() {
var form = this;
var options = form.data('jqv');
var duration = options ? options.fadeDuration : 0.3;
$('.formError').fadeTo(duration, 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Typically called when user exists a field using tab or a mouse click, triggers a field
* validation
*/
_onFieldEvent: function(event) {
var field = $(this);
var form = field.closest('form');
var options = form.data('jqv');
options.eventTrigger = "field";
// validate the current field
window.setTimeout(function() {
methods._validateField(field, options);
if (options.InvalidFields.length == 0 && options.onFieldSuccess) {
options.onFieldSuccess();
} else if (options.InvalidFields.length > 0 && options.onFieldFailure) {
options.onFieldFailure();
}
}, (event.data) ? event.data.delay : 0);
},
/**
* Called when the form is submited, shows prompts accordingly
*
* @param {jqObject}
* form
* @return false if form submission needs to be cancelled
*/
_onSubmitEvent: function() {
var form = $(this);
var options = form.data('jqv');
options.eventTrigger = "submit";
// validate each field
// (- skip field ajax validation, not necessary IF we will perform an ajax form validation)
var r = methods._validateFields(form);
if (r && options.ajaxFormValidation) {
methods._validateFormWithAjax(form, options);
// cancel form auto-submission - process with async call onAjaxFormComplete
return false;
}
if (options.onValidationComplete) {
// !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing
return !!options.onValidationComplete(form, r);
}
return r;
},
/**
* Return true if the ajax field validations passed so far
* @param {Object} options
* @return true, is all ajax validation passed so far (remember ajax is async)
*/
_checkAjaxStatus: function(options) {
var status = true;
$.each(options.ajaxValidCache, function(key, value) {
if (!value) {
status = false;
// break the each
return false;
}
});
return status;
},
/**
* Return true if the ajax field is validated
* @param {String} fieldid
* @param {Object} options
* @return true, if validation passed, false if false or doesn't exist
*/
_checkAjaxFieldStatus: function(fieldid, options) {
return options.ajaxValidCache[fieldid] == true;
},
/**
* Validates form fields, shows prompts accordingly
*
* @param {jqObject}
* form
* @param {skipAjaxFieldValidation}
* boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked
*
* @return true if form is valid, false if not, undefined if ajax form validation is done
*/
_validateFields: function(form) {
var options = form.data('jqv');
// this variable is set to true if an error is found
var errorFound = false;
// Trigger hook, start validation
form.trigger("jqv.form.validating");
// first, evaluate status of non ajax fields
var first_err = null;
form.find('[' + options.validateAttribute + '*=validate]').not(":disabled").each(function() {
var field = $(this);
var names = [];
if ($.inArray(field.attr('name'), names) < 0) {
errorFound |= methods._validateField(field, options);
if (errorFound && first_err == null)
if (field.is(":hidden") && options.prettySelect)
first_err = field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
else
first_err = field;
if (options.doNotShowAllErrosOnSubmit)
return false;
names.push(field.attr('name'));
//if option set, stop checking validation rules after one error is found
if (options.showOneMessage == true && errorFound) {
return false;
}
}
});
// second, check to see if all ajax calls completed ok
// errorFound |= !methods._checkAjaxStatus(options);
// third, check status and scroll the container accordingly
form.trigger("jqv.form.result", [errorFound]);
if (errorFound) {
if (options.scroll) {
var destination = first_err.offset().top;
var fixleft = first_err.offset().left;
//prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
var positionType = options.promptPosition;
if (typeof (positionType) == 'string' && positionType.indexOf(":") != -1)
positionType = positionType.substring(0, positionType.indexOf(":"));
if (positionType != "bottomRight" && positionType != "bottomLeft") {
var prompt_err = methods._getPrompt(first_err);
if (prompt_err) {
destination = prompt_err.offset().top;
}
}
// get the position of the first error, there should be at least one, no need to check this
//var destination = form.find(".formError:not('.greenPopup'):first").offset().top;
if (options.isOverflown) {
var overflowDIV = $(options.overflownDIV);
if (!overflowDIV.length) return false;
var scrollContainerScroll = overflowDIV.scrollTop();
var scrollContainerPos = -parseInt(overflowDIV.offset().top);
destination += scrollContainerScroll + scrollContainerPos - 5;
var scrollContainer = $(options.overflownDIV + ":not(:animated)");
scrollContainer.animate({ scrollTop: destination }, 1100, function() {
if (options.focusFirstField) first_err.focus();
});
} else {
$("body,html").stop().animate({
scrollTop: destination,
scrollLeft: fixleft
}, 1100, function() {
if (options.focusFirstField) first_err.focus();
});
}
} else if (options.focusFirstField)
first_err.focus();
return false;
}
return true;
},
/**
* This method is called to perform an ajax form validation.
* During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true
*
* @param {jqObject} form
* @param {Map} options
*/
_validateFormWithAjax: function(form, options) {
var data = form.serialize();
var type = (options.ajaxmethod) ? options.ajaxmethod : "GET";
var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action");
var dataType = (options.dataType) ? options.dataType : "json";
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm = false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg) {
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm |= true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
},
/**
* Validates field, shows prompts accordingly
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @param {Map}
* user options
* @return false if field is valid (It is inversed for *fields*, it return false on validate and true on errors.)
*/
_validateField: function(field, options, skipAjaxValidation) {
if (!field.attr("id")) {
field.attr("id", "form-validation-field-" + $.validationEngine.fieldIdCounter);
++$.validationEngine.fieldIdCounter;
}
if (field.is(":hidden") && !options.prettySelect || field.parent().is(":hidden"))
return false;
var rulesParsing = field.attr(options.validateAttribute);
var getRules = /validate\[(.*)\]/.exec(rulesParsing);
if (!getRules)
return false;
var str = getRules[1];
var rules = str.split(/\[|,|\]/);
// true if we ran the ajax validation, tells the logic to stop messing with prompts
var isAjaxValidator = false;
var fieldName = field.attr("name");
var promptText = "";
var promptType = "";
var required = false;
var limitErrors = false;
options.isError = false;
options.showArrow = true;
// If the programmer wants to limit the amount of error messages per field,
if (options.maxErrorsPerField > 0) {
limitErrors = true;
}
var form = $(field.closest("form"));
// Fix for adding spaces in the rules
for (var i in rules) {
rules[i] = rules[i].replace(" ", "");
// Remove any parsing errors
if (rules[i] === '') {
delete rules[i];
}
}
for (var i = 0, field_errors = 0; i < rules.length; i++) {
// If we are limiting errors, and have hit the max, break
if (limitErrors && field_errors >= options.maxErrorsPerField) {
// If we haven't hit a required yet, check to see if there is one in the validation rules for this
// field and that it's index is greater or equal to our current index
if (!required) {
var have_required = $.inArray('required', rules);
required = (have_required != -1 && have_required >= i);
}
break;
}
var errorMsg = undefined;
switch (rules[i]) {
case "required":
required = true;
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._required);
break;
case "custom":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom);
break;
case "groupRequired":
// Check is its the first of group, if not, reload validation with first field
// AND continue normal validation on present field
var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]";
var firstOfGroup = form.find(classGroup).eq(0);
if (firstOfGroup[0] != field[0]) {
methods._validateField(firstOfGroup, options, skipAjaxValidation);
options.showArrow = true;
continue;
}
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._groupRequired);
if (errorMsg) required = true;
options.showArrow = false;
break;
case "ajax":
// AJAX defaults to returning it's loading message
errorMsg = methods._ajax(field, rules, i, options);
if (errorMsg) {
promptType = "load";
}
break;
case "minSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minSize);
break;
case "maxSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxSize);
break;
case "min":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._min);
break;
case "max":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._max);
break;
case "past":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._past);
break;
case "future":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._future);
break;
case "dateRange":
var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._dateRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "dateTimeRange":
var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._dateTimeRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "maxCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxCheckbox);
break;
case "minCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minCheckbox);
break;
case "equals":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._equals);
break;
case "funcCall":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCall);
break;
case "creditCard":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._creditCard);
break;
case "condRequired":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._condRequired);
if (errorMsg !== undefined) {
required = true;
}
break;
default:
}
var end_validation = false;
// If we were passed back an message object, check what the status was to determine what to do
if (typeof errorMsg == "object") {
switch (errorMsg.status) {
case "_break":
end_validation = true;
break;
// If we have an error message, set errorMsg to the error message
case "_error":
errorMsg = errorMsg.message;
break;
// If we want to throw an error, but not show a prompt, return early with true
case "_error_no_prompt":
return true;
break;
// Anything else we continue on
default:
break;
}
}
// If it has been specified that validation should end now, break
if (end_validation) {
break;
}
// If we have a string, that means that we have an error, so add it to the error message.
if (typeof errorMsg == 'string') {
promptText += errorMsg + "<br/>";
options.isError = true;
field_errors++;
}
}
// If the rules required is not added, an empty field is not validated
if (!required && field.val().length < 1) options.isError = false;
// Hack for radio/checkbox group button, the validation go into the
// first radio/checkbox of the group
var fieldType = field.prop("type");
if ((fieldType == "radio" || fieldType == "checkbox") && form.find("input[name='" + fieldName + "']").size() > 1) {
field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first"));
options.showArrow = false;
}
if (field.is(":hidden") && options.prettySelect) {
field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
}
if (options.isError) {
methods._showPrompt(field, promptText, promptType, false, options);
} else {
if (!isAjaxValidator) methods._closePrompt(field);
}
if (!isAjaxValidator) {
field.trigger("jqv.field.result", [field, options.isError, promptText]);
}
/* Record error */
var errindex = $.inArray(field[0], options.InvalidFields);
if (errindex == -1) {
if (options.isError)
options.InvalidFields.push(field[0]);
} else if (!options.isError) {
options.InvalidFields.splice(errindex, 1);
}
methods._handleStatusCssClasses(field, options);
return options.isError;
},
/**
* Handling css classes of fields indicating result of validation
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @private
*/
_handleStatusCssClasses: function(field, options) {
/* remove all classes */
if (options.addSuccessCssClassToField)
field.removeClass(options.addSuccessCssClassToField);
if (options.addFailureCssClassToField)
field.removeClass(options.addFailureCssClassToField);
/* Add classes */
if (options.addSuccessCssClassToField && !options.isError)
field.addClass(options.addSuccessCssClassToField);
if (options.addFailureCssClassToField && options.isError)
field.addClass(options.addFailureCssClassToField);
},
/********************
* _getErrorMessage
*
* @param form
* @param field
* @param rule
* @param rules
* @param i
* @param options
* @param originalValidationMethod
* @return {*}
* @private
*/
_getErrorMessage: function(form, field, rule, rules, i, options, originalValidationMethod) {
// If we are using the custon validation type, build the index for the rule.
// Otherwise if we are doing a function call, make the call and return the object
// that is passed back.
var beforeChangeRule = rule;
if (rule == "custom") {
var custom_validation_type_index = jQuery.inArray(rule, rules) + 1;
var custom_validation_type = rules[custom_validation_type_index];
rule = "custom[" + custom_validation_type + "]";
}
var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class");
var element_classes_array = element_classes.split(" ");
// Call the original validation method. If we are dealing with dates or checkboxes, also pass the form
var errorMsg;
if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") {
errorMsg = originalValidationMethod(form, field, rules, i, options);
} else {
errorMsg = originalValidationMethod(field, rules, i, options);
}
// If the original validation method returned an error and we have a custom error message,
// return the custom message instead. Otherwise return the original error message.
if (errorMsg != undefined) {
var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, beforeChangeRule, options);
if (custom_message) errorMsg = custom_message;
}
return errorMsg;
},
_getCustomErrorMessage: function(field, classes, rule, options) {
var custom_message = false;
var validityProp = methods._validityProp[rule];
// If there is a validityProp for this rule, check to see if the field has an attribute for it
if (validityProp != undefined) {
custom_message = field.attr("data-errormessage-" + validityProp);
// If there was an error message for it, return the message
if (custom_message != undefined)
return custom_message;
}
custom_message = field.attr("data-errormessage");
// If there is an inline custom error message, return it
if (custom_message != undefined)
return custom_message;
var id = '#' + field.attr("id");
// If we have custom messages for the element's id, get the message for the rule from the id.
// Otherwise, if we have custom messages for the element's classes, use the first class message we find instead.
if (typeof options.custom_error_messages[id] != "undefined" &&
typeof options.custom_error_messages[id][rule] != "undefined") {
custom_message = options.custom_error_messages[id][rule]['message'];
} else if (classes.length > 0) {
for (var i = 0; i < classes.length && classes.length > 0; i++) {
var element_class = "." + classes[i];
if (typeof options.custom_error_messages[element_class] != "undefined" &&
typeof options.custom_error_messages[element_class][rule] != "undefined") {
custom_message = options.custom_error_messages[element_class][rule]['message'];
break;
}
}
}
if (!custom_message &&
typeof options.custom_error_messages[rule] != "undefined" &&
typeof options.custom_error_messages[rule]['message'] != "undefined") {
custom_message = options.custom_error_messages[rule]['message'];
}
return custom_message;
},
_validityProp: {
"required": "value-missing",
"custom": "custom-error",
"groupRequired": "value-missing",
"ajax": "custom-error",
"minSize": "range-underflow",
"maxSize": "range-overflow",
"min": "range-underflow",
"max": "range-overflow",
"past": "type-mismatch",
"future": "type-mismatch",
"dateRange": "type-mismatch",
"dateTimeRange": "type-mismatch",
"maxCheckbox": "range-overflow",
"minCheckbox": "range-underflow",
"equals": "pattern-mismatch",
"funcCall": "custom-error",
"creditCard": "pattern-mismatch",
"condRequired": "value-missing"
},
/**
* Required validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_required: function(field, rules, i, options) {
switch (field.prop("type")) {
case "text":
case "password":
case "textarea":
case "file":
case "select-one":
case "select-multiple":
default:
if (!$.trim(field.val()) || field.val() == field.attr("data-validation-placeholder") || field.val() == field.attr("placeholder"))
return options.allrules[rules[i]].alertText;
break;
case "radio":
case "checkbox":
var form = field.closest("form");
var name = field.attr("name");
if (form.find("input[name='" + name + "']:checked").size() == 0) {
if (form.find("input[name='" + name + "']:visible").size() == 1)
return options.allrules[rules[i]].alertTextCheckboxe;
else
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
}
},
/**
* Validate that 1 from the group field is required
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_groupRequired: function(field, rules, i, options) {
var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]";
var isValid = false;
// Check all fields from the group
field.closest("form").find(classGroup).each(function() {
if (!methods._required($(this), rules, i, options)) {
isValid = true;
return false;
}
});
if (!isValid) {
return options.allrules[rules[i]].alertText;
}
},
/**
* Validate rules
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_custom: function(field, rules, i, options) {
var customRule = rules[i + 1];
var rule = options.allrules[customRule];
var fn;
if (!rule) {
alert("jqv:custom rule not found - " + customRule);
return;
}
if (rule["regex"]) {
var ex = rule.regex;
if (!ex) {
alert("jqv:custom regex not found - " + customRule);
return;
}
var pattern = new RegExp(ex);
if (!pattern.test(field.val())) return options.allrules[customRule].alertText;
} else if (rule["func"]) {
fn = rule["func"];
if (typeof (fn) !== "function") {
alert("jqv:custom parameter 'function' is no function - " + customRule);
return;
}
if (!fn(field, rules, i, options))
return options.allrules[customRule].alertText;
} else {
alert("jqv:custom type not allowed " + customRule);
return;
}
},
/**
* Validate custom function outside of the engine scope
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_funcCall: function(field, rules, i, options) {
var functionName = rules[i + 1];
var fn;
if (functionName.indexOf('.') > -1) {
var namespaces = functionName.split('.');
var scope = window;
while (namespaces.length) {
scope = scope[namespaces.shift()];
}
fn = scope;
}
else
fn = window[functionName] || options.customFunctions[functionName];
if (typeof (fn) == 'function')
return fn(field, rules, i, options);
},
/**
* Field match
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_equals: function(field, rules, i, options) {
var equalsField = rules[i + 1];
if (field.val() != $("#" + equalsField).val())
return options.allrules.equals.alertText;
},
/**
* Check the maximum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxSize: function(field, rules, i, options) {
var max = rules[i + 1];
var len = field.val().length;
if (len > max) {
var rule = options.allrules.maxSize;
return rule.alertText + max + rule.alertText2;
}
},
/**
* Check the minimum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minSize: function(field, rules, i, options) {
var min = rules[i + 1];
var len = field.val().length;
if (len < min) {
var rule = options.allrules.minSize;
return rule.alertText + min + rule.alertText2;
}
},
/**
* Check number minimum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_min: function(field, rules, i, options) {
var min = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len < min) {
var rule = options.allrules.min;
if (rule.alertText2) return rule.alertText + min + rule.alertText2;
return rule.alertText + min;
}
},
/**
* Check number maximum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_max: function(field, rules, i, options) {
var max = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len > max) {
var rule = options.allrules.max;
if (rule.alertText2) return rule.alertText + max + rule.alertText2;
//orefalo: to review, also do the translations
return rule.alertText + max;
}
},
/**
* Checks date is in the past
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_past: function(form, field, rules, i, options) {
var p = rules[i + 1];
var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']"));
var pdate;
if (p.toLowerCase() == "now") {
pdate = new Date();
} else if (undefined != fieldAlt.val()) {
if (fieldAlt.is(":disabled"))
return;
pdate = methods._parseDate(fieldAlt.val());
} else {
pdate = methods._parseDate(p);
}
var vdate = methods._parseDate(field.val());
if (vdate > pdate) {
var rule = options.allrules.past;
if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks date is in the future
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_future: function(form, field, rules, i, options) {
var p = rules[i + 1];
var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']"));
var pdate;
if (p.toLowerCase() == "now") {
pdate = new Date();
} else if (undefined != fieldAlt.val()) {
if (fieldAlt.is(":disabled"))
return;
pdate = methods._parseDate(fieldAlt.val());
} else {
pdate = methods._parseDate(p);
}
var vdate = methods._parseDate(field.val());
if (vdate < pdate) {
var rule = options.allrules.future;
if (rule.alertText2)
return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks if valid date
*
* @param {string} date string
* @return a bool based on determination of valid date
*/
_isDate: function(value) {
var dateRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/);
return dateRegEx.test(value);
},
/**
* Checks if valid date time
*
* @param {string} date string
* @return a bool based on determination of valid date time
*/
_isDateTime: function(value) {
var dateTimeRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/);
return dateTimeRegEx.test(value);
},
//Checks if the start date is before the end date
//returns true if end is later than start
_dateCompare: function(start, end) {
return (new Date(start.toString()) < new Date(end.toString()));
},
/**
* Checks date range
*
* @param {jqObject} first field name
* @param {jqObject} second field name
* @return an error string if validation failed
*/
_dateRange: function(field, rules, i, options) {
//are not both populated
if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDate(options.firstOfGroup[0].value) || !methods._isDate(options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
},
/**
* Checks date time range
*
* @param {jqObject} first field name
* @param {jqObject} second field name
* @return an error string if validation failed
*/
_dateTimeRange: function(field, rules, i, options) {
//are not both populated
if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDateTime(options.firstOfGroup[0].value) || !methods._isDateTime(options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
},
/**
* Max number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxCheckbox: function(form, field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = form.find("input[name='" + groupname + "']:checked").size();
if (groupSize > nbCheck) {
options.showArrow = false;
if (options.allrules.maxCheckbox.alertText2)
return options.allrules.maxCheckbox.alertText + " " + nbCheck + " " + options.allrules.maxCheckbox.alertText2;
return options.allrules.maxCheckbox.alertText;
}
},
/**
* Min number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minCheckbox: function(form, field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = form.find("input[name='" + groupname + "']:checked").size();
if (groupSize < nbCheck) {
options.showArrow = false;
return options.allrules.minCheckbox.alertText + " " + nbCheck + " " + options.allrules.minCheckbox.alertText2;
}
},
/**
* Checks that it is a valid credit card number according to the
* Luhn checksum algorithm.
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_creditCard: function(field, rules, i, options) {
//spaces and dashes may be valid characters, but must be stripped to calculate the checksum.
var valid = false, cardNumber = field.val().replace(/ +/g, '').replace(/-+/g, '');
var numDigits = cardNumber.length;
if (numDigits >= 14 && numDigits <= 16 && parseInt(cardNumber) > 0) {
var sum = 0, i = numDigits - 1, pos = 1, digit, luhn = new String();
do {
digit = parseInt(cardNumber.charAt(i));
luhn += (pos++ % 2 == 0) ? digit * 2 : digit;
} while (--i >= 0)
for (i = 0; i < luhn.length; i++) {
sum += parseInt(luhn.charAt(i));
}
valid = sum % 10 == 0;
}
if (!valid) return options.allrules.creditCard.alertText;
},
/**
* Ajax field validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return nothing! the ajax validator handles the prompts itself
*/
_ajax: function(field, rules, i, options) {
var errorSelector = rules[i + 1];
var rule = options.allrules[errorSelector];
var extraData = rule.extraData;
var extraDataDynamic = rule.extraDataDynamic;
var data = {
"fieldId": field.attr("id"),
"fieldValue": field.val()
};
if (typeof extraData === "object") {
$.extend(data, extraData);
} else if (typeof extraData === "string") {
var tempData = extraData.split("&");
for (var i = 0; i < tempData.length; i++) {
var values = tempData[i].split("=");
if (values[0] && values[0]) {
data[values[0]] = values[1];
}
}
}
if (extraDataDynamic) {
var tmpData = [];
var domIds = String(extraDataDynamic).split(",");
for (var i = 0; i < domIds.length; i++) {
var id = domIds[i];
if ($(id).length) {
var inputValue = field.closest("form").find(id).val();
var keyValue = id.replace('#', '') + '=' + escape(inputValue);
data[id.replace('#', '')] = inputValue;
}
}
}
// If a field change event triggered this we want to clear the cache for this ID
if (options.eventTrigger == "field") {
delete (options.ajaxValidCache[field.attr("id")]);
}
// If there is an error or if the the field is already validated, do not re-execute AJAX
if (!options.isError && !methods._checkAjaxFieldStatus(field.attr("id"), options)) {
$.ajax({
type: options.ajaxFormValidationMethod,
url: rule.url,
cache: false,
dataType: "json",
data: data,
field: field,
rule: rule,
methods: methods,
options: options,
beforeSend: function() { },
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
// asynchronously called on success, data is the json answer from the server
var errorFieldId = json[0];
//var errorField = $($("#" + errorFieldId)[0]);
var errorField = $("#" + errorFieldId + "']").eq(0);
// make sure we found the element
if (errorField.length == 1) {
var status = json[1];
// read the optional msg from the server
var msg = json[2];
if (!status) {
// Houston we got a problem - display an red prompt
options.ajaxValidCache[errorFieldId] = false;
options.isError = true;
// resolve the msg prompt
if (msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt) {
msg = txt;
}
}
}
else
msg = rule.alertText;
methods._showPrompt(errorField, msg, "", true, options);
} else {
options.ajaxValidCache[errorFieldId] = true;
// resolves the msg prompt
if (msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt) {
msg = txt;
}
}
}
else
msg = rule.alertTextOk;
// see if we should display a green prompt
if (msg)
methods._showPrompt(errorField, msg, "pass", true, options);
else
methods._closePrompt(errorField);
// If a submit form triggered this, we want to re-submit the form
if (options.eventTrigger == "submit")
field.closest("form").submit();
}
}
errorField.trigger("jqv.field.result", [errorField, options.isError, msg]);
}
});
return rule.alertTextLoad;
}
},
/**
* Common method to handle ajax errors
*
* @param {Object} data
* @param {Object} transport
*/
_ajaxError: function(data, transport) {
if (data.status == 0 && transport == null)
alert("The page is not served from a server! ajax call failed");
else if (typeof console != "undefined")
console.log("Ajax error: " + data.status + " " + transport);
},
/**
* date -> string
*
* @param {Object} date
*/
_dateToString: function(date) {
return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
},
/**
* Parses an ISO date
* @param {String} d
*/
_parseDate: function(d) {
var dateParts = d.split("-");
if (dateParts == d)
dateParts = d.split("/");
return new Date(dateParts[0], (dateParts[1] - 1), dateParts[2]);
},
/**
* Builds or updates a prompt with the given information
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) {
var prompt = methods._getPrompt(field);
// The ajax submit errors are not see has an error in the form,
// When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time
// Because no error was found befor submitting
if (ajaxform) prompt = false;
if (prompt)
methods._updatePrompt(field, prompt, promptText, type, ajaxed, options);
else
methods._buildPrompt(field, promptText, type, ajaxed, options);
},
/**
* Builds and shades a prompt for the given field.
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_buildPrompt: function(field, promptText, type, ajaxed, options) {
// create the prompt
var prompt = $('<div>');
prompt.addClass(methods._getClassName(field.attr("id")) + "formError");
// add a class name to identify the parent form of the prompt
prompt.addClass("parentForm" + methods._getClassName(field.parents('form').attr("id")));
prompt.addClass("formError");
switch (type) {
case "pass":
prompt.addClass("greenPopup");
break;
case "load":
prompt.addClass("blackPopup");
break;
default:
/* it has error */
//alert("unknown popup type:"+type);
}
if (ajaxed)
prompt.addClass("ajaxed");
// create the prompt content
var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt);
// create the css arrow pointing at the field
// note that there is no triangle on max-checkbox and radio
if (options.showArrow) {
var arrow = $('<div>').addClass("formErrorArrow");
//prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
var positionType = field.data("promptPosition") || options.promptPosition;
if (typeof (positionType) == 'string') {
var pos = positionType.indexOf(":");
if (pos != -1)
positionType = positionType.substring(0, pos);
}
switch (positionType) {
case "bottomLeft":
case "bottomRight":
prompt.find(".formErrorContent").before(arrow);
arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
break;
case "topLeft":
case "topRight":
arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
prompt.append(arrow);
break;
}
}
// Modify z-indexes for jquery ui
if (field.closest('.ui-dialog').length)
prompt.addClass('formErrorInsideDialog');
prompt.css({
"opacity": 0,
'position': 'absolute'
});
field.before(prompt);
var pos = methods._calculatePosition(field, prompt, options);
prompt.css({
"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize,
"opacity": 0
}).data("callerField", field);
if (options.autoHidePrompt) {
setTimeout(function() {
prompt.animate({
"opacity": 0
}, function() {
prompt.closest('.formErrorOuter').remove();
prompt.remove();
});
}, options.autoHideDelay);
}
return prompt.animate({
"opacity": 0.87
});
},
/**
* Updates the prompt text field - the field for which the prompt
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_updatePrompt: function(field, prompt, promptText, type, ajaxed, options, noAnimation) {
if (prompt) {
if (typeof type !== "undefined") {
if (type == "pass")
prompt.addClass("greenPopup");
else
prompt.removeClass("greenPopup");
if (type == "load")
prompt.addClass("blackPopup");
else
prompt.removeClass("blackPopup");
}
if (ajaxed)
prompt.addClass("ajaxed");
else
prompt.removeClass("ajaxed");
prompt.find(".formErrorContent").html(promptText);
var pos = methods._calculatePosition(field, prompt, options);
var css = { "top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize
};
if (noAnimation)
prompt.css(css);
else
prompt.animate(css);
}
},
/**
* Closes the prompt associated with the given field
*
* @param {jqObject}
* field
*/
_closePrompt: function(field) {
var prompt = methods._getPrompt(field);
if (prompt)
prompt.fadeTo("fast", 0, function() {
prompt.parent('.formErrorOuter').remove();
prompt.remove();
});
},
closePrompt: function(field) {
return methods._closePrompt(field);
},
/**
* Returns the error prompt matching the field if any
*
* @param {jqObject}
* field
* @return undefined or the error prompt (jqObject)
*/
_getPrompt: function(field) {
var formId = $(field).closest('form').attr('id');
var className = methods._getClassName(field.attr("id")) + "formError";
var match = $("." + methods._escapeExpression(className) + '.parentForm' + formId)[0];
if (match)
return $(match);
},
/**
* Returns the escapade classname
*
* @param {selector}
* className
*/
_escapeExpression: function(selector) {
return selector.replace(/([#;&,\.\+\*\~':"\!\^$\[\]\(\)=>\|])/g, "\\$1");
},
/**
* returns true if we are in a RTLed document
*
* @param {jqObject} field
*/
isRTL: function(field) {
var $document = $(document);
var $body = $('body');
var rtl =
(field && field.hasClass('rtl')) ||
(field && (field.attr('dir') || '').toLowerCase() === 'rtl') ||
$document.hasClass('rtl') ||
($document.attr('dir') || '').toLowerCase() === 'rtl' ||
$body.hasClass('rtl') ||
($body.attr('dir') || '').toLowerCase() === 'rtl';
return Boolean(rtl);
},
/**
* Calculates prompt position
*
* @param {jqObject}
* field
* @param {jqObject}
* the prompt
* @param {Map}
* options
* @return positions
*/
_calculatePosition: function(field, promptElmt, options) {
var promptTopPosition, promptleftPosition, marginTopSize;
var fieldWidth = field.width();
var fieldLeft = field.position().left;
var fieldTop = field.position().top;
var fieldHeight = field.height();
var promptHeight = promptElmt.height();
// is the form contained in an overflown container?
promptTopPosition = promptleftPosition = 0;
// compensation for the arrow
marginTopSize = -promptHeight;
//prompt positioning adjustment support
//now you can adjust prompt position
//usage: positionType:Xshift,Yshift
//for example:
// bottomLeft:+20 means bottomLeft position shifted by 20 pixels right horizontally
// topRight:20, -15 means topRight position shifted by 20 pixels to right and 15 pixels to top
//You can use +pixels, - pixels. If no sign is provided than + is default.
var positionType = field.data("promptPosition") || options.promptPosition;
var shift1 = "";
var shift2 = "";
var shiftX = 0;
var shiftY = 0;
if (typeof (positionType) == 'string') {
//do we have any position adjustments ?
if (positionType.indexOf(":") != -1) {
shift1 = positionType.substring(positionType.indexOf(":") + 1);
positionType = positionType.substring(0, positionType.indexOf(":"));
//if any advanced positioning will be needed (percents or something else) - parser should be added here
//for now we use simple parseInt()
//do we have second parameter?
if (shift1.indexOf(",") != -1) {
shift2 = shift1.substring(shift1.indexOf(",") + 1);
shift1 = shift1.substring(0, shift1.indexOf(","));
shiftY = parseInt(shift2);
if (isNaN(shiftY)) shiftY = 0;
};
shiftX = parseInt(shift1);
if (isNaN(shift1)) shift1 = 0;
};
};
switch (positionType) {
default:
case "topRight":
promptleftPosition += fieldLeft + fieldWidth - 30;
promptTopPosition += fieldTop;
break;
case "topLeft":
promptTopPosition += fieldTop;
promptleftPosition += fieldLeft;
break;
case "centerRight":
promptTopPosition = fieldTop + 4;
marginTopSize = 0;
promptleftPosition = fieldLeft + field.outerWidth(true) + 5;
break;
case "centerLeft":
promptleftPosition = fieldLeft - (promptElmt.width() + 2);
promptTopPosition = fieldTop + 4;
marginTopSize = 0;
break;
case "bottomLeft":
promptTopPosition = fieldTop + field.height() + 5;
marginTopSize = 0;
promptleftPosition = fieldLeft;
break;
case "bottomRight":
promptleftPosition = fieldLeft + fieldWidth - 30;
promptTopPosition = fieldTop + field.height() + 5;
marginTopSize = 0;
};
//apply adjusments if any
promptleftPosition += shiftX;
promptTopPosition += shiftY;
return {
"callerTopPosition": promptTopPosition + "px",
"callerleftPosition": promptleftPosition + "px",
"marginTopSize": marginTopSize + "px"
};
},
/**
* Saves the user options and variables in the form.data
*
* @param {jqObject}
* form - the form where the user option should be saved
* @param {Map}
* options - the user options
* @return the user options (extended from the defaults)
*/
_saveOptions: function(form, options) {
// is there a language localisation ?
if ($.validationEngineLanguage)
var allRules = $.validationEngineLanguage.allRules;
else
$.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page");
// --- Internals DO NOT TOUCH or OVERLOAD ---
// validation rules and i18
$.validationEngine.defaults.allrules = allRules;
var userOptions = $.extend(true, {}, $.validationEngine.defaults, options);
form.data('jqv', userOptions);
return userOptions;
},
/**
* Removes forbidden characters from class name
* @param {String} className
*/
_getClassName: function(className) {
if (className)
return className.replace(/:/g, "_").replace(/\./g, "_");
},
/**
* Escape special character for jQuery selector
* http://totaldev.com/content/escaping-characters-get-valid-jquery-id
* @param {String} selector
*/
_jqSelector: function(str) {
return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
},
/**
* Conditionally required field
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_condRequired: function(field, rules, i, options) {
var idx, dependingField;
for (idx = (i + 1); idx < rules.length; idx++) {
dependingField = jQuery("#" + rules[idx]).first();
/* Use _required for determining wether dependingField has a value.
* There is logic there for handling all field types, and default value; so we won't replicate that here
*/
if (dependingField.length && methods._required(dependingField, ["required"], 0, options) == undefined) {
/* We now know any of the depending fields has a value,
* so we can validate this field as per normal required code
*/
return methods._required(field, ["required"], 0, options);
}
}
}
};
/**
* Plugin entry point.
* You may pass an action as a parameter or a list of options.
* if none, the init and attach methods are being called.
* Remember: if you pass options, the attached method is NOT called automatically
*
* @param {String}
* method (optional) action
*/
$.fn.validationEngine = function(method) {
var form = $(this);
if (!form[0]) return form; // stop here if the form does not exist
if (typeof (method) == 'string' && method.charAt(0) != '_' && methods[method]) {
// make sure init is called once
if (method != "showPrompt" && method != "hide" && method != "hideAll")
methods.init.apply(form);
return methods[method].apply(form, Array.prototype.slice.call(arguments, 1));
} else if (typeof method == 'object' || !method) {
// default constructor with or without arguments
methods.init.apply(form, arguments);
return methods.attach.apply(form);
} else {
$.error('Method ' + method + ' does not exist in jQuery.validationEngine');
}
};
// LEAK GLOBAL OPTIONS
$.validationEngine = { fieldIdCounter: 0, defaults: {
// Name of the event triggering field validation
validationEventTrigger: "blur",
// Automatically scroll viewport to the first error
scroll: true,
// Focus on the first input
focusFirstField: true,
// Opening box position, possible locations are: topLeft,
// topRight, bottomLeft, centerRight, bottomRight
promptPosition: "topRight",
bindMethod: "bind",
// internal, automatically set to true when it parse a _ajax rule
inlineAjax: false,
// if set to true, the form data is sent asynchronously via ajax to the form.action url (get)
ajaxFormValidation: false,
// The url to send the submit ajax validation (default to action)
ajaxFormValidationURL: false,
// HTTP method used for ajax validation
ajaxFormValidationMethod: 'get',
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
onAjaxFormComplete: $.noop,
// called right before the ajax call, may return false to cancel
onBeforeAjaxFormValidation: $.noop,
// Stops form from submitting and execute function assiciated with it
onValidationComplete: false,
// Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages
doNotShowAllErrosOnSubmit: false,
// Object where you store custom messages to override the default error messages
custom_error_messages: {},
// true if you want to vind the input fields
binded: true,
// set to true, when the prompt arrow needs to be displayed
showArrow: true,
// did one of the validation fail ? kept global to stop further ajax validations
isError: false,
// Limit how many displayed errors a field can have
maxErrorsPerField: false,
// Caches field validation status, typically only bad status are created.
// the array is used during ajax form validation to detect issues early and prevent an expensive submit
ajaxValidCache: {},
// Auto update prompt position after window resize
autoPositionUpdate: false,
InvalidFields: [],
onFieldSuccess: false,
onFieldFailure: false,
onFormSuccess: false,
onFormFailure: false,
addSuccessCssClassToField: false,
addFailureCssClassToField: false,
// Auto-hide prompt
autoHidePrompt: false,
// Delay before auto-hide
autoHideDelay: 10000,
// Fade out duration while hiding the validations
fadeDuration: 0.3,
// Use Prettify select library
prettySelect: false,
// Custom ID uses prefix
usePrefix: "",
// Custom ID uses suffix
useSuffix: "",
// Only show one message per error prompt
showOneMessage: false
}
};
$(function() { $.validationEngine.defaults.promptPosition = methods.isRTL() ? 'topLeft' : "topRight" });
})(jQuery);
| JavaScript |
/* Cached from: js/demo.js on Tue, 20 Mar 2012 10:17:20 -0700 */
$(document).ready(function() {
var a = $(".nav"), b = $("#demoframe"), g = $("#jsddm", a), i = $("#contentheader .toolbar"), j = $(".demo-description", a), h = $("#contentheader h2"), c = document.title, k = 0, f = "Choose a demo from above", e = document.location.href.match(/#([\w-]+)$/i);
e = e && e.length ? e[1] : null;
function d() {
var l = $("body", $("iframe:visible", b).contents()).height() + 30;
a.height(Math.max(680, l))
}
$("iframe.demo", a).load(function() {
$("#loading").fadeOut(400);
d()
});
i.delegate(".button:not(.source):not(.fiddle)", "mousedown mouseup mouseleave", function(l) {
l.preventDefault();
$(this).toggleClass("active", l.type === "mousedown")
});
$(".popout", i).click(function() {
var n = 1000, l = 650, p = parseInt((screen.availWidth / 2) - (n / 2)), o = parseInt((screen.availHeight / 2) - (l / 2)), m = "width=" + n + ",height=" + l + ",status,resizable,left=" + p + ",top=" + o + "screenX=" + p + ",screenY=" + o;
window.open($("iframe:visible", a).attr("src"), "qtipdemo", m);
return false
});
$(".source", i).mousedown(function() {
$("iframe", b).toggle();
d();
$(this).toggleClass("active");
return false
}).click(false);
$(".download", i).click(function() {
window.location = $("iframe.demo", a).attr("src") + "?download";
return false
}).click(false);
$(".fiddle", i).attr("target", "_blank");
$(window).bind("resize", function() {
b.width($(this).width() - g.outerWidth() - 1)
}).triggerHandler("resize");
$("li", g).each(function(m, n) {
var l = $(this);
l.toggleClass("odd", !!(l.index() % 2))
}).find("[title]").qtip({
position: {
target: "mouse",
adjust: {
mouse: false,
x: 5,
y: 5
}
},
show: {
delay: 600,
solo: a
},
hide: {
event: "mouseleave click",
distance: 15
},
style: {
tip: false
}
});
g.delegate("li a", "click", function(o) {
var m = $(this), n = m.parent().index(), l = m.attr("href"), q = l.match(/\/([\w-]+)\/?$/i), p = document.location.hash, r = m.attr("rel");
if (!$(this).hasClass("active")) {
$("#loading", a).fadeIn(100, function() {
$("iframe", a).attr("src", function(s, t) {
return l + ($(this).hasClass("source") ? "?source" : "")
});
if ($("iframe.source:visible", a).length) {
$(".source", i).trigger("mousedown")
}
d();
j.html(f = m.attr("title"));
document.title = c + " - " + m.text();
h.html("Demos - " + m.text());
if (q && q[1] === "simple") {
if (p) {
document.location.hash = ""
}
} else {
if (q && q.length) {
document.location.hash = q[1]
}
}
});
$(".fiddle", i).toggle(!!r).attr("href", "http://jsfiddle.net/craga89/" + r);
$("li", g).removeClass("active");
m.parent().addClass("active")
}
o.preventDefault()
});
hashLink = $("li a" + (e ? "[href$=" + e + "]" : ":eq(" + k + ")"), g);
hashLink.trigger("click");
$(".accordion", g).accordion({
active: hashLink.parents("ul").index("ul") - 1
})
});
| JavaScript |
/*
* jQuery selectbox plugin
*
* Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
* Licensed under the GPL license and MIT:
* http://www.opensource.org/licenses/GPL-license.php
* http://www.opensource.org/licenses/mit-license.php
*
* The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
*
* Revision: $Id$
* Version: 0.5
*
* Changelog :
* Version 0.5
* - separate css style for current selected element and hover element which solve the highlight issue
* Version 0.4
* - Fix width when the select is in a hidden div @Pawel Maziarz
* - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
*/
jQuery.fn.extend({
selectbox: function(options) {
return this.each(function() {
new jQuery.SelectBox(this, options);
});
}
});
/* pawel maziarz: work around for ie logging */
if (!window.console) {
var console = {
log: function(msg) {
}
}
}
/* */
jQuery.SelectBox = function(selectobj, options) {
var opt = options || {};
opt.inputClass = opt.inputClass || "selectbox2";
opt.containerClass = opt.containerClass || "selectbox-wrapper2";
opt.hoverClass = opt.hoverClass || "current2";
opt.currentClass = opt.selectedClass || "selected2"
opt.debug = opt.debug || false;
var elm_id = selectobj.id;
var active = -1;
var inFocus = false;
var hasfocus = 0;
//jquery object for select element
var $select = $(selectobj);
// jquery container object
var $container = setupContainer(opt);
//jquery input object
var $input = setupInput(opt);
// hide select and append newly created elements
$select.hide().before($input).before($container);
init();
$input
.click(function(){
if (!inFocus) {
$container.toggle();
}
})
.focus(function(){
if ($container.not(':visible')) {
inFocus = true;
$container.show();
}
})
.keydown(function(event) {
switch(event.keyCode) {
case 38: // up
event.preventDefault();
moveSelect(-1);
break;
case 40: // down
event.preventDefault();
moveSelect(1);
break;
//case 9: // tab
case 13: // return
event.preventDefault(); // seems not working in mac !
$('li.'+opt.hoverClass).trigger('click');
break;
case 27: //escape
hideMe();
break;
}
})
.blur(function() {
if ($container.is(':visible') && hasfocus > 0 ) {
if(opt.debug) console.log('container visible and has focus')
} else {
hideMe();
}
});
function hideMe() {
hasfocus = 0;
$container.hide();
}
function init() {
$container.append(getSelectOptions($input.attr('id'))).hide();
var width = $input.css('width');
$container.width(width);
}
function setupContainer(options) {
var container = document.createElement("div");
$container = $(container);
$container.attr('id', elm_id+'_container');
$container.addClass(options.containerClass);
return $container;
}
function setupInput(options) {
var input = document.createElement("input");
var $input = $(input);
$input.attr("id", elm_id+"_input");
$input.attr("type", "text");
$input.addClass(options.inputClass);
$input.attr("autocomplete", "off");
$input.attr("readonly", "readonly");
$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
return $input;
}
function moveSelect(step) {
var lis = $("li", $container);
if (!lis) return;
active += step;
if (active < 0) {
active = 0;
} else if (active >= lis.size()) {
active = lis.size() - 1;
}
lis.removeClass(opt.hoverClass);
$(lis[active]).addClass(opt.hoverClass);
}
function setCurrent() {
var li = $("li."+opt.currentClass, $container).get(0);
var ar = (''+li.id).split('_');
var el = ar[ar.length-1];
$select.val(el);
$input.val($(li).html());
return true;
}
// select value
function getCurrentSelected() {
return $select.val();
}
// input value
function getCurrentValue() {
return $input.val();
}
function getSelectOptions(parentid) {
var select_options = new Array();
var ul = document.createElement('ul');
$select.children('option').each(function() {
var li = document.createElement('li');
li.setAttribute('id', parentid + '_' + $(this).val());
li.innerHTML = $(this).html();
if ($(this).is(':selected')) {
$input.val($(this).html());
$(li).addClass(opt.currentClass);
}
ul.appendChild(li);
$(li)
.mouseover(function(event) {
hasfocus = 1;
if (opt.debug) console.log('over on : '+this.id);
jQuery(event.target, $container).addClass(opt.hoverClass);
})
.mouseout(function(event) {
hasfocus = -1;
if (opt.debug) console.log('out on : '+this.id);
jQuery(event.target, $container).removeClass(opt.hoverClass);
})
.click(function(event) {
var fl = $('li.'+opt.hoverClass, $container).get(0);
if (opt.debug) console.log('click on :'+this.id);
$('li.'+opt.currentClass).removeClass(opt.currentClass);
$(this).addClass(opt.currentClass);
setCurrent();
hideMe();
});
});
return ul;
}
};
| JavaScript |
/************************************************************************
*************************************************************************
@Name : jNotify - jQuery Plugin
@Revison : 2.1
@Date : 18/01/2011
@Author: ALPIXEL (www.myjqueryplugins.com - www.alpixel.fr)
@Support: FF, IE7, IE8, MAC Firefox, MAC Safari
@License : Open Source - MIT License : http://www.opensource.org/licenses/mit-license.php
**************************************************************************
*************************************************************************/
(function($) {
$.jNotify = {
defaults: {
/** VARS - OPTIONS **/
autoHide: true, // Notify box auto-close after 'TimeShown' ms ?
clickOverlay: false, // if 'clickOverlay' = false, close the notice box on the overlay click ?
MinWidth: 200, // min-width CSS property
TimeShown: 1500, // Box shown during 'TimeShown' ms
ShowTimeEffect: 200, // duration of the Show Effect
HideTimeEffect: 200, // duration of the Hide effect
LongTrip: 15, // in pixel, length of the move effect when show and hide
HorizontalPosition: 'center', // left, center, right
VerticalPosition: 'top', // top, center, bottom
ShowOverlay: true, // show overlay behind the notice ?
ColorOverlay: '#000', // color of the overlay
OpacityOverlay: 0.3, // opacity of the overlay
/** METHODS - OPTIONS **/
onClosed: null,
onCompleted: null
},
/*****************/
/** Init Method **/
/*****************/
init: function(msg, options, id) {
opts = $.extend({}, $.jNotify.defaults, options);
/** Box **/
if ($("#" + id).length == 0)
$Div = $.jNotify._construct(id, msg);
// Width of the Brower
WidthDoc = parseInt($(window).width());
HeightDoc = parseInt($(window).height());
// Scroll Position
ScrollTop = parseInt($(window).scrollTop());
ScrollLeft = parseInt($(window).scrollLeft());
// Position of the jNotify Box
posTop = $.jNotify.vPos(opts.VerticalPosition);
posLeft = $.jNotify.hPos(opts.HorizontalPosition);
// Show the jNotify Box
if (opts.ShowOverlay && $("#jOverlay").length == 0)
$.jNotify._showOverlay($Div);
$.jNotify._show(msg);
},
/*******************/
/** Construct DOM **/
/*******************/
_construct: function(id, msg) {
$Div =
$('<div id="' + id + '"/>')
.css({ opacity: 0, minWidth: opts.MinWidth })
.html(msg)
.appendTo('body');
return $Div;
},
/**********************/
/** Postions Methods **/
/**********************/
vPos: function(pos) {
switch (pos) {
case 'top':
var vPos = ScrollTop + parseInt($Div.outerHeight(true) / 2);
break;
case 'center':
var vPos = ScrollTop + (HeightDoc / 2) - (parseInt($Div.outerHeight(true)) / 2);
break;
case 'bottom':
var vPos = ScrollTop + HeightDoc - parseInt($Div.outerHeight(true));
break;
}
return vPos;
},
hPos: function(pos) {
switch (pos) {
case 'left':
var hPos = ScrollLeft;
break;
case 'center':
var hPos = ScrollLeft + (WidthDoc / 2) - (parseInt($Div.outerWidth(true)) / 2);
break;
case 'right':
var hPos = ScrollLeft + WidthDoc - parseInt($Div.outerWidth(true));
break;
}
return hPos;
},
/*********************/
/** Show Div Method **/
/*********************/
_show: function(msg) {
$Div
.css({
top: posTop,
left: posLeft
});
switch (opts.VerticalPosition) {
case 'top':
$Div.animate({
top: posTop + opts.LongTrip,
opacity: 1
}, opts.ShowTimeEffect, function() {
if (opts.onCompleted) opts.onCompleted();
});
if (opts.autoHide)
$.jNotify._close();
else
$Div.css('cursor', 'pointer').click(function(e) {
$.jNotify._close();
});
break;
case 'center':
$Div.animate({
opacity: 1
}, opts.ShowTimeEffect, function() {
if (opts.onCompleted) opts.onCompleted();
});
if (opts.autoHide)
$.jNotify._close();
else
$Div.css('cursor', 'pointer').click(function(e) {
$.jNotify._close();
});
break;
case 'bottom':
$Div.animate({
top: posTop - opts.LongTrip,
opacity: 1
}, opts.ShowTimeEffect, function() {
if (opts.onCompleted) opts.onCompleted();
});
if (opts.autoHide)
$.jNotify._close();
else
$Div.css('cursor', 'pointer').click(function(e) {
$.jNotify._close();
});
break;
}
},
_showOverlay: function(el) {
var overlay =
$('<div id="jOverlay" />')
.css({
backgroundColor: opts.ColorOverlay,
opacity: opts.OpacityOverlay
})
.appendTo('body')
.show();
if (opts.clickOverlay)
overlay.click(function(e) {
e.preventDefault();
opts.TimeShown = 0; // Thanks to Guillaume M.
$.jNotify._close();
});
},
_close: function() {
switch (opts.VerticalPosition) {
case 'top':
if (!opts.autoHide)
opts.TimeShown = 0;
$Div.stop(true, true).delay(opts.TimeShown).animate({ // Tanks to Guillaume M.
top: posTop - opts.LongTrip,
opacity: 0
}, opts.HideTimeEffect, function() {
$(this).remove();
if (opts.ShowOverlay && $("#jOverlay").length > 0)
$("#jOverlay").remove();
if (opts.onClosed) opts.onClosed();
});
break;
case 'center':
if (!opts.autoHide)
opts.TimeShown = 0;
$Div.stop(true, true).delay(opts.TimeShown).animate({ // Tanks to Guillaume M.
opacity: 0
}, opts.HideTimeEffect, function() {
$(this).remove();
if (opts.ShowOverlay && $("#jOverlay").length > 0)
$("#jOverlay").remove();
if (opts.onClosed) opts.onClosed();
});
break;
case 'bottom':
if (!opts.autoHide)
opts.TimeShown = 0;
$Div.stop(true, true).delay(opts.TimeShown).animate({ // Tanks to Guillaume M.
top: posTop + opts.LongTrip,
opacity: 0
}, opts.HideTimeEffect, function() {
$(this).remove();
if (opts.ShowOverlay && $("#jOverlay").length > 0)
$("#jOverlay").remove();
if (opts.onClosed) opts.onClosed();
});
break;
}
},
_isReadable: function(id) {
if ($('#' + id).length > 0)
return false;
else
return true;
}
};
/** Init method **/
jNotify = function(msg, options) {
if ($.jNotify._isReadable('jNotify'))
$.jNotify.init(msg, options, 'jNotify');
};
jSuccess = function(msg, options) {
if ($.jNotify._isReadable('jSuccess'))
$.jNotify.init(msg, options, 'jSuccess');
};
jError = function(msg, options) {
if ($.jNotify._isReadable('jError'))
$.jNotify.init(msg, options, 'jError');
};
})(jQuery); | JavaScript |
function get_cookie(name)
{
with(document.cookie)
{
var regexp=new RegExp("(^|;\\s+)"+name+"=(.*?)(;|$)");
var hit=regexp.exec(document.cookie);
if(hit&&hit.length>2) return unescape(hit[2]);
else return '';
}
};
function set_cookie(name,value,days)
{
if(days)
{
var date=new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires="; expires="+date.toGMTString();
}
else expires="";
document.cookie=name+"="+value+expires+"; path=/";
}
function get_password(name)
{
var pass=get_cookie(name);
if(pass) return pass;
var chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var pass='';
for(var i=0;i<8;i++)
{
var rnd=Math.floor(Math.random()*chars.length);
pass+=chars.substring(rnd,rnd+1);
}
return(pass);
}
function insert(text)
{
var textarea=document.forms.postform.field4;
if(textarea)
{
if(textarea.createTextRange && textarea.caretPos) // IE
{
var caretPos=textarea.caretPos;
caretPos.text=caretPos.text.charAt(caretPos.text.length-1)==" "?text+" ":text;
}
else if(textarea.setSelectionRange) // Firefox
{
var start=textarea.selectionStart;
var end=textarea.selectionEnd;
textarea.value=textarea.value.substr(0,start)+text+textarea.value.substr(end);
textarea.setSelectionRange(start+text.length,start+text.length);
}
else
{
textarea.value+=text+" ";
}
textarea.focus();
}
}
function highlight(post)
{
var cells=document.getElementsByTagName("td");
for(var i=0;i<cells.length;i++) if(cells[i].className=="highlight") cells[i].className="reply";
var reply=document.getElementById("reply"+post);
if(reply)
{
reply.className="highlight";
/* var match=/^([^#]*)/.exec(document.location.toString());
document.location=match[1]+"#"+post;*/
return false;
}
return true;
}
function set_stylesheet(styletitle,norefresh)
{
set_cookie("wakabastyle",styletitle,365);
var links=document.getElementsByTagName("link");
var found=false;
for(var i=0;i<links.length;i++)
{
var rel=links[i].getAttribute("rel");
var title=links[i].getAttribute("title");
if(rel.indexOf("style")!=-1&&title)
{
links[i].disabled=true; // IE needs this to work. IE needs to die.
if(styletitle==title) { links[i].disabled=false; found=true; }
}
}
if(!found) set_preferred_stylesheet();
}
function set_preferred_stylesheet()
{
var links=document.getElementsByTagName("link");
for(var i=0;i<links.length;i++)
{
var rel=links[i].getAttribute("rel");
var title=links[i].getAttribute("title");
if(rel.indexOf("style")!=-1&&title) links[i].disabled=(rel.indexOf("alt")!=-1);
}
}
function get_active_stylesheet()
{
var links=document.getElementsByTagName("link");
for(var i=0;i<links.length;i++)
{
var rel=links[i].getAttribute("rel");
var title=links[i].getAttribute("title");
if(rel.indexOf("style")!=-1&&title&&!links[i].disabled) return title;
}
return null;
}
function get_preferred_stylesheet()
{
var links=document.getElementsByTagName("link");
for(var i=0;i<links.length;i++)
{
var rel=links[i].getAttribute("rel");
var title=links[i].getAttribute("title");
if(rel.indexOf("style")!=-1&&rel.indexOf("alt")==-1&&title) return title;
}
return null;
}
function set_inputs(id) { with(document.getElementById(id)) {if(!field1.value) field1.value=get_cookie("name"); if(!field2.value) field2.value=get_cookie("email"); if(!password.value) password.value=get_password("password"); } }
function set_delpass(id) { with(document.getElementById(id)) password.value=get_cookie("password"); }
function do_ban(el)
{
var reason=prompt("Give a reason for this ban:");
if(reason) document.location=el.href+"&comment="+encodeURIComponent(reason);
return false;
}
window.onunload=function(e)
{
if(style_cookie)
{
var title=get_active_stylesheet();
set_cookie(style_cookie,title,365);
}
}
window.onload=function(e)
{
var match;
if(match=/#i([0-9]+)/.exec(document.location.toString()))
if(!document.forms.postform.field4.value)
insert(">>"+match[1]);
if(match=/#([0-9]+)/.exec(document.location.toString()))
highlight(match[1]);
}
if(style_cookie)
{
var cookie=get_cookie(style_cookie);
var title=cookie?cookie:get_preferred_stylesheet();
set_stylesheet(title);
} | JavaScript |
{
"0": {
"ShangDian": false,
"ZiZhiLv": 0,
"MapTrans": 0,
"ZuoQiLv": 0,
"ZhuaPuLv": 0,
"B": 5,
"ShiZhuang": false,
"StarLv": 0,
"Auction": false,
"DayAward": false,
"Fight": 0,
"Award": 0,
"PetSkillLv": 0,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 0,
"DaTi": 0,
"StarMax": 30000,
"Produce": 1,
"IsHome": false,
"A": 100,
"ShiBan": 0,
"HomeHour": 2
},
"1": {
"ShangDian": false,
"ZiZhiLv": 0,
"MapTrans": 5,
"ZuoQiLv": 0,
"ZhuaPuLv": 0,
"B": 10,
"ShiZhuang": false,
"StarLv": 0,
"Auction": false,
"DayAward": false,
"Fight": 0,
"Award": 0,
"PetSkillLv": 0,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 0,
"DaTi": 0,
"StarMax": 30000,
"Produce": 1,
"IsHome": false,
"A": 500,
"ShiBan": 0,
"HomeHour": 2
},
"2": {
"ShangDian": false,
"ZiZhiLv": 0,
"MapTrans": 10,
"ZuoQiLv": 0,
"ZhuaPuLv": 0,
"B": 15,
"ShiZhuang": false,
"StarLv": 0,
"Auction": false,
"DayAward": true,
"Fight": 0,
"Award": 2,
"PetSkillLv": 0,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 0,
"DaTi": 0,
"StarMax": 40000,
"Produce": 1,
"IsHome": true,
"A": 1000,
"ShiBan": 0,
"HomeHour": 24
},
"3": {
"ShangDian": false,
"ZiZhiLv": 0,
"MapTrans": 15,
"ZuoQiLv": 0,
"ZhuaPuLv": 0,
"B": 20,
"ShiZhuang": false,
"StarLv": 0,
"Auction": false,
"DayAward": true,
"Fight": 0,
"Award": 4,
"PetSkillLv": 0,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 1,
"DaTi": 0,
"StarMax": 60000,
"Produce": 2,
"IsHome": true,
"A": 2000,
"ShiBan": 0,
"HomeHour": 24
},
"4": {
"ShangDian": true,
"ZiZhiLv": 0,
"MapTrans": 20,
"ZuoQiLv": 0,
"ZhuaPuLv": 0,
"B": 25,
"ShiZhuang": false,
"StarLv": 0,
"Auction": true,
"DayAward": true,
"Fight": 0.05,
"Award": 6,
"PetSkillLv": 0,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 0,
"DaTi": 0.05,
"StarMax": 80000,
"Produce": 3,
"IsHome": true,
"A": 5000,
"ShiBan": 0,
"HomeHour": 24
},
"5": {
"ShangDian": true,
"ZiZhiLv": 0,
"MapTrans": 25,
"ZuoQiLv": 0,
"ZhuaPuLv": 0,
"B": 30,
"ShiZhuang": true,
"StarLv": 0,
"Auction": true,
"DayAward": true,
"Fight": 0.1,
"Award": 6,
"PetSkillLv": 0.05,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 1,
"DaTi": 0.1,
"StarMax": 100000,
"Produce": 3,
"IsHome": true,
"A": 10000,
"ShiBan": 0,
"HomeHour": 24
},
"6": {
"ShangDian": true,
"ZiZhiLv": 0.05,
"MapTrans": 30,
"ZuoQiLv": 0,
"ZhuaPuLv": 0,
"B": 35,
"ShiZhuang": true,
"StarLv": 0,
"Auction": true,
"DayAward": true,
"Fight": 0.1,
"Award": 6,
"PetSkillLv": 0.05,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 0,
"DaTi": 0.1,
"StarMax": 120000,
"Produce": 3,
"IsHome": true,
"A": 20000,
"ShiBan": 0,
"HomeHour": 24
},
"7": {
"ShangDian": true,
"ZiZhiLv": 0.05,
"MapTrans": 35,
"ZuoQiLv": 0,
"ZhuaPuLv": 0,
"B": 40,
"ShiZhuang": true,
"StarLv": 0.05,
"Auction": true,
"DayAward": true,
"Fight": 0.1,
"Award": 6,
"PetSkillLv": 0.05,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 1,
"DaTi": 0.1,
"StarMax": 140000,
"Produce": 3,
"IsHome": true,
"A": 50000,
"ShiBan": 0,
"HomeHour": 24
},
"8": {
"ShangDian": true,
"ZiZhiLv": 0.05,
"MapTrans": 40,
"ZuoQiLv": 0,
"ZhuaPuLv": 0.05,
"B": 45,
"ShiZhuang": true,
"StarLv": 0.05,
"Auction": true,
"DayAward": true,
"Fight": 0.1,
"Award": 6,
"PetSkillLv": 0.05,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 0,
"DaTi": 0.1,
"StarMax": 160000,
"Produce": 3,
"IsHome": true,
"A": 80000,
"ShiBan": 0,
"HomeHour": 24
},
"9": {
"ShangDian": true,
"ZiZhiLv": 0.05,
"MapTrans": 45,
"ZuoQiLv": 0,
"ZhuaPuLv": 0.05,
"B": 50,
"ShiZhuang": true,
"StarLv": 0.05,
"Auction": true,
"DayAward": true,
"Fight": 0.1,
"Award": 6,
"PetSkillLv": 0.05,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 1,
"DaTi": 0.1,
"StarMax": 180000,
"Produce": 3,
"IsHome": true,
"A": 150000,
"ShiBan": 0,
"HomeHour": 24
},
"10": {
"ShangDian": true,
"ZiZhiLv": 0.05,
"MapTrans": 50,
"ZuoQiLv": 0.05,
"ZhuaPuLv": 0.05,
"B": 55,
"ShiZhuang": true,
"StarLv": 0.05,
"Auction": true,
"DayAward": true,
"Fight": 0.1,
"Award": 6,
"PetSkillLv": 0.05,
"FuseLv": 0,
"MapSecret": 0,
"Cote": 0,
"DaTi": 0.1,
"StarMax": 200000,
"Produce": 3,
"IsHome": true,
"A": 100000000,
"ShiBan": 0,
"HomeHour": 24
},
"KaiQi": {
"ShangDian": 4,
"ZiZhiLv": 6,
"MapTrans": 1,
"ZuoQiLv": 10,
"ZhuaPuLv": 8,
"ShiZhuang": 5,
"StarLv": 7,
"Auction": 4,
"DayAward": 2,
"Fight": 4,
"Award": 1,
"PetSkillLv": 5,
"FuseLv": 0,
"MapSecret": 3,
"Cote": 3,
"DaTi": 4,
"StarMax": 0,
"Produce": 0,
"IsHome": 2,
"ShiBan": 0,
"HomeHour": 0
}
} | JavaScript |
/*
Holder - 2.0 - client side image placeholders
(c) 2012-2013 Ivan Malopinsky / http://imsky.co
Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
Commercial use requires attribution.
*/
var Holder = Holder || {};
(function (app, win) {
var preempted = false,
fallback = false,
canvas = document.createElement('canvas');
//getElementsByClassName polyfill
document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s})
//getComputedStyle polyfill
window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this})
//http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications
function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}};
//https://gist.github.com/991057 by Jed Schmidt with modifications
function selector(a){
a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]);
var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret;
}
//shallow object property extend
function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c}
//hasOwnProperty polyfill
if (!Object.prototype.hasOwnProperty)
Object.prototype.hasOwnProperty = function(prop) {
var proto = this.__proto__ || this.constructor.prototype;
return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);
}
function text_size(width, height, template) {
height = parseInt(height,10);
width = parseInt(width,10);
var bigSide = Math.max(height, width)
var smallSide = Math.min(height, width)
var scale = 1 / 12;
var newHeight = Math.min(smallSide * 0.75, 0.75 * bigSide * scale);
return {
height: Math.round(Math.max(template.size, newHeight))
}
}
function draw(ctx, dimensions, template, ratio) {
var ts = text_size(dimensions.width, dimensions.height, template);
var text_height = ts.height;
var width = dimensions.width * ratio,
height = dimensions.height * ratio;
var font = template.font ? template.font : "sans-serif";
canvas.width = width;
canvas.height = height;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = template.background;
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = template.foreground;
ctx.font = "bold " + text_height + "px " + font;
var text = template.text ? template.text : (Math.floor(dimensions.width) + "x" + Math.floor(dimensions.height));
var text_width = ctx.measureText(text).width;
if (text_width / width >= 0.75) {
text_height = Math.floor(text_height * 0.75 * (width/text_width));
}
//Resetting font size if necessary
ctx.font = "bold " + (text_height * ratio) + "px " + font;
ctx.fillText(text, (width / 2), (height / 2), width);
return canvas.toDataURL("image/png");
}
function render(mode, el, holder, src) {
var dimensions = holder.dimensions,
theme = holder.theme,
text = holder.text ? decodeURIComponent(holder.text) : holder.text;
var dimensions_caption = dimensions.width + "x" + dimensions.height;
theme = (text ? extend(theme, {
text: text
}) : theme);
theme = (holder.font ? extend(theme, {
font: holder.font
}) : theme);
if (mode == "image") {
el.setAttribute("data-src", src);
el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption);
if (fallback || !holder.auto) {
el.style.width = dimensions.width + "px";
el.style.height = dimensions.height + "px";
}
if (fallback) {
el.style.backgroundColor = theme.background;
} else {
el.setAttribute("src", draw(ctx, dimensions, theme, ratio));
}
} else if (mode == "background") {
if (!fallback) {
el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")";
el.style.backgroundSize = dimensions.width + "px " + dimensions.height + "px";
}
} else if (mode == "fluid") {
el.setAttribute("data-src", src);
el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption);
if (dimensions.height.substr(-1) == "%") {
el.style.height = dimensions.height
} else {
el.style.height = dimensions.height + "px"
}
if (dimensions.width.substr(-1) == "%") {
el.style.width = dimensions.width
} else {
el.style.width = dimensions.width + "px"
}
if (el.style.display == "inline" || el.style.display == "") {
el.style.display = "block";
}
if (fallback) {
el.style.backgroundColor = theme.background;
} else {
el.holderData = holder;
fluid_images.push(el);
fluid_update(el);
}
}
};
function fluid_update(element) {
var images;
if (element.nodeType == null) {
images = fluid_images;
} else {
images = [element]
}
for (i in images) {
var el = images[i]
if (el.holderData) {
var holder = el.holderData;
el.setAttribute("src", draw(ctx, {
height: el.clientHeight,
width: el.clientWidth
}, holder.theme, ratio));
}
}
}
function parse_flags(flags, options) {
var ret = {
theme: settings.themes.gray
}, render = false;
for (sl = flags.length, j = 0; j < sl; j++) {
var flag = flags[j];
if (app.flags.dimensions.match(flag)) {
render = true;
ret.dimensions = app.flags.dimensions.output(flag);
} else if (app.flags.fluid.match(flag)) {
render = true;
ret.dimensions = app.flags.fluid.output(flag);
ret.fluid = true;
} else if (app.flags.colors.match(flag)) {
ret.theme = app.flags.colors.output(flag);
} else if (options.themes[flag]) {
//If a theme is specified, it will override custom colors
ret.theme = options.themes[flag];
} else if (app.flags.text.match(flag)) {
ret.text = app.flags.text.output(flag);
} else if (app.flags.font.match(flag)) {
ret.font = app.flags.font.output(flag);
} else if (app.flags.auto.match(flag)) {
ret.auto = true;
}
}
return render ? ret : false;
};
if (!canvas.getContext) {
fallback = true;
} else {
if (canvas.toDataURL("image/png")
.indexOf("data:image/png") < 0) {
//Android doesn't support data URI
fallback = true;
} else {
var ctx = canvas.getContext("2d");
}
}
var dpr = 1, bsr = 1;
if(!fallback){
dpr = window.devicePixelRatio || 1,
bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
}
var ratio = dpr / bsr;
var fluid_images = [];
var settings = {
domain: "holder.js",
images: "img",
bgnodes: ".holderjs",
themes: {
"gray": {
background: "#eee",
foreground: "#aaa",
size: 12
},
"social": {
background: "#3a5a97",
foreground: "#fff",
size: 12
},
"industrial": {
background: "#434A52",
foreground: "#C2F200",
size: 12
}
},
stylesheet: ""
};
app.flags = {
dimensions: {
regex: /^(\d+)x(\d+)$/,
output: function (val) {
var exec = this.regex.exec(val);
return {
width: +exec[1],
height: +exec[2]
}
}
},
fluid: {
regex: /^([0-9%]+)x([0-9%]+)$/,
output: function (val) {
var exec = this.regex.exec(val);
return {
width: exec[1],
height: exec[2]
}
}
},
colors: {
regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i,
output: function (val) {
var exec = this.regex.exec(val);
return {
size: settings.themes.gray.size,
foreground: "#" + exec[2],
background: "#" + exec[1]
}
}
},
text: {
regex: /text\:(.*)/,
output: function (val) {
return this.regex.exec(val)[1];
}
},
font: {
regex: /font\:(.*)/,
output: function (val) {
return this.regex.exec(val)[1];
}
},
auto: {
regex: /^auto$/
}
}
for (var flag in app.flags) {
if (!app.flags.hasOwnProperty(flag)) continue;
app.flags[flag].match = function (val) {
return val.match(this.regex)
}
}
app.add_theme = function (name, theme) {
name != null && theme != null && (settings.themes[name] = theme);
return app;
};
app.add_image = function (src, el) {
var node = selector(el);
if (node.length) {
for (var i = 0, l = node.length; i < l; i++) {
var img = document.createElement("img")
img.setAttribute("data-src", src);
node[i].appendChild(img);
}
}
return app;
};
app.run = function (o) {
var options = extend(settings, o),
images = [], imageNodes = [], bgnodes = [];
if(typeof(options.images) == "string"){
imageNodes = selector(options.images);
}
else if (window.NodeList && options.images instanceof window.NodeList) {
imageNodes = options.images;
} else if (window.Node && options.images instanceof window.Node) {
imageNodes = [options.images];
}
if(typeof(options.bgnodes) == "string"){
bgnodes = selector(options.bgnodes);
} else if (window.NodeList && options.elements instanceof window.NodeList) {
bgnodes = options.bgnodes;
} else if (window.Node && options.bgnodes instanceof window.Node) {
bgnodes = [options.bgnodes];
}
preempted = true;
for (i = 0, l = imageNodes.length; i < l; i++) images.push(imageNodes[i]);
var holdercss = document.getElementById("holderjs-style");
if (!holdercss) {
holdercss = document.createElement("style");
holdercss.setAttribute("id", "holderjs-style");
holdercss.type = "text/css";
document.getElementsByTagName("head")[0].appendChild(holdercss);
}
if (!options.nocss) {
if (holdercss.styleSheet) {
holdercss.styleSheet.cssText += options.stylesheet;
} else {
holdercss.appendChild(document.createTextNode(options.stylesheet));
}
}
var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)");
for (var l = bgnodes.length, i = 0; i < l; i++) {
var src = window.getComputedStyle(bgnodes[i], null)
.getPropertyValue("background-image");
var flags = src.match(cssregex);
var bgsrc = bgnodes[i].getAttribute("data-background-src");
if (flags) {
var holder = parse_flags(flags[1].split("/"), options);
if (holder) {
render("background", bgnodes[i], holder, src);
}
}
else if(bgsrc != null){
var holder = parse_flags(bgsrc.substr(bgsrc.lastIndexOf(options.domain) + options.domain.length + 1)
.split("/"), options);
if(holder){
render("background", bgnodes[i], holder, src);
}
}
}
for (l = images.length, i = 0; i < l; i++) {
var attr_src = attr_data_src = src = null;
try{
attr_src = images[i].getAttribute("src");
attr_datasrc = images[i].getAttribute("data-src");
}catch(e){}
if (attr_datasrc == null && !! attr_src && attr_src.indexOf(options.domain) >= 0) {
src = attr_src;
} else if ( !! attr_datasrc && attr_datasrc.indexOf(options.domain) >= 0) {
src = attr_datasrc;
}
if (src) {
var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1)
.split("/"), options);
if (holder) {
if (holder.fluid) {
render("fluid", images[i], holder, src)
} else {
render("image", images[i], holder, src);
}
}
}
}
return app;
};
contentLoaded(win, function () {
if (window.addEventListener) {
window.addEventListener("resize", fluid_update, false);
window.addEventListener("orientationchange", fluid_update, false);
} else {
window.attachEvent("onresize", fluid_update)
}
preempted || app.run();
});
if (typeof define === "function" && define.amd) {
define("Holder", [], function () {
return app;
});
}
})(Holder, window);
| JavaScript |
/*
Copyright (C) 2011 Google Inc.
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.
*/
var a=null;
PR.registerLangHandler(PR.createSimpleLexer([["opn",/^[([{]+/,a,"([{"],["clo",/^[)\]}]+/,a,")]}"],["com",/^;[^\n\r]*/,a,";"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \u00a0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:def|if|do|let|quote|var|fn|loop|recur|throw|try|monitor-enter|monitor-exit|defmacro|defn|defn-|macroexpand|macroexpand-1|for|doseq|dosync|dotimes|and|or|when|not|assert|doto|proxy|defstruct|first|rest|cons|defprotocol|deftype|defrecord|reify|defmulti|defmethod|meta|with-meta|ns|in-ns|create-ns|import|intern|refer|alias|namespace|resolve|ref|deref|refset|new|set!|memfn|to-array|into-array|aset|gen-class|reduce|map|filter|find|nil?|empty?|hash-map|hash-set|vec|vector|seq|flatten|reverse|assoc|dissoc|list|list?|disj|get|union|difference|intersection|extend|extend-type|extend-protocol|prn)\b/,a],
["typ",/^:[\dA-Za-z-]+/]]),["clj"]);
| JavaScript |
var device_width = 0;
var device_height = 0;
function reinit()
{
$.Metro.initDropdowns('header');
$.Metro.initPulls('header');
}
$(function(){
$("[data-load]").each(function(){
$(this).load($(this).data("load"), function(){
reinit();
});
});
window.prettyPrint && prettyPrint();
$(".history-back").on("click", function(e){
e.preventDefault();
history.back();
return false;
})
})
function headerPosition(){
if ($(window).scrollTop() > $('header').height()) {
$("header .navigation-bar")
.addClass("fixed-top")
.addClass(" shadow")
;
} else {
$("header .navigation-bar")
.removeClass("fixed-top")
.removeClass(" shadow")
;
}
}
$(function() {
if ($('nav > .side-menu').length > 0) {
var side_menu = $('nav > .side-menu');
var fixblock_pos = side_menu.position().top;
$(window).scroll(function(){
if ($(window).scrollTop() > fixblock_pos){
side_menu.css({'position': 'fixed', 'top':'65px', 'z-index':'1000'});
} else {
side_menu.css({'position': 'static'});
}
})
}
});
$(function(){
setTimeout(function(){headerPosition();}, 100);
})
$(window).scroll(function(){
headerPosition();
});
$(document).ready(function(){
var TriggerClick = 0;
$('#fluid-button').click(function(){
if(TriggerClick==0){
TriggerClick=1;
$( ".fluid-sides" ).animate({width: "+=16%"}, 200);
$( "#fluid-button" ).animate({left: "+=16%"}, 200);
}
else{
TriggerClick=0;
$( ".fluid-sides" ).animate({width: "0px"}, 200);
$( "#fluid-button" ).animate({left: "0"}, 200);
}
});
}); //window
function getDetail(mode){
if(mode=='hide'){$( "#detail" ).animate({width: "0%"}, 200);}
else{$( "#detail" ).animate({width: "78.5%"}, 200);}
}
function loadAsetMenu(){
$( "#pencarian" ).animate({width: "0px"}, 200);
$( "#tematik" ).css("margin", "0px");
$( "#tematik" ).animate({width: "22%",margin: "0px"}, 200);
}
function loadSearchMenu(){
$( "#tematik" ).animate({width: "0px",margin:"0 -10px 0 0"}, 200);
$( "#pencarian" ).animate({width: "22%"}, 200);
}
/*
function getDeviceSize(){
device_width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
//device_height = (window.innerHeight > 0) ? window.innerHeight : screen.height;
$("#device_width").html(device_width);
//$("#device_height").html(device_height);
}
$(function(){
$("<div/>").addClass("padding20 bg-dark fg-white border bd-white no-display").css({
position: "fixed",
top: 0,
right: 0
}).html('<span id="device_width">0</span>').appendTo("body");
getDeviceSize();
})
$(window).resize(function(){
getDeviceSize();
})
*/
| JavaScript |
$(function(){
if ((document.location.host.indexOf('.dev') > -1) || (document.location.host.indexOf('modernui') > -1) ) {
$("<script/>").attr('src', base_url+'/metroui/js/metro/metro-loader.js').appendTo($('head'));
} else {
$("<script/>").attr('src', base_url+'/metroui/js/metro.min.js').appendTo($('head'));
}
}) | JavaScript |
if (document.location.host.indexOf('.dev') > -1) {
//console.log('local');
} else {
if (document.location.host.indexOf('metroui') > -1) {
//document.write("<img src='http://c.hit.ua/hit?i=98055&g=0&x=2"+"&r="+encodeURI(document.referrer)+"&u="+encodeURI(window.location.href)+"' border='0' width='1' height='1'/>");
document.write("<script src='http://c.hit.ua/hit?i=98055&g=0&x=3&r="+encodeURI(document.referrer)+"&u="+encodeURI(window.location.href)+"'></script>");
} else {
console.log('hitua.js is a counter for Metro UI CSS'+"\n"+'Do not include this counter in you project');
}
}
| JavaScript |
var plugins = [
'global',
'core',
'locale',
'touch-handler',
'accordion',
'button-set',
'date-format',
'calendar',
'datepicker',
'carousel',
'countdown',
'dropdown',
'input-control',
'live-tile',
'progressbar',
'rating',
'slider',
'tab-control',
'table',
'times',
'dialog',
'notify',
'listview',
'treeview',
'fluentmenu',
'hint',
'streamer',
'stepper',
'drag-tile',
'scroll',
'pull',
'initiator'
];
$.each(plugins, function(i, plugin){
$("<script/>").attr('src', '/metroui/js/metro/metro-'+plugin+'.js').appendTo($('head'));
});
| JavaScript |
(function( $ ) {
$.widget("metro.livetile", {
version: "1.0.0",
options: {
effect: 'slideLeft',
period: 4000,
duration: 700,
easing: 'doubleSqrt'
},
_frames: {},
_currentIndex: 0,
_interval: 0,
_outPosition: 0,
_size: {},
_create: function(){
var that = this,
element = this.element;
if (element.data('effect') != undefined) {this.options.effect = element.data('effect');}
if (element.data('direction') != undefined) {this.options.direction = element.data('direction');}
if (element.data('period') != undefined) {this.options.period = element.data('period');}
if (element.data('duration') != undefined) {this.options.duration = element.data('duration');}
if (element.data('easing') != undefined) {this.options.easing = element.data('easing');}
//this._frames = element.children(".tile-content, .event-content");
this._frames = element.children("[class*='-content']");
//console.log(this._frames);
if (this._frames.length <= 1) return;
$.easing.doubleSqrt = function(t) {return Math.sqrt(Math.sqrt(t));};
this._size = {
'width': element.width(),
'height': element.height()
};
element.on('mouseenter', function(){
that.stop();
});
element.on('mouseleave', function(){
that.start();
});
this.start();
},
start: function(){
var that = this;
this._interval = setInterval(function(){
that._animate();
}, this.options.period);
},
stop: function(){
clearInterval(this._interval);
},
_animate: function(){
var currentFrame = this._frames[this._currentIndex], nextFrame;
this._currentIndex += 1;
if (this._currentIndex >= this._frames.length) this._currentIndex = 0;
nextFrame = this._frames[this._currentIndex];
switch (this.options.effect) {
case 'slideLeft': this._effectSlideLeft(currentFrame, nextFrame); break;
case 'slideRight': this._effectSlideRight(currentFrame, nextFrame); break;
case 'slideDown': this._effectSlideDown(currentFrame, nextFrame); break;
case 'slideUpDown': this._effectSlideUpDown(currentFrame, nextFrame); break;
case 'slideLeftRight': this._effectSlideLeftRight(currentFrame, nextFrame); break;
default: this._effectSlideUp(currentFrame, nextFrame);
}
},
_effectSlideLeftRight: function(currentFrame, nextFrame){
if (this._currentIndex % 2 == 0)
this._effectSlideLeft(currentFrame, nextFrame);
else
this._effectSlideRight(currentFrame, nextFrame);
},
_effectSlideUpDown: function(currentFrame, nextFrame){
if (this._currentIndex % 2 == 0)
this._effectSlideUp(currentFrame, nextFrame);
else
this._effectSlideDown(currentFrame, nextFrame);
},
_effectSlideUp: function(currentFrame, nextFrame){
var _out = this._size.height;
var options = {
'duration': this.options.duration,
'easing': this.options.easing
};
$(currentFrame)
.animate({top: -_out}, options);
$(nextFrame)
.css({top: _out})
.show()
.animate({top: 0}, options);
},
_effectSlideDown: function(currentFrame, nextFrame){
var _out = this._size.height;
var options = {
'duration': this.options.duration,
'easing': this.options.easing
};
$(currentFrame)
.animate({top: _out}, options);
$(nextFrame)
.css({top: -_out})
.show()
.animate({top: 0}, options);
},
_effectSlideLeft: function(currentFrame, nextFrame){
var _out = this._size.width;
var options = {
'duration': this.options.duration,
'easing': this.options.easing
};
$(currentFrame)
.animate({left: _out * -1}, options);
$(nextFrame)
.css({left: _out})
.show()
.animate({left: 0}, options);
},
_effectSlideRight: function(currentFrame, nextFrame){
var _out = this._size.width;
var options = {
'duration': this.options.duration,
'easing': this.options.easing
};
$(currentFrame)
.animate({left: _out}, options);
$(nextFrame)
.css({left: -_out})
.show()
.animate({left: 0}, options);
},
_destroy: function(){},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.times", {
version: "1.0.0",
options: {
style: {
background: "bg-dark",
foreground: "fg-white",
divider: "fg-dark"
},
blink: true,
alarm: {
h: 0,
m: 0,
s: 0
},
ontick: function(h, m, s){},
onalarm: function(){}
},
wrappers: {},
_interval: 0,
_create: function(){
var that = this, element = this.element;
$.each(['Hours','Minutes','Seconds'],function(){
$('<span class="count'+this+'">').html(
'<span class="digit-wrapper">\
<span class="digit">0</span>\
</span>\
<span class="digit-wrapper">\
<span class="digit">0</span>\
</span>'
).appendTo(element);
if(this!="Seconds"){
element.append('<span class="divider"></span>');
}
});
this.wrappers = this.element.find('.digit-wrapper');
if (element.data('blink') != undefined) {
this.options.blink = element.data('blick');
}
if (element.data('styleBackground') != undefined) {
this.options.style.background = element.data('styleBackground');
}
if (element.data('styleForeground') != undefined) {
this.options.style.foreground = element.data('styleForeground');
}
if (element.data('styleDivider') != undefined) {
this.options.style.divider = element.data('styleDivider');
}
if (this.options.style.background != "default") {
this.element.find(".digit").addClass(this.options.style.background);
}
if (this.options.style.foreground != "default") {
this.element.find(".digit").addClass(this.options.style.foreground);
}
if (this.options.style.divider != "default") {
this.element.find(".divider").addClass(this.options.style.divider);
}
if (element.data('alarm') != undefined) {
var _alarm = element.data('alarm').split(":");
this.options.alarm.h = _alarm[0] != undefined ? _alarm[0] : 0;
this.options.alarm.m = _alarm[1] != undefined ? _alarm[1] : 0;
this.options.alarm.s = _alarm[2] != undefined ? _alarm[2] : 0;
}
if (element.data('onalarm') != undefined) {
}
setTimeout( function(){
that.tick()
}, 1000);
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
},
tick: function(){
var that = this;
this._interval = setInterval(function(){
var _date = new Date();
var h, m, s;
h = _date.getHours();
that.updateDuo(0, 1, h);
m = _date.getMinutes();
that.updateDuo(2, 3, m);
s = _date.getSeconds();
that.updateDuo(4, 5, s);
// Calling an optional user supplied callback
that.options.ontick(h, m, s);
that.blinkDivider();
var alarm = that.options.alarm;
if (alarm) {
if (
(alarm.h != undefined && alarm.h == h)
&& (alarm.m != undefined && alarm.m == m)
&& (alarm.s != undefined && alarm.s == s)
) {
that.options.onalarm();
that._trigger('alarm');
}
}
// Scheduling another call of this function in 1s
}, 1000);
},
blinkDivider: function(){
if (this.options.blink)
this.element.find(".divider").toggleClass("no-visible");
},
updateDuo: function(minor, major, value){
this.switchDigit(this.wrappers.eq(minor),Math.floor(value/10)%10);
this.switchDigit(this.wrappers.eq(major),value%10);
},
switchDigit: function(wrapper, number){
var digit = wrapper.find('.digit');
if(digit.is(':animated')){
return false;
}
if(wrapper.data('digit') == number){
// We are already showing this number
return false;
}
wrapper.data('digit', number);
var replacement = $('<span>',{
'class':'digit',
css:{
top:'-2.1em',
opacity:0
},
html:number
});
replacement.addClass(this.options.style.background);
replacement.addClass(this.options.style.foreground);
digit
.before(replacement)
.removeClass('static')
.animate({top:'2.5em',opacity:0},'fast',function(){
digit.remove();
});
replacement
.delay(100)
.animate({top:0,opacity:1},'fast');
return true;
}
});
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.tablecontrol", {
version: "1.0.0",
options: {
width: '100%',
height: 'auto',
cls: 'table',
checkRow: false,
colModel: [],
data: []
},
_create: function(){
var element = this.element,
table;
element.css({
width: this.options.width,
height: this.options.height
});
table = this.createTable(element);
this.addHeader(table, this.options.colModel);
this.addTableData(table, this.options.data);
table.addClass(this.options.cls);
},
addHeader: function(container, data){
var thead = $("<thead/>").appendTo(container);
var th, tr = $("<tr/>").appendTo(thead);
$.each(data, function(index, column){
th = $("<th/>").addClass(column.hcls).html(column.caption).appendTo(tr);
});
},
createTable: function(container){
return $("<table/>").appendTo(container);
},
addTableData: function(container, data){
var that = this,
tbody = $("<tbody/>").appendTo(container);
$.each(data, function(i, row){
that.addRowData(tbody, row);
});
},
addRowData: function(container, row){
var td, tr = $("<tr/>").appendTo(container);
if (row.__row_class != undefined) {
tr.addClass(row.__row_class);
}
$.each(this.options.colModel, function(index, val){
td = $("<td/>").css("width", val.width).addClass(val.cls).html(row[val.field]).appendTo(tr);
});
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
$(function(){
$('[data-role=table]').tablecontrol();
}); | JavaScript |
(function( $ ) {
$.widget("metro.rating", {
version: "1.0.0",
options: {
score: 0,
half: false,
stars: 5,
static: true,
hints: ['bad', 'poor', 'regular', 'good', 'gorgeous'],
showHint: false,
showScore: false,
scoreHint: "Current score: ",
click: function(value, rating){}
},
_create: function(){
var that = this,
element = this.element;
if (element.data('score') != undefined) {
this.options.score = element.data('score');
}
if (element.data('half') != undefined) {
this.options.half = element.data('half');
}
if (element.data('stars') != undefined) {
this.options.stars = element.data('stars');
}
if (element.data('showHint') != undefined) {
this.options.showHint = element.data('showHint');
}
if (element.data('static') != undefined) {
this.options.static = element.data('static');
}
if (element.data('showScore') != undefined) {
this.options.showScore = element.data('showScore');
}
if (element.data('scoreHint') != undefined) {
this.options.scoreHint = element.data('scoreHint');
}
this._showRating();
},
rate: function(value){
this.options.score = value;
this._showRating();
},
_showRating: function(){
var that = this,
element = this.element,
options = this.options,
ul, li;
element.addClass("rating");
element.html('');
ul = $("<ul/>");
if (!options.static){
element.addClass("active");
}
for(var i=0; i<options.stars;i++){
li = $("<li/>"); li.data('value', i+1);
if (options.showHint) li.attr('title', options.hints[i]);
if (i <= options.score - 1) {
li.addClass("rated");
}
li.on("click", function(){
options.click($(this).data('value'), that);
});
li.appendTo(ul);
}
ul.appendTo(element);
if (options.showScore) {
$("<span/>").addClass('score-hint').html(options.scoreHint+options.score).appendTo(element);
element.css('height', 'auto');
} else {
element.find('ul').css('margin-bottom', 0);
}
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
// this is a temporary solution
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
//console.log(arguments);
// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date;
//if (isNaN(date)) throw SyntaxError("invalid date");
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
//console.log(locale);
locale = $.Metro.currentLocale;
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: $.Metro.Locale[locale].days[D],
dddd: $.Metro.Locale[locale].days[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: $.Metro.Locale[locale].months[m],
mmmm: $.Metro.Locale[locale].months[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};
/*
* End date format
*/
| JavaScript |
(function( $ ) {
$.widget("metro.countdown", {
version: "1.0.0",
options: {
style: {
background: "bg-dark",
foreground: "fg-white",
divider: "fg-dark"
},
blink: true,
days: 1,
stoptimer: 0,
ontick: function(d, h, m, s){},
onstop: function(){}
},
wrappers: {},
_interval: 0,
_create: function(){
var that = this, countdown = this.element;
$.each(['Days','Hours','Minutes','Seconds'],function(){
$('<span class="count'+this+'">').html(
'<span class="digit-wrapper">\
<span class="digit">0</span>\
</span>\
<span class="digit-wrapper">\
<span class="digit">0</span>\
</span>'
).appendTo(countdown);
if(this!="Seconds"){
countdown.append('<span class="divider"></span>');
}
});
this.wrappers = this.element.find('.digit-wrapper');
if (countdown.data('blink') != undefined) {
this.options.blink = countdown.data('blick');
}
if (countdown.data('styleBackground') != undefined) {
this.options.style.background = countdown.data('styleBackground');
}
if (countdown.data('styleForeground') != undefined) {
this.options.style.foreground = countdown.data('styleForeground');
}
if (countdown.data('styleDivider') != undefined) {
this.options.style.divider = countdown.data('styleDivider');
}
if (this.options.style.background != "default") {
this.element.find(".digit").addClass(this.options.style.background);
}
if (this.options.style.foreground != "default") {
this.element.find(".digit").addClass(this.options.style.foreground);
}
if (this.options.style.divider != "default") {
this.element.find(".divider").addClass(this.options.style.divider);
}
if (countdown.data('stoptimer') != undefined) {
this.options.stoptimer = new Date(countdown.data('stoptimer'));
}
if (this.options.stoptimer == 0) {
this.options.stoptimer = (new Date()).getTime() + this.options.days*24*60*60*1000;
}
setTimeout( function(){
that.tick()
}, 1000);
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
},
tick: function(){
var that = this;
this._interval = setInterval(function(){
var days = 24*60*60,
hours = 60*60,
minutes = 60;
var left, d, h, m, s;
left = Math.floor((that.options.stoptimer - (new Date())) / 1000);
if(left < 0){
left = 0;
}
// Number of days left
d = Math.floor(left / days);
that.updateDuo(0, 1, d);
left -= d*days;
// Number of hours left
h = Math.floor(left / hours);
that.updateDuo(2, 3, h);
left -= h*hours;
// Number of minutes left
m = Math.floor(left / minutes);
that.updateDuo(4, 5, m);
left -= m*minutes;
// Number of seconds left
s = left;
that.updateDuo(6, 7, s);
// Calling an optional user supplied ontick
that.options.ontick(d, h, m, s);
that.blinkDivider();
// Scheduling another call of this function in 1s
if (d === 0 && h === 0 && m === 0 && s === 0) {
that.options.onstop();
that.stopDigit();
that._trigger('alarm');
clearInterval(that._interval);
}
}, 1000);
},
blinkDivider: function(){
if (this.options.blink)
this.element.find(".divider").toggleClass("no-visible");
},
stopDigit: function(){
this.wrappers.each(function(){
$(this).children(".digit").addClass("stop");
})
},
updateDuo: function(minor, major, value){
this.switchDigit(this.wrappers.eq(minor),Math.floor(value/10)%10);
this.switchDigit(this.wrappers.eq(major),value%10);
},
switchDigit: function(wrapper, number){
var digit = wrapper.find('.digit');
if(digit.is(':animated')){
return false;
}
if(wrapper.data('digit') == number){
// We are already showing this number
return false;
}
wrapper.data('digit', number);
var replacement = $('<span>',{
'class':'digit',
css:{
top:'-2.1em',
opacity:0
},
html:number
});
replacement.addClass(this.options.style.background);
replacement.addClass(this.options.style.foreground);
digit
.before(replacement)
.removeClass('static')
.animate({top:'2.5em'},'fast',function(){
digit.remove();
});
replacement
.delay(100)
.animate({top:0,opacity:1},'fast');
return true;
}
});
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.scrollbar", {
version: "1.0.0",
options: {
height: '100%', /* '100%'|int */
width: '100%', /* '100%'|int */
axis: ['x','y'], /* x|y|[x,y] */
wheel: 55 /* step in px */
//size: 'auto' /* 'auto'|int */
},
startSize: {
width: null,
height: null
},
elemPadding: false,
bothScroll: false,
scrollbar: null,
contentHeight: 0,
contentWidth: 0,
contentMinHeight: 0,
contentMinWidth: 0,
dragElem: null,
dragStart: false,
startCoords: {
x:0,
y:0
},
currCoords: {
x:0,
y:0
},
handlers: false,
_create: function() {
var elem = this.element;
var that = this;
if(elem.data('scroll') != undefined) {
var dataScroll = elem.data('scroll');
if(dataScroll == 'vertical') {
this.options.axis = 'y';
}
if(dataScroll == 'horizontal') {
this.options.axis = 'x';
}
if(dataScroll == 'both') {
this.options.axis = ['x','y'];
}
}
if(elem.data('height') != undefined) {
this.options.height = elem.data('height');
}
if(elem.data('width') != undefined) {
this.options.width = elem.data('width');
}
if(elem.data('wheel') != undefined) {
this.options.wheel = elem.data('wheel');
}
elem.css({
position: 'relative'
});
var width = elem.outerWidth();
var height = elem.outerHeight();
this.contentMinWidth = width;
this.contentMinHeight = height;
this.startSize.width = this.options.width;
this.startSize.height = this.options.height;
var sw = (this.startSize.width == parseInt(this.startSize.width)) ? this.startSize.width+'px' : this.startSize.width;
var sh = (this.startSize.height == parseInt(this.startSize.height)) ? this.startSize.height+'px' : this.startSize.height;
elem.wrap('<div class="scrollbar" style="width: '+sw+'; height: '+sh+';"></div>');
this.scrollbar = elem.parents('.scrollbar').first();
this.scrollbar.parents().first().css({
overflow: 'hidden'
});
this._build(width,height);
$(window).resize(function () {
that._resize();
});
},
_resize: function () {
var elem = this.element;
if( (!isNaN(parseInt(this.element.css('left'))) && parseInt(this.element.css('left')) != 0) || (!isNaN(parseInt(this.element.css('top'))) && parseInt(this.element.css('top'))) ) {
var l = Math.abs(parseInt(this.element.css('left')));
var t = Math.abs(parseInt(this.element.css('top')));
var w = this.scrollbar.width();
var h = this.scrollbar.height();
if(this.contentWidth - l < w) {
l = l - (w-(this.contentWidth - l));
if(l<0) {
l = 0;
}
this.element.css('left',l*(-1));
}
this.element.css('left',l*(-1));
if(this.contentHeight - t < h) {
t = t - (h-(this.contentHeight - t));
if(t<0) {
t = 0;
}
this.element.css('top',t*(-1));
}
}
this.options.width = this.startSize.width;
this.options.height = this.startSize.height;
this.scrollbar.css({
padding: 0
});
if(this.elemPadding) {
this.element.css({
paddingRight: '-=5',
paddingBottom: '-=5'
});
this.elemPadding = false;
}
if(this.scrollbar.find('.scrollbar-v').length>0) {
this.scrollbar.find('.scrollbar-v').remove();
}
if(this.scrollbar.find('.scrollbar-h').length>0) {
this.scrollbar.find('.scrollbar-h').remove();
}
if(this.scrollbar.find('.scrollbar-both').length>0) {
this.scrollbar.find('.scrollbar-both').remove();
}
var width = elem.outerWidth();
var height = elem.outerHeight();
this.contentWidth = width;
this.contentHeight = height;
this._removeHandlers();
this._build(width,height);
},
_build: function (width,height) {
var elem = this.element;
this.options.width = (this.options.width == '100%') ? this.scrollbar.outerWidth() : this.options.width;
this.options.height = (this.options.height == '100%') ? this.scrollbar.outerHeight() : this.options.height;
this.scrollbar.css({
width: this.startSize.width,
height: this.startSize.height
});
this.contentWidth = width;
this.contentHeight = height;
if(this.options.axis == 'y') {
/* vertical */
if(this.contentHeight>this.options.height) {
this.scrollbar.css({
paddingRight: 20,
paddingBottom: 0
});
var width = elem.outerWidth();
var height = elem.outerHeight();
this.contentWidth = width;
this.contentHeight = height;
this._verticalScrollbar();
this._startHandlers();
}
else {
if(this.scrollbar.find('.scrollbar-v').length>0) {
this.scrollbar.find('.scrollbar-v').hide();
}
this.scrollbar.css({
paddingRight: 0,
paddingBottom: 0
});
}
}
else if(this.options.axis == 'x') {
/* horizontal */
if(this.contentWidth>this.options.width) {
if(this.startSize.height == '100%') {
this.scrollbar.css({
paddingBottom: 20,
paddingRight: 0
});
var width = elem.outerWidth();
var height = elem.outerHeight();
this.contentWidth = width;
this.contentHeight = height;
}
this._horizontalScrollbar();
this._startHandlers();
}
else {
if(this.scrollbar.find('.scrollbar-h').length>0) {
this.scrollbar.find('.scrollbar-h').hide();
}
this.scrollbar.css({
paddingBottom: 0,
paddingRight: 0
});
}
}
else {
/* both */
if(this.contentHeight>this.options.height && this.contentWidth>this.options.width) {
this.bothScroll = true;
if(this.scrollbar.find('.scrollbar-both').length>0) {
this.scrollbar.find('.scrollbar-both').show();
}
else {
this.scrollbar.append('<div class="scrollbar-both"></div>');
}
if(!this.elemPadding) {
this.element.css({
paddingRight: '+=5',
paddingBottom: '+=5'
});
this.elemPadding = true;
}
var width = elem.outerWidth();
var height = elem.outerHeight();
this.contentWidth = width;
this.contentHeight = height;
this._verticalScrollbar();
this._horizontalScrollbar();
this._startHandlers();
}
else {
this.bothScroll = false;
if(this.scrollbar.find('.scrollbar-both').length>0) {
this.scrollbar.find('.scrollbar-both').hide();
}
if(this.elemPadding) {
this.element.css({
paddingRight: '-=5',
paddingBottom: '-=5'
});
this.elemPadding = false;
}
if(this.contentWidth>this.options.width) {
if(this.startSize.height == '100%') {
this.scrollbar.css({
paddingBottom: 20,
paddingRight: 0
});
var width = elem.outerWidth();
var height = elem.outerHeight();
this.contentWidth = width;
this.contentHeight = height;
}
this._horizontalScrollbar();
this._startHandlers();
}
else {
if(this.scrollbar.find('.scrollbar-h').length>0) {
this.scrollbar.find('.scrollbar-h').hide();
}
this.scrollbar.css({
paddingBottom: 0,
paddingRight: 0
});
}
if(this.contentHeight>this.options.height) {
this.scrollbar.css({
paddingRight: 20,
paddingBottom: 0
});
var width = elem.outerWidth();
var height = elem.outerHeight();
this.contentWidth = width;
this.contentHeight = height;
this._verticalScrollbar();
this._startHandlers();
}
else {
if(this.scrollbar.find('.scrollbar-v').length>0) {
this.scrollbar.find('.scrollbar-v').hide();
}
this.scrollbar.css({
paddingRight: 0,
paddingBottom: 0
});
}
}
}
},
_verticalScrollbar: function () {
if(this.scrollbar.find('.scrollbar-v').length<1) {
var str = [];
str[str.length] = '<div class="scrollbar-v">';
str[str.length] = '<div class="scrollbar-v-up"></div>';
str[str.length] = '<div class="scrollbar-v-down"></div>';
str[str.length] = '<div class="scrollbar-line-v">';
str[str.length] = '<div class="scrollbar-line-v-btn"></div>';
str[str.length] = '</div>';
str[str.length] = '</div>';
str = str.join('');
this.scrollbar.append(str);
}
else {
this.scrollbar.find('.scrollbar-v').show();
}
var line = this.scrollbar.find('.scrollbar-line-v');
var btn = this.scrollbar.find('.scrollbar-line-v-btn');
var scrollBar = this.scrollbar.find('.scrollbar-v');
if(this.bothScroll) {
scrollBar.height(this.options.height);
var h = scrollBar.height()-15;
this.options.height = h;
scrollBar.height(h);
}
else {
scrollBar.height(this.options.height);
}
var height = this.options.height-32;
var ratio = height/this.contentHeight;
line.height(height);
if(ratio>=(this.contentHeight-32)/this.contentHeight) {
btn.hide();
}
else {
var btnHeight = ratio*this.options.height;
btn.show().height(btnHeight);
}
},
_horizontalScrollbar: function () {
if(this.scrollbar.find('.scrollbar-h').length<1) {
var str = [];
str[str.length] = '<div class="scrollbar-h">';
str[str.length] = '<div class="scrollbar-h-up"></div>';
str[str.length] = '<div class="scrollbar-h-down"></div>';
str[str.length] = '<div class="scrollbar-line-h">';
str[str.length] = '<div class="scrollbar-line-h-btn"></div>';
str[str.length] = '</div>';
str[str.length] = '</div>';
str = str.join('');
this.scrollbar.append(str);
}
else {
this.scrollbar.find('.scrollbar-h').show();
}
var line = this.scrollbar.find('.scrollbar-line-h');
var btn = this.scrollbar.find('.scrollbar-line-h-btn');
var scrollBar = this.scrollbar.find('.scrollbar-h');
if(this.bothScroll) {
scrollBar.width(this.options.width);
var w = scrollBar.width()-15;
this.options.width = w;
scrollBar.width(w);
}
else {
scrollBar.width(this.options.width);
}
var width = this.options.width-32;
var ratio = width/this.contentWidth;
var btnWidth = ratio*this.options.width;
var l = (!isNaN(parseInt(this.element.css('left')))) ? parseInt(this.element.css('left')) : 0;
var left = Math.abs(l)*ratio;
line.width(width);
if(ratio>=(this.contentWidth-32)/this.contentWidth) {
btn.hide();
}
else {
btn.show().width(btnWidth).css({
left:left
});
}
},
_startHandlers: function () {
if(this.handlers) {
return false;
}
this.handlers = true;
var that = this;
$(document).mousemove(function(e){
that._drag(e);
});
$(document).mouseup(function(e){
that._dragEnd(e);
});
this.scrollbar.find('.scrollbar-line-v-btn,.scrollbar-line-h-btn').on('mousedown', function(e){
that._dragStart(e, $(this));
});
this.scrollbar.find('.scrollbar-line-v,.scrollbar-line-h').on('click', function(e){
that._clickPos(e, $(this));
});
this.scrollbar.find('.scrollbar-v-up,.scrollbar-h-up').on('click', function(e){
that._fixScroll(1,$(this));
});
this.scrollbar.find('.scrollbar-v-down,.scrollbar-h-down').on('click', function(e){
that._fixScroll(-1,$(this));
});
this.scrollbar.mousewheel(function(e, delta) {
that._fixScroll(delta);
return false;
});
},
_removeHandlers: function () {
if(!this.handlers) {
return false;
}
this.handlers = false;
var that = this;
$(document).mousemove(function(e){
return false;
});
$(document).mouseup(function(e){
return false;
});
this.scrollbar.find('.scrollbar-line-v-btn,.scrollbar-line-h-btn').off('mousedown');
this.scrollbar.find('.scrollbar-line-v,.scrollbar-line-h').off('click');
this.scrollbar.find('.scrollbar-v-up,.scrollbar-h-up').off('click');
this.scrollbar.find('.scrollbar-v-down,.scrollbar-h-down').off('click');
},
_clickPos: function (e,elem) {
if($(e.target).attr('class') == 'scrollbar-line-v' || $(e.target).attr('class') == 'scrollbar-line-h') {
var offset = elem.offset();
if($(e.target).attr('class') == 'scrollbar-line-v') {
var top = e.pageY - offset.top;
var btn = elem.find('.scrollbar-line-v-btn');
this.dragElem = {
elem: btn,
width: btn.width(),
height: btn.height(),
parent: elem,
parentWidth: elem.width(),
parentHeight: elem.height(),
parentOffset: offset
};
this._scrollTo(0,top,'y');
this.dragElem = null;
}
else {
var left = e.pageX - offset.left;
var btn = elem.find('.scrollbar-line-h-btn');
this.dragElem = {
elem: btn,
width: btn.width(),
height: btn.height(),
parent: elem,
parentWidth: elem.width(),
parentHeight: elem.height(),
parentOffset: offset
};
this._scrollTo(left,0,'x');
this.dragElem = null;
}
}
},
_fixScroll: function (delta,elem) {
var step = this.options.wheel;
if( (elem !== undefined && (elem.hasClass('scrollbar-h-up') || elem.hasClass('scrollbar-h-down'))) || this.options.axis == 'x' || (this.options.axis != 'x' && this.options.axis != 'y' && this.scrollbar.find('.scrollbar-v').length<1)) {
var percent = step/this.contentWidth*100;
var barStep = (this.options.width-32)/100*percent;
var leftCss = parseInt(this.element.css('left'));
var pos = (!isNaN(leftCss)) ? Math.abs(leftCss) : 0;
var btn = this.scrollbar.find('.scrollbar-line-h-btn');
var parent = this.scrollbar.find('.scrollbar-line-h');
var barLeftCss = parseFloat(btn.css('left'));
var barPos = (!isNaN(barLeftCss)) ? barLeftCss : 0;
if(delta>0) {
var left = pos-step;
var barLeft = barPos-barStep;
}
else {
var left = pos+step;
var barLeft = barPos+barStep;
}
if(left<0) {
left = 0;
}
if(left>this.contentWidth-this.options.width) {
left = this.contentWidth-this.options.width;
}
var parentsSize = {
width: parent.width(),
height: parent.height()
};
var dragElemSize = {
width: btn.width(),
height: btn.height()
};
if(barLeft<0) {
barLeft = 0;
}
if(barLeft+dragElemSize.width>parentsSize.width) {
barLeft = parentsSize.width-dragElemSize.width;
}
this.element.css({
left: left*(-1)
});
btn.css({
left: barLeft
});
}
else {
var percent = step/this.contentHeight*100;
var barStep = (this.options.height-32)/100*percent;
var topCss = parseInt(this.element.css('top'));
var pos = (!isNaN(topCss)) ? Math.abs(topCss) : 0;
var btn = this.scrollbar.find('.scrollbar-line-v-btn');
var parent = this.scrollbar.find('.scrollbar-line-v');
var barTopCss = parseFloat(btn.css('top'));
var barPos = (!isNaN(barTopCss)) ? barTopCss : 0;
if(delta>0) {
var top = pos-step;
var barTop = barPos-barStep;
}
else {
var top = pos+step;
var barTop = barPos+barStep;
}
if(top<0) {
top = 0;
}
if(top>this.contentHeight-this.options.height) {
top = this.contentHeight-this.options.height;
}
var parentsSize = {
width: parent.width(),
height: parent.height()
};
var dragElemSize = {
width: btn.width(),
height: btn.height()
};
if(barTop<0) {
barTop = 0;
}
if(barTop+dragElemSize.height>parentsSize.height) {
barTop = parentsSize.height-dragElemSize.height;
}
this.element.css({
top: top*(-1)
});
btn.css({
top: barTop
});
}
},
_scrollTo: function (left,top,xy) {
if(xy == 'x') {
var width = this.options.width-32;
var ratio = width/this.contentWidth;
var currLeft = left/ratio;
if(currLeft<0) {
currLeft = 0;
}
if(currLeft>this.contentWidth-this.options.width) {
currLeft = this.contentWidth-this.options.width;
}
if(left<0) {
left = 0;
}
if(left>this.dragElem.parentWidth-this.dragElem.width) {
left = this.dragElem.parentWidth-this.dragElem.width;
}
this.dragElem.elem.css({
left:left
});
this.element.css({
left: currLeft*(-1)
});
}
else {
var height = this.options.height-32;
var ratio = height/this.contentHeight;
var currTop = top/ratio;
if(currTop<0) {
currTop = 0;
}
if(currTop>this.contentHeight-this.options.height) {
currTop = this.contentHeight-this.options.height;
}
if(top<0) {
top = 0;
}
if(top>this.dragElem.parentHeight-this.dragElem.height) {
top = this.dragElem.parentHeight-this.dragElem.height;
}
this.dragElem.elem.css({
top:top
});
this.element.css({
top: currTop*(-1)
});
}
},
_scroll: function () {
if(this.dragElem.elem.hasClass('scrollbar-line-h-btn')) {
var width = this.options.width-32;
var ratio = width/this.contentWidth;
var leftCss = parseInt(this.dragElem.elem.css('left'));
var leftCurr = (!isNaN(leftCss)) ? Math.abs(leftCss) : 0;
var left = leftCurr/ratio;
if(left<0) {
left = 0;
}
if(left>this.contentWidth-this.options.width) {
left = this.contentWidth-this.options.width;
}
this.element.css({
left: left*(-1)
});
}
else {
var height = this.options.height-32;
var ratio = height/this.contentHeight;
var topCss = parseInt(this.dragElem.elem.css('top'));
var topCurr = (!isNaN(topCss)) ? Math.abs(topCss) : 0;
var top = topCurr/ratio;
if(top<0) {
top = 0;
}
if(top>this.contentHeight-this.options.height) {
top = this.contentHeight-this.options.height;
}
this.element.css({
top: top*(-1)
});
}
},
_startCoordsDiff: function (e) {
var offset = this.dragElem.elem.offset();
this.startCoords.x = e.pageX - offset.left;
this.startCoords.y = e.pageY - offset.top;
},
_dragStart: function (e,elem) {
var parent = elem.parents().first();
this.dragElem = {
elem: elem,
width: elem.width(),
height: elem.height(),
parent: parent,
parentWidth: parent.width(),
parentHeight: parent.height(),
parentOffset: parent.offset()
};
this.dragStart = true;
this.currCoords.x = e.pageX;
this.currCoords.y = e.pageY;
this._startCoordsDiff(e);
},
_drag: function (e) {
if( this.dragStart ) {
this.currCoords.x = e.pageX;
this.currCoords.y = e.pageY;
var left = this.currCoords.x - this.startCoords.x - this.dragElem.parentOffset.left;
var top = this.currCoords.y - this.startCoords.y - this.dragElem.parentOffset.top;
if(left<0) {
left = 0;
}
if(left+this.dragElem.width>=this.dragElem.parentWidth) {
left = this.dragElem.parentWidth-this.dragElem.width;
}
if(top<0) {
top = 0;
}
if(top+this.dragElem.height>this.dragElem.parentHeight) {
top = this.dragElem.parentHeight-this.dragElem.height;
}
this.dragElem.elem.css({
left: left,
top: top
});
this._scroll();
}
},
_dragEnd: function (e) {
if(this.dragStart) {
this.dragElem = null;
this.dragStart = false;
this.startCoords.x = 0;
this.startCoords.y = 0;
this.currCoords.x = null;
this.currCoords.y = null;
}
},
_destroy: function() {
},
_setOption: function(key, value) {
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.dragtile", {
version: "1.0.0",
options: {
},
_create: function(){
var that = this, element = tile = this.element,
area = element.parents('.tile-area'),
tiles = area.find(".tile"),
groups = area.find(".tile-group");
tile.attr("draggable", "true");
addTouchEvents(tile[0]);
tile[0].addEventListener('dragstart', this._dragStart, false);
tile[0].addEventListener('dragend', this._dragEnd, false);
tile.on('mousedown', function(e){
});
tile.on('mouseup', function(e){
});
},
_dragStart: function(e){
$(this).css('opacity',.4);
},
_dragEnd: function(e){
$(this).css('opacity',1);
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.slider", {
version: "1.0.0",
options: {
position: 0,
accuracy: 0,
color: 'default',
completeColor: 'default',
markerColor: 'default',
colors: [],
showHint: false,
change: function(value, slider){},
changed: function(value, slider){},
_slider: {
vertical: false,
offset: 0,
length: 0,
marker: 0,
ppp: 0,
start: 0,
stop: 0
}
},
_create: function(){
var that = this,
element = this.element,
o = this.options,
s = this.options._slider;
if (element.data('accuracy') != undefined) {
o.accuracy = element.data('accuracy') > 0 ? element.data('accuracy') : 0;
}
if (element.data('position') != undefined) {
o.position = this._correctValue(element.data('position') > 0 ? (element.data('position') > 100 ? 100 : element.data('position')) : 0);
}
if (element.data('color') != undefined) {
o.color = element.data('color');
}
if (element.data('completeColor') != undefined) {
o.completeColor = element.data('completeColor');
}
if (element.data('markerColor') != undefined) {
o.markerColor = element.data('markerColor');
}
if (element.data('colors') != undefined) {
o.colors = element.data('colors').split(",");
}
if (element.data('showHint') != undefined) {
o.showHint = element.data('showHint');
}
s.vertical = element.hasClass("vertical");
this._createSlider();
this._initPoints();
this._placeMarker(o.position);
addTouchEvents(element[0]);
element.children('.marker').on('mousedown', function (e) {
e.preventDefault();
that._startMoveMarker(e);
});
element.on('mousedown', function (e) {
e.preventDefault();
that._startMoveMarker(e);
});
},
_startMoveMarker: function(e){
var element = this.element, o = this.options, that = this, hint = element.children('.hint');
$(element).on('mousemove', function (event) {
that._movingMarker(event);
if (!element.hasClass('permanent-hint')) {
hint.css('display', 'block');
}
});
$(element).on('mouseup', function () {
$(element).off('mousemove');
element.off('mouseup');
element.data('value', that.options.position);
element.trigger('changed', that.options.position);
o.changed(that.options.position, element);
if (!element.hasClass('permanent-hint')) {
hint.css('display', 'none');
}
});
this._initPoints();
this._movingMarker(e)
},
_movingMarker: function (event) {
var cursorPos,
percents,
valuePix,
vertical = this.options._slider.vertical,
sliderOffset = this.options._slider.offset,
sliderStart = this.options._slider.start,
sliderEnd = this.options._slider.stop,
sliderLength = this.options._slider.length,
markerSize = this.options._slider.marker;
if (vertical) {
cursorPos = event.pageY - sliderOffset;
} else {
cursorPos = event.pageX - sliderOffset;
}
if (cursorPos < sliderStart) {
cursorPos = sliderStart;
} else if (cursorPos > sliderEnd) {
cursorPos = sliderEnd;
}
if (vertical) {
valuePix = sliderLength - cursorPos - markerSize / 2;
} else {
valuePix = cursorPos - markerSize / 2;
}
percents = this._pixToPerc(valuePix);
this._placeMarker(percents);
this.options.position = percents;
this.options.change(Math.round(percents), this.element);
},
_placeMarker: function (value) {
var size, size2, o = this.options, colorParts = 0, colorIndex = 0, colorDelta = 0,
marker = this.element.children('.marker'),
complete = this.element.children('.complete'),
hint = this.element.children('.hint');
colorParts = o.colors.length;
colorDelta = o._slider.length / colorParts;
if (this.options._slider.vertical) {
size = this._percToPix(value) + this.options._slider.marker;
size2 = this.options._slider.length - size;
marker.css('top', size2);
complete.css('height', size);
if (colorParts) {
colorIndex = Math.round(size / colorDelta)-1;
complete.css('background-color', o.colors[colorIndex<0?0:colorIndex]);
}
if (o.showHint) {
hint.html(Math.round(value)).css('top', size2 - hint.height()/2);
}
} else {
size = this._percToPix(value);
marker.css('left', size);
complete.css('width', size);
if (colorParts) {
colorIndex = Math.round(size / colorDelta)-1;
complete.css('background-color', o.colors[colorIndex<0?0:colorIndex]);
}
if (o.showHint) {
hint.html(Math.round(value)).css('left', size - hint.width()/2);
}
}
},
_pixToPerc: function (valuePix) {
var valuePerc;
valuePerc = valuePix * this.options._slider.ppp;
return this._correctValue(valuePerc);
},
_percToPix: function (value) {
if (this.options._slider.ppp === 0) {
return 0;
}
return value / this.options._slider.ppp;
},
_correctValue: function (value) {
var accuracy = this.options.accuracy;
if (accuracy === 0) {
return value;
}
if (value === 100) {
return 100;
}
value = Math.floor(value / accuracy) * accuracy + Math.round(value % accuracy / accuracy) * accuracy;
if (value > 100) {
return 100;
}
return value;
},
_initPoints: function(){
var s = this.options._slider, element = this.element;
if (s.vertical) {
s.offset = element.offset().top;
s.length = element.height();
s.marker = element.children('.marker').height();
} else {
s.offset = element.offset().left;
s.length = element.width();
s.marker = element.children('.marker').width();
}
s.ppp = 100 / (s.length - s.marker);
s.start = s.marker / 2;
s.stop = s.length - s.marker / 2;
},
_createSlider: function(){
var element = this.element,
options = this.options,
complete, marker, hint;
element.html('');
complete = $("<div/>").addClass("complete").appendTo(element);
marker = $("<a/>").addClass("marker").appendTo(element);
if (options.showHint) {
hint = $("<span/>").addClass("hint").appendTo(element);
}
if (options.color != 'default') {
element.css('background-color', options.color);
}
if (options.completeColor != 'default') {
complete.css('background-color', options.completeColor);
}
if (options.markerColor != 'default') {
marker.css('background-color', options.markerColor);
}
},
value: function (value) {
if (typeof value !== 'undefined') {
this._placeMarker(parseInt(value));
this.options.position = parseInt(value);
this.options.change(Math.round(parseInt(value)), this.element);
return this;
} else {
return Math.round(this.options.position);
}
},
_destroy: function(){},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function($){
/*
* Init or ReInit components
* */
$.Metro.initAccordions = function(area){
if (area != undefined) {
$(area).find('[data-role=accordion]').accordion();
} else {
$('[data-role=accordion]').accordion();
}
};
$.Metro.initButtonSets = function(area){
if (area != undefined) {
$(area).find('[data-role=button-set]').buttonset();
$(area).find('[data-role=button-group]').buttongroup();
} else {
$('[data-role=button-set]').buttonset();
$('[data-role=button-group]').buttongroup();
}
};
$.Metro.initCalendars = function(area){
if (area != undefined) {
$(area).find('[data-role=calendar]').calendar();
} else {
$('[data-role=calendar]').calendar();
}
};
$.Metro.initCarousels = function(area){
if (area != undefined) {
$(area).find('[data-role=carousel]').carousel();
} else {
$('[data-role=carousel]').carousel();
}
};
$.Metro.initCountdowns = function(area){
if (area != undefined) {
$(area).find('[data-role=countdown]').countdown();
} else {
$('[data-role=countdown]').countdown();
}
};
$.Metro.initDatepickers = function(area){
if (area != undefined) {
$(area).find('[data-role=datepicker]').datepicker();
} else {
$('[data-role=datepicker]').datepicker();
}
};
$.Metro.initDropdowns = function(area){
if (area != undefined) {
$(area).find('[data-role=dropdown]').dropdown();
} else {
$('[data-role=dropdown]').dropdown();
}
};
$.Metro.initFluentMenus = function(area){
if (area != undefined) {
$(area).find('[data-role=fluentmenu]').fluentmenu();
} else {
$('[data-role=fluentmenu]').fluentmenu();
}
};
$.Metro.initHints = function(area){
if (area != undefined) {
$(area).find('[data-hint]').hint();
} else {
$('[data-hint]').hint();
}
};
$.Metro.initInputs = function(area){
if (area != undefined) {
$(area).find('[data-role=input-control], .input-control').inputControl();
} else {
$('[data-role=input-control], .input-control').inputControl();
}
};
$.Metro.transformInputs = function(area){
if (area != undefined) {
$(area).find('[data-transform=input-control]').inputTransform();
} else {
$('[data-transform=input-control]').inputTransform();
}
};
$.Metro.initListViews = function(area){
if (area != undefined) {
$(area).find('[data-role=listview]').listview();
} else {
$('[data-role=listview]').listview();
}
};
$.Metro.initLives = function(area){
if (area != undefined) {
$(area).find('[data-role=live-tile], [data-role=live]').livetile();
} else {
$('[data-role=live-tile], [data-role=live]').livetile();
}
};
$.Metro.initProgreeBars = function(area){
if (area != undefined) {
$(area).find('[data-role=progress-bar]').progressbar();
} else {
$('[data-role=progress-bar]').progressbar();
}
};
$.Metro.initRatings = function(area){
if (area != undefined) {
$(area).find('[data-role=rating]').rating();
} else {
$('[data-role=rating]').rating();
}
};
$.Metro.initScrolls = function(area){
if (area != undefined) {
$(area).find('[data-role=scrollbox]').scrollbar();
} else {
$('[data-role=scrollbox]').scrollbar();
}
};
$.Metro.initSliders = function(area){
if (area != undefined) {
$(area).find('[data-role=slider]').slider();
} else {
$('[data-role=slider]').slider();
}
};
$.Metro.initTabs = function(area){
if (area != undefined) {
$(area).find('[data-role=tab-control]').tabcontrol();
} else {
$('[data-role=tab-control]').tabcontrol();
}
};
$.Metro.initTimes = function(area){
if (area != undefined) {
$(area).find('[data-role=times]').times();
} else {
$('[data-role=times]').times();
}
};
$.Metro.initTrees = function(area){
if (area != undefined) {
$(area).find('[data-role=treeview]').treeview();
} else {
$('[data-role=treeview]').treeview();
}
};
/*
* Components in develop
* */
$.Metro.initSteppers = function(area){
if (area != undefined) {
$(area).find('[data-role=stepper]').stepper();
} else {
$('[data-role=stepper]').stepper();
}
};
$.Metro.initStreamers = function(area){
if (area != undefined) {
$(area).find('[data-role=streamer]').streamer();
} else {
$('[data-role=streamer]').streamer();
}
};
$.Metro.initDragTiles = function(area){
if (area != undefined) {
$(area).find('[data-role=drag-drop]').dragtile();
} else {
$('[data-role=drag-drop]').dragtile();
}
};
$.Metro.initPulls = function(area){
if (area != undefined) {
$(area).find('[data-role=pull-menu], .pull-menu').pullmenu();
} {
$('[data-role=pull-menu], .pull-menu').pullmenu();
}
};
$.Metro.initAll = function(area) {
$.Metro.initAccordions(area);
$.Metro.initButtonSets(area);
$.Metro.initCalendars(area);
$.Metro.initCarousels(area);
$.Metro.initCountdowns(area);
$.Metro.initDatepickers(area);
$.Metro.initDropdowns(area);
$.Metro.initFluentMenus(area);
$.Metro.initHints(area);
$.Metro.initInputs(area);
$.Metro.transformInputs(area);
$.Metro.initListViews(area);
$.Metro.initLives(area);
$.Metro.initProgreeBars(area);
$.Metro.initRatings(area);
$.Metro.initScrolls(area);
$.Metro.initSliders(area);
$.Metro.initTabs(area);
$.Metro.initTimes(area);
$.Metro.initTrees(area);
$.Metro.initSteppers(area);
$.Metro.initStreamers(area);
$.Metro.initDragTiles(area);
$.Metro.initPulls(area);
}
})(jQuery);
$(function(){
$.Metro.initAll();
}); | JavaScript |
(function($){
$.Metro = function(params){
params = $.extend({
}, params);
};
})(jQuery);
$(function(){
$('html').on('click', function(e){
$('.dropdown-menu').each(function(i, el){
if (!$(el).hasClass('keep-open') && $(el).css('display')=='block') {
$(el).hide();
}
});
});
});
$(function(){
$(window).on('resize', function(){
if (METRO_DIALOG) {
var top = ($(window).height() - METRO_DIALOG.outerHeight()) / 2;
var left = ($(window).width() - METRO_DIALOG.outerWidth()) / 2;
METRO_DIALOG.css({
top: top, left: left
});
}
});
}); | JavaScript |
(function( $ ) {
$.widget("metro.streamer", {
version: "1.0.0",
options: {
scrollBar: false,
meter: {
start: 9,
stop: 19,
interval: 20
},
slideToGroup: 1,
slideToTime: "10:20",
slideSleep: 1000,
slideSpeed: 1000,
onClick: function(event){},
onLongClick: function(event){}
},
_create: function(){
var that = this, element = this.element, o = this.options,
streams = element.find(".stream"),
events = element.find(".event"),
events_container = element.find(".events"),
events_area = element.find(".events-area"),
groups = element.find(".event-group"),
event_streams = element.find(".event-stream");
if (element.data('scrollBar') != undefined) o.scrollBar = element.data('scrollBar');
if (element.data('meterStart') != undefined) o.meter.start = parseInt(element.data('meterStart'));
if (element.data('meterStop') != undefined) o.meter.stop = parseInt(element.data('meterStop'));
if (element.data('meterInterval') != undefined) o.meter.interval = element.data('meterInterval');
if (element.data('slideToGroup') != undefined) o.slideToGroup = parseInt(element.data('slideToGroup'));
if (element.data('slideSleep') != undefined) o.slideSleep = parseInt(element.data('slideSleep'));
if (element.data('slideSpeed') != undefined) o.slideSpeed = parseInt(element.data('slideSpeed'));
element.data('streamSelect', -1);
var meter = $("<ul/>").addClass("meter");
var i, j, m, start = o.meter.start, stop = o.meter.stop, interval = o.meter.interval;
var _intervals = [];
for (i = start; i<stop; i++) {
for (j = 0; j < 60; j+=interval) {
m = (i<10?"0"+i:i)+":"+(j<10?"0"+j:j);
$("<li/>").addClass("js-interval-"+ m.replace(":", "-")).html("<em>"+m+"</em>").appendTo(meter);
_intervals.push(m);
}
}
element.data("intervals", _intervals);
meter.insertBefore(element.find(".events-grid"));
//console.log(element.data("intervals"));
// Re-Calc all event-stream width and set background for time
element.find(".event-stream").each(function(i, s){
var event_stream_width = 0;
var events = $(s).find(".event");
events.each(function(i, el){
event_stream_width += $(el).outerWidth();
});
$(s).css({
width: (event_stream_width + ( (events.length-1) * 2 ) + 1)
});
$(s).find(".time").css("background-color", $(streams[i]).css('background-color'));
});
// Set scrollbar
events_container.css({
'overflow-x': (o.scrollBar ? 'scroll' : 'hidden')
});
// Set streamer height
element.css({
height: element.find(".streams").outerHeight() + (o.scrollBar ? 20 : 0)
});
// Re-Calc events-area width
var events_area_width = 0;
groups.each(function(i, el){
events_area_width += $(el).outerWidth();
});
events_area_width += ( (groups.length-1) * 2 ) + 10;
events_area.css('width', events_area_width);
events.each(function(i, el){
addTouchEvents(el);
});
events.mousedown(function(e){
if (e.altKey) {
$(this).toggleClass("selected");
}
});
element.mousewheel(function(event, delta){
var scroll_value = delta * 50;
events_container.scrollLeft(events_container.scrollLeft() - scroll_value);
return false;
});
streams.each(function(i, s){
$(s).mousedown(function(e){
if (element.data('streamSelect') == i) {
events.removeClass('event-disable');
element.data('streamSelect', -1);
} else {
element.data('streamSelect', i);
events.addClass('event-disable');
$(event_streams[i]).find(".event").removeClass("event-disable");
}
});
});
events.on('click', function(e){
e.preventDefault();
o.onClick($(this));
});
events.on('longclick', function(e){
$(this).toggleClass("selected");
e.preventDefault();
o.onLongClick($(this));
});
element.find(".js-go-previous-time").on('click', function(e){
var next_index = element.data("intervals").indexOf(element.data("current-time"));
if (next_index == 0) {
return;
}
next_index--;
var new_time = element.data("intervals")[next_index];
that.slideToTime(new_time, 0, o.slideSpeed);
});
element.find(".js-go-next-time").on('click', function(e){
var next_index = element.data("intervals").indexOf(element.data("current-time"));
if (next_index == element.data("intervals").length - 1) {
return;
}
next_index++;
var new_time = element.data("intervals")[next_index];
that.slideToTime(new_time, 0, o.slideSpeed);
});
element.find(".js-show-all-streams").on("click", function(e){
element.find(".event").removeClass("event-disable");
element.data('streamSelect', -1);
e.preventDefault();
});
element.find(".js-schedule-mode").on("click", function(e){
$(this).toggleClass("inverse");
element.data("schedule-mode", $(this).hasClass("inverse"));
e.preventDefault();
});
if (o.slideToTime) {
this.slideToTime(o.slideToTime, o.slideSleep, o.slideSpeed);
} else {
this.slideToGroup(o.slideToGroup, o.slideSleep, o.slideSpeed);
}
},
slideToTime: function(time, sleep, speed){
var that = this, element = this.element,
interval = element.find(".meter li.js-interval-"+time.replace(":", "-"))[0],
streams_width = element.find(".streams").outerWidth() + 2;
setTimeout(function(){
element.find(".events").animate({
scrollLeft: "+="+ (interval.offsetLeft - streams_width)
}, speed, function(){
that._afterSlide();
});
}, sleep);
element.data("current-time", time);
},
slideToGroup: function(group, sleep, speed){
var that = this, element = this.element, groups = element.find(".event-group"), streams_width = element.find(".streams").outerWidth() + 2;
setTimeout(function(){
element.find(".events").animate({
scrollLeft: "+="+ (groups[group-1].offsetLeft - streams_width)
}, speed, function(){
that._afterSlide();
});
}, sleep);
},
_afterSlide: function(){
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function($){
$.Metro.currentLocale = 'en';
if (METRO_LOCALE != undefined) $.Metro.currentLocale = METRO_LOCALE; else $.Metro.currentLocale = 'en';
//console.log(METRO_LOCALE, $.Metro.currentLocale);
$.Metro.Locale = {
'en': {
months: [
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December",
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
],
days: [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"
],
buttons: [
"Today", "Clear"
]
},
'fr': {
months: [
"Janvier", "Février", "Mars", "Avril", "Peut", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre",
"Jan", "Fév", "Mar", "Avr", "Peu", "Jun", "Jul", "Aoû", "Sep", "Oct", "Nov", "Déc"
],
days: [
"Sunday", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi",
"Sn", "Ln", "Md", "Mc", "Ju", "Vn", "Sm"
],
buttons: [
"Aujourd", "Effacer"
]
},
'ua': {
months: [
"Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень",
"Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"
],
days: [
"Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П’ятниця", "Субота",
"Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
],
buttons: [
"Сьогодні", "Очистити"
]
},
'ru': {
months: [
"Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь",
"Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"
],
days: [
"Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота",
"Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
],
buttons: [
"Сегодня", "Очистить"
]
},
/** By NoGrief (nogrief@gmail.com) */
'zhCN': {
months: [
"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月",
"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
],
days: [
"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六",
"日", "一", "二", "三", "四", "五", "六"
],
buttons: [
"今日", "清除"
]
},
'it': {
months: [
'Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre',
'Gen',' Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'
],
days: [
'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato', 'Domenica',
'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'
],
buttons: [
"Oggi", "Cancella"
]
},
'de': {
months: [
"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember",
"Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"
],
days: [
"Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag",
"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
],
buttons: [
"Heute", "zurücksetzten"
]
},
/** By Javier Rodríguez (javier.rodriguez at fjrodriguez.com) */
'es': {
months: [
"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre",
"Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sept", "Oct", "Nov", "Dic"
],
days: [
"Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado",
"Do", "Lu", "Mar", "Mié", "Jue", "Vi", "Sáb"
],
buttons: [
"Hoy", "Limpiar"
]
}
};
$.Metro.setLocale = function(locale, data){
$.Metro.Locale[locale] = data;
};
})(jQuery); | JavaScript |
(function( $ ) {
$.widget("metro.hint", {
version: "1.0.0",
options: {
position: "bottom",
background: '#FFFCC0',
shadow: false,
border: false,
_hint: undefined
},
_create: function(){
var that = this;
var o = this.options;
this.element.on('mouseenter', function(e){
that.createHint();
o._hint.stop().fadeIn();
e.preventDefault();
});
this.element.on('mouseleave', function(e){
o._hint.stop().fadeOut(function(){
o._hint.remove();
});
e.preventDefault();
});
},
createHint: function(){
var that = this, element = this.element,
hint = element.data('hint').split("|"),
o = this.options;
var _hint;
if (element.data('hintPosition') != undefined) o.position = element.data('hintPosition');
if (element.data('hintBackground') != undefined) o.background = element.data('hintBackground');
if (element.data('hintShadow') != undefined) o.shadow = element.data('hintShadow');
if (element.data('hintBorder') != undefined) o.border = element.data('hintBorder');
if (element[0].tagName == 'TD' || element[0].tagName == 'TH') {
var wrp = $("<div/>").css("display", "inline-block").html(element.html());
element.html(wrp);
element = wrp;
}
var hint_title = hint.length > 1 ? hint[0] : false;
var hint_text = hint.length > 1 ? hint[1] : hint[0];
//_hint = $("<div/>").addClass("hint").appendTo(element.parent());
_hint = $("<div/>").addClass("hint").appendTo('body');
if (hint_title) {
$("<div/>").addClass("hint-title").html(hint_title).appendTo(_hint);
}
$("<div/>").addClass("hint-text").html(hint_text).appendTo(_hint);
_hint.addClass(o.position);
if (o.shadow) _hint.addClass("shadow");
if (o.background) {_hint.css("background-color", o.background);}
if (o.border) _hint.css("border-color", o.border);
//console.log(_hint);
if (o.position == 'top') {
_hint.css({
top: element.offset().top - $(window).scrollTop() - _hint.outerHeight() - 20,
left: element.offset().left - $(window).scrollLeft()
});
} else if (o.position == 'bottom') {
_hint.css({
top: element.offset().top - $(window).scrollTop() + element.outerHeight(),
left: element.offset().left - $(window).scrollLeft()
});
} else if (o.position == 'right') {
_hint.css({
top: element.offset().top - 10 - $(window).scrollTop(),
left: element.offset().left + element.outerWidth() + 10 - $(window).scrollLeft()
});
} else if (o.position == 'left') {
_hint.css({
top: element.offset().top - 10 - $(window).scrollTop(),
left: element.offset().left - _hint.outerWidth() - 10 - $(window).scrollLeft()
});
}
o._hint = _hint;
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.pullmenu", {
version: "1.0.0",
options: {
},
_create: function(){
var that = this,
element = this.element;
var menu = (element.data("relation") != undefined) ? element.data("relation") : element.parent().children(".element-menu, .horizontal-menu");
addTouchEvents(element[0]);
element.on("click", function(e){
menu.slideToggle();
e.preventDefault();
e.stopPropagation();
});
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
$(window).resize(function(){
var device_width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
if (device_width > 800) {$(".element-menu").show();} else {$(".element-menu").hide();}
});
| JavaScript |
(function( $ ) {
$.widget("metro.tabcontrol", {
version: "1.0.0",
options: {
effect: 'none',
activateStoredTab: false,
tabclick: function(tab){},
tabchange: function(tab){}
},
_create: function(){
var that = this,
element = this.element,
tabs = $(element.children(".tabs")).children("li"),
frames = $(element.children(".frames")).children(".frame"),
element_id = element.attr("id");
if (element.data('effect') != undefined) {
this.options.effect = element.data('effect');
}
this.init(tabs, frames);
tabs.each(function(){
var tab = $(this).children("a");
tab.on('click', function(e){
e.preventDefault();
that.options.tabclick(this);
if ($(this).parent().hasClass('disabled')) {
return false;
}
tabs.removeClass("active");
tab.parent("li").addClass("active");
frames.hide();
var current_frame = $(tab.attr("href"));
switch (that.options.effect) {
case 'slide': current_frame.slideDown(); break;
case 'fade': current_frame.fadeIn(); break;
default: current_frame.show();
}
that._trigger('change', null, current_frame);
that.options.tabchange(this);
if (element_id != undefined) window.localStorage.setItem(element_id+"-current-tab", $(this).attr("href"));
});
});
if (this.options.activateStoredTab) this._activateStoredTab(tabs);
},
init: function(tabs, frames){
var that = this;
tabs.each(function(){
if ($(this).hasClass("active")) {
var current_frame = $($($(this).children("a")).attr("href"));
frames.hide();
current_frame.show();
that._trigger('change', null, current_frame);
}
});
},
_activateStoredTab: function(tabs){
var current_stored_tab = window.localStorage.getItem(this.element.attr('id')+'-current-tab');
if (current_stored_tab != undefined) {
tabs.each(function(){
var a = $(this).children("a");
if (a.attr("href") == current_stored_tab) {
a.click();
}
});
}
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
var METRO_LOCALE;
var METRO_WEEK_START;
var METRO_DIALOG = false;
var METRO_HINT = {
position: top,
background: '#fff',
shadow: true,
border: 'default'
}; | JavaScript |
(function( $ ) {
$.widget("metro.fluentmenu", {
version: "1.0.0",
options: {
onSpecialClick: function(e, el){},
onTabClick: function(e, el){}
},
_create: function(){
var that = this, element = this.element, o = this.options,
tabs = element.find('.tabs-holder > li > a');
this._hidePanels();
this._showPanel();
tabs.on('click', function(e){
if ($(this).parent('li').hasClass('special')) {
o.onSpecialClick(e, $(this));
} else {
var panel = $($(this).attr('href'));
that._hidePanels();
that._showPanel(panel);
element.find('.tabs-holder > li').removeClass('active');
$(this).parent('li').addClass('active');
o.onTabClick(e, $(this));
}
e.preventDefault();
});
},
_hidePanels: function(){
this.element.find('.tab-panel').hide();
},
_showPanel: function(panel){
if (panel == undefined) {
panel = this.element.find('.tabs-holder li.active a').attr('href');
}
$(panel).show();
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.inputControl", {
version: "1.0.0",
options: {
},
_create: function(){
var that = this,
control = this.element;
if (control.hasClass('text')) {
this.initTextInput(control, that);
} else if (control.hasClass('password')) {
this.initPasswordInput(control, that);
} else if (control.hasClass('checkbox') || control.hasClass('radio') || control.hasClass('switch')) {
this.initCheckboxInput(control, that);
} else if (control.hasClass('file')) {
this.initFileInput(control, that);
}
},
initCheckboxInput: function(el, that) {
},
initFileInput: function(el, that){
var button, input, wrapper;
wrapper = $("<input type='text' id='__input_file_wrapper__' readonly style='z-index: 1; cursor: default;'>");
button = el.children('.btn-file');
input = el.children('input[type="file"]');
input.css('z-index', 0);
wrapper.insertAfter(input);
input.attr('tabindex', '-1');
//button.attr('tabindex', '-1');
button.attr('type', 'button');
input.on('change', function(){
var val = $(this).val();
if (val != '') {
wrapper.val(val);
}
});
button.on('click', function(){
input.trigger('click');
});
},
initTextInput: function(el, that){
var button = el.children('.btn-clear'),
input = el.children('input[type=text]');
//console.log(button.length);
//button = el.children('.btn-clear');
if (button.length == 0) return;
button.attr('tabindex', '-1');
button.attr('type', 'button');
button.on('click', function(){
input = el.children('input');
if (input.prop('readonly')) return;
input.val('');
input.focus();
that._trigger("onClear", null, el);
});
if (!input.attr("disabled")) input.on('click', function(){$(this).focus();});
},
initPasswordInput: function(el, that){
var button = el.children('.btn-reveal'),
input = el.children('input[type=password]');
var wrapper;
if (button.length == 0) return;
button.attr('tabindex', '-1');
button.attr('type', 'button');
button.on('mousedown', function(e){
input.attr('type', 'text');
//e.preventDefault();
// wrapper = el.find(".__wrapper__").length == 0 ? $('<input type="text" class="__wrapper__" />') : el.find(".__wrapper__");
//
// input.hide();
// wrapper.appendTo(that.element);
// wrapper.val(input.val());
//
// that._trigger("onPasswordShow", null, that.element);
});
button.on('mouseup, mouseleave, blur', function(e){
input.attr('type', 'password').focus();
//e.preventDefault();
// input.show().focus();
// wrapper.remove();
//
// that._trigger("onPasswordHide", null, that.element);
});
if (!input.attr("disabled")) input.on('click', function(){$(this).focus();});
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
});
})( jQuery );
(function( $ ) {
$.widget("metro.inputTransform", {
version: "1.0.0",
options: {
transformType: "text"
},
_create: function(){
var that = this,
element = this.element,
inputType;
var checkTransform = element.parent().hasClass("input-control");
if (checkTransform) return;
inputType = element.get(0).tagName.toLowerCase();
if (inputType == "textarea") {
this.options.transformType = "textarea";
} else if (inputType == "select") {
this.options.transformType = "select";
} else {
if (element.data('transformType') != undefined) {
this.options.transformType = element.data('transformType');
} else {
this.options.transformType = element.attr("type");
}
}
var control = undefined;
switch (this.options.transformType) {
case "password": control = this._createInputPassword(); break;
case "file": control = this._createInputFile(); break;
case "checkbox": control = this._createInputCheckbox(); break;
case "radio": control = this._createInputRadio(); break;
case "switch": control = this._createInputSwitch(); break;
case "select": control = this._createInputSelect(); break;
case "textarea": control = this._createInputTextarea(); break;
case "search": control = this._createInputSearch(); break;
case "email": control = this._createInputEmail(); break;
case "tel": control = this._createInputTel(); break;
default: control = this._createInputText();
}
control.inputControl();
},
_createInputTextarea: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("textarea");
var clone = element.clone(true);
var parent = element.parent();
clone.appendTo(wrapper);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputSelect: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("select");
var clone = element.clone(true);
var parent = element.parent();
clone.val(element.val()).appendTo(wrapper);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputSwitch: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("switch");
var label = $("<label/>");
var button = $("<span/>").addClass("check");
var clone = element.clone(true);
var parent = element.parent();
var caption = $("<span/>").addClass("caption").html( element.data('caption') != undefined ? element.data('caption') : "" );
label.appendTo(wrapper);
clone.appendTo(label);
button.appendTo(label);
caption.appendTo(label);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputCheckbox: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("checkbox");
var label = $("<label/>");
var button = $("<span/>").addClass("check");
var clone = element.clone(true);
var parent = element.parent();
var caption = $("<span/>").addClass("caption").html( element.data('caption') != undefined ? element.data('caption') : "" );
label.appendTo(wrapper);
clone.appendTo(label);
button.appendTo(label);
caption.appendTo(label);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputRadio: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("radio");
var label = $("<label/>");
var button = $("<span/>").addClass("check");
var clone = element.clone(true);
var parent = element.parent();
var caption = $("<span/>").addClass("caption").html( element.data('caption') != undefined ? element.data('caption') : "" );
label.appendTo(wrapper);
clone.appendTo(label);
button.appendTo(label);
caption.appendTo(label);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputSearch: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("text");
var button = $("<button/>").addClass("btn-search");
var clone = element.clone(true);
var parent = element.parent();
clone.appendTo(wrapper);
button.appendTo(wrapper);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputTel: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("tel");
var button = $("<button/>").addClass("btn-clear");
var clone = element.clone(true);
var parent = element.parent();
clone.appendTo(wrapper);
button.appendTo(wrapper);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputEmail: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("email");
var button = $("<button/>").addClass("btn-clear");
var clone = element.clone(true);
var parent = element.parent();
clone.appendTo(wrapper);
button.appendTo(wrapper);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputText: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("text");
var button = $("<button/>").addClass("btn-clear");
var clone = element.clone(true);
var parent = element.parent();
clone.appendTo(wrapper);
button.appendTo(wrapper);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputPassword: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("password");
var button = $("<button/>").addClass("btn-reveal");
var clone = element.clone(true);
var parent = element.parent();
clone.appendTo(wrapper);
button.appendTo(wrapper);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_createInputFile: function(){
var element = this.element;
var wrapper = $("<div/>").addClass("input-control").addClass("file");
var button = $("<button/>").addClass("btn-file");
var clone = element.clone(true);
var parent = element.parent();
clone.appendTo(wrapper);
button.appendTo(wrapper);
wrapper.insertBefore(element);
element.remove();
return wrapper;
},
_destroy: function(){},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.progressbar", {
version: "1.0.0",
options: {
value: 0,
color: "bg-cyan",
animate: false,
onchange: function(val){}
},
_create: function(){
var that = this,
element = this.element;
if (element.data('value') != undefined) {
this.value(element.data('value')+'%');
}
if (element.data('color') != undefined) {
this.options.color = element.data('color');
}
if (element.data('animate') != undefined) {
this.options.animate = element.data('animate');
}
this._showBar();
},
_showBar: function(){
var element = this.element;
element.html('');
var bar = $("<div />");
bar.addClass("bar");
if (this.options.color.indexOf("bg-")+1)
bar.addClass(this.options.color);
else {
bar.css('background', this.options.color);
}
bar.appendTo(element);
if (this.options.animate) {
bar.animate({width: this.value()+'%'});
} else {
bar.css('width', this.value()+'%');
}
this.options.onchange(this.value());
},
value: function(val){
if (val != undefined) {
this.options.value = parseInt(val);
this._showBar();
} else {
return parseInt(this.options.value);
}
},
color: function(color){
this.options.color = color;
if (this.options.color.indexOf("bg-")+1)
this.element.find(".bar").addClass(this.options.color);
else {
this.element.find(".bar").css('background', this.options.color);
}
this._showBar();
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.listview", {
version: "1.0.0",
options: {
onGroupExpand: function(g){},
onGroupCollapse: function(g){},
onListClick: function(l){}
},
_create: function(){
var that = this, element = this.element;
element.children('.collapsed').children('.group-content').hide();
element.find('.group-title').on('click', function(e){
var $this = $(this),
group = $this.parent('.list-group'),
group_content = group.children('.group-content');
group.toggleClass('collapsed');
if (group.hasClass('collapsed')) {
group_content.slideUp();
that.options.onGroupCollapse(group);
} else {
group_content.slideDown();
that.options.onGroupExpand(group);
}
e.preventDefault();
});
element.find('.list').on('click', function(e){
element.find('.list').removeClass('active');
$(this).toggleClass('active');
that.options.onListClick($(this));
e.preventDefault();
});
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
// Calendar
(function( $ ) {
$.widget("metro.calendar", {
version: "1.0.0",
options: {
format: "yyyy-mm-dd",
multiSelect: false,
startMode: 'day', //year, month, day
weekStart: (METRO_WEEK_START != undefined ? METRO_WEEK_START : 0), // 0 - Sunday, 1 - Monday
otherDays: false,
date: new Date(),
buttons: true,
locale: $.Metro.currentLocale,
getDates: function(d){},
click: function(d, d0){},
_storage: []
},
_year: 0,
_month: 0,
_day: 0,
_today: new Date(),
_event: '',
_mode: 'day', // day, month, year
_distance: 0,
_events: [],
_create: function(){
var element = this.element;
if (element.data('multiSelect') != undefined) this.options.multiSelect = element.data("multiSelect");
if (element.data('format') != undefined) this.options.format = element.data("format");
if (element.data('date') != undefined) this.options.date = new Date(element.data("date"));
if (element.data('locale') != undefined) this.options.locale = element.data("locale");
if (element.data('startMode') != undefined) this.options.startMode = element.data('startMode');
if (element.data('weekStart') != undefined) this.options.weekStart = element.data('weekStart');
if (element.data('otherDays') != undefined) this.options.otherDays = element.data('otherDays');
this._year = this.options.date.getFullYear();
this._distance = parseInt(this.options.date.getFullYear())-4;
this._month = this.options.date.getMonth();
this._day = this.options.date.getDate();
this._mode = this.options.startMode;
element.data("_storage", []);
this._renderCalendar();
},
_renderMonth: function(){
var year = this._year,
month = this._month,
day = this._day,
event = this._event,
feb = 28;
if (month == 1) {
if ((year%100!=0) && (year%4==0) || (year%400==0)) {
feb = 29;
}
}
var totalDays = ["31", ""+feb+"","31","30","31","30","31","31","30","31","30","31"];
var daysInMonth = totalDays[month];
var first_week_day = new Date(year, month, 1).getDay();
var table, tr, td, i;
this.element.html("");
table = $("<table/>").addClass("bordered");
// Add calendar header
tr = $("<tr/>");
$("<td/>").addClass("text-center").html("<a class='btn-previous-year' href='#'><i class='icon-previous'></i></a>").appendTo(tr);
$("<td/>").addClass("text-center").html("<a class='btn-previous-month' href='#'><i class='icon-arrow-left-4'></i></a>").appendTo(tr);
$("<td/>").attr("colspan", 3).addClass("text-center").html("<a class='btn-select-month' href='#'>"+ $.Metro.Locale[this.options.locale].months[month]+' '+year+"</a>").appendTo(tr);
$("<td/>").addClass("text-center").html("<a class='btn-next-month' href='#'><i class='icon-arrow-right-4'></i></a>").appendTo(tr);
$("<td/>").addClass("text-center").html("<a class='btn-next-year' href='#'><i class='icon-next'></i></a>").appendTo(tr);
tr.addClass("calendar-header").appendTo(table);
// Add day names
var j;
tr = $("<tr/>");
for(i = 0; i < 7; i++) {
if (!this.options.weekStart)
td = $("<td/>").addClass("text-center day-of-week").html($.Metro.Locale[this.options.locale].days[i+7]).appendTo(tr);
else {
j = i + 1;
if (j == 7) j = 0;
td = $("<td/>").addClass("text-center day-of-week").html($.Metro.Locale[this.options.locale].days[j+7]).appendTo(tr);
}
}
tr.addClass("calendar-subheader").appendTo(table);
// Add empty days for previos month
var prevMonth = this._month - 1; if (prevMonth < 0) prevMonth = 11; var daysInPrevMonth = totalDays[prevMonth];
var _first_week_day = ((this.options.weekStart) ? first_week_day + 6 : first_week_day)%7;
var htmlPrevDay = "";
tr = $("<tr/>");
for(i = 0; i < _first_week_day; i++) {
if (this.options.otherDays) htmlPrevDay = daysInPrevMonth - (_first_week_day - i - 1);
td = $("<td/>").addClass("empty").html("<small class='other-day'>"+htmlPrevDay+"</small>").appendTo(tr);
}
var week_day = ((this.options.weekStart) ? first_week_day + 6 : first_week_day)%7;
//console.log(week_day, week_day%7);
for (i = 1; i <= daysInMonth; i++) {
//console.log(week_day, week_day%7);
week_day %= 7;
if (week_day == 0) {
tr.appendTo(table);
tr = $("<tr/>");
}
td = $("<td/>").addClass("text-center day").html("<a href='#'>"+i+"</a>");
if (year == this._today.getFullYear() && month == this._today.getMonth() && this._today.getDate() == i) {
td.addClass("today");
}
var d = (new Date(this._year, this._month, i)).format('yyyy-mm-dd');
if (this.element.data('_storage').indexOf(d)>=0) {
td.find("a").addClass("selected");
}
td.appendTo(tr);
week_day++;
}
// next month other days
var htmlOtherDays = "";
for (i = week_day+1; i<=7; i++){
if (this.options.otherDays) htmlOtherDays = i - week_day;
td = $("<td/>").addClass("empty").html("<small class='other-day'>"+htmlOtherDays+"</small>").appendTo(tr);
}
tr.appendTo(table);
if (this.options.buttons) {
tr = $("<tr/>").addClass("calendar-actions");
td = $("<td/>").attr('colspan', 7).addClass("text-left").html("" +
"<button class='button calendar-btn-today small success'>"+$.Metro.Locale[this.options.locale].buttons[0]+
"</button> <button class='button calendar-btn-clear small warning'>"+$.Metro.Locale[this.options.locale].buttons[1]+"</button>");
td.appendTo(tr);
tr.appendTo(table);
}
table.appendTo(this.element);
this.options.getDates(this.element.data('_storage'));
},
_renderMonths: function(){
var table, tr, td, i, j;
this.element.html("");
table = $("<table/>").addClass("bordered");
// Add calendar header
tr = $("<tr/>");
$("<td/>").addClass("text-center").html("<a class='btn-previous-year' href='#'><i class='icon-arrow-left-4'></i></a>").appendTo(tr);
$("<td/>").attr("colspan", 2).addClass("text-center").html("<a class='btn-select-year' href='#'>"+this._year+"</a>").appendTo(tr);
$("<td/>").addClass("text-center").html("<a class='btn-next-year' href='#'><i class='icon-arrow-right-4'></i></a>").appendTo(tr);
tr.addClass("calendar-header").appendTo(table);
tr = $("<tr/>");
j = 0;
for (i=0;i<12;i++) {
//td = $("<td/>").addClass("text-center month").html("<a href='#' data-month='"+i+"'>"+this.options.monthsShort[i]+"</a>");
td = $("<td/>").addClass("text-center month").html("<a href='#' data-month='"+i+"'>"+$.Metro.Locale[this.options.locale].months[i+12]+"</a>");
if (this._month == i && (new Date()).getFullYear() == this._year) {
td.addClass("today");
}
td.appendTo(tr);
if ((j+1) % 4 == 0) {
tr.appendTo(table);
tr = $("<tr/>");
}
j+=1;
}
table.appendTo(this.element);
},
_renderYears: function(){
var table, tr, td, i, j;
this.element.html("");
table = $("<table/>").addClass("bordered");
// Add calendar header
tr = $("<tr/>");
$("<td/>").addClass("text-center").html("<a class='btn-previous-year' href='#'><i class='icon-arrow-left-4'></i></a>").appendTo(tr);
$("<td/>").attr("colspan", 2).addClass("text-center").html( (this._distance)+"-"+(this._distance+11) ).appendTo(tr);
$("<td/>").addClass("text-center").html("<a class='btn-next-year' href='#'><i class='icon-arrow-right-4'></i></a>").appendTo(tr);
tr.addClass("calendar-header").appendTo(table);
tr = $("<tr/>");
j = 0;
for (i=this._distance;i<this._distance+12;i++) {
td = $("<td/>").addClass("text-center year").html("<a href='#' data-year='"+i+"'>"+i+"</a>");
if ((new Date()).getFullYear() == i) {
td.addClass("today");
}
td.appendTo(tr);
if ((j+1) % 4 == 0) {
tr.appendTo(table);
tr = $("<tr/>");
}
j+=1;
}
table.appendTo(this.element);
},
_renderCalendar: function(){
switch (this._mode) {
case 'year': this._renderYears(); break;
case 'month': this._renderMonths(); break;
default: this._renderMonth();
}
this._initButtons();
},
_initButtons: function(){
// Add actions
var that = this, table = this.element.find('table');
if (this._mode == 'day') {
table.find('.btn-select-month').on('click', function(e){
e.preventDefault();
e.stopPropagation();
that._mode = 'month';
that._renderCalendar();
});
table.find('.btn-previous-month').on('click', function(e){
that._event = 'eventPrevious';
e.preventDefault();
e.stopPropagation();
that._month -= 1;
if (that._month < 0) {
that._year -= 1;
that._month = 11;
}
that._renderCalendar();
});
table.find('.btn-next-month').on('click', function(e){
that._event = 'eventNext';
e.preventDefault();
e.stopPropagation();
that._month += 1;
if (that._month == 12) {
that._year += 1;
that._month = 0;
}
that._renderCalendar();
});
table.find('.btn-previous-year').on('click', function(e){
that._event = 'eventPrevious';
e.preventDefault();
e.stopPropagation();
that._year -= 1;
that._renderCalendar();
});
table.find('.btn-next-year').on('click', function(e){
that._event = 'eventNext';
e.preventDefault();
e.stopPropagation();
that._year += 1;
that._renderCalendar();
});
table.find('.calendar-btn-today').on('click', function(e){
that._event = 'eventNext';
e.preventDefault();
e.stopPropagation();
that.options.date = new Date();
that._year = that.options.date.getFullYear();
that._month = that.options.date.getMonth();
that._day = that.options.date.getDate();
that._renderCalendar();
});
table.find('.calendar-btn-clear').on('click', function(e){
e.preventDefault();
e.stopPropagation();
that.options.date = new Date();
that._year = that.options.date.getFullYear();
that._month = that.options.date.getMonth();
that._day = that.options.date.getDate();
that.element.data('_storage', []);
that._renderCalendar();
});
table.find('.day a').on('click', function(e){
e.preventDefault();
e.stopPropagation();
var d = (new Date(that._year, that._month, parseInt($(this).html()))).format(that.options.format,null);
var d0 = (new Date(that._year, that._month, parseInt($(this).html())));
if (that.options.multiSelect) {
$(this).toggleClass("selected");
if ($(this).hasClass("selected")) {
that._addDate(d);
} else {
that._removeDate(d);
}
} else {
table.find('.day a').removeClass('selected');
$(this).addClass("selected");
that.element.data('_storage', []);
that._addDate(d);
}
that.options.getDates(that.element.data('_storage'));
that.options.click(d, d0);
});
} else if (this._mode == 'month') {
table.find('.month a').on('click', function(e){
that._event = 'eventNext';
e.preventDefault();
e.stopPropagation();
that._month = parseInt($(this).data('month'));
that._mode = 'day';
that._renderCalendar();
});
table.find('.btn-previous-year').on('click', function(e){
that._event = 'eventPrevious';
e.preventDefault();
e.stopPropagation();
that._year -= 1;
that._renderCalendar();
});
table.find('.btn-next-year').on('click', function(e){
that._event = 'eventNext';
e.preventDefault();
e.stopPropagation();
that._year += 1;
that._renderCalendar();
});
table.find('.btn-select-year').on('click', function(e){
that._event = 'eventNext';
e.preventDefault();
e.stopPropagation();
that._mode = 'year';
that._renderCalendar();
});
} else {
table.find('.year a').on('click', function(e){
that._event = 'eventNext';
e.preventDefault();
e.stopPropagation();
that._year = parseInt($(this).data('year'));
that._mode = 'month';
that._renderCalendar();
});
table.find('.btn-previous-year').on('click', function(e){
that._event = 'eventPrevious';
e.preventDefault();
e.stopPropagation();
that._distance -= 10;
that._renderCalendar();
});
table.find('.btn-next-year').on('click', function(e){
that._event = 'eventNext';
e.preventDefault();
e.stopPropagation();
that._distance += 10;
that._renderCalendar();
});
}
},
_addDate: function(d){
var index = this.element.data('_storage').indexOf(d);
if (index < 0) this.element.data('_storage').push(d);
},
_removeDate: function(d){
var index = this.element.data('_storage').indexOf(d);
this.element.data('_storage').splice(index, 1);
},
setDate: function(d){
var r;
d = new Date(d);
r = (new Date(d.getFullYear()+"/"+ (d.getMonth()+1)+"/"+ d.getDate())).format('yyyy-mm-dd');
this._addDate(r);
this._renderCalendar();
},
getDate: function(index){
return new Date(index != undefined ? this.element.data('_storage')[index] : this.element.data('_storage')[0]).format(this.options.format);
},
getDates: function(){
return this.element.data('_storage');
},
unsetDate: function(d){
var r;
d = new Date(d);
r = (new Date(d.getFullYear()+"-"+ (d.getMonth()+1)+"-"+ d.getDate())).format('yyyy-mm-dd');
this._removeDate(r);
this._renderCalendar();
},
_destroy: function(){},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.treeview", {
version: "1.0.0",
options: {
onNodeClick: function(node){},
onNodeCollapsed: function(node){},
onNodeExpanded: function(node){}
},
_create: function(){
var that = this, element = this.element;
element.find('.node.collapsed').find('ul').hide();
element.find('.node-toggle').on('click', function(e){
var $this = $(this), node = $this.parent().parent("li");
if (node.hasClass("keep-open")) return;
node.toggleClass('collapsed');
if (node.hasClass('collapsed')) {
node.children('ul').fadeOut('fast');
that.options.onNodeCollapsed(node);
} else {
node.children('ul').fadeIn('fast');
that.options.onNodeExpanded(node);
}
that.options.onNodeClick(node);
e.preventDefault();
e.stopPropagation();
});
element.find("a").each(function(){
var $this = $(this);
$this.css({
paddingLeft: ($this.parents("ul").length-1) * 10
});
});
element.find('a').on('click', function(e){
var $this = $(this), node = $this.parent('li');
element.find('a').removeClass('active');
$this.toggleClass('active');
that.options.onNodeClick(node);
e.preventDefault();
});
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
// DatePicker
(function( $ ) {
$.widget("metro.datepicker", {
version: "1.0.0",
options: {
format: "dd.mm.yyyy",
date: undefined,
effect: 'none',
position: 'bottom',
locale: $.Metro.currentLocale,
weekStart: (METRO_WEEK_START != undefined ? METRO_WEEK_START : 0), // 0 - Sunday, 1 - Monday
otherDays: false,
selected: function(d, d0){},
_calendar: undefined
},
_create: function(){
var that = this,
element = this.element,
input = element.children("input"),
button = element.children("button.btn-date");
if (element.data('date') != undefined) this.options.date = element.data('date');
if (element.data('format') != undefined) this.options.format = element.data('format');
if (element.data('effect') != undefined) this.options.effect = element.data('effect');
if (element.data('position') != undefined) this.options.position = element.data('position');
if (element.data('locale') != undefined) this.options.locale = element.data('locale');
if (element.data('weekStart') != undefined) this.options.weekStart = element.data('weekStart');
if (element.data('otherDays') != undefined) this.options.otherDays = element.data('otherDays');
this._createCalendar(element, this.options.date);
input.attr('readonly', true);
button.on('click', function(e){
e.stopPropagation();
if (that.options._calendar.css('display') == 'none') {
that._show();
} else {
that._hide();
}
});
element.on('click', function(e){
e.stopPropagation();
if (that.options._calendar.css('display') == 'none') {
that._show();
} else {
that._hide();
}
});
$('html').on('click', function(e){
$(".calendar-dropdown").hide();
})
},
_createCalendar: function(to, curDate){
var _calendar, that = this;
_calendar = $("<div/>").css({
position: 'absolute'
, display: 'none'
, 'max-width': 260
, 'z-index': 1000
}).addClass('calendar calendar-dropdown').appendTo(to);
if (that.options.date != undefined) {
_calendar.data('date', that.options.date);
}
_calendar.calendar({
multiSelect: false,
format: that.options.format,
buttons: false,
locale: that.options.locale,
otherDays: that.options.otherDays,
weekStart: that.options.weekStart,
click: function(d, d0){
//console.log(d, d0);
_calendar.calendar('setDate', d0);
to.children("input[type=text]").val(d);
that.options.selected(d, d0);
that._hide();
}
});
if (curDate != undefined) {
_calendar.calendar('setDate', curDate);
to.children("input[type=text]").val(_calendar.calendar('getDate'));
}
// Set position
switch (this.options.position) {
case 'top': _calendar.css({top: (0-_calendar.height()), left: 0}); break;
default: _calendar.css({top: '100%', left: 0});
}
this.options._calendar = _calendar;
},
_show: function(){
if (this.options.effect == 'slide') {
$(".calendar-dropdown").slideUp('fast');
this.options._calendar.slideDown('fast');
} else if (this.options.effect == 'fade') {
$(".calendar-dropdown").fadeOut('fast');
this.options._calendar.fadeIn('fast');
} else {
$(".calendar-dropdown").hide();
this.options._calendar.show();
}
},
_hide: function(){
if (this.options.effect == 'slide') {
this.options._calendar.slideUp('fast');
} else if (this.options.effect == 'fade') {
this.options._calendar.fadeOut('fast');
} else {
this.options._calendar.hide();
}
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function($) {
var _notify_container = false;
var _notifies = [];
$.Notify = function(params) {
//$.Notify.settings = params;
params = $.extend({
icon: '',
caption: '',
content: '',
shadow: true,
width: 'auto',
height: 'auto',
style: false, // {background: '', color: ''}
position: 'right', //right, left
timeout: 5000
}, params);
var _container = _notify_container || $("<div/>").addClass("metro notify-container").appendTo('body'); _notify_container = _container;
//console.log(_container);
if (params.content == '' || params.content == undefined) return;
var _notify;
_notify = $("<div/>").addClass("notify");
if (params.shadow) _notify.addClass("shadow");
if (params.style && params.style.background != undefined) _notify.css("background-color", params.style.background);
if (params.style && params.style.color != undefined) _notify.css("color", params.style.color);
// add title
if (params.caption != '' && params.caption != undefined) {
$("<div/>").addClass("caption").html(params.caption).appendTo(_notify);
}
// add content
if (params.content != '' && params.content != undefined) {
$("<div/>").addClass("content").html(params.content).appendTo(_notify);
}
if (params.width != 'auto') _notify.css('min-width', params.width);
if (params.height != 'auto') _notify.css('min-height', params.height);
_notify.hide().appendTo(_container).fadeIn('slow');
_notifies.push( _notify );
setTimeout(function(){
$.Notify.close(_notify);
}, params.timeout);
};
$.Notify.show = function(message, title){
$.Notify({
content: message,
caption: title
});
};
$.Notify.close = function(_notify) {
if(_notify == undefined) {
return false;
}
_notify.fadeOut('slow', function(){
$(this).remove();
_notifies.splice(_notifies.indexOf(_notify), 1);
});
return true;
};
})(jQuery);
| JavaScript |
(function($) {
if (METRO_DIALOG == undefined) {
//var METRO_DIALOG = false;
}
$.Dialog = function(params) {
if(!$.Dialog.opened) {
$.Dialog.opened = true;
} else {
return METRO_DIALOG;
}
$.Dialog.settings = params;
params = $.extend({
icon: false,
title: '',
content: '',
flat: false,
shadow: false,
overlay: false,
width: 'auto',
height: 'auto',
position: 'default',
padding: false,
overlayClickClose: true,
sysButtons: {
btnClose: true
},
onShow: function(_dialog){},
sysBtnCloseClick: function(event){},
sysBtnMinClick: function(event){},
sysBtnMaxClick: function(event){}
}, params);
var _overlay, _window, _caption, _content;
_overlay = $("<div/>").addClass("metro window-overlay");
if (params.overlay) {
_overlay.css({
backgroundColor: 'rgba(0,0,0,.7)'
});
}
_window = $("<div/>").addClass("window");
if (params.flat) _window.addClass("flat");
if (params.shadow) _window.addClass("shadow").css('overflow', 'hidden');
_caption = $("<div/>").addClass("caption");
_content = $("<div/>").addClass("content");
_content.css({
paddingTop: 32 + params.padding,
paddingLeft: params.padding,
paddingRight: params.padding,
paddingBottom: params.padding
});
if (params.sysButtons) {
if (params.sysButtons.btnClose) {
$("<button/>").addClass("btn-close").on('click', function(e){
e.preventDefault();
e.stopPropagation();
$.Dialog.close();
params.sysBtnCloseClick(e);
}).appendTo(_caption);
}
if (params.sysButtons.btnMax) {
$("<button/>").addClass("btn-max").on('click', function(e){
e.preventDefault();
e.stopPropagation();
params.sysBtnMaxClick(e);
}).appendTo(_caption);
}
if (params.sysButtons.btnMin) {
$("<button/>").addClass("btn-min").on('click', function(e){
e.preventDefault();
e.stopPropagation();
params.sysBtnMinClick(e);
}).appendTo(_caption);
}
}
if (params.icon) $(params.icon).addClass("icon").appendTo(_caption);
$("<div/>").addClass("title").html(params.title).appendTo(_caption);
_content.html(params.content);
_caption.appendTo(_window);
_content.appendTo(_window);
_window.appendTo(_overlay);
if (params.width != 'auto') _window.css('min-width', params.width);
if (params.height != 'auto') _window.css('min-height', params.height);
_overlay.hide().appendTo('body').fadeIn('fast');
METRO_DIALOG = _window;
_window
.css("position", "fixed")
.css("z-index", parseInt(_overlay.css('z-index'))+1)
.css("top", ($(window).height() - METRO_DIALOG.outerHeight()) / 2 )
.css("left", ($(window).width() - _window.outerWidth()) / 2)
;
addTouchEvents(_window[0]);
if(params.draggable) {
_caption.on("mousedown", function(e) {
$.Dialog.drag = true;
_caption.css('cursor', 'move');
var z_idx = _window.css('z-index'),
drg_h = _window.outerHeight(),
drg_w = _window.outerWidth(),
pos_y = _window.offset().top + drg_h - e.pageY,
pos_x = _window.offset().left + drg_w - e.pageX;
_window.css('z-index', 99999).parents().on("mousemove", function(e) {
var t = (e.pageY > 0)?(e.pageY + pos_y - drg_h):(0);
var l = (e.pageX > 0)?(e.pageX + pos_x - drg_w):(0);
if ($.Dialog.drag) {
if(t >= 0 && t <= window.innerHeight - _window.outerHeight()) {
_window.offset({top: t});
}
if(l >= 0 && l <= window.innerWidth - _window.outerWidth()) {
_window.offset({left: l});
}
}
});
e.preventDefault();
}).on("mouseup", function() {
_window.removeClass('draggable');
$.Dialog.drag = false;
_caption.css('cursor', 'default');
});
}
_window.on('click', function(e){
e.stopPropagation();
});
if (params.overlayClickClose) {
_overlay.on('click', function(e){
e.preventDefault();
$.Dialog.close();
});
}
params.onShow(METRO_DIALOG);
$.Dialog.autoResize();
return METRO_DIALOG;
}
$.Dialog.content = function(newContent) {
if(!$.Dialog.opened || METRO_DIALOG == undefined) {
return false;
}
if(newContent) {
METRO_DIALOG.children(".content").html(newContent);
$.Dialog.autoResize();
return true;
} else {
return METRO_DIALOG.children(".content").html();
}
}
$.Dialog.title = function(newTitle) {
if(!$.Dialog.opened || METRO_DIALOG == undefined) {
return false;
}
var _title = METRO_DIALOG.children('.caption').children('.title');
if(newTitle) {
_title.html(newTitle);
} else {
_title.html();
}
return true;
}
$.Dialog.autoResize = function(){
if(!$.Dialog.opened || METRO_DIALOG == undefined) {
return false;
}
var _content = METRO_DIALOG.children(".content");
var top = ($(window).height() - METRO_DIALOG.outerHeight()) / 2;
var left = ($(window).width() - METRO_DIALOG.outerWidth()) / 2;
METRO_DIALOG.css({
width: _content.outerWidth(),
height: _content.outerHeight(),
top: top,
left: left
});
return true;
}
$.Dialog.close = function() {
if(!$.Dialog.opened || METRO_DIALOG == undefined) {
return false;
}
$.Dialog.opened = false;
var _overlay = METRO_DIALOG.parent(".window-overlay");
_overlay.fadeOut(function(){
$(this).remove();
});
return false;
}
})(jQuery);
| JavaScript |
(function( $ ) {
$.widget("metro.stepper", {
version: "1.0.0",
options: {
diameter: 32
},
_create: function(){
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.buttonset", {
version: "1.0.0",
options: {
click: function(btn, on){}
},
_buttons: {},
_create: function(){
var element = this.element;
this._buttons = element.find("button, .button");
this.init();
},
init: function(){
var that = this;
this._buttons.each(function(){
var btn = $(this);
btn.on('click', function(e){
e.preventDefault();
btn.toggleClass("active");
that.options.click(btn, btn.hasClass("active"));
that._trigger("click", event, {button: btn, on: (btn.hasClass("active"))});
});
});
},
_destroy: function(){},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
(function( $ ) {
$.widget("metro.buttongroup", {
version: "1.0.0",
options: {
click: function(btn, on){}
},
_buttons: {},
_create: function(){
var element = this.element;
this._buttons = element.find("button, .button");
this.init();
},
init: function(){
var that = this;
this._buttons.each(function(){
var btn = $(this);
btn.on('click', function(e){
e.preventDefault();
that._buttons.removeClass("active");
btn.addClass("active");
that.options.click(btn, btn.hasClass("active"));
that._trigger("click", event, {button: btn, on: (btn.hasClass("active"))});
});
});
},
_destroy: function(){},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.carousel", {
version: "1.0.0",
options: {
auto: true,
period: 2000,
duration: 500,
effect: 'slowdown', // slide, fade, switch, slowdown
direction: 'left',
markers: {
show: true,
type: 'default',
position: 'left' //bottom-left, bottom-right, bottom-center, top-left, top-right, top-center
},
controls: true,
stop: true,
width: '100%',
height: 300
},
_slides: {},
_currentIndex: 0,
_interval: 0,
_outPosition: 0,
_create: function(){
var that = this, o = this.options,
element = carousel = this.element,
controls = carousel.find('.controls');
if (element.data('auto') != undefined) o.auto = element.data('auto');
if (element.data('period') != undefined) o.period = element.data('period');
if (element.data('duration') != undefined) o.duration = element.data('duration');
if (element.data('effect') != undefined) o.effect = element.data('effect');
if (element.data('direction') != undefined) o.direction = element.data('direction');
if (element.data('width') != undefined) o.width = element.data('width');
if (element.data('height') != undefined) o.height = element.data('height');
if (element.data('stop') != undefined) o.stop = element.data('stop');
if (element.data('controls') != undefined) o.controls = element.data('controls');
if (element.data('markersShow') != undefined) o.markers.show = element.data('markersShow');
if (element.data('markersType') != undefined) o.markers.type = element.data('markersType');
if (element.data('markersPosition') != undefined) o.markers.position = element.data('markersPosition');
carousel.css({
'width': this.options.width,
'height': this.options.height
});
this._slides = carousel.find('.slide');
if (this._slides.length <= 1) return;
if (this.options.markers !== false && this.options.markers.show && this._slides.length > 1) {
this._markers(that);
}
if (this.options.controls && this._slides.length > 1) {
carousel.find('.controls.left').on('click', function(){
that._slideTo('prior');
});
carousel.find('.controls.right').on('click', function(){
that._slideTo('next');
});
} else {
controls.hide();
}
if (this.options.stop) {
carousel
.on('mouseenter', function(){
clearInterval(that._interval);
})
.on('mouseleave', function(){
if (that.options.auto) that._autoStart(), that.options.period;
})
}
if (this.options.auto) {
this._autoStart();
}
},
_autoStart: function(){
var that = this;
this._interval = setInterval(function(){
if (that.options.direction == 'left') {
that._slideTo('next')
} else {
that._slideTo('prior')
}
}, this.options.period);
},
_slideTo: function(direction){
var
currentSlide = this._slides[this._currentIndex],
nextSlide;
if (direction == undefined) direction = 'next';
if (direction === 'prior') {
this._currentIndex -= 1;
if (this._currentIndex < 0) this._currentIndex = this._slides.length - 1;
this._outPosition = this.element.width();
} else if (direction === 'next') {
this._currentIndex += 1;
if (this._currentIndex >= this._slides.length) this._currentIndex = 0;
this._outPosition = -this.element.width();
}
nextSlide = this._slides[this._currentIndex];
switch (this.options.effect) {
case 'switch': this._effectSwitch(currentSlide, nextSlide); break;
case 'slowdown': this._effectSlowdown(currentSlide, nextSlide, this.options.duration); break;
case 'fade': this._effectFade(currentSlide, nextSlide, this.options.duration); break;
default: this._effectSlide(currentSlide, nextSlide, this.options.duration);
}
var carousel = this.element, that = this;
carousel.find('.markers ul li a').each(function(){
var index = $(this).data('num');
if (index === that._currentIndex) {
$(this).parent().addClass('active');
} else {
$(this).parent().removeClass('active');
}
});
},
_slideToSlide: function(slideIndex){
var
currentSlide = this._slides[this._currentIndex],
nextSlide = this._slides[slideIndex];
if (slideIndex > this._currentIndex) {
this._outPosition = -this.element.width();
} else {
this._outPosition = this.element.width();
}
switch (this.options.effect) {
case 'switch' : this._effectSwitch(currentSlide, nextSlide); break;
case 'slowdown': this._effectSlowdown(currentSlide, nextSlide, this.options.duration); break;
case 'fade': this._effectFade(currentSlide, nextSlide, this.options.duration); break;
default : this._effectSlide(currentSlide, nextSlide, this.options.duration);
}
this._currentIndex = slideIndex;
},
_markers: function (that) {
var div, ul, li, i, markers;
div = $('<div class="markers '+this.options.markers.type+'" />');
ul = $('<ul></ul>').appendTo(div);
for (i = 0; i < this._slides.length; i++) {
li = $('<li><a href="javascript:void(0)" data-num="' + i + '"></a></li>');
if (i === 0) {
li.addClass('active');
}
li.appendTo(ul);
}
ul.find('li a').removeClass('active').on('click', function () {
var $this = $(this),
index = $this.data('num');
ul.find('li').removeClass('active');
$this.parent().addClass('active');
if (index == that._currentIndex) {
return true;
}
that._slideToSlide(index);
return true;
});
div.appendTo(this.element);
switch (this.options.markers.position) {
case 'top-left' : {
div.css({
left: '10px',
right: 'auto',
bottom: 'auto',
top: '10px'
});
break;
}
case 'top-right' : {
div.css({
left: 'auto',
right: '10px',
bottom: 'auto',
top: '0px'
});
break;
}
case 'top-center' : {
div.css({
left: this.element.width()/2 - div.width()/2,
right: 'auto',
bottom: 'auto',
top: '0px'
});
break;
}
case 'bottom-left' : {
div.css({
left: '10px',
right: 'auto'
});
break;
}
case 'bottom-right' : {
div.css({
right: '10px',
left: 'auto'
});
break;
}
case 'bottom-center' : {
div.css({
left: this.element.width()/2 - div.width()/2,
right: 'auto'
});
break;
}
}
},
_effectSwitch: function(currentSlide, nextSlide){
$(currentSlide)
.hide();
$(nextSlide)
.css({left: 0})
.show();
},
_effectSlide: function(currentSlide, nextSlide, duration){
$(currentSlide)
.animate({left: this._outPosition}, duration);
$(nextSlide)
.css('left', this._outPosition * -1)
.show()
.animate({left: 0}, duration);
},
_effectSlowdown: function(currentSlide, nextSlide, duration){
var options = {
'duration': duration,
'easing': 'doubleSqrt'
};
$.easing.doubleSqrt = function(t) {
return Math.sqrt(Math.sqrt(t));
};
$(currentSlide)
.animate({left: this._outPosition}, options);
//$(nextSlide).find('.subslide').hide();
$(nextSlide)
.css('left', this._outPosition * -1)
.show()
.animate({left: 0}, options);
//setTimeout(function(){
// $(nextSlide).find('.subslide').fadeIn();
//}, 500);
},
_effectFade: function(currentSlide, nextSlide, duration){
$(currentSlide)
.fadeOut(duration);
$(nextSlide)
.css({left: 0})
.fadeIn(duration);
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
});
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.accordion", {
version: "1.0.0",
options: {
closeAny: true,
open: function(frame){},
action: function(frame){}
},
_frames: {},
_create: function(){
var element = this.element;
if (element.data('closeany') != undefined) this.options.closeAny = element.data('closeany');
this._frames = element.children(".accordion-frame");
this.init();
},
init: function(){
var that = this;
this._frames.each(function(){
var frame = this,
a = $(this).children(".heading"),
content = $(this).children(".content");
if ($(a).hasClass("active") && !$(a).attr('disabled') && $(a).data('action') != 'none') {
$(content).show();
$(a).removeClass("collapsed");
} else {
$(a).addClass("collapsed");
}
a.on('click', function(e){
e.preventDefault();
if ($(this).attr('disabled') || $(this).data('action') == 'none') return;
if (that.options.closeAny) that._closeFrames();
if ($(content).is(":hidden")) {
$(content).slideDown();
$(this).removeClass("collapsed");
that._trigger("frame", e, {frame: frame});
that.options.open(frame);
} else {
$(content).slideUp();
$(this).addClass("collapsed");
}
that.options.action(frame);
});
});
},
_closeFrames: function(){
this._frames.children(".content").slideUp().parent().children('.heading').addClass("collapsed");
},
_destroy: function(){},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
(function( $ ) {
$.widget("metro.widget", {
version: "1.0.0",
options: {
},
_create: function(){
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
})
})( jQuery );
| JavaScript |
var hasTouch = 'ontouchend' in window, eventTimer;
var moveDirection = 'undefined', startX, startY, deltaX, deltaY, mouseDown = false
function addTouchEvents(element){
if (hasTouch) {
element.addEventListener("touchstart", touch2Mouse, true);
element.addEventListener("touchmove", touch2Mouse, true);
element.addEventListener("touchend", touch2Mouse, true);
}
}
function touch2Mouse(e)
{
var theTouch = e.changedTouches[0];
var mouseEv;
switch(e.type)
{
case "touchstart": mouseEv="mousedown"; break;
case "touchend": mouseEv="mouseup"; break;
case "touchmove": mouseEv="mousemove"; break;
default: return;
}
if (mouseEv == "mousedown") {
eventTimer = (new Date()).getTime();
startX = theTouch.clientX;
startY = theTouch.clientY;
mouseDown = true;
}
if (mouseEv == "mouseup") {
if ((new Date()).getTime() - eventTimer <= 500) {
mouseEv = "click";
} else if ((new Date()).getTime() - eventTimer > 1000) {
mouseEv = "longclick";
}
eventTimer = 0;
mouseDown = false;
}
if (mouseEv == "mousemove") {
if (mouseDown) {
deltaX = theTouch.clientX - startX;
deltaY = theTouch.clientY - startY;
moveDirection = deltaX > deltaY ? 'horizontal' : 'vertical';
}
}
var mouseEvent = document.createEvent("MouseEvent");
mouseEvent.initMouseEvent(mouseEv, true, true, window, 1, theTouch.screenX, theTouch.screenY, theTouch.clientX, theTouch.clientY, false, false, false, false, 0, null);
theTouch.target.dispatchEvent(mouseEvent);
e.preventDefault();
}
/* To add touch support for element need create listeners for component dom element
if (hasTouch) {
element.addEventListener("touchstart", touch2Mouse, true);
element.addEventListener("touchmove", touch2Mouse, true);
element.addEventListener("touchend", touch2Mouse, true);
}
*/ | JavaScript |
(function( $ ) {
$.widget("metro.dropdown", {
version: "1.0.0",
options: {
effect: 'slide'
},
_create: function(){
var that = this,
menu = this.element,
name = this.name,
parent = this.element.parent(),
toggle = parent.children('.dropdown-toggle');
if (menu.data('effect') != undefined) {
this.options.effect = menu.data('effect');
}
toggle.on('click.'+name, function(e){
e.preventDefault();
e.stopPropagation();
if (menu.css('display') == 'block' && !menu.hasClass('keep-open')) {
that._close(menu);
} else {
$('.dropdown-menu').each(function(i, el){
if (!menu.parents('.dropdown-menu').is(el) && !$(el).hasClass('keep-open') && $(el).css('display')=='block') {
that._close(el);
}
});
that._open(menu);
}
});
$(menu).find('li.disabled a').on('click', function(e){
e.preventDefault();
});
},
_open: function(el){
switch (this.options.effect) {
case 'fade': $(el).fadeIn('fast'); break;
case 'slide': $(el).slideDown('fast'); break;
default: $(el).hide();
}
this._trigger("onOpen", null, el);
},
_close: function(el){
switch (this.options.effect) {
case 'fade': $(el).fadeOut('fast'); break;
case 'slide': $(el).slideUp('fast'); break;
default: $(el).hide();
}
this._trigger("onClose", null, el);
},
_destroy: function(){
},
_setOption: function(key, value){
this._super('_setOption', key, value);
}
});
})( jQuery );
/*
(function($){
$.fn.PullDown = function( options ){
var defaults = {
};
var $this = $(this)
;
var initSelectors = function(selectors){
addTouchEvents(selectors[0]);
selectors.on('click', function(e){
var $m = $this.parent().children(".element-menu");
console.log($m);
if ($m.css('display') == "block") {
$m.slideUp('fast');
} else {
$m.slideDown('fast');
}
e.preventDefault();
e.stopPropagation();
});
};
return this.each(function(){
if ( options ) {
$.extend(defaults, options);
}
initSelectors($this);
});
};
$(function () {
$('.pull-menu, .menu-pull').each(function () {
$(this).PullDown();
});
});
})(window.jQuery);
*/
| JavaScript |
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.1.3
*
* Requires: 1.2.2+
*/
(function (factory) {
if ( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS style for Browserify
module.exports = factory;
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
var lowestDelta, lowestDeltaXY;
if ( $.event.fixHooks ) {
for ( var i = toFix.length; i; ) {
$.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i = toBind.length; i; ) {
this.addEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i = toBind.length; i; ) {
this.removeEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event,
args = [].slice.call(arguments, 1),
delta = 0,
deltaX = 0,
deltaY = 0,
absDelta = 0,
absDeltaXY = 0,
fn;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
if ( orgEvent.detail ) { delta = orgEvent.detail * -1; }
// New school wheel delta (wheel event)
if ( orgEvent.deltaY ) {
deltaY = orgEvent.deltaY * -1;
delta = deltaY;
}
if ( orgEvent.deltaX ) {
deltaX = orgEvent.deltaX;
delta = deltaX * -1;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; }
// Look for lowest delta to normalize the delta values
absDelta = Math.abs(delta);
if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }
// Get a whole value for the deltas
fn = delta > 0 ? 'floor' : 'ceil';
delta = Math[fn](delta / lowestDelta);
deltaX = Math[fn](deltaX / lowestDeltaXY);
deltaY = Math[fn](deltaY / lowestDeltaXY);
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
}));
| JavaScript |
$(function(){
if (document.location.host.indexOf('.dev') > -1) return;
var repo = "olton/Metro-UI-CSS";
$.ajax({
url: 'https://api.github.com/repos/' + repo,
dataType: 'jsonp',
error: function(result){
},
success: function(results){
var repo = results.data;
var watchers = repo.watchers;
var forks = repo.forks;
$(".github-watchers").html(watchers);
$(".github-forks").html(forks);
}
})
}); | JavaScript |
var showmenu = 0;
var ajaxRequest = '';
var listener = 0;
var addMode;
var printMode;
$(function() {
addMode = false;
printMode = false;
$('.mki_header_back, .mki_news_ticker_back').css({opacity:.6});
$('.mki_app_menu').css({opacity:.9});
$('.mki_app_menu').css({top:$('.mki_app_menu').outerHeight()*-1});
$('#mki_right_content_petatematik').css({right:0});
$('.mki_quick_search').css({opacity:.95});
$('#mki_active_right').val('mki_right_content_petatematik');
//$('#mki_active_right').val('mki_right_content_pemetaan');
$( "#mki_right_content_petatematik" ).css("margin", "0px");
$( "#mki_right_content_petatematik" ).animate({width: "22%",margin: "0px"}, 200);
$(window).resize(function() {
$('.mki_right_content').css({height:$(window).height()-$('.mki_header_front').outerHeight()-60});
//$('.mki_right_content_data').css({height:$(window).height()-$('.mki_header_front').outerHeight()-100});
$('.mki_map_area').css({height:$(window).height()-$('.mki_header_front').outerHeight()-40});
$('#mki_map_view').css({height:$(window).height()-$('.mki_header_front').outerHeight()-60, width:'100%'});
$('.mki_left_content').css({height:$('.mki_right_content').outerHeight(), width:$(window).width()-$('.mki_right_content').outerWidth()});
//$('#mki_map_view').css({position:absolute});
//$('#mki_content_responden, #mki_content_dashboard').css({width:$(window).width()-40});
//$('#mki_quick_search_result').css({height:($('.mki_left_content').outerHeight()-$('#mki_form_quick_search').outerHeight())});
});
$('.mki_app_logout').hover(function() {
$(this).addClass('mki_app_logout_hover');
}, function() {
$(this).removeClass('mki_app_logout_hover');
});
$('.mki_app_logout').click(function() {
window.location.href=base_url+'auth/logout';
});
$('.mki_app_menu ul').hover(function() { }, function() {
showmenu = 0;
$('.mki_app_menu').stop().animate({top:$('.mki_app_menu').outerHeight()*-1});
});
$('.mki_app_menu ul li').hover(function() {
$(this).stop().animate({'padding-left':25}, 300);
$(this).addClass('mki_app_menu_hover');
},function() {
$(this).stop().animate({'padding-left':20}, 200);
$(this).removeClass('mki_app_menu_hover');
});
$('.mki_app_menu ul li').click(function() {
$('.mki_app_menu_selected').each(function() {
$(this).removeClass('mki_app_menu_selected');
});
$(this).addClass('mki_app_menu_selected');
var thisname = $(this).find('span').html();
var thisicon = $(this).find('i').attr('class');
$('.mki_menu_current_icon').html('<i class="'+thisicon+'"></i>');
$('.mki_menu_current_name').html(thisname);
var showcontent = $(this).attr('ref');
var activeright = $('#mki_active_right').val();
//load content
if(showcontent=='pemetaan') {
onMapClick(activeright);
} else if(showcontent=='penambahan') {
onAddClick(activeright);
} else if(showcontent=='petatematik') {
onTematikClick(activeright);
}else if(showcontent=='pencetakan') {
onPrintClick(activeright);
}else if(showcontent=='lokasiskpd') {
onAddSKPDClick(activeright);
}
//hide menu
showmenu = 0;
$('.mki_app_menu').stop().animate({top:$('.mki_app_menu').outerHeight()*-1});
});
$('.mki_menu_arrow').click(function() {
//alert(showmenu);
if(showmenu==0) {
showmenu = 1;
$('.mki_app_menu').stop().animate({top:70});
} else {
showmenu = 0;
$('.mki_app_menu').stop().animate({top:$('.mki_app_menu').outerHeight()*-1});
}
});
$('#mki_close_responden_detail').click(function() {
closeRespondenDetail();
});
$('#mki_close_aset_detail').click(function() {
closeAsetDetail();
});
$('#mki_close_responden_edit').click(function() {
closeRespondenEdit();
});
$('#mki_close_survey_edit').click(function() {
closeSurveyEdit();
});
$('#mki_close_option_add').click(function() {
closeOptionAdd();
});
$('#mki_close_pengguna_add').click(function() {
closeUserAdd();
});
$('#mki_close_responden_add').click(function() {
closeRespondenAdd();
});
$('.mki_right_list_menu ul li').hover(function() {
$(this).addClass('mki_right_list_menu_hover');
}, function() {
$(this).removeClass('mki_right_list_menu_hover');
});
$('.mki_right_list_menu ul li').click(function() {
closeOptionAdd();
$('.mki_right_list_menu_selected').each(function() {
$(this).removeClass('mki_right_list_menu_selected');
});
//clear rekap
$('#mki_btn_custom_recap_clear').hide();
$('#mki_btn_custom_recap').show();
$('#mki_custom_item_active').val(0);
$('#mki_btn_summary_recap').show();
$('#mki_custom_item').val('-');
$('#mki_right_custom_recap_list').empty();
$('.mki_filter_quiz_item').removeAttr('disabled');
$('#mki_filter_quiz').show();
$('#mki_right_custom_recap').hide();
$(this).addClass('mki_right_list_menu_selected');
var thisid = $(this).attr('id');
var rw_selected = $('#mki_filter_rw').val();
thisid = thisid.replace('mki_rekap_','');
$('#mki_right_list_menu_inload').val(thisid);
var rwname = $('#rw_'+rw_selected).text();
rwname = (rw_selected=='nol')?'':' '+rwname;
$('#mki_preload_rekap div').html('<div class="win-ring small"></div> Menghitung data '+$(this).html()+' semua responden'+rwname+'...');
$('#mki_preload_rekap').show();
$('#mki_loaded_rekap').hide();
ajaxGetRekap('rekap', thisid, rw_selected);
});
$('.dropdown-menu li').click(function() {
closeOptionAdd();
$('.mki_right_petatematik_menu_selected').each(function() {
$(this).removeClass('mki_right_petatematik_menu_selected');
});
$(this).addClass('mki_right_petatematik_menu_selected');
var thisid = $(this).attr('id');
thisid = thisid.replace('mki_tematik_','');
$('#mki_right_petatematik_menu_inload').val(thisid);
AddTematik('1',thisid,printMode);
});
$(window).resize();
$('.mki_site_logo').hover(function() {
$(this).css({'background-color': '#ffffff'});
},function() {
$(this).css({'background-color': '#f5f5f5'});
});
$('.mki_site_logo').click(function() {
window.location.href='';
});
$('#mki_quick_search').keyup(function(e) {
var code = e.keyCode || e.which;
if(code==13) {
var rws = $('#mki_quick_search_rw').val();
if(rws!='nol') {
showQuickSearch();
}
else{
$('#mki_quick_search_result').html('<center><br/> Silahkan Pilih Golongan Aset!</center>');
}
}
});
$('#mki_quick_search_rw').change(function() {
var rws = $('#mki_quick_search_rw').val();
if(rws!='nol') {
showQuickSearch();
}
else{
$('#mki_quick_search_result').html('<center><br/> Silahkan Pilih Golongan Aset!</center>');
}
});
$('#mki_close_quick_search').click(function() {
//$('#mki_quick_search_result').empty();
$('#mki_quick_search').val('');
$('#mki_close_quick_search').fadeOut(500);
$('.mki_quick_search_list').show();
setTimeout(function() { $('#mki_quick_search').animate({'width':'260px'}, 500); }, 600);
clearAllMarkers();
onMapClick();
});
$("#mki_quick_search_rw").change(function () {
if(addMode){$("#noreg").val(this.value);}
$.ajax({
type : 'post',
url : base_url+'map/get_bidang_list/'+this.value,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$("#mki_search_bid").html(data.list);
$("#mki_search_kel").html("<select style='width:260px' id='mki_quick_search_kel'><option id='mki_quick_search_kel_nol' value='nol'>-- Kelompok Aset --</option></select>");
$("#mki_search_sub").html("<select style='width:260px' id='mki_quick_search_sub'><option id='mki_quick_search_sub_nol' value='nol'>-- Sub-Kelompok Aset --</option></select>");
$("#mki_search_brg").html("<select style='width:260px' id='mki_quick_search_brg'><option id='mki_quick_search_brg_nol' value='nol'>-- Barang Aset --</option></select>");
}
});
});
$("#mki_search_bid").delegate("#mki_quick_search_bid","change",function () {
if(addMode){$("#noreg").val(this.value);}
$.ajax({
type : 'post',
url : base_url+'map/get_kelompok_list/'+this.value,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$("#mki_search_kel").html(data.list);
$("#mki_search_sub").html("<select style='width:260px' id='mki_quick_search_sub'><option id='mki_quick_search_sub_nol' value='nol'>-- Sub-Kelompok Aset --</option></select>");
$("#mki_search_brg").html("<select style='width:260px' id='mki_quick_search_brg'><option id='mki_quick_search_brg_nol' value='nol'>-- Barang Aset --</option></select>");
}
});
});
$("#mki_search_kel").delegate("#mki_quick_search_kel","change",function () {
if(addMode){$("#noreg").val(this.value);}
$.ajax({
type : 'post',
url : base_url+'map/get_subkel_list/'+this.value,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$("#mki_search_sub").html(data.list);
$("#mki_search_brg").html("<select style='width:260px' id='mki_quick_search_brg'><option id='mki_quick_search_brg_nol' value='nol'>-- Barang Aset --</option></select>");
}
});
});
$("#mki_search_sub").delegate("#mki_quick_search_sub","change",function () {
if(addMode){$("#noreg").val(this.value);}
$.ajax({
type : 'post',
url : base_url+'map/get_barang_list/'+this.value,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$("#mki_search_brg").html(data.list);
}
});
});
$("#mki_search_brg").delegate("#mki_quick_search_brg","change",function () {
$("#noreg").val(this.value);
});
//copy paste fungsi searching untuk add point
$('#mki_add_search').keyup(function(e) {
var code = e.keyCode || e.which;
if(code==13) {
var rws = $('#mki_add_search_rw').val();
if(rws!='nol') {
showAddSearch();
}
else{
$('#mki_add_search_result').html('<center><br/> Silahkan Pilih Golongan Aset!</center>');
}
}
});
//copy paste fungsi searching untuk add skpd
$('#mki_search_skpd').keyup(function(e) {
var code = e.keyCode || e.which;
if(code==13) {
showAddSKPD(this.value);
}
});
$('#mki_add_search_rw').change(function() {
var rws = $('#mki_add_search_rw').val();
if(rws!='nol') {
showAddSearch();
}
else{
$('#mki_add_search_result').html('<center><br/> Silahkan Pilih Golongan Aset!</center>');
}
});
$('#mki_close_add_search').click(function() {
//$('#mki_quick_search_result').empty();
//$('#mki_add_search_result').val('');
$('#mki_add_search').val('');
$('#mki_close_add_search').fadeOut(500);
$('.mki_add_search_list').show();
setTimeout(function() { $('#mki_add_search').animate({'width':'260px'}, 500); }, 600);
clearAllMarkers();
//onMapClick();
onAddClick();
});
$("#mki_add_search_rw").change(function () {
if(addMode){$("#noreg").val(this.value);}
$.ajax({
type : 'post',
url : base_url+'map/get_bidang_list/'+this.value,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$("#mki_addsearch_bid").html(data.list);
$("#mki_addsearch_kel").html("<select style='width:260px' id='mki_add_search_kel'><option id='mki_add_search_kel_nol' value='nol'>-- Kelompok Aset --</option></select>");
$("#mki_addsearch_sub").html("<select style='width:260px' id='mki_add_search_sub'><option id='mki_add_search_sub_nol' value='nol'>-- Sub-Kelompok Aset --</option></select>");
$("#mki_addsearch_brg").html("<select style='width:260px' id='mki_add_search_brg'><option id='mki_add_search_brg_nol' value='nol'>-- Barang Aset --</option></select>");
}
});
});
$("#mki_addsearch_bid").delegate("#mki_add_search_bid","change",function () {
if(addMode){$("#noreg").val(this.value);}
$.ajax({
type : 'post',
url : base_url+'map/get_kelompok_list/'+this.value,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$("#mki_addsearch_kel").html(data.list);
$("#mki_addsearch_sub").html("<select style='width:260px' id='mki_add_search_sub'><option id='mki_add_search_sub_nol' value='nol'>-- Sub-Kelompok Aset --</option></select>");
$("#mki_addsearch_brg").html("<select style='width:260px' id='mki_add_search_brg'><option id='mki_add_search_brg_nol' value='nol'>-- Barang Aset --</option></select>");
}
});
});
$("#mki_addsearch_kel").delegate("#mki_add_search_kel","change",function () {
if(addMode){$("#noreg").val(this.value);}
$.ajax({
type : 'post',
url : base_url+'map/get_subkel_list/'+this.value,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$("#mki_addsearch_sub").html(data.list);
$("#mki_addsearch_brg").html("<select style='width:260px' id='mki_add_search_brg'><option id='mki_add_search_brg_nol' value='nol'>-- Barang Aset --</option></select>");
}
});
});
$("#mki_addsearch_sub").delegate("#mki_add_search_sub","change",function () {
if(addMode){$("#noreg").val(this.value);}
$.ajax({
type : 'post',
url : base_url+'map/get_barang_list/'+this.value,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$("#mki_addsearch_brg").html(data.list);
}
});
});
$("#mki_addsearch_brg").delegate("#mki_add_search_brg","change",function () {
$("#noreg").val(this.value);
});
//end searching add point
}); //end function
function closeRespondenDetail() {
$('#mki_content_responden_detail').fadeOut();
}
function closeAsetDetail() {
$('#mki_content_aset_detail').fadeOut();
}
function closeRespondenEdit() {
$('#mki_content_responden_edit').fadeOut();
}
function closeSurveyEdit() {
$('#mki_content_survey_edit').fadeOut();
}
function closeOptionAdd() {
$('#mki_content_kuisoner_option_add').fadeOut();
}
function closeUserAdd() {
$('#mki_content_add_pengguna').fadeOut();
}
function closeRespondenAdd() {
$('#mki_content_add_responden').fadeOut();
}
function showQuickSearch() {
var rws = $('#mki_quick_search_rw').val();
var kw = $('#mki_quick_search').val();
//alert(rws); alert(kw);
$('#mki_quick_search_result').html('');
if(kw!='') {
$.ajax({
type : 'post',
url : base_url+'map/quick_search/'+rws,
data : 'qs='+kw,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$('#mki_quick_search').animate({'width':'230px'}, 500);
setTimeout(function() { $('#mki_close_quick_search').fadeIn(); }, 600);
$('.mki_quick_search_list').hide();
for(var i=0; i<pid.length; i++) {
markers[pid[i]].setMap(null);
}
if(data.status) {
//$('#mki_quick_search_result').empty();
//var bounds = new google.maps.LatLngBounds();
for(var i=0; i<data.responden.length; i++) {
// showMarkers(map,asets,tematik)
//var kdbarang = data.responden[i]['kd_brg'];
var kdbarang = "'"+data.responden[i]['kd_brg']+"'";
var catikon = 'markers/'+data.responden[i]['kd_brg'].substr(0,6)+'.png';
showMarker(map, data.responden[i],catikon);
//markers['rid_'+data.responden[i].data_id].setMap(map);
//bounds.extend(markers['rid_'+data.responden[i].data_id].getPosition());
var noregteks="'"+data.responden[i].no_reg+"'";
$('#mki_quick_search_result').append('<div class="mki_quick_search_list"><i class="icon-target-2" style="font-size:12px;cursor:pointer;" onClick="showRespondenMap('+noregteks+')"></i> <span style="cursor: pointer;" onClick="showAsetDetail('+noregteks+','+kdbarang+');">'+data.responden[i].no_reg+'</span></div>');
$('#mki_quick_search_list_'+data.responden[i].data_id).show();
}
//map.fitBounds(bounds);
} else {
$('#mki_quick_search_result').html('<center><br/>Data responden dengan kata kunci <i>"<b>'+kw+'</b>"</i> tidak ditemukan, silahkan masukkan kata kunci yang lain!</center>');
}
}
});
}
}
function showAddSearch() {
var rws = $('#mki_add_search_rw').val();
var kw = $('#mki_add_search').val();
$('#mki_add_search_result').html('');
if(kw!='') {
$.ajax({
type : 'post',
url : base_url+'map/add_search/'+rws,
data : 'qs='+kw,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$('#mki_add_search').animate({'width':'230px'}, 500);
setTimeout(function() { $('#mki_close_add_search').fadeIn(); }, 600);
$('.mki_add_search_list').hide();
for(var i=0; i<pid.length; i++) {
markers[pid[i]].setMap(null);
}
if(data.status) {
//$('#mki_quick_search_result').empty();
//var bounds = new google.maps.LatLngBounds();
for(var i=0; i<data.responden.length; i++) {
// showMarkers(map,asets,tematik)
//var kdbarang = data.responden[i]['kd_brg'];
var kdbarang = "'"+data.responden[i]['kd_brg']+"'";
////var catikon = 'markers/'+data.responden[i]['kd_brg'].substr(0,6)+'.png';
////showMarker(map, data.responden[i],catikon);
//markers['rid_'+data.responden[i].data_id].setMap(map);
//bounds.extend(markers['rid_'+data.responden[i].data_id].getPosition());
var noregteks="'"+data.responden[i].no_reg+"'";
$('#mki_add_search_result').append('<div class="mki_add_search_list"><i class="icon-target-2" style="font-size:12px;cursor:pointer;" onClick="addRespondenMap('+noregteks+','+kdbarang+')"></i> <span style="cursor: pointer;" onClick="showAsetDetail('+noregteks+','+kdbarang+');">'+data.responden[i].no_reg+'</span></div>');
$('#mki_add_search_list_'+data.responden[i].data_id).show();
}
//map.fitBounds(bounds);
} else {
$('#mki_add_search_result').html('<center><br/>Data responden dengan kata kunci <i>"<b>'+kw+'</b>"</i> tidak ditemukan, silahkan masukkan kata kunci yang lain!</center>');
}
}
});
}
}
// Lihat Data SKPD
function showAddSKPD(key) {
$('#mki_search_skpd').html('');
if(key!='') {
$.ajax({
type : 'post',
url : base_url+'map/skpd_search/',
data : 'key='+key,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
$('.mki_add_search_list').hide();
for(var i=0; i<pid.length; i++) {
markers[pid[i]].setMap(null);
}
if(data.status) {
for(var i=0; i<data.responden.length; i++) {
var kdskpd = "'"+data.responden[i]['kd_uskpd']+"'";
var nmskpd = "'"+data.responden[i]['nm_uskpd']+"'";
var alamat = "'"+data.responden[i]['alamat']+"'";
$('#mki_search_skpd_result').append('<div class="mki_add_search_list"><i class="icon-target-2" style="font-size:12px;cursor:pointer;" onClick="addRespondenMap2('+kdskpd+','+nmskpd+')"></i> <span style="cursor: pointer;" onClick="showAsetUnitDetil('+kdskpd+',"");">['+kdskpd+'] '+nmskpd+'</span></div>');
$('#mki_add_search_list_'+data.responden[i].data_id).show();
}
} else {
$('#mki_search_skpd_result').html('<center><br/>Data responden dengan kata kunci <i>"<b>'+key+'</b>"</i> tidak ditemukan, silahkan masukkan kata kunci yang lain!</center>');
}
}
});
}
}
function showRespondenMap(r_id) {
//alert(r_id);
//var ridteks='rid_'+"'"+r_id+"'";
//$('#mki_menu_petatematik').click();
for(var i=0; i<pid.length; i++) {
markers[pid[i]].setMap(null);
}
//var bounds = new google.maps.LatLngBounds();
markers[pid[pid.length-1]].setMap(map);
//markers[ridteks].setMap(map);
//bounds.extend(markers['rid_'+r_id].getPosition());
//map.fitBounds(bounds);
}
function addRespondenMap(r_id,kd_brg) {
document.getElementById("noreg").value=r_id;
document.getElementById("kdbrg").value=kd_brg;
}
function addRespondenMap2(r_id,kd_brg) {
document.getElementById("kdskpd").value=r_id;
document.getElementById("nmskpd").value=kd_brg;
}
//function showRespondenDetil(r_id) {
function showRespondenDetil(r_id,kdbrg) {
//alert(r_id);alert(kdbrg);
infowindow.close();
$('#mki_preload_responden_detail').show();
$('#mki_loaded_responden_detail').hide();
$('#mki_content_responden_detail').stop().fadeIn();
$.ajax({
type : 'post',
url : base_url+'map/responden',
//data : 'data_id='+r_id, //{gol:gol,noreg:noreg,kdbrg:kdbrg,alamat1:alamat1,alamat2:alamat2,lat:lat,lon:lon,nodok:nodok,noser:noser,tglser:tglser}
data : {data_id:r_id,kdbrg:kdbrg},
cache : false,
success: function(html) {
if(html!='') {
$('#mki_preload_responden_detail').hide();
$('#mki_loaded_responden_detail').show();
$('#mki_table_responden_detail tbody').html(html);
}
}
});
}
function showAsetDetail(r_id,kdbrg) {
//alert(r_id);alert(kdbrg);
//infowindow.close();
$('#mki_preload_aset_detail').show();
$('#mki_loaded_aset_detail').hide();
$('#mki_content_aset_detail').stop().fadeIn();
$.ajax({
type : 'post',
url : base_url+'map/responden',
//data : 'data_id='+r_id, //{gol:gol,noreg:noreg,kdbrg:kdbrg,alamat1:alamat1,alamat2:alamat2,lat:lat,lon:lon,nodok:nodok,noser:noser,tglser:tglser}
data : {data_id:r_id,kdbrg:kdbrg},
cache : false,
success: function(html) {
if(html!='') {
$('#mki_preload_aset_detail').hide();
$('#mki_loaded_aset_detail').show();
$('#mki_table_aset_detail tbody').html(html);
}
}
});
}
function showAsetUnitDetil(kdskpd,kdbidang) {
//alert(kdskpd);
//alert(kdbidang);
infowindow.close();
$('#mki_preload_responden_detail').show();
$('#mki_loaded_responden_detail').hide();
$('#mki_content_responden_detail').stop().fadeIn();
$.ajax({
type : 'post',
url : base_url+'map/get_asetunit',
//data : 'data_id='+r_id, //{gol:gol,noreg:noreg,kdbrg:kdbrg,alamat1:alamat1,alamat2:alamat2,lat:lat,lon:lon,nodok:nodok,noser:noser,tglser:tglser}
data : {kdskpd:kdskpd,kdbidang:kdbidang},
cache : false,
success: function(html) {
if(html!='') {
$('#mki_preload_responden_detail').hide();
$('#mki_loaded_responden_detail').show();
$('#mki_table_responden_detail tbody').html(html);
}
}
});
}
function showUnitDetil(id,category) {
infowindow.close();
$('#mki_preload_responden_detail').show();
$('#mki_loaded_responden_detail').hide();
$('#mki_content_responden_detail').stop().fadeIn();
$.ajax({
type : 'post',
url : base_url+'map/unit/',
data : {id:id,category:category},
cache : false,
success: function(html) {
if(html!='') {
$('#mki_preload_responden_detail').hide();
$('#mki_loaded_responden_detail').show();
$('#mki_table_responden_detail tbody').html(html);
}
}
});
}
function showRespondenDetil_reload(r_id) {
$.ajax({
type : 'post',
url : base_url+'map/responden',
data : 'data_id='+r_id,
cache : false,
success: function(html) {
if(html!='') {
$('#mki_table_responden_detail tbody').html(html);
}
}
});
}
function showRespondenEdit(r_id) {
$('#mki_preload_responden_edit').show();
$('#mki_loaded_responden_edit').hide();
$('#mki_content_responden_edit').stop().fadeIn();
$.ajax({
type : 'post',
url : base_url+'responden/responden_edit',
data : 'data_id='+r_id,
cache : false,
success: function(html) {
if(html!='') {
$('#mki_preload_responden_edit').hide();
$('#mki_loaded_responden_edit').show();
$('#mki_table_responden_edit').html(html);
}
}
});
}
function showOptionAdd(id) {
resetOnReload();
$('#mki_preload_option_add').hide();
$('#mki_loaded_option_add').show();
$('#mki_content_kuisoner_option_add').stop().fadeIn();
if(id>0) {
$('#mki_kuisoner_kuisoner_savebtn').hide();
$('#mki_kuisoner_kuisoner_editbtn').show();
$('#mki_kadd_pilihan').hide();
$.ajax({
type : 'post',
url : base_url+'kuisoner/get_kuisoner/'+id,
cache : false,
success: function(datas) {
var data = $.parseJSON(datas);
if(data.status) {
$('#kadd_id').val(data.pertanyaan['kuisoner_group_id']);
$('#kadd_group').val(data.pertanyaan['kuisoner_group_id']).change();
$('#kadd_pertanyaan').val(data.pertanyaan['kuisoner_pertanyaan']);
if(data.pertanyaan['kuisoner_rekap']==1) {
$('#kadd_isrekap').prop({'checked':'checked'});
$('#kadd_box_rekap_nama').show();
$('#kadd_rekap_nama').val(data.pertanyaan['kuisoner_rekap_nama']);
}
$('.mki_form_option').remove();
} else {
closeOptionAdd();
}
}
});
}
}
function showPenggunaAdd() {
$('#uadd_id, #uadd_name, #uadd_username, #uadd_password_1, #uadd_password_2, #uadd_kelurahan').val('');
$('#mki_preload_adduser').hide();
$('.mki_form_error_display').html('');
$('#mki_loaded_adduser').show();
$('#mki_content_add_pengguna').stop().fadeIn();
}
function showPenggunaEdit(pid) {
$('#uadd_id, #uadd_name, #uadd_username, #uadd_password_1, #uadd_password_2, #uadd_kelurahan').val('');
$('.mki_form_error_display').html('');
$('#mki_preload_adduser').show();
$('#mki_loaded_adduser').hide();
$('#mki_content_add_pengguna').stop().fadeIn();
$.ajax({
type : 'post',
url : base_url+'setting/get_user/'+pid,
cache : false,
success: function(html) {
var datas = $.parseJSON(html);
if(datas.status) {
$('#uadd_id').val(datas['datas'].pengguna_id+'-'+datas['datas'].pengguna_pegawai_id).attr({'error':0});
$('#uadd_name').val(datas['datas'].pegawai_nama_depan).attr({'error':0});
$('#uadd_username').val(datas['datas'].pengguna_nama).attr({'error':0,'lastdata':datas['datas'].pengguna_nama});
$('#uadd_password_1').val('').attr({'error':0});
$('#uadd_password_2').val('').attr({'error':0});
$('#uadd_kelurahan').val(datas['datas'].pengguna_kelurahan_id).attr({'error':0});
$('#mki_preload_adduser').hide();
$('#mki_loaded_adduser').show();
}
}
});
}
function showAllMarkers() {
var bounds = new google.maps.LatLngBounds();
for(var i=0; i<pid.length; i++) {
markers[pid[i]].setMap(map);
bounds.extend(markers[pid[i]].getPosition());
}
map.fitBounds(bounds);
}
function clearAllMarkers() {
//var bounds = new google.maps.LatLngBounds();
////for(var i=0; i<pid.length; i++) {
////markers[pid[i]].setMap(null);
//bounds.extend(markers[pid[i]].getPosition());
////}
clearOverlays();
//map.fitBounds(bounds);
$('#mki_quick_search_result').html('');
$('#mki_add_search_result').html('');
}
function showRespondenAdd() {
$('#mki_preload_add_responden').show();
$('#mki_loaded_add_responden').hide();
$('#mki_content_add_responden').stop().fadeIn();
$.ajax({
type : 'get',
url : base_url+'responden/responden_add',
cache : false,
success: function(html) {
if(html!='') {
$('#mki_preload_add_responden').hide();
$('#mki_loaded_add_responden').show();
$('#mki_left_content_add_responden_html').html(html);
}
}
});
}
function onMapClick(activeright) {
clearOverlays();
$('.mki_left_content').stop().fadeOut(1200);
$('#mki_quick_search').stop().fadeIn(200);
if(activeright!='mki_right_content_pemetaan') {
if(activeright=='mki_right_content_petatematik'){
$( '#'+activeright ).animate({width: "0px",margin:"0 -10px 0 0"}, 200);
}else if(activeright!='mki_right_content_pemetaan'){
$( '#'+activeright ).animate({width: "0px"}, 200);
}
$( "#mki_right_content_pemetaan" ).animate({width: "22%"}, 200);
// $('#mki_right_content_pemetaan').css({right:0,'z-index':29});
// $('#'+activeright).animate({right:-300}, 500);
setTimeout(function() {
$('#mki_right_content_pemetaan').css({'z-index':30});
$('#mki_active_right').val('mki_right_content_pemetaan');
}, 500);
}
showQuickSearch();
addMode = false;
printMode = false;
}
function onSettingsClick(activeright) {
$('.mki_left_content').stop().fadeOut(1200);
$('#mki_content_pengaturan').stop().fadeIn();
if(activeright!='mki_right_content_pengaturan') {
$('#mki_right_content_pengaturan').css({right:0,'z-index':29});
$('#'+activeright).animate({right:-300}, 500);
setTimeout(function() {
$('#mki_right_content_pengaturan').css({'z-index':30});
$('#mki_active_right').val('mki_right_content_pengaturan');
}, 500);
}
addMode = false;
printMode = false;
}
function onAddClick(activeright) {
$('.mki_left_content').stop().fadeOut(1200);
$('#mki_quick_search').stop().fadeOut(200);
if(activeright!='mki_right_content_addpoint') {
if(activeright=='mki_right_content_petatematik'){
$( '#'+activeright ).animate({width: "0px",margin:"0 -10px 0 0"}, 200);
}else if(activeright!='mki_right_content_addpoint'){
$( '#'+activeright ).animate({width: "0px"}, 200);
}
$( "#mki_right_content_addpoint" ).animate({width: "22%"}, 200);
// $('#mki_right_content_addpoint').css({right:0,'z-index':29});
// $('#'+activeright).animate({right:-300}, 500);
setTimeout(function() {
$('#mki_right_content_addpoint').css({'z-index':30});
$('#mki_active_right').val('mki_right_content_addpoint');
}, 500);
}
skpd=false;
addMode = true;
printMode = false;
}
function onAddSKPDClick(activeright) {
$('.mki_left_content').stop().fadeOut(1200);
$('#mki_quick_search').stop().fadeOut(200);
if(activeright!='mki_right_content_addskpd') {
if(activeright=='mki_right_content_petatematik'){
$( '#'+activeright ).animate({width: "0px",margin:"0 -10px 0 0"}, 200);
}else if(activeright!='mki_right_content_addskpd'){
$( '#'+activeright ).animate({width: "0px"}, 200);
}
$( "#mki_right_content_addskpd" ).animate({width: "22%"}, 200);
// $('#mki_right_content_addskpd').css({right:0,'z-index':29});
// $('#'+activeright).animate({right:-300}, 500);
setTimeout(function() {
$('#mki_right_content_addskpd').css({'z-index':30});
$('#mki_active_right').val('mki_right_content_addskpd');
}, 500);
}
skpd=true;
addMode = true;
printMode = false;
}
function onTematikClick(activeright) {
//if($('#mki_left_content_data_html').html()=='') {
$('#mki_tematik_'+$('#mki_right_petatematik_menu_inload').val()).click();
//}
$('.mki_left_content').stop().fadeOut(1200);
//$('#mki_content_rekapitulasi').stop().fadeIn();
if(activeright!='mki_right_content_petatematik') {
$( '#'+activeright ).animate({width: "0px"}, 200);
$( "#mki_right_content_petatematik" ).css("margin", "0px");
$( "#mki_right_content_petatematik" ).animate({width: "22%",margin: "0px"}, 200);
//$('#mki_right_content_petatematik').css({right:0,'z-index':29});
//$('#'+activeright).animate({right:-300}, 500);
setTimeout(function() {
$('#mki_right_content_petatematik').css({'z-index':30});
$('#mki_active_right').val('mki_right_content_petatematik');
}, 500);
}
addMode = false;
printMode = false;
}
function onPrintClick(activeright) {
$('#mki_tematik_'+$('#mki_right_petatematik_menu_inload').val()).click();
$('.mki_left_content').stop().fadeOut(1200);
if(activeright!='mki_right_content_petatematik') {
if(activeright!='mki_right_content_petatematik'){
$( '#'+activeright ).animate({width: "0px"}, 200);
}
$( '#'+activeright ).animate({width: "0px"}, 200);
$( "#mki_right_content_petatematik" ).css("margin", "0px");
$( "#mki_right_content_petatematik" ).animate({width: "22%",margin: "0px"}, 200);
// $('#mki_right_content_petatematik').css({right:0,'z-index':29});
// $('#'+activeright).animate({right:-300}, 500);
setTimeout(function() {
$('#mki_right_content_petatematik').css({'z-index':30});
$('#mki_active_right').val('mki_right_content_petatematik');
}, 500);
}
addMode = false;
printMode = true;
}
function refreshTable() {
$('.paginate_active').click();
}
function openInNewTab(url) {
window.open(url, 'unduh');
}
function reloadKuisoner() {
$('#mki_list_datakuisoner_option').click();
}
function delete_elem(thiselem) {
var grandma = thiselem.parent().parent();
thiselem.parent().remove();
var thisstatus = thiselem.parent().attr('ref');
if(thisstatus=='child') {
if(grandma.find('.mki_form_option').length==1) {
grandma.attr({added:0}).hide();
grandma.prev().show();
grandma.prev().prev().show();
}
grandma.children('.mki_form_option').last().prev().children('input').focus();
} else if(thisstatus=='parent') {
if($('#mki_option_elem').children('.mki_form_option').length==2) {
insert_before_parent($('#mki_form_option_add_elem_parent'));
}
$('#mki_form_option_add_elem_parent').prev().children('input').focus();
}
renumbering_answer();
}
function saveResponden() {
//var gol = document.getElementById("mki_quick_search_rw").value;
var noreg = escape(document.getElementById("add_noreg_brg").value);
var kdbrg = document.getElementById("add_kd_brg").value;
var gol = kdbrg.substr(0,2);
//alert(gol);
//var alamat1 = document.getElementById("add_alamat_brg").value;
// var alamat2 = document.getElementById("add_alamat2_brg").value;
var lat = document.getElementById("add_lat").value;
var lon = document.getElementById("add_lon").value;
//var nodok = document.getElementById("add_nodok_brg").value;
// var noser = document.getElementById("add_noser_brg").value;
//var tglser = document.getElementById("add_tglser_brg").value;
//$('#mki_preload_responden_detail').show();
//$('#mki_loaded_responden_detail').hide();
//$('#mki_content_responden_detail').stop().fadeIn();
$.ajax({
type : 'post',
url : base_url+'map/save_responden',
//data : {gol:gol,noreg:noreg,kdbrg:kdbrg,alamat1:alamat1,alamat2:alamat2,lat:lat,lon:lon,nodok:nodok,noser:noser,tglser:tglser},
data : {gol:gol,noreg:noreg,lat:lat,lon:lon},
cache : false,
success: function(html) {
$('#mki_loaded_responden_detail').hide();
$('#mki_content_responden_detail').hide();
alert('Data Berhasil Disimpan');
}
});
}
function saveSKPD() {
var kdskpd = escape(document.getElementById("add_kd_skpd").value);
var lat = document.getElementById("add_lat").value;
var lon = document.getElementById("add_lon").value;
$.ajax({
type : 'post',
url : base_url+'map/save_skpd',
data : {kdskpd:kdskpd,lat:lat,lon:lon},
cache : false,
success: function(html) {
$('#mki_loaded_responden_detail').hide();
$('#mki_content_responden_detail').hide();
alert('Data Berhasil Disimpan');
}
});
} | JavaScript |
/*!
* jQuery Charms Plugin
* Original author: @aozora
* Licensed under the MIT license
*/
(function($, window, document, undefined){
// undefined is used here as the undefined global
// variable in ECMAScript 3 and is mutable (i.e. it can
// be changed by someone else). undefined isn't really
// being passed in so we can ensure that its value is
// truly undefined. In ES5, undefined can no longer be
// modified.
// window and document are passed through as local
// variables rather than as globals, because this (slightly)
// quickens the resolution process and can be more
// efficiently minified (especially when both are
// regularly referenced in your plugin).
// Create the defaults once
var pluginName = 'charms',
defaults = {
width: '320px',
animateDuration: 600
};
// The actual plugin constructor
function Charms(element, options){
this.element = element;
// jQuery has an extend method that merges the
// contents of two or more objects, storing the
// result in the first object. The first object
// is generally empty because we don't want to alter
// the default options for future instances of the plugin
this.options = $.extend({ }, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Charms.prototype = {
init: function(){
// Place initialization logic here
// You already have access to the DOM element and
// the options via the instance, e.g. this.element
// and this.options
// you can add more functions like the one below and
// call them like so: this.yourotherfunction(this.element, this.options).
},
showSection: function(sectionId, width){
var w = this.options.width;
if (width !== undefined){
w = width;
}
var transition = $.support.transition && $(this.element).hasClass('slide');
if (transition) {
var ow = $(this.element).eq(0).offsetWidth; // force reflow
}
$(this.element).addClass('in');
return false;
},
close: function(){
$(this.element).removeClass('in');
return false;
},
toggleSection: function(sectionId, width){
if ($(this.element).hasClass('in')){
this.close();
}else{
this.showSection(sectionId, width);
}
}//,
//
// togglePin: function () {
// var isPinned = $.cookie('charms_pinned');
//
// if (isPinned == null)
// {
// // pin
// $.cookie('charms_pinned', 'true');
// $.cookie('charms_width', $(this.element).width() );
// $("a#pin-charms").addClass("active");
// }
// else
// {
// // unpin
// $.cookie('charms_pinned', null);
// $.cookie('charms_width', null );
// $("a#pin-charms").removeClass("active");
// }
// }
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations and allowing any
// public function (ie. a function whose name doesn't start
// with an underscore) to be called via the jQuery plugin,
// e.g. $(element).defaultPluginName('functionName', arg1, arg2)
$.fn[pluginName] = function(options){
var args = arguments;
if (options === undefined || typeof options === 'object')
{
return this.each(function(){
if (!$.data(this, 'plugin_' + pluginName))
{
$.data(this, 'plugin_' + pluginName, new Charms(this, options));
}
});
} else if (typeof options === 'string' && options[0] !== '_' && options !== 'init')
{
return this.each(function(){
var instance = $.data(this, 'plugin_' + pluginName);
if (instance instanceof Charms && typeof instance[options] === 'function')
{
instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
});
}
};
})(jQuery, window, document);
(function ($)
{
$("#charms").charms();
$('.close-charms').click(function(e){
e.preventDefault();
$("#charms").charms('close');
});
/*$("a#pin-charms").click(function () {
$(this)
$("#charms").charms('togglePin');
});*/
})(jQuery);
| JavaScript |
/* ==========================================================
* bootstrap-pivot.js v1.0.0 alpha1
* http://aozora.github.com/bootmetro/
* ==========================================================
* Copyright 2013 Marcello Palmitessa
* ========================================================== */
!function ($) {
"use strict";
/* PIVOT CLASS DEFINITION
* ========================= */
var Pivot = function (element, options) {
this.$element = $(element)
this.options = options
this.options.slide && this.slide(this.options.slide)
}
Pivot.prototype = {
to: function (pos) {
var $active = this.$element.find('> .pivot-items > .pivot-item.active').eq(0)
, children = $active.parent().children()
, activePos = children.index($active)
, that = this
if (pos > (children.length - 1) || pos < 0)
return
if (this.sliding) {
return this.$element.one('slid', function () {
that.to(pos)
})
return
}
if (pos === activePos)
return
return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos]))
}
, next: function () {
if (this.sliding) return
return this.slide('next')
}
, prev: function () {
if (this.sliding) return
return this.slide('prev')
}
, slide: function (type, next) {
var $active = this.$element.find('> .pivot-items > .pivot-item.active').eq(0)
, $next = next || $active[type]()
, direction = type == 'next' ? 'left' : 'right'
, fallback = type == 'next' ? 'first' : 'last'
, that = this
, e
this.sliding = true
$next = $next.length ? $next : this.$element.find('> .pivot-items > .pivot-item')[fallback]()
e = $.Event('slide', {
relatedTarget: $next[0]
})
if ($next.hasClass('active')) {
that.sliding = false // this should prevent issue #45
return
}
if ($.support.transition && this.$element.hasClass('slide')) {
this.$element.trigger(e)
if (e.isDefaultPrevented())
return
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
this.$element.one($.support.transition.end, function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () { that.$element.trigger('slid') }, 0)
})
} else {
this.$element.trigger(e)
if (e.isDefaultPrevented())
return
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger('slid')
}
return this
}
}
/* PIVOT PLUGIN DEFINITION
* ========================== */
$.fn.pivot = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('pivot')
, options = $.extend({}, $.fn.pivot.defaults, typeof option == 'object' && option)
, action = typeof option == 'string' ? option : options.slide
if (!data)
$this.data('pivot', (data = new Pivot(this, options)))
if (typeof option == 'number')
data.to(option)
else if (action) data[action]()
})
}
$.fn.pivot.defaults = { }
$.fn.pivot.Constructor = Pivot
/* PIVOT DATA-API
* ================= */
$(document).on('click.pivot.data-api', '[data-pivot-index]', function (e) {
var $this = $(this), href
, $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
, options = $.extend({}, $target.data(), $this.data())
, $index = parseInt($this.attr('data-pivot-index'), 10);
$('[data-pivot-index].active').removeClass('active')
$this.addClass('active')
$target.pivot($index)
e.preventDefault()
})
}(window.jQuery);
| JavaScript |
/**
* @license
* Highcharts funnel module, Beta
*
* (c) 2010-2012 Torstein Hønsi
*
* License: www.highcharts.com/license
*/
/*global Highcharts */
(function (Highcharts) {
'use strict';
// create shortcuts
var defaultOptions = Highcharts.getOptions(),
defaultPlotOptions = defaultOptions.plotOptions,
seriesTypes = Highcharts.seriesTypes,
merge = Highcharts.merge,
noop = function () {},
each = Highcharts.each;
// set default options
defaultPlotOptions.funnel = merge(defaultPlotOptions.pie, {
center: ['50%', '50%'],
width: '90%',
neckWidth: '30%',
height: '100%',
neckHeight: '25%',
dataLabels: {
//position: 'right',
connectorWidth: 1,
connectorColor: '#606060'
},
size: true, // to avoid adapting to data label size in Pie.drawDataLabels
states: {
select: {
color: '#C0C0C0',
borderColor: '#000000',
shadow: false
}
}
});
seriesTypes.funnel = Highcharts.extendClass(seriesTypes.pie, {
type: 'funnel',
animate: noop,
/**
* Overrides the pie translate method
*/
translate: function () {
var
// Get positions - either an integer or a percentage string must be given
getLength = function (length, relativeTo) {
return (/%$/).test(length) ?
relativeTo * parseInt(length, 10) / 100 :
parseInt(length, 10);
},
sum = 0,
series = this,
chart = series.chart,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
cumulative = 0, // start at top
options = series.options,
center = options.center,
centerX = getLength(center[0], plotWidth),
centerY = getLength(center[0], plotHeight),
width = getLength(options.width, plotWidth),
tempWidth,
getWidthAt,
height = getLength(options.height, plotHeight),
neckWidth = getLength(options.neckWidth, plotWidth),
neckHeight = getLength(options.neckHeight, plotHeight),
neckY = height - neckHeight,
data = series.data,
path,
fraction,
half = options.dataLabels.position === 'left' ? 1 : 0,
x1,
y1,
x2,
x3,
y3,
x4,
y5;
// Return the width at a specific y coordinate
series.getWidthAt = getWidthAt = function (y) {
return y > height - neckHeight ?
neckWidth :
neckWidth + (width - neckWidth) * ((height - neckHeight - y) / (height - neckHeight));
};
series.getX = function (y, half) {
return centerX + (half ? -1 : 1) * ((getWidthAt(y) / 2) + options.dataLabels.distance);
};
// Expose
series.center = [centerX, centerY, height];
series.centerX = centerX;
/*
* Individual point coordinate naming:
*
* x1,y1 _________________ x2,y1
* \ /
* \ /
* \ /
* \ /
* \ /
* x3,y3 _________ x4,y3
*
* Additional for the base of the neck:
*
* | |
* | |
* | |
* x3,y5 _________ x4,y5
*/
// get the total sum
each(data, function (point) {
sum += point.y;
});
each(data, function (point) {
// set start and end positions
y5 = null;
fraction = sum ? point.y / sum : 0;
y1 = cumulative * height;
y3 = y1 + fraction * height;
//tempWidth = neckWidth + (width - neckWidth) * ((height - neckHeight - y1) / (height - neckHeight));
tempWidth = getWidthAt(y1);
x1 = centerX - tempWidth / 2;
x2 = x1 + tempWidth;
tempWidth = getWidthAt(y3);
x3 = centerX - tempWidth / 2;
x4 = x3 + tempWidth;
// the entire point is within the neck
if (y1 > neckY) {
x1 = x3 = centerX - neckWidth / 2;
x2 = x4 = centerX + neckWidth / 2;
// the base of the neck
} else if (y3 > neckY) {
y5 = y3;
tempWidth = getWidthAt(neckY);
x3 = centerX - tempWidth / 2;
x4 = x3 + tempWidth;
y3 = neckY;
}
// save the path
path = [
'M',
x1, y1,
'L',
x2, y1,
x4, y3
];
if (y5) {
path.push(x4, y5, x3, y5);
}
path.push(x3, y3, 'Z');
// prepare for using shared dr
point.shapeType = 'path';
point.shapeArgs = { d: path };
// for tooltips and data labels
point.percentage = fraction * 100;
point.plotX = centerX;
point.plotY = (y1 + (y5 || y3)) / 2;
// Placement of tooltips and data labels
point.tooltipPos = [
centerX,
point.plotY
];
// Slice is a noop on funnel points
point.slice = noop;
// Mimicking pie data label placement logic
point.half = half;
cumulative += fraction;
});
series.setTooltipPoints();
},
/**
* Draw a single point (wedge)
* @param {Object} point The point object
* @param {Object} color The color of the point
* @param {Number} brightness The brightness relative to the color
*/
drawPoints: function () {
var series = this,
options = series.options,
chart = series.chart,
renderer = chart.renderer;
each(series.data, function (point) {
var graphic = point.graphic,
shapeArgs = point.shapeArgs;
if (!graphic) { // Create the shapes
point.graphic = renderer.path(shapeArgs).
attr({
fill: point.color,
stroke: options.borderColor,
'stroke-width': options.borderWidth
}).
add(series.group);
} else { // Update the shapes
graphic.animate(shapeArgs);
}
});
},
/**
* Extend the pie data label method
*/
drawDataLabels: function () {
var data = this.data,
labelDistance = this.options.dataLabels.distance,
leftSide,
sign,
point,
i = data.length,
x,
y;
// In the original pie label anticollision logic, the slots are distributed
// from one labelDistance above to one labelDistance below the pie. In funnels
// we don't want this.
this.center[2] -= 2 * labelDistance;
// Set the label position array for each point.
while (i--) {
point = data[i];
leftSide = point.half;
sign = leftSide ? 1 : -1;
y = point.plotY;
x = this.getX(y, leftSide);
// set the anchor point for data labels
point.labelPos = [
0, // first break of connector
y, // a/a
x + (labelDistance - 5) * sign, // second break, right outside point shape
y, // a/a
x + labelDistance * sign, // landing point for connector
y, // a/a
leftSide ? 'right' : 'left', // alignment
0 // center angle
];
}
seriesTypes.pie.prototype.drawDataLabels.call(this);
}
});
}(Highcharts));
| JavaScript |
/**
* @license Data plugin for Highcharts
*
* (c) 2012-2013 Torstein Hønsi
* Last revision 2012-11-27
*
* License: www.highcharts.com/license
*/
/*
* The Highcharts Data plugin is a utility to ease parsing of input sources like
* CSV, HTML tables or grid views into basic configuration options for use
* directly in the Highcharts constructor.
*
* Demo: http://jsfiddle.net/highcharts/SnLFj/
*
* --- OPTIONS ---
*
* - columns : Array<Array<Mixed>>
* A two-dimensional array representing the input data on tabular form. This input can
* be used when the data is already parsed, for example from a grid view component.
* Each cell can be a string or number. If not switchRowsAndColumns is set, the columns
* are interpreted as series. See also the rows option.
*
* - complete : Function(chartOptions)
* The callback that is evaluated when the data is finished loading, optionally from an
* external source, and parsed. The first argument passed is a finished chart options
* object, containing series and an xAxis with categories if applicable. Thise options
* can be extended with additional options and passed directly to the chart constructor.
*
* - csv : String
* A comma delimited string to be parsed. Related options are startRow, endRow, startColumn
* and endColumn to delimit what part of the table is used. The lineDelimiter and
* itemDelimiter options define the CSV delimiter formats.
*
* - endColumn : Integer
* In tabular input data, the first row (indexed by 0) to use. Defaults to the last
* column containing data.
*
* - endRow : Integer
* In tabular input data, the last row (indexed by 0) to use. Defaults to the last row
* containing data.
*
* - googleSpreadsheetKey : String
* A Google Spreadsheet key. See https://developers.google.com/gdata/samples/spreadsheet_sample
* for general information on GS.
*
* - googleSpreadsheetWorksheet : String
* The Google Spreadsheet worksheet. The available id's can be read from
* https://spreadsheets.google.com/feeds/worksheets/{key}/public/basic
*
* - itemDelimiter : String
* Item or cell delimiter for parsing CSV. Defaults to ",".
*
* - lineDelimiter : String
* Line delimiter for parsing CSV. Defaults to "\n".
*
* - parsed : Function
* A callback function to access the parsed columns, the two-dimentional input data
* array directly, before they are interpreted into series data and categories.
*
* - parseDate : Function
* A callback function to parse string representations of dates into JavaScript timestamps.
* Return an integer on success.
*
* - rows : Array<Array<Mixed>>
* The same as the columns input option, but defining rows intead of columns.
*
* - startColumn : Integer
* In tabular input data, the first column (indexed by 0) to use.
*
* - startRow : Integer
* In tabular input data, the first row (indexed by 0) to use.
*
* - table : String|HTMLElement
* A HTML table or the id of such to be parsed as input data. Related options ara startRow,
* endRow, startColumn and endColumn to delimit what part of the table is used.
*/
// JSLint options:
/*global jQuery */
(function (Highcharts) {
// Utilities
var each = Highcharts.each;
// The Data constructor
var Data = function (options) {
this.init(options);
};
// Set the prototype properties
Highcharts.extend(Data.prototype, {
/**
* Initialize the Data object with the given options
*/
init: function (options) {
this.options = options;
this.columns = options.columns || this.rowsToColumns(options.rows) || [];
// No need to parse or interpret anything
if (this.columns.length) {
this.dataFound();
// Parse and interpret
} else {
// Parse a CSV string if options.csv is given
this.parseCSV();
// Parse a HTML table if options.table is given
this.parseTable();
// Parse a Google Spreadsheet
this.parseGoogleSpreadsheet();
}
},
dataFound: function () {
// Interpret the values into right types
this.parseTypes();
// Use first row for series names?
this.findHeaderRow();
// Handle columns if a handleColumns callback is given
this.parsed();
// Complete if a complete callback is given
this.complete();
},
/**
* Parse a CSV input string
*/
parseCSV: function () {
var self = this,
options = this.options,
csv = options.csv,
columns = this.columns,
startRow = options.startRow || 0,
endRow = options.endRow || Number.MAX_VALUE,
startColumn = options.startColumn || 0,
endColumn = options.endColumn || Number.MAX_VALUE,
lines,
activeRowNo = 0;
if (csv) {
lines = csv
.replace(/\r\n/g, "\n") // Unix
.replace(/\r/g, "\n") // Mac
.split(options.lineDelimiter || "\n");
each(lines, function (line, rowNo) {
var trimmed = self.trim(line),
isComment = trimmed.indexOf('#') === 0,
isBlank = trimmed === '',
items;
if (rowNo >= startRow && rowNo <= endRow && !isComment && !isBlank) {
items = line.split(options.itemDelimiter || ',');
each(items, function (item, colNo) {
if (colNo >= startColumn && colNo <= endColumn) {
if (!columns[colNo - startColumn]) {
columns[colNo - startColumn] = [];
}
columns[colNo - startColumn][activeRowNo] = item;
}
});
activeRowNo += 1;
}
});
this.dataFound();
}
},
/**
* Parse a HTML table
*/
parseTable: function () {
var options = this.options,
table = options.table,
columns = this.columns,
startRow = options.startRow || 0,
endRow = options.endRow || Number.MAX_VALUE,
startColumn = options.startColumn || 0,
endColumn = options.endColumn || Number.MAX_VALUE,
colNo;
if (table) {
if (typeof table === 'string') {
table = document.getElementById(table);
}
each(table.getElementsByTagName('tr'), function (tr, rowNo) {
colNo = 0;
if (rowNo >= startRow && rowNo <= endRow) {
each(tr.childNodes, function (item) {
if ((item.tagName === 'TD' || item.tagName === 'TH') && colNo >= startColumn && colNo <= endColumn) {
if (!columns[colNo]) {
columns[colNo] = [];
}
columns[colNo][rowNo - startRow] = item.innerHTML;
colNo += 1;
}
});
}
});
this.dataFound(); // continue
}
},
/**
* TODO:
* - switchRowsAndColumns
*/
parseGoogleSpreadsheet: function () {
var self = this,
options = this.options,
googleSpreadsheetKey = options.googleSpreadsheetKey,
columns = this.columns,
startRow = options.startRow || 0,
endRow = options.endRow || Number.MAX_VALUE,
startColumn = options.startColumn || 0,
endColumn = options.endColumn || Number.MAX_VALUE,
gr, // google row
gc; // google column
if (googleSpreadsheetKey) {
jQuery.getJSON('https://spreadsheets.google.com/feeds/cells/' +
googleSpreadsheetKey + '/' + (options.googleSpreadsheetWorksheet || 'od6') +
'/public/values?alt=json-in-script&callback=?',
function (json) {
// Prepare the data from the spreadsheat
var cells = json.feed.entry,
cell,
cellCount = cells.length,
colCount = 0,
rowCount = 0,
i;
// First, find the total number of columns and rows that
// are actually filled with data
for (i = 0; i < cellCount; i++) {
cell = cells[i];
colCount = Math.max(colCount, cell.gs$cell.col);
rowCount = Math.max(rowCount, cell.gs$cell.row);
}
// Set up arrays containing the column data
for (i = 0; i < colCount; i++) {
if (i >= startColumn && i <= endColumn) {
// Create new columns with the length of either end-start or rowCount
columns[i - startColumn] = [];
// Setting the length to avoid jslint warning
columns[i - startColumn].length = Math.min(rowCount, endRow - startRow);
}
}
// Loop over the cells and assign the value to the right
// place in the column arrays
for (i = 0; i < cellCount; i++) {
cell = cells[i];
gr = cell.gs$cell.row - 1; // rows start at 1
gc = cell.gs$cell.col - 1; // columns start at 1
// If both row and col falls inside start and end
// set the transposed cell value in the newly created columns
if (gc >= startColumn && gc <= endColumn &&
gr >= startRow && gr <= endRow) {
columns[gc - startColumn][gr - startRow] = cell.content.$t;
}
}
self.dataFound();
});
}
},
/**
* Find the header row. For now, we just check whether the first row contains
* numbers or strings. Later we could loop down and find the first row with
* numbers.
*/
findHeaderRow: function () {
var headerRow = 0;
each(this.columns, function (column) {
if (typeof column[0] !== 'string') {
headerRow = null;
}
});
this.headerRow = 0;
},
/**
* Trim a string from whitespace
*/
trim: function (str) {
return typeof str === 'string' ? str.replace(/^\s+|\s+$/g, '') : str;
},
/**
* Parse numeric cells in to number types and date types in to true dates.
* @param {Object} columns
*/
parseTypes: function () {
var columns = this.columns,
col = columns.length,
row,
val,
floatVal,
trimVal,
dateVal;
while (col--) {
row = columns[col].length;
while (row--) {
val = columns[col][row];
floatVal = parseFloat(val);
trimVal = this.trim(val);
/*jslint eqeq: true*/
if (trimVal == floatVal) { // is numeric
/*jslint eqeq: false*/
columns[col][row] = floatVal;
// If the number is greater than milliseconds in a year, assume datetime
if (floatVal > 365 * 24 * 3600 * 1000) {
columns[col].isDatetime = true;
} else {
columns[col].isNumeric = true;
}
} else { // string, continue to determine if it is a date string or really a string
dateVal = this.parseDate(val);
if (col === 0 && typeof dateVal === 'number' && !isNaN(dateVal)) { // is date
columns[col][row] = dateVal;
columns[col].isDatetime = true;
} else { // string
columns[col][row] = trimVal === '' ? null : trimVal;
}
}
}
}
},
//*
dateFormats: {
'YYYY-mm-dd': {
regex: '^([0-9]{4})-([0-9]{2})-([0-9]{2})$',
parser: function (match) {
return Date.UTC(+match[1], match[2] - 1, +match[3]);
}
}
},
// */
/**
* Parse a date and return it as a number. Overridable through options.parseDate.
*/
parseDate: function (val) {
var parseDate = this.options.parseDate,
ret,
key,
format,
match;
if (parseDate) {
ret = parseDate(val);
}
if (typeof val === 'string') {
for (key in this.dateFormats) {
format = this.dateFormats[key];
match = val.match(format.regex);
if (match) {
ret = format.parser(match);
}
}
}
return ret;
},
/**
* Reorganize rows into columns
*/
rowsToColumns: function (rows) {
var row,
rowsLength,
col,
colsLength,
columns;
if (rows) {
columns = [];
rowsLength = rows.length;
for (row = 0; row < rowsLength; row++) {
colsLength = rows[row].length;
for (col = 0; col < colsLength; col++) {
if (!columns[col]) {
columns[col] = [];
}
columns[col][row] = rows[row][col];
}
}
}
return columns;
},
/**
* A hook for working directly on the parsed columns
*/
parsed: function () {
if (this.options.parsed) {
this.options.parsed.call(this, this.columns);
}
},
/**
* If a complete callback function is provided in the options, interpret the
* columns into a Highcharts options object.
*/
complete: function () {
var columns = this.columns,
hasXData,
categories,
firstCol,
type,
options = this.options,
series,
data,
name,
i,
j;
if (options.complete) {
// Use first column for X data or categories?
if (columns.length > 1) {
firstCol = columns.shift();
if (this.headerRow === 0) {
firstCol.shift(); // remove the first cell
}
// Use the first column for categories or X values
hasXData = firstCol.isNumeric || firstCol.isDatetime;
if (!hasXData) { // means type is neither datetime nor linear
categories = firstCol;
}
if (firstCol.isDatetime) {
type = 'datetime';
}
}
// Use the next columns for series
series = [];
for (i = 0; i < columns.length; i++) {
if (this.headerRow === 0) {
name = columns[i].shift();
}
data = [];
for (j = 0; j < columns[i].length; j++) {
data[j] = columns[i][j] !== undefined ?
(hasXData ?
[firstCol[j], columns[i][j]] :
columns[i][j]
) :
null;
}
series[i] = {
name: name,
data: data
};
}
// Do the callback
options.complete({
xAxis: {
categories: categories,
type: type
},
series: series
});
}
}
});
// Register the Data prototype and data function on Highcharts
Highcharts.Data = Data;
Highcharts.data = function (options) {
return new Data(options);
};
// Extend Chart.init so that the Chart constructor accepts a new configuration
// option group, data.
Highcharts.wrap(Highcharts.Chart.prototype, 'init', function (proceed, userOptions, callback) {
var chart = this;
if (userOptions && userOptions.data) {
Highcharts.data(Highcharts.extend(userOptions.data, {
complete: function (dataOptions) {
// Merge series configs
if (userOptions.series) {
each(userOptions.series, function (series, i) {
userOptions.series[i] = Highcharts.merge(series, dataOptions.series[i]);
});
}
// Do the merge
userOptions = Highcharts.merge(dataOptions, userOptions);
proceed.call(chart, userOptions, callback);
}
}));
} else {
proceed.call(chart, userOptions, callback);
}
});
}(Highcharts));
| JavaScript |
/**
* @license A class to parse color values
* @author Stoyan Stefanov <sstoo@gmail.com>
* @link http://www.phpied.com/rgb-color-parser-in-javascript/
* Use it if you like it
*
*/
function RGBColor(color_string)
{
this.ok = false;
// strip any leading #
if (color_string.charAt(0) == '#') { // remove # if any
color_string = color_string.substr(1,6);
}
color_string = color_string.replace(/ /g,'');
color_string = color_string.toLowerCase();
// before getting into regexps, try simple matches
// and overwrite the input
var simple_colors = {
aliceblue: 'f0f8ff',
antiquewhite: 'faebd7',
aqua: '00ffff',
aquamarine: '7fffd4',
azure: 'f0ffff',
beige: 'f5f5dc',
bisque: 'ffe4c4',
black: '000000',
blanchedalmond: 'ffebcd',
blue: '0000ff',
blueviolet: '8a2be2',
brown: 'a52a2a',
burlywood: 'deb887',
cadetblue: '5f9ea0',
chartreuse: '7fff00',
chocolate: 'd2691e',
coral: 'ff7f50',
cornflowerblue: '6495ed',
cornsilk: 'fff8dc',
crimson: 'dc143c',
cyan: '00ffff',
darkblue: '00008b',
darkcyan: '008b8b',
darkgoldenrod: 'b8860b',
darkgray: 'a9a9a9',
darkgreen: '006400',
darkkhaki: 'bdb76b',
darkmagenta: '8b008b',
darkolivegreen: '556b2f',
darkorange: 'ff8c00',
darkorchid: '9932cc',
darkred: '8b0000',
darksalmon: 'e9967a',
darkseagreen: '8fbc8f',
darkslateblue: '483d8b',
darkslategray: '2f4f4f',
darkturquoise: '00ced1',
darkviolet: '9400d3',
deeppink: 'ff1493',
deepskyblue: '00bfff',
dimgray: '696969',
dodgerblue: '1e90ff',
feldspar: 'd19275',
firebrick: 'b22222',
floralwhite: 'fffaf0',
forestgreen: '228b22',
fuchsia: 'ff00ff',
gainsboro: 'dcdcdc',
ghostwhite: 'f8f8ff',
gold: 'ffd700',
goldenrod: 'daa520',
gray: '808080',
green: '008000',
greenyellow: 'adff2f',
honeydew: 'f0fff0',
hotpink: 'ff69b4',
indianred : 'cd5c5c',
indigo : '4b0082',
ivory: 'fffff0',
khaki: 'f0e68c',
lavender: 'e6e6fa',
lavenderblush: 'fff0f5',
lawngreen: '7cfc00',
lemonchiffon: 'fffacd',
lightblue: 'add8e6',
lightcoral: 'f08080',
lightcyan: 'e0ffff',
lightgoldenrodyellow: 'fafad2',
lightgrey: 'd3d3d3',
lightgreen: '90ee90',
lightpink: 'ffb6c1',
lightsalmon: 'ffa07a',
lightseagreen: '20b2aa',
lightskyblue: '87cefa',
lightslateblue: '8470ff',
lightslategray: '778899',
lightsteelblue: 'b0c4de',
lightyellow: 'ffffe0',
lime: '00ff00',
limegreen: '32cd32',
linen: 'faf0e6',
magenta: 'ff00ff',
maroon: '800000',
mediumaquamarine: '66cdaa',
mediumblue: '0000cd',
mediumorchid: 'ba55d3',
mediumpurple: '9370d8',
mediumseagreen: '3cb371',
mediumslateblue: '7b68ee',
mediumspringgreen: '00fa9a',
mediumturquoise: '48d1cc',
mediumvioletred: 'c71585',
midnightblue: '191970',
mintcream: 'f5fffa',
mistyrose: 'ffe4e1',
moccasin: 'ffe4b5',
navajowhite: 'ffdead',
navy: '000080',
oldlace: 'fdf5e6',
olive: '808000',
olivedrab: '6b8e23',
orange: 'ffa500',
orangered: 'ff4500',
orchid: 'da70d6',
palegoldenrod: 'eee8aa',
palegreen: '98fb98',
paleturquoise: 'afeeee',
palevioletred: 'd87093',
papayawhip: 'ffefd5',
peachpuff: 'ffdab9',
peru: 'cd853f',
pink: 'ffc0cb',
plum: 'dda0dd',
powderblue: 'b0e0e6',
purple: '800080',
red: 'ff0000',
rosybrown: 'bc8f8f',
royalblue: '4169e1',
saddlebrown: '8b4513',
salmon: 'fa8072',
sandybrown: 'f4a460',
seagreen: '2e8b57',
seashell: 'fff5ee',
sienna: 'a0522d',
silver: 'c0c0c0',
skyblue: '87ceeb',
slateblue: '6a5acd',
slategray: '708090',
snow: 'fffafa',
springgreen: '00ff7f',
steelblue: '4682b4',
tan: 'd2b48c',
teal: '008080',
thistle: 'd8bfd8',
tomato: 'ff6347',
turquoise: '40e0d0',
violet: 'ee82ee',
violetred: 'd02090',
wheat: 'f5deb3',
white: 'ffffff',
whitesmoke: 'f5f5f5',
yellow: 'ffff00',
yellowgreen: '9acd32'
};
for (var key in simple_colors) {
if (color_string == key) {
color_string = simple_colors[key];
}
}
// emd of simple type-in colors
// array of color definition objects
var color_defs = [
{
re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
process: function (bits){
return [
parseInt(bits[1]),
parseInt(bits[2]),
parseInt(bits[3])
];
}
},
{
re: /^(\w{2})(\w{2})(\w{2})$/,
example: ['#00ff00', '336699'],
process: function (bits){
return [
parseInt(bits[1], 16),
parseInt(bits[2], 16),
parseInt(bits[3], 16)
];
}
},
{
re: /^(\w{1})(\w{1})(\w{1})$/,
example: ['#fb0', 'f0f'],
process: function (bits){
return [
parseInt(bits[1] + bits[1], 16),
parseInt(bits[2] + bits[2], 16),
parseInt(bits[3] + bits[3], 16)
];
}
}
];
// search through the definitions to find a match
for (var i = 0; i < color_defs.length; i++) {
var re = color_defs[i].re;
var processor = color_defs[i].process;
var bits = re.exec(color_string);
if (bits) {
channels = processor(bits);
this.r = channels[0];
this.g = channels[1];
this.b = channels[2];
this.ok = true;
}
}
// validate/cleanup values
this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
// some getters
this.toRGB = function () {
return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
}
this.toHex = function () {
var r = this.r.toString(16);
var g = this.g.toString(16);
var b = this.b.toString(16);
if (r.length == 1) r = '0' + r;
if (g.length == 1) g = '0' + g;
if (b.length == 1) b = '0' + b;
return '#' + r + g + b;
}
// help
this.getHelpXML = function () {
var examples = new Array();
// add regexps
for (var i = 0; i < color_defs.length; i++) {
var example = color_defs[i].example;
for (var j = 0; j < example.length; j++) {
examples[examples.length] = example[j];
}
}
// add type-in colors
for (var sc in simple_colors) {
examples[examples.length] = sc;
}
var xml = document.createElement('ul');
xml.setAttribute('id', 'rgbcolor-examples');
for (var i = 0; i < examples.length; i++) {
try {
var list_item = document.createElement('li');
var list_color = new RGBColor(examples[i]);
var example_div = document.createElement('div');
example_div.style.cssText =
'margin: 3px; '
+ 'border: 1px solid black; '
+ 'background:' + list_color.toHex() + '; '
+ 'color:' + list_color.toHex()
;
example_div.appendChild(document.createTextNode('test'));
var list_item_value = document.createTextNode(
' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()
);
list_item.appendChild(example_div);
list_item.appendChild(list_item_value);
xml.appendChild(list_item);
} catch(e){}
}
return xml;
}
}
/**
* @license canvg.js - Javascript SVG parser and renderer on Canvas
* MIT Licensed
* Gabe Lerner (gabelerner@gmail.com)
* http://code.google.com/p/canvg/
*
* Requires: rgbcolor.js - http://www.phpied.com/rgb-color-parser-in-javascript/
*
*/
if(!window.console) {
window.console = {};
window.console.log = function(str) {};
window.console.dir = function(str) {};
}
if(!Array.prototype.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}
(function(){
// canvg(target, s)
// empty parameters: replace all 'svg' elements on page with 'canvas' elements
// target: canvas element or the id of a canvas element
// s: svg string, url to svg file, or xml document
// opts: optional hash of options
// ignoreMouse: true => ignore mouse events
// ignoreAnimation: true => ignore animations
// ignoreDimensions: true => does not try to resize canvas
// ignoreClear: true => does not clear canvas
// offsetX: int => draws at a x offset
// offsetY: int => draws at a y offset
// scaleWidth: int => scales horizontally to width
// scaleHeight: int => scales vertically to height
// renderCallback: function => will call the function after the first render is completed
// forceRedraw: function => will call the function on every frame, if it returns true, will redraw
this.canvg = function (target, s, opts) {
// no parameters
if (target == null && s == null && opts == null) {
var svgTags = document.getElementsByTagName('svg');
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var c = document.createElement('canvas');
c.width = svgTag.clientWidth;
c.height = svgTag.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}
return;
}
opts = opts || {};
if (typeof target == 'string') {
target = document.getElementById(target);
}
// reuse class per canvas
var svg;
if (target.svg == null) {
svg = build();
target.svg = svg;
}
else {
svg = target.svg;
svg.stop();
}
svg.opts = opts;
var ctx = target.getContext('2d');
if (typeof(s.documentElement) != 'undefined') {
// load from xml doc
svg.loadXmlDoc(ctx, s);
}
else if (s.substr(0,1) == '<') {
// load from xml string
svg.loadXml(ctx, s);
}
else {
// load from url
svg.load(ctx, s);
}
}
function build() {
var svg = { };
svg.FRAMERATE = 30;
svg.MAX_VIRTUAL_PIXELS = 30000;
// globals
svg.init = function(ctx) {
svg.Definitions = {};
svg.Styles = {};
svg.Animations = [];
svg.Images = [];
svg.ctx = ctx;
svg.ViewPort = new (function () {
this.viewPorts = [];
this.Clear = function() { this.viewPorts = []; }
this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); }
this.RemoveCurrent = function() { this.viewPorts.pop(); }
this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; }
this.width = function() { return this.Current().width; }
this.height = function() { return this.Current().height; }
this.ComputeSize = function(d) {
if (d != null && typeof(d) == 'number') return d;
if (d == 'x') return this.width();
if (d == 'y') return this.height();
return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2);
}
});
}
svg.init();
// images loaded
svg.ImagesLoaded = function() {
for (var i=0; i<svg.Images.length; i++) {
if (!svg.Images[i].loaded) return false;
}
return true;
}
// trim
svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); }
// compress spaces
svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); }
// ajax
svg.ajax = function(url) {
var AJAX;
if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();}
else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');}
if(AJAX){
AJAX.open('GET',url,false);
AJAX.send(null);
return AJAX.responseText;
}
return null;
}
// parse xml
svg.parseXml = function(xml) {
if (window.DOMParser)
{
var parser = new DOMParser();
return parser.parseFromString(xml, 'text/xml');
}
else
{
xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
xmlDoc.loadXML(xml);
return xmlDoc;
}
}
svg.Property = function(name, value) {
this.name = name;
this.value = value;
this.hasValue = function() {
return (this.value != null && this.value !== '');
}
// return the numerical value of the property
this.numValue = function() {
if (!this.hasValue()) return 0;
var n = parseFloat(this.value);
if ((this.value + '').match(/%$/)) {
n = n / 100.0;
}
return n;
}
this.valueOrDefault = function(def) {
if (this.hasValue()) return this.value;
return def;
}
this.numValueOrDefault = function(def) {
if (this.hasValue()) return this.numValue();
return def;
}
/* EXTENSIONS */
var that = this;
// color extensions
this.Color = {
// augment the current color value with the opacity
addOpacity: function(opacity) {
var newValue = that.value;
if (opacity != null && opacity != '') {
var color = new RGBColor(that.value);
if (color.ok) {
newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')';
}
}
return new svg.Property(that.name, newValue);
}
}
// definition extensions
this.Definition = {
// get the definition from the definitions table
getDefinition: function() {
var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2');
return svg.Definitions[name];
},
isUrl: function() {
return that.value.indexOf('url(') == 0
},
getFillStyle: function(e) {
var def = this.getDefinition();
// gradient
if (def != null && def.createGradient) {
return def.createGradient(svg.ctx, e);
}
// pattern
if (def != null && def.createPattern) {
return def.createPattern(svg.ctx, e);
}
return null;
}
}
// length extensions
this.Length = {
DPI: function(viewPort) {
return 96.0; // TODO: compute?
},
EM: function(viewPort) {
var em = 12;
var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort);
return em;
},
// get the length as pixels
toPixels: function(viewPort) {
if (!that.hasValue()) return 0;
var s = that.value+'';
if (s.match(/em$/)) return that.numValue() * this.EM(viewPort);
if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0;
if (s.match(/px$/)) return that.numValue();
if (s.match(/pt$/)) return that.numValue() * 1.25;
if (s.match(/pc$/)) return that.numValue() * 15;
if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54;
if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4;
if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort);
if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort);
return that.numValue();
}
}
// time extensions
this.Time = {
// get the time as milliseconds
toMilliseconds: function() {
if (!that.hasValue()) return 0;
var s = that.value+'';
if (s.match(/s$/)) return that.numValue() * 1000;
if (s.match(/ms$/)) return that.numValue();
return that.numValue();
}
}
// angle extensions
this.Angle = {
// get the angle as radians
toRadians: function() {
if (!that.hasValue()) return 0;
var s = that.value+'';
if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0);
if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0);
if (s.match(/rad$/)) return that.numValue();
return that.numValue() * (Math.PI / 180.0);
}
}
}
// fonts
svg.Font = new (function() {
this.Styles = ['normal','italic','oblique','inherit'];
this.Variants = ['normal','small-caps','inherit'];
this.Weights = ['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','inherit'];
this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) {
var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font);
return {
fontFamily: fontFamily || f.fontFamily,
fontSize: fontSize || f.fontSize,
fontStyle: fontStyle || f.fontStyle,
fontWeight: fontWeight || f.fontWeight,
fontVariant: fontVariant || f.fontVariant,
toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') }
}
}
var that = this;
this.Parse = function(s) {
var f = {};
var d = svg.trim(svg.compressSpaces(s || '')).split(' ');
var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false }
var ff = '';
for (var i=0; i<d.length; i++) {
if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; }
else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; }
else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontWeight = d[i]; set.fontStyle = set.fontVariant = set.fontWeight = true; }
else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; }
else { if (d[i] != 'inherit') ff += d[i]; }
} if (ff != '') f.fontFamily = ff;
return f;
}
});
// points and paths
svg.ToNumberArray = function(s) {
var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' ');
for (var i=0; i<a.length; i++) {
a[i] = parseFloat(a[i]);
}
return a;
}
svg.Point = function(x, y) {
this.x = x;
this.y = y;
this.angleTo = function(p) {
return Math.atan2(p.y - this.y, p.x - this.x);
}
this.applyTransform = function(v) {
var xp = this.x * v[0] + this.y * v[2] + v[4];
var yp = this.x * v[1] + this.y * v[3] + v[5];
this.x = xp;
this.y = yp;
}
}
svg.CreatePoint = function(s) {
var a = svg.ToNumberArray(s);
return new svg.Point(a[0], a[1]);
}
svg.CreatePath = function(s) {
var a = svg.ToNumberArray(s);
var path = [];
for (var i=0; i<a.length; i+=2) {
path.push(new svg.Point(a[i], a[i+1]));
}
return path;
}
// bounding box
svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want
this.x1 = Number.NaN;
this.y1 = Number.NaN;
this.x2 = Number.NaN;
this.y2 = Number.NaN;
this.x = function() { return this.x1; }
this.y = function() { return this.y1; }
this.width = function() { return this.x2 - this.x1; }
this.height = function() { return this.y2 - this.y1; }
this.addPoint = function(x, y) {
if (x != null) {
if (isNaN(this.x1) || isNaN(this.x2)) {
this.x1 = x;
this.x2 = x;
}
if (x < this.x1) this.x1 = x;
if (x > this.x2) this.x2 = x;
}
if (y != null) {
if (isNaN(this.y1) || isNaN(this.y2)) {
this.y1 = y;
this.y2 = y;
}
if (y < this.y1) this.y1 = y;
if (y > this.y2) this.y2 = y;
}
}
this.addX = function(x) { this.addPoint(x, null); }
this.addY = function(y) { this.addPoint(null, y); }
this.addBoundingBox = function(bb) {
this.addPoint(bb.x1, bb.y1);
this.addPoint(bb.x2, bb.y2);
}
this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) {
var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0)
var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0)
var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0)
var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0)
this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y);
}
this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
// from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y];
this.addPoint(p0[0], p0[1]);
this.addPoint(p3[0], p3[1]);
for (i=0; i<=1; i++) {
var f = function(t) {
return Math.pow(1-t, 3) * p0[i]
+ 3 * Math.pow(1-t, 2) * t * p1[i]
+ 3 * (1-t) * Math.pow(t, 2) * p2[i]
+ Math.pow(t, 3) * p3[i];
}
var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
var c = 3 * p1[i] - 3 * p0[i];
if (a == 0) {
if (b == 0) continue;
var t = -c / b;
if (0 < t && t < 1) {
if (i == 0) this.addX(f(t));
if (i == 1) this.addY(f(t));
}
continue;
}
var b2ac = Math.pow(b, 2) - 4 * c * a;
if (b2ac < 0) continue;
var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
if (0 < t1 && t1 < 1) {
if (i == 0) this.addX(f(t1));
if (i == 1) this.addY(f(t1));
}
var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
if (0 < t2 && t2 < 1) {
if (i == 0) this.addX(f(t2));
if (i == 1) this.addY(f(t2));
}
}
}
this.isPointInBox = function(x, y) {
return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2);
}
this.addPoint(x1, y1);
this.addPoint(x2, y2);
}
// transforms
svg.Transform = function(v) {
var that = this;
this.Type = {}
// translate
this.Type.translate = function(s) {
this.p = svg.CreatePoint(s);
this.apply = function(ctx) {
ctx.translate(this.p.x || 0.0, this.p.y || 0.0);
}
this.applyToPoint = function(p) {
p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
}
}
// rotate
this.Type.rotate = function(s) {
var a = svg.ToNumberArray(s);
this.angle = new svg.Property('angle', a[0]);
this.cx = a[1] || 0;
this.cy = a[2] || 0;
this.apply = function(ctx) {
ctx.translate(this.cx, this.cy);
ctx.rotate(this.angle.Angle.toRadians());
ctx.translate(-this.cx, -this.cy);
}
this.applyToPoint = function(p) {
var a = this.angle.Angle.toRadians();
p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]);
p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]);
}
}
this.Type.scale = function(s) {
this.p = svg.CreatePoint(s);
this.apply = function(ctx) {
ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0);
}
this.applyToPoint = function(p) {
p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]);
}
}
this.Type.matrix = function(s) {
this.m = svg.ToNumberArray(s);
this.apply = function(ctx) {
ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
}
this.applyToPoint = function(p) {
p.applyTransform(this.m);
}
}
this.Type.SkewBase = function(s) {
this.base = that.Type.matrix;
this.base(s);
this.angle = new svg.Property('angle', s);
}
this.Type.SkewBase.prototype = new this.Type.matrix;
this.Type.skewX = function(s) {
this.base = that.Type.SkewBase;
this.base(s);
this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0];
}
this.Type.skewX.prototype = new this.Type.SkewBase;
this.Type.skewY = function(s) {
this.base = that.Type.SkewBase;
this.base(s);
this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0];
}
this.Type.skewY.prototype = new this.Type.SkewBase;
this.transforms = [];
this.apply = function(ctx) {
for (var i=0; i<this.transforms.length; i++) {
this.transforms[i].apply(ctx);
}
}
this.applyToPoint = function(p) {
for (var i=0; i<this.transforms.length; i++) {
this.transforms[i].applyToPoint(p);
}
}
var data = svg.trim(svg.compressSpaces(v)).split(/\s(?=[a-z])/);
for (var i=0; i<data.length; i++) {
var type = data[i].split('(')[0];
var s = data[i].split('(')[1].replace(')','');
var transform = new this.Type[type](s);
this.transforms.push(transform);
}
}
// aspect ratio
svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {
// aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
aspectRatio = svg.compressSpaces(aspectRatio);
aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer
var align = aspectRatio.split(' ')[0] || 'xMidYMid';
var meetOrSlice = aspectRatio.split(' ')[1] || 'meet';
// calculate scale
var scaleX = width / desiredWidth;
var scaleY = height / desiredHeight;
var scaleMin = Math.min(scaleX, scaleY);
var scaleMax = Math.max(scaleX, scaleY);
if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; }
if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; }
refX = new svg.Property('refX', refX);
refY = new svg.Property('refY', refY);
if (refX.hasValue() && refY.hasValue()) {
ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y'));
}
else {
// align
if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);
if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);
if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0);
if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight);
}
// scale
if (align == 'none') ctx.scale(scaleX, scaleY);
else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin);
else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax);
// translate
ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);
}
// elements
svg.Element = {}
svg.Element.ElementBase = function(node) {
this.attributes = {};
this.styles = {};
this.children = [];
// get or create attribute
this.attribute = function(name, createIfNotExists) {
var a = this.attributes[name];
if (a != null) return a;
a = new svg.Property(name, '');
if (createIfNotExists == true) this.attributes[name] = a;
return a;
}
// get or create style, crawls up node tree
this.style = function(name, createIfNotExists) {
var s = this.styles[name];
if (s != null) return s;
var a = this.attribute(name);
if (a != null && a.hasValue()) {
return a;
}
var p = this.parent;
if (p != null) {
var ps = p.style(name);
if (ps != null && ps.hasValue()) {
return ps;
}
}
s = new svg.Property(name, '');
if (createIfNotExists == true) this.styles[name] = s;
return s;
}
// base render
this.render = function(ctx) {
// don't render display=none
if (this.style('display').value == 'none') return;
// don't render visibility=hidden
if (this.attribute('visibility').value == 'hidden') return;
ctx.save();
this.setContext(ctx);
// mask
if (this.attribute('mask').hasValue()) {
var mask = this.attribute('mask').Definition.getDefinition();
if (mask != null) mask.apply(ctx, this);
}
else if (this.style('filter').hasValue()) {
var filter = this.style('filter').Definition.getDefinition();
if (filter != null) filter.apply(ctx, this);
}
else this.renderChildren(ctx);
this.clearContext(ctx);
ctx.restore();
}
// base set context
this.setContext = function(ctx) {
// OVERRIDE ME!
}
// base clear context
this.clearContext = function(ctx) {
// OVERRIDE ME!
}
// base render children
this.renderChildren = function(ctx) {
for (var i=0; i<this.children.length; i++) {
this.children[i].render(ctx);
}
}
this.addChild = function(childNode, create) {
var child = childNode;
if (create) child = svg.CreateElement(childNode);
child.parent = this;
this.children.push(child);
}
if (node != null && node.nodeType == 1) { //ELEMENT_NODE
// add children
for (var i=0; i<node.childNodes.length; i++) {
var childNode = node.childNodes[i];
if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE
}
// add attributes
for (var i=0; i<node.attributes.length; i++) {
var attribute = node.attributes[i];
this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue);
}
// add tag styles
var styles = svg.Styles[node.nodeName];
if (styles != null) {
for (var name in styles) {
this.styles[name] = styles[name];
}
}
// add class styles
if (this.attribute('class').hasValue()) {
var classes = svg.compressSpaces(this.attribute('class').value).split(' ');
for (var j=0; j<classes.length; j++) {
styles = svg.Styles['.'+classes[j]];
if (styles != null) {
for (var name in styles) {
this.styles[name] = styles[name];
}
}
styles = svg.Styles[node.nodeName+'.'+classes[j]];
if (styles != null) {
for (var name in styles) {
this.styles[name] = styles[name];
}
}
}
}
// add inline styles
if (this.attribute('style').hasValue()) {
var styles = this.attribute('style').value.split(';');
for (var i=0; i<styles.length; i++) {
if (svg.trim(styles[i]) != '') {
var style = styles[i].split(':');
var name = svg.trim(style[0]);
var value = svg.trim(style[1]);
this.styles[name] = new svg.Property(name, value);
}
}
}
// add id
if (this.attribute('id').hasValue()) {
if (svg.Definitions[this.attribute('id').value] == null) {
svg.Definitions[this.attribute('id').value] = this;
}
}
}
}
svg.Element.RenderedElementBase = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.setContext = function(ctx) {
// fill
if (this.style('fill').Definition.isUrl()) {
var fs = this.style('fill').Definition.getFillStyle(this);
if (fs != null) ctx.fillStyle = fs;
}
else if (this.style('fill').hasValue()) {
var fillStyle = this.style('fill');
if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value);
ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);
}
// stroke
if (this.style('stroke').Definition.isUrl()) {
var fs = this.style('stroke').Definition.getFillStyle(this);
if (fs != null) ctx.strokeStyle = fs;
}
else if (this.style('stroke').hasValue()) {
var strokeStyle = this.style('stroke');
if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value);
ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);
}
if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels();
if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;
if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;
if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;
// font
if (typeof(ctx.font) != 'undefined') {
ctx.font = svg.Font.CreateFont(
this.style('font-style').value,
this.style('font-variant').value,
this.style('font-weight').value,
this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '',
this.style('font-family').value).toString();
}
// transform
if (this.attribute('transform').hasValue()) {
var transform = new svg.Transform(this.attribute('transform').value);
transform.apply(ctx);
}
// clip
if (this.attribute('clip-path').hasValue()) {
var clip = this.attribute('clip-path').Definition.getDefinition();
if (clip != null) clip.apply(ctx);
}
// opacity
if (this.style('opacity').hasValue()) {
ctx.globalAlpha = this.style('opacity').numValue();
}
}
}
svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase;
svg.Element.PathElementBase = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.path = function(ctx) {
if (ctx != null) ctx.beginPath();
return new svg.BoundingBox();
}
this.renderChildren = function(ctx) {
this.path(ctx);
svg.Mouse.checkPath(this, ctx);
if (ctx.fillStyle != '') ctx.fill();
if (ctx.strokeStyle != '') ctx.stroke();
var markers = this.getMarkers();
if (markers != null) {
if (this.style('marker-start').Definition.isUrl()) {
var marker = this.style('marker-start').Definition.getDefinition();
marker.render(ctx, markers[0][0], markers[0][1]);
}
if (this.style('marker-mid').Definition.isUrl()) {
var marker = this.style('marker-mid').Definition.getDefinition();
for (var i=1;i<markers.length-1;i++) {
marker.render(ctx, markers[i][0], markers[i][1]);
}
}
if (this.style('marker-end').Definition.isUrl()) {
var marker = this.style('marker-end').Definition.getDefinition();
marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]);
}
}
}
this.getBoundingBox = function() {
return this.path();
}
this.getMarkers = function() {
return null;
}
}
svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase;
// svg element
svg.Element.svg = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.baseClearContext = this.clearContext;
this.clearContext = function(ctx) {
this.baseClearContext(ctx);
svg.ViewPort.RemoveCurrent();
}
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
// initial values
ctx.strokeStyle = 'rgba(0,0,0,0)';
ctx.lineCap = 'butt';
ctx.lineJoin = 'miter';
ctx.miterLimit = 4;
this.baseSetContext(ctx);
// create new view port
if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {
ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y'));
}
var width = svg.ViewPort.width();
var height = svg.ViewPort.height();
if (typeof(this.root) == 'undefined' && this.attribute('width').hasValue() && this.attribute('height').hasValue()) {
width = this.attribute('width').Length.toPixels('x');
height = this.attribute('height').Length.toPixels('y');
var x = 0;
var y = 0;
if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {
x = -this.attribute('refX').Length.toPixels('x');
y = -this.attribute('refY').Length.toPixels('y');
}
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(width, y);
ctx.lineTo(width, height);
ctx.lineTo(x, height);
ctx.closePath();
ctx.clip();
}
svg.ViewPort.SetCurrent(width, height);
// viewbox
if (this.attribute('viewBox').hasValue()) {
var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
var minX = viewBox[0];
var minY = viewBox[1];
width = viewBox[2];
height = viewBox[3];
svg.AspectRatio(ctx,
this.attribute('preserveAspectRatio').value,
svg.ViewPort.width(),
width,
svg.ViewPort.height(),
height,
minX,
minY,
this.attribute('refX').value,
this.attribute('refY').value);
svg.ViewPort.RemoveCurrent();
svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
}
}
}
svg.Element.svg.prototype = new svg.Element.RenderedElementBase;
// rect element
svg.Element.rect = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.path = function(ctx) {
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
var rx = this.attribute('rx').Length.toPixels('x');
var ry = this.attribute('ry').Length.toPixels('y');
if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;
if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(x + rx, y);
ctx.lineTo(x + width - rx, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + ry)
ctx.lineTo(x + width, y + height - ry);
ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height)
ctx.lineTo(x + rx, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - ry)
ctx.lineTo(x, y + ry);
ctx.quadraticCurveTo(x, y, x + rx, y)
ctx.closePath();
}
return new svg.BoundingBox(x, y, x + width, y + height);
}
}
svg.Element.rect.prototype = new svg.Element.PathElementBase;
// circle element
svg.Element.circle = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.path = function(ctx) {
var cx = this.attribute('cx').Length.toPixels('x');
var cy = this.attribute('cy').Length.toPixels('y');
var r = this.attribute('r').Length.toPixels();
if (ctx != null) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2, true);
ctx.closePath();
}
return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);
}
}
svg.Element.circle.prototype = new svg.Element.PathElementBase;
// ellipse element
svg.Element.ellipse = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.path = function(ctx) {
var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
var rx = this.attribute('rx').Length.toPixels('x');
var ry = this.attribute('ry').Length.toPixels('y');
var cx = this.attribute('cx').Length.toPixels('x');
var cy = this.attribute('cy').Length.toPixels('y');
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(cx, cy - ry);
ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);
ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);
ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);
ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);
ctx.closePath();
}
return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);
}
}
svg.Element.ellipse.prototype = new svg.Element.PathElementBase;
// line element
svg.Element.line = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.getPoints = function() {
return [
new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')),
new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))];
}
this.path = function(ctx) {
var points = this.getPoints();
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.lineTo(points[1].x, points[1].y);
}
return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);
}
this.getMarkers = function() {
var points = this.getPoints();
var a = points[0].angleTo(points[1]);
return [[points[0], a], [points[1], a]];
}
}
svg.Element.line.prototype = new svg.Element.PathElementBase;
// polyline element
svg.Element.polyline = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.points = svg.CreatePath(this.attribute('points').value);
this.path = function(ctx) {
var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(this.points[0].x, this.points[0].y);
}
for (var i=1; i<this.points.length; i++) {
bb.addPoint(this.points[i].x, this.points[i].y);
if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);
}
return bb;
}
this.getMarkers = function() {
var markers = [];
for (var i=0; i<this.points.length - 1; i++) {
markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]);
}
markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]);
return markers;
}
}
svg.Element.polyline.prototype = new svg.Element.PathElementBase;
// polygon element
svg.Element.polygon = function(node) {
this.base = svg.Element.polyline;
this.base(node);
this.basePath = this.path;
this.path = function(ctx) {
var bb = this.basePath(ctx);
if (ctx != null) {
ctx.lineTo(this.points[0].x, this.points[0].y);
ctx.closePath();
}
return bb;
}
}
svg.Element.polygon.prototype = new svg.Element.polyline;
// path element
svg.Element.path = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
var d = this.attribute('d').value;
// TODO: convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF
d = d.replace(/,/gm,' '); // get rid of all commas
d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // separate commands from points
d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from points
d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma
d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma
d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax
d = svg.compressSpaces(d); // compress multiple spaces
d = svg.trim(d);
this.PathParser = new (function(d) {
this.tokens = d.split(' ');
this.reset = function() {
this.i = -1;
this.command = '';
this.previousCommand = '';
this.start = new svg.Point(0, 0);
this.control = new svg.Point(0, 0);
this.current = new svg.Point(0, 0);
this.points = [];
this.angles = [];
}
this.isEnd = function() {
return this.i >= this.tokens.length - 1;
}
this.isCommandOrEnd = function() {
if (this.isEnd()) return true;
return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null;
}
this.isRelativeCommand = function() {
return this.command == this.command.toLowerCase();
}
this.getToken = function() {
this.i = this.i + 1;
return this.tokens[this.i];
}
this.getScalar = function() {
return parseFloat(this.getToken());
}
this.nextCommand = function() {
this.previousCommand = this.command;
this.command = this.getToken();
}
this.getPoint = function() {
var p = new svg.Point(this.getScalar(), this.getScalar());
return this.makeAbsolute(p);
}
this.getAsControlPoint = function() {
var p = this.getPoint();
this.control = p;
return p;
}
this.getAsCurrentPoint = function() {
var p = this.getPoint();
this.current = p;
return p;
}
this.getReflectedControlPoint = function() {
if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') {
return this.current;
}
// reflect point
var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);
return p;
}
this.makeAbsolute = function(p) {
if (this.isRelativeCommand()) {
p.x = this.current.x + p.x;
p.y = this.current.y + p.y;
}
return p;
}
this.addMarker = function(p, from, priorTo) {
// if the last angle isn't filled in because we didn't have this point yet ...
if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length-1] == null) {
this.angles[this.angles.length-1] = this.points[this.points.length-1].angleTo(priorTo);
}
this.addMarkerAngle(p, from == null ? null : from.angleTo(p));
}
this.addMarkerAngle = function(p, a) {
this.points.push(p);
this.angles.push(a);
}
this.getMarkerPoints = function() { return this.points; }
this.getMarkerAngles = function() {
for (var i=0; i<this.angles.length; i++) {
if (this.angles[i] == null) {
for (var j=i+1; j<this.angles.length; j++) {
if (this.angles[j] != null) {
this.angles[i] = this.angles[j];
break;
}
}
}
}
return this.angles;
}
})(d);
this.path = function(ctx) {
var pp = this.PathParser;
pp.reset();
var bb = new svg.BoundingBox();
if (ctx != null) ctx.beginPath();
while (!pp.isEnd()) {
pp.nextCommand();
switch (pp.command.toUpperCase()) {
case 'M':
var p = pp.getAsCurrentPoint();
pp.addMarker(p);
bb.addPoint(p.x, p.y);
if (ctx != null) ctx.moveTo(p.x, p.y);
pp.start = pp.current;
while (!pp.isCommandOrEnd()) {
var p = pp.getAsCurrentPoint();
pp.addMarker(p, pp.start);
bb.addPoint(p.x, p.y);
if (ctx != null) ctx.lineTo(p.x, p.y);
}
break;
case 'L':
while (!pp.isCommandOrEnd()) {
var c = pp.current;
var p = pp.getAsCurrentPoint();
pp.addMarker(p, c);
bb.addPoint(p.x, p.y);
if (ctx != null) ctx.lineTo(p.x, p.y);
}
break;
case 'H':
while (!pp.isCommandOrEnd()) {
var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);
pp.addMarker(newP, pp.current);
pp.current = newP;
bb.addPoint(pp.current.x, pp.current.y);
if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
}
break;
case 'V':
while (!pp.isCommandOrEnd()) {
var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
pp.addMarker(newP, pp.current);
pp.current = newP;
bb.addPoint(pp.current.x, pp.current.y);
if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
}
break;
case 'C':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var p1 = pp.getPoint();
var cntrl = pp.getAsControlPoint();
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl, p1);
bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'S':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var p1 = pp.getReflectedControlPoint();
var cntrl = pp.getAsControlPoint();
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl, p1);
bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'Q':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var cntrl = pp.getAsControlPoint();
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl, cntrl);
bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'T':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var cntrl = pp.getReflectedControlPoint();
pp.control = cntrl;
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl, cntrl);
bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'A':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var rx = pp.getScalar();
var ry = pp.getScalar();
var xAxisRotation = pp.getScalar() * (Math.PI / 180.0);
var largeArcFlag = pp.getScalar();
var sweepFlag = pp.getScalar();
var cp = pp.getAsCurrentPoint();
// Conversion from endpoint to center parameterization
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
// x1', y1'
var currp = new svg.Point(
Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,
-Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
);
// adjust radii
var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2);
if (l > 1) {
rx *= Math.sqrt(l);
ry *= Math.sqrt(l);
}
// cx', cy'
var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
((Math.pow(rx,2)*Math.pow(ry,2))-(Math.pow(rx,2)*Math.pow(currp.y,2))-(Math.pow(ry,2)*Math.pow(currp.x,2))) /
(Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2))
);
if (isNaN(s)) s = 0;
var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
// cx, cy
var centp = new svg.Point(
(curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
(curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
);
// vector magnitude
var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); }
// ratio between two vectors
var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) }
// angle between two vectors
var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); }
// initial angle
var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]);
// angle delta
var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry];
var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry];
var ad = a(u, v);
if (r(u,v) <= -1) ad = Math.PI;
if (r(u,v) >= 1) ad = 0;
if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI;
if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI;
// for markers
var halfWay = new svg.Point(
centp.x - rx * Math.cos((a1 + ad) / 2),
centp.y - ry * Math.sin((a1 + ad) / 2)
);
pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better
if (ctx != null) {
var r = rx > ry ? rx : ry;
var sx = rx > ry ? 1 : rx / ry;
var sy = rx > ry ? ry / rx : 1;
ctx.translate(centp.x, centp.y);
ctx.rotate(xAxisRotation);
ctx.scale(sx, sy);
ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);
ctx.scale(1/sx, 1/sy);
ctx.rotate(-xAxisRotation);
ctx.translate(-centp.x, -centp.y);
}
}
break;
case 'Z':
if (ctx != null) ctx.closePath();
pp.current = pp.start;
}
}
return bb;
}
this.getMarkers = function() {
var points = this.PathParser.getMarkerPoints();
var angles = this.PathParser.getMarkerAngles();
var markers = [];
for (var i=0; i<points.length; i++) {
markers.push([points[i], angles[i]]);
}
return markers;
}
}
svg.Element.path.prototype = new svg.Element.PathElementBase;
// pattern element
svg.Element.pattern = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.createPattern = function(ctx, element) {
// render me using a temporary svg element
var tempSvg = new svg.Element.svg();
tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value);
tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value);
tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);
tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);
tempSvg.children = this.children;
var c = document.createElement('canvas');
c.width = this.attribute('width').Length.toPixels('x');
c.height = this.attribute('height').Length.toPixels('y');
tempSvg.render(c.getContext('2d'));
return ctx.createPattern(c, 'repeat');
}
}
svg.Element.pattern.prototype = new svg.Element.ElementBase;
// marker element
svg.Element.marker = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.baseRender = this.render;
this.render = function(ctx, point, angle) {
ctx.translate(point.x, point.y);
if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle);
if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);
ctx.save();
// render me using a temporary svg element
var tempSvg = new svg.Element.svg();
tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);
tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);
tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);
tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);
tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));
tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));
tempSvg.children = this.children;
tempSvg.render(ctx);
ctx.restore();
if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth);
if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle);
ctx.translate(-point.x, -point.y);
}
}
svg.Element.marker.prototype = new svg.Element.ElementBase;
// definitions element
svg.Element.defs = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.render = function(ctx) {
// NOOP
}
}
svg.Element.defs.prototype = new svg.Element.ElementBase;
// base for gradients
svg.Element.GradientBase = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');
this.stops = [];
for (var i=0; i<this.children.length; i++) {
var child = this.children[i];
this.stops.push(child);
}
this.getGradient = function() {
// OVERRIDE ME!
}
this.createGradient = function(ctx, element) {
var stopsContainer = this;
if (this.attribute('xlink:href').hasValue()) {
stopsContainer = this.attribute('xlink:href').Definition.getDefinition();
}
var g = this.getGradient(ctx, element);
for (var i=0; i<stopsContainer.stops.length; i++) {
g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color);
}
if (this.attribute('gradientTransform').hasValue()) {
// render as transformed pattern on temporary canvas
var rootView = svg.ViewPort.viewPorts[0];
var rect = new svg.Element.rect();
rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS/3.0);
rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS/3.0);
rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS);
rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS);
var group = new svg.Element.g();
group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value);
group.children = [ rect ];
var tempSvg = new svg.Element.svg();
tempSvg.attributes['x'] = new svg.Property('x', 0);
tempSvg.attributes['y'] = new svg.Property('y', 0);
tempSvg.attributes['width'] = new svg.Property('width', rootView.width);
tempSvg.attributes['height'] = new svg.Property('height', rootView.height);
tempSvg.children = [ group ];
var c = document.createElement('canvas');
c.width = rootView.width;
c.height = rootView.height;
var tempCtx = c.getContext('2d');
tempCtx.fillStyle = g;
tempSvg.render(tempCtx);
return tempCtx.createPattern(c, 'no-repeat');
}
return g;
}
}
svg.Element.GradientBase.prototype = new svg.Element.ElementBase;
// linear gradient element
svg.Element.linearGradient = function(node) {
this.base = svg.Element.GradientBase;
this.base(node);
this.getGradient = function(ctx, element) {
var bb = element.getBoundingBox();
var x1 = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('x1').numValue()
: this.attribute('x1').Length.toPixels('x'));
var y1 = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('y1').numValue()
: this.attribute('y1').Length.toPixels('y'));
var x2 = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('x2').numValue()
: this.attribute('x2').Length.toPixels('x'));
var y2 = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('y2').numValue()
: this.attribute('y2').Length.toPixels('y'));
return ctx.createLinearGradient(x1, y1, x2, y2);
}
}
svg.Element.linearGradient.prototype = new svg.Element.GradientBase;
// radial gradient element
svg.Element.radialGradient = function(node) {
this.base = svg.Element.GradientBase;
this.base(node);
this.getGradient = function(ctx, element) {
var bb = element.getBoundingBox();
var cx = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('cx').numValue()
: this.attribute('cx').Length.toPixels('x'));
var cy = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('cy').numValue()
: this.attribute('cy').Length.toPixels('y'));
var fx = cx;
var fy = cy;
if (this.attribute('fx').hasValue()) {
fx = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('fx').numValue()
: this.attribute('fx').Length.toPixels('x'));
}
if (this.attribute('fy').hasValue()) {
fy = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('fy').numValue()
: this.attribute('fy').Length.toPixels('y'));
}
var r = (this.gradientUnits == 'objectBoundingBox'
? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue()
: this.attribute('r').Length.toPixels());
return ctx.createRadialGradient(fx, fy, 0, cx, cy, r);
}
}
svg.Element.radialGradient.prototype = new svg.Element.GradientBase;
// gradient stop element
svg.Element.stop = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.offset = this.attribute('offset').numValue();
var stopColor = this.style('stop-color');
if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value);
this.color = stopColor.value;
}
svg.Element.stop.prototype = new svg.Element.ElementBase;
// animation base element
svg.Element.AnimateBase = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
svg.Animations.push(this);
this.duration = 0.0;
this.begin = this.attribute('begin').Time.toMilliseconds();
this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds();
this.getProperty = function() {
var attributeType = this.attribute('attributeType').value;
var attributeName = this.attribute('attributeName').value;
if (attributeType == 'CSS') {
return this.parent.style(attributeName, true);
}
return this.parent.attribute(attributeName, true);
};
this.initialValue = null;
this.removed = false;
this.calcValue = function() {
// OVERRIDE ME!
return '';
}
this.update = function(delta) {
// set initial value
if (this.initialValue == null) {
this.initialValue = this.getProperty().value;
}
// if we're past the end time
if (this.duration > this.maxDuration) {
// loop for indefinitely repeating animations
if (this.attribute('repeatCount').value == 'indefinite') {
this.duration = 0.0
}
else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) {
this.removed = true;
this.getProperty().value = this.initialValue;
return true;
}
else {
return false; // no updates made
}
}
this.duration = this.duration + delta;
// if we're past the begin time
var updated = false;
if (this.begin < this.duration) {
var newValue = this.calcValue(); // tween
if (this.attribute('type').hasValue()) {
// for transform, etc.
var type = this.attribute('type').value;
newValue = type + '(' + newValue + ')';
}
this.getProperty().value = newValue;
updated = true;
}
return updated;
}
// fraction of duration we've covered
this.progress = function() {
return ((this.duration - this.begin) / (this.maxDuration - this.begin));
}
}
svg.Element.AnimateBase.prototype = new svg.Element.ElementBase;
// animate element
svg.Element.animate = function(node) {
this.base = svg.Element.AnimateBase;
this.base(node);
this.calcValue = function() {
var from = this.attribute('from').numValue();
var to = this.attribute('to').numValue();
// tween value linearly
return from + (to - from) * this.progress();
};
}
svg.Element.animate.prototype = new svg.Element.AnimateBase;
// animate color element
svg.Element.animateColor = function(node) {
this.base = svg.Element.AnimateBase;
this.base(node);
this.calcValue = function() {
var from = new RGBColor(this.attribute('from').value);
var to = new RGBColor(this.attribute('to').value);
if (from.ok && to.ok) {
// tween color linearly
var r = from.r + (to.r - from.r) * this.progress();
var g = from.g + (to.g - from.g) * this.progress();
var b = from.b + (to.b - from.b) * this.progress();
return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')';
}
return this.attribute('from').value;
};
}
svg.Element.animateColor.prototype = new svg.Element.AnimateBase;
// animate transform element
svg.Element.animateTransform = function(node) {
this.base = svg.Element.animate;
this.base(node);
}
svg.Element.animateTransform.prototype = new svg.Element.animate;
// font element
svg.Element.font = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.horizAdvX = this.attribute('horiz-adv-x').numValue();
this.isRTL = false;
this.isArabic = false;
this.fontFace = null;
this.missingGlyph = null;
this.glyphs = [];
for (var i=0; i<this.children.length; i++) {
var child = this.children[i];
if (child.type == 'font-face') {
this.fontFace = child;
if (child.style('font-family').hasValue()) {
svg.Definitions[child.style('font-family').value] = this;
}
}
else if (child.type == 'missing-glyph') this.missingGlyph = child;
else if (child.type == 'glyph') {
if (child.arabicForm != '') {
this.isRTL = true;
this.isArabic = true;
if (typeof(this.glyphs[child.unicode]) == 'undefined') this.glyphs[child.unicode] = [];
this.glyphs[child.unicode][child.arabicForm] = child;
}
else {
this.glyphs[child.unicode] = child;
}
}
}
}
svg.Element.font.prototype = new svg.Element.ElementBase;
// font-face element
svg.Element.fontface = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.ascent = this.attribute('ascent').value;
this.descent = this.attribute('descent').value;
this.unitsPerEm = this.attribute('units-per-em').numValue();
}
svg.Element.fontface.prototype = new svg.Element.ElementBase;
// missing-glyph element
svg.Element.missingglyph = function(node) {
this.base = svg.Element.path;
this.base(node);
this.horizAdvX = 0;
}
svg.Element.missingglyph.prototype = new svg.Element.path;
// glyph element
svg.Element.glyph = function(node) {
this.base = svg.Element.path;
this.base(node);
this.horizAdvX = this.attribute('horiz-adv-x').numValue();
this.unicode = this.attribute('unicode').value;
this.arabicForm = this.attribute('arabic-form').value;
}
svg.Element.glyph.prototype = new svg.Element.path;
// text element
svg.Element.text = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
if (node != null) {
// add children
this.children = [];
for (var i=0; i<node.childNodes.length; i++) {
var childNode = node.childNodes[i];
if (childNode.nodeType == 1) { // capture tspan and tref nodes
this.addChild(childNode, true);
}
else if (childNode.nodeType == 3) { // capture text
this.addChild(new svg.Element.tspan(childNode), false);
}
}
}
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
this.baseSetContext(ctx);
if (this.style('dominant-baseline').hasValue()) ctx.textBaseline = this.style('dominant-baseline').value;
if (this.style('alignment-baseline').hasValue()) ctx.textBaseline = this.style('alignment-baseline').value;
}
this.renderChildren = function(ctx) {
var textAnchor = this.style('text-anchor').valueOrDefault('start');
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
for (var i=0; i<this.children.length; i++) {
var child = this.children[i];
if (child.attribute('x').hasValue()) {
child.x = child.attribute('x').Length.toPixels('x');
}
else {
if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x');
child.x = x;
}
var childLength = child.measureText(ctx);
if (textAnchor != 'start' && (i==0 || child.attribute('x').hasValue())) { // new group?
// loop through rest of children
var groupLength = childLength;
for (var j=i+1; j<this.children.length; j++) {
var childInGroup = this.children[j];
if (childInGroup.attribute('x').hasValue()) break; // new group
groupLength += childInGroup.measureText(ctx);
}
child.x -= (textAnchor == 'end' ? groupLength : groupLength / 2.0);
}
x = child.x + childLength;
if (child.attribute('y').hasValue()) {
child.y = child.attribute('y').Length.toPixels('y');
}
else {
if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y');
child.y = y;
}
y = child.y;
child.render(ctx);
}
}
}
svg.Element.text.prototype = new svg.Element.RenderedElementBase;
// text base
svg.Element.TextElementBase = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.getGlyph = function(font, text, i) {
var c = text[i];
var glyph = null;
if (font.isArabic) {
var arabicForm = 'isolated';
if ((i==0 || text[i-1]==' ') && i<text.length-2 && text[i+1]!=' ') arabicForm = 'terminal';
if (i>0 && text[i-1]!=' ' && i<text.length-2 && text[i+1]!=' ') arabicForm = 'medial';
if (i>0 && text[i-1]!=' ' && (i == text.length-1 || text[i+1]==' ')) arabicForm = 'initial';
if (typeof(font.glyphs[c]) != 'undefined') {
glyph = font.glyphs[c][arabicForm];
if (glyph == null && font.glyphs[c].type == 'glyph') glyph = font.glyphs[c];
}
}
else {
glyph = font.glyphs[c];
}
if (glyph == null) glyph = font.missingGlyph;
return glyph;
}
this.renderChildren = function(ctx) {
var customFont = this.parent.style('font-family').Definition.getDefinition();
if (customFont != null) {
var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle);
var text = this.getText();
if (customFont.isRTL) text = text.split("").reverse().join("");
var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
for (var i=0; i<text.length; i++) {
var glyph = this.getGlyph(customFont, text, i);
var scale = fontSize / customFont.fontFace.unitsPerEm;
ctx.translate(this.x, this.y);
ctx.scale(scale, -scale);
var lw = ctx.lineWidth;
ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize;
if (fontStyle == 'italic') ctx.transform(1, 0, .4, 1, 0, 0);
glyph.render(ctx);
if (fontStyle == 'italic') ctx.transform(1, 0, -.4, 1, 0, 0);
ctx.lineWidth = lw;
ctx.scale(1/scale, -1/scale);
ctx.translate(-this.x, -this.y);
this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm;
if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) {
this.x += dx[i];
}
}
return;
}
if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y);
if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
}
this.getText = function() {
// OVERRIDE ME
}
this.measureText = function(ctx) {
var customFont = this.parent.style('font-family').Definition.getDefinition();
if (customFont != null) {
var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
var measure = 0;
var text = this.getText();
if (customFont.isRTL) text = text.split("").reverse().join("");
var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
for (var i=0; i<text.length; i++) {
var glyph = this.getGlyph(customFont, text, i);
measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm;
if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) {
measure += dx[i];
}
}
return measure;
}
var textToMeasure = svg.compressSpaces(this.getText());
if (!ctx.measureText) return textToMeasure.length * 10;
ctx.save();
this.setContext(ctx);
var width = ctx.measureText(textToMeasure).width;
ctx.restore();
return width;
}
}
svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase;
// tspan
svg.Element.tspan = function(node) {
this.base = svg.Element.TextElementBase;
this.base(node);
this.text = node.nodeType == 3 ? node.nodeValue : // text
node.childNodes.length > 0 ? node.childNodes[0].nodeValue : // element
node.text;
this.getText = function() {
return this.text;
}
}
svg.Element.tspan.prototype = new svg.Element.TextElementBase;
// tref
svg.Element.tref = function(node) {
this.base = svg.Element.TextElementBase;
this.base(node);
this.getText = function() {
var element = this.attribute('xlink:href').Definition.getDefinition();
if (element != null) return element.children[0].getText();
}
}
svg.Element.tref.prototype = new svg.Element.TextElementBase;
// a element
svg.Element.a = function(node) {
this.base = svg.Element.TextElementBase;
this.base(node);
this.hasText = true;
for (var i=0; i<node.childNodes.length; i++) {
if (node.childNodes[i].nodeType != 3) this.hasText = false;
}
// this might contain text
this.text = this.hasText ? node.childNodes[0].nodeValue : '';
this.getText = function() {
return this.text;
}
this.baseRenderChildren = this.renderChildren;
this.renderChildren = function(ctx) {
if (this.hasText) {
// render as text element
this.baseRenderChildren(ctx);
var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y));
}
else {
// render as temporary group
var g = new svg.Element.g();
g.children = this.children;
g.parent = this;
g.render(ctx);
}
}
this.onclick = function() {
window.open(this.attribute('xlink:href').value);
}
this.onmousemove = function() {
svg.ctx.canvas.style.cursor = 'pointer';
}
}
svg.Element.a.prototype = new svg.Element.TextElementBase;
// image element
svg.Element.image = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
svg.Images.push(this);
this.img = document.createElement('img');
this.loaded = false;
var that = this;
this.img.onload = function() { that.loaded = true; }
this.img.src = this.attribute('xlink:href').value;
this.renderChildren = function(ctx) {
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
if (width == 0 || height == 0) return;
ctx.save();
ctx.translate(x, y);
svg.AspectRatio(ctx,
this.attribute('preserveAspectRatio').value,
width,
this.img.width,
height,
this.img.height,
0,
0);
ctx.drawImage(this.img, 0, 0);
ctx.restore();
}
}
svg.Element.image.prototype = new svg.Element.RenderedElementBase;
// group element
svg.Element.g = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.getBoundingBox = function() {
var bb = new svg.BoundingBox();
for (var i=0; i<this.children.length; i++) {
bb.addBoundingBox(this.children[i].getBoundingBox());
}
return bb;
};
}
svg.Element.g.prototype = new svg.Element.RenderedElementBase;
// symbol element
svg.Element.symbol = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
this.baseSetContext(ctx);
// viewbox
if (this.attribute('viewBox').hasValue()) {
var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
var minX = viewBox[0];
var minY = viewBox[1];
width = viewBox[2];
height = viewBox[3];
svg.AspectRatio(ctx,
this.attribute('preserveAspectRatio').value,
this.attribute('width').Length.toPixels('x'),
width,
this.attribute('height').Length.toPixels('y'),
height,
minX,
minY);
svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
}
}
}
svg.Element.symbol.prototype = new svg.Element.RenderedElementBase;
// style element
svg.Element.style = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
// text, or spaces then CDATA
var css = node.childNodes[0].nodeValue + (node.childNodes.length > 1 ? node.childNodes[1].nodeValue : '');
css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(^[\s]*\/\/.*)/gm, ''); // remove comments
css = svg.compressSpaces(css); // replace whitespace
var cssDefs = css.split('}');
for (var i=0; i<cssDefs.length; i++) {
if (svg.trim(cssDefs[i]) != '') {
var cssDef = cssDefs[i].split('{');
var cssClasses = cssDef[0].split(',');
var cssProps = cssDef[1].split(';');
for (var j=0; j<cssClasses.length; j++) {
var cssClass = svg.trim(cssClasses[j]);
if (cssClass != '') {
var props = {};
for (var k=0; k<cssProps.length; k++) {
var prop = cssProps[k].indexOf(':');
var name = cssProps[k].substr(0, prop);
var value = cssProps[k].substr(prop + 1, cssProps[k].length - prop);
if (name != null && value != null) {
props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value));
}
}
svg.Styles[cssClass] = props;
if (cssClass == '@font-face') {
var fontFamily = props['font-family'].value.replace(/"/g,'');
var srcs = props['src'].value.split(',');
for (var s=0; s<srcs.length; s++) {
if (srcs[s].indexOf('format("svg")') > 0) {
var urlStart = srcs[s].indexOf('url');
var urlEnd = srcs[s].indexOf(')', urlStart);
var url = srcs[s].substr(urlStart + 5, urlEnd - urlStart - 6);
var doc = svg.parseXml(svg.ajax(url));
var fonts = doc.getElementsByTagName('font');
for (var f=0; f<fonts.length; f++) {
var font = svg.CreateElement(fonts[f]);
svg.Definitions[fontFamily] = font;
}
}
}
}
}
}
}
}
}
svg.Element.style.prototype = new svg.Element.ElementBase;
// use element
svg.Element.use = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
this.baseSetContext(ctx);
if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0);
if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y'));
}
this.getDefinition = function() {
var element = this.attribute('xlink:href').Definition.getDefinition();
if (this.attribute('width').hasValue()) element.attribute('width', true).value = this.attribute('width').value;
if (this.attribute('height').hasValue()) element.attribute('height', true).value = this.attribute('height').value;
return element;
}
this.path = function(ctx) {
var element = this.getDefinition();
if (element != null) element.path(ctx);
}
this.renderChildren = function(ctx) {
var element = this.getDefinition();
if (element != null) element.render(ctx);
}
}
svg.Element.use.prototype = new svg.Element.RenderedElementBase;
// mask element
svg.Element.mask = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.apply = function(ctx, element) {
// render as temp svg
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
// temporarily remove mask to avoid recursion
var mask = element.attribute('mask').value;
element.attribute('mask').value = '';
var cMask = document.createElement('canvas');
cMask.width = x + width;
cMask.height = y + height;
var maskCtx = cMask.getContext('2d');
this.renderChildren(maskCtx);
var c = document.createElement('canvas');
c.width = x + width;
c.height = y + height;
var tempCtx = c.getContext('2d');
element.render(tempCtx);
tempCtx.globalCompositeOperation = 'destination-in';
tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat');
tempCtx.fillRect(0, 0, x + width, y + height);
ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat');
ctx.fillRect(0, 0, x + width, y + height);
// reassign mask
element.attribute('mask').value = mask;
}
this.render = function(ctx) {
// NO RENDER
}
}
svg.Element.mask.prototype = new svg.Element.ElementBase;
// clip element
svg.Element.clipPath = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.apply = function(ctx) {
for (var i=0; i<this.children.length; i++) {
if (this.children[i].path) {
this.children[i].path(ctx);
ctx.clip();
}
}
}
this.render = function(ctx) {
// NO RENDER
}
}
svg.Element.clipPath.prototype = new svg.Element.ElementBase;
// filters
svg.Element.filter = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.apply = function(ctx, element) {
// render as temp svg
var bb = element.getBoundingBox();
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
if (x == 0 || y == 0) {
x = bb.x1;
y = bb.y1;
}
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
if (width == 0 || height == 0) {
width = bb.width();
height = bb.height();
}
// temporarily remove filter to avoid recursion
var filter = element.style('filter').value;
element.style('filter').value = '';
// max filter distance
var extraPercent = .20;
var px = extraPercent * width;
var py = extraPercent * height;
var c = document.createElement('canvas');
c.width = width + 2*px;
c.height = height + 2*py;
var tempCtx = c.getContext('2d');
tempCtx.translate(-x + px, -y + py);
element.render(tempCtx);
// apply filters
for (var i=0; i<this.children.length; i++) {
this.children[i].apply(tempCtx, 0, 0, width + 2*px, height + 2*py);
}
// render on me
ctx.drawImage(c, 0, 0, width + 2*px, height + 2*py, x - px, y - py, width + 2*px, height + 2*py);
// reassign filter
element.style('filter', true).value = filter;
}
this.render = function(ctx) {
// NO RENDER
}
}
svg.Element.filter.prototype = new svg.Element.ElementBase;
svg.Element.feGaussianBlur = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
function make_fgauss(sigma) {
sigma = Math.max(sigma, 0.01);
var len = Math.ceil(sigma * 4.0) + 1;
mask = [];
for (var i = 0; i < len; i++) {
mask[i] = Math.exp(-0.5 * (i / sigma) * (i / sigma));
}
return mask;
}
function normalize(mask) {
var sum = 0;
for (var i = 1; i < mask.length; i++) {
sum += Math.abs(mask[i]);
}
sum = 2 * sum + Math.abs(mask[0]);
for (var i = 0; i < mask.length; i++) {
mask[i] /= sum;
}
return mask;
}
function convolve_even(src, dst, mask, width, height) {
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var a = imGet(src, x, y, width, height, 3)/255;
for (var rgba = 0; rgba < 4; rgba++) {
var sum = mask[0] * (a==0?255:imGet(src, x, y, width, height, rgba)) * (a==0||rgba==3?1:a);
for (var i = 1; i < mask.length; i++) {
var a1 = imGet(src, Math.max(x-i,0), y, width, height, 3)/255;
var a2 = imGet(src, Math.min(x+i, width-1), y, width, height, 3)/255;
sum += mask[i] *
((a1==0?255:imGet(src, Math.max(x-i,0), y, width, height, rgba)) * (a1==0||rgba==3?1:a1) +
(a2==0?255:imGet(src, Math.min(x+i, width-1), y, width, height, rgba)) * (a2==0||rgba==3?1:a2));
}
imSet(dst, y, x, height, width, rgba, sum);
}
}
}
}
function imGet(img, x, y, width, height, rgba) {
return img[y*width*4 + x*4 + rgba];
}
function imSet(img, x, y, width, height, rgba, val) {
img[y*width*4 + x*4 + rgba] = val;
}
function blur(ctx, width, height, sigma)
{
var srcData = ctx.getImageData(0, 0, width, height);
var mask = make_fgauss(sigma);
mask = normalize(mask);
tmp = [];
convolve_even(srcData.data, tmp, mask, width, height);
convolve_even(tmp, srcData.data, mask, height, width);
ctx.clearRect(0, 0, width, height);
ctx.putImageData(srcData, 0, 0);
}
this.apply = function(ctx, x, y, width, height) {
// assuming x==0 && y==0 for now
blur(ctx, width, height, this.attribute('stdDeviation').numValue());
}
}
svg.Element.filter.prototype = new svg.Element.feGaussianBlur;
// title element, do nothing
svg.Element.title = function(node) {
}
svg.Element.title.prototype = new svg.Element.ElementBase;
// desc element, do nothing
svg.Element.desc = function(node) {
}
svg.Element.desc.prototype = new svg.Element.ElementBase;
svg.Element.MISSING = function(node) {
console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.');
}
svg.Element.MISSING.prototype = new svg.Element.ElementBase;
// element factory
svg.CreateElement = function(node) {
var className = node.nodeName.replace(/^[^:]+:/,''); // remove namespace
className = className.replace(/\-/g,''); // remove dashes
var e = null;
if (typeof(svg.Element[className]) != 'undefined') {
e = new svg.Element[className](node);
}
else {
e = new svg.Element.MISSING(node);
}
e.type = node.nodeName;
return e;
}
// load from url
svg.load = function(ctx, url) {
svg.loadXml(ctx, svg.ajax(url));
}
// load from xml
svg.loadXml = function(ctx, xml) {
svg.loadXmlDoc(ctx, svg.parseXml(xml));
}
svg.loadXmlDoc = function(ctx, dom) {
svg.init(ctx);
var mapXY = function(p) {
var e = ctx.canvas;
while (e) {
p.x -= e.offsetLeft;
p.y -= e.offsetTop;
e = e.offsetParent;
}
if (window.scrollX) p.x += window.scrollX;
if (window.scrollY) p.y += window.scrollY;
return p;
}
// bind mouse
if (svg.opts['ignoreMouse'] != true) {
ctx.canvas.onclick = function(e) {
var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
svg.Mouse.onclick(p.x, p.y);
};
ctx.canvas.onmousemove = function(e) {
var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
svg.Mouse.onmousemove(p.x, p.y);
};
}
var e = svg.CreateElement(dom.documentElement);
e.root = true;
// render loop
var isFirstRender = true;
var draw = function() {
svg.ViewPort.Clear();
if (ctx.canvas.parentNode) svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight);
if (svg.opts['ignoreDimensions'] != true) {
// set canvas size
if (e.style('width').hasValue()) {
ctx.canvas.width = e.style('width').Length.toPixels('x');
ctx.canvas.style.width = ctx.canvas.width + 'px';
}
if (e.style('height').hasValue()) {
ctx.canvas.height = e.style('height').Length.toPixels('y');
ctx.canvas.style.height = ctx.canvas.height + 'px';
}
}
var cWidth = ctx.canvas.clientWidth || ctx.canvas.width;
var cHeight = ctx.canvas.clientHeight || ctx.canvas.height;
svg.ViewPort.SetCurrent(cWidth, cHeight);
if (svg.opts != null && svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX'];
if (svg.opts != null && svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY'];
if (svg.opts != null && svg.opts['scaleWidth'] != null && svg.opts['scaleHeight'] != null) {
var xRatio = 1, yRatio = 1;
if (e.attribute('width').hasValue()) xRatio = e.attribute('width').Length.toPixels('x') / svg.opts['scaleWidth'];
if (e.attribute('height').hasValue()) yRatio = e.attribute('height').Length.toPixels('y') / svg.opts['scaleHeight'];
e.attribute('width', true).value = svg.opts['scaleWidth'];
e.attribute('height', true).value = svg.opts['scaleHeight'];
e.attribute('viewBox', true).value = '0 0 ' + (cWidth * xRatio) + ' ' + (cHeight * yRatio);
e.attribute('preserveAspectRatio', true).value = 'none';
}
// clear and render
if (svg.opts['ignoreClear'] != true) {
ctx.clearRect(0, 0, cWidth, cHeight);
}
e.render(ctx);
if (isFirstRender) {
isFirstRender = false;
if (svg.opts != null && typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback']();
}
}
var waitingForImages = true;
if (svg.ImagesLoaded()) {
waitingForImages = false;
draw();
}
svg.intervalID = setInterval(function() {
var needUpdate = false;
if (waitingForImages && svg.ImagesLoaded()) {
waitingForImages = false;
needUpdate = true;
}
// need update from mouse events?
if (svg.opts['ignoreMouse'] != true) {
needUpdate = needUpdate | svg.Mouse.hasEvents();
}
// need update from animations?
if (svg.opts['ignoreAnimation'] != true) {
for (var i=0; i<svg.Animations.length; i++) {
needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE);
}
}
// need update from redraw?
if (svg.opts != null && typeof(svg.opts['forceRedraw']) == 'function') {
if (svg.opts['forceRedraw']() == true) needUpdate = true;
}
// render if needed
if (needUpdate) {
draw();
svg.Mouse.runEvents(); // run and clear our events
}
}, 1000 / svg.FRAMERATE);
}
svg.stop = function() {
if (svg.intervalID) {
clearInterval(svg.intervalID);
}
}
svg.Mouse = new (function() {
this.events = [];
this.hasEvents = function() { return this.events.length != 0; }
this.onclick = function(x, y) {
this.events.push({ type: 'onclick', x: x, y: y,
run: function(e) { if (e.onclick) e.onclick(); }
});
}
this.onmousemove = function(x, y) {
this.events.push({ type: 'onmousemove', x: x, y: y,
run: function(e) { if (e.onmousemove) e.onmousemove(); }
});
}
this.eventElements = [];
this.checkPath = function(element, ctx) {
for (var i=0; i<this.events.length; i++) {
var e = this.events[i];
if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;
}
}
this.checkBoundingBox = function(element, bb) {
for (var i=0; i<this.events.length; i++) {
var e = this.events[i];
if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;
}
}
this.runEvents = function() {
svg.ctx.canvas.style.cursor = '';
for (var i=0; i<this.events.length; i++) {
var e = this.events[i];
var element = this.eventElements[i];
while (element) {
e.run(element);
element = element.parent;
}
}
// done running, clear
this.events = [];
this.eventElements = [];
}
});
return svg;
}
})();
if (CanvasRenderingContext2D) {
CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh) {
canvg(this.canvas, s, {
ignoreMouse: true,
ignoreAnimation: true,
ignoreDimensions: true,
ignoreClear: true,
offsetX: dx,
offsetY: dy,
scaleWidth: dw,
scaleHeight: dh
});
}
}/**
* @license Highcharts JS v3.0.1 (2013-04-09)
* CanVGRenderer Extension module
*
* (c) 2011-2012 Torstein Hønsi, Erik Olsson
*
* License: www.highcharts.com/license
*/
// JSLint options:
/*global Highcharts */
(function (Highcharts) { // encapsulate
var UNDEFINED,
DIV = 'div',
ABSOLUTE = 'absolute',
RELATIVE = 'relative',
HIDDEN = 'hidden',
VISIBLE = 'visible',
PX = 'px',
css = Highcharts.css,
CanVGRenderer = Highcharts.CanVGRenderer,
SVGRenderer = Highcharts.SVGRenderer,
extend = Highcharts.extend,
merge = Highcharts.merge,
addEvent = Highcharts.addEvent,
createElement = Highcharts.createElement,
discardElement = Highcharts.discardElement;
// Extend CanVG renderer on demand, inherit from SVGRenderer
extend(CanVGRenderer.prototype, SVGRenderer.prototype);
// Add additional functionality:
extend(CanVGRenderer.prototype, {
create: function (chart, container, chartWidth, chartHeight) {
this.setContainer(container, chartWidth, chartHeight);
this.configure(chart);
},
setContainer: function (container, chartWidth, chartHeight) {
var containerStyle = container.style,
containerParent = container.parentNode,
containerLeft = containerStyle.left,
containerTop = containerStyle.top,
containerOffsetWidth = container.offsetWidth,
containerOffsetHeight = container.offsetHeight,
canvas,
initialHiddenStyle = { visibility: HIDDEN, position: ABSOLUTE };
this.init.apply(this, [container, chartWidth, chartHeight]);
// add the canvas above it
canvas = createElement('canvas', {
width: containerOffsetWidth,
height: containerOffsetHeight
}, {
position: RELATIVE,
left: containerLeft,
top: containerTop
}, container);
this.canvas = canvas;
// Create the tooltip line and div, they are placed as siblings to
// the container (and as direct childs to the div specified in the html page)
this.ttLine = createElement(DIV, null, initialHiddenStyle, containerParent);
this.ttDiv = createElement(DIV, null, initialHiddenStyle, containerParent);
this.ttTimer = UNDEFINED;
// Move away the svg node to a new div inside the container's parent so we can hide it.
var hiddenSvg = createElement(DIV, {
width: containerOffsetWidth,
height: containerOffsetHeight
}, {
visibility: HIDDEN,
left: containerLeft,
top: containerTop
}, containerParent);
this.hiddenSvg = hiddenSvg;
hiddenSvg.appendChild(this.box);
},
/**
* Configures the renderer with the chart. Attach a listener to the event tooltipRefresh.
**/
configure: function (chart) {
var renderer = this,
options = chart.options.tooltip,
borderWidth = options.borderWidth,
tooltipDiv = renderer.ttDiv,
tooltipDivStyle = options.style,
tooltipLine = renderer.ttLine,
padding = parseInt(tooltipDivStyle.padding, 10);
// Add border styling from options to the style
tooltipDivStyle = merge(tooltipDivStyle, {
padding: padding + PX,
'background-color': options.backgroundColor,
'border-style': 'solid',
'border-width': borderWidth + PX,
'border-radius': options.borderRadius + PX
});
// Optionally add shadow
if (options.shadow) {
tooltipDivStyle = merge(tooltipDivStyle, {
'box-shadow': '1px 1px 3px gray', // w3c
'-webkit-box-shadow': '1px 1px 3px gray' // webkit
});
}
css(tooltipDiv, tooltipDivStyle);
// Set simple style on the line
css(tooltipLine, {
'border-left': '1px solid darkgray'
});
// This event is triggered when a new tooltip should be shown
addEvent(chart, 'tooltipRefresh', function (args) {
var chartContainer = chart.container,
offsetLeft = chartContainer.offsetLeft,
offsetTop = chartContainer.offsetTop,
position;
// Set the content of the tooltip
tooltipDiv.innerHTML = args.text;
// Compute the best position for the tooltip based on the divs size and container size.
position = chart.tooltip.getPosition(tooltipDiv.offsetWidth, tooltipDiv.offsetHeight, {plotX: args.x, plotY: args.y});
css(tooltipDiv, {
visibility: VISIBLE,
left: position.x + PX,
top: position.y + PX,
'border-color': args.borderColor
});
// Position the tooltip line
css(tooltipLine, {
visibility: VISIBLE,
left: offsetLeft + args.x + PX,
top: offsetTop + chart.plotTop + PX,
height: chart.plotHeight + PX
});
// This timeout hides the tooltip after 3 seconds
// First clear any existing timer
if (renderer.ttTimer !== UNDEFINED) {
clearTimeout(renderer.ttTimer);
}
// Start a new timer that hides tooltip and line
renderer.ttTimer = setTimeout(function () {
css(tooltipDiv, { visibility: HIDDEN });
css(tooltipLine, { visibility: HIDDEN });
}, 3000);
});
},
/**
* Extend SVGRenderer.destroy to also destroy the elements added by CanVGRenderer.
*/
destroy: function () {
var renderer = this;
// Remove the canvas
discardElement(renderer.canvas);
// Kill the timer
if (renderer.ttTimer !== UNDEFINED) {
clearTimeout(renderer.ttTimer);
}
// Remove the divs for tooltip and line
discardElement(renderer.ttLine);
discardElement(renderer.ttDiv);
discardElement(renderer.hiddenSvg);
// Continue with base class
return SVGRenderer.prototype.destroy.apply(renderer);
},
/**
* Take a color and return it if it's a string, do not make it a gradient even if it is a
* gradient. Currently canvg cannot render gradients (turns out black),
* see: http://code.google.com/p/canvg/issues/detail?id=104
*
* @param {Object} color The color or config object
*/
color: function (color, elem, prop) {
if (color && color.linearGradient) {
// Pick the end color and forward to base implementation
color = color.stops[color.stops.length - 1][1];
}
return SVGRenderer.prototype.color.call(this, color, elem, prop);
},
/**
* Draws the SVG on the canvas or adds a draw invokation to the deferred list.
*/
draw: function () {
var renderer = this;
window.canvg(renderer.canvas, renderer.hiddenSvg.innerHTML);
}
});
}(Highcharts));
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.