code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/**
* jQuery EasyUI 1.3.5
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
*/
(function(){
var _1={draggable:{js:"jquery.draggable.js"},droppable:{js:"jquery.droppable.js"},resizable:{js:"jquery.resizable.js"},linkbutton:{js:"jquery.linkbutton.js",css:"linkbutton.css"},progressbar:{js:"jquery.progressbar.js",css:"progressbar.css"},tooltip:{js:"jquery.tooltip.js",css:"tooltip.css"},pagination:{js:"jquery.pagination.js",css:"pagination.css",dependencies:["linkbutton"]},datagrid:{js:"jquery.datagrid.js",css:"datagrid.css",dependencies:["panel","resizable","linkbutton","pagination"]},treegrid:{js:"jquery.treegrid.js",css:"tree.css",dependencies:["datagrid"]},propertygrid:{js:"jquery.propertygrid.js",css:"propertygrid.css",dependencies:["datagrid"]},panel:{js:"jquery.panel.js",css:"panel.css"},window:{js:"jquery.window.js",css:"window.css",dependencies:["resizable","draggable","panel"]},dialog:{js:"jquery.dialog.js",css:"dialog.css",dependencies:["linkbutton","window"]},messager:{js:"jquery.messager.js",css:"messager.css",dependencies:["linkbutton","window","progressbar"]},layout:{js:"jquery.layout.js",css:"layout.css",dependencies:["resizable","panel"]},form:{js:"jquery.form.js"},menu:{js:"jquery.menu.js",css:"menu.css"},tabs:{js:"jquery.tabs.js",css:"tabs.css",dependencies:["panel","linkbutton"]},menubutton:{js:"jquery.menubutton.js",css:"menubutton.css",dependencies:["linkbutton","menu"]},splitbutton:{js:"jquery.splitbutton.js",css:"splitbutton.css",dependencies:["menubutton"]},accordion:{js:"jquery.accordion.js",css:"accordion.css",dependencies:["panel"]},calendar:{js:"jquery.calendar.js",css:"calendar.css"},combo:{js:"jquery.combo.js",css:"combo.css",dependencies:["panel","validatebox"]},combobox:{js:"jquery.combobox.js",css:"combobox.css",dependencies:["combo"]},combotree:{js:"jquery.combotree.js",dependencies:["combo","tree"]},combogrid:{js:"jquery.combogrid.js",dependencies:["combo","datagrid"]},validatebox:{js:"jquery.validatebox.js",css:"validatebox.css",dependencies:["tooltip"]},numberbox:{js:"jquery.numberbox.js",dependencies:["validatebox"]},searchbox:{js:"jquery.searchbox.js",css:"searchbox.css",dependencies:["menubutton"]},spinner:{js:"jquery.spinner.js",css:"spinner.css",dependencies:["validatebox"]},numberspinner:{js:"jquery.numberspinner.js",dependencies:["spinner","numberbox"]},timespinner:{js:"jquery.timespinner.js",dependencies:["spinner"]},tree:{js:"jquery.tree.js",css:"tree.css",dependencies:["draggable","droppable"]},datebox:{js:"jquery.datebox.js",css:"datebox.css",dependencies:["calendar","combo"]},datetimebox:{js:"jquery.datetimebox.js",dependencies:["datebox","timespinner"]},slider:{js:"jquery.slider.js",dependencies:["draggable"]},tooltip:{js:"jquery.tooltip.js"},parser:{js:"jquery.parser.js"}};
var _2={"af":"easyui-lang-af.js","ar":"easyui-lang-ar.js","bg":"easyui-lang-bg.js","ca":"easyui-lang-ca.js","cs":"easyui-lang-cs.js","cz":"easyui-lang-cz.js","da":"easyui-lang-da.js","de":"easyui-lang-de.js","el":"easyui-lang-el.js","en":"easyui-lang-en.js","es":"easyui-lang-es.js","fr":"easyui-lang-fr.js","it":"easyui-lang-it.js","jp":"easyui-lang-jp.js","nl":"easyui-lang-nl.js","pl":"easyui-lang-pl.js","pt_BR":"easyui-lang-pt_BR.js","ru":"easyui-lang-ru.js","sv_SE":"easyui-lang-sv_SE.js","tr":"easyui-lang-tr.js","zh_CN":"easyui-lang-zh_CN.js","zh_TW":"easyui-lang-zh_TW.js"};
var _3={};
function _4(_5,_6){
var _7=false;
var _8=document.createElement("script");
_8.type="text/javascript";
_8.language="javascript";
_8.src=_5;
_8.onload=_8.onreadystatechange=function(){
if(!_7&&(!_8.readyState||_8.readyState=="loaded"||_8.readyState=="complete")){
_7=true;
_8.onload=_8.onreadystatechange=null;
if(_6){
_6.call(_8);
}
}
};
document.getElementsByTagName("head")[0].appendChild(_8);
};
function _9(_a,_b){
_4(_a,function(){
document.getElementsByTagName("head")[0].removeChild(this);
if(_b){
_b();
}
});
};
function _c(_d,_e){
var _f=document.createElement("link");
_f.rel="stylesheet";
_f.type="text/css";
_f.media="screen";
_f.href=_d;
document.getElementsByTagName("head")[0].appendChild(_f);
if(_e){
_e.call(_f);
}
};
function _10(_11,_12){
_3[_11]="loading";
var _13=_1[_11];
var _14="loading";
var _15=(easyloader.css&&_13["css"])?"loading":"loaded";
if(easyloader.css&&_13["css"]){
if(/^http/i.test(_13["css"])){
var url=_13["css"];
}else{
var url=easyloader.base+"themes/"+easyloader.theme+"/"+_13["css"];
}
_c(url,function(){
_15="loaded";
if(_14=="loaded"&&_15=="loaded"){
_16();
}
});
}
if(/^http/i.test(_13["js"])){
var url=_13["js"];
}else{
var url=easyloader.base+"plugins/"+_13["js"];
}
_4(url,function(){
_14="loaded";
if(_14=="loaded"&&_15=="loaded"){
_16();
}
});
function _16(){
_3[_11]="loaded";
easyloader.onProgress(_11);
if(_12){
_12();
}
};
};
function _17(_18,_19){
var mm=[];
var _1a=false;
if(typeof _18=="string"){
add(_18);
}else{
for(var i=0;i<_18.length;i++){
add(_18[i]);
}
}
function add(_1b){
if(!_1[_1b]){
return;
}
var d=_1[_1b]["dependencies"];
if(d){
for(var i=0;i<d.length;i++){
add(d[i]);
}
}
mm.push(_1b);
};
function _1c(){
if(_19){
_19();
}
easyloader.onLoad(_18);
};
var _1d=0;
function _1e(){
if(mm.length){
var m=mm[0];
if(!_3[m]){
_1a=true;
_10(m,function(){
mm.shift();
_1e();
});
}else{
if(_3[m]=="loaded"){
mm.shift();
_1e();
}else{
if(_1d<easyloader.timeout){
_1d+=10;
setTimeout(arguments.callee,10);
}
}
}
}else{
if(easyloader.locale&&_1a==true&&_2[easyloader.locale]){
var url=easyloader.base+"locale/"+_2[easyloader.locale];
_9(url,function(){
_1c();
});
}else{
_1c();
}
}
};
_1e();
};
easyloader={modules:_1,locales:_2,base:".",theme:"default",css:true,locale:null,timeout:2000,load:function(_1f,_20){
if(/\.css$/i.test(_1f)){
if(/^http/i.test(_1f)){
_c(_1f,_20);
}else{
_c(easyloader.base+_1f,_20);
}
}else{
if(/\.js$/i.test(_1f)){
if(/^http/i.test(_1f)){
_4(_1f,_20);
}else{
_4(easyloader.base+_1f,_20);
}
}else{
_17(_1f,_20);
}
}
},onProgress:function(_21){
},onLoad:function(_22){
}};
var _23=document.getElementsByTagName("script");
for(var i=0;i<_23.length;i++){
var src=_23[i].src;
if(!src){
continue;
}
var m=src.match(/easyloader\.js(\W|$)/i);
if(m){
easyloader.base=src.substring(0,m.index);
}
}
window.using=easyloader.load;
if(window.jQuery){
jQuery(function(){
easyloader.load("parser",function(){
jQuery.parser.parse();
});
});
}
})();
| JavaScript |
/**
* easyloader - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
*/
(function(){
var modules = {
draggable:{
js:'jquery.draggable.js'
},
droppable:{
js:'jquery.droppable.js'
},
resizable:{
js:'jquery.resizable.js'
},
linkbutton:{
js:'jquery.linkbutton.js',
css:'linkbutton.css'
},
progressbar:{
js:'jquery.progressbar.js',
css:'progressbar.css'
},
tooltip:{
js:'jquery.tooltip.js',
css:'tooltip.css'
},
pagination:{
js:'jquery.pagination.js',
css:'pagination.css',
dependencies:['linkbutton']
},
datagrid:{
js:'jquery.datagrid.js',
css:'datagrid.css',
dependencies:['panel','resizable','linkbutton','pagination']
},
treegrid:{
js:'jquery.treegrid.js',
css:'tree.css',
dependencies:['datagrid']
},
propertygrid:{
js:'jquery.propertygrid.js',
css:'propertygrid.css',
dependencies:['datagrid']
},
panel: {
js:'jquery.panel.js',
css:'panel.css'
},
window:{
js:'jquery.window.js',
css:'window.css',
dependencies:['resizable','draggable','panel']
},
dialog:{
js:'jquery.dialog.js',
css:'dialog.css',
dependencies:['linkbutton','window']
},
messager:{
js:'jquery.messager.js',
css:'messager.css',
dependencies:['linkbutton','window','progressbar']
},
layout:{
js:'jquery.layout.js',
css:'layout.css',
dependencies:['resizable','panel']
},
form:{
js:'jquery.form.js'
},
menu:{
js:'jquery.menu.js',
css:'menu.css'
},
tabs:{
js:'jquery.tabs.js',
css:'tabs.css',
dependencies:['panel','linkbutton']
},
menubutton:{
js:'jquery.menubutton.js',
css:'menubutton.css',
dependencies:['linkbutton','menu']
},
splitbutton:{
js:'jquery.splitbutton.js',
css:'splitbutton.css',
dependencies:['menubutton']
},
accordion:{
js:'jquery.accordion.js',
css:'accordion.css',
dependencies:['panel']
},
calendar:{
js:'jquery.calendar.js',
css:'calendar.css'
},
combo:{
js:'jquery.combo.js',
css:'combo.css',
dependencies:['panel','validatebox']
},
combobox:{
js:'jquery.combobox.js',
css:'combobox.css',
dependencies:['combo']
},
combotree:{
js:'jquery.combotree.js',
dependencies:['combo','tree']
},
combogrid:{
js:'jquery.combogrid.js',
dependencies:['combo','datagrid']
},
validatebox:{
js:'jquery.validatebox.js',
css:'validatebox.css',
dependencies:['tooltip']
},
numberbox:{
js:'jquery.numberbox.js',
dependencies:['validatebox']
},
searchbox:{
js:'jquery.searchbox.js',
css:'searchbox.css',
dependencies:['menubutton']
},
spinner:{
js:'jquery.spinner.js',
css:'spinner.css',
dependencies:['validatebox']
},
numberspinner:{
js:'jquery.numberspinner.js',
dependencies:['spinner','numberbox']
},
timespinner:{
js:'jquery.timespinner.js',
dependencies:['spinner']
},
tree:{
js:'jquery.tree.js',
css:'tree.css',
dependencies:['draggable','droppable']
},
datebox:{
js:'jquery.datebox.js',
css:'datebox.css',
dependencies:['calendar','combo']
},
datetimebox:{
js:'jquery.datetimebox.js',
dependencies:['datebox','timespinner']
},
slider:{
js:'jquery.slider.js',
dependencies:['draggable']
},
tooltip:{
js:'jquery.tooltip.js'
},
parser:{
js:'jquery.parser.js'
}
};
var locales = {
'af':'easyui-lang-af.js',
'ar':'easyui-lang-ar.js',
'bg':'easyui-lang-bg.js',
'ca':'easyui-lang-ca.js',
'cs':'easyui-lang-cs.js',
'cz':'easyui-lang-cz.js',
'da':'easyui-lang-da.js',
'de':'easyui-lang-de.js',
'el':'easyui-lang-el.js',
'en':'easyui-lang-en.js',
'es':'easyui-lang-es.js',
'fr':'easyui-lang-fr.js',
'it':'easyui-lang-it.js',
'jp':'easyui-lang-jp.js',
'nl':'easyui-lang-nl.js',
'pl':'easyui-lang-pl.js',
'pt_BR':'easyui-lang-pt_BR.js',
'ru':'easyui-lang-ru.js',
'sv_SE':'easyui-lang-sv_SE.js',
'tr':'easyui-lang-tr.js',
'zh_CN':'easyui-lang-zh_CN.js',
'zh_TW':'easyui-lang-zh_TW.js'
};
var queues = {};
function loadJs(url, callback){
var done = false;
var script = document.createElement('script');
script.type = 'text/javascript';
script.language = 'javascript';
script.src = url;
script.onload = script.onreadystatechange = function(){
if (!done && (!script.readyState || script.readyState == 'loaded' || script.readyState == 'complete')){
done = true;
script.onload = script.onreadystatechange = null;
if (callback){
callback.call(script);
}
}
}
document.getElementsByTagName("head")[0].appendChild(script);
}
function runJs(url, callback){
loadJs(url, function(){
document.getElementsByTagName("head")[0].removeChild(this);
if (callback){
callback();
}
});
}
function loadCss(url, callback){
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.media = 'screen';
link.href = url;
document.getElementsByTagName('head')[0].appendChild(link);
if (callback){
callback.call(link);
}
}
function loadSingle(name, callback){
queues[name] = 'loading';
var module = modules[name];
var jsStatus = 'loading';
var cssStatus = (easyloader.css && module['css']) ? 'loading' : 'loaded';
if (easyloader.css && module['css']){
if (/^http/i.test(module['css'])){
var url = module['css'];
} else {
var url = easyloader.base + 'themes/' + easyloader.theme + '/' + module['css'];
}
loadCss(url, function(){
cssStatus = 'loaded';
if (jsStatus == 'loaded' && cssStatus == 'loaded'){
finish();
}
});
}
if (/^http/i.test(module['js'])){
var url = module['js'];
} else {
var url = easyloader.base + 'plugins/' + module['js'];
}
loadJs(url, function(){
jsStatus = 'loaded';
if (jsStatus == 'loaded' && cssStatus == 'loaded'){
finish();
}
});
function finish(){
queues[name] = 'loaded';
easyloader.onProgress(name);
if (callback){
callback();
}
}
}
function loadModule(name, callback){
var mm = [];
var doLoad = false;
if (typeof name == 'string'){
add(name);
} else {
for(var i=0; i<name.length; i++){
add(name[i]);
}
}
function add(name){
if (!modules[name]) return;
var d = modules[name]['dependencies'];
if (d){
for(var i=0; i<d.length; i++){
add(d[i]);
}
}
mm.push(name);
}
function finish(){
if (callback){
callback();
}
easyloader.onLoad(name);
}
var time = 0;
function loadMm(){
if (mm.length){
var m = mm[0]; // the first module
if (!queues[m]){
doLoad = true;
loadSingle(m, function(){
mm.shift();
loadMm();
});
} else if (queues[m] == 'loaded'){
mm.shift();
loadMm();
} else {
if (time < easyloader.timeout){
time += 10;
setTimeout(arguments.callee, 10);
}
}
} else {
if (easyloader.locale && doLoad == true && locales[easyloader.locale]){
var url = easyloader.base + 'locale/' + locales[easyloader.locale];
runJs(url, function(){
finish();
});
} else {
finish();
}
}
}
loadMm();
}
easyloader = {
modules:modules,
locales:locales,
base:'.',
theme:'default',
css:true,
locale:null,
timeout:2000,
load: function(name, callback){
if (/\.css$/i.test(name)){
if (/^http/i.test(name)){
loadCss(name, callback);
} else {
loadCss(easyloader.base + name, callback);
}
} else if (/\.js$/i.test(name)){
if (/^http/i.test(name)){
loadJs(name, callback);
} else {
loadJs(easyloader.base + name, callback);
}
} else {
loadModule(name, callback);
}
},
onProgress: function(name){},
onLoad: function(name){}
};
var scripts = document.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
var src = scripts[i].src;
if (!src) continue;
var m = src.match(/easyloader\.js(\W|$)/i);
if (m){
easyloader.base = src.substring(0, m.index);
}
}
window.using = easyloader.load;
if (window.jQuery){
jQuery(function(){
easyloader.load('parser', function(){
jQuery.parser.parse();
});
});
}
})();
| JavaScript |
/**
* droppable - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*/
(function($){
function init(target){
$(target).addClass('droppable');
$(target).bind('_dragenter', function(e, source){
$.data(target, 'droppable').options.onDragEnter.apply(target, [e, source]);
});
$(target).bind('_dragleave', function(e, source){
$.data(target, 'droppable').options.onDragLeave.apply(target, [e, source]);
});
$(target).bind('_dragover', function(e, source){
$.data(target, 'droppable').options.onDragOver.apply(target, [e, source]);
});
$(target).bind('_drop', function(e, source){
$.data(target, 'droppable').options.onDrop.apply(target, [e, source]);
});
}
$.fn.droppable = function(options, param){
if (typeof options == 'string'){
return $.fn.droppable.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'droppable');
if (state){
$.extend(state.options, options);
} else {
init(this);
$.data(this, 'droppable', {
options: $.extend({}, $.fn.droppable.defaults, $.fn.droppable.parseOptions(this), options)
});
}
});
};
$.fn.droppable.methods = {
options: function(jq){
return $.data(jq[0], 'droppable').options;
},
enable: function(jq){
return jq.each(function(){
$(this).droppable({disabled:false});
});
},
disable: function(jq){
return jq.each(function(){
$(this).droppable({disabled:true});
});
}
};
$.fn.droppable.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.parser.parseOptions(target, ['accept']), {
disabled: (t.attr('disabled') ? true : undefined)
});
};
$.fn.droppable.defaults = {
accept:null,
disabled:false,
onDragEnter:function(e, source){},
onDragOver:function(e, source){},
onDragLeave:function(e, source){},
onDrop:function(e, source){}
};
})(jQuery);
| JavaScript |
/**
* calendar - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
*/
(function($){
function setSize(target){
var opts = $.data(target, 'calendar').options;
var t = $(target);
// if (opts.fit == true){
// var p = t.parent();
// opts.width = p.width();
// opts.height = p.height();
// }
opts.fit ? $.extend(opts, t._fit()) : t._fit(false);
var header = t.find('.calendar-header');
t._outerWidth(opts.width);
t._outerHeight(opts.height);
t.find('.calendar-body')._outerHeight(t.height() - header._outerHeight());
}
function init(target){
$(target).addClass('calendar').html(
'<div class="calendar-header">' +
'<div class="calendar-prevmonth"></div>' +
'<div class="calendar-nextmonth"></div>' +
'<div class="calendar-prevyear"></div>' +
'<div class="calendar-nextyear"></div>' +
'<div class="calendar-title">' +
'<span>Aprial 2010</span>' +
'</div>' +
'</div>' +
'<div class="calendar-body">' +
'<div class="calendar-menu">' +
'<div class="calendar-menu-year-inner">' +
'<span class="calendar-menu-prev"></span>' +
'<span><input class="calendar-menu-year" type="text"></input></span>' +
'<span class="calendar-menu-next"></span>' +
'</div>' +
'<div class="calendar-menu-month-inner">' +
'</div>' +
'</div>' +
'</div>'
);
$(target).find('.calendar-title span').hover(
function(){$(this).addClass('calendar-menu-hover');},
function(){$(this).removeClass('calendar-menu-hover');}
).click(function(){
var menu = $(target).find('.calendar-menu');
if (menu.is(':visible')){
menu.hide();
} else {
showSelectMenus(target);
}
});
$('.calendar-prevmonth,.calendar-nextmonth,.calendar-prevyear,.calendar-nextyear', target).hover(
function(){$(this).addClass('calendar-nav-hover');},
function(){$(this).removeClass('calendar-nav-hover');}
);
$(target).find('.calendar-nextmonth').click(function(){
showMonth(target, 1);
});
$(target).find('.calendar-prevmonth').click(function(){
showMonth(target, -1);
});
$(target).find('.calendar-nextyear').click(function(){
showYear(target, 1);
});
$(target).find('.calendar-prevyear').click(function(){
showYear(target, -1);
});
$(target).bind('_resize', function(){
var opts = $.data(target, 'calendar').options;
if (opts.fit == true){
setSize(target);
}
return false;
});
}
/**
* show the calendar corresponding to the current month.
*/
function showMonth(target, delta){
var opts = $.data(target, 'calendar').options;
opts.month += delta;
if (opts.month > 12){
opts.year++;
opts.month = 1;
} else if (opts.month < 1){
opts.year--;
opts.month = 12;
}
show(target);
var menu = $(target).find('.calendar-menu-month-inner');
menu.find('td.calendar-selected').removeClass('calendar-selected');
menu.find('td:eq(' + (opts.month-1) + ')').addClass('calendar-selected');
}
/**
* show the calendar corresponding to the current year.
*/
function showYear(target, delta){
var opts = $.data(target, 'calendar').options;
opts.year += delta;
show(target);
var menu = $(target).find('.calendar-menu-year');
menu.val(opts.year);
}
/**
* show the select menu that can change year or month, if the menu is not be created then create it.
*/
function showSelectMenus(target){
var opts = $.data(target, 'calendar').options;
$(target).find('.calendar-menu').show();
if ($(target).find('.calendar-menu-month-inner').is(':empty')){
$(target).find('.calendar-menu-month-inner').empty();
var t = $('<table></table>').appendTo($(target).find('.calendar-menu-month-inner'));
var idx = 0;
for(var i=0; i<3; i++){
var tr = $('<tr></tr>').appendTo(t);
for(var j=0; j<4; j++){
$('<td class="calendar-menu-month"></td>').html(opts.months[idx++]).attr('abbr',idx).appendTo(tr);
}
}
$(target).find('.calendar-menu-prev,.calendar-menu-next').hover(
function(){$(this).addClass('calendar-menu-hover');},
function(){$(this).removeClass('calendar-menu-hover');}
);
$(target).find('.calendar-menu-next').click(function(){
var y = $(target).find('.calendar-menu-year');
if (!isNaN(y.val())){
y.val(parseInt(y.val()) + 1);
}
});
$(target).find('.calendar-menu-prev').click(function(){
var y = $(target).find('.calendar-menu-year');
if (!isNaN(y.val())){
y.val(parseInt(y.val() - 1));
}
});
$(target).find('.calendar-menu-year').keypress(function(e){
if (e.keyCode == 13){
setDate();
}
});
$(target).find('.calendar-menu-month').hover(
function(){$(this).addClass('calendar-menu-hover');},
function(){$(this).removeClass('calendar-menu-hover');}
).click(function(){
var menu = $(target).find('.calendar-menu');
menu.find('.calendar-selected').removeClass('calendar-selected');
$(this).addClass('calendar-selected');
setDate();
});
}
function setDate(){
var menu = $(target).find('.calendar-menu');
var year = menu.find('.calendar-menu-year').val();
var month = menu.find('.calendar-selected').attr('abbr');
if (!isNaN(year)){
opts.year = parseInt(year);
opts.month = parseInt(month);
show(target);
}
menu.hide();
}
var body = $(target).find('.calendar-body');
var sele = $(target).find('.calendar-menu');
var seleYear = sele.find('.calendar-menu-year-inner');
var seleMonth = sele.find('.calendar-menu-month-inner');
seleYear.find('input').val(opts.year).focus();
seleMonth.find('td.calendar-selected').removeClass('calendar-selected');
seleMonth.find('td:eq('+(opts.month-1)+')').addClass('calendar-selected');
sele._outerWidth(body._outerWidth());
sele._outerHeight(body._outerHeight());
seleMonth._outerHeight(sele.height() - seleYear._outerHeight());
}
/**
* get weeks data.
*/
function getWeeks(target, year, month){
var opts = $.data(target, 'calendar').options;
var dates = [];
var lastDay = new Date(year, month, 0).getDate();
for(var i=1; i<=lastDay; i++) dates.push([year,month,i]);
// group date by week
var weeks = [], week = [];
// var memoDay = 0;
var memoDay = -1;
while(dates.length > 0){
var date = dates.shift();
week.push(date);
var day = new Date(date[0],date[1]-1,date[2]).getDay();
if (memoDay == day){
day = 0;
} else if (day == (opts.firstDay==0 ? 7 : opts.firstDay) - 1){
weeks.push(week);
week = [];
}
memoDay = day;
}
if (week.length){
weeks.push(week);
}
var firstWeek = weeks[0];
if (firstWeek.length < 7){
while(firstWeek.length < 7){
var firstDate = firstWeek[0];
var date = new Date(firstDate[0],firstDate[1]-1,firstDate[2]-1)
firstWeek.unshift([date.getFullYear(), date.getMonth()+1, date.getDate()]);
}
} else {
var firstDate = firstWeek[0];
var week = [];
for(var i=1; i<=7; i++){
var date = new Date(firstDate[0], firstDate[1]-1, firstDate[2]-i);
week.unshift([date.getFullYear(), date.getMonth()+1, date.getDate()]);
}
weeks.unshift(week);
}
var lastWeek = weeks[weeks.length-1];
while(lastWeek.length < 7){
var lastDate = lastWeek[lastWeek.length-1];
var date = new Date(lastDate[0], lastDate[1]-1, lastDate[2]+1);
lastWeek.push([date.getFullYear(), date.getMonth()+1, date.getDate()]);
}
if (weeks.length < 6){
var lastDate = lastWeek[lastWeek.length-1];
var week = [];
for(var i=1; i<=7; i++){
var date = new Date(lastDate[0], lastDate[1]-1, lastDate[2]+i);
week.push([date.getFullYear(), date.getMonth()+1, date.getDate()]);
}
weeks.push(week);
}
return weeks;
}
/**
* show the calendar day.
*/
function show(target){
var opts = $.data(target, 'calendar').options;
$(target).find('.calendar-title span').html(opts.months[opts.month-1] + ' ' + opts.year);
var body = $(target).find('div.calendar-body');
body.find('>table').remove();
var t = $('<table cellspacing="0" cellpadding="0" border="0"><thead></thead><tbody></tbody></table>').prependTo(body);
var tr = $('<tr></tr>').appendTo(t.find('thead'));
for(var i=opts.firstDay; i<opts.weeks.length; i++){
tr.append('<th>'+opts.weeks[i]+'</th>');
}
for(var i=0; i<opts.firstDay; i++){
tr.append('<th>'+opts.weeks[i]+'</th>');
}
var weeks = getWeeks(target, opts.year, opts.month);
for(var i=0; i<weeks.length; i++){
var week = weeks[i];
var tr = $('<tr></tr>').appendTo(t.find('tbody'));
for(var j=0; j<week.length; j++){
var day = week[j];
$('<td class="calendar-day calendar-other-month"></td>').attr('abbr',day[0]+','+day[1]+','+day[2]).html(day[2]).appendTo(tr);
}
}
t.find('td[abbr^="'+opts.year+','+opts.month+'"]').removeClass('calendar-other-month');
var now = new Date();
var today = now.getFullYear()+','+(now.getMonth()+1)+','+now.getDate();
t.find('td[abbr="'+today+'"]').addClass('calendar-today');
if (opts.current){
t.find('.calendar-selected').removeClass('calendar-selected');
var current = opts.current.getFullYear()+','+(opts.current.getMonth()+1)+','+opts.current.getDate();
t.find('td[abbr="'+current+'"]').addClass('calendar-selected');
}
// calulate the saturday and sunday index
var saIndex = 6 - opts.firstDay;
var suIndex = saIndex + 1;
if (saIndex >= 7) saIndex -= 7;
if (suIndex >= 7) suIndex -= 7;
t.find('tr').find('td:eq('+saIndex+')').addClass('calendar-saturday');
t.find('tr').find('td:eq('+suIndex+')').addClass('calendar-sunday');
t.find('td').hover(
function(){$(this).addClass('calendar-hover');},
function(){$(this).removeClass('calendar-hover');}
).click(function(){
t.find('.calendar-selected').removeClass('calendar-selected');
$(this).addClass('calendar-selected');
var parts = $(this).attr('abbr').split(',');
opts.current = new Date(parts[0], parseInt(parts[1])-1, parts[2]);
opts.onSelect.call(target, opts.current);
});
}
$.fn.calendar = function(options, param){
if (typeof options == 'string'){
return $.fn.calendar.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'calendar');
if (state){
$.extend(state.options, options);
} else {
state = $.data(this, 'calendar', {
options:$.extend({}, $.fn.calendar.defaults, $.fn.calendar.parseOptions(this), options)
});
init(this);
}
if (state.options.border == false){
$(this).addClass('calendar-noborder');
}
setSize(this);
show(this);
$(this).find('div.calendar-menu').hide(); // hide the calendar menu
});
};
$.fn.calendar.methods = {
options: function(jq){
return $.data(jq[0], 'calendar').options;
},
resize: function(jq){
return jq.each(function(){
setSize(this);
});
},
moveTo: function(jq, date){
return jq.each(function(){
$(this).calendar({
year: date.getFullYear(),
month: date.getMonth()+1,
current: date
});
});
}
};
$.fn.calendar.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.parser.parseOptions(target, [
'width','height',{firstDay:'number',fit:'boolean',border:'boolean'}
]));
};
$.fn.calendar.defaults = {
width:180,
height:180,
fit:false,
border:true,
firstDay:0,
weeks:['S','M','T','W','T','F','S'],
months:['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
year:new Date().getFullYear(),
month:new Date().getMonth()+1,
current:new Date(),
onSelect: function(date){}
};
})(jQuery);
| JavaScript |
/**
* slider - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* draggable
*
*/
(function($){
function init(target){
var slider = $('<div class="slider">' +
'<div class="slider-inner">' +
'<a href="javascript:void(0)" class="slider-handle"></a>' +
'<span class="slider-tip"></span>' +
'</div>' +
'<div class="slider-rule"></div>' +
'<div class="slider-rulelabel"></div>' +
'<div style="clear:both"></div>' +
'<input type="hidden" class="slider-value">' +
'</div>').insertAfter(target);
var t = $(target);
t.addClass('slider-f').hide();
var name = t.attr('name');
if (name){
slider.find('input.slider-value').attr('name', name);
t.removeAttr('name').attr('sliderName', name);
}
return slider;
}
/**
* set the slider size, for vertical slider, the height property is required
*/
function setSize(target, param){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
if (param){
if (param.width) opts.width = param.width;
if (param.height) opts.height = param.height;
}
if (opts.mode == 'h'){
slider.css('height', '');
slider.children('div').css('height', '');
if (!isNaN(opts.width)){
slider.width(opts.width);
}
} else {
slider.css('width', '');
slider.children('div').css('width', '');
if (!isNaN(opts.height)){
slider.height(opts.height);
slider.find('div.slider-rule').height(opts.height);
slider.find('div.slider-rulelabel').height(opts.height);
slider.find('div.slider-inner')._outerHeight(opts.height);
}
}
initValue(target);
}
/**
* show slider rule if needed
*/
function showRule(target){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
var aa = opts.mode == 'h' ? opts.rule : opts.rule.slice(0).reverse();
if (opts.reversed){
aa = aa.slice(0).reverse();
}
_build(aa);
function _build(aa){
var rule = slider.find('div.slider-rule');
var label = slider.find('div.slider-rulelabel');
rule.empty();
label.empty();
for(var i=0; i<aa.length; i++){
var distance = i*100/(aa.length-1)+'%';
var span = $('<span></span>').appendTo(rule);
span.css((opts.mode=='h'?'left':'top'), distance);
// show the labels
if (aa[i] != '|'){
span = $('<span></span>').appendTo(label);
span.html(aa[i]);
if (opts.mode == 'h'){
span.css({
left: distance,
marginLeft: -Math.round(span.outerWidth()/2)
});
} else {
span.css({
top: distance,
marginTop: -Math.round(span.outerHeight()/2)
});
}
}
}
}
}
/**
* build the slider and set some properties
*/
function buildSlider(target){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
slider.removeClass('slider-h slider-v slider-disabled');
slider.addClass(opts.mode == 'h' ? 'slider-h' : 'slider-v');
slider.addClass(opts.disabled ? 'slider-disabled' : '');
slider.find('a.slider-handle').draggable({
axis:opts.mode,
cursor:'pointer',
disabled: opts.disabled,
onDrag:function(e){
var left = e.data.left;
var width = slider.width();
if (opts.mode!='h'){
left = e.data.top;
width = slider.height();
}
if (left < 0 || left > width) {
return false;
} else {
var value = pos2value(target, left);
adjustValue(value);
return false;
}
},
onBeforeDrag:function(){
state.isDragging = true;
},
onStartDrag:function(){
opts.onSlideStart.call(target, opts.value);
},
onStopDrag:function(e){
var value = pos2value(target, (opts.mode=='h'?e.data.left:e.data.top));
adjustValue(value);
opts.onSlideEnd.call(target, opts.value);
opts.onComplete.call(target, opts.value);
state.isDragging = false;
}
});
slider.find('div.slider-inner').unbind('.slider').bind('mousedown.slider', function(e){
if (state.isDragging){return}
var pos = $(this).offset();
var value = pos2value(target, (opts.mode=='h'?(e.pageX-pos.left):(e.pageY-pos.top)));
adjustValue(value);
opts.onComplete.call(target, opts.value);
});
function adjustValue(value){
var s = Math.abs(value % opts.step);
if (s < opts.step/2){
value -= s;
} else {
value = value - s + opts.step;
}
setValue(target, value);
}
}
/**
* set a specified value to slider
*/
function setValue(target, value){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
var oldValue = opts.value;
if (value < opts.min) value = opts.min;
if (value > opts.max) value = opts.max;
opts.value = value;
$(target).val(value);
slider.find('input.slider-value').val(value);
var pos = value2pos(target, value);
var tip = slider.find('.slider-tip');
if (opts.showTip){
tip.show();
tip.html(opts.tipFormatter.call(target, opts.value));
} else {
tip.hide();
}
if (opts.mode == 'h'){
var style = 'left:'+pos+'px;';
slider.find('.slider-handle').attr('style', style);
tip.attr('style', style + 'margin-left:' + (-Math.round(tip.outerWidth()/2)) + 'px');
} else {
var style = 'top:' + pos + 'px;';
slider.find('.slider-handle').attr('style', style);
tip.attr('style', style + 'margin-left:' + (-Math.round(tip.outerWidth())) + 'px');
}
if (oldValue != value){
opts.onChange.call(target, value, oldValue);
}
}
function initValue(target){
var opts = $.data(target, 'slider').options;
var fn = opts.onChange;
opts.onChange = function(){};
setValue(target, opts.value);
opts.onChange = fn;
}
/**
* translate value to slider position
*/
function value2pos(target, value){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
if (opts.mode == 'h'){
var pos = (value-opts.min)/(opts.max-opts.min)*slider.width();
if (opts.reversed){
pos = slider.width() - pos;
}
} else {
var pos = slider.height() - (value-opts.min)/(opts.max-opts.min)*slider.height();
if (opts.reversed){
pos = slider.height() - pos;
}
}
return pos.toFixed(0);
}
/**
* translate slider position to value
*/
function pos2value(target, pos){
var state = $.data(target, 'slider');
var opts = state.options;
var slider = state.slider;
if (opts.mode == 'h'){
var value = opts.min + (opts.max-opts.min)*(pos/slider.width());
} else {
var value = opts.min + (opts.max-opts.min)*((slider.height()-pos)/slider.height());
}
return opts.reversed ? opts.max - value.toFixed(0) : value.toFixed(0);
}
$.fn.slider = function(options, param){
if (typeof options == 'string'){
return $.fn.slider.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'slider');
if (state){
$.extend(state.options, options);
} else {
state = $.data(this, 'slider', {
options: $.extend({}, $.fn.slider.defaults, $.fn.slider.parseOptions(this), options),
slider: init(this)
});
$(this).removeAttr('disabled');
}
var opts = state.options;
opts.min = parseFloat(opts.min);
opts.max = parseFloat(opts.max);
opts.value = parseFloat(opts.value);
opts.step = parseFloat(opts.step);
opts.originalValue = opts.value;
buildSlider(this);
showRule(this);
setSize(this);
});
};
$.fn.slider.methods = {
options: function(jq){
return $.data(jq[0], 'slider').options;
},
destroy: function(jq){
return jq.each(function(){
$.data(this, 'slider').slider.remove();
$(this).remove();
});
},
resize: function(jq, param){
return jq.each(function(){
setSize(this, param);
});
},
getValue: function(jq){
return jq.slider('options').value;
},
setValue: function(jq, value){
return jq.each(function(){
setValue(this, value);
});
},
clear: function(jq){
return jq.each(function(){
var opts = $(this).slider('options');
setValue(this, opts.min);
});
},
reset: function(jq){
return jq.each(function(){
var opts = $(this).slider('options');
setValue(this, opts.originalValue);
});
},
enable: function(jq){
return jq.each(function(){
$.data(this, 'slider').options.disabled = false;
buildSlider(this);
});
},
disable: function(jq){
return jq.each(function(){
$.data(this, 'slider').options.disabled = true;
buildSlider(this);
});
}
};
$.fn.slider.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.parser.parseOptions(target, [
'width','height','mode',{reversed:'boolean',showTip:'boolean',min:'number',max:'number',step:'number'}
]), {
value: (t.val() || undefined),
disabled: (t.attr('disabled') ? true : undefined),
rule: (t.attr('rule') ? eval(t.attr('rule')) : undefined)
});
};
$.fn.slider.defaults = {
width: 'auto',
height: 'auto',
mode: 'h', // 'h'(horizontal) or 'v'(vertical)
reversed: false,
showTip: false,
disabled: false,
value: 0,
min: 0,
max: 100,
step: 1,
rule: [], // [0,'|',100]
tipFormatter: function(value){return value},
onChange: function(value, oldValue){},
onSlideStart: function(value){},
onSlideEnd: function(value){},
onComplete: function(value){}
};
})(jQuery);
| JavaScript |
/**
* tabs - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* panel
* linkbutton
*
*/
(function($){
/**
* set the tabs scrollers to show or not,
* dependent on the tabs count and width
*/
function setScrollers(container) {
var opts = $.data(container, 'tabs').options;
if (opts.tabPosition == 'left' || opts.tabPosition == 'right' || !opts.showHeader){return}
var header = $(container).children('div.tabs-header');
var tool = header.children('div.tabs-tool');
var sLeft = header.children('div.tabs-scroller-left');
var sRight = header.children('div.tabs-scroller-right');
var wrap = header.children('div.tabs-wrap');
// set the tool height
var tHeight = header.outerHeight();
if (opts.plain){
tHeight -= tHeight - header.height();
}
tool._outerHeight(tHeight);
var tabsWidth = 0;
$('ul.tabs li', header).each(function(){
tabsWidth += $(this).outerWidth(true);
});
var cWidth = header.width() - tool._outerWidth();
if (tabsWidth > cWidth) {
sLeft.add(sRight).show()._outerHeight(tHeight);
if (opts.toolPosition == 'left'){
tool.css({
left: sLeft.outerWidth(),
right: ''
});
wrap.css({
marginLeft: sLeft.outerWidth() + tool._outerWidth(),
marginRight: sRight._outerWidth(),
width: cWidth - sLeft.outerWidth() - sRight.outerWidth()
});
} else {
tool.css({
left: '',
right: sRight.outerWidth()
});
wrap.css({
marginLeft: sLeft.outerWidth(),
marginRight: sRight.outerWidth() + tool._outerWidth(),
width: cWidth - sLeft.outerWidth() - sRight.outerWidth()
});
}
} else {
sLeft.add(sRight).hide();
if (opts.toolPosition == 'left'){
tool.css({
left: 0,
right: ''
});
wrap.css({
marginLeft: tool._outerWidth(),
marginRight: 0,
width: cWidth
});
} else {
tool.css({
left: '',
right: 0
});
wrap.css({
marginLeft: 0,
marginRight: tool._outerWidth(),
width: cWidth
});
}
}
}
function addTools(container){
var opts = $.data(container, 'tabs').options;
var header = $(container).children('div.tabs-header');
if (opts.tools) {
if (typeof opts.tools == 'string'){
$(opts.tools).addClass('tabs-tool').appendTo(header);
$(opts.tools).show();
} else {
header.children('div.tabs-tool').remove();
var tools = $('<div class="tabs-tool"><table cellspacing="0" cellpadding="0" style="height:100%"><tr></tr></table></div>').appendTo(header);
var tr = tools.find('tr');
for(var i=0; i<opts.tools.length; i++){
var td = $('<td></td>').appendTo(tr);
var tool = $('<a href="javascript:void(0);"></a>').appendTo(td);
tool[0].onclick = eval(opts.tools[i].handler || function(){});
tool.linkbutton($.extend({}, opts.tools[i], {
plain: true
}));
}
}
} else {
header.children('div.tabs-tool').remove();
}
}
function setSize(container) {
var state = $.data(container, 'tabs');
var opts = state.options;
var cc = $(container);
opts.fit ? $.extend(opts, cc._fit()) : cc._fit(false);
cc.width(opts.width).height(opts.height);
var header = $(container).children('div.tabs-header');
var panels = $(container).children('div.tabs-panels');
var wrap = header.find('div.tabs-wrap');
var ul = wrap.find('.tabs');
for(var i=0; i<state.tabs.length; i++){
var p_opts = state.tabs[i].panel('options');
var p_t = p_opts.tab.find('a.tabs-inner');
var width = parseInt(p_opts.tabWidth || opts.tabWidth) || undefined;
if (width){
p_t._outerWidth(width);
} else {
p_t.css('width', '');
}
p_t._outerHeight(opts.tabHeight);
p_t.css('lineHeight', p_t.height()+'px');
}
if (opts.tabPosition == 'left' || opts.tabPosition == 'right'){
header._outerWidth(opts.showHeader ? opts.headerWidth : 0);
// header._outerWidth(opts.headerWidth);
panels._outerWidth(cc.width() - header.outerWidth());
header.add(panels)._outerHeight(opts.height);
wrap._outerWidth(header.width());
ul._outerWidth(wrap.width()).css('height','');
} else {
var lrt = header.children('div.tabs-scroller-left,div.tabs-scroller-right,div.tabs-tool');
header._outerWidth(opts.width).css('height','');
if (opts.showHeader){
header.css('background-color','');
wrap.css('height','');
lrt.show();
} else {
header.css('background-color','transparent');
header._outerHeight(0);
wrap._outerHeight(0);
lrt.hide();
}
ul._outerHeight(opts.tabHeight).css('width','');
setScrollers(container);
var height = opts.height;
if (!isNaN(height)) {
panels._outerHeight(height - header.outerHeight());
} else {
panels.height('auto');
}
var width = opts.width;
if (!isNaN(width)){
panels._outerWidth(width);
} else {
panels.width('auto');
}
}
}
/**
* set selected tab panel size
*/
function setSelectedSize(container){
var opts = $.data(container, 'tabs').options;
var tab = getSelectedTab(container);
if (tab){
var panels = $(container).children('div.tabs-panels');
var width = opts.width=='auto' ? 'auto' : panels.width();
var height = opts.height=='auto' ? 'auto' : panels.height();
tab.panel('resize', {
width: width,
height: height
});
}
}
/**
* wrap the tabs header and body
*/
function wrapTabs(container) {
var tabs = $.data(container, 'tabs').tabs;
var cc = $(container);
cc.addClass('tabs-container');
var pp = $('<div class="tabs-panels"></div>').insertBefore(cc);
cc.children('div').each(function(){
pp[0].appendChild(this);
});
cc[0].appendChild(pp[0]);
// cc.wrapInner('<div class="tabs-panels"/>');
$('<div class="tabs-header">'
+ '<div class="tabs-scroller-left"></div>'
+ '<div class="tabs-scroller-right"></div>'
+ '<div class="tabs-wrap">'
+ '<ul class="tabs"></ul>'
+ '</div>'
+ '</div>').prependTo(container);
cc.children('div.tabs-panels').children('div').each(function(i){
var opts = $.extend({}, $.parser.parseOptions(this), {
selected: ($(this).attr('selected') ? true : undefined)
});
var pp = $(this);
tabs.push(pp);
createTab(container, pp, opts);
});
cc.children('div.tabs-header').find('.tabs-scroller-left, .tabs-scroller-right').hover(
function(){$(this).addClass('tabs-scroller-over');},
function(){$(this).removeClass('tabs-scroller-over');}
);
cc.bind('_resize', function(e,force){
var opts = $.data(container, 'tabs').options;
if (opts.fit == true || force){
setSize(container);
setSelectedSize(container);
}
return false;
});
}
function bindEvents(container){
var state = $.data(container, 'tabs')
var opts = state.options;
$(container).children('div.tabs-header').unbind().bind('click', function(e){
if ($(e.target).hasClass('tabs-scroller-left')){
$(container).tabs('scrollBy', -opts.scrollIncrement);
} else if ($(e.target).hasClass('tabs-scroller-right')){
$(container).tabs('scrollBy', opts.scrollIncrement);
} else {
var li = $(e.target).closest('li');
if (li.hasClass('tabs-disabled')){return;}
var a = $(e.target).closest('a.tabs-close');
if (a.length){
closeTab(container, getLiIndex(li));
} else if (li.length){
// selectTab(container, getLiIndex(li));
var index = getLiIndex(li);
var popts = state.tabs[index].panel('options');
if (popts.collapsible){
popts.closed ? selectTab(container, index) : unselectTab(container, index);
} else {
selectTab(container, index);
}
}
}
}).bind('contextmenu', function(e){
var li = $(e.target).closest('li');
if (li.hasClass('tabs-disabled')){return;}
if (li.length){
opts.onContextMenu.call(container, e, li.find('span.tabs-title').html(), getLiIndex(li));
}
});
function getLiIndex(li){
var index = 0;
li.parent().children('li').each(function(i){
if (li[0] == this){
index = i;
return false;
}
});
return index;
}
}
function setProperties(container){
var opts = $.data(container, 'tabs').options;
var header = $(container).children('div.tabs-header');
var panels = $(container).children('div.tabs-panels');
header.removeClass('tabs-header-top tabs-header-bottom tabs-header-left tabs-header-right');
panels.removeClass('tabs-panels-top tabs-panels-bottom tabs-panels-left tabs-panels-right');
if (opts.tabPosition == 'top'){
header.insertBefore(panels);
} else if (opts.tabPosition == 'bottom'){
header.insertAfter(panels);
header.addClass('tabs-header-bottom');
panels.addClass('tabs-panels-top');
} else if (opts.tabPosition == 'left'){
header.addClass('tabs-header-left');
panels.addClass('tabs-panels-right');
} else if (opts.tabPosition == 'right'){
header.addClass('tabs-header-right');
panels.addClass('tabs-panels-left');
}
if (opts.plain == true) {
header.addClass('tabs-header-plain');
} else {
header.removeClass('tabs-header-plain');
}
if (opts.border == true){
header.removeClass('tabs-header-noborder');
panels.removeClass('tabs-panels-noborder');
} else {
header.addClass('tabs-header-noborder');
panels.addClass('tabs-panels-noborder');
}
}
function createTab(container, pp, options) {
var state = $.data(container, 'tabs');
options = options || {};
// create panel
pp.panel($.extend({}, options, {
border: false,
noheader: true,
closed: true,
doSize: false,
iconCls: (options.icon ? options.icon : undefined),
onLoad: function(){
if (options.onLoad){
options.onLoad.call(this, arguments);
}
state.options.onLoad.call(container, $(this));
}
}));
var opts = pp.panel('options');
var tabs = $(container).children('div.tabs-header').find('ul.tabs');
opts.tab = $('<li></li>').appendTo(tabs); // set the tab object in panel options
opts.tab.append(
'<a href="javascript:void(0)" class="tabs-inner">' +
'<span class="tabs-title"></span>' +
'<span class="tabs-icon"></span>' +
'</a>'
);
$(container).tabs('update', {
tab: pp,
options: opts
});
}
function addTab(container, options) {
var opts = $.data(container, 'tabs').options;
var tabs = $.data(container, 'tabs').tabs;
if (options.selected == undefined) options.selected = true;
var pp = $('<div></div>').appendTo($(container).children('div.tabs-panels'));
tabs.push(pp);
createTab(container, pp, options);
opts.onAdd.call(container, options.title, tabs.length-1);
// setScrollers(container);
setSize(container);
if (options.selected){
selectTab(container, tabs.length-1); // select the added tab panel
}
}
/**
* update tab panel, param has following properties:
* tab: the tab panel to be updated
* options: the tab panel options
*/
function updateTab(container, param){
var selectHis = $.data(container, 'tabs').selectHis;
var pp = param.tab; // the tab panel
var oldTitle = pp.panel('options').title;
pp.panel($.extend({}, param.options, {
iconCls: (param.options.icon ? param.options.icon : undefined)
}));
var opts = pp.panel('options'); // get the tab panel options
var tab = opts.tab;
var s_title = tab.find('span.tabs-title');
var s_icon = tab.find('span.tabs-icon');
s_title.html(opts.title);
s_icon.attr('class', 'tabs-icon');
tab.find('a.tabs-close').remove();
if (opts.closable){
s_title.addClass('tabs-closable');
$('<a href="javascript:void(0)" class="tabs-close"></a>').appendTo(tab);
} else{
s_title.removeClass('tabs-closable');
}
if (opts.iconCls){
s_title.addClass('tabs-with-icon');
s_icon.addClass(opts.iconCls);
} else {
s_title.removeClass('tabs-with-icon');
}
if (oldTitle != opts.title){
for(var i=0; i<selectHis.length; i++){
if (selectHis[i] == oldTitle){
selectHis[i] = opts.title;
}
}
}
tab.find('span.tabs-p-tool').remove();
if (opts.tools){
var p_tool = $('<span class="tabs-p-tool"></span>').insertAfter(tab.find('a.tabs-inner'));
if ($.isArray(opts.tools)){
for(var i=0; i<opts.tools.length; i++){
var t = $('<a href="javascript:void(0)"></a>').appendTo(p_tool);
t.addClass(opts.tools[i].iconCls);
if (opts.tools[i].handler){
t.bind('click', {handler:opts.tools[i].handler}, function(e){
if ($(this).parents('li').hasClass('tabs-disabled')){return;}
e.data.handler.call(this);
});
}
}
} else {
$(opts.tools).children().appendTo(p_tool);
}
var pr = p_tool.children().length * 12;
if (opts.closable) {
pr += 8;
} else {
pr -= 3;
p_tool.css('right','5px');
}
s_title.css('padding-right', pr+'px');
}
// setProperties(container);
// setScrollers(container);
setSize(container);
$.data(container, 'tabs').options.onUpdate.call(container, opts.title, getTabIndex(container, pp));
}
/**
* close a tab with specified index or title
*/
function closeTab(container, which) {
var opts = $.data(container, 'tabs').options;
var tabs = $.data(container, 'tabs').tabs;
var selectHis = $.data(container, 'tabs').selectHis;
if (!exists(container, which)) return;
var tab = getTab(container, which);
var title = tab.panel('options').title;
var index = getTabIndex(container, tab);
if (opts.onBeforeClose.call(container, title, index) == false) return;
var tab = getTab(container, which, true);
tab.panel('options').tab.remove();
tab.panel('destroy');
opts.onClose.call(container, title, index);
// setScrollers(container);
setSize(container);
// remove the select history item
for(var i=0; i<selectHis.length; i++){
if (selectHis[i] == title){
selectHis.splice(i, 1);
i --;
}
}
// select the nearest tab panel
var hisTitle = selectHis.pop();
if (hisTitle){
selectTab(container, hisTitle);
} else if (tabs.length){
selectTab(container, 0);
}
}
/**
* get the specified tab panel
*/
function getTab(container, which, removeit){
var tabs = $.data(container, 'tabs').tabs;
if (typeof which == 'number'){
if (which < 0 || which >= tabs.length){
return null;
} else {
var tab = tabs[which];
if (removeit) {
tabs.splice(which, 1);
}
return tab;
}
}
for(var i=0; i<tabs.length; i++){
var tab = tabs[i];
if (tab.panel('options').title == which){
if (removeit){
tabs.splice(i, 1);
}
return tab;
}
}
return null;
}
function getTabIndex(container, tab){
var tabs = $.data(container, 'tabs').tabs;
for(var i=0; i<tabs.length; i++){
if (tabs[i][0] == $(tab)[0]){
return i;
}
}
return -1;
}
function getSelectedTab(container){
var tabs = $.data(container, 'tabs').tabs;
for(var i=0; i<tabs.length; i++){
var tab = tabs[i];
if (tab.panel('options').closed == false){
return tab;
}
}
return null;
}
/**
* do first select action, if no tab is setted the first tab will be selected.
*/
function doFirstSelect(container){
var state = $.data(container, 'tabs')
var tabs = state.tabs;
for(var i=0; i<tabs.length; i++){
if (tabs[i].panel('options').selected){
selectTab(container, i);
return;
}
}
// if (tabs.length){
// selectTab(container, 0);
// }
selectTab(container, state.options.selected);
}
function selectTab(container, which){
var state = $.data(container, 'tabs');
var opts = state.options;
var tabs = state.tabs;
var selectHis = state.selectHis;
if (tabs.length == 0) {return;}
var panel = getTab(container, which); // get the panel to be activated
if (!panel){return}
var selected = getSelectedTab(container);
if (selected){
if (panel[0] == selected[0]){return}
unselectTab(container, getTabIndex(container, selected));
if (!selected.panel('options').closed){return}
}
panel.panel('open');
var title = panel.panel('options').title; // the panel title
selectHis.push(title); // push select history
var tab = panel.panel('options').tab; // get the tab object
tab.addClass('tabs-selected');
// scroll the tab to center position if required.
var wrap = $(container).find('>div.tabs-header>div.tabs-wrap');
var left = tab.position().left;
var right = left + tab.outerWidth();
if (left < 0 || right > wrap.width()){
var deltaX = left - (wrap.width()-tab.width()) / 2;
$(container).tabs('scrollBy', deltaX);
} else {
$(container).tabs('scrollBy', 0);
}
setSelectedSize(container);
opts.onSelect.call(container, title, getTabIndex(container, panel));
}
function unselectTab(container, which){
var state = $.data(container, 'tabs');
var p = getTab(container, which);
if (p){
var opts = p.panel('options');
if (!opts.closed){
p.panel('close');
if (opts.closed){
opts.tab.removeClass('tabs-selected');
state.options.onUnselect.call(container, opts.title, getTabIndex(container, p));
}
}
}
}
function exists(container, which){
return getTab(container, which) != null;
}
function showHeader(container, visible){
var opts = $.data(container, 'tabs').options;
opts.showHeader = visible;
$(container).tabs('resize');
}
$.fn.tabs = function(options, param){
if (typeof options == 'string') {
return $.fn.tabs.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'tabs');
var opts;
if (state) {
opts = $.extend(state.options, options);
state.options = opts;
} else {
$.data(this, 'tabs', {
options: $.extend({},$.fn.tabs.defaults, $.fn.tabs.parseOptions(this), options),
tabs: [],
selectHis: []
});
wrapTabs(this);
}
addTools(this);
setProperties(this);
setSize(this);
bindEvents(this);
doFirstSelect(this);
});
};
$.fn.tabs.methods = {
options: function(jq){
var cc = jq[0];
var opts = $.data(cc, 'tabs').options;
var s = getSelectedTab(cc);
opts.selected = s ? getTabIndex(cc, s) : -1;
return opts;
},
tabs: function(jq){
return $.data(jq[0], 'tabs').tabs;
},
resize: function(jq){
return jq.each(function(){
setSize(this);
setSelectedSize(this);
});
},
add: function(jq, options){
return jq.each(function(){
addTab(this, options);
});
},
close: function(jq, which){
return jq.each(function(){
closeTab(this, which);
});
},
getTab: function(jq, which){
return getTab(jq[0], which);
},
getTabIndex: function(jq, tab){
return getTabIndex(jq[0], tab);
},
getSelected: function(jq){
return getSelectedTab(jq[0]);
},
select: function(jq, which){
return jq.each(function(){
selectTab(this, which);
});
},
unselect: function(jq, which){
return jq.each(function(){
unselectTab(this, which);
});
},
exists: function(jq, which){
return exists(jq[0], which);
},
update: function(jq, options){
return jq.each(function(){
updateTab(this, options);
});
},
enableTab: function(jq, which){
return jq.each(function(){
$(this).tabs('getTab', which).panel('options').tab.removeClass('tabs-disabled');
});
},
disableTab: function(jq, which){
return jq.each(function(){
$(this).tabs('getTab', which).panel('options').tab.addClass('tabs-disabled');
});
},
showHeader: function(jq){
return jq.each(function(){
showHeader(this, true);
});
},
hideHeader: function(jq){
return jq.each(function(){
showHeader(this, false);
});
},
scrollBy: function(jq, deltaX){ // scroll the tab header by the specified amount of pixels
return jq.each(function(){
var opts = $(this).tabs('options');
var wrap = $(this).find('>div.tabs-header>div.tabs-wrap');
var pos = Math.min(wrap._scrollLeft() + deltaX, getMaxScrollWidth());
wrap.animate({scrollLeft: pos}, opts.scrollDuration);
function getMaxScrollWidth(){
var w = 0;
var ul = wrap.children('ul');
ul.children('li').each(function(){
w += $(this).outerWidth(true);
});
return w - wrap.width() + (ul.outerWidth() - ul.width());
}
});
}
};
$.fn.tabs.parseOptions = function(target){
return $.extend({}, $.parser.parseOptions(target, [
'width','height','tools','toolPosition','tabPosition',
{fit:'boolean',border:'boolean',plain:'boolean',headerWidth:'number',tabWidth:'number',tabHeight:'number',selected:'number',showHeader:'boolean'}
]));
};
$.fn.tabs.defaults = {
width: 'auto',
height: 'auto',
headerWidth: 150, // the tab header width, it is valid only when tabPosition set to 'left' or 'right'
tabWidth: 'auto', // the tab width
tabHeight: 27, // the tab height
selected: 0, // the initialized selected tab index
showHeader: true,
plain: false,
fit: false,
border: true,
tools: null,
toolPosition: 'right', // left,right
tabPosition: 'top', // possible values: top,bottom
scrollIncrement: 100,
scrollDuration: 400,
onLoad: function(panel){},
onSelect: function(title, index){},
onUnselect: function(title, index){},
onBeforeClose: function(title, index){},
onClose: function(title, index){},
onAdd: function(title, index){},
onUpdate: function(title, index){},
onContextMenu: function(e, title, index){}
};
})(jQuery);
| JavaScript |
/**
* window - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* panel
* draggable
* resizable
*
*/
(function($){
function setSize(target, param){
var opts = $.data(target, 'window').options;
if (param){
$.extend(opts, param);
// if (param.width) opts.width = param.width;
// if (param.height) opts.height = param.height;
// if (param.left != null) opts.left = param.left;
// if (param.top != null) opts.top = param.top;
}
$(target).panel('resize', opts);
}
function moveWindow(target, param){
var state = $.data(target, 'window');
if (param){
if (param.left != null) state.options.left = param.left;
if (param.top != null) state.options.top = param.top;
}
$(target).panel('move', state.options);
if (state.shadow){
state.shadow.css({
left: state.options.left,
top: state.options.top
});
}
}
/**
* center the window only horizontally
*/
function hcenter(target, tomove){
var state = $.data(target, 'window');
var opts = state.options;
var width = opts.width;
if (isNaN(width)){
width = state.window._outerWidth();
}
if (opts.inline){
var parent = state.window.parent();
opts.left = (parent.width() - width) / 2 + parent.scrollLeft();
} else {
opts.left = ($(window)._outerWidth() - width) / 2 + $(document).scrollLeft();
}
if (tomove){moveWindow(target);}
}
/**
* center the window only vertically
*/
function vcenter(target, tomove){
var state = $.data(target, 'window');
var opts = state.options;
var height = opts.height;
if (isNaN(height)){
height = state.window._outerHeight();
}
if (opts.inline){
var parent = state.window.parent();
opts.top = (parent.height() - height) / 2 + parent.scrollTop();
} else {
opts.top = ($(window)._outerHeight() - height) / 2 + $(document).scrollTop();
}
if (tomove){moveWindow(target);}
}
function create(target){
var state = $.data(target, 'window');
var win = $(target).panel($.extend({}, state.options, {
border: false,
doSize: true, // size the panel, the property undefined in window component
closed: true, // close the panel
cls: 'window',
headerCls: 'window-header',
bodyCls: 'window-body ' + (state.options.noheader ? 'window-body-noheader' : ''),
onBeforeDestroy: function(){
if (state.options.onBeforeDestroy.call(target) == false) return false;
if (state.shadow) state.shadow.remove();
if (state.mask) state.mask.remove();
},
onClose: function(){
if (state.shadow) state.shadow.hide();
if (state.mask) state.mask.hide();
state.options.onClose.call(target);
},
onOpen: function(){
if (state.mask){
state.mask.css({
display:'block',
zIndex: $.fn.window.defaults.zIndex++
});
}
if (state.shadow){
state.shadow.css({
display:'block',
zIndex: $.fn.window.defaults.zIndex++,
left: state.options.left,
top: state.options.top,
width: state.window._outerWidth(),
height: state.window._outerHeight()
});
}
state.window.css('z-index', $.fn.window.defaults.zIndex++);
state.options.onOpen.call(target);
},
onResize: function(width, height){
var opts = $(this).panel('options');
$.extend(state.options, {
width: opts.width,
height: opts.height,
left: opts.left,
top: opts.top
});
if (state.shadow){
state.shadow.css({
left: state.options.left,
top: state.options.top,
width: state.window._outerWidth(),
height: state.window._outerHeight()
});
}
state.options.onResize.call(target, width, height);
},
onMinimize: function(){
if (state.shadow) state.shadow.hide();
if (state.mask) state.mask.hide();
state.options.onMinimize.call(target);
},
onBeforeCollapse: function(){
if (state.options.onBeforeCollapse.call(target) == false) return false;
if (state.shadow) state.shadow.hide();
},
onExpand: function(){
if (state.shadow) state.shadow.show();
state.options.onExpand.call(target);
}
}));
state.window = win.panel('panel');
// create mask
if (state.mask) state.mask.remove();
if (state.options.modal == true){
state.mask = $('<div class="window-mask"></div>').insertAfter(state.window);
state.mask.css({
width: (state.options.inline ? state.mask.parent().width() : getPageArea().width),
height: (state.options.inline ? state.mask.parent().height() : getPageArea().height),
display: 'none'
});
}
// create shadow
if (state.shadow) state.shadow.remove();
if (state.options.shadow == true){
state.shadow = $('<div class="window-shadow"></div>').insertAfter(state.window);
state.shadow.css({
display: 'none'
});
}
// if require center the window
if (state.options.left == null){hcenter(target);}
if (state.options.top == null){vcenter(target);}
moveWindow(target);
if (state.options.closed == false){
win.window('open'); // open the window
}
}
/**
* set window drag and resize property
*/
function setProperties(target){
var state = $.data(target, 'window');
state.window.draggable({
handle: '>div.panel-header>div.panel-title',
disabled: state.options.draggable == false,
onStartDrag: function(e){
if (state.mask) state.mask.css('z-index', $.fn.window.defaults.zIndex++);
if (state.shadow) state.shadow.css('z-index', $.fn.window.defaults.zIndex++);
state.window.css('z-index', $.fn.window.defaults.zIndex++);
if (!state.proxy){
state.proxy = $('<div class="window-proxy"></div>').insertAfter(state.window);
}
state.proxy.css({
display:'none',
zIndex: $.fn.window.defaults.zIndex++,
left: e.data.left,
top: e.data.top
});
state.proxy._outerWidth(state.window._outerWidth());
state.proxy._outerHeight(state.window._outerHeight());
setTimeout(function(){
if (state.proxy) state.proxy.show();
}, 500);
},
onDrag: function(e){
state.proxy.css({
display:'block',
left: e.data.left,
top: e.data.top
});
return false;
},
onStopDrag: function(e){
state.options.left = e.data.left;
state.options.top = e.data.top;
$(target).window('move');
state.proxy.remove();
state.proxy = null;
}
});
state.window.resizable({
disabled: state.options.resizable == false,
onStartResize:function(e){
state.pmask = $('<div class="window-proxy-mask"></div>').insertAfter(state.window);
state.pmask.css({
zIndex: $.fn.window.defaults.zIndex++,
left: e.data.left,
top: e.data.top,
width: state.window._outerWidth(),
height: state.window._outerHeight()
});
if (!state.proxy){
state.proxy = $('<div class="window-proxy"></div>').insertAfter(state.window);
}
state.proxy.css({
zIndex: $.fn.window.defaults.zIndex++,
left: e.data.left,
top: e.data.top
});
state.proxy._outerWidth(e.data.width);
state.proxy._outerHeight(e.data.height);
},
onResize: function(e){
state.proxy.css({
left: e.data.left,
top: e.data.top
});
state.proxy._outerWidth(e.data.width);
state.proxy._outerHeight(e.data.height);
return false;
},
onStopResize: function(e){
$.extend(state.options, {
left: e.data.left,
top: e.data.top,
width: e.data.width,
height: e.data.height
});
setSize(target);
state.pmask.remove();
state.pmask = null;
state.proxy.remove();
state.proxy = null;
}
});
}
function getPageArea() {
if (document.compatMode == 'BackCompat') {
return {
width: Math.max(document.body.scrollWidth, document.body.clientWidth),
height: Math.max(document.body.scrollHeight, document.body.clientHeight)
}
} else {
return {
width: Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth),
height: Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight)
}
}
}
// when window resize, reset the width and height of the window's mask
$(window).resize(function(){
$('body>div.window-mask').css({
width: $(window)._outerWidth(),
height: $(window)._outerHeight()
});
setTimeout(function(){
$('body>div.window-mask').css({
width: getPageArea().width,
height: getPageArea().height
});
}, 50);
});
$.fn.window = function(options, param){
if (typeof options == 'string'){
var method = $.fn.window.methods[options];
if (method){
return method(this, param);
} else {
return this.panel(options, param);
}
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'window');
if (state){
$.extend(state.options, options);
} else {
state = $.data(this, 'window', {
options: $.extend({}, $.fn.window.defaults, $.fn.window.parseOptions(this), options)
});
if (!state.options.inline){
// $(this).appendTo('body');
document.body.appendChild(this);
}
}
create(this);
setProperties(this);
});
};
$.fn.window.methods = {
options: function(jq){
var popts = jq.panel('options');
var wopts = $.data(jq[0], 'window').options;
return $.extend(wopts, {
closed: popts.closed,
collapsed: popts.collapsed,
minimized: popts.minimized,
maximized: popts.maximized
});
},
window: function(jq){
return $.data(jq[0], 'window').window;
},
resize: function(jq, param){
return jq.each(function(){
setSize(this, param);
});
},
move: function(jq, param){
return jq.each(function(){
moveWindow(this, param);
});
},
hcenter: function(jq){
return jq.each(function(){
hcenter(this, true);
});
},
vcenter: function(jq){
return jq.each(function(){
vcenter(this, true);
});
},
center: function(jq){
return jq.each(function(){
hcenter(this);
vcenter(this);
moveWindow(this);
});
}
};
$.fn.window.parseOptions = function(target){
return $.extend({}, $.fn.panel.parseOptions(target), $.parser.parseOptions(target, [
{draggable:'boolean',resizable:'boolean',shadow:'boolean',modal:'boolean',inline:'boolean'}
]));
};
// Inherited from $.fn.panel.defaults
$.fn.window.defaults = $.extend({}, $.fn.panel.defaults, {
zIndex: 9000,
draggable: true,
resizable: true,
shadow: true,
modal: false,
inline: false, // true to stay inside its parent, false to go on top of all elements
// window's property which difference from panel
title: 'New Window',
collapsible: true,
minimizable: true,
maximizable: true,
closable: true,
closed: false
});
})(jQuery);
| JavaScript |
/**
* combobox - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* combo
*
*/
(function($){
function findRowBy(target, value, param, isGroup){
var state = $.data(target, 'combobox');
var opts = state.options;
if (isGroup){
return _findRow(state.groups, param, value);
} else {
return _findRow(state.data, (param ? param : state.options.valueField), value);
}
function _findRow(data,key,value){
for(var i=0; i<data.length; i++){
var row = data[i];
if (row[key] == value){return row}
}
return null;
}
}
/**
* scroll panel to display the specified item
*/
function scrollTo(target, value){
var panel = $(target).combo('panel');
var row = findRowBy(target, value);
if (row){
var item = $('#'+row.domId);
if (item.position().top <= 0){
var h = panel.scrollTop() + item.position().top;
panel.scrollTop(h);
} else if (item.position().top + item.outerHeight() > panel.height()){
var h = panel.scrollTop() + item.position().top + item.outerHeight() - panel.height();
panel.scrollTop(h);
}
}
}
function nav(target, dir){
var opts = $.data(target, 'combobox').options;
var panel = $(target).combobox('panel');
var item = panel.children('div.combobox-item-hover');
if (!item.length){
item = panel.children('div.combobox-item-selected');
}
item.removeClass('combobox-item-hover');
var firstSelector = 'div.combobox-item:visible:not(.combobox-item-disabled):first';
var lastSelector = 'div.combobox-item:visible:not(.combobox-item-disabled):last';
if (!item.length){
item = panel.children(dir=='next' ? firstSelector : lastSelector);
// item = panel.children('div.combobox-item:visible:' + (dir=='next'?'first':'last'));
} else {
if (dir == 'next'){
item = item.nextAll(firstSelector);
// item = item.nextAll('div.combobox-item:visible:first');
if (!item.length){
item = panel.children(firstSelector);
// item = panel.children('div.combobox-item:visible:first');
}
} else {
item = item.prevAll(firstSelector);
// item = item.prevAll('div.combobox-item:visible:first');
if (!item.length){
item = panel.children(lastSelector);
// item = panel.children('div.combobox-item:visible:last');
}
}
}
if (item.length){
item.addClass('combobox-item-hover');
var row = findRowBy(target, item.attr('id'), 'domId');
if (row){
scrollTo(target, row[opts.valueField]);
if (opts.selectOnNavigation){
select(target, row[opts.valueField]);
}
}
}
}
/**
* select the specified value
*/
function select(target, value){
var opts = $.data(target, 'combobox').options;
var values = $(target).combo('getValues');
if ($.inArray(value+'', values) == -1){
if (opts.multiple){
values.push(value);
} else {
values = [value];
}
setValues(target, values);
opts.onSelect.call(target, findRowBy(target, value));
}
}
/**
* unselect the specified value
*/
function unselect(target, value){
var opts = $.data(target, 'combobox').options;
var values = $(target).combo('getValues');
var index = $.inArray(value+'', values);
if (index >= 0){
values.splice(index, 1);
setValues(target, values);
opts.onUnselect.call(target, findRowBy(target, value));
}
}
/**
* set values
*/
function setValues(target, values, remainText){
var opts = $.data(target, 'combobox').options;
var panel = $(target).combo('panel');
panel.find('div.combobox-item-selected').removeClass('combobox-item-selected');
var vv = [], ss = [];
for(var i=0; i<values.length; i++){
var v = values[i];
var s = v;
var row = findRowBy(target, v);
if (row){
s = row[opts.textField];
$('#'+row.domId).addClass('combobox-item-selected');
}
vv.push(v);
ss.push(s);
}
$(target).combo('setValues', vv);
if (!remainText){
$(target).combo('setText', ss.join(opts.separator));
}
}
/**
* load data, the old list items will be removed.
*/
var itemIndex = 1;
function loadData(target, data, remainText){
var state = $.data(target, 'combobox');
var opts = state.options;
state.data = opts.loadFilter.call(target, data);
state.groups = [];
data = state.data;
var selected = $(target).combobox('getValues');
var dd = [];
var group = undefined;
for(var i=0; i<data.length; i++){
var row = data[i];
var v = row[opts.valueField]+'';
var s = row[opts.textField];
var g = row[opts.groupField];
if (g){
if (group != g){
group = g;
var grow = {value:g, domId:('_easyui_combobox_'+itemIndex++)};
state.groups.push(grow);
dd.push('<div id="' + grow.domId + '" class="combobox-group">');
dd.push(opts.groupFormatter ? opts.groupFormatter.call(target, g) : g);
dd.push('</div>');
}
} else {
group = undefined;
}
var cls = 'combobox-item' + (row.disabled ? ' combobox-item-disabled' : '') + (g ? ' combobox-gitem' : '');
row.domId = '_easyui_combobox_' + itemIndex++;
dd.push('<div id="' + row.domId + '" class="' + cls + '">');
dd.push(opts.formatter ? opts.formatter.call(target, row) : s);
dd.push('</div>');
// if (item['selected']){
// (function(){
// for(var i=0; i<selected.length; i++){
// if (v == selected[i]) return;
// }
// selected.push(v);
// })();
// }
if (row['selected'] && $.inArray(v, selected) == -1){
selected.push(v);
}
}
$(target).combo('panel').html(dd.join(''));
if (opts.multiple){
setValues(target, selected, remainText);
} else {
setValues(target, selected.length ? [selected[selected.length-1]] : [], remainText);
}
opts.onLoadSuccess.call(target, data);
}
/**
* request remote data if the url property is setted.
*/
function request(target, url, param, remainText){
var opts = $.data(target, 'combobox').options;
if (url){
opts.url = url;
}
// if (!opts.url) return;
param = param || {};
if (opts.onBeforeLoad.call(target, param) == false) return;
opts.loader.call(target, param, function(data){
loadData(target, data, remainText);
}, function(){
opts.onLoadError.apply(this, arguments);
});
}
/**
* do the query action
*/
function doQuery(target, q){
var state = $.data(target, 'combobox');
var opts = state.options;
if (opts.multiple && !q){
setValues(target, [], true);
} else {
setValues(target, [q], true);
}
if (opts.mode == 'remote'){
request(target, null, {q:q}, true);
} else {
var panel = $(target).combo('panel');
panel.find('div.combobox-item,div.combobox-group').hide();
var data = state.data;
var group = undefined;
for(var i=0; i<data.length; i++){
var row = data[i];
if (opts.filter.call(target, q, row)){
var v = row[opts.valueField];
var s = row[opts.textField];
var g = row[opts.groupField];
var item = $('#'+row.domId).show();
if (s.toLowerCase() == q.toLowerCase()){
// setValues(target, [v], true);
setValues(target, [v]);
item.addClass('combobox-item-selected');
}
if (opts.groupField && group != g){
var grow = findRowBy(target, g, 'value', true);
if (grow){
$('#'+grow.domId).show();
}
group = g;
}
}
}
}
}
function doEnter(target){
var t = $(target);
var opts = t.combobox('options');
var panel = t.combobox('panel');
var item = panel.children('div.combobox-item-hover');
if (!item.length){
item = panel.children('div.combobox-item-selected');
}
if (!item.length){return}
var row = findRowBy(target, item.attr('id'), 'domId');
if (!row){return}
var value = row[opts.valueField];
if (opts.multiple){
if (item.hasClass('combobox-item-selected')){
t.combobox('unselect', value);
} else {
t.combobox('select', value);
}
} else {
t.combobox('select', value);
t.combobox('hidePanel');
}
var vv = [];
var values = t.combobox('getValues');
for(var i=0; i<values.length; i++){
if (findRowBy(target, values[i])){
vv.push(values[i]);
}
}
t.combobox('setValues', vv);
}
/**
* create the component
*/
function create(target){
var opts = $.data(target, 'combobox').options;
$(target).addClass('combobox-f');
$(target).combo($.extend({}, opts, {
onShowPanel: function(){
$(target).combo('panel').find('div.combobox-item,div.combobox-group').show();
scrollTo(target, $(target).combobox('getValue'));
opts.onShowPanel.call(target);
}
}));
$(target).combo('panel').unbind().bind('mouseover', function(e){
$(this).children('div.combobox-item-hover').removeClass('combobox-item-hover');
var item = $(e.target).closest('div.combobox-item');
if (!item.hasClass('combobox-item-disabled')){
item.addClass('combobox-item-hover');
}
e.stopPropagation();
}).bind('mouseout', function(e){
$(e.target).closest('div.combobox-item').removeClass('combobox-item-hover');
e.stopPropagation();
}).bind('click', function(e){
var item = $(e.target).closest('div.combobox-item');
if (!item.length || item.hasClass('combobox-item-disabled')){return}
var row = findRowBy(target, item.attr('id'), 'domId');
if (!row){return}
var value = row[opts.valueField];
if (opts.multiple){
if (item.hasClass('combobox-item-selected')){
unselect(target, value);
} else {
select(target, value);
}
} else {
select(target, value);
$(target).combo('hidePanel');
}
e.stopPropagation();
});
}
$.fn.combobox = function(options, param){
if (typeof options == 'string'){
var method = $.fn.combobox.methods[options];
if (method){
return method(this, param);
} else {
return this.combo(options, param);
}
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'combobox');
if (state){
$.extend(state.options, options);
create(this);
} else {
state = $.data(this, 'combobox', {
options: $.extend({}, $.fn.combobox.defaults, $.fn.combobox.parseOptions(this), options),
data: []
});
create(this);
var data = $.fn.combobox.parseData(this);
if (data.length){
loadData(this, data);
}
}
if (state.options.data){
loadData(this, state.options.data);
}
request(this);
});
};
$.fn.combobox.methods = {
options: function(jq){
var copts = jq.combo('options');
return $.extend($.data(jq[0], 'combobox').options, {
originalValue: copts.originalValue,
disabled: copts.disabled,
readonly: copts.readonly
});
},
getData: function(jq){
return $.data(jq[0], 'combobox').data;
},
setValues: function(jq, values){
return jq.each(function(){
setValues(this, values);
});
},
setValue: function(jq, value){
return jq.each(function(){
setValues(this, [value]);
});
},
clear: function(jq){
return jq.each(function(){
$(this).combo('clear');
var panel = $(this).combo('panel');
panel.find('div.combobox-item-selected').removeClass('combobox-item-selected');
});
},
reset: function(jq){
return jq.each(function(){
var opts = $(this).combobox('options');
if (opts.multiple){
$(this).combobox('setValues', opts.originalValue);
} else {
$(this).combobox('setValue', opts.originalValue);
}
});
},
loadData: function(jq, data){
return jq.each(function(){
loadData(this, data);
});
},
reload: function(jq, url){
return jq.each(function(){
request(this, url);
});
},
select: function(jq, value){
return jq.each(function(){
select(this, value);
});
},
unselect: function(jq, value){
return jq.each(function(){
unselect(this, value);
});
}
};
$.fn.combobox.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.fn.combo.parseOptions(target), $.parser.parseOptions(target,[
'valueField','textField','groupField','mode','method','url'
]));
};
$.fn.combobox.parseData = function(target){
var data = [];
var opts = $(target).combobox('options');
$(target).children().each(function(){
if (this.tagName.toLowerCase() == 'optgroup'){
var group = $(this).attr('label');
$(this).children().each(function(){
_parseItem(this, group);
});
} else {
_parseItem(this);
}
});
return data;
function _parseItem(el, group){
var t = $(el);
var row = {};
row[opts.valueField] = t.attr('value')!=undefined ? t.attr('value') : t.html();
row[opts.textField] = t.html();
row['selected'] = t.is(':selected');
row['disabled'] = t.is(':disabled');
if (group){
opts.groupField = opts.groupField || 'group';
row[opts.groupField] = group;
}
data.push(row);
}
};
$.fn.combobox.defaults = $.extend({}, $.fn.combo.defaults, {
valueField: 'value',
textField: 'text',
groupField: null,
groupFormatter: function(group){return group;},
mode: 'local', // or 'remote'
method: 'post',
url: null,
data: null,
keyHandler: {
up: function(e){nav(this,'prev');e.preventDefault()},
down: function(e){nav(this,'next');e.preventDefault()},
left: function(e){},
right: function(e){},
enter: function(e){doEnter(this)},
query: function(q,e){doQuery(this, q)}
},
filter: function(q, row){
var opts = $(this).combobox('options');
return row[opts.textField].toLowerCase().indexOf(q.toLowerCase()) == 0;
},
formatter: function(row){
var opts = $(this).combobox('options');
return row[opts.textField];
},
loader: function(param, success, error){
var opts = $(this).combobox('options');
if (!opts.url) return false;
$.ajax({
type: opts.method,
url: opts.url,
data: param,
dataType: 'json',
success: function(data){
success(data);
},
error: function(){
error.apply(this, arguments);
}
});
},
loadFilter: function(data){
return data;
},
onBeforeLoad: function(param){},
onLoadSuccess: function(){},
onLoadError: function(){},
onSelect: function(record){},
onUnselect: function(record){}
});
})(jQuery);
| JavaScript |
/**
* draggable - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*/
(function($){
// var isDragging = false;
function drag(e){
var state = $.data(e.data.target, 'draggable');
var opts = state.options;
var proxy = state.proxy;
var dragData = e.data;
var left = dragData.startLeft + e.pageX - dragData.startX;
var top = dragData.startTop + e.pageY - dragData.startY;
if (proxy){
if (proxy.parent()[0] == document.body){
if (opts.deltaX != null && opts.deltaX != undefined){
left = e.pageX + opts.deltaX;
} else {
left = e.pageX - e.data.offsetWidth;
}
if (opts.deltaY != null && opts.deltaY != undefined){
top = e.pageY + opts.deltaY;
} else {
top = e.pageY - e.data.offsetHeight;
}
} else {
if (opts.deltaX != null && opts.deltaX != undefined){
left += e.data.offsetWidth + opts.deltaX;
}
if (opts.deltaY != null && opts.deltaY != undefined){
top += e.data.offsetHeight + opts.deltaY;
}
}
}
// if (opts.deltaX != null && opts.deltaX != undefined){
// left = e.pageX + opts.deltaX;
// }
// if (opts.deltaY != null && opts.deltaY != undefined){
// top = e.pageY + opts.deltaY;
// }
if (e.data.parent != document.body) {
left += $(e.data.parent).scrollLeft();
top += $(e.data.parent).scrollTop();
}
if (opts.axis == 'h') {
dragData.left = left;
} else if (opts.axis == 'v') {
dragData.top = top;
} else {
dragData.left = left;
dragData.top = top;
}
}
function applyDrag(e){
var state = $.data(e.data.target, 'draggable');
var opts = state.options;
var proxy = state.proxy;
if (!proxy){
proxy = $(e.data.target);
}
// if (proxy){
// proxy.css('cursor', opts.cursor);
// } else {
// proxy = $(e.data.target);
// $.data(e.data.target, 'draggable').handle.css('cursor', opts.cursor);
// }
proxy.css({
left:e.data.left,
top:e.data.top
});
$('body').css('cursor', opts.cursor);
}
function doDown(e){
// isDragging = true;
$.fn.draggable.isDragging = true;
var state = $.data(e.data.target, 'draggable');
var opts = state.options;
var droppables = $('.droppable').filter(function(){
return e.data.target != this;
}).filter(function(){
var accept = $.data(this, 'droppable').options.accept;
if (accept){
return $(accept).filter(function(){
return this == e.data.target;
}).length > 0;
} else {
return true;
}
});
state.droppables = droppables;
var proxy = state.proxy;
if (!proxy){
if (opts.proxy){
if (opts.proxy == 'clone'){
proxy = $(e.data.target).clone().insertAfter(e.data.target);
} else {
proxy = opts.proxy.call(e.data.target, e.data.target);
}
state.proxy = proxy;
} else {
proxy = $(e.data.target);
}
}
proxy.css('position', 'absolute');
drag(e);
applyDrag(e);
opts.onStartDrag.call(e.data.target, e);
return false;
}
function doMove(e){
var state = $.data(e.data.target, 'draggable');
drag(e);
if (state.options.onDrag.call(e.data.target, e) != false){
applyDrag(e);
}
var source = e.data.target;
state.droppables.each(function(){
var dropObj = $(this);
if (dropObj.droppable('options').disabled){return;}
var p2 = dropObj.offset();
if (e.pageX > p2.left && e.pageX < p2.left + dropObj.outerWidth()
&& e.pageY > p2.top && e.pageY < p2.top + dropObj.outerHeight()){
if (!this.entered){
$(this).trigger('_dragenter', [source]);
this.entered = true;
}
$(this).trigger('_dragover', [source]);
} else {
if (this.entered){
$(this).trigger('_dragleave', [source]);
this.entered = false;
}
}
});
return false;
}
function doUp(e){
// isDragging = false;
$.fn.draggable.isDragging = false;
// drag(e);
doMove(e);
var state = $.data(e.data.target, 'draggable');
var proxy = state.proxy;
var opts = state.options;
if (opts.revert){
if (checkDrop() == true){
$(e.data.target).css({
position:e.data.startPosition,
left:e.data.startLeft,
top:e.data.startTop
});
} else {
if (proxy){
var left, top;
if (proxy.parent()[0] == document.body){
left = e.data.startX - e.data.offsetWidth;
top = e.data.startY - e.data.offsetHeight;
} else {
left = e.data.startLeft;
top = e.data.startTop;
}
proxy.animate({
left: left,
top: top
}, function(){
removeProxy();
});
} else {
$(e.data.target).animate({
left:e.data.startLeft,
top:e.data.startTop
}, function(){
$(e.data.target).css('position', e.data.startPosition);
});
}
}
} else {
$(e.data.target).css({
position:'absolute',
left:e.data.left,
top:e.data.top
});
checkDrop();
}
opts.onStopDrag.call(e.data.target, e);
$(document).unbind('.draggable');
setTimeout(function(){
$('body').css('cursor','');
},100);
function removeProxy(){
if (proxy){
proxy.remove();
}
state.proxy = null;
}
function checkDrop(){
var dropped = false;
state.droppables.each(function(){
var dropObj = $(this);
if (dropObj.droppable('options').disabled){return;}
var p2 = dropObj.offset();
if (e.pageX > p2.left && e.pageX < p2.left + dropObj.outerWidth()
&& e.pageY > p2.top && e.pageY < p2.top + dropObj.outerHeight()){
if (opts.revert){
$(e.data.target).css({
position:e.data.startPosition,
left:e.data.startLeft,
top:e.data.startTop
});
}
$(this).trigger('_drop', [e.data.target]);
removeProxy();
dropped = true;
this.entered = false;
return false;
}
});
if (!dropped && !opts.revert){
removeProxy();
}
return dropped;
}
return false;
}
$.fn.draggable = function(options, param){
if (typeof options == 'string'){
return $.fn.draggable.methods[options](this, param);
}
return this.each(function(){
var opts;
var state = $.data(this, 'draggable');
if (state) {
state.handle.unbind('.draggable');
opts = $.extend(state.options, options);
} else {
opts = $.extend({}, $.fn.draggable.defaults, $.fn.draggable.parseOptions(this), options || {});
}
var handle = opts.handle ? (typeof opts.handle=='string' ? $(opts.handle, this) : opts.handle) : $(this);
$.data(this, 'draggable', {
options: opts,
handle: handle
});
if (opts.disabled) {
$(this).css('cursor', '');
return;
}
handle.unbind('.draggable').bind('mousemove.draggable', {target:this}, function(e){
// if (isDragging) return;
if ($.fn.draggable.isDragging){return}
var opts = $.data(e.data.target, 'draggable').options;
if (checkArea(e)){
$(this).css('cursor', opts.cursor);
} else {
$(this).css('cursor', '');
}
}).bind('mouseleave.draggable', {target:this}, function(e){
$(this).css('cursor', '');
}).bind('mousedown.draggable', {target:this}, function(e){
if (checkArea(e) == false) return;
$(this).css('cursor', '');
var position = $(e.data.target).position();
var offset = $(e.data.target).offset();
var data = {
startPosition: $(e.data.target).css('position'),
startLeft: position.left,
startTop: position.top,
left: position.left,
top: position.top,
startX: e.pageX,
startY: e.pageY,
offsetWidth: (e.pageX - offset.left),
offsetHeight: (e.pageY - offset.top),
target: e.data.target,
parent: $(e.data.target).parent()[0]
};
$.extend(e.data, data);
var opts = $.data(e.data.target, 'draggable').options;
if (opts.onBeforeDrag.call(e.data.target, e) == false) return;
$(document).bind('mousedown.draggable', e.data, doDown);
$(document).bind('mousemove.draggable', e.data, doMove);
$(document).bind('mouseup.draggable', e.data, doUp);
// $('body').css('cursor', opts.cursor);
});
// check if the handle can be dragged
function checkArea(e) {
var state = $.data(e.data.target, 'draggable');
var handle = state.handle;
var offset = $(handle).offset();
var width = $(handle).outerWidth();
var height = $(handle).outerHeight();
var t = e.pageY - offset.top;
var r = offset.left + width - e.pageX;
var b = offset.top + height - e.pageY;
var l = e.pageX - offset.left;
return Math.min(t,r,b,l) > state.options.edge;
}
});
};
$.fn.draggable.methods = {
options: function(jq){
return $.data(jq[0], 'draggable').options;
},
proxy: function(jq){
return $.data(jq[0], 'draggable').proxy;
},
enable: function(jq){
return jq.each(function(){
$(this).draggable({disabled:false});
});
},
disable: function(jq){
return jq.each(function(){
$(this).draggable({disabled:true});
});
}
};
$.fn.draggable.parseOptions = function(target){
var t = $(target);
return $.extend({},
$.parser.parseOptions(target, ['cursor','handle','axis',
{'revert':'boolean','deltaX':'number','deltaY':'number','edge':'number'}]), {
disabled: (t.attr('disabled') ? true : undefined)
});
};
$.fn.draggable.defaults = {
proxy:null, // 'clone' or a function that will create the proxy object,
// the function has the source parameter that indicate the source object dragged.
revert:false,
cursor:'move',
deltaX:null,
deltaY:null,
handle: null,
disabled: false,
edge:0,
axis:null, // v or h
onBeforeDrag: function(e){},
onStartDrag: function(e){},
onDrag: function(e){},
onStopDrag: function(e){}
};
$.fn.draggable.isDragging = false;
// $(function(){
// function touchHandler(e) {
// var touches = e.changedTouches, first = touches[0], type = "";
//
// switch(e.type) {
// case "touchstart": type = "mousedown"; break;
// case "touchmove": type = "mousemove"; break;
// case "touchend": type = "mouseup"; break;
// default: return;
// }
// var simulatedEvent = document.createEvent("MouseEvent");
// simulatedEvent.initMouseEvent(type, true, true, window, 1,
// first.screenX, first.screenY,
// first.clientX, first.clientY, false,
// false, false, false, 0/*left*/, null);
//
// first.target.dispatchEvent(simulatedEvent);
// if (isDragging){
// e.preventDefault();
// }
// }
//
// if (document.addEventListener){
// document.addEventListener("touchstart", touchHandler, true);
// document.addEventListener("touchmove", touchHandler, true);
// document.addEventListener("touchend", touchHandler, true);
// document.addEventListener("touchcancel", touchHandler, true);
// }
// });
})(jQuery);
| JavaScript |
/**
* linkbutton - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*/
(function($){
function createButton(target) {
var opts = $.data(target, 'linkbutton').options;
var t = $(target);
t.addClass('l-btn').removeClass('l-btn-plain l-btn-selected l-btn-plain-selected');
if (opts.plain){t.addClass('l-btn-plain')}
if (opts.selected){
t.addClass(opts.plain ? 'l-btn-selected l-btn-plain-selected' : 'l-btn-selected');
}
t.attr('group', opts.group || '');
t.attr('id', opts.id || '');
t.html(
'<span class="l-btn-left">' +
'<span class="l-btn-text"></span>' +
'</span>'
);
if (opts.text){
t.find('.l-btn-text').html(opts.text);
if (opts.iconCls){
t.find('.l-btn-text').addClass(opts.iconCls).addClass(opts.iconAlign=='left' ? 'l-btn-icon-left' : 'l-btn-icon-right');
}
} else {
t.find('.l-btn-text').html('<span class="l-btn-empty"> </span>');
if (opts.iconCls){
t.find('.l-btn-empty').addClass(opts.iconCls);
}
}
t.unbind('.linkbutton').bind('focus.linkbutton',function(){
if (!opts.disabled){
$(this).find('.l-btn-text').addClass('l-btn-focus');
}
}).bind('blur.linkbutton',function(){
$(this).find('.l-btn-text').removeClass('l-btn-focus');
});
if (opts.toggle && !opts.disabled){
t.bind('click.linkbutton', function(){
if (opts.selected){
$(this).linkbutton('unselect');
} else {
$(this).linkbutton('select');
}
});
}
setSelected(target, opts.selected)
setDisabled(target, opts.disabled);
}
function setSelected(target, selected){
var opts = $.data(target, 'linkbutton').options;
if (selected){
if (opts.group){
$('a.l-btn[group="'+opts.group+'"]').each(function(){
var o = $(this).linkbutton('options');
if (o.toggle){
$(this).removeClass('l-btn-selected l-btn-plain-selected');
o.selected = false;
}
});
}
$(target).addClass(opts.plain ? 'l-btn-selected l-btn-plain-selected' : 'l-btn-selected');
opts.selected = true;
} else {
if (!opts.group){
$(target).removeClass('l-btn-selected l-btn-plain-selected');
opts.selected = false;
}
}
}
function setDisabled(target, disabled){
var state = $.data(target, 'linkbutton');
var opts = state.options;
$(target).removeClass('l-btn-disabled l-btn-plain-disabled');
if (disabled){
opts.disabled = true;
var href = $(target).attr('href');
if (href){
state.href = href;
$(target).attr('href', 'javascript:void(0)');
}
if (target.onclick){
state.onclick = target.onclick;
target.onclick = null;
}
opts.plain ? $(target).addClass('l-btn-disabled l-btn-plain-disabled') : $(target).addClass('l-btn-disabled');
} else {
opts.disabled = false;
if (state.href) {
$(target).attr('href', state.href);
}
if (state.onclick) {
target.onclick = state.onclick;
}
}
}
$.fn.linkbutton = function(options, param){
if (typeof options == 'string'){
return $.fn.linkbutton.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'linkbutton');
if (state){
$.extend(state.options, options);
} else {
$.data(this, 'linkbutton', {
options: $.extend({}, $.fn.linkbutton.defaults, $.fn.linkbutton.parseOptions(this), options)
});
$(this).removeAttr('disabled');
}
createButton(this);
});
};
$.fn.linkbutton.methods = {
options: function(jq){
return $.data(jq[0], 'linkbutton').options;
},
enable: function(jq){
return jq.each(function(){
setDisabled(this, false);
});
},
disable: function(jq){
return jq.each(function(){
setDisabled(this, true);
});
},
select: function(jq){
return jq.each(function(){
setSelected(this, true);
});
},
unselect: function(jq){
return jq.each(function(){
setSelected(this, false);
});
}
};
$.fn.linkbutton.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.parser.parseOptions(target,
['id','iconCls','iconAlign','group',{plain:'boolean',toggle:'boolean',selected:'boolean'}]
), {
disabled: (t.attr('disabled') ? true : undefined),
text: $.trim(t.html()),
iconCls: (t.attr('icon') || t.attr('iconCls'))
});
};
$.fn.linkbutton.defaults = {
id: null,
disabled: false,
toggle: false,
selected: false,
group: null,
plain: false,
text: '',
iconCls: null,
iconAlign: 'left'
};
})(jQuery);
| JavaScript |
/**
* progressbar - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* none
*
*/
(function($){
function init(target){
$(target).addClass('progressbar');
$(target).html('<div class="progressbar-text"></div><div class="progressbar-value"><div class="progressbar-text"></div></div>');
return $(target);
}
function setSize(target,width){
var opts = $.data(target, 'progressbar').options;
var bar = $.data(target, 'progressbar').bar;
if (width) opts.width = width;
bar._outerWidth(opts.width)._outerHeight(opts.height);
bar.find('div.progressbar-text').width(bar.width());
bar.find('div.progressbar-text,div.progressbar-value').css({
height: bar.height()+'px',
lineHeight: bar.height()+'px'
});
}
$.fn.progressbar = function(options, param){
if (typeof options == 'string'){
var method = $.fn.progressbar.methods[options];
if (method){
return method(this, param);
}
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'progressbar');
if (state){
$.extend(state.options, options);
} else {
state = $.data(this, 'progressbar', {
options: $.extend({}, $.fn.progressbar.defaults, $.fn.progressbar.parseOptions(this), options),
bar: init(this)
});
}
$(this).progressbar('setValue', state.options.value);
setSize(this);
});
};
$.fn.progressbar.methods = {
options: function(jq){
return $.data(jq[0], 'progressbar').options;
},
resize: function(jq, width){
return jq.each(function(){
setSize(this, width);
});
},
getValue: function(jq){
return $.data(jq[0], 'progressbar').options.value;
},
setValue: function(jq, value){
if (value < 0) value = 0;
if (value > 100) value = 100;
return jq.each(function(){
var opts = $.data(this, 'progressbar').options;
var text = opts.text.replace(/{value}/, value);
var oldValue = opts.value;
opts.value = value;
$(this).find('div.progressbar-value').width(value+'%');
$(this).find('div.progressbar-text').html(text);
if (oldValue != value){
opts.onChange.call(this, value, oldValue);
}
});
}
};
$.fn.progressbar.parseOptions = function(target){
return $.extend({}, $.parser.parseOptions(target, ['width','height','text',{value:'number'}]));
};
$.fn.progressbar.defaults = {
width: 'auto',
height: 22,
value: 0, // percentage value
text: '{value}%',
onChange:function(newValue,oldValue){}
};
})(jQuery);
| JavaScript |
/**
* menu - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*/
(function($){
/**
* initialize the target menu, the function can be invoked only once
*/
function init(target){
$(target).appendTo('body');
$(target).addClass('menu-top'); // the top menu
$(document).unbind('.menu').bind('mousedown.menu', function(e){
var allMenu = $('body>div.menu:visible');
var m = $(e.target).closest('div.menu', allMenu);
if (m.length){return}
$('body>div.menu-top:visible').menu('hide');
});
var menus = splitMenu($(target));
for(var i=0; i<menus.length; i++){
createMenu(menus[i]);
}
function splitMenu(menu){
var menus = [];
menu.addClass('menu');
menus.push(menu);
if (!menu.hasClass('menu-content')){
menu.children('div').each(function(){
var submenu = $(this).children('div');
if (submenu.length){
submenu.insertAfter(target);
this.submenu = submenu; // point to the sub menu
var mm = splitMenu(submenu);
menus = menus.concat(mm);
}
});
}
return menus;
}
function createMenu(menu){
var width = $.parser.parseOptions(menu[0], ['width']).width;
if (menu.hasClass('menu-content')){
menu[0].originalWidth = width || menu._outerWidth();
} else {
menu[0].originalWidth = width || 0;
menu.children('div').each(function(){
var item = $(this);
var itemOpts = $.extend({}, $.parser.parseOptions(this,['name','iconCls','href',{separator:'boolean'}]), {
disabled: (item.attr('disabled') ? true : undefined)
});
if (itemOpts.separator){
item.addClass('menu-sep');
}
if (!item.hasClass('menu-sep')){
item[0].itemName = itemOpts.name || '';
item[0].itemHref = itemOpts.href || '';
var text = item.addClass('menu-item').html();
item.empty().append($('<div class="menu-text"></div>').html(text));
if (itemOpts.iconCls){
$('<div class="menu-icon"></div>').addClass(itemOpts.iconCls).appendTo(item);
}
if (itemOpts.disabled){
setDisabled(target, item[0], true);
}
if (item[0].submenu){
$('<div class="menu-rightarrow"></div>').appendTo(item); // has sub menu
}
bindMenuItemEvent(target, item);
}
});
$('<div class="menu-line"></div>').prependTo(menu);
}
setMenuWidth(target, menu);
menu.hide();
bindMenuEvent(target, menu);
}
}
function setMenuWidth(target, menu){
var opts = $.data(target, 'menu').options;
// var d = menu.css('display');
var style = menu.attr('style');
menu.css({
display: 'block',
left:-10000,
height: 'auto',
overflow: 'hidden'
});
// menu.find('div.menu-item')._outerHeight(22);
var width = 0;
menu.find('div.menu-text').each(function(){
if (width < $(this)._outerWidth()){
width = $(this)._outerWidth();
}
$(this).closest('div.menu-item')._outerHeight($(this)._outerHeight()+2);
});
width += 65;
menu._outerWidth(Math.max((menu[0].originalWidth || 0), width, opts.minWidth));
menu.children('div.menu-line')._outerHeight(menu.outerHeight());
// menu.css('display', d);
menu.attr('style', style);
}
/**
* bind menu event
*/
function bindMenuEvent(target, menu){
var state = $.data(target, 'menu');
menu.unbind('.menu').bind('mouseenter.menu', function(){
if (state.timer){
clearTimeout(state.timer);
state.timer = null;
}
}).bind('mouseleave.menu', function(){
if (state.options.hideOnUnhover){
state.timer = setTimeout(function(){
hideAll(target);
}, 100);
}
});
}
/**
* bind menu item event
*/
function bindMenuItemEvent(target, item){
if (!item.hasClass('menu-item')){return}
item.unbind('.menu');
item.bind('click.menu', function(){
if ($(this).hasClass('menu-item-disabled')){
return;
}
// only the sub menu clicked can hide all menus
if (!this.submenu){
hideAll(target);
var href = $(this).attr('href');
if (href){
location.href = href;
}
}
var item = $(target).menu('getItem', this);
$.data(target, 'menu').options.onClick.call(target, item);
}).bind('mouseenter.menu', function(e){
// hide other menu
item.siblings().each(function(){
if (this.submenu){
hideMenu(this.submenu);
}
$(this).removeClass('menu-active');
});
// show this menu
item.addClass('menu-active');
if ($(this).hasClass('menu-item-disabled')){
item.addClass('menu-active-disabled');
return;
}
var submenu = item[0].submenu;
if (submenu){
$(target).menu('show', {
menu: submenu,
parent: item
});
}
}).bind('mouseleave.menu', function(e){
item.removeClass('menu-active menu-active-disabled');
var submenu = item[0].submenu;
if (submenu){
if (e.pageX>=parseInt(submenu.css('left'))){
item.addClass('menu-active');
} else {
hideMenu(submenu);
}
} else {
item.removeClass('menu-active');
}
});
}
/**
* hide top menu and it's all sub menus
*/
function hideAll(target){
var state = $.data(target, 'menu');
if (state){
if ($(target).is(':visible')){
hideMenu($(target));
state.options.onHide.call(target);
}
}
return false;
}
/**
* show the menu, the 'param' object has one or more properties:
* left: the left position to display
* top: the top position to display
* menu: the menu to display, if not defined, the 'target menu' is used
* parent: the parent menu item to align to
* alignTo: the element object to align to
*/
function showMenu(target, param){
var left,top;
param = param || {};
var menu = $(param.menu || target);
if (menu.hasClass('menu-top')){
var opts = $.data(target, 'menu').options;
$.extend(opts, param);
left = opts.left;
top = opts.top;
if (opts.alignTo){
var at = $(opts.alignTo);
left = at.offset().left;
top = at.offset().top + at._outerHeight();
}
// if (param.left != undefined){left = param.left}
// if (param.top != undefined){top = param.top}
if (left + menu.outerWidth() > $(window)._outerWidth() + $(document)._scrollLeft()){
left = $(window)._outerWidth() + $(document).scrollLeft() - menu.outerWidth() - 5;
}
if (top + menu.outerHeight() > $(window)._outerHeight() + $(document).scrollTop()){
// top -= menu.outerHeight();
top = $(window)._outerHeight() + $(document).scrollTop() - menu.outerHeight() - 5;
}
} else {
var parent = param.parent; // the parent menu item
left = parent.offset().left + parent.outerWidth() - 2;
if (left + menu.outerWidth() + 5 > $(window)._outerWidth() + $(document).scrollLeft()){
left = parent.offset().left - menu.outerWidth() + 2;
}
var top = parent.offset().top - 3;
if (top + menu.outerHeight() > $(window)._outerHeight() + $(document).scrollTop()){
top = $(window)._outerHeight() + $(document).scrollTop() - menu.outerHeight() - 5;
}
}
menu.css({left:left,top:top});
menu.show(0, function(){
if (!menu[0].shadow){
menu[0].shadow = $('<div class="menu-shadow"></div>').insertAfter(menu);
}
menu[0].shadow.css({
display:'block',
zIndex:$.fn.menu.defaults.zIndex++,
left:menu.css('left'),
top:menu.css('top'),
width:menu.outerWidth(),
height:menu.outerHeight()
});
menu.css('z-index', $.fn.menu.defaults.zIndex++);
if (menu.hasClass('menu-top')){
$.data(menu[0], 'menu').options.onShow.call(menu[0]);
}
});
}
function hideMenu(menu){
if (!menu) return;
hideit(menu);
menu.find('div.menu-item').each(function(){
if (this.submenu){
hideMenu(this.submenu);
}
$(this).removeClass('menu-active');
});
function hideit(m){
m.stop(true,true);
if (m[0].shadow){
m[0].shadow.hide();
}
m.hide();
}
}
function findItem(target, text){
var result = null;
var tmp = $('<div></div>');
function find(menu){
menu.children('div.menu-item').each(function(){
var item = $(target).menu('getItem', this);
var s = tmp.empty().html(item.text).text();
if (text == $.trim(s)) {
result = item;
} else if (this.submenu && !result){
find(this.submenu);
}
});
}
find($(target));
tmp.remove();
return result;
}
function setDisabled(target, itemEl, disabled){
var t = $(itemEl);
if (!t.hasClass('menu-item')){return}
if (disabled){
t.addClass('menu-item-disabled');
if (itemEl.onclick){
itemEl.onclick1 = itemEl.onclick;
itemEl.onclick = null;
}
} else {
t.removeClass('menu-item-disabled');
if (itemEl.onclick1){
itemEl.onclick = itemEl.onclick1;
itemEl.onclick1 = null;
}
}
}
function appendItem(target, param){
var menu = $(target);
if (param.parent){
if (!param.parent.submenu){
var submenu = $('<div class="menu"><div class="menu-line"></div></div>').appendTo('body');
submenu.hide();
param.parent.submenu = submenu;
$('<div class="menu-rightarrow"></div>').appendTo(param.parent);
}
menu = param.parent.submenu;
}
if (param.separator){
var item = $('<div class="menu-sep"></div>').appendTo(menu);
} else {
var item = $('<div class="menu-item"></div>').appendTo(menu);
$('<div class="menu-text"></div>').html(param.text).appendTo(item);
}
if (param.iconCls) $('<div class="menu-icon"></div>').addClass(param.iconCls).appendTo(item);
if (param.id) item.attr('id', param.id);
if (param.name){item[0].itemName = param.name}
if (param.href){item[0].itemHref = param.href}
if (param.onclick){
if (typeof param.onclick == 'string'){
item.attr('onclick', param.onclick);
} else {
item[0].onclick = eval(param.onclick);
}
}
if (param.handler){item[0].onclick = eval(param.handler)}
if (param.disabled){setDisabled(target, item[0], true)}
bindMenuItemEvent(target, item);
bindMenuEvent(target, menu);
setMenuWidth(target, menu);
}
function removeItem(target, itemEl){
function removeit(el){
if (el.submenu){
el.submenu.children('div.menu-item').each(function(){
removeit(this);
});
var shadow = el.submenu[0].shadow;
if (shadow) shadow.remove();
el.submenu.remove();
}
$(el).remove();
}
removeit(itemEl);
}
function destroyMenu(target){
$(target).children('div.menu-item').each(function(){
removeItem(target, this);
});
if (target.shadow) target.shadow.remove();
$(target).remove();
}
$.fn.menu = function(options, param){
if (typeof options == 'string'){
return $.fn.menu.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'menu');
if (state){
$.extend(state.options, options);
} else {
state = $.data(this, 'menu', {
options: $.extend({}, $.fn.menu.defaults, $.fn.menu.parseOptions(this), options)
});
init(this);
}
$(this).css({
left: state.options.left,
top: state.options.top
});
});
};
$.fn.menu.methods = {
options: function(jq){
return $.data(jq[0], 'menu').options;
},
show: function(jq, pos){
return jq.each(function(){
showMenu(this, pos);
});
},
hide: function(jq){
return jq.each(function(){
hideAll(this);
});
},
destroy: function(jq){
return jq.each(function(){
destroyMenu(this);
});
},
/**
* set the menu item text
* param: {
* target: DOM object, indicate the menu item
* text: string, the new text
* }
*/
setText: function(jq, param){
return jq.each(function(){
$(param.target).children('div.menu-text').html(param.text);
});
},
/**
* set the menu icon class
* param: {
* target: DOM object, indicate the menu item
* iconCls: the menu item icon class
* }
*/
setIcon: function(jq, param){
return jq.each(function(){
var item = $(this).menu('getItem', param.target);
if (item.iconCls){
$(item.target).children('div.menu-icon').removeClass(item.iconCls).addClass(param.iconCls);
} else {
$('<div class="menu-icon"></div>').addClass(param.iconCls).appendTo(param.target);
}
});
},
/**
* get the menu item data that contains the following property:
* {
* target: DOM object, the menu item
* id: the menu id
* text: the menu item text
* iconCls: the icon class
* href: a remote address to redirect to
* onclick: a function to be called when the item is clicked
* }
*/
getItem: function(jq, itemEl){
var t = $(itemEl);
var item = {
target: itemEl,
id: t.attr('id'),
text: $.trim(t.children('div.menu-text').html()),
disabled: t.hasClass('menu-item-disabled'),
// href: t.attr('href'),
// name: t.attr('name'),
name: itemEl.itemName,
href: itemEl.itemHref,
onclick: itemEl.onclick
}
var icon = t.children('div.menu-icon');
if (icon.length){
var cc = [];
var aa = icon.attr('class').split(' ');
for(var i=0; i<aa.length; i++){
if (aa[i] != 'menu-icon'){
cc.push(aa[i]);
}
}
item.iconCls = cc.join(' ');
}
return item;
},
findItem: function(jq, text){
return findItem(jq[0], text);
},
/**
* append menu item, the param contains following properties:
* parent,id,text,iconCls,href,onclick
* when parent property is assigned, append menu item to it
*/
appendItem: function(jq, param){
return jq.each(function(){
appendItem(this, param);
});
},
removeItem: function(jq, itemEl){
return jq.each(function(){
removeItem(this, itemEl);
});
},
enableItem: function(jq, itemEl){
return jq.each(function(){
setDisabled(this, itemEl, false);
});
},
disableItem: function(jq, itemEl){
return jq.each(function(){
setDisabled(this, itemEl, true);
});
}
};
$.fn.menu.parseOptions = function(target){
return $.extend({}, $.parser.parseOptions(target, ['left','top',{minWidth:'number',hideOnUnhover:'boolean'}]));
};
$.fn.menu.defaults = {
zIndex:110000,
left: 0,
top: 0,
minWidth: 120,
hideOnUnhover: true, // Automatically hides the menu when mouse exits it
onShow: function(){},
onHide: function(){},
onClick: function(item){}
};
})(jQuery);
| JavaScript |
/**
* datebox - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* calendar
* combo
*
*/
(function($){
/**
* create date box
*/
function createBox(target){
var state = $.data(target, 'datebox');
var opts = state.options;
$(target).addClass('datebox-f').combo($.extend({}, opts, {
onShowPanel:function(){
setCalendar();
setValue(target, $(target).datebox('getText'));
opts.onShowPanel.call(target);
}
}));
$(target).combo('textbox').parent().addClass('datebox');
/**
* if the calendar isn't created, create it.
*/
if (!state.calendar){
createCalendar();
}
function createCalendar(){
var panel = $(target).combo('panel').css('overflow','hidden');
var cc = $('<div class="datebox-calendar-inner"></div>').appendTo(panel);
if (opts.sharedCalendar){
state.calendar = $(opts.sharedCalendar).appendTo(cc);
if (!state.calendar.hasClass('calendar')){
state.calendar.calendar();
}
} else {
state.calendar = $('<div></div>').appendTo(cc).calendar();
}
$.extend(state.calendar.calendar('options'), {
fit:true,
border:false,
onSelect:function(date){
var opts = $(this.target).datebox('options');
setValue(this.target, opts.formatter(date));
$(this.target).combo('hidePanel');
opts.onSelect.call(target, date);
}
});
setValue(target, opts.value);
var button = $('<div class="datebox-button"><table cellspacing="0" cellpadding="0" style="width:100%"><tr></tr></table></div>').appendTo(panel);
var tr = button.find('tr');
for(var i=0; i<opts.buttons.length; i++){
var td = $('<td></td>').appendTo(tr);
var btn = opts.buttons[i];
var t = $('<a href="javascript:void(0)"></a>').html($.isFunction(btn.text) ? btn.text(target) : btn.text).appendTo(td);
t.bind('click', {target: target, handler: btn.handler}, function(e){
e.data.handler.call(this, e.data.target);
});
}
tr.find('td').css('width', (100/opts.buttons.length)+'%');
}
function setCalendar(){
var panel = $(target).combo('panel');
var cc = panel.children('div.datebox-calendar-inner');
panel.children()._outerWidth(panel.width());
state.calendar.appendTo(cc);
state.calendar[0].target = target;
if (opts.panelHeight != 'auto'){
var height = panel.height();
panel.children().not(cc).each(function(){
height -= $(this).outerHeight();
});
cc._outerHeight(height);
}
state.calendar.calendar('resize');
}
}
/**
* called when user inputs some value in text box
*/
function doQuery(target, q){
setValue(target, q);
}
/**
* called when user press enter key
*/
function doEnter(target){
var state = $.data(target, 'datebox');
var opts = state.options;
var value = opts.formatter(state.calendar.calendar('options').current);
setValue(target, value);
$(target).combo('hidePanel');
}
function setValue(target, value){
var state = $.data(target, 'datebox');
var opts = state.options;
$(target).combo('setValue', value).combo('setText', value);
state.calendar.calendar('moveTo', opts.parser(value));
}
$.fn.datebox = function(options, param){
if (typeof options == 'string'){
var method = $.fn.datebox.methods[options];
if (method){
return method(this, param);
} else {
return this.combo(options, param);
}
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'datebox');
if (state){
$.extend(state.options, options);
} else {
$.data(this, 'datebox', {
options: $.extend({}, $.fn.datebox.defaults, $.fn.datebox.parseOptions(this), options)
});
}
createBox(this);
});
};
$.fn.datebox.methods = {
options: function(jq){
var copts = jq.combo('options');
return $.extend($.data(jq[0], 'datebox').options, {
originalValue: copts.originalValue,
disabled: copts.disabled,
readonly: copts.readonly
});
},
calendar: function(jq){ // get the calendar object
return $.data(jq[0], 'datebox').calendar;
},
setValue: function(jq, value){
return jq.each(function(){
setValue(this, value);
});
},
reset: function(jq){
return jq.each(function(){
var opts = $(this).datebox('options');
$(this).datebox('setValue', opts.originalValue);
});
}
};
$.fn.datebox.parseOptions = function(target){
return $.extend({}, $.fn.combo.parseOptions(target), $.parser.parseOptions(target, ['sharedCalendar']));
};
$.fn.datebox.defaults = $.extend({}, $.fn.combo.defaults, {
panelWidth:180,
panelHeight:'auto',
sharedCalendar:null,
keyHandler: {
up:function(e){},
down:function(e){},
left: function(e){},
right: function(e){},
enter:function(e){doEnter(this)},
query:function(q,e){doQuery(this, q)}
},
currentText:'Today',
closeText:'Close',
okText:'Ok',
buttons:[{
text: function(target){return $(target).datebox('options').currentText;},
handler: function(target){
$(target).datebox('calendar').calendar({
year:new Date().getFullYear(),
month:new Date().getMonth()+1,
current:new Date()
});
doEnter(target);
}
},{
text: function(target){return $(target).datebox('options').closeText;},
handler: function(target){
$(this).closest('div.combo-panel').panel('close');
}
}],
formatter:function(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return m+'/'+d+'/'+y;
},
parser:function(s){
var t = Date.parse(s);
if (!isNaN(t)){
return new Date(t);
} else {
return new Date();
}
},
onSelect:function(date){}
});
})(jQuery);
| JavaScript |
/**
* parser - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
*/
(function($){
$.parser = {
auto: true,
onComplete: function(context){},
plugins:['draggable','droppable','resizable','pagination','tooltip',
'linkbutton','menu','menubutton','splitbutton','progressbar',
'tree','combobox','combotree','combogrid','numberbox','validatebox','searchbox',
'numberspinner','timespinner','calendar','datebox','datetimebox','slider',
'layout','panel','datagrid','propertygrid','treegrid','tabs','accordion','window','dialog'
],
parse: function(context){
var aa = [];
for(var i=0; i<$.parser.plugins.length; i++){
var name = $.parser.plugins[i];
var r = $('.easyui-' + name, context);
if (r.length){
if (r[name]){
r[name]();
} else {
aa.push({name:name,jq:r});
}
}
}
if (aa.length && window.easyloader){
var names = [];
for(var i=0; i<aa.length; i++){
names.push(aa[i].name);
}
easyloader.load(names, function(){
for(var i=0; i<aa.length; i++){
var name = aa[i].name;
var jq = aa[i].jq;
jq[name]();
}
$.parser.onComplete.call($.parser, context);
});
} else {
$.parser.onComplete.call($.parser, context);
}
},
/**
* parse options, including standard 'data-options' attribute.
*
* calling examples:
* $.parser.parseOptions(target);
* $.parser.parseOptions(target, ['id','title','width',{fit:'boolean',border:'boolean'},{min:'number'}]);
*/
parseOptions: function(target, properties){
var t = $(target);
var options = {};
var s = $.trim(t.attr('data-options'));
if (s){
// var first = s.substring(0,1);
// var last = s.substring(s.length-1,1);
// if (first != '{') s = '{' + s;
// if (last != '}') s = s + '}';
if (s.substring(0, 1) != '{'){
s = '{' + s + '}';
}
options = (new Function('return ' + s))();
}
if (properties){
var opts = {};
for(var i=0; i<properties.length; i++){
var pp = properties[i];
if (typeof pp == 'string'){
if (pp == 'width' || pp == 'height' || pp == 'left' || pp == 'top'){
opts[pp] = parseInt(target.style[pp]) || undefined;
} else {
opts[pp] = t.attr(pp);
}
} else {
for(var name in pp){
var type = pp[name];
if (type == 'boolean'){
opts[name] = t.attr(name) ? (t.attr(name) == 'true') : undefined;
} else if (type == 'number'){
opts[name] = t.attr(name)=='0' ? 0 : parseFloat(t.attr(name)) || undefined;
}
}
}
}
$.extend(options, opts);
}
return options;
}
};
$(function(){
var d = $('<div style="position:absolute;top:-1000px;width:100px;height:100px;padding:5px"></div>').appendTo('body');
d.width(100);
$._boxModel = parseInt(d.width()) == 100;
d.remove();
if (!window.easyloader && $.parser.auto){
$.parser.parse();
}
});
/**
* extend plugin to set box model width
*/
$.fn._outerWidth = function(width){
if (width == undefined){
if (this[0] == window){
return this.width() || document.body.clientWidth;
}
return this.outerWidth()||0;
}
return this.each(function(){
if ($._boxModel){
$(this).width(width - ($(this).outerWidth() - $(this).width()));
} else {
$(this).width(width);
}
});
};
/**
* extend plugin to set box model height
*/
$.fn._outerHeight = function(height){
if (height == undefined){
if (this[0] == window){
return this.height() || document.body.clientHeight;
}
return this.outerHeight()||0;
}
return this.each(function(){
if ($._boxModel){
$(this).height(height - ($(this).outerHeight() - $(this).height()));
} else {
$(this).height(height);
}
});
};
$.fn._scrollLeft = function(left){
if (left == undefined){
return this.scrollLeft();
} else {
return this.each(function(){$(this).scrollLeft(left)});
}
}
$.fn._propAttr = $.fn.prop || $.fn.attr;
/**
* set or unset the fit property of parent container, return the width and height of parent container
*/
$.fn._fit = function(fit){
fit = fit == undefined ? true : fit;
var t = this[0];
var p = (t.tagName == 'BODY' ? t : this.parent()[0]);
var fcount = p.fcount || 0;
if (fit){
if (!t.fitted){
t.fitted = true;
p.fcount = fcount + 1;
$(p).addClass('panel-noscroll');
if (p.tagName == 'BODY'){
$('html').addClass('panel-fit');
}
}
} else {
if (t.fitted){
t.fitted = false;
p.fcount = fcount - 1;
if (p.fcount == 0){
$(p).removeClass('panel-noscroll');
if (p.tagName == 'BODY'){
$('html').removeClass('panel-fit');
}
}
}
}
return {
width: $(p).width(),
height: $(p).height()
}
}
})(jQuery);
/**
* support for mobile devices
*/
(function($){
var longTouchTimer = null;
var dblTouchTimer = null;
var isDblClick = false;
function onTouchStart(e){
if (e.touches.length != 1){return}
if (!isDblClick){
isDblClick = true;
dblClickTimer = setTimeout(function(){
isDblClick = false;
}, 500);
} else {
clearTimeout(dblClickTimer);
isDblClick = false;
fire(e, 'dblclick');
// e.preventDefault();
}
longTouchTimer = setTimeout(function(){
fire(e, 'contextmenu', 3);
}, 1000);
fire(e, 'mousedown');
if ($.fn.draggable.isDragging || $.fn.resizable.isResizing){
e.preventDefault();
}
}
function onTouchMove(e){
if (e.touches.length != 1){return}
if (longTouchTimer){
clearTimeout(longTouchTimer);
}
fire(e, 'mousemove');
if ($.fn.draggable.isDragging || $.fn.resizable.isResizing){
e.preventDefault();
}
}
function onTouchEnd(e){
// if (e.touches.length > 0){return}
if (longTouchTimer){
clearTimeout(longTouchTimer);
}
fire(e, 'mouseup');
if ($.fn.draggable.isDragging || $.fn.resizable.isResizing){
e.preventDefault();
}
}
function fire(e, name, which){
var event = new $.Event(name);
event.pageX = e.changedTouches[0].pageX;
event.pageY = e.changedTouches[0].pageY;
event.which = which || 1;
$(e.target).trigger(event);
}
if (document.addEventListener){
document.addEventListener("touchstart", onTouchStart, true);
document.addEventListener("touchmove", onTouchMove, true);
document.addEventListener("touchend", onTouchEnd, true);
}
})(jQuery);
| JavaScript |
/**
* propertygrid - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* datagrid
*
*/
(function($){
var currTarget;
function buildGrid(target){
var state = $.data(target, 'propertygrid');
var opts = $.data(target, 'propertygrid').options;
$(target).datagrid($.extend({}, opts, {
cls:'propertygrid',
view:(opts.showGroup ? opts.groupView : opts.view),
onClickRow:function(index, row){
if (currTarget != this){
// leaveCurrRow();
stopEditing(currTarget);
currTarget = this;
}
if (opts.editIndex != index && row.editor){
var col = $(this).datagrid('getColumnOption', "value");
col.editor = row.editor;
// leaveCurrRow();
stopEditing(currTarget);
$(this).datagrid('beginEdit', index);
$(this).datagrid('getEditors', index)[0].target.focus();
opts.editIndex = index;
}
opts.onClickRow.call(target, index, row);
},
loadFilter:function(data){
stopEditing(this);
return opts.loadFilter.call(this, data);
}
}));
$(document).unbind('.propertygrid').bind('mousedown.propertygrid', function(e){
var p = $(e.target).closest('div.datagrid-view,div.combo-panel');
// var p = $(e.target).closest('div.propertygrid,div.combo-panel');
if (p.length){return;}
stopEditing(currTarget);
currTarget = undefined;
});
// function leaveCurrRow(){
// var t = $(currTarget);
// if (!t.length){return;}
// var opts = $.data(currTarget, 'propertygrid').options;
// var index = opts.editIndex;
// if (index == undefined){return;}
// var ed = t.datagrid('getEditors', index)[0];
// if (ed){
// ed.target.blur();
// if (t.datagrid('validateRow', index)){
// t.datagrid('endEdit', index);
// } else {
// t.datagrid('cancelEdit', index);
// }
// }
// opts.editIndex = undefined;
// }
}
function stopEditing(target){
var t = $(target);
if (!t.length){return}
var opts = $.data(target, 'propertygrid').options;
var index = opts.editIndex;
if (index == undefined){return;}
var ed = t.datagrid('getEditors', index)[0];
if (ed){
ed.target.blur();
if (t.datagrid('validateRow', index)){
t.datagrid('endEdit', index);
} else {
t.datagrid('cancelEdit', index);
}
}
opts.editIndex = undefined;
}
$.fn.propertygrid = function(options, param){
if (typeof options == 'string'){
var method = $.fn.propertygrid.methods[options];
if (method){
return method(this, param);
} else {
return this.datagrid(options, param);
}
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'propertygrid');
if (state){
$.extend(state.options, options);
} else {
var opts = $.extend({}, $.fn.propertygrid.defaults, $.fn.propertygrid.parseOptions(this), options);
opts.frozenColumns = $.extend(true, [], opts.frozenColumns);
opts.columns = $.extend(true, [], opts.columns);
$.data(this, 'propertygrid', {
options: opts
});
}
buildGrid(this);
});
}
$.fn.propertygrid.methods = {
options: function(jq){
return $.data(jq[0], 'propertygrid').options;
}
};
$.fn.propertygrid.parseOptions = function(target){
return $.extend({}, $.fn.datagrid.parseOptions(target), $.parser.parseOptions(target,[{showGroup:'boolean'}]));
};
// the group view definition
var groupview = $.extend({}, $.fn.datagrid.defaults.view, {
render: function(target, container, frozen){
var table = [];
var groups = this.groups;
for(var i=0; i<groups.length; i++){
table.push(this.renderGroup.call(this, target, i, groups[i], frozen));
}
$(container).html(table.join(''));
},
renderGroup: function(target, groupIndex, group, frozen){
var state = $.data(target, 'datagrid');
var opts = state.options;
var fields = $(target).datagrid('getColumnFields', frozen);
var table = [];
table.push('<div class="datagrid-group" group-index=' + groupIndex + '>');
table.push('<table cellspacing="0" cellpadding="0" border="0" style="height:100%"><tbody>');
table.push('<tr>');
if ((frozen && (opts.rownumbers || opts.frozenColumns.length)) ||
(!frozen && !(opts.rownumbers || opts.frozenColumns.length))){
table.push('<td style="border:0;text-align:center;width:25px"><span class="datagrid-row-expander datagrid-row-collapse" style="display:inline-block;width:16px;height:16px;cursor:pointer"> </span></td>');
}
table.push('<td style="border:0;">');
if (!frozen){
table.push('<span class="datagrid-group-title">');
table.push(opts.groupFormatter.call(target, group.value, group.rows));
table.push('</span>');
}
table.push('</td>');
table.push('</tr>');
table.push('</tbody></table>');
table.push('</div>');
table.push('<table class="datagrid-btable" cellspacing="0" cellpadding="0" border="0"><tbody>');
var index = group.startIndex;
for(var j=0; j<group.rows.length; j++) {
var css = opts.rowStyler ? opts.rowStyler.call(target, index, group.rows[j]) : '';
var classValue = '';
var styleValue = '';
if (typeof css == 'string'){
styleValue = css;
} else if (css){
classValue = css['class'] || '';
styleValue = css['style'] || '';
}
var cls = 'class="datagrid-row ' + (index % 2 && opts.striped ? 'datagrid-row-alt ' : ' ') + classValue + '"';
var style = styleValue ? 'style="' + styleValue + '"' : '';
var rowId = state.rowIdPrefix + '-' + (frozen?1:2) + '-' + index;
table.push('<tr id="' + rowId + '" datagrid-row-index="' + index + '" ' + cls + ' ' + style + '>');
table.push(this.renderRow.call(this, target, fields, frozen, index, group.rows[j]));
table.push('</tr>');
index++;
}
table.push('</tbody></table>');
return table.join('');
},
bindEvents: function(target){
var state = $.data(target, 'datagrid');
var dc = state.dc;
var body = dc.body1.add(dc.body2);
var clickHandler = ($.data(body[0],'events')||$._data(body[0],'events')).click[0].handler;
body.unbind('click').bind('click', function(e){
var tt = $(e.target);
var expander = tt.closest('span.datagrid-row-expander');
if (expander.length){
var gindex = expander.closest('div.datagrid-group').attr('group-index');
if (expander.hasClass('datagrid-row-collapse')){
$(target).datagrid('collapseGroup', gindex);
} else {
$(target).datagrid('expandGroup', gindex);
}
} else {
clickHandler(e);
}
e.stopPropagation();
});
},
onBeforeRender: function(target, rows){
var state = $.data(target, 'datagrid');
var opts = state.options;
initCss();
var groups = [];
for(var i=0; i<rows.length; i++){
var row = rows[i];
var group = getGroup(row[opts.groupField]);
if (!group){
group = {
value: row[opts.groupField],
rows: [row]
};
groups.push(group);
} else {
group.rows.push(row);
}
}
var index = 0;
var newRows = [];
for(var i=0; i<groups.length; i++){
var group = groups[i];
group.startIndex = index;
index += group.rows.length;
newRows = newRows.concat(group.rows);
}
state.data.rows = newRows;
this.groups = groups;
var that = this;
setTimeout(function(){
that.bindEvents(target);
},0);
function getGroup(value){
for(var i=0; i<groups.length; i++){
var group = groups[i];
if (group.value == value){
return group;
}
}
return null;
}
function initCss(){
if (!$('#datagrid-group-style').length){
$('head').append(
'<style id="datagrid-group-style">' +
'.datagrid-group{height:25px;overflow:hidden;font-weight:bold;border-bottom:1px solid #ccc;}' +
'</style>'
);
}
}
}
});
$.extend($.fn.datagrid.methods, {
expandGroup:function(jq, groupIndex){
return jq.each(function(){
var view = $.data(this, 'datagrid').dc.view;
var group = view.find(groupIndex!=undefined ? 'div.datagrid-group[group-index="'+groupIndex+'"]' : 'div.datagrid-group');
var expander = group.find('span.datagrid-row-expander');
if (expander.hasClass('datagrid-row-expand')){
expander.removeClass('datagrid-row-expand').addClass('datagrid-row-collapse');
group.next('table').show();
}
$(this).datagrid('fixRowHeight');
});
},
collapseGroup:function(jq, groupIndex){
return jq.each(function(){
var view = $.data(this, 'datagrid').dc.view;
var group = view.find(groupIndex!=undefined ? 'div.datagrid-group[group-index="'+groupIndex+'"]' : 'div.datagrid-group');
var expander = group.find('span.datagrid-row-expander');
if (expander.hasClass('datagrid-row-collapse')){
expander.removeClass('datagrid-row-collapse').addClass('datagrid-row-expand');
group.next('table').hide();
}
$(this).datagrid('fixRowHeight');
});
}
});
// end of group view definition
$.fn.propertygrid.defaults = $.extend({}, $.fn.datagrid.defaults, {
singleSelect:true,
remoteSort:false,
fitColumns:true,
loadMsg:'',
frozenColumns:[[
{field:'f',width:16,resizable:false}
]],
columns:[[
{field:'name',title:'Name',width:100,sortable:true},
{field:'value',title:'Value',width:100,resizable:false}
]],
showGroup:false,
groupView:groupview,
groupField:'group',
groupFormatter:function(fvalue,rows){return fvalue}
});
})(jQuery);
| JavaScript |
/**
* form - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*/
(function($){
/**
* submit the form
*/
function ajaxSubmit(target, options){
options = options || {};
var param = {};
if (options.onSubmit){
if (options.onSubmit.call(target, param) == false) {
return;
}
}
var form = $(target);
if (options.url){
form.attr('action', options.url);
}
var frameId = 'easyui_frame_' + (new Date().getTime());
var frame = $('<iframe id='+frameId+' name='+frameId+'></iframe>')
.attr('src', window.ActiveXObject ? 'javascript:false' : 'about:blank')
.css({
position:'absolute',
top:-1000,
left:-1000
});
var t = form.attr('target'), a = form.attr('action');
form.attr('target', frameId);
var paramFields = $();
try {
frame.appendTo('body');
frame.bind('load', cb);
for(var n in param){
var f = $('<input type="hidden" name="' + n + '">').val(param[n]).appendTo(form);
paramFields = paramFields.add(f);
}
checkState();
form[0].submit();
} finally {
form.attr('action', a);
t ? form.attr('target', t) : form.removeAttr('target');
paramFields.remove();
}
function checkState(){
var f = $('#'+frameId);
if (!f.length){return}
try{
var s = f.contents()[0].readyState;
if (s && s.toLowerCase() == 'uninitialized'){
setTimeout(checkState, 100);
}
} catch(e){
cb();
}
}
var checkCount = 10;
function cb(){
var frame = $('#'+frameId);
if (!frame.length){return}
frame.unbind();
var data = '';
try{
var body = frame.contents().find('body');
data = body.html();
if (data == ''){
if (--checkCount){
setTimeout(cb, 100);
return;
}
// return;
}
var ta = body.find('>textarea');
if (ta.length){
data = ta.val();
} else {
var pre = body.find('>pre');
if (pre.length){
data = pre.html();
}
}
} catch(e){
}
if (options.success){
options.success(data);
}
setTimeout(function(){
frame.unbind();
frame.remove();
}, 100);
}
}
/**
* load form data
* if data is a URL string type load from remote site,
* otherwise load from local data object.
*/
function load(target, data){
if (!$.data(target, 'form')){
$.data(target, 'form', {
options: $.extend({}, $.fn.form.defaults)
});
}
var opts = $.data(target, 'form').options;
if (typeof data == 'string'){
var param = {};
if (opts.onBeforeLoad.call(target, param) == false) return;
$.ajax({
url: data,
data: param,
dataType: 'json',
success: function(data){
_load(data);
},
error: function(){
opts.onLoadError.apply(target, arguments);
}
});
} else {
_load(data);
}
function _load(data){
var form = $(target);
for(var name in data){
var val = data[name];
var rr = _checkField(name, val);
if (!rr.length){
// var f = form.find('input[numberboxName="'+name+'"]');
// if (f.length){
// f.numberbox('setValue', val); // set numberbox value
// } else {
// $('input[name="'+name+'"]', form).val(val);
// $('textarea[name="'+name+'"]', form).val(val);
// $('select[name="'+name+'"]', form).val(val);
// }
var count = _loadOther(name, val);
if (!count){
$('input[name="'+name+'"]', form).val(val);
$('textarea[name="'+name+'"]', form).val(val);
$('select[name="'+name+'"]', form).val(val);
}
}
_loadCombo(name, val);
}
opts.onLoadSuccess.call(target, data);
validate(target);
}
/**
* check the checkbox and radio fields
*/
function _checkField(name, val){
var rr = $(target).find('input[name="'+name+'"][type=radio], input[name="'+name+'"][type=checkbox]');
rr._propAttr('checked', false);
rr.each(function(){
var f = $(this);
if (f.val() == String(val) || $.inArray(f.val(), $.isArray(val)?val:[val]) >= 0){
f._propAttr('checked', true);
}
});
return rr;
}
function _loadOther(name, val){
var count = 0;
var pp = ['numberbox','slider'];
for(var i=0; i<pp.length; i++){
var p = pp[i];
var f = $(target).find('input['+p+'Name="'+name+'"]');
if (f.length){
f[p]('setValue', val);
count += f.length;
}
}
return count;
}
function _loadCombo(name, val){
var form = $(target);
var cc = ['combobox','combotree','combogrid','datetimebox','datebox','combo'];
var c = form.find('[comboName="' + name + '"]');
if (c.length){
for(var i=0; i<cc.length; i++){
var type = cc[i];
if (c.hasClass(type+'-f')){
if (c[type]('options').multiple){
c[type]('setValues', val);
} else {
c[type]('setValue', val);
}
return;
}
}
}
}
}
/**
* clear the form fields
*/
function clear(target){
$('input,select,textarea', target).each(function(){
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'hidden' || t == 'password' || tag == 'textarea'){
this.value = '';
} else if (t == 'file'){
var file = $(this);
file.after(file.clone().val(''));
file.remove();
} else if (t == 'checkbox' || t == 'radio'){
this.checked = false;
} else if (tag == 'select'){
this.selectedIndex = -1;
}
});
// if ($.fn.combo) $('.combo-f', target).combo('clear');
// if ($.fn.combobox) $('.combobox-f', target).combobox('clear');
// if ($.fn.combotree) $('.combotree-f', target).combotree('clear');
// if ($.fn.combogrid) $('.combogrid-f', target).combogrid('clear');
var t = $(target);
var plugins = ['combo','combobox','combotree','combogrid','slider'];
for(var i=0; i<plugins.length; i++){
var plugin = plugins[i];
var r = t.find('.'+plugin+'-f');
if (r.length && r[plugin]){
r[plugin]('clear');
}
}
validate(target);
}
function reset(target){
target.reset();
var t = $(target);
// if ($.fn.combo){t.find('.combo-f').combo('reset');}
// if ($.fn.combobox){t.find('.combobox-f').combobox('reset');}
// if ($.fn.combotree){t.find('.combotree-f').combotree('reset');}
// if ($.fn.combogrid){t.find('.combogrid-f').combogrid('reset');}
// if ($.fn.datebox){t.find('.datebox-f').datebox('reset');}
// if ($.fn.datetimebox){t.find('.datetimebox-f').datetimebox('reset');}
// if ($.fn.spinner){t.find('.spinner-f').spinner('reset');}
// if ($.fn.timespinner){t.find('.timespinner-f').timespinner('reset');}
// if ($.fn.numberbox){t.find('.numberbox-f').numberbox('reset');}
// if ($.fn.numberspinner){t.find('.numberspinner-f').numberspinner('reset');}
var plugins = ['combo','combobox','combotree','combogrid','datebox','datetimebox','spinner','timespinner','numberbox','numberspinner','slider'];
for(var i=0; i<plugins.length; i++){
var plugin = plugins[i];
var r = t.find('.'+plugin+'-f');
if (r.length && r[plugin]){
r[plugin]('reset');
}
}
validate(target);
}
/**
* set the form to make it can submit with ajax.
*/
function setForm(target){
var options = $.data(target, 'form').options;
var form = $(target);
form.unbind('.form').bind('submit.form', function(){
setTimeout(function(){
ajaxSubmit(target, options);
}, 0);
return false;
});
}
// function validate(target){
// if ($.fn.validatebox){
// var box = $('.validatebox-text', target);
// if (box.length){
// box.validatebox('validate');
//// box.trigger('focus');
//// box.trigger('blur');
// var invalidbox = $('.validatebox-invalid:first', target).focus();
// return invalidbox.length == 0;
// }
// }
// return true;
// }
function validate(target){
if ($.fn.validatebox){
var t = $(target);
t.find('.validatebox-text:not(:disabled)').validatebox('validate');
var invalidbox = t.find('.validatebox-invalid');
invalidbox.filter(':not(:disabled):first').focus();
return invalidbox.length == 0;
}
return true;
}
function setValidation(target, novalidate){
$(target).find('.validatebox-text:not(:disabled)').validatebox(novalidate ? 'disableValidation' : 'enableValidation');
}
$.fn.form = function(options, param){
if (typeof options == 'string'){
return $.fn.form.methods[options](this, param);
}
options = options || {};
return this.each(function(){
if (!$.data(this, 'form')){
$.data(this, 'form', {
options: $.extend({}, $.fn.form.defaults, options)
});
}
setForm(this);
});
};
$.fn.form.methods = {
submit: function(jq, options){
return jq.each(function(){
ajaxSubmit(this, $.extend({}, $.fn.form.defaults, options||{}));
});
},
load: function(jq, data){
return jq.each(function(){
load(this, data);
});
},
clear: function(jq){
return jq.each(function(){
clear(this);
});
},
reset: function(jq){
return jq.each(function(){
reset(this);
});
},
validate: function(jq){
return validate(jq[0]);
},
disableValidation: function(jq){
return jq.each(function(){
setValidation(this, true);
});
},
enableValidation: function(jq){
return jq.each(function(){
setValidation(this, false);
});
}
};
$.fn.form.defaults = {
url: null,
onSubmit: function(param){return $(this).form('validate');},
success: function(data){},
onBeforeLoad: function(param){},
onLoadSuccess: function(data){},
onLoadError: function(){}
};
})(jQuery);
| JavaScript |
/**
* resizable - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*/
(function($){
// var isResizing = false;
$.fn.resizable = function(options, param){
if (typeof options == 'string'){
return $.fn.resizable.methods[options](this, param);
}
function resize(e){
var resizeData = e.data;
var options = $.data(resizeData.target, 'resizable').options;
if (resizeData.dir.indexOf('e') != -1) {
var width = resizeData.startWidth + e.pageX - resizeData.startX;
width = Math.min(
Math.max(width, options.minWidth),
options.maxWidth
);
resizeData.width = width;
}
if (resizeData.dir.indexOf('s') != -1) {
var height = resizeData.startHeight + e.pageY - resizeData.startY;
height = Math.min(
Math.max(height, options.minHeight),
options.maxHeight
);
resizeData.height = height;
}
if (resizeData.dir.indexOf('w') != -1) {
var width = resizeData.startWidth - e.pageX + resizeData.startX;
width = Math.min(
Math.max(width, options.minWidth),
options.maxWidth
);
resizeData.width = width;
resizeData.left = resizeData.startLeft + resizeData.startWidth - resizeData.width;
// resizeData.width = resizeData.startWidth - e.pageX + resizeData.startX;
// if (resizeData.width >= options.minWidth && resizeData.width <= options.maxWidth) {
// resizeData.left = resizeData.startLeft + e.pageX - resizeData.startX;
// }
}
if (resizeData.dir.indexOf('n') != -1) {
var height = resizeData.startHeight - e.pageY + resizeData.startY;
height = Math.min(
Math.max(height, options.minHeight),
options.maxHeight
);
resizeData.height = height;
resizeData.top = resizeData.startTop + resizeData.startHeight - resizeData.height;
// resizeData.height = resizeData.startHeight - e.pageY + resizeData.startY;
// if (resizeData.height >= options.minHeight && resizeData.height <= options.maxHeight) {
// resizeData.top = resizeData.startTop + e.pageY - resizeData.startY;
// }
}
}
function applySize(e){
var resizeData = e.data;
var t = $(resizeData.target);
t.css({
left: resizeData.left,
top: resizeData.top
});
if (t.outerWidth() != resizeData.width){t._outerWidth(resizeData.width)}
if (t.outerHeight() != resizeData.height){t._outerHeight(resizeData.height)}
// t._outerWidth(resizeData.width)._outerHeight(resizeData.height);
}
function doDown(e){
// isResizing = true;
$.fn.resizable.isResizing = true;
$.data(e.data.target, 'resizable').options.onStartResize.call(e.data.target, e);
return false;
}
function doMove(e){
resize(e);
if ($.data(e.data.target, 'resizable').options.onResize.call(e.data.target, e) != false){
applySize(e)
}
return false;
}
function doUp(e){
// isResizing = false;
$.fn.resizable.isResizing = false;
resize(e, true);
applySize(e);
$.data(e.data.target, 'resizable').options.onStopResize.call(e.data.target, e);
$(document).unbind('.resizable');
$('body').css('cursor','');
// $('body').css('cursor','auto');
return false;
}
return this.each(function(){
var opts = null;
var state = $.data(this, 'resizable');
if (state) {
$(this).unbind('.resizable');
opts = $.extend(state.options, options || {});
} else {
opts = $.extend({}, $.fn.resizable.defaults, $.fn.resizable.parseOptions(this), options || {});
$.data(this, 'resizable', {
options:opts
});
}
if (opts.disabled == true) {
return;
}
// bind mouse event using namespace resizable
$(this).bind('mousemove.resizable', {target:this}, function(e){
// if (isResizing) return;
if ($.fn.resizable.isResizing){return}
var dir = getDirection(e);
if (dir == '') {
$(e.data.target).css('cursor', '');
} else {
$(e.data.target).css('cursor', dir + '-resize');
}
}).bind('mouseleave.resizable', {target:this}, function(e){
$(e.data.target).css('cursor', '');
}).bind('mousedown.resizable', {target:this}, function(e){
var dir = getDirection(e);
if (dir == '') return;
function getCssValue(css) {
var val = parseInt($(e.data.target).css(css));
if (isNaN(val)) {
return 0;
} else {
return val;
}
}
var data = {
target: e.data.target,
dir: dir,
startLeft: getCssValue('left'),
startTop: getCssValue('top'),
left: getCssValue('left'),
top: getCssValue('top'),
startX: e.pageX,
startY: e.pageY,
startWidth: $(e.data.target).outerWidth(),
startHeight: $(e.data.target).outerHeight(),
width: $(e.data.target).outerWidth(),
height: $(e.data.target).outerHeight(),
deltaWidth: $(e.data.target).outerWidth() - $(e.data.target).width(),
deltaHeight: $(e.data.target).outerHeight() - $(e.data.target).height()
};
$(document).bind('mousedown.resizable', data, doDown);
$(document).bind('mousemove.resizable', data, doMove);
$(document).bind('mouseup.resizable', data, doUp);
$('body').css('cursor', dir+'-resize');
});
// get the resize direction
function getDirection(e) {
var tt = $(e.data.target);
var dir = '';
var offset = tt.offset();
var width = tt.outerWidth();
var height = tt.outerHeight();
var edge = opts.edge;
if (e.pageY > offset.top && e.pageY < offset.top + edge) {
dir += 'n';
} else if (e.pageY < offset.top + height && e.pageY > offset.top + height - edge) {
dir += 's';
}
if (e.pageX > offset.left && e.pageX < offset.left + edge) {
dir += 'w';
} else if (e.pageX < offset.left + width && e.pageX > offset.left + width - edge) {
dir += 'e';
}
var handles = opts.handles.split(',');
for(var i=0; i<handles.length; i++) {
var handle = handles[i].replace(/(^\s*)|(\s*$)/g, '');
if (handle == 'all' || handle == dir) {
return dir;
}
}
return '';
}
});
};
$.fn.resizable.methods = {
options: function(jq){
return $.data(jq[0], 'resizable').options;
},
enable: function(jq){
return jq.each(function(){
$(this).resizable({disabled:false});
});
},
disable: function(jq){
return jq.each(function(){
$(this).resizable({disabled:true});
});
}
};
$.fn.resizable.parseOptions = function(target){
var t = $(target);
return $.extend({},
$.parser.parseOptions(target, [
'handles',{minWidth:'number',minHeight:'number',maxWidth:'number',maxHeight:'number',edge:'number'}
]), {
disabled: (t.attr('disabled') ? true : undefined)
})
};
$.fn.resizable.defaults = {
disabled:false,
handles:'n, e, s, w, ne, se, sw, nw, all',
minWidth: 10,
minHeight: 10,
maxWidth: 10000,//$(document).width(),
maxHeight: 10000,//$(document).height(),
edge:5,
onStartResize: function(e){},
onResize: function(e){},
onStopResize: function(e){}
};
$.fn.resizable.isResizing = false;
})(jQuery);
| JavaScript |
/**
* accordion - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* panel
*
*/
(function($){
function setSize(container){
var state = $.data(container, 'accordion');
var opts = state.options;
var panels = state.panels;
var cc = $(container);
opts.fit ? $.extend(opts, cc._fit()) : cc._fit(false);
if (!isNaN(opts.width)){
cc._outerWidth(opts.width);
} else {
cc.css('width', '');
}
var headerHeight = 0;
var bodyHeight = 'auto';
var headers = cc.find('>div.panel>div.accordion-header');
if (headers.length){
headerHeight = $(headers[0]).css('height', '')._outerHeight();
}
if (!isNaN(opts.height)){
cc._outerHeight(opts.height);
bodyHeight = cc.height() - headerHeight*headers.length;
} else {
cc.css('height', '');
}
_resize(true, bodyHeight - _resize(false) + 1);
function _resize(collapsible, height){
var totalHeight = 0;
for(var i=0; i<panels.length; i++){
var p = panels[i];
var h = p.panel('header')._outerHeight(headerHeight);
if (p.panel('options').collapsible == collapsible){
var pheight = isNaN(height) ? undefined : (height+headerHeight*h.length);
p.panel('resize', {
width: cc.width(),
height: (collapsible ? pheight : undefined)
});
totalHeight += p.panel('panel').outerHeight()-headerHeight;
}
}
return totalHeight;
}
}
/**
* find a panel by specified property, return the panel object or panel index.
*/
function findBy(container, property, value, all){
var panels = $.data(container, 'accordion').panels;
var pp = [];
for(var i=0; i<panels.length; i++){
var p = panels[i];
if (property){
if (p.panel('options')[property] == value){
pp.push(p);
}
} else {
if (p[0] == $(value)[0]){
return i;
}
}
}
if (property){
return all ? pp : (pp.length ? pp[0] : null);
} else {
return -1;
}
}
function getSelections(container){
return findBy(container, 'collapsed', false, true);
}
function getSelected(container){
var pp = getSelections(container);
return pp.length ? pp[0] : null;
}
/**
* get panel index, start with 0
*/
function getPanelIndex(container, panel){
return findBy(container, null, panel);
}
/**
* get the specified panel.
*/
function getPanel(container, which){
var panels = $.data(container, 'accordion').panels;
if (typeof which == 'number'){
if (which < 0 || which >= panels.length){
return null;
} else {
return panels[which];
}
}
return findBy(container, 'title', which);
}
function setProperties(container){
var opts = $.data(container, 'accordion').options;
var cc = $(container);
if (opts.border){
cc.removeClass('accordion-noborder');
} else {
cc.addClass('accordion-noborder');
}
}
function init(container){
var state = $.data(container, 'accordion');
var cc = $(container);
cc.addClass('accordion');
state.panels = [];
cc.children('div').each(function(){
var opts = $.extend({}, $.parser.parseOptions(this), {
selected: ($(this).attr('selected') ? true : undefined)
});
var pp = $(this);
state.panels.push(pp);
createPanel(container, pp, opts);
});
cc.bind('_resize', function(e,force){
var opts = $.data(container, 'accordion').options;
if (opts.fit == true || force){
setSize(container);
}
return false;
});
}
function createPanel(container, pp, options){
var opts = $.data(container, 'accordion').options;
pp.panel($.extend({}, {
collapsible: true,
minimizable: false,
maximizable: false,
closable: false,
doSize: false,
collapsed: true,
headerCls: 'accordion-header',
bodyCls: 'accordion-body'
}, options, {
onBeforeExpand: function(){
if (options.onBeforeExpand){
if (options.onBeforeExpand.call(this) == false){return false}
}
if (!opts.multiple){
// get all selected panel
var all = $.grep(getSelections(container), function(p){
return p.panel('options').collapsible;
});
for(var i=0; i<all.length; i++){
unselect(container, getPanelIndex(container, all[i]));
}
}
var header = $(this).panel('header');
header.addClass('accordion-header-selected');
header.find('.accordion-collapse').removeClass('accordion-expand');
},
onExpand: function(){
if (options.onExpand){options.onExpand.call(this)}
opts.onSelect.call(container, $(this).panel('options').title, getPanelIndex(container, this));
},
onBeforeCollapse: function(){
if (options.onBeforeCollapse){
if (options.onBeforeCollapse.call(this) == false){return false}
}
var header = $(this).panel('header');
header.removeClass('accordion-header-selected');
header.find('.accordion-collapse').addClass('accordion-expand');
},
onCollapse: function(){
if (options.onCollapse){options.onCollapse.call(this)}
opts.onUnselect.call(container, $(this).panel('options').title, getPanelIndex(container, this));
}
}));
var header = pp.panel('header');
var tool = header.children('div.panel-tool');
tool.children('a.panel-tool-collapse').hide(); // hide the old collapse button
var t = $('<a href="javascript:void(0)"></a>').addClass('accordion-collapse accordion-expand').appendTo(tool);
t.bind('click', function(){
var index = getPanelIndex(container, pp);
if (pp.panel('options').collapsed){
select(container, index);
} else {
unselect(container, index);
}
return false;
});
pp.panel('options').collapsible ? t.show() : t.hide();
header.click(function(){
$(this).find('a.accordion-collapse:visible').triggerHandler('click');
return false;
});
}
/**
* select and set the specified panel active
*/
function select(container, which){
var p = getPanel(container, which);
if (!p){return}
stopAnimate(container);
var opts = $.data(container, 'accordion').options;
p.panel('expand', opts.animate);
}
function unselect(container, which){
var p = getPanel(container, which);
if (!p){return}
stopAnimate(container);
var opts = $.data(container, 'accordion').options;
p.panel('collapse', opts.animate);
}
function doFirstSelect(container){
var opts = $.data(container, 'accordion').options;
var p = findBy(container, 'selected', true);
if (p){
_select(getPanelIndex(container, p));
} else {
_select(opts.selected);
}
function _select(index){
var animate = opts.animate;
opts.animate = false;
select(container, index);
opts.animate = animate;
}
}
/**
* stop the animation of all panels
*/
function stopAnimate(container){
var panels = $.data(container, 'accordion').panels;
for(var i=0; i<panels.length; i++){
panels[i].stop(true,true);
}
}
function add(container, options){
var state = $.data(container, 'accordion');
var opts = state.options;
var panels = state.panels;
if (options.selected == undefined) options.selected = true;
stopAnimate(container);
var pp = $('<div></div>').appendTo(container);
panels.push(pp);
createPanel(container, pp, options);
setSize(container);
opts.onAdd.call(container, options.title, panels.length-1);
if (options.selected){
select(container, panels.length-1);
}
}
function remove(container, which){
var state = $.data(container, 'accordion');
var opts = state.options;
var panels = state.panels;
stopAnimate(container);
var panel = getPanel(container, which);
var title = panel.panel('options').title;
var index = getPanelIndex(container, panel);
if (!panel){return}
if (opts.onBeforeRemove.call(container, title, index) == false){return}
panels.splice(index, 1);
panel.panel('destroy');
if (panels.length){
setSize(container);
var curr = getSelected(container);
if (!curr){
select(container, 0);
}
}
opts.onRemove.call(container, title, index);
}
$.fn.accordion = function(options, param){
if (typeof options == 'string'){
return $.fn.accordion.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'accordion');
if (state){
$.extend(state.options, options);
} else {
$.data(this, 'accordion', {
options: $.extend({}, $.fn.accordion.defaults, $.fn.accordion.parseOptions(this), options),
accordion: $(this).addClass('accordion'),
panels: []
});
init(this);
}
setProperties(this);
setSize(this);
doFirstSelect(this);
});
};
$.fn.accordion.methods = {
options: function(jq){
return $.data(jq[0], 'accordion').options;
},
panels: function(jq){
return $.data(jq[0], 'accordion').panels;
},
resize: function(jq){
return jq.each(function(){
setSize(this);
});
},
getSelections: function(jq){
return getSelections(jq[0]);
},
getSelected: function(jq){
return getSelected(jq[0]);
},
getPanel: function(jq, which){
return getPanel(jq[0], which);
},
getPanelIndex: function(jq, panel){
return getPanelIndex(jq[0], panel);
},
select: function(jq, which){
return jq.each(function(){
select(this, which);
});
},
unselect: function(jq, which){
return jq.each(function(){
unselect(this, which);
});
},
add: function(jq, options){
return jq.each(function(){
add(this, options);
});
},
remove: function(jq, which){
return jq.each(function(){
remove(this, which);
});
}
};
$.fn.accordion.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.parser.parseOptions(target, [
'width','height',
{fit:'boolean',border:'boolean',animate:'boolean',multiple:'boolean',selected:'number'}
]));
};
$.fn.accordion.defaults = {
width: 'auto',
height: 'auto',
fit: false,
border: true,
animate: true,
multiple: false,
selected: 0,
onSelect: function(title, index){},
onUnselect: function(title, index){},
onAdd: function(title, index){},
onBeforeRemove: function(title, index){},
onRemove: function(title, index){}
};
})(jQuery);
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'ページ';
$.fn.pagination.defaults.afterPageText = '{pages} 中';
$.fn.pagination.defaults.displayMsg = '全 {total} アイテム中 {from} から {to} を表示中';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = '処理中です。少々お待ちください...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'OK';
$.messager.defaults.cancel = 'キャンセル';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = '入力は必須です。';
$.fn.validatebox.defaults.rules.email.message = '正しいメールアドレスを入力してください。';
$.fn.validatebox.defaults.rules.url.message = '正しいURLを入力してください。';
$.fn.validatebox.defaults.rules.length.message = '{0} から {1} の範囲の正しい値を入力してください。';
$.fn.validatebox.defaults.rules.remote.message = 'このフィールドを修正してください。';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = '入力は必須です。';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = '入力は必須です。';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = '入力は必須です。';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = '入力は必須です。';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['日','月','火','水','木','金','土'];
$.fn.calendar.defaults.months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = '今日';
$.fn.datebox.defaults.closeText = '閉じる';
$.fn.datebox.defaults.okText = 'OK';
$.fn.datebox.defaults.missingMessage = '入力は必須です。';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Bladsy';
$.fn.pagination.defaults.afterPageText = 'Van {pages}';
$.fn.pagination.defaults.displayMsg = 'Wys (from) tot (to) van (total) items';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Verwerking, wag asseblief ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Die styl';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = "Die veld is verpligtend.";
$.fn.validatebox.defaults.rules.email.message = "Gee 'n geldige e-pos adres.";
$.fn.validatebox.defaults.rules.url.message = "Gee 'n geldige URL nie.";
$.fn.validatebox.defaults.rules.length.message = "Voer 'n waarde tussen {0} en {1}.";
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Die veld is verpligtend.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Die veld is verpligtend.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Die veld is verpligtend.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Die veld is verpligtend.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Vandag';
$.fn.datebox.defaults.closeText = 'Sluit';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Die veld is verpligtend.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Sayfa';
$.fn.pagination.defaults.afterPageText = ' / {pages}';
$.fn.pagination.defaults.displayMsg = '{from} ile {to} arası gösteriliyor, toplam {total} kayıt';
}
if ($.fn.datagrid){
$.fn.panel.defaults.loadingMessage = "Yükleniyor...";
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadingMessage = "Yükleniyor...";
$.fn.datagrid.defaults.loadMsg = 'İşleminiz Yapılıyor, lütfen bekleyin ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Tamam';
$.messager.defaults.cancel = 'İptal';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Bu alan zorunludur.';
$.fn.validatebox.defaults.rules.email.message = 'Lütfen geçerli bir email adresi giriniz.';
$.fn.validatebox.defaults.rules.url.message = 'Lütfen geçerli bir URL giriniz.';
$.fn.validatebox.defaults.rules.length.message = 'Lütfen {0} ile {1} arasında bir değer giriniz.';
$.fn.validatebox.defaults.rules.remote.message = 'Lütfen bu alanı düzeltiniz.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Bu alan zorunludur.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Bu alan zorunludur.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Bu alan zorunludur.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Bu alan zorunludur.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'];
$.fn.calendar.defaults.months = ['Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Bugün';
$.fn.datebox.defaults.closeText = 'Kapat';
$.fn.datebox.defaults.okText = 'Tamam';
$.fn.datebox.defaults.missingMessage = 'Bu alan zorunludur.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
$.fn.datebox.defaults.formatter=function(date){
var y=date.getFullYear();
var m=date.getMonth()+1;
var d=date.getDate();
if(m<10){m="0"+m;}
if(d<10){d="0"+d;}
return d+"."+m+"."+y;
};
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Seite';
$.fn.pagination.defaults.afterPageText = 'von {pages}';
$.fn.pagination.defaults.displayMsg = '{from} bis {to} von {total} Datensätzen';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Verarbeitung läuft, bitte warten ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'OK';
$.messager.defaults.cancel = 'Abbruch';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Dieses Feld wird benötigt.';
$.fn.validatebox.defaults.rules.email.message = 'Bitte geben Sie eine gültige E-Mail-Adresse ein.';
$.fn.validatebox.defaults.rules.url.message = 'Bitte geben Sie eine gültige URL ein.';
$.fn.validatebox.defaults.rules.length.message = 'Bitte geben Sie einen Wert zwischen {0} und {1} ein.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Dieses Feld wird benötigt.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Dieses Feld wird benötigt.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Dieses Feld wird benötigt.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Dieses Feld wird benötigt.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.firstDay = 1;
$.fn.calendar.defaults.weeks = ['S','M','D','M','D','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Heute';
$.fn.datebox.defaults.closeText = 'Schließen';
$.fn.datebox.defaults.okText = 'OK';
$.fn.datebox.defaults.missingMessage = 'Dieses Feld wird benötigt.';
$.fn.datebox.defaults.formatter = function(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return (d<10?('0'+d):d)+'.'+(m<10?('0'+m):m)+'.'+y;
};
$.fn.datebox.defaults.parser = function(s){
if (!s) return new Date();
var ss = s.split('.');
var m = parseInt(ss[1],10);
var d = parseInt(ss[0],10);
var y = parseInt(ss[2],10);
if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
return new Date(y,m-1,d);
} else {
return new Date();
}
};
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Pagina';
$.fn.pagination.defaults.afterPageText = 'di {pages}';
$.fn.pagination.defaults.displayMsg = 'Visualizzazione {from} a {to} di {total} elementi';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'In lavorazione, attendere ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Annulla';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Questo campo è richiesto.';
$.fn.validatebox.defaults.rules.email.message = 'Inserisci un indirizzo email valido.';
$.fn.validatebox.defaults.rules.url.message = 'Inserisci un URL valido.';
$.fn.validatebox.defaults.rules.length.message = 'Inserisci un valore tra {0} e {1}.';
$.fn.validatebox.defaults.rules.remote.message = 'Aggiusta questo campo.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Questo campo è richiesto.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Questo campo è richiesto.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Questo campo è richiesto.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Questo campo è richiesto.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Oggi';
$.fn.datebox.defaults.closeText = 'Chiudi';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Questo campo è richiesto.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'صفحة';
$.fn.pagination.defaults.afterPageText = 'من {pages}';
$.fn.pagination.defaults.displayMsg = 'عرض {from} إلى {to} من {total} عنصر';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'معالجة, الرجاء الإنتظار ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'موافق';
$.messager.defaults.cancel = 'إلغاء';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'هذا الحقل مطلوب.';
$.fn.validatebox.defaults.rules.email.message = 'الرجاء إدخال بريد إلكتروني صحيح.';
$.fn.validatebox.defaults.rules.url.message = 'الرجاء إدخال رابط صحيح.';
$.fn.validatebox.defaults.rules.length.message = 'الرجاء إدخال قيمة بين {0} و {1}.';
$.fn.validatebox.defaults.rules.remote.message = 'الرجاء التأكد من الحقل.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'هذا الحقل مطلوب.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'هذا الحقل مطلوب.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'هذا الحقل مطلوب.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'هذا الحقل مطلوب.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'اليوم';
$.fn.datebox.defaults.closeText = 'إغلاق';
$.fn.datebox.defaults.okText = 'موافق';
$.fn.datebox.defaults.missingMessage = 'هذا الحقل مطلوب.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Page';
$.fn.pagination.defaults.afterPageText = 'of {pages}';
$.fn.pagination.defaults.displayMsg = 'Displaying {from} to {to} of {total} items';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Processing, please wait ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Cancel';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'This field is required.';
$.fn.validatebox.defaults.rules.email.message = 'Please enter a valid email address.';
$.fn.validatebox.defaults.rules.url.message = 'Please enter a valid URL.';
$.fn.validatebox.defaults.rules.length.message = 'Please enter a value between {0} and {1}.';
$.fn.validatebox.defaults.rules.remote.message = 'Please fix this field.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'This field is required.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'This field is required.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'This field is required.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'This field is required.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Today';
$.fn.datebox.defaults.closeText = 'Close';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'This field is required.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Strana';
$.fn.pagination.defaults.afterPageText = 'z {pages}';
$.fn.pagination.defaults.displayMsg = 'Zobrazuji záznam {from} až {to} z {total}.';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Pracuji, čekejte prosím…';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Zrušit';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Toto pole je vyžadováno.';
$.fn.validatebox.defaults.rules.email.message = 'Zadejte, prosím, platnou e-mailovou adresu.';
$.fn.validatebox.defaults.rules.url.message = 'Zadejte, prosím, platnou adresu URL.';
$.fn.validatebox.defaults.rules.length.message = 'Zadejte, prosím, hodnotu mezi {0} a {1}.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['N','P','Ú','S','Č','P','S']; //neděle pondělí úterý středa čtvrtek pátek sobota
$.fn.calendar.defaults.months = ['led', 'únr', 'bře', 'dub', 'kvě', 'čvn', 'čvc', 'srp', 'zář', 'říj', 'lis', 'pro']; //leden únor březen duben květen červen červenec srpen září říjen listopad prosinec
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Dnes';
$.fn.datebox.defaults.closeText = 'Zavřít';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = '第';
$.fn.pagination.defaults.afterPageText = '共{pages}页';
$.fn.pagination.defaults.displayMsg = '显示{from}到{to},共{total}记录';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = '正在处理,请稍待。。。';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = '确定';
$.messager.defaults.cancel = '取消';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = '该输入项为必输项';
$.fn.validatebox.defaults.rules.email.message = '请输入有效的电子邮件地址';
$.fn.validatebox.defaults.rules.url.message = '请输入有效的URL地址';
$.fn.validatebox.defaults.rules.length.message = '输入内容长度必须介于{0}和{1}之间';
$.fn.validatebox.defaults.rules.remote.message = '请修正该字段';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = '该输入项为必输项';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = '该输入项为必输项';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = '该输入项为必输项';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = '该输入项为必输项';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['日','一','二','三','四','五','六'];
$.fn.calendar.defaults.months = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = '今天';
$.fn.datebox.defaults.closeText = '关闭';
$.fn.datebox.defaults.okText = '确定';
$.fn.datebox.defaults.missingMessage = '该输入项为必输项';
$.fn.datebox.defaults.formatter = function(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
};
$.fn.datebox.defaults.parser = function(s){
if (!s) return new Date();
var ss = s.split('-');
var y = parseInt(ss[0],10);
var m = parseInt(ss[1],10);
var d = parseInt(ss[2],10);
if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
return new Date(y,m-1,d);
} else {
return new Date();
}
};
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Page';
$.fn.pagination.defaults.afterPageText = 'de {pages}';
$.fn.pagination.defaults.displayMsg = 'Affichage de {from} et {to} au {total} des articles';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = "Traitement, s'il vous plaît patienter ...";
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Annuler';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Ce champ est obligatoire.';
$.fn.validatebox.defaults.rules.email.message = "S'il vous plaît entrer une adresse email valide.";
$.fn.validatebox.defaults.rules.url.message = "S'il vous plaît entrer une URL valide.";
$.fn.validatebox.defaults.rules.length.message = "S'il vous plaît entrez une valeur comprise entre {0} et {1}.";
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Ce champ est obligatoire.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Ce champ est obligatoire.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Ce champ est obligatoire.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Ce champ est obligatoire.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = "Aujourd'hui";
$.fn.datebox.defaults.closeText = 'Fermer';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Ce champ est obligatoire.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Страница';
$.fn.pagination.defaults.afterPageText = 'из {pages}';
$.fn.pagination.defaults.displayMsg = 'Просмотр {from} до {to} из {total} записей';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Обрабатывается, пожалуйста ждите ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ок';
$.messager.defaults.cancel = 'Закрыть';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Это поле необходимо.';
$.fn.validatebox.defaults.rules.email.message = 'Пожалуйста введите корректный e-mail адрес.';
$.fn.validatebox.defaults.rules.url.message = 'Пожалуйста введите корректный URL.';
$.fn.validatebox.defaults.rules.length.message = 'Пожалуйста введите зачение между {0} и {1}.';
$.fn.validatebox.defaults.rules.remote.message = 'Пожалуйста исправте это поле.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Это поле необходимо.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Это поле необходимо.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Это поле необходимо.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Это поле необходимо.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.firstDay = 1;
$.fn.calendar.defaults.weeks = ['В','П','В','С','Ч','П','С'];
$.fn.calendar.defaults.months = ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Сегодня';
$.fn.datebox.defaults.closeText = 'Закрыть';
$.fn.datebox.defaults.okText = 'Ок';
$.fn.datebox.defaults.missingMessage = 'Это поле необходимо.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Strana';
$.fn.pagination.defaults.afterPageText = 'z {pages}';
$.fn.pagination.defaults.displayMsg = 'Zobrazuji {from} do {to} z {total} položky';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Zpracování, čekejte prosím ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Zrušit';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Toto pole je vyžadováno.';
$.fn.validatebox.defaults.rules.email.message = 'Zadejte prosím platnou e-mailovou adresu.';
$.fn.validatebox.defaults.rules.url.message = 'Zadejte prosím platnou adresu URL.';
$.fn.validatebox.defaults.rules.length.message = 'Prosím, zadejte hodnotu mezi {0} a {1}.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Dnes';
$.fn.datebox.defaults.closeText = 'Zavřít';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Toto pole je vyžadováno.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Pagina';
$.fn.pagination.defaults.afterPageText = 'van {pages}';
$.fn.pagination.defaults.displayMsg = 'Tonen van {from} tot {to} van de {total} items';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Verwerking, even geduld ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Annuleren';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Dit veld is verplicht.';
$.fn.validatebox.defaults.rules.email.message = 'Geef een geldig e-mailadres.';
$.fn.validatebox.defaults.rules.url.message = 'Vul een geldige URL.';
$.fn.validatebox.defaults.rules.length.message = 'Voer een waarde tussen {0} en {1}.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Dit veld is verplicht.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Dit veld is verplicht.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Dit veld is verplicht.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Dit veld is verplicht.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Vandaag';
$.fn.datebox.defaults.closeText = 'Dicht';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Dit veld is verplicht.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Страница';
$.fn.pagination.defaults.afterPageText = 'от {pages}';
$.fn.pagination.defaults.displayMsg = 'Показани {from} за {to} от {total} продукти';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Обработка, моля изчакайте ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Добре';
$.messager.defaults.cancel = 'Задрасквам';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Това поле е задължително.';
$.fn.validatebox.defaults.rules.email.message = 'Моля, въведете валиден имейл адрес.';
$.fn.validatebox.defaults.rules.url.message = 'Моля въведете валиден URL.';
$.fn.validatebox.defaults.rules.length.message = 'Моля, въведете стойност между {0} и {1}.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Това поле е задължително.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Това поле е задължително.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Това поле е задължително.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Това поле е задължително.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Днес';
$.fn.datebox.defaults.closeText = 'Близо';
$.fn.datebox.defaults.okText = 'Добре';
$.fn.datebox.defaults.missingMessage = 'Това поле е задължително.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Página';
$.fn.pagination.defaults.afterPageText = 'de {pages}';
$.fn.pagination.defaults.displayMsg = 'Mostrando {from} a {to} de {total} itens';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Processando, aguarde ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Cancelar';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Esse campo é requerido.';
$.fn.validatebox.defaults.rules.email.message = 'Insira um endereço de email válido.';
$.fn.validatebox.defaults.rules.url.message = 'Insira uma URL válida.';
$.fn.validatebox.defaults.rules.length.message = 'Insira uma valor entre {0} e {1}.';
$.fn.validatebox.defaults.rules.remote.message = 'Corrija esse campo.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Esse campo é requerido.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Esse campo é requerido.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Esse campo é requerido.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Esse campo é requerido.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['D','S','T','Q','Q','S','S'];
$.fn.calendar.defaults.months = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Hoje';
$.fn.datebox.defaults.closeText = 'Fechar';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Esse campo é requerido.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Página';
$.fn.pagination.defaults.afterPageText = 'de {pages}';
$.fn.pagination.defaults.displayMsg = 'Mostrando {from} a {to} de {total} elementos';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Procesando, por favor espere ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Aceptar';
$.messager.defaults.cancel = 'Cancelar';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Este campo es obligatorio.';
$.fn.validatebox.defaults.rules.email.message = 'Por favor ingrese una dirección de correo válida.';
$.fn.validatebox.defaults.rules.url.message = 'Por favor ingrese una URL válida.';
$.fn.validatebox.defaults.rules.length.message = 'Por favor ingrese un valor entre {0} y {1}.';
$.fn.validatebox.defaults.rules.remote.message = 'Por favor corrija este campo.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Este campo es obligatorio.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Este campo es obligatorio.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Este campo es obligatorio.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Este campo es obligatorio.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['Do','Lu','Ma','Mi','Ju','Vi','Sá'];
$.fn.calendar.defaults.months = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Hoy';
$.fn.datebox.defaults.closeText = 'Cerrar';
$.fn.datebox.defaults.okText = 'Aceptar';
$.fn.datebox.defaults.missingMessage = 'Este campo es obligatorio.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Page';
$.fn.pagination.defaults.afterPageText = 'af {pages}';
$.fn.pagination.defaults.displayMsg = 'Viser {from} til {to} af {total} poster';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Behandling, vent venligst ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Annuller';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Dette felt er påkrævet.';
$.fn.validatebox.defaults.rules.email.message = 'Angiv en gyldig e-mail-adresse.';
$.fn.validatebox.defaults.rules.url.message = 'Angiv en gyldig webadresse.';
$.fn.validatebox.defaults.rules.length.message = 'Angiv en værdi mellem {0} og {1}.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Dette felt er påkrævet.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Dette felt er påkrævet.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Dette felt er påkrævet.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Dette felt er påkrævet.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'I dag';
$.fn.datebox.defaults.closeText = 'Luk';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Dette felt er påkrævet.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = '第';
$.fn.pagination.defaults.afterPageText = '共{pages}頁';
$.fn.pagination.defaults.displayMsg = '顯示{from}到{to},共{total}記錄';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = '正在處理,請稍待。。。';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = '確定';
$.messager.defaults.cancel = '取消';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = '該輸入項為必輸項';
$.fn.validatebox.defaults.rules.email.message = '請輸入有效的電子郵件地址';
$.fn.validatebox.defaults.rules.url.message = '請輸入有效的URL地址';
$.fn.validatebox.defaults.rules.length.message = '輸入內容長度必須介於{0}和{1}之間';
$.fn.validatebox.defaults.rules.remote.message = '請修正此欄位';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = '該輸入項為必輸項';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = '該輸入項為必輸項';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = '該輸入項為必輸項';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = '該輸入項為必輸項';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['日','一','二','三','四','五','六'];
$.fn.calendar.defaults.months = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = '今天';
$.fn.datebox.defaults.closeText = '關閉';
$.fn.datebox.defaults.okText = '確定';
$.fn.datebox.defaults.missingMessage = '該輸入項為必輸項';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Σελίδα';
$.fn.pagination.defaults.afterPageText = 'από {pages}';
$.fn.pagination.defaults.displayMsg = 'Εμφάνιση {from} εώς {to} από {total} αντικείμενα';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Γίνεται Επεξεργασία, Παρακαλώ Περιμένετε ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Εντάξει';
$.messager.defaults.cancel = 'Άκυρο';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Το πεδίο είναι υποχρεωτικό.';
$.fn.validatebox.defaults.rules.email.message = 'Παρακαλώ εισάγετε σωστή Ηλ.Διεύθυνση.';
$.fn.validatebox.defaults.rules.url.message = 'Παρακαλώ εισάγετε σωστό σύνδεσμο.';
$.fn.validatebox.defaults.rules.length.message = 'Παρακαλώ εισάγετε τιμή μεταξύ {0} και {1}.';
$.fn.validatebox.defaults.rules.remote.message = 'Παρακαλώ διορθώστε αυτό το πεδίο.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Το πεδίο είναι υποχρεωτικό.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Το πεδίο είναι υποχρεωτικό.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Το πεδίο είναι υποχρεωτικό.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Το πεδίο είναι υποχρεωτικό.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['Κυρ','Δευ','Τρι','Τετ','Πεμ','Παρ','Σαβ'];
$.fn.calendar.defaults.months = ['Ιαν', 'Φεβ', 'Μαρ', 'Απρ', 'Μαϊ', 'Ιου', 'Ιου', 'Αυγ', 'Σεπ', 'Οκτ', 'Νοε', 'Δεκ'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Σήμερα';
$.fn.datebox.defaults.closeText = 'Κλείσιμο';
$.fn.datebox.defaults.okText = 'Εντάξει';
$.fn.datebox.defaults.missingMessage = 'Το πεδίο είναι υποχρεωτικό.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination) {
$.fn.pagination.defaults.beforePageText = 'Sida';
$.fn.pagination.defaults.afterPageText = 'av {pages}';
$.fn.pagination.defaults.displayMsg = 'Visar {from} till {to} av {total} poster';
}
if ($.fn.datagrid) {
$.fn.datagrid.defaults.loadMsg = 'Bearbetar, vänligen vänta ...';
}
if ($.fn.treegrid && $.fn.datagrid) {
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager) {
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Avbryt';
}
if ($.fn.validatebox) {
$.fn.validatebox.defaults.missingMessage = 'Detta fält är obligatoriskt.';
$.fn.validatebox.defaults.rules.email.message = 'Vänligen ange en korrekt e-post adress.';
$.fn.validatebox.defaults.rules.url.message = 'Vänligen ange en korrekt URL.';
$.fn.validatebox.defaults.rules.length.message = 'Vänligen ange ett nummer mellan {0} och {1}.';
$.fn.validatebox.defaults.rules.remote.message = 'Vänligen åtgärda detta fält.';
}
if ($.fn.numberbox) {
$.fn.numberbox.defaults.missingMessage = 'Detta fält är obligatoriskt.';
}
if ($.fn.combobox) {
$.fn.combobox.defaults.missingMessage = 'Detta fält är obligatoriskt.';
}
if ($.fn.combotree) {
$.fn.combotree.defaults.missingMessage = 'Detta fält är obligatoriskt.';
}
if ($.fn.combogrid) {
$.fn.combogrid.defaults.missingMessage = 'Detta fält är obligatoriskt.';
}
if ($.fn.calendar) {
$.fn.calendar.defaults.weeks = ['Sön', 'Mån', 'Tis', 'Ons', 'Tors', 'Fre', 'Lör'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'];
}
if ($.fn.datebox) {
$.fn.datebox.defaults.currentText = 'I dag';
$.fn.datebox.defaults.closeText = 'Stäng';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Detta fält är obligatoriskt.';
}
if ($.fn.datetimebox && $.fn.datebox) {
$.extend($.fn.datetimebox.defaults, {
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Strona';
$.fn.pagination.defaults.afterPageText = 'z {pages}';
$.fn.pagination.defaults.displayMsg = 'Wyświetlono elementy od {from} do {to} z {total}';
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Przetwarzanie, proszę czekać ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Cancel';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'To pole jest wymagane.';
$.fn.validatebox.defaults.rules.email.message = 'Wprowadź poprawny adres email.';
$.fn.validatebox.defaults.rules.url.message = 'Wprowadź poprawny adres URL.';
$.fn.validatebox.defaults.rules.length.message = 'Wprowadź wartość z zakresu od {0} do {1}.';
$.fn.validatebox.defaults.rules.remote.message = 'Proszę poprawić to pole.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'To pole jest wymagane.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'To pole jest wymagane.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'To pole jest wymagane.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'To pole jest wymagane.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['N','P','W','Ś','C','P','S'];
$.fn.calendar.defaults.months = ['Sty', 'Lut', 'Mar', 'Kwi', 'Maj', 'Cze', 'Lip', 'Sie', 'Wrz', 'Paź', 'Lis', 'Gru'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Dzisiaj';
$.fn.datebox.defaults.closeText = 'Zamknij';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'To pole jest wymagane.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
if ($.fn.pagination){
$.fn.pagination.defaults.beforePageText = 'Pàgina';
$.fn.pagination.defaults.afterPageText = 'de {pages}';
$.fn.pagination.defaults.displayMsg = "Veient {from} a {to} de {total} d'articles";
}
if ($.fn.datagrid){
$.fn.datagrid.defaults.loadMsg = 'Elaboració, si us plau esperi ...';
}
if ($.fn.treegrid && $.fn.datagrid){
$.fn.treegrid.defaults.loadMsg = $.fn.datagrid.defaults.loadMsg;
}
if ($.messager){
$.messager.defaults.ok = 'Ok';
$.messager.defaults.cancel = 'Cancel';
}
if ($.fn.validatebox){
$.fn.validatebox.defaults.missingMessage = 'Aquest camp és obligatori.';
$.fn.validatebox.defaults.rules.email.message = 'Introduïu una adreça de correu electrònic vàlida.';
$.fn.validatebox.defaults.rules.url.message = 'Si us plau, introduïu un URL vàlida.';
$.fn.validatebox.defaults.rules.length.message = 'Si us plau, introduïu un valor entre {0} i {1}.';
}
if ($.fn.numberbox){
$.fn.numberbox.defaults.missingMessage = 'Aquest camp és obligatori.';
}
if ($.fn.combobox){
$.fn.combobox.defaults.missingMessage = 'Aquest camp és obligatori.';
}
if ($.fn.combotree){
$.fn.combotree.defaults.missingMessage = 'Aquest camp és obligatori.';
}
if ($.fn.combogrid){
$.fn.combogrid.defaults.missingMessage = 'Aquest camp és obligatori.';
}
if ($.fn.calendar){
$.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S'];
$.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
if ($.fn.datebox){
$.fn.datebox.defaults.currentText = 'Avui';
$.fn.datebox.defaults.closeText = 'Tancar';
$.fn.datebox.defaults.okText = 'Ok';
$.fn.datebox.defaults.missingMessage = 'Aquest camp és obligatori.';
}
if ($.fn.datetimebox && $.fn.datebox){
$.extend($.fn.datetimebox.defaults,{
currentText: $.fn.datebox.defaults.currentText,
closeText: $.fn.datebox.defaults.closeText,
okText: $.fn.datebox.defaults.okText,
missingMessage: $.fn.datebox.defaults.missingMessage
});
}
| JavaScript |
(function($) {
jQuery.fn.reverse = Array.prototype.reverse;
var
// auxiliar functions
aux = {
setup : function( $wrapper, $items, opts ) {
// set the wrappers position to relative
$wrapper.css('position', 'relative');
// save the items position
aux.saveInitialPosition( $items );
// set the items to absolute and assign top & left
$items.each(function(i) {
var $item = $(this);
$item.css({
position : 'absolute',
left : $item.data('left'),
top : $item.data('top')
});
});
// check how many items we have per row
var rowCount = Math.floor( $wrapper.width() / $items.width() ),
// number of items to show is rowCount * n rows
shown = rowCount * opts.rows,
// total number of rows
totalRows = Math.ceil( $items.length / rowCount );
// save this values for later
var config = {};
config.currentRow = 1;
config.totalRows = totalRows;
config.rowCount = rowCount;
config.shownItems = shown;
$wrapper.data('config', config);
// show n rowns
$wrapper.children(':gt(' + (shown - 1) + ')').hide();
// assign row classes to the items
$items.each(function(i) {
var $item = $(this),
row = Math.ceil( (i + 1) / rowCount );
$item.addClass('mix_row_' + row);
});
nav.setup( $wrapper, $items, opts );
},
saveInitialPosition : function( $items ) {
$items.each(function(i) {
var $item = $(this);
$item.data({
left : $item.position().left + 'px',
top : $item.position().top + 'px'
});
});
}
},
// navigation types
nav = {
setup : function( $wrapper, $items, opts ) {
nav[opts.type.mode].setup( $wrapper, $items, opts );
},
def : {
setup : function( $wrapper, $items, opts ) {
var config = $wrapper.data('config');
$items.each(function(i) {
var $item = $(this),
row = Math.ceil( (i + 1) / config.rowCount ),
t,
f = row % opts.rows;
if( f === 1 ) {
t = '0px';
} else if( f === 0 ) {
t = (opts.rows - 1) * $items.height() + 'px';
} else {
t = (f - 1) * $items.height() + 'px';
}
$item.css({ top : t });
});
},
pagination : function( $wrapper, dir, opts ) {
var config = $wrapper.data('config');
if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||
( dir === -1 && config.currentRow - opts.rows <= 0 )
) {
$wrapper.data( 'anim', false );
return false;
}
var currentRows = '', nextRows = '';
for( var i = 0; i < opts.rows; ++i ) {
currentRows += '.mix_row_' + (config.currentRow + i) + ',';
(dir === 1)
? nextRows += '.mix_row_' + (config.currentRow + opts.rows + i) + ','
: nextRows += '.mix_row_' + (config.currentRow - 1 - i) + ',';
}
$wrapper.children(currentRows).hide();
$wrapper.children(nextRows).show();
(dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
$wrapper.data( 'anim', false );
$wrapper.data('config', config);
}
},
fade : {
setup : function( $wrapper, $items, opts ) {
// same like def mode
nav['def'].setup( $wrapper, $items, opts );
},
pagination : function( $wrapper, dir, opts ) {
var config = $wrapper.data('config');
if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||
( dir === -1 && config.currentRow - opts.rows <= 0 )
) {
$wrapper.data( 'anim', false );
return false;
}
var currentRows = '', nextRows = '';
for( var i = 0; i < opts.rows; ++i ) {
currentRows += '.mix_row_' + (config.currentRow + i) + ',';
(dir === 1)
? nextRows += '.mix_row_' + (config.currentRow + opts.rows + i) + ','
: nextRows += '.mix_row_' + (config.currentRow - 1 - i) + ',';
}
$wrapper.children(currentRows).fadeOut( opts.type.speed, opts.type.easing );
var $nextRowElements= $wrapper.children(nextRows),
totalNextRows = $nextRowElements.length,
cnt = 0;
$nextRowElements.fadeIn( opts.type.speed, opts.type.easing, function() {
++cnt;
if( cnt === totalNextRows ) {
$wrapper.data( 'anim', false );
}
});
(dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
$wrapper.data('config', config);
}
},
seqfade : {
setup : function( $wrapper, $items, opts ) {
// same like def mode
nav['def'].setup( $wrapper, $items, opts );
},
pagination : function( $wrapper, dir, opts ) {
var config = $wrapper.data('config');
if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||
( dir === -1 && config.currentRow - opts.rows <= 0 )
) {
$wrapper.data( 'anim', false );
return false;
}
var currentRows = '', nextRows = '';
for( var i = 0; i < opts.rows; ++i ) {
currentRows += '.mix_row_' + (config.currentRow + i) + ',';
(dir === 1)
? nextRows += '.mix_row_' + (config.currentRow + opts.rows + i) + ','
: nextRows += '.mix_row_' + (config.currentRow - 1 - i) + ',';
}
var seq_t = opts.type.factor;
var $currentRowElements;
( dir === 1 )
? $currentRowElements = $wrapper.children(currentRows)
: $currentRowElements = $wrapper.children(currentRows).reverse();
$currentRowElements.each(function(i) {
var $el = $(this);
setTimeout(function() {
$el.fadeOut( opts.type.speed, opts.type.easing )
}, seq_t + i * seq_t);
});
var $nextRowElements;
( dir === 1 )
? $nextRowElements = $wrapper.children(nextRows)
: $nextRowElements = $wrapper.children(nextRows).reverse();
var total_elems = $nextRowElements.length,
cnt = 0;
$nextRowElements.each(function(i) {
var $el = $(this);
setTimeout(function() {
$el.fadeIn( opts.type.speed, opts.type.easing, function() {
++cnt;
if( cnt === total_elems ) {
$wrapper.data( 'anim', false );
}
})
}, (seq_t * 2) + i * seq_t);
});
(dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
$wrapper.data('config', config);
}
},
updown : {
setup : function( $wrapper, $items, opts ) {
var config = $wrapper.data('config');
$wrapper.children(':gt(' + (config.shownItems - 1) + ')').css('opacity', 0);
$items.each(function(i) {
var $item = $(this),
row = Math.ceil( (i + 1) / config.rowCount ),
t = $item.position().top,
f = row % opts.rows;
if( row > opts.rows ) {
t = (opts.rows * $items.height());
}
$item.css({ top : t + 'px'});
});
},
pagination : function( $wrapper, dir, opts ) {
var config = $wrapper.data('config');
if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||
( dir === -1 && config.currentRow - 1 <= 0 )
) {
$wrapper.data( 'anim', false );
return false;
}
var movingRows = '';
for( var i = 0; i <= opts.rows; ++i ) {
( dir === 1 )
? movingRows += '.mix_row_' + (config.currentRow + i) + ','
: movingRows += '.mix_row_' + (config.currentRow + (i - 1)) + ',';
}
var $elements;
( dir === 1 )
? $elements = $wrapper.children(movingRows)
: $elements = $wrapper.children(movingRows).reverse();
var total_elems = $elements.length,
cnt = 0;
$elements.each(function(i) {
var $el = $(this),
row = $el.attr('class'),
animParam = {},
currentRow = config.currentRow;
// if first row fade out
// if last row fade in
// for all the rows move them up / down
if( dir === 1 ) {
if( row === 'mix_row_' + (currentRow) ) {
animParam.opacity = 0;
}
else if( row === 'mix_row_' + (currentRow + opts.rows) ) {
animParam.opacity = 1;
}
}
else {
if( row === 'mix_row_' + (currentRow - 1) ) {
animParam.opacity = 1;
}
else if( row === 'mix_row_' + (currentRow + opts.rows - 1) ) {
animParam.opacity = 0;
}
}
$el.show();
(dir === 1)
? animParam.top = $el.position().top - $el.height() + 'px'
: animParam.top = $el.position().top + $el.height() + 'px'
$el.stop().animate(animParam, opts.type.speed, opts.type.easing, function() {
if( parseInt( animParam.top ) < 0 || parseInt( animParam.top ) > $el.height() * (opts.rows - 1) )
$el.hide();
++cnt;
if( cnt === total_elems ) {
$wrapper.data( 'anim', false );
}
});
});
(dir === 1) ? config.currentRow += 1 : config.currentRow -= 1;
$wrapper.data('config', config);
}
},
sequpdown : {
setup : function( $wrapper, $items, opts ) {
// same like updown mode
nav['updown'].setup( $wrapper, $items, opts );
},
pagination : function( $wrapper, dir, opts ) {
var config = $wrapper.data('config');
if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||
( dir === -1 && config.currentRow - 1 <= 0 )
) {
$wrapper.data( 'anim', false );
return false;
}
var movingRows = '';
for( var i = 0; i <= opts.rows; ++i ) {
( dir === 1 )
? movingRows += '.mix_row_' + (config.currentRow + i) + ','
: movingRows += '.mix_row_' + (config.currentRow + (i - 1)) + ',';
}
var seq_t = opts.type.factor,
$elements;
var dircond = 1;
if( opts.type.reverse ) dircond = -1;
( dir === dircond )
? $elements = $wrapper.children(movingRows)
: $elements = $wrapper.children(movingRows).reverse();
var total_elems = $elements.length,
cnt = 0;
$elements.each(function(i) {
var $el = $(this),
row = $el.attr('class'),
animParam = {},
currentRow = config.currentRow;
setTimeout(function() {
// if first row fade out
// if last row fade in
// for all the rows move them up / down
if( dir === 1 ) {
if( row === 'mix_row_' + (currentRow) ) {
animParam.opacity = 0;
}
else if( row === 'mix_row_' + (currentRow + opts.rows) ) {
animParam.opacity = 1;
}
}
else {
if( row === 'mix_row_' + (currentRow - 1) ) {
animParam.opacity = 1;
}
else if( row === 'mix_row_' + (currentRow + opts.rows - 1) ) {
animParam.opacity = 0;
}
}
$el.show();
(dir === 1)
? animParam.top = $el.position().top - $el.height() + 'px'
: animParam.top = $el.position().top + $el.height() + 'px'
$el.stop().animate(animParam, opts.type.speed, opts.type.easing, function() {
if( parseInt( animParam.top ) < 0 || parseInt( animParam.top ) > $el.height() * (opts.rows - 1) )
$el.hide();
++cnt;
if( cnt === total_elems ) {
$wrapper.data( 'anim', false );
}
});
}, seq_t + i * seq_t);
});
(dir === 1) ? config.currentRow += 1 : config.currentRow -= 1;
$wrapper.data('config', config);
}
},
showhide : {
setup : function( $wrapper, $items, opts ) {
var config = $wrapper.data('config');
$items.each(function(i) {
var $item = $(this),
row = Math.ceil( (i + 1) / config.rowCount ),
t,
f = row % opts.rows;
if( f === 1 ) {
t = '0px';
} else if( f === 0 ) {
t = (opts.rows - 1) * $items.height() + 'px';
} else {
t = (f - 1) * $items.height() + 'px';
}
$item.css({ top : t });
});
},
pagination : function( $wrapper, dir, opts ) {
var config = $wrapper.data('config');
if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||
( dir === -1 && config.currentRow - opts.rows <= 0 )
) {
$wrapper.data( 'anim', false );
return false;
}
var currentRows = '', nextRows = '';
for( var i = 0; i < opts.rows; ++i ) {
currentRows += '.mix_row_' + (config.currentRow + i) + ',';
(dir === 1)
? nextRows += '.mix_row_' + (config.currentRow + opts.rows + i) + ','
: nextRows += '.mix_row_' + (config.currentRow - 1 - i) + ',';
}
$wrapper.children(currentRows).hide( opts.type.speed, opts.type.easing );
var $nextRowElements= $wrapper.children(nextRows),
totalNextRows = $nextRowElements.length,
cnt = 0;
$nextRowElements.show( opts.type.speed, opts.type.easing, function() {
++cnt;
if( cnt === totalNextRows ) {
$wrapper.data( 'anim', false );
}
});
(dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
$wrapper.data('config', config);
}
},
disperse : {
setup : function( $wrapper, $items, opts ) {
var config = $wrapper.data('config');
$items.each(function(i) {
var $item = $(this),
row = Math.ceil( (i + 1) / config.rowCount ),
t,
f = row % opts.rows;
if( f === 1 ) {
t = '0px';
} else if( f === 0 ) {
t = (opts.rows - 1) * $items.height() + 'px';
} else {
t = (f - 1) * $items.height() + 'px';
}
$item.css({ top : t }).data('top', t);
});
},
pagination : function( $wrapper, dir, opts ) {
var config = $wrapper.data('config');
if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||
( dir === -1 && config.currentRow - opts.rows <= 0 )
) {
$wrapper.data( 'anim', false );
return false;
}
var currentRows = '', nextRows = '';
for( var i = 0; i < opts.rows; ++i ) {
currentRows += '.mix_row_' + (config.currentRow + i) + ',';
(dir === 1)
? nextRows += '.mix_row_' + (config.currentRow + opts.rows + i) + ','
: nextRows += '.mix_row_' + (config.currentRow - 1 - i) + ',';
}
$wrapper.children(currentRows).each(function(i) {
var $el = $(this);
$el.stop().animate({
left : $el.position().left + Math.floor( Math.random() * 101 ) - 50 + 'px',
top : $el.position().top + Math.floor( Math.random() * 101 ) - 50 + 'px',
opacity : 0
}, opts.type.speed, opts.type.easing, function() {
$el.css({
left : $el.data('left'),
top : $el.data('top')
}).hide();
});
});
var $nextRowElements = $wrapper.children(nextRows);
total_elems = $nextRowElements.length,
cnt = 0;
$nextRowElements.each(function(i) {
var $el = $(this);
$el.css({
left : parseInt($el.data('left')) + Math.floor( Math.random() * 301 ) - 150 + 'px',
top : parseInt($el.data('top')) + Math.floor( Math.random() * 301 ) - 150 + 'px',
opacity : 0
})
.show()
.animate({
left : $el.data('left'),
top : $el.data('top'),
opacity : 1
}, opts.type.speed, opts.type.easing, function() {
++cnt;
if( cnt === total_elems ) {
$wrapper.data( 'anim', false );
}
});
});
(dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
$wrapper.data('config', config);
}
},
rows : {
setup : function( $wrapper, $items, opts ) {
// same like def mode
nav['def'].setup( $wrapper, $items, opts );
},
pagination : function( $wrapper, dir, opts ) {
var config = $wrapper.data('config');
if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||
( dir === -1 && config.currentRow - opts.rows <= 0 )
) {
$wrapper.data( 'anim', false );
return false;
}
var currentRows = '', nextRows = '';
for( var i = 0; i < opts.rows; ++i ) {
currentRows += '.mix_row_' + (config.currentRow + i) + ',';
(dir === 1)
? nextRows += '.mix_row_' + (config.currentRow + opts.rows + i) + ','
: nextRows += '.mix_row_' + (config.currentRow - 1 - i) + ',';
}
$wrapper.children(currentRows).each(function(i) {
var $el = $(this),
rownmb = $el.attr('class').match(/mix_row_(\d+)/)[1],
diff;
if( rownmb%2 === 0 ) {
diff = opts.type.factor;
}
else {
diff = -opts.type.factor;
}
$el.stop().animate({
left : $el.position().left + diff + 'px',
opacity : 0
}, opts.type.speed, opts.type.easing, function() {
$el.css({
left : $el.data('left')
}).hide();
});
});
var $nextRowElements = $wrapper.children(nextRows);
total_elems = $nextRowElements.length,
cnt = 0;
$nextRowElements.each(function(i) {
var $el = $(this),
rownmb = $el.attr('class').match(/mix_row_(\d+)/)[1],
diff;
if( rownmb%2 === 0 ) {
diff = opts.type.factor;
}
else {
diff = -opts.type.factor;
}
$el.css({
left : parseInt($el.data('left')) + diff + 'px',
opacity : 0
})
.show()
.animate({
left : $el.data('left'),
opacity : 1
}, opts.type.speed, opts.type.easing, function() {
++cnt;
if( cnt === total_elems ) {
$wrapper.data( 'anim', false );
}
});
});
(dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
$wrapper.data('config', config);
}
}
},
methods = {
init : function( options ) {
if( this.length ) {
var settings = {
rows : 2,
navL : '#mix_prev',
navR : '#mix_next',
type : {
mode : 'def', // use def | fade | seqfade | updown | sequpdown | showhide | disperse | rows
speed : 500, // for fade, seqfade, updown, sequpdown, showhide, disperse, rows
easing : 'jswing', // for fade, seqfade, updown, sequpdown, showhide, disperse, rows
factor : 50, // for seqfade, sequpdown, rows
reverse : false // for sequpdown
}
};
return this.each(function() {
// if options exist, lets merge them with our default settings
if ( options ) {
$.extend( settings, options );
}
var $el = $(this).css( 'visibility', 'hidden' ),
// the ul
$wrapper = $el.find('ul.mix_gallery'),
// the items
$thumbs = $wrapper.children('li'),
total = $thumbs.length,
// the navigation elements
$p_nav = $(settings.navL),
$n_nav = $(settings.navR);
// save current row for later (first visible row)
//config.currentRow = 1;
// flag to control animation progress
$wrapper.data( 'anim', false );
// preload thumbs
var loaded = 0;
$thumbs.find('img').each( function(i) {
var $img = $(this);
$('<img/>').load( function() {
++loaded;
if( loaded === total ) {
// setup
aux.setup( $wrapper, $thumbs, settings );
$el.css( 'visibility', 'visible' );
// navigation events
if( $p_nav.length ) {
$p_nav.bind('click.gridnav', function( e ) {
if( $wrapper.data( 'anim' ) ) return false;
$wrapper.data( 'anim', true );
nav[settings.type.mode].pagination( $wrapper, -1, settings );
return false;
});
}
if( $n_nav.length ) {
$n_nav.bind('click.gridnav', function( e ) {
if( $wrapper.data( 'anim' ) ) return false;
$wrapper.data( 'anim', true );
nav[settings.type.mode].pagination( $wrapper, 1, settings );
return false;
});
}
/*
adds events to the mouse
*/
$el.bind('mousewheel.gridnav', function(e, delta) {
if(delta > 0) {
if( $wrapper.data( 'anim' ) ) return false;
$wrapper.data( 'anim', true );
nav[settings.type.mode].pagination( $wrapper, -1, settings );
}
else {
if( $wrapper.data( 'anim' ) ) return false;
$wrapper.data( 'anim', true );
nav[settings.type.mode].pagination( $wrapper, 1, settings );
}
return false;
});
}
}).attr( 'src', $img.attr('src') );
});
});
}
}
};
$.fn.gridnav = 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.gridnav' );
}
};
})(jQuery);
| JavaScript |
var mainNav = function() {
var main = {
obj_nav : $(arguments[0]) || $("nav"),
settings : {
show_delay : 0,
hide_delay : 0,
_ie6 : /MSIE 6.+Win/.test(navigator.userAgent),
_ie7 : /MSIE 7.+Win/.test(navigator.userAgent)
},
init : function(obj, level) {
obj.lists = obj.childElements();
obj.lists.each(function(el,ind){
main.handlNavElement(el);
if((main.settings._ie6 || main.settings._ie7) && level){
main.ieFixZIndex(el, ind, obj.lists.size());
}
});
if(main.settings._ie6 && !level){
document.execCommand("BackgroundImageCache", false, true);
}
},
handlNavElement : function(list) {
if(list !== undefined){
list.onmouseover = function(){
main.fireNavEvent(this,true);
};
list.onmouseout = function(){
main.fireNavEvent(this,false);
};
if(list.down("ul")){
main.init(list.down("ul"), true);
}
}
},
ieFixZIndex : function(el, i, l) {
if(el.tagName.toString().toLowerCase().indexOf("iframe") == -1){
el.style.zIndex = l - i;
} else {
el.onmouseover = "null";
el.onmouseout = "null";
}
},
fireNavEvent : function(elm,ev) {
if(ev){
elm.addClassName("over");
elm.down("a").addClassName("over");
if (elm.childElements()[1]) {
main.show(elm.childElements()[1]);
}
} else {
elm.removeClassName("over");
elm.down("a").removeClassName("over");
if (elm.childElements()[1]) {
main.hide(elm.childElements()[1]);
}
}
},
show : function (sub_elm) {
if (sub_elm.hide_time_id) {
clearTimeout(sub_elm.hide_time_id);
}
sub_elm.show_time_id = setTimeout(function() {
if (!sub_elm.hasClassName("shown-sub")) {
sub_elm.addClassName("shown-sub");
}
}, main.settings.show_delay);
},
hide : function (sub_elm) {
if (sub_elm.show_time_id) {
clearTimeout(sub_elm.show_time_id);
}
sub_elm.hide_time_id = setTimeout(function(){
if (sub_elm.hasClassName("shown-sub")) {
sub_elm.removeClassName("shown-sub");
}
}, main.settings.hide_delay);
}
};
if (arguments[1]) {
main.settings = Object.extend(main.settings, arguments[1]);
}
if (main.obj_nav) {
main.init(main.obj_nav, false);
}
};
document.observe("dom:loaded", function() {
//run navigation without delays and with default id="#nav"
//mainNav();
//run navigation with delays
mainNav("nav", {"show_delay":"100","hide_delay":"100"});
});
| JavaScript |
jQuery.noConflict();
jQuery(function() {
jQuery('#mix_container').gridnav({
type : {
mode : 'disperse', // use def | fade | seqfade | updown | sequpdown | showhide | disperse | rows
speed : 500, // for fade, seqfade, updown, sequpdown, showhide, disperse, rows
easing : '', // for fade, seqfade, updown, sequpdown, showhide, disperse, rows
factor : '', // for seqfade, sequpdown, rows
reverse : '' // for sequpdown
}
});
});
jQuery(document).ready(function () {
//Examples of how to assign the ColorBox event to elements
jQuery(".group1").colorbox({rel:'group1'});
jQuery(".group2").colorbox({rel:'group2', transition:"fade"});
jQuery(".group3").colorbox({rel:'group3', transition:"none", width:"75%", height:"75%"});
jQuery(".group4").colorbox({rel:'group4', slideshow:true});
jQuery(".ajax").colorbox();
jQuery(".youtube").colorbox({iframe:true, innerWidth:425, innerHeight:344});
jQuery(".iframe").colorbox({iframe:true, width:"80%", height:"80%"});
jQuery(".inline").colorbox({inline:true, width:"50%"});
jQuery(".callbacks").colorbox({
onOpen:function(){ alert('onOpen: colorbox is about to open'); },
onLoad:function(){ alert('onLoad: colorbox has started to load the targeted content'); },
onComplete:function(){ alert('onComplete: colorbox has displayed the loaded content'); },
onCleanup:function(){ alert('onCleanup: colorbox has begun the close process'); },
onClosed:function(){ alert('onClosed: colorbox has completely closed'); }
});
//Example of preserving a JavaScript event for inline calls.
jQuery("#click").click(function(){
jQuery('#click').css({"background-color":"#f00", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here.");
return false;
});
jQuery('#more_view').jcarousel({
start: 1,
scroll:1,
wrap: 'circular'
});
// hide #back-top first
jQuery("#back-top").hide();
// fade in #back-top
jQuery(function () {
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 100) {
jQuery('#back-top').fadeIn();
} else {
jQuery('#back-top').fadeOut();
}
});
// scroll body to 0px on click
jQuery('#back-top a').click(function () {
jQuery('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});
jQuery('#slider').nivoSlider();
jQuery('.mycarousel_related').jcarousel({
scroll: 1,
wrap: 'circular'
});
});
jQuery(function() {
jQuery("div.add-to-cart").append('<div class="add">›</div><div class="dec add">‹</div>');
jQuery(".add").click(function() {
var jQueryadd = jQuery(this);
var oldValue = jQueryadd.parent().find("input").val();
var newVal = 0;
if (jQueryadd.text() == "›") {
newVal = parseFloat(oldValue) + 1;
// AJAX save would go here
} else {
// Don't allow decrementing below zero
if (oldValue >= 1) {
newVal = parseFloat(oldValue) - 1;
// AJAX save would go here
}
if(oldValue == 0){
newVal = parseFloat(oldValue);
}
}
jQueryadd.parent().find("input").val(newVal);
});
jQuery("#reset_btn").click(function(){
document.getElementById('qty').value=1;
});
}); | JavaScript |
// ColorBox v1.3.19 - jQuery lightbox plugin
// (c) 2011 Jack Moore - jacklmoore.com
// License: http://www.opensource.org/licenses/mit-license.php
(function ($, document, window) {
var
// Default settings object.
// See http://jacklmoore.com/colorbox for details.
defaults = {
transition: "elastic",
speed: 300,
width: false,
initialWidth: "600",
innerWidth: false,
maxWidth: false,
height: false,
initialHeight: "450",
innerHeight: false,
maxHeight: false,
scalePhotos: true,
scrolling: true,
inline: false,
html: false,
iframe: false,
fastIframe: true,
photo: false,
href: false,
title: false,
rel: false,
opacity: 0.9,
preloading: true,
current: "image {current} of {total}",
previous: "previous",
next: "next",
close: "close",
open: false,
returnFocus: true,
reposition: true,
loop: true,
slideshow: false,
slideshowAuto: true,
slideshowSpeed: 2500,
slideshowStart: "start slideshow",
slideshowStop: "stop slideshow",
onOpen: false,
onLoad: false,
onComplete: false,
onCleanup: false,
onClosed: false,
overlayClose: true,
escKey: true,
arrowKey: true,
top: false,
bottom: false,
left: false,
right: false,
fixed: false,
data: undefined
},
// Abstracting the HTML and event identifiers for easy rebranding
colorbox = 'colorbox',
prefix = 'cbox',
boxElement = prefix + 'Element',
// Events
event_open = prefix + '_open',
event_load = prefix + '_load',
event_complete = prefix + '_complete',
event_cleanup = prefix + '_cleanup',
event_closed = prefix + '_closed',
event_purge = prefix + '_purge',
// Special Handling for IE
isIE = !$.support.opacity && !$.support.style, // IE7 & IE8
isIE6 = isIE && !window.XMLHttpRequest, // IE6
event_ie6 = prefix + '_IE6',
// Cached jQuery Object Variables
$overlay,
$box,
$wrap,
$content,
$topBorder,
$leftBorder,
$rightBorder,
$bottomBorder,
$related,
$window,
$loaded,
$loadingBay,
$loadingOverlay,
$title,
$current,
$slideshow,
$next,
$prev,
$close,
$groupControls,
// Variables for cached values or use across multiple functions
settings,
interfaceHeight,
interfaceWidth,
loadedHeight,
loadedWidth,
element,
index,
photo,
open,
active,
closing,
loadingTimer,
publicMethod,
div = "div",
init;
// ****************
// HELPER FUNCTIONS
// ****************
// Convience function for creating new jQuery objects
function $tag(tag, id, css) {
var element = document.createElement(tag);
if (id) {
element.id = prefix + id;
}
if (css) {
element.style.cssText = css;
}
return $(element);
}
// Determine the next and previous members in a group.
function getIndex(increment) {
var
max = $related.length,
newIndex = (index + increment) % max;
return (newIndex < 0) ? max + newIndex : newIndex;
}
// Convert '%' and 'px' values to integers
function setSize(size, dimension) {
return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : $window.height()) / 100) : 1) * parseInt(size, 10));
}
// Checks an href to see if it is a photo.
// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
function isImage(url) {
return settings.photo || /\.(gif|png|jpe?g|bmp|ico)((#|\?).*)?$/i.test(url);
}
// Assigns function results to their respective properties
function makeSettings() {
var i;
settings = $.extend({}, $.data(element, colorbox));
for (i in settings) {
if ($.isFunction(settings[i]) && i.slice(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time.
settings[i] = settings[i].call(element);
}
}
settings.rel = settings.rel || element.rel || 'nofollow';
settings.href = settings.href || $(element).attr('href');
settings.title = settings.title || element.title;
if (typeof settings.href === "string") {
settings.href = $.trim(settings.href);
}
}
function trigger(event, callback) {
$.event.trigger(event);
if (callback) {
callback.call(element);
}
}
// Slideshow functionality
function slideshow() {
var
timeOut,
className = prefix + "Slideshow_",
click = "click." + prefix,
start,
stop,
clear;
if (settings.slideshow && $related[1]) {
start = function () {
$slideshow
.text(settings.slideshowStop)
.unbind(click)
.bind(event_complete, function () {
if (settings.loop || $related[index + 1]) {
timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
}
})
.bind(event_load, function () {
clearTimeout(timeOut);
})
.one(click + ' ' + event_cleanup, stop);
$box.removeClass(className + "off").addClass(className + "on");
timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
};
stop = function () {
clearTimeout(timeOut);
$slideshow
.text(settings.slideshowStart)
.unbind([event_complete, event_load, event_cleanup, click].join(' '))
.one(click, function () {
publicMethod.next();
start();
});
$box.removeClass(className + "on").addClass(className + "off");
};
if (settings.slideshowAuto) {
start();
} else {
stop();
}
} else {
$box.removeClass(className + "off " + className + "on");
}
}
function launch(target) {
if (!closing) {
element = target;
makeSettings();
$related = $(element);
index = 0;
if (settings.rel !== 'nofollow') {
$related = $('.' + boxElement).filter(function () {
var relRelated = $.data(this, colorbox).rel || this.rel;
return (relRelated === settings.rel);
});
index = $related.index(element);
// Check direct calls to ColorBox.
if (index === -1) {
$related = $related.add(element);
index = $related.length - 1;
}
}
if (!open) {
open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.
$box.show();
if (settings.returnFocus) {
$(element).blur().one(event_closed, function () {
$(this).focus();
});
}
// +settings.opacity avoids a problem in IE when using non-zero-prefixed-string-values, like '.5'
$overlay.css({"opacity": +settings.opacity, "cursor": settings.overlayClose ? "pointer" : "auto"}).show();
// Opens inital empty ColorBox prior to content being loaded.
settings.w = setSize(settings.initialWidth, 'x');
settings.h = setSize(settings.initialHeight, 'y');
publicMethod.position();
if (isIE6) {
$window.bind('resize.' + event_ie6 + ' scroll.' + event_ie6, function () {
$overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()});
}).trigger('resize.' + event_ie6);
}
trigger(event_open, settings.onOpen);
$groupControls.add($title).hide();
$close.html(settings.close).show();
}
publicMethod.load(true);
}
}
// ColorBox's markup needs to be added to the DOM prior to being called
// so that the browser will go ahead and load the CSS background images.
function appendHTML() {
if (!$box && document.body) {
init = false;
$window = $(window);
$box = $tag(div).attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''}).hide();
$overlay = $tag(div, "Overlay", isIE6 ? 'position:absolute' : '').hide();
$wrap = $tag(div, "Wrapper");
$content = $tag(div, "Content").append(
$loaded = $tag(div, "LoadedContent", 'width:0; height:0; overflow:hidden'),
$loadingOverlay = $tag(div, "LoadingOverlay").add($tag(div, "LoadingGraphic")),
$title = $tag(div, "Title"),
$current = $tag(div, "Current"),
$next = $tag(div, "Next"),
$prev = $tag(div, "Previous"),
$slideshow = $tag(div, "Slideshow").bind(event_open, slideshow),
$close = $tag(div, "Close")
);
$wrap.append( // The 3x3 Grid that makes up ColorBox
$tag(div).append(
$tag(div, "TopLeft"),
$topBorder = $tag(div, "TopCenter"),
$tag(div, "TopRight")
),
$tag(div, false, 'clear:left').append(
$leftBorder = $tag(div, "MiddleLeft"),
$content,
$rightBorder = $tag(div, "MiddleRight")
),
$tag(div, false, 'clear:left').append(
$tag(div, "BottomLeft"),
$bottomBorder = $tag(div, "BottomCenter"),
$tag(div, "BottomRight")
)
).find('div div').css({'float': 'left'});
$loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none');
$groupControls = $next.add($prev).add($current).add($slideshow);
$(document.body).append($overlay, $box.append($wrap, $loadingBay));
}
}
// Add ColorBox's event bindings
function addBindings() {
if ($box) {
if (!init) {
init = true;
// Cache values needed for size calculations
interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6
interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width();
loadedHeight = $loaded.outerHeight(true);
loadedWidth = $loaded.outerWidth(true);
// Setting padding to remove the need to do size conversions during the animation step.
$box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth});
// Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly.
$next.click(function () {
publicMethod.next();
});
$prev.click(function () {
publicMethod.prev();
});
$close.click(function () {
publicMethod.close();
});
$overlay.click(function () {
if (settings.overlayClose) {
publicMethod.close();
}
});
// Key Bindings
$(document).bind('keydown.' + prefix, function (e) {
var key = e.keyCode;
if (open && settings.escKey && key === 27) {
e.preventDefault();
publicMethod.close();
}
if (open && settings.arrowKey && $related[1]) {
if (key === 37) {
e.preventDefault();
$prev.click();
} else if (key === 39) {
e.preventDefault();
$next.click();
}
}
});
$('.' + boxElement, document).live('click', function (e) {
// ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt.
// See: http://jacklmoore.com/notes/click-events/
if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey)) {
e.preventDefault();
launch(this);
}
});
}
return true;
}
return false;
}
// Don't do anything if ColorBox already exists.
if ($.colorbox) {
return;
}
// Append the HTML when the DOM loads
$(appendHTML);
// ****************
// PUBLIC FUNCTIONS
// Usage format: $.fn.colorbox.close();
// Usage from within an iframe: parent.$.fn.colorbox.close();
// ****************
publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
var $this = this;
options = options || {};
appendHTML();
if (addBindings()) {
if (!$this[0]) {
if ($this.selector) { // if a selector was given and it didn't match any elements, go ahead and exit.
return $this;
}
// if no selector was given (ie. $.colorbox()), create a temporary element to work with
$this = $('<a/>');
options.open = true; // assume an immediate open
}
if (callback) {
options.onComplete = callback;
}
$this.each(function () {
$.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options));
}).addClass(boxElement);
if (($.isFunction(options.open) && options.open.call($this)) || options.open) {
launch($this[0]);
}
}
return $this;
};
publicMethod.position = function (speed, loadedCallback) {
var
top = 0,
left = 0,
offset = $box.offset(),
scrollTop = $window.scrollTop(),
scrollLeft = $window.scrollLeft();
$window.unbind('resize.' + prefix);
// remove the modal so that it doesn't influence the document width/height
$box.css({top: -9e4, left: -9e4});
if (settings.fixed && !isIE6) {
offset.top -= scrollTop;
offset.left -= scrollLeft;
$box.css({position: 'fixed'});
} else {
top = scrollTop;
left = scrollLeft;
$box.css({position: 'absolute'});
}
// keeps the top and left positions within the browser's viewport.
if (settings.right !== false) {
left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.right, 'x'), 0);
} else if (settings.left !== false) {
left += setSize(settings.left, 'x');
} else {
left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2);
}
if (settings.bottom !== false) {
top += Math.max($window.height() - settings.h - loadedHeight - interfaceHeight - setSize(settings.bottom, 'y'), 0);
} else if (settings.top !== false) {
top += setSize(settings.top, 'y');
} else {
top += Math.round(Math.max($window.height() - settings.h - loadedHeight - interfaceHeight, 0) / 2);
}
$box.css({top: offset.top, left: offset.left});
// setting the speed to 0 to reduce the delay between same-sized content.
speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed || 0;
// this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly,
// but it has to be shrank down around the size of div#colorbox when it's done. If not,
// it can invoke an obscure IE bug when using iframes.
$wrap[0].style.width = $wrap[0].style.height = "9999px";
function modalDimensions(that) {
$topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width;
$content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height;
}
$box.dequeue().animate({width: settings.w + loadedWidth, height: settings.h + loadedHeight, top: top, left: left}, {
duration: speed,
complete: function () {
modalDimensions(this);
active = false;
// shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation.
$wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
$wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";
if (settings.reposition) {
setTimeout(function () { // small delay before binding onresize due to an IE8 bug.
$window.bind('resize.' + prefix, publicMethod.position);
}, 1);
}
if (loadedCallback) {
loadedCallback();
}
},
step: function () {
modalDimensions(this);
}
});
};
publicMethod.resize = function (options) {
if (open) {
options = options || {};
if (options.width) {
settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth;
}
if (options.innerWidth) {
settings.w = setSize(options.innerWidth, 'x');
}
$loaded.css({width: settings.w});
if (options.height) {
settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight;
}
if (options.innerHeight) {
settings.h = setSize(options.innerHeight, 'y');
}
if (!options.innerHeight && !options.height) {
$loaded.css({height: "auto"});
settings.h = $loaded.height();
}
$loaded.css({height: settings.h});
publicMethod.position(settings.transition === "none" ? 0 : settings.speed);
}
};
publicMethod.prep = function (object) {
if (!open) {
return;
}
var callback, speed = settings.transition === "none" ? 0 : settings.speed;
$loaded.remove();
$loaded = $tag(div, 'LoadedContent').append(object);
function getWidth() {
settings.w = settings.w || $loaded.width();
settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
return settings.w;
}
function getHeight() {
settings.h = settings.h || $loaded.height();
settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
return settings.h;
}
$loaded.hide()
.appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations.
.css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'})
.css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height.
.prependTo($content);
$loadingBay.hide();
// floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width.
//$(photo).css({'float': 'none', marginLeft: 'auto', marginRight: 'auto'});
$(photo).css({'float': 'none'});
// Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay.
if (isIE6) {
$('select').not($box.find('select')).filter(function () {
return this.style.visibility !== 'hidden';
}).css({'visibility': 'hidden'}).one(event_cleanup, function () {
this.style.visibility = 'inherit';
});
}
callback = function () {
var preload, i, total = $related.length, iframe, frameBorder = 'frameBorder', allowTransparency = 'allowTransparency', complete, src, img;
if (!open) {
return;
}
function removeFilter() {
if (isIE) {
$box[0].style.removeAttribute('filter');
}
}
complete = function () {
clearTimeout(loadingTimer);
$loadingOverlay.hide();
trigger(event_complete, settings.onComplete);
};
if (isIE) {
//This fadeIn helps the bicubic resampling to kick-in.
if (photo) {
$loaded.fadeIn(100);
}
}
$title.html(settings.title).add($loaded).show();
if (total > 1) { // handle grouping
if (typeof settings.current === "string") {
$current.html(settings.current.replace('{current}', index + 1).replace('{total}', total)).show();
}
$next[(settings.loop || index < total - 1) ? "show" : "hide"]().html(settings.next);
$prev[(settings.loop || index) ? "show" : "hide"]().html(settings.previous);
if (settings.slideshow) {
$slideshow.show();
}
// Preloads images within a rel group
if (settings.preloading) {
preload = [
getIndex(-1),
getIndex(1)
];
while (i = $related[preload.pop()]) {
src = $.data(i, colorbox).href || i.href;
if ($.isFunction(src)) {
src = src.call(i);
}
if (isImage(src)) {
img = new Image();
img.src = src;
}
}
}
} else {
$groupControls.hide();
}
if (settings.iframe) {
iframe = $tag('iframe')[0];
if (frameBorder in iframe) {
iframe[frameBorder] = 0;
}
if (allowTransparency in iframe) {
iframe[allowTransparency] = "true";
}
// give the iframe a unique name to prevent caching
iframe.name = prefix + (+new Date());
if (settings.fastIframe) {
complete();
} else {
$(iframe).one('load', complete);
}
iframe.src = settings.href;
if (!settings.scrolling) {
iframe.scrolling = "no";
}
$(iframe).addClass(prefix + 'Iframe').appendTo($loaded).one(event_purge, function () {
iframe.src = "//about:blank";
});
} else {
complete();
}
if (settings.transition === 'fade') {
$box.fadeTo(speed, 1, removeFilter);
} else {
removeFilter();
}
};
if (settings.transition === 'fade') {
$box.fadeTo(speed, 0, function () {
publicMethod.position(0, callback);
});
} else {
publicMethod.position(speed, callback);
}
};
publicMethod.load = function (launched) {
var href, setResize, prep = publicMethod.prep;
active = true;
photo = false;
element = $related[index];
if (!launched) {
makeSettings();
}
trigger(event_purge);
trigger(event_load, settings.onLoad);
settings.h = settings.height ?
setSize(settings.height, 'y') - loadedHeight - interfaceHeight :
settings.innerHeight && setSize(settings.innerHeight, 'y');
settings.w = settings.width ?
setSize(settings.width, 'x') - loadedWidth - interfaceWidth :
settings.innerWidth && setSize(settings.innerWidth, 'x');
// Sets the minimum dimensions for use in image scaling
settings.mw = settings.w;
settings.mh = settings.h;
// Re-evaluate the minimum width and height based on maxWidth and maxHeight values.
// If the width or height exceed the maxWidth or maxHeight, use the maximum values instead.
if (settings.maxWidth) {
settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth;
settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
}
if (settings.maxHeight) {
settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight;
settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
}
href = settings.href;
loadingTimer = setTimeout(function () {
$loadingOverlay.show();
}, 100);
if (settings.inline) {
// Inserts an empty placeholder where inline content is being pulled from.
// An event is bound to put inline content back when ColorBox closes or loads new content.
$tag(div).hide().insertBefore($(href)[0]).one(event_purge, function () {
$(this).replaceWith($loaded.children());
});
prep($(href));
} else if (settings.iframe) {
// IFrame element won't be added to the DOM until it is ready to be displayed,
// to avoid problems with DOM-ready JS that might be trying to run in that iframe.
prep(" ");
} else if (settings.html) {
prep(settings.html);
} else if (isImage(href)) {
$(photo = new Image())
.addClass(prefix + 'Photo')
.error(function () {
settings.title = false;
prep($tag(div, 'Error').text('This image could not be loaded'));
})
.load(function () {
var percent;
photo.onload = null; //stops animated gifs from firing the onload repeatedly.
if (settings.scalePhotos) {
setResize = function () {
photo.height -= photo.height * percent;
photo.width -= photo.width * percent;
};
if (settings.mw && photo.width > settings.mw) {
percent = (photo.width - settings.mw) / photo.width;
setResize();
}
if (settings.mh && photo.height > settings.mh) {
percent = (photo.height - settings.mh) / photo.height;
setResize();
}
}
if (settings.h) {
photo.style.marginTop = Math.max(settings.h - photo.height, 0) / 2 + 'px';
}
if ($related[1] && (settings.loop || $related[index + 1])) {
photo.style.cursor = 'pointer';
photo.onclick = function () {
publicMethod.next();
};
}
if (isIE) {
photo.style.msInterpolationMode = 'bicubic';
}
setTimeout(function () { // A pause because Chrome will sometimes report a 0 by 0 size otherwise.
prep(photo);
}, 1);
});
setTimeout(function () { // A pause because Opera 10.6+ will sometimes not run the onload function otherwise.
photo.src = href;
}, 1);
} else if (href) {
$loadingBay.load(href, settings.data, function (data, status, xhr) {
prep(status === 'error' ? $tag(div, 'Error').text('Request unsuccessful: ' + xhr.statusText) : $(this).contents());
});
}
};
// Navigates to the next page/image in a set.
publicMethod.next = function () {
if (!active && $related[1] && (settings.loop || $related[index + 1])) {
index = getIndex(1);
publicMethod.load();
}
};
publicMethod.prev = function () {
if (!active && $related[1] && (settings.loop || index)) {
index = getIndex(-1);
publicMethod.load();
}
};
// Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close();
publicMethod.close = function () {
if (open && !closing) {
closing = true;
open = false;
trigger(event_cleanup, settings.onCleanup);
$window.unbind('.' + prefix + ' .' + event_ie6);
$overlay.fadeTo(200, 0);
$box.stop().fadeTo(300, 0, function () {
$box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide();
trigger(event_purge);
$loaded.remove();
setTimeout(function () {
closing = false;
trigger(event_closed, settings.onClosed);
}, 1);
});
}
};
// Removes changes ColorBox made to the document, but does not remove the plugin
// from jQuery.
publicMethod.remove = function () {
$([]).add($box).add($overlay).remove();
$box = null;
$('.' + boxElement)
.removeData(colorbox)
.removeClass(boxElement)
.die();
};
// A method for fetching the current element ColorBox is referencing.
// returns a jQuery object.
publicMethod.element = function () {
return $(element);
};
publicMethod.settings = defaults;
}(jQuery, document, this)); | JavaScript |
/*
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*
* Uses the built in easing capabilities added In jQuery 1.1
* to offer multiple easing options
*
* TERMS OF USE - jQuery Easing
*
* Open source under the BSD License.
*
* Copyright © 2008 George McGinley Smith
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
def: 'easeOutQuad',
swing: function (x, t, b, c, d) {
//alert(jQuery.easing.default);
return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
},
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;
}
});
/*
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright © 2001 Robert Penner
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/ | JavaScript |
function piv(data){ // positive int
if(data != parseInt(data) || parseInt(data) < 0 ){
if(data == ''){
return true;
}
else{
return false;
}
}
else{
return true;
}
}
function piv_nn(data){ // positive int not null
if(data != parseInt(data) || parseInt(data) < 0){
return false;
}
else{
return true;
}
}
| JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
(function() {
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) {
var el = document.createElement('div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
function isForm(element) {
return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM'
}
function isInput(element) {
if (Object.isElement(element)) {
var name = element.nodeName.toUpperCase()
return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA'
}
else return false
}
var submitBubbles = isEventSupported('submit'),
changeBubbles = isEventSupported('change')
if (!submitBubbles || !changeBubbles) {
// augment the Event.Handler class to observe custom events when needed
Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap(
function(init, element, eventName, selector, callback) {
init(element, eventName, selector, callback)
// is the handler being attached to an element that doesn't support this event?
if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) ||
(!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) {
// "submit" => "emulated:submit"
this.eventName = 'emulated:' + this.eventName
}
}
)
}
if (!submitBubbles) {
// discover forms on the page by observing focus events which always bubble
document.on('focusin', 'form', function(focusEvent, form) {
// special handler for the real "submit" event (one-time operation)
if (!form.retrieve('emulated:submit')) {
form.on('submit', function(submitEvent) {
var emulated = form.fire('emulated:submit', submitEvent, true)
// if custom event received preventDefault, cancel the real one too
if (emulated.returnValue === false) submitEvent.preventDefault()
})
form.store('emulated:submit', true)
}
})
}
if (!changeBubbles) {
// discover form inputs on the page
document.on('focusin', 'input, select, texarea', function(focusEvent, input) {
// special handler for real "change" events
if (!input.retrieve('emulated:change')) {
input.on('change', function(changeEvent) {
input.fire('emulated:change', changeEvent, true)
})
input.store('emulated:change', true)
}
})
}
function handleRemote(element) {
var method, url, params;
var event = element.fire("ajax:before");
if (event.stopped) return false;
if (element.tagName.toLowerCase() === 'form') {
method = element.readAttribute('method') || 'post';
url = element.readAttribute('action');
params = element.serialize();
} else {
method = element.readAttribute('data-method') || 'get';
url = element.readAttribute('href');
params = {};
}
new Ajax.Request(url, {
method: method,
parameters: params,
evalScripts: true,
onComplete: function(request) { element.fire("ajax:complete", request); },
onSuccess: function(request) { element.fire("ajax:success", request); },
onFailure: function(request) { element.fire("ajax:failure", request); }
});
element.fire("ajax:after");
}
function handleMethod(element) {
var method = element.readAttribute('data-method'),
url = element.readAttribute('href'),
csrf_param = $$('meta[name=csrf-param]')[0],
csrf_token = $$('meta[name=csrf-token]')[0];
var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
element.parentNode.insert(form);
if (method !== 'post') {
var field = new Element('input', { type: 'hidden', name: '_method', value: method });
form.insert(field);
}
if (csrf_param) {
var param = csrf_param.readAttribute('content'),
token = csrf_token.readAttribute('content'),
field = new Element('input', { type: 'hidden', name: param, value: token });
form.insert(field);
}
form.submit();
}
document.on("click", "*[data-confirm]", function(event, element) {
var message = element.readAttribute('data-confirm');
if (!confirm(message)) event.stop();
});
document.on("click", "a[data-remote]", function(event, element) {
if (event.stopped) return;
handleRemote(element);
event.stop();
});
document.on("click", "a[data-method]", function(event, element) {
if (event.stopped) return;
handleMethod(element);
event.stop();
});
document.on("submit", function(event) {
var element = event.findElement(),
message = element.readAttribute('data-confirm');
if (message && !confirm(message)) {
event.stop();
return false;
}
var inputs = element.select("input[type=submit][data-disable-with]");
inputs.each(function(input) {
input.disabled = true;
input.writeAttribute('data-original-value', input.value);
input.value = input.readAttribute('data-disable-with');
});
var element = event.findElement("form[data-remote]");
if (element) {
handleRemote(element);
event.stop();
}
});
document.on("ajax:after", "form", function(event, element) {
var inputs = element.select("input[type=submit][disabled=true][data-disable-with]");
inputs.each(function(input) {
input.value = input.readAttribute('data-original-value');
input.removeAttribute('data-original-value');
input.disabled = false;
});
});
Ajax.Responders.register({
onCreate: function(request) {
var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
if (csrf_meta_tag) {
var header = 'X-CSRF-Token',
token = csrf_meta_tag.readAttribute('content');
if (!request.options.requestHeaders) {
request.options.requestHeaders = {};
}
request.options.requestHeaders[header] = token;
}
}
});
})();
| JavaScript |
var HEYFITTY = function(){
this.NAVBAR = new NAVBAR();
// this.FOOTER = new FOOTER();
this.init = function(){
// this.FOOTER.init();
this.NAVBAR.init();
this.initPageScroll();
this.initgridRotator();
this.initValidate();
}
}
HEYFITTY.prototype = {
initPageScroll: function(){
//jQuery for page scrolling feature - requires jQuery Easing plugin
$('.page-scroll a').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
},
/*
* GRID ROTATOR STUFF
*/
initgridRotator: function(){
$( '#ri-grid' ).gridrotator( {
rows : 14,
columns : 14,
maxStep : 12,
interval : 1000,
animType : 'fadeInOut',
w1024 : {rows : 6,columns : 6},
w768 : {rows : 5,columns : 5},
w480 : {rows : 6,columns : 4},
w320 : {rows : 7,columns : 4},
w240 : {rows : 7,columns : 3},
} );
},
initValidate: function(){
if( $("#form-join").length ){
$("#form-join").bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
joinUsername: {
validators: {
notEmpty: {
message: 'Please Enter Username'
}
}
},
joinEmail: {
validators: {
notEmpty: {
message: 'Please Enter Email'
}
}
},
joinPassword: {
validators: {
notEmpty: {
message: 'Please Enter Password'
}
}
},
}
})
.on('error.form.bv', function(e) {
HEYFITTY.FOOTER.resize();
})
}
}
}
$().ready(function(){
var heyFittyApp = new HEYFITTY();
heyFittyApp.init();
});
/*
* NAVBAR CENTERING MIDDLE NAV FUNCTION...
* This function centres the charts, discover and livefeed nav container to the middle of the page based on the window size.
* It also does media queries to ensure that when the navbar has collapsed that the nav isn't pushed.
* Handles: '.central-navbar'
* Returns: Nothing
*/
var NAVBAR = function(){
var self = this;
var push_value;
//Init()
this.init = function(){
self.set_css();
self.push_value = self.get_centre_nav_push_value();
self.center_nav_responsive();
self.handler();
}
// Handler Event
this.handler = function(){
//Change central nav position on window.resize()
$(window).resize(function(){
self.set_css();
self.center_nav_responsive();
});
//jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".navbar").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
}
//Center the nav based on media query checks
this.center_nav_responsive = function(){
//Media query to check for collapsed nav.
if ( $(window).width() >= 991) {
self.push_value = self.get_centre_nav_push_value();
self.push_nav();
} else {
self.push_value = 0;
self.push_nav();
}
}
//Get the push value. DRY.
this.get_centre_nav_push_value = function(){
var push_value = (
//Explanation of what on earth is happening in this line.
//1. Get the width of the navbar minus the width of the central navbar total
//2. Divide this number by 2 to get the centre of the navbar
//3. Account for the brand heading's width by subtracting this from the current number
//4. Divide the brand heading by 2 to get the absolute middle
( ( $(".navbar").width() - $(".central-navbar").width() ) / 2 - $(".navbar-brand").width() ) - $(".navbar-brand").width() / 2
);
return push_value;
}
//Push the nav!
this.push_nav = function(){
$(".central-navbar").css("margin-left", self.push_value);
}
/*
* Navbar button style alteration, changes the green join button style between mobile and desktop view
*/
this.set_css = function(){
if ( $(window).width() <= 767 ) {
$(".middle-section-link").css("right", "15px");
$("#join-heyfitty").removeClass("join-heyfitty-style");
$("#login-heyfitty").removeClass("login-link");
}
if ( $(window).width() >= 768 ){
$("#join-heyfitty").addClass("join-heyfitty-style");
$("#login-heyfitty").addClass("login-link");
}
}
}
var FOOTER = function(){
var self = this;
this.init = function(){
self.resize();
self.handler();
}
this.handler = function(){
$(window).resize(function(){
self.resize();
});
}
this.resize = function(){
footerHeight = $(".heyfitty-footer").outerHeight()+50;
wH = $(window).height();
$(".frontpage").height(wH-footerHeight);
}
}
| JavaScript |
/**
* jquery.gridrotator.js v1.1.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2012, Codrops
* http://www.codrops.com
*/
;( function( $, window, undefined ) {
'use strict';
/*
* debouncedresize: special jQuery event that happens once after a window resize
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery-smartresize/blob/master/jquery.debouncedresize.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*/
var $event = $.event,
$special,
resizeTimeout;
$special = $event.special.debouncedresize = {
setup: function() {
$( this ).on( "resize", $special.handler );
},
teardown: function() {
$( this ).off( "resize", $special.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments,
dispatch = function() {
// set correct event type
event.type = "debouncedresize";
$event.dispatch.apply( context, args );
};
if ( resizeTimeout ) {
clearTimeout( resizeTimeout );
}
execAsap ?
dispatch() :
resizeTimeout = setTimeout( dispatch, $special.threshold );
},
threshold: 100
};
// http://www.hardcode.nl/subcategory_1/article_317-array-shuffle-function
Array.prototype.shuffle = function() {
var i=this.length,p,t;
while (i--) {
p = Math.floor(Math.random()*i);
t = this[i];
this[i]=this[p];
this[p]=t;
}
return this;
};
// HTML5 PageVisibility API
// http://www.html5rocks.com/en/tutorials/pagevisibility/intro/
// by Joe Marini (@joemarini)
function getHiddenProp(){
var prefixes = ['webkit','moz','ms','o'];
// if 'hidden' is natively supported just return it
if ('hidden' in document) return 'hidden';
// otherwise loop over all the known prefixes until we find one
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document)
return prefixes[i] + 'Hidden';
}
// otherwise it's not supported
return null;
}
function isHidden() {
var prop = getHiddenProp();
if (!prop) return false;
return document[prop];
}
function isEmpty( obj ) {
return Object.keys(obj).length === 0;
}
// global
var $window = $( window ),
Modernizr = window.Modernizr;
$.GridRotator = function( options, element ) {
this.$el = $( element );
if( Modernizr.backgroundsize ) {
var self = this;
this.$el.addClass( 'ri-grid-loading' );
this._init( options );
}
};
// the options
$.GridRotator.defaults = {
// number of rows
rows : 4,
// number of columns
columns : 10,
w1024 : { rows : 3, columns : 8 },
w768 : {rows : 3,columns : 7 },
w480 : {rows : 3,columns : 5 },
w320 : {rows : 2,columns : 4 },
w240 : {rows : 2,columns : 3 },
// step: number of items that are replaced at the same time
// random || [some number]
// note: for performance issues, the number "can't" be > options.maxStep
step : 'random',
// change it as you wish..
maxStep : 3,
// prevent user to click the items
preventClick : true,
// animation type
// showHide || fadeInOut ||
// slideLeft || slideRight || slideTop || slideBottom ||
// rotateBottom || rotateLeft || rotateRight || rotateTop ||
// scale ||
// rotate3d ||
// rotateLeftScale || rotateRightScale || rotateTopScale || rotateBottomScale ||
// random
animType : 'random',
// animation speed
animSpeed : 800,
// animation easings
animEasingOut : 'linear',
animEasingIn: 'linear',
// the item(s) will be replaced every 3 seconds
// note: for performance issues, the time "can't" be < 300 ms
interval : 3000,
// if false the animations will not start
// use false if onhover is true for example
slideshow : true,
// if true the items will switch when hovered
onhover : false,
// ids of elements that shouldn't change
nochange : []
};
$.GridRotator.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.GridRotator.defaults, options );
// cache some elements + variables
this._config();
},
_config : function() {
var self = this,
transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
};
// support CSS transitions and 3d transforms
this.supportTransitions = Modernizr.csstransitions;
this.supportTransforms3D = Modernizr.csstransforms3d;
this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.gridrotator';
// all animation types for the random option
this.animTypes = this.supportTransforms3D ? [
'fadeInOut',
'slideLeft',
'slideRight',
'slideTop',
'slideBottom',
'rotateLeft',
'rotateRight',
'rotateTop',
'rotateBottom',
'scale',
'rotate3d',
'rotateLeftScale',
'rotateRightScale',
'rotateTopScale',
'rotateBottomScale' ] :
[ 'fadeInOut', 'slideLeft', 'slideRight', 'slideTop', 'slideBottom' ];
this.animType = this.options.animType;
if( this.animType !== 'random' && !this.supportTransforms3D && $.inArray( this.animType, this.animTypes ) === -1 && this.animType !== 'showHide' ) {
// fallback to 'fadeInOut' if user sets a type which is not supported
this.animType = 'fadeInOut';
}
this.animTypesTotal = this.animTypes.length;
// the <ul> where the items are placed
this.$list = this.$el.children( 'ul' );
// remove images and add background-image to anchors
// preload the images before
var loaded = 0,
$imgs = this.$list.find( 'img' ),
count = $imgs.length;
$imgs.each( function() {
var $img = $( this ), src = $img.attr( 'src' );
$( '<img/>' ).load( function() {
++loaded;
$img.parent().css( 'background-image', 'url(' + src + ')' );
if( loaded === count ) {
$imgs.remove();
self.$el.removeClass( 'ri-grid-loading' );
// the items
self.$items = self.$list.children( 'li' );
// make a copy of the items
self.$itemsCache = self.$items.clone();
// total number of items
self.itemsTotal = self.$items.length;
// the items that will be out of the grid
// actually the item's child (anchor element)
self.outItems= [];
self._layout( function() {
self._initEvents();
} );
// replace [options.step] items after [options.interval] time
// the items that go out are randomly chosen, while the ones that get in
// follow a "First In First Out" logic
self._start();
}
} ).attr( 'src', src )
} );
},
_layout : function( callback ) {
var self = this;
// sets the grid dimentions based on the container's width
this._setGridDim();
// reset
this.$list.empty();
this.$items = this.$itemsCache.clone().appendTo( this.$list );
var $outItems = this.$items.filter( ':gt(' + ( this.showTotal - 1 ) + ')' ),
$outAItems = $outItems.children( 'a' );
this.outItems.length = 0;
$outAItems.each( function( i ) {
self.outItems.push( $( this ) );
} );
$outItems.remove();
// container's width
var containerWidth = ( document.defaultView ) ? parseInt( document.defaultView.getComputedStyle( this.$el.get( 0 ), null ).width ) : this.$el.width(),
// item's width
itemWidth = Math.floor( containerWidth / this.columns ),
// calculate gap
gapWidth = containerWidth - ( this.columns * Math.floor( itemWidth ) );
for( var i = 0; i < this.rows; ++i ) {
for( var j = 0; j < this.columns; ++j ) {
var idx = this.columns * i + j,
$item = this.$items.eq( idx );
$item.css( {
width : j < Math.floor( gapWidth ) ? itemWidth + 1 : itemWidth,
height : itemWidth
} );
if( $.inArray( idx, this.options.nochange ) !== -1 ) {
$item.addClass( 'ri-nochange' ).data( 'nochange', true );
}
}
}
if( this.options.preventClick ) {
this.$items.children().css( 'cursor', 'default' ).on( 'click.gridrotator', false );
}
if( callback ) {
callback.call();
}
},
// set the grid rows and columns
_setGridDim : function() {
// container's width
var c_w = this.$el.width();
// we will choose the number of rows/columns according to the container's width and the values set in the plugin options
switch( true ) {
case ( c_w < 240 ) : this.rows = this.options.w240.rows; this.columns = this.options.w240.columns; break;
case ( c_w < 320 ) : this.rows = this.options.w320.rows; this.columns = this.options.w320.columns; break;
case ( c_w < 480 ) : this.rows = this.options.w480.rows; this.columns = this.options.w480.columns; break;
case ( c_w < 768 ) : this.rows = this.options.w768.rows; this.columns = this.options.w768.columns; break;
case ( c_w < 1024 ) : this.rows = this.options.w1024.rows; this.columns = this.options.w1024.columns; break;
default : this.rows = this.options.rows; this.columns = this.options.columns; break;
}
this.showTotal = this.rows * this.columns;
},
// init window resize event
_initEvents : function() {
var self = this;
$window.on( 'debouncedresize.gridrotator', function() {
self._layout();
} );
// use the property name to generate the prefixed event name
var visProp = getHiddenProp();
// HTML5 PageVisibility API
// http://www.html5rocks.com/en/tutorials/pagevisibility/intro/
// by Joe Marini (@joemarini)
if (visProp) {
var evtname = visProp.replace(/[H|h]idden/,'') + 'visibilitychange';
document.addEventListener(evtname, function() { self._visChange(); } );
}
if( !Modernizr.touch && this.options.onhover ) {
self.$items.on( 'mouseenter.gridrotator', function() {
var $item = $( this );
if( !$item.data( 'active' ) && !$item.data( 'hovered' ) && !$item.data( 'nochange' ) ) {
$item.data( 'hovered', true );
self._replace( $item );
}
} ).on( 'mouseleave.gridrotator', function() {
$( this ).data( 'hovered', false );
} );
}
},
_visChange : function() {
isHidden() ? clearTimeout( this.playtimeout ) : this._start();
},
// start rotating elements
_start : function() {
if( this.showTotal < this.itemsTotal && this.options.slideshow ) {
this._showNext();
}
},
// get which type of animation
_getAnimType : function() {
return this.animType === 'random' ? this.animTypes[ Math.floor( Math.random() * this.animTypesTotal ) ] : this.animType;
},
// get css properties for the transition effect
_getAnimProperties : function( $out ) {
var startInProp = {}, startOutProp = {}, endInProp = {}, endOutProp = {},
animType = this._getAnimType(), speed, delay = 0;
switch( animType ) {
case 'showHide' :
speed = 0;
endOutProp.opacity = 0;
break;
case 'fadeInOut' :
endOutProp.opacity = 0;
break;
case 'slideLeft' :
startInProp.left = $out.width();
endInProp.left = 0;
endOutProp.left = -$out.width();
break;
case 'slideRight' :
startInProp.left = -$out.width();
endInProp.left = 0;
endOutProp.left = $out.width();
break;
case 'slideTop' :
startInProp.top = $out.height();
endInProp.top = 0;
endOutProp.top = -$out.height();
break;
case 'slideBottom' :
startInProp.top = -$out.height();
endInProp.top = 0;
endOutProp.top = $out.height();
break;
case 'rotateLeft' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'rotateY(90deg)';
endInProp.transform = 'rotateY(0deg)';
delay = speed;
endOutProp.transform = 'rotateY(-90deg)';
break;
case 'rotateRight' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'rotateY(-90deg)';
endInProp.transform = 'rotateY(0deg)';
delay = speed;
endOutProp.transform = 'rotateY(90deg)';
break;
case 'rotateTop' :
speed = this.options.animSpeed / 2;
startInProp.transform= 'rotateX(90deg)';
endInProp.transform = 'rotateX(0deg)';
delay = speed;
endOutProp.transform = 'rotateX(-90deg)';
break;
case 'rotateBottom' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'rotateX(-90deg)';
endInProp.transform = 'rotateX(0deg)';
delay = speed;
endOutProp.transform = 'rotateX(90deg)';
break;
case 'scale' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0)';
startOutProp.transform = 'scale(1)';
endInProp.transform = 'scale(1)';
delay = speed;
endOutProp.transform = 'scale(0)';
break;
case 'rotateLeftScale' :
startOutProp.transform = 'scale(1)';
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0.3) rotateY(90deg)';
endInProp.transform = 'scale(1) rotateY(0deg)';
delay = speed;
endOutProp.transform = 'scale(0.3) rotateY(-90deg)';
break;
case 'rotateRightScale' :
startOutProp.transform = 'scale(1)';
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0.3) rotateY(-90deg)';
endInProp.transform = 'scale(1) rotateY(0deg)';
delay = speed;
endOutProp.transform = 'scale(0.3) rotateY(90deg)';
break;
case 'rotateTopScale' :
startOutProp.transform = 'scale(1)';
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0.3) rotateX(90deg)';
endInProp.transform = 'scale(1) rotateX(0deg)';
delay = speed;
endOutProp.transform = 'scale(0.3) rotateX(-90deg)';
break;
case 'rotateBottomScale' :
startOutProp.transform = 'scale(1)';
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0.3) rotateX(-90deg)';
endInProp.transform = 'scale(1) rotateX(0deg)';
delay = speed;
endOutProp.transform = 'scale(0.3) rotateX(90deg)';
break;
case 'rotate3d' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'rotate3d( 1, 1, 0, 90deg )';
endInProp.transform = 'rotate3d( 1, 1, 0, 0deg )';
delay = speed;
endOutProp.transform = 'rotate3d( 1, 1, 0, -90deg )';
break;
}
return {
startInProp : startInProp,
startOutProp : startOutProp,
endInProp : endInProp,
endOutProp : endOutProp,
delay : delay,
animSpeed : speed != undefined ? speed : this.options.animSpeed
};
},
// show next [option.step] elements
_showNext : function( time ) {
var self = this;
clearTimeout( this.playtimeout );
this.playtimeout = setTimeout( function() {
var step = self.options.step, max= self.options.maxStep, min = 1;
if( max > self.showTotal ) {
max = self.showTotal;
}
// number of items to swith at this point of time
var nmbOut = step === 'random' ? Math.floor( Math.random() * max + min ) : Math.min( Math.abs( step ) , max ) ,
// array with random indexes. These will be the indexes of the items we will replace
randArr = self._getRandom( nmbOut, self.showTotal );
for( var i = 0; i < nmbOut; ++i ) {
// element to go out
var $out = self.$items.eq( randArr[ i ] );
// if element is active, which means it is currently animating,
// then we need to get different positions..
if( $out.data( 'active' ) || $out.data( 'nochange' ) ) {
// one of the items is active, call again..
self._showNext( 1 );
return false;
}
self._replace( $out );
}
// again and again..
self._showNext();
}, time || Math.max( Math.abs( this.options.interval ) , 300 ) );
},
_replace : function( $out ) {
$out.data( 'active', true );
var self = this,
$outA = $out.children( 'a:last' ),
newElProp = {
width : $outA.width(),
height : $outA.height()
};
// element stays active
$out.data( 'active', true );
// get the element (anchor) that will go in (first one inserted in this.outItems)
var $inA = this.outItems.shift();
// save element that went out
this.outItems.push( $outA.clone().css( 'transition', 'none' ) );
// prepend in element
$inA.css( newElProp ).prependTo( $out );
var animProp = this._getAnimProperties( $outA );
$inA.css( animProp.startInProp );
$outA.css( animProp.startOutProp );
this._setTransition( $inA, 'all', animProp.animSpeed, animProp.delay, this.options.animEasingIn );
this._setTransition( $outA, 'all', animProp.animSpeed, 0, this.options.animEasingOut );
this._applyTransition( $inA, animProp.endInProp, animProp.animSpeed, function() {
var $el = $( this ),
t = animProp.animSpeed === self.options.animSpeed && isEmpty( animProp.endInProp ) ? animProp.animSpeed : 0;
setTimeout( function() {
if( self.supportTransitions ) {
$el.off( self.transEndEventName );
}
$el.next().remove();
$el.parent().data( 'active', false );
}, t );
}, animProp.animSpeed === 0 || isEmpty( animProp.endInProp ) );
this._applyTransition( $outA, animProp.endOutProp, animProp.animSpeed );
},
_getRandom : function( cnt, limit ) {
var randArray = [];
for( var i = 0; i < limit; ++i ) {
randArray.push( i )
}
return randArray.shuffle().slice( 0, cnt );
},
_setTransition : function( el, prop, speed, delay, easing ) {
setTimeout( function() {
el.css( 'transition', prop + ' ' + speed + 'ms ' + delay + 'ms ' + easing );
}, 25 );
},
_applyTransition : function( el, styleCSS, speed, fncomplete, force ) {
var self = this;
setTimeout( function() {
$.fn.applyStyle = self.supportTransitions ? $.fn.css : $.fn.animate;
if( fncomplete && self.supportTransitions ) {
el.on( self.transEndEventName, fncomplete );
if( force ) {
fncomplete.call( el );
}
}
fncomplete = fncomplete || function() { return false; };
el.stop().applyStyle( styleCSS, $.extend( true, [], { duration : speed + 'ms', complete : fncomplete } ) );
}, 25 );
}
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.gridrotator = function( options ) {
var instance = $.data( this, 'gridrotator' );
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
if ( !instance ) {
logError( "cannot call methods on gridrotator prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for gridrotator instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'gridrotator', new $.GridRotator( options, this ) );
}
});
}
return instance;
};
} )( jQuery, window );
| JavaScript |
/**
* jquery.gridrotator.js v1.1.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2012, Codrops
* http://www.codrops.com
*/
;( function( $, window, undefined ) {
'use strict';
/*
* debouncedresize: special jQuery event that happens once after a window resize
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery-smartresize/blob/master/jquery.debouncedresize.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*/
var $event = $.event,
$special,
resizeTimeout;
$special = $event.special.debouncedresize = {
setup: function() {
$( this ).on( "resize", $special.handler );
},
teardown: function() {
$( this ).off( "resize", $special.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments,
dispatch = function() {
// set correct event type
event.type = "debouncedresize";
$event.dispatch.apply( context, args );
};
if ( resizeTimeout ) {
clearTimeout( resizeTimeout );
}
execAsap ?
dispatch() :
resizeTimeout = setTimeout( dispatch, $special.threshold );
},
threshold: 100
};
// http://www.hardcode.nl/subcategory_1/article_317-array-shuffle-function
Array.prototype.shuffle = function() {
var i=this.length,p,t;
while (i--) {
p = Math.floor(Math.random()*i);
t = this[i];
this[i]=this[p];
this[p]=t;
}
return this;
};
// HTML5 PageVisibility API
// http://www.html5rocks.com/en/tutorials/pagevisibility/intro/
// by Joe Marini (@joemarini)
function getHiddenProp(){
var prefixes = ['webkit','moz','ms','o'];
// if 'hidden' is natively supported just return it
if ('hidden' in document) return 'hidden';
// otherwise loop over all the known prefixes until we find one
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document)
return prefixes[i] + 'Hidden';
}
// otherwise it's not supported
return null;
}
function isHidden() {
var prop = getHiddenProp();
if (!prop) return false;
return document[prop];
}
function isEmpty( obj ) {
return Object.keys(obj).length === 0;
}
// global
var $window = $( window ),
Modernizr = window.Modernizr;
$.GridRotator = function( options, element ) {
this.$el = $( element );
if( Modernizr.backgroundsize ) {
var self = this;
this.$el.addClass( 'ri-grid-loading' );
this._init( options );
}
};
// the options
$.GridRotator.defaults = {
// number of rows
rows : 4,
// number of columns
columns : 10,
w1024 : { rows : 3, columns : 8 },
w768 : {rows : 3,columns : 7 },
w480 : {rows : 3,columns : 5 },
w320 : {rows : 2,columns : 4 },
w240 : {rows : 2,columns : 3 },
// step: number of items that are replaced at the same time
// random || [some number]
// note: for performance issues, the number "can't" be > options.maxStep
step : 'random',
// change it as you wish..
maxStep : 3,
// prevent user to click the items
preventClick : true,
// animation type
// showHide || fadeInOut ||
// slideLeft || slideRight || slideTop || slideBottom ||
// rotateBottom || rotateLeft || rotateRight || rotateTop ||
// scale ||
// rotate3d ||
// rotateLeftScale || rotateRightScale || rotateTopScale || rotateBottomScale ||
// random
animType : 'random',
// animation speed
animSpeed : 2000,
// animation easings
animEasingOut : 'linear',
animEasingIn: 'linear',
// the item(s) will be replaced every 3 seconds
// note: for performance issues, the time "can't" be < 300 ms
interval : 3000,
// if false the animations will not start
// use false if onhover is true for example
slideshow : true,
// if true the items will switch when hovered
onhover : false,
// ids of elements that shouldn't change
nochange : []
};
$.GridRotator.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.GridRotator.defaults, options );
// cache some elements + variables
this._config();
},
_config : function() {
var self = this,
transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
};
// support CSS transitions and 3d transforms
this.supportTransitions = Modernizr.csstransitions;
this.supportTransforms3D = Modernizr.csstransforms3d;
this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.gridrotator';
// all animation types for the random option
this.animTypes = this.supportTransforms3D ? [
'fadeInOut',
'slideLeft',
'slideRight',
'slideTop',
'slideBottom',
'rotateLeft',
'rotateRight',
'rotateTop',
'rotateBottom',
'scale',
'rotate3d',
'rotateLeftScale',
'rotateRightScale',
'rotateTopScale',
'rotateBottomScale' ] :
[ 'fadeInOut', 'slideLeft', 'slideRight', 'slideTop', 'slideBottom' ];
this.animType = this.options.animType;
if( this.animType !== 'random' && !this.supportTransforms3D && $.inArray( this.animType, this.animTypes ) === -1 && this.animType !== 'showHide' ) {
// fallback to 'fadeInOut' if user sets a type which is not supported
this.animType = 'fadeInOut';
}
this.animTypesTotal = this.animTypes.length;
// the <ul> where the items are placed
this.$list = this.$el.children( 'ul' );
// remove images and add background-image to anchors
// preload the images before
var loaded = 0,
$imgs = this.$list.find( 'img' ),
count = $imgs.length;
$imgs.each( function() {
var $img = $( this ), src = $img.attr( 'src' );
$( '<img/>' ).load( function() {
++loaded;
$img.parent().css( 'background-image', 'url(' + src + ')' );
if( loaded === count ) {
$imgs.remove();
self.$el.removeClass( 'ri-grid-loading' );
// the items
self.$items = self.$list.children( 'li' );
// make a copy of the items
self.$itemsCache = self.$items.clone();
// total number of items
self.itemsTotal = self.$items.length;
// the items that will be out of the grid
// actually the item's child (anchor element)
self.outItems= [];
self._layout( function() {
self._initEvents();
} );
// replace [options.step] items after [options.interval] time
// the items that go out are randomly chosen, while the ones that get in
// follow a "First In First Out" logic
self._start();
}
} ).attr( 'src', src )
} );
},
_layout : function( callback ) {
var self = this;
// sets the grid dimentions based on the container's width
this._setGridDim();
// reset
this.$list.empty();
this.$items = this.$itemsCache.clone().appendTo( this.$list );
var $outItems = this.$items.filter( ':gt(' + ( this.showTotal - 1 ) + ')' ),
$outAItems = $outItems.children( 'a' );
this.outItems.length = 0;
$outAItems.each( function( i ) {
self.outItems.push( $( this ) );
} );
$outItems.remove();
// container's width
var containerWidth = ( document.defaultView ) ? parseInt( document.defaultView.getComputedStyle( this.$el.get( 0 ), null ).width ) : this.$el.width(),
// item's width
itemWidth = Math.floor( containerWidth / this.columns ),
// calculate gap
gapWidth = containerWidth - ( this.columns * Math.floor( itemWidth ) );
for( var i = 0; i < this.rows; ++i ) {
for( var j = 0; j < this.columns; ++j ) {
var idx = this.columns * i + j,
$item = this.$items.eq( idx );
$item.css( {
width : j < Math.floor( gapWidth ) ? itemWidth + 1 : itemWidth,
height : itemWidth
} );
if( $.inArray( idx, this.options.nochange ) !== -1 ) {
$item.addClass( 'ri-nochange' ).data( 'nochange', true );
}
}
}
if( this.options.preventClick ) {
this.$items.children().css( 'cursor', 'default' ).on( 'click.gridrotator', false );
}
if( callback ) {
callback.call();
}
},
// set the grid rows and columns
_setGridDim : function() {
// container's width
var c_w = this.$el.width();
// we will choose the number of rows/columns according to the container's width and the values set in the plugin options
switch( true ) {
case ( c_w < 240 ) : this.rows = this.options.w240.rows; this.columns = this.options.w240.columns; break;
case ( c_w < 320 ) : this.rows = this.options.w320.rows; this.columns = this.options.w320.columns; break;
case ( c_w < 480 ) : this.rows = this.options.w480.rows; this.columns = this.options.w480.columns; break;
case ( c_w < 768 ) : this.rows = this.options.w768.rows; this.columns = this.options.w768.columns; break;
case ( c_w < 1024 ) : this.rows = this.options.w1024.rows; this.columns = this.options.w1024.columns; break;
default : this.rows = this.options.rows; this.columns = this.options.columns; break;
}
this.showTotal = this.rows * this.columns;
},
// init window resize event
_initEvents : function() {
var self = this;
$window.on( 'debouncedresize.gridrotator', function() {
self._layout();
} );
// use the property name to generate the prefixed event name
var visProp = getHiddenProp();
// HTML5 PageVisibility API
// http://www.html5rocks.com/en/tutorials/pagevisibility/intro/
// by Joe Marini (@joemarini)
if (visProp) {
var evtname = visProp.replace(/[H|h]idden/,'') + 'visibilitychange';
document.addEventListener(evtname, function() { self._visChange(); } );
}
if( !Modernizr.touch && this.options.onhover ) {
self.$items.on( 'mouseenter.gridrotator', function() {
var $item = $( this );
if( !$item.data( 'active' ) && !$item.data( 'hovered' ) && !$item.data( 'nochange' ) ) {
$item.data( 'hovered', true );
self._replace( $item );
}
} ).on( 'mouseleave.gridrotator', function() {
$( this ).data( 'hovered', false );
} );
}
},
_visChange : function() {
isHidden() ? clearTimeout( this.playtimeout ) : this._start();
},
// start rotating elements
_start : function() {
if( this.showTotal < this.itemsTotal && this.options.slideshow ) {
this._showNext();
}
},
// get which type of animation
_getAnimType : function() {
return this.animType === 'random' ? this.animTypes[ Math.floor( Math.random() * this.animTypesTotal ) ] : this.animType;
},
// get css properties for the transition effect
_getAnimProperties : function( $out ) {
var startInProp = {}, startOutProp = {}, endInProp = {}, endOutProp = {},
animType = this._getAnimType(), speed, delay = 0;
switch( animType ) {
case 'showHide' :
speed = 0;
endOutProp.opacity = 0;
break;
case 'fadeInOut' :
endOutProp.opacity = 0;
break;
case 'slideLeft' :
startInProp.left = $out.width();
endInProp.left = 0;
endOutProp.left = -$out.width();
break;
case 'slideRight' :
startInProp.left = -$out.width();
endInProp.left = 0;
endOutProp.left = $out.width();
break;
case 'slideTop' :
startInProp.top = $out.height();
endInProp.top = 0;
endOutProp.top = -$out.height();
break;
case 'slideBottom' :
startInProp.top = -$out.height();
endInProp.top = 0;
endOutProp.top = $out.height();
break;
case 'rotateLeft' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'rotateY(90deg)';
endInProp.transform = 'rotateY(0deg)';
delay = speed;
endOutProp.transform = 'rotateY(-90deg)';
break;
case 'rotateRight' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'rotateY(-90deg)';
endInProp.transform = 'rotateY(0deg)';
delay = speed;
endOutProp.transform = 'rotateY(90deg)';
break;
case 'rotateTop' :
speed = this.options.animSpeed / 2;
startInProp.transform= 'rotateX(90deg)';
endInProp.transform = 'rotateX(0deg)';
delay = speed;
endOutProp.transform = 'rotateX(-90deg)';
break;
case 'rotateBottom' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'rotateX(-90deg)';
endInProp.transform = 'rotateX(0deg)';
delay = speed;
endOutProp.transform = 'rotateX(90deg)';
break;
case 'scale' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0)';
startOutProp.transform = 'scale(1)';
endInProp.transform = 'scale(1)';
delay = speed;
endOutProp.transform = 'scale(0)';
break;
case 'rotateLeftScale' :
startOutProp.transform = 'scale(1)';
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0.3) rotateY(90deg)';
endInProp.transform = 'scale(1) rotateY(0deg)';
delay = speed;
endOutProp.transform = 'scale(0.3) rotateY(-90deg)';
break;
case 'rotateRightScale' :
startOutProp.transform = 'scale(1)';
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0.3) rotateY(-90deg)';
endInProp.transform = 'scale(1) rotateY(0deg)';
delay = speed;
endOutProp.transform = 'scale(0.3) rotateY(90deg)';
break;
case 'rotateTopScale' :
startOutProp.transform = 'scale(1)';
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0.3) rotateX(90deg)';
endInProp.transform = 'scale(1) rotateX(0deg)';
delay = speed;
endOutProp.transform = 'scale(0.3) rotateX(-90deg)';
break;
case 'rotateBottomScale' :
startOutProp.transform = 'scale(1)';
speed = this.options.animSpeed / 2;
startInProp.transform = 'scale(0.3) rotateX(-90deg)';
endInProp.transform = 'scale(1) rotateX(0deg)';
delay = speed;
endOutProp.transform = 'scale(0.3) rotateX(90deg)';
break;
case 'rotate3d' :
speed = this.options.animSpeed / 2;
startInProp.transform = 'rotate3d( 1, 1, 0, 90deg )';
endInProp.transform = 'rotate3d( 1, 1, 0, 0deg )';
delay = speed;
endOutProp.transform = 'rotate3d( 1, 1, 0, -90deg )';
break;
}
return {
startInProp : startInProp,
startOutProp : startOutProp,
endInProp : endInProp,
endOutProp : endOutProp,
delay : delay,
animSpeed : speed != undefined ? speed : this.options.animSpeed
};
},
// show next [option.step] elements
_showNext : function( time ) {
var self = this;
clearTimeout( this.playtimeout );
this.playtimeout = setTimeout( function() {
var step = self.options.step, max= self.options.maxStep, min = 1;
if( max > self.showTotal ) {
max = self.showTotal;
}
// number of items to swith at this point of time
var nmbOut = step === 'random' ? Math.floor( Math.random() * max + min ) : Math.min( Math.abs( step ) , max ) ,
// array with random indexes. These will be the indexes of the items we will replace
randArr = self._getRandom( nmbOut, self.showTotal );
for( var i = 0; i < nmbOut; ++i ) {
// element to go out
var $out = self.$items.eq( randArr[ i ] );
// if element is active, which means it is currently animating,
// then we need to get different positions..
if( $out.data( 'active' ) || $out.data( 'nochange' ) ) {
// one of the items is active, call again..
self._showNext( 1 );
return false;
}
self._replace( $out );
}
// again and again..
self._showNext();
}, time || Math.max( Math.abs( this.options.interval ) , 300 ) );
},
_replace : function( $out ) {
$out.data( 'active', true );
var self = this,
$outA = $out.children( 'a:last' ),
newElProp = {
width : $outA.width(),
height : $outA.height()
};
// element stays active
$out.data( 'active', true );
// get the element (anchor) that will go in (first one inserted in this.outItems)
var $inA = this.outItems.shift();
// save element that went out
this.outItems.push( $outA.clone().css( 'transition', 'none' ) );
// prepend in element
$inA.css( newElProp ).prependTo( $out );
var animProp = this._getAnimProperties( $outA );
$inA.css( animProp.startInProp );
$outA.css( animProp.startOutProp );
this._setTransition( $inA, 'all', animProp.animSpeed, animProp.delay, this.options.animEasingIn );
this._setTransition( $outA, 'all', animProp.animSpeed, 0, this.options.animEasingOut );
this._applyTransition( $inA, animProp.endInProp, animProp.animSpeed, function() {
var $el = $( this ),
t = animProp.animSpeed === self.options.animSpeed && isEmpty( animProp.endInProp ) ? animProp.animSpeed : 0;
setTimeout( function() {
if( self.supportTransitions ) {
$el.off( self.transEndEventName );
}
$el.next().remove();
$el.parent().data( 'active', false );
}, t );
}, animProp.animSpeed === 0 || isEmpty( animProp.endInProp ) );
this._applyTransition( $outA, animProp.endOutProp, animProp.animSpeed );
},
_getRandom : function( cnt, limit ) {
var randArray = [];
for( var i = 0; i < limit; ++i ) {
randArray.push( i )
}
return randArray.shuffle().slice( 0, cnt );
},
_setTransition : function( el, prop, speed, delay, easing ) {
setTimeout( function() {
el.css( 'transition', prop + ' ' + speed + 'ms ' + delay + 'ms ' + easing );
}, 25 );
},
_applyTransition : function( el, styleCSS, speed, fncomplete, force ) {
var self = this;
setTimeout( function() {
$.fn.applyStyle = self.supportTransitions ? $.fn.css : $.fn.animate;
if( fncomplete && self.supportTransitions ) {
el.on( self.transEndEventName, fncomplete );
if( force ) {
fncomplete.call( el );
}
}
fncomplete = fncomplete || function() { return false; };
el.stop().applyStyle( styleCSS, $.extend( true, [], { duration : speed + 'ms', complete : fncomplete } ) );
}, 25 );
}
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.gridrotator = function( options ) {
var instance = $.data( this, 'gridrotator' );
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
if ( !instance ) {
logError( "cannot call methods on gridrotator prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for gridrotator instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'gridrotator', new $.GridRotator( options, this ) );
}
});
}
return instance;
};
} )( jQuery, window );
| JavaScript |
$(function(){
$('#recslide').show();
var recslide_gone_in=false;
var bts_scroll_lock=false;
$(window).scroll(function()
{
if(bts_scroll_lock)return;
if(recslide_gone_in==false)$('#recslide .expand').hide();
if(document.getElementById("recslide_place_holder")){
var distanceTop=$('#recslide_place_holder').offset().top-$(window).height();
}
else {
var distanceTop = $(document).height() - $(window).height();
}
if($(window).scrollTop()>=distanceTop)
{
if(recslide_gone_in==false)
{
$('#recslide').animate({'right':'0px','bottom':'0px'},300)
}
else $('#recslide').animate({'bottom':'-80px','right':'0px'},300)
}
else $('#recslide').stop(true).animate({'right':'-430px','bottom':'0px'},300)});
$('#recslide .help').bind('click', function ()
{
try{
location.href='http://24work.blogspot.com';
}
catch(err){}});
$('#recslide .close').bind('click',function()
{bts_scroll_lock=true;$('#recslide').stop(true).animate({'bottom':'-80px'},300);bts_scroll_lock=false;recslide_gone_in=true;$('#recslide .expand').show();$('#recslide .close').hide()});$('#recslide .expand').bind('click',function(){$('#recslide .expand').hide();$('#recslide').stop(true).animate({'bottom':'0px'},300);recslide_gone_in=false;$('#recslide .close').show()})});
var recslideprocessJson=function(json,status){
if(json.feed.entry)var randomNum=Math.ceil(Math.random()*json.feed.openSearch$totalResults.$t);$.ajax({url:'/feeds/posts/summary',data:{'max-results':'2','alt':'json-in-script','start-index':randomNum},success:recslideprocessRecommendation,dataType:'jsonp',cache:true})};$.ajax({url:'/feeds/posts/summary',data:{'max-results':'1','alt':'json-in-script'},success:recslideprocessJson,dataType:'jsonp',cache:true});
var recslideprocessRecommendation=function(json,status){
try{
if(json.feed.entry){
for(var i=0;i<json.feed.entry.length;i++){
var entry=json.feed.entry[i];var url='';
for(var k=0;k<entry.link.length;k++){
if(entry.link[k].rel=='alternate'){url=entry.link[k].href;break}};
var title=entry.title.$t;
if(location.href.indexOf(url)==-1)
{
try{var thumbUrl='';thumbUrl=entry.media$thumbnail.url;$('#recslide_image').html('<img src="'+thumbUrl+'" class="image" title="'+title+'" />')}
catch(errr){}
var link=$('<a>');
link.attr('title',title);link.text(title);link.attr('href',url);
$('#recslide_title').empty();
link.appendTo($('#recslide_title'));
$('#share_box').empty();
$('#share_box').html('<table border="0" ><tr><td><a href="https://twitter.com/share" class="twitter-share-button" data-url="'+url+'" data-text="'+title+'">Tweet</a><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script></td><td><iframe src="//www.facebook.com/plugins/like.php?href='+url+'&send=false&layout=button_count&width=80&show_faces=true&action=like&colorscheme=light&font=verdana&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:21px;" allowTransparency="true"></iframe></td></tr></table>');
return
}}}}
catch(error){$('#recslide_title').html('<p>Sorry! Some error occurred while fetching the Blog Feed.</p>')}
}; | JavaScript |
//<![CDATA[
/* ------------------------------------------------------------------------
s3Slider
Developped By: Boban Karišik -> http://www.serie3.info/
CSS Help: Mészáros Róbert -> http://www.perspectived.com/
Version: 1.0
Copyright: Feel free to redistribute the script/modify it, as
long as you leave my infos at the top.
-------------------------------------------------------------------------- */
(function($){
$.fn.s3Slider = function(vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#" + element[0].id + "Content ." + element[0].id + "Image");
var itemsSpan = $("#" + element[0].id + "Content ." + element[0].id + "Image span");
items.each(function(i) {
$(items[i]).mouseover(function() {
mOver = true;
});
$(items[i]).mouseout(function() {
mOver = false;
fadeElement(true);
});
});
var fadeElement = function(isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if(items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut);
} else {
console.log("Poof..");
}
}
var makeSlider = function() {
current = (current != null) ? current : items[(items.length-1)];
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if(faderStat == true) {
if(!mOver) {
$(items[currNo]).fadeIn((timeOut/6), function() {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
} else {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
}
});
}
} else {
if(!mOver) {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
} else {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
}
}
}
}
makeSlider();
};
})(jQuery);
//]]> | JavaScript |
//<![CDATA[
//** Featured Content Slider script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
//** May 2nd, 08'- Script rewritten and updated to 2.0.
//** June 12th, 08'- Script updated to v 2.3, which adds the following features:
//1) Changed behavior of script to actually collapse the previous content when the active one is shown, instead of just tucking it underneath the later.
//2) Added setting to reveal a content either via "click" or "mouseover" of pagination links (default is former).
//3) Added public function for jumping to a particular slide within a Featured Content instance using an arbitrary link, for example.
//** July 11th, 08'- Script updated to v 2.4:
//1) Added ability to select a particular slide when the page first loads using a URL parameter (ie: mypage.htm?myslider=4 to select 4th slide in "myslider")
//2) Fixed bug where the first slide disappears when the mouse clicks or mouses over it when page first loads.
var featuredcontentslider={
//3 variables below you can customize if desired:
ajaxloadingmsg: '<div style="margin: 20px 0 0 20px"><img src="loading.gif" /> Fetching slider Contents. Please wait...</div>',
bustajaxcache: true, //bust caching of external ajax page after 1st request?
enablepersist: true, //persist to last content viewed when returning to page?
settingcaches: {}, //object to cache "setting" object of each script instance
jumpTo:function(fcsid, pagenumber){ //public function to go to a slide manually.
this.turnpage(this.settingcaches[fcsid], pagenumber)
},
ajaxconnect:function(setting){
var page_request = false
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else
return false
var pageurl=setting.contentsource[1]
page_request.onreadystatechange=function(){
featuredcontentslider.ajaxpopulate(page_request, setting)
}
document.getElementById(setting.id).innerHTML=this.ajaxloadingmsg
var bustcache=(!this.bustajaxcache)? "" : (pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', pageurl+bustcache, true)
page_request.send(null)
},
ajaxpopulate:function(page_request, setting){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
document.getElementById(setting.id).innerHTML=page_request.responseText
this.buildpaginate(setting)
}
},
buildcontentdivs:function(setting){
var alldivs=document.getElementById(setting.id).getElementsByTagName("div")
for (var i=0; i<alldivs.length; i++){
if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv"
setting.contentdivs.push(alldivs[i])
alldivs[i].style.display="none" //collapse all content DIVs to begin with
}
}
},
buildpaginate:function(setting){
this.buildcontentdivs(setting)
var sliderdiv=document.getElementById(setting.id)
var pdiv=document.getElementById("paginate-"+setting.id)
var phtml=""
var toc=setting.toc
var nextprev=setting.nextprev
if (typeof toc=="string" && toc!="markup" || typeof toc=="object"){
for (var i=1; i<=setting.contentdivs.length; i++){
phtml+='<a href="#'+i+'" class="toc">'+(typeof toc=="string"? toc.replace(/#increment/, i) : toc[i-1])+'</a> '
}
phtml=(nextprev[0]!=''? '<a href="#prev" class="prev">'+nextprev[0]+'</a> ' : '') + phtml + (nextprev[1]!=''? '<a href="#next" class="next">'+nextprev[1]+'</a>' : '')
pdiv.innerHTML=phtml
}
var pdivlinks=pdiv.getElementsByTagName("a")
var toclinkscount=0 //var to keep track of actual # of toc links
for (var i=0; i<pdivlinks.length; i++){
if (this.css(pdivlinks[i], "toc", "check")){
if (toclinkscount>setting.contentdivs.length-1){ //if this toc link is out of range (user defined more toc links then there are contents)
pdivlinks[i].style.display="none" //hide this toc link
continue
}
pdivlinks[i].setAttribute("rel", ++toclinkscount) //store page number inside toc link
pdivlinks[i][setting.revealtype]=function(){
featuredcontentslider.turnpage(setting, this.getAttribute("rel"))
return false
}
setting.toclinks.push(pdivlinks[i])
}
else if (this.css(pdivlinks[i], "prev", "check") || this.css(pdivlinks[i], "next", "check")){ //check for links with class "prev" or "next"
pdivlinks[i].onclick=function(){
featuredcontentslider.turnpage(setting, this.className)
return false
}
}
}
this.turnpage(setting, setting.currentpage, true)
if (setting.autorotate[0]){ //if auto rotate enabled
pdiv[setting.revealtype]=function(){
featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id])
}
sliderdiv["onclick"]=function(){ //stop content slider when slides themselves are clicked on
featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id])
}
setting.autorotate[1]=setting.autorotate[1]+(1/setting.enablefade[1]*50) //add time to run fade animation (roughly) to delay between rotation
this.autorotate(setting)
}
},
urlparamselect:function(fcsid){
var result=window.location.search.match(new RegExp(fcsid+"=(\\d+)", "i")) //check for "?featuredcontentsliderid=2" in URL
return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index
},
turnpage:function(setting, thepage, autocall){
var currentpage=setting.currentpage //current page # before change
var totalpages=setting.contentdivs.length
var turntopage=(/prev/i.test(thepage))? currentpage-1 : (/next/i.test(thepage))? currentpage+1 : parseInt(thepage)
turntopage=(turntopage<1)? totalpages : (turntopage>totalpages)? 1 : turntopage //test for out of bound and adjust
if (turntopage==setting.currentpage && typeof autocall=="undefined") //if a pagination link is clicked on repeatedly
return
setting.currentpage=turntopage
setting.contentdivs[turntopage-1].style.zIndex=++setting.topzindex
this.cleartimer(setting, window["fcsfade"+setting.id])
setting.cacheprevpage=setting.prevpage
if (setting.enablefade[0]==true){
setting.curopacity=0
this.fadeup(setting)
}
if (setting.enablefade[0]==false){ //if fade is disabled, fire onChange event immediately (verus after fade is complete)
setting.contentdivs[setting.prevpage-1].style.display="none" //collapse last content div shown (it was set to "block")
setting.onChange(setting.prevpage, setting.currentpage)
}
setting.contentdivs[turntopage-1].style.visibility="visible"
setting.contentdivs[turntopage-1].style.display="block"
if (setting.prevpage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted)
this.css(setting.toclinks[setting.prevpage-1], "selected", "remove")
if (turntopage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted)
this.css(setting.toclinks[turntopage-1], "selected", "add")
setting.prevpage=turntopage
if (this.enablepersist)
this.setCookie("fcspersist"+setting.id, turntopage)
},
setopacity:function(setting, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between)
var targetobject=setting.contentdivs[setting.currentpage-1]
if (targetobject.filters && targetobject.filters[0]){ //IE syntax
if (typeof targetobject.filters[0].opacity=="number") //IE6
targetobject.filters[0].opacity=value*100
else //IE 5.5
targetobject.style.filter="alpha(opacity="+value*100+")"
}
else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
targetobject.style.MozOpacity=value
else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
targetobject.style.opacity=value
setting.curopacity=value
},
fadeup:function(setting){
if (setting.curopacity<1){
this.setopacity(setting, setting.curopacity+setting.enablefade[1])
window["fcsfade"+setting.id]=setTimeout(function(){featuredcontentslider.fadeup(setting)}, 50)
}
else{ //when fade is complete
if (setting.cacheprevpage!=setting.currentpage) //if previous content isn't the same as the current shown div (happens the first time the page loads/ script is run)
setting.contentdivs[setting.cacheprevpage-1].style.display="none" //collapse last content div shown (it was set to "block")
setting.onChange(setting.cacheprevpage, setting.currentpage)
}
},
cleartimer:function(setting, timervar){
if (typeof timervar!="undefined"){
clearTimeout(timervar)
clearInterval(timervar)
if (setting.cacheprevpage!=setting.currentpage){ //if previous content isn't the same as the current shown div
setting.contentdivs[setting.cacheprevpage-1].style.display="none"
}
}
},
css:function(el, targetclass, action){
var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig")
if (action=="check")
return needle.test(el.className)
else if (action=="remove")
el.className=el.className.replace(needle, "")
else if (action=="add")
el.className+=" "+targetclass
},
autorotate:function(setting){
window["fcsautorun"+setting.id]=setInterval(function(){featuredcontentslider.turnpage(setting, "next")}, setting.autorotate[1])
},
getCookie:function(Name){
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
},
setCookie:function(name, value){
document.cookie = name+"="+value
},
init:function(setting){
var persistedpage=this.getCookie("fcspersist"+setting.id) || 1
var urlselectedpage=this.urlparamselect(setting.id) //returns null or index from: mypage.htm?featuredcontentsliderid=index
this.settingcaches[setting.id]=setting //cache "setting" object
setting.contentdivs=[]
setting.toclinks=[]
setting.topzindex=0
setting.currentpage=urlselectedpage || ((this.enablepersist)? persistedpage : 1)
setting.prevpage=setting.currentpage
setting.revealtype="on"+(setting.revealtype || "click")
setting.curopacity=0
setting.onChange=setting.onChange || function(){}
if (setting.contentsource[0]=="inline")
this.buildpaginate(setting)
if (setting.contentsource[0]=="ajax")
this.ajaxconnect(setting)
}
}
//]]> | JavaScript |
//<![CDATA[
//Featured Content Glider: By http://www.dynamicdrive.com
//Created: Dec 22nd, 07'
//Updated (Jan 29th, 08): Added four possible slide directions: "updown", "downup", "leftright", or "rightleft"
//Updated (Feb 1st, 08): Changed glide behavior to reverse direction when previous button is clicked
//Updated (Feb 12th, 08): Added ability to retrieve gliding contents from an external file using Ajax ("remotecontent" variable added to configuration)
var featuredcontentglider={
csszindex: 100,
ajaxloadingmsg: '<b>Fetching Content. Please wait...</b>',
glide:function(config, showpage, isprev){
var selected=parseInt(showpage)
if (selected>=config.$contentdivs.length){ //if no content exists at this index position
alert("No content exists at page "+(selected+1)+"! Loading 1st page instead.")
selected=0
}
var $target=config.$contentdivs.eq(selected)
//Test for toggler not being initialized yet, or user clicks on the currently selected page):
if (config.$togglerdiv.attr('lastselected')==null || parseInt(config.$togglerdiv.attr('lastselected'))!=selected){
var $selectedlink=config.$toc.eq(selected)
config.$next.attr('loadpage', (selected<config.$contentdivs.length-1)? selected+1+'pg' : 0+'pg')
config.$prev.attr('loadpage', (selected==0)? config.$contentdivs.length-1+'pg' : selected-1+'pg')
var startpoint=(isprev=="previous")? -config.startpoint : config.startpoint
$target.css(config.leftortop, startpoint).css("zIndex", this.csszindex++) //hide content so it's just out of view before animating it
var endpoint=(config.leftortop=="left")? {left:0} : {top:0} //animate it into view
$target.animate(endpoint, config.speed)
config.$toc.removeClass('selected')
$selectedlink.addClass('selected')
config.$togglerdiv.attr('lastselected', selected+'pg')
}
},
getremotecontent:function(config){
config.$glider.html(this.ajaxloadingmsg)
$.ajax({
url: config.remotecontent,
error:function(ajaxrequest){
config.$glider.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
},
success:function(content){
config.$glider.html(content)
featuredcontentglider.setuptoggler(config)
}
})
},
aligncontents:function(config){
config.$contentdivs=$("#"+config.gliderid+" ."+config.contentclass)
config.$contentdivs.css(config.leftortop, config.startpoint).css({height: config.$glider.height(), visibility: 'visible'}) //position content divs so they're out of view:
},
setuptoggler:function(config){
this.aligncontents(config)
config.$togglerdiv.hide()
config.$toc.each(function(index){
$(this).attr('pagenumber', index+'pg')
if (index > (config.$contentdivs.length-1))
$(this).css({display: 'none'}) //hide redundant "toc" links
})
var $nextandprev=$("#"+config.togglerid+" .next, #"+config.togglerid+" .prev")
$nextandprev.click(function(event){ //Assign click behavior to 'next' and 'prev' links
featuredcontentglider.glide(config, this.getAttribute('loadpage'), this.getAttribute('buttontype'))
event.preventDefault() //cancel default link action
})
config.$toc.click(function(event){ //Assign click behavior to 'toc' links
featuredcontentglider.glide(config, this.getAttribute('pagenumber'))
event.preventDefault()
})
config.$togglerdiv.fadeIn(1000, function(){
featuredcontentglider.glide(config, config.selected)
if (config.autorotate==true){ //auto rotate contents?
config.stepcount=0 //set steps taken
config.totalsteps=config.$contentdivs.length*config.autorotateconfig[1] //Total steps limit: num of contents x num of user specified cycles)
featuredcontentglider.autorotate(config)
}
})
config.$togglerdiv.click(function(){
featuredcontentglider.cancelautorotate(config.togglerid)
})
},
autorotate:function(config){
var rotatespeed=config.speed+config.autorotateconfig[0]
window[config.togglerid+"timer"]=setInterval(function(){
if (config.totalsteps>0 && config.stepcount>=config.totalsteps){
clearInterval(window[config.togglerid+"timer"])
}
else{
config.$next.click()
config.stepcount++
}
}, rotatespeed)
},
cancelautorotate:function(togglerid){
if (window[togglerid+"timer"])
clearInterval(window[togglerid+"timer"])
},
getCookie:function(Name){
var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
},
setCookie:function(name, value){
document.cookie = name+"="+value
},
init:function(config){
$(document).ready(function(){
config.$glider=$("#"+config.gliderid)
config.$togglerdiv=$("#"+config.togglerid)
config.$toc=config.$togglerdiv.children('.toc')
config.$next=config.$togglerdiv.children('.next')
config.$prev=config.$togglerdiv.children('.prev')
config.$prev.attr('buttontype', 'previous')
var selected=(config.persiststate)? featuredcontentglider.getCookie(config.gliderid) : config.selected
config.selected=(isNaN(parseInt(selected))) ? config.selected : selected //test for cookie value containing null (1st page load) or "undefined" string
config.leftortop=(/up/i.test(config.direction))? "top" : "left" //set which CSS property to manipulate based on "direction"
config.heightorwidth=(/up/i.test(config.direction))? config.$glider.height() : config.$glider.width() //Get glider height or width based on "direction"
config.startpoint=(/^(left|up)/i.test(config.direction))? -config.heightorwidth : config.heightorwidth //set initial position of contents based on "direction"
if (typeof config.remotecontent!="undefined" && config.remotecontent.length>0)
featuredcontentglider.getremotecontent(config)
else
featuredcontentglider.setuptoggler(config)
$(window).bind('unload', function(){ //clean up and persist
config.$togglerdiv.unbind('click')
config.$toc.unbind('click')
config.$next.unbind('click')
config.$prev.unbind('click')
if (config.persiststate)
featuredcontentglider.setCookie(config.gliderid, config.$togglerdiv.attr('lastselected'))
config=null
})
})
}
}
//]]> | JavaScript |
//<![CDATA[
//Featured Content Glider: By http://www.dynamicdrive.com
//Created: Dec 22nd, 07'
//Updated (Jan 29th, 08): Added four possible slide directions: "updown", "downup", "leftright", or "rightleft"
//Updated (Feb 1st, 08): Changed glide behavior to reverse direction when previous button is clicked
//Updated (Feb 12th, 08): Added ability to retrieve gliding contents from an external file using Ajax ("remotecontent" variable added to configuration)
var featuredcontentglider={
csszindex: 100,
ajaxloadingmsg: '<b>Fetching Content. Please wait...</b>',
glide:function(config, showpage, isprev){
var selected=parseInt(showpage)
if (selected>=config.$contentdivs.length){ //if no content exists at this index position
alert("No content exists at page "+(selected+1)+"! Loading 1st page instead.")
selected=0
}
var $target=config.$contentdivs.eq(selected)
//Test for toggler not being initialized yet, or user clicks on the currently selected page):
if (config.$togglerdiv.attr('lastselected')==null || parseInt(config.$togglerdiv.attr('lastselected'))!=selected){
var $selectedlink=config.$toc.eq(selected)
config.$next.attr('loadpage', (selected<config.$contentdivs.length-1)? selected+1+'pg' : 0+'pg')
config.$prev.attr('loadpage', (selected==0)? config.$contentdivs.length-1+'pg' : selected-1+'pg')
var startpoint=(isprev=="previous")? -config.startpoint : config.startpoint
$target.css(config.leftortop, startpoint).css("zIndex", this.csszindex++) //hide content so it's just out of view before animating it
var endpoint=(config.leftortop=="left")? {left:0} : {top:0} //animate it into view
$target.animate(endpoint, config.speed)
config.$toc.removeClass('selected')
$selectedlink.addClass('selected')
config.$togglerdiv.attr('lastselected', selected+'pg')
}
},
getremotecontent:function(config){
config.$glider.html(this.ajaxloadingmsg)
$.ajax({
url: config.remotecontent,
error:function(ajaxrequest){
config.$glider.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
},
success:function(content){
config.$glider.html(content)
featuredcontentglider.setuptoggler(config)
}
})
},
aligncontents:function(config){
config.$contentdivs=$("#"+config.gliderid+" ."+config.contentclass)
config.$contentdivs.css(config.leftortop, config.startpoint).css({height: config.$glider.height(), visibility: 'visible'}) //position content divs so they're out of view:
},
setuptoggler:function(config){
this.aligncontents(config)
config.$togglerdiv.hide()
config.$toc.each(function(index){
$(this).attr('pagenumber', index+'pg')
if (index > (config.$contentdivs.length-1))
$(this).css({display: 'none'}) //hide redundant "toc" links
})
var $nextandprev=$("#"+config.togglerid+" .next, #"+config.togglerid+" .prev")
$nextandprev.click(function(event){ //Assign click behavior to 'next' and 'prev' links
featuredcontentglider.glide(config, this.getAttribute('loadpage'), this.getAttribute('buttontype'))
event.preventDefault() //cancel default link action
})
config.$toc.click(function(event){ //Assign click behavior to 'toc' links
featuredcontentglider.glide(config, this.getAttribute('pagenumber'))
event.preventDefault()
})
config.$togglerdiv.fadeIn(1000, function(){
featuredcontentglider.glide(config, config.selected)
if (config.autorotate==true){ //auto rotate contents?
config.stepcount=0 //set steps taken
config.totalsteps=config.$contentdivs.length*config.autorotateconfig[1] //Total steps limit: num of contents x num of user specified cycles)
featuredcontentglider.autorotate(config)
}
})
config.$togglerdiv.click(function(){
featuredcontentglider.cancelautorotate(config.togglerid)
})
},
autorotate:function(config){
var rotatespeed=config.speed+config.autorotateconfig[0]
window[config.togglerid+"timer"]=setInterval(function(){
if (config.totalsteps>0 && config.stepcount>=config.totalsteps){
clearInterval(window[config.togglerid+"timer"])
}
else{
config.$next.click()
config.stepcount++
}
}, rotatespeed)
},
cancelautorotate:function(togglerid){
if (window[togglerid+"timer"])
clearInterval(window[togglerid+"timer"])
},
getCookie:function(Name){
var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
},
setCookie:function(name, value){
document.cookie = name+"="+value
},
init:function(config){
$(document).ready(function(){
config.$glider=$("#"+config.gliderid)
config.$togglerdiv=$("#"+config.togglerid)
config.$toc=config.$togglerdiv.children('.toc')
config.$next=config.$togglerdiv.children('.next')
config.$prev=config.$togglerdiv.children('.prev')
config.$prev.attr('buttontype', 'previous')
var selected=(config.persiststate)? featuredcontentglider.getCookie(config.gliderid) : config.selected
config.selected=(isNaN(parseInt(selected))) ? config.selected : selected //test for cookie value containing null (1st page load) or "undefined" string
config.leftortop=(/up/i.test(config.direction))? "top" : "left" //set which CSS property to manipulate based on "direction"
config.heightorwidth=(/up/i.test(config.direction))? config.$glider.height() : config.$glider.width() //Get glider height or width based on "direction"
config.startpoint=(/^(left|up)/i.test(config.direction))? -config.heightorwidth : config.heightorwidth //set initial position of contents based on "direction"
if (typeof config.remotecontent!="undefined" && config.remotecontent.length>0)
featuredcontentglider.getremotecontent(config)
else
featuredcontentglider.setuptoggler(config)
$(window).bind('unload', function(){ //clean up and persist
config.$togglerdiv.unbind('click')
config.$toc.unbind('click')
config.$next.unbind('click')
config.$prev.unbind('click')
if (config.persiststate)
featuredcontentglider.setCookie(config.gliderid, config.$togglerdiv.attr('lastselected'))
config=null
})
})
}
}
//]]> | JavaScript |
//<![CDATA[
function rp(json) {
for (var i = startposts; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
posttitle = posttitle.link(posturl);
var readmorelink = "(Read More)";
readmorelink = readmorelink.link(posturl);
var postdate = entry.published.$t;
var cdyear = postdate.substring(0,4);
var cdmonth = postdate.substring(5,7);
var cdday = postdate.substring(8,10);
var monthnames = new Array();
monthnames[1] = "Jan";
monthnames[2] = "Feb";
monthnames[3] = "Mar";
monthnames[4] = "Apr";
monthnames[5] = "May";
monthnames[6] = "Jun";
monthnames[7] = "Jul";
monthnames[8] = "Aug";
monthnames[9] = "Sep";
monthnames[10] = "Oct";
monthnames[11] = "Nov";
monthnames[12] = "Dec";
if ("content" in entry) {
var postcontent = entry.content.$t;
} else if ("summary" in entry) {
var postcontent = entry.summary.$t;
} else
var postcontent = "";
var re = /<\S[^>]*>/g;
postcontent = postcontent.replace(re, "");
if (showposttitle == true) document.write(posttitle);
if (showpostdate == true) document.write(' - ' + monthnames[parseInt(cdmonth,10)] + ' ' + cdday);
if (showpostsummary == true) {
if (postcontent.length < numchars) {
document.write(postcontent);
} else {
postcontent = postcontent.substring(0, numchars);
var quoteEnd = postcontent.lastIndexOf(" ");
postcontent = postcontent.substring(0,quoteEnd);
document.write(postcontent);
document.write('...' + readmorelink);
}
}
}
}
//]]> | JavaScript |
//<![CDATA[
/*
* jScroller 0.3 - Scroller Script
*
* Copyright (c) 2007 Markus Bordihn (http://markusbordihn.de)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* $Date: 2007-11-15 13:00:00 +0100 (Thu, 15 Nov 2007) $
* $Rev: 0.3 $
*/
$(document).ready(function(){
this.defaults = {
scroller: {
interval: 0, // Dont touch !
refresh: 150, // Refresh Time in ms
direction: "left", // down,right,left,up
speed: 5, // Set the Scroller Speed
id: "#scroller",
cont_id: "#scroller_container"
}
}
var jscroller_config = $.extend(this.defaults), jscroller_scroller = $(jscroller_config.scroller.id), jscroller_scroller_cont = $(jscroller_config.scroller.cont_id);
if (jscroller_scroller && jscroller_scroller_cont) {
jscroller_scroller.css({position: 'absolute', left: 0, top: 0});
jscroller_init();
}
function jscroller_startScroll() {
if(!jscroller_config.scroller.interval) {
jscroller_config.scroller.interval=window.setInterval(jscroller_doScroll,jscroller_config.scroller.refresh);
}
}
function jscroller_stopScroll() {
if (jscroller_config.scroller.interval) {
window.clearInterval(jscroller_config.scroller.interval);
jscroller_config.scroller.interval=0;
}
}
function jscroller_init() {
$("#scroller a").click(function(){
window.open(this.href);
return false;
});
jscroller_scroller_cont.css('overflow','hidden');
if(!jscroller_config.scroller.interval) {
if (window.attachEvent) {
window.attachEvent("onfocus", jscroller_startScroll);
window.attachEvent("onblur", jscroller_stopScroll);
window.attachEvent("onresize", jscroller_startScroll);
window.attachEvent("onscroll", jscroller_startScroll);
}
else if (window.addEventListener) {
window.addEventListener("focus", jscroller_startScroll, false);
window.addEventListener("blur", jscroller_stopScroll, false);
window.addEventListener("resize", jscroller_startScroll, false);
window.addEventListener("scroll", jscroller_startScroll, false);
}
jscroller_startScroll();
if ($.browser.msie) {window.focus()}
}
}
function jscroller_getElem(Elem) {
return (typeof Elem == "string" && document.getElementById)? document.getElementById(Elem) : Elem;
}
function jscroller_doScroll() {
if (scroller_dom = jscroller_getElem(jscroller_scroller.attr("id"))) {
var
p_top= Number((/[0-9-,.]+/.exec(jscroller_scroller.css('top'))||0)),
p_left=Number((/[0-9-,.]+/.exec(jscroller_scroller.css('left'))||0)),
min_height=jscroller_scroller_cont.height(),
min_width=jscroller_scroller_cont.width(),
speed=jscroller_config.scroller.speed,
p_height=scroller_dom.offsetHeight,
p_width=scroller_dom.offsetWidth,
direction=jscroller_config.scroller.direction,
jscroller=jscroller_scroller;
switch(direction) {
case 'up':
if (p_top <= -1*p_height) {p_top=min_height;}
jscroller.css('top',p_top-speed+'px');
break;
case 'right':
if (p_left >= min_width) {p_left=-1*p_width;}
jscroller.css('left',p_left+speed+'px');
break;
case 'left':
if (p_left <= -1*p_width) {p_left=min_width;}
jscroller.css('left',p_left-speed+'px');
break;
case 'down':
if (p_top >= min_height) {p_top=-1*p_height;}
jscroller.css('top',p_top+speed+'px');
break;
}
}
}
});
//]]> | JavaScript |
var theInt = null;
var $crosslink, $navthumb;
var curclicked = 0;
theInterval = function(cur){
clearInterval(theInt);
if( typeof cur != 'undefined' )
curclicked = cur;
$crosslink.removeClass("active-thumb");
$navthumb.eq(curclicked).parent().addClass("active-thumb");
$(".stripNav ul li a").eq(curclicked).trigger('click');
theInt = setInterval(function(){
$crosslink.removeClass("active-thumb");
$navthumb.eq(curclicked).parent().addClass("active-thumb");
$(".stripNav ul li a").eq(curclicked).trigger('click');
curclicked++;
if( 6 == curclicked )
curclicked = 0;
}, 3000);
};
$(function(){
$("#main-photo-slider").codaSlider();
$navthumb = $(".nav-thumb");
$crosslink = $(".cross-link");
$navthumb
.click(function() {
var $this = $(this);
theInterval($this.parent().attr('href').slice(1) - 1);
return false;
});
theInterval();
});
| JavaScript |
//<![CDATA[
$(document).ready(function() {
//Execute the slideShow, set 6 seconds for each images
slideShow(3000);
});
function slideShow(speed) {
//append a LI item to the UL list for displaying caption
$('ul.slideshow').append('<li id="slideshow-caption" class="caption"><div class="slideshow-caption-container"><h3></h3><p></p></div></li>');
//Set the opacity of all images to 0
$('ul.slideshow li').css({opacity: 0.0});
//Get the first image and display it (set it to full opacity)
$('ul.slideshow li:first').css({opacity: 1.0});
//Get the caption of the first image from REL attribute and display it
$('#slideshow-caption h3').html($('ul.slideshow a:first').find('img').attr('title'));
$('#slideshow-caption p').html($('ul.slideshow a:first').find('img').attr('alt'));
//Display the caption
$('#slideshow-caption').css({opacity: 0.7, bottom:0});
//Call the gallery function to run the slideshow
var timer = setInterval('gallery()',speed);
//pause the slideshow on mouse over
$('ul.slideshow').hover(
function () {
clearInterval(timer);
},
function () {
timer = setInterval('gallery()',speed);
}
);
}
function gallery() {
//if no IMGs have the show class, grab the first image
var current = ($('ul.slideshow li.show')? $('ul.slideshow li.show') : $('#ul.slideshow li:first'));
//Get next image, if it reached the end of the slideshow, rotate it back to the first image
var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption')? $('ul.slideshow li:first') :current.next()) : $('ul.slideshow li:first'));
//Get next image caption
var title = next.find('img').attr('title');
var desc = next.find('img').attr('alt');
//Set the fade in effect for the next image, show class has higher z-index
next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000);
//Hide the caption first, and then set and display the caption
$('#slideshow-caption').animate({bottom:-70}, 300, function () {
//Display the content
$('#slideshow-caption h3').html(title);
$('#slideshow-caption p').html(desc);
$('#slideshow-caption').animate({bottom:0}, 500);
});
//Hide the current image
current.animate({opacity: 0.0}, 1000).removeClass('show');
}
//]]> | JavaScript |
window.addEvent('domready', function(){
var totIncrement = 0;
var increment = 212;
var maxRightIncrement = increment*(-6);
var fx = new Fx.Style('slider-list', 'margin-left', {
duration: 1000,
transition: Fx.Transitions.Back.easeInOut,
wait: true
});
//-------------------------------------
// EVENTS for the button "previous"
$('previous').addEvents({
'click' : function(event){
if(totIncrement<0){
totIncrement = totIncrement+increment;
fx.stop()
fx.start(totIncrement);
}
}
});
//-------------------------------------
// EVENTS for the button "next"
$('next').addEvents({
'click' : function(event){
if(totIncrement>maxRightIncrement){
totIncrement = totIncrement-increment;
fx.stop()
fx.start(totIncrement);
}
}
})
}); | JavaScript |
//<![CDATA[
//** Created: March 19th, 08'
//** Aug 16th, 08'- Updated to v 1.4:
//1) Adds ability to set speed/duration of panel animation (in milliseconds)
//2) Adds persistence support, so the last viewed panel is recalled when viewer returns within same browser session
//3) Adds ability to specify whether panels should stop at the very last and first panel, or wrap around and start all over again
//4) Adds option to specify two navigational image links positioned to the left and right of the Carousel Viewer to move the panels back and forth
//** Aug 27th, 08'- Nav buttons (if enabled) also repositions themselves now if window is resized
var stepcarousel={
ajaxloadingmsg: '<div style="margin: 1em; font-weight: bold"><img src="ajaxloadr.gif" style="vertical-align: middle" /> Fetching Content. Please wait...</div>', //customize HTML to show while fetching Ajax content
defaultbuttonsfade: 0.4, //Fade degree for disabled nav buttons (0=completely transparent, 1=completely opaque)
configholder: {},
getCSSValue:function(val){ //Returns either 0 (if val contains 'auto') or val as an integer
return (val=="auto")? 0 : parseInt(val)
},
getremotepanels:function($, config){ //function to fetch external page containing the panel DIVs
config.$belt.html(this.ajaxloadingmsg)
$.ajax({
url: config.contenttype[1], //path to external content
async: true,
error:function(ajaxrequest){
config.$belt.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
},
success:function(content){
config.$belt.html(content)
config.$panels=config.$gallery.find('.'+config.panelclass)
stepcarousel.alignpanels($, config)
}
})
},
getoffset:function(what, offsettype){
return (what.offsetParent)? what[offsettype]+this.getoffset(what.offsetParent, offsettype) : what[offsettype]
},
getCookie:function(Name){
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
},
setCookie:function(name, value){
document.cookie = name+"="+value
},
fadebuttons:function(config, currentpanel){
config.$leftnavbutton.fadeTo('fast', currentpanel==0? this.defaultbuttonsfade : 1)
config.$rightnavbutton.fadeTo('fast', currentpanel==config.lastvisiblepanel? this.defaultbuttonsfade : 1)
},
addnavbuttons:function(config, currentpanel){
config.$leftnavbutton=$('<img src="'+config.defaultbuttons.leftnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Back '+config.defaultbuttons.moveby+' panels'}).appendTo('body')
config.$rightnavbutton=$('<img src="'+config.defaultbuttons.rightnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Forward '+config.defaultbuttons.moveby+' panels'}).appendTo('body')
config.$leftnavbutton.bind('click', function(){ //assign nav button event handlers
stepcarousel.stepBy(config.galleryid, -config.defaultbuttons.moveby)
})
config.$rightnavbutton.bind('click', function(){ //assign nav button event handlers
stepcarousel.stepBy(config.galleryid, config.defaultbuttons.moveby)
})
if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
this.fadebuttons(config, currentpanel)
}
},
alignpanels:function($, config){
var paneloffset=0
config.paneloffsets=[paneloffset] //array to store upper left offset of each panel (1st element=0)
config.panelwidths=[] //array to store widths of each panel
config.$panels.each(function(index){ //loop through panels
var $currentpanel=$(this)
$currentpanel.css({float: 'none', position: 'absolute', left: paneloffset+'px'}) //position panel
$currentpanel.bind('click', function(e){return config.onpanelclick(e.target)}) //bind onpanelclick() to onclick event
paneloffset+=stepcarousel.getCSSValue($currentpanel.css('marginRight')) + parseInt($currentpanel.get(0).offsetWidth || $currentpanel.css('width')) //calculate next panel offset
config.paneloffsets.push(paneloffset) //remember this offset
config.panelwidths.push(paneloffset-config.paneloffsets[config.paneloffsets.length-2]) //remember panel width
})
config.paneloffsets.pop() //delete last offset (redundant)
var addpanelwidths=0
var lastpanelindex=config.$panels.length-1
config.lastvisiblepanel=lastpanelindex
for (var i=config.$panels.length-1; i>=0; i--){
addpanelwidths+=(i==lastpanelindex? config.panelwidths[lastpanelindex] : config.paneloffsets[i+1]-config.paneloffsets[i])
if (config.gallerywidth>addpanelwidths){
config.lastvisiblepanel=i //calculate index of panel that when in 1st position reveals the very last panel all at once based on gallery width
}
}
config.$belt.css({width: paneloffset+'px'}) //Set Belt DIV to total panels' widths
config.currentpanel=(config.panelbehavior.persist)? parseInt(this.getCookie(window[config.galleryid+"persist"])) : 0 //determine 1st panel to show by default
config.currentpanel=(typeof config.currentpanel=="number" && config.currentpanel<config.$panels.length)? config.currentpanel : 0
if (config.currentpanel!=0){
var endpoint=config.paneloffsets[config.currentpanel]+(config.currentpanel==0? 0 : config.beltoffset)
config.$belt.css({left: -endpoint+'px'})
}
if (config.defaultbuttons.enable==true){ //if enable default back/forth nav buttons
this.addnavbuttons(config, config.currentpanel)
$(window).bind("load, resize", function(){ //refresh position of nav buttons when page loads/resizes, in case offsets weren't available document.oncontentload
config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
config.$leftnavbutton.css({left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px'})
config.$rightnavbutton.css({left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px'})
})
}
this.statusreport(config.galleryid)
config.oninit()
config.onslideaction(this)
},
stepTo:function(galleryid, pindex){ /*User entered pindex starts at 1 for intuitiveness. Internally pindex still starts at 0 */
var config=stepcarousel.configholder[galleryid]
if (typeof config=="undefined"){
alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
return
}
var pindex=Math.min(pindex-1, config.paneloffsets.length-1)
var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset)
if (config.panelbehavior.wraparound==false && config.defaultbuttons.enable==true){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
this.fadebuttons(config, pindex)
}
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
config.currentpanel=pindex
this.statusreport(galleryid)
},
stepBy:function(galleryid, steps){
var config=stepcarousel.configholder[galleryid]
if (typeof config=="undefined"){
alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
return
}
var direction=(steps>0)? 'forward' : 'back' //If "steps" is negative, that means backwards
var pindex=config.currentpanel+steps //index of panel to stop at
if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
pindex=(direction=="back" && pindex<=0)? 0 : (direction=="forward")? Math.min(pindex, config.lastvisiblepanel) : pindex
if (config.defaultbuttons.enable==true){ //if default nav buttons are enabled, fade them in and out depending on if at start or end of carousel
stepcarousel.fadebuttons(config, pindex)
}
}
else{ //else, for normal stepBy behavior
pindex=(pindex>config.paneloffsets.length-1 || pindex<0 && pindex-steps>0)? 0 : (pindex<0)? config.paneloffsets.length+steps : pindex //take into account end or starting panel and step direction
}
var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset) //left distance for Belt DIV to travel to
if (pindex==0 && direction=='forward' || config.currentpanel==0 && direction=='back' && config.panelbehavior.wraparound==true){ //decide whether to apply "push pull" effect
config.$belt.animate({left: -config.paneloffsets[config.currentpanel]-(direction=='forward'? 100 : -30)+'px'}, 'normal', function(){
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
})
}
else
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
config.currentpanel=pindex
this.statusreport(galleryid)
},
statusreport:function(galleryid){
var config=stepcarousel.configholder[galleryid]
var startpoint=config.currentpanel //index of first visible panel
var visiblewidth=0
for (var endpoint=startpoint; endpoint<config.paneloffsets.length; endpoint++){ //index (endpoint) of last visible panel
visiblewidth+=config.panelwidths[endpoint]
if (visiblewidth>config.gallerywidth){
break
}
}
startpoint+=1 //format startpoint for user friendiness
endpoint=(endpoint+1==startpoint)? startpoint : endpoint //If only one image visible on the screen and partially hidden, set endpoint to startpoint
var valuearray=[startpoint, endpoint, config.panelwidths.length]
for (var i=0; i<config.statusvars.length; i++){
window[config.statusvars[i]]=valuearray[i] //Define variable (with user specified name) and set to one of the status values
config.$statusobjs[i].text(valuearray[i]+" ") //Populate element on page with ID="user specified name" with one of the status values
}
},
setup:function(config){
//Disable Step Gallery scrollbars ASAP dynamically (enabled for sake of users with JS disabled)
document.write('<style type="text/css">\n#'+config.galleryid+'{overflow: hidden;}\n</style>')
jQuery(document).ready(function($){
config.$gallery=$('#'+config.galleryid)
config.gallerywidth=config.$gallery.width()
config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
config.$belt=config.$gallery.find('.'+config.beltclass) //Find Belt DIV that contains all the panels
config.$panels=config.$gallery.find('.'+config.panelclass) //Find Panel DIVs that each contain a slide
config.onpanelclick=(typeof config.onpanelclick=="undefined")? function(target){} : config.onpanelclick //attach custom "onpanelclick" event handler
config.onslideaction=(typeof config.onslide=="undefined")? function(){} : function(beltobj){$(beltobj).stop(); config.onslide()} //attach custom "onslide" event handler
config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
config.beltoffset=stepcarousel.getCSSValue(config.$belt.css('marginLeft')) //Find length of Belt DIV's left margin
config.statusvars=config.statusvars || [] //get variable names that will hold "start", "end", and "total" slides info
config.$statusobjs=[$('#'+config.statusvars[0]), $('#'+config.statusvars[1]), $('#'+config.statusvars[2])]
config.currentpanel=0
stepcarousel.configholder[config.galleryid]=config //store config parameter as a variable
if (config.contenttype[0]=="ajax" && typeof config.contenttype[1]!="undefined") //fetch ajax content?
stepcarousel.getremotepanels($, config)
else
stepcarousel.alignpanels($, config) //align panels and initialize gallery
}) //end document.ready
jQuery(window).bind('unload', function(){ //clean up
if (config.panelbehavior.persist){
stepcarousel.setCookie(window[config.galleryid+"persist"], config.currentpanel)
}
jQuery.each(config, function(ai, oi){
oi=null
})
config=null
})
}
}
//]]> | JavaScript |
//< + b;
},
bounceout: 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;
}
},
bounceinout: function(x, t, b, c, d) {
if (t < d/2) return jQuery.easing['bouncein'] (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing['bounceout'] (x, t*2-d,0, c, d) * .5 + c*.5 + b;
},
elasin: 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;
},
elasout: 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;
},
elasinout: 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;
},
backin: function(x, t, b, c, d) {
var s=1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
backout: function(x, t, b, c, d) {
var s=1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
backinout: function(x, t, b, c, d) {
var 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;
},
linear: function(x, t, b, c, d) {
return c*t/d + b; //linear
}
};
//]]> | JavaScript |
//<![CDATA[
/*
This file is part of JonDesign's SmoothGallery v2.0.
JonDesign's SmoothGallery is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
JonDesign's SmoothGallery is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with JonDesign's SmoothGallery; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Main Developer: Jonathan Schemoul (JonDesign: http://www.jondesign.net/)
Contributed code by:
- Christian Ehret (bugfix)
- Nitrix (bugfix)
- Valerio from Mad4Milk for his great help with the carousel scrolling and many other things.
- Archie Cowan for helping me find a bugfix on carousel inner width problem.
- Tomocchino from #mootools for the preloader class
Many thanks to:
- The mootools team for the great mootools lib, and it's help and support throughout the project.
*/
// declaring the class
var gallery = {
initialize: function(element, options) {
this.setOptions({
showArrows: true,
showCarousel: true,
showInfopane: true,
embedLinks: true,
fadeDuration: 500,
timed: false,
delay: 9000,
preloader: true,
preloaderImage: true,
preloaderErrorImage: true,
/* Data retrieval */
manualData: [],
populateFrom: false,
populateData: true,
destroyAfterPopulate: true,
elementSelector: "div.imageElement",
titleSelector: "h2",
subtitleSelector: "p",
linkSelector: "a.open",
imageSelector: "img.full",
thumbnailSelector: "img.thumbnail",
defaultTransition: "fade",
/* InfoPane options */
slideInfoZoneOpacity: 0.7,
slideInfoZoneSlide: true,
/* Carousel options */
carouselMinimizedOpacity: 0.4,
carouselMinimizedHeight: 20,
carouselMaximizedOpacity: 0.9,
thumbHeight: 75,
thumbWidth: 100,
thumbSpacing: 10,
thumbIdleOpacity: 0.2,
textShowCarousel: 'Featured Content',
showCarouselLabel: true,
thumbCloseCarousel: true,
useThumbGenerator: false,
thumbGenerator: 'resizer.php',
useExternalCarousel: false,
carouselElement: false,
carouselHorizontal: true,
activateCarouselScroller: true,
carouselPreloader: true,
textPreloadingCarousel: 'Loading...',
/* CSS Classes */
baseClass: 'jdGallery',
withArrowsClass: 'withArrows',
/* Plugins: HistoryManager */
useHistoryManager: false,
customHistoryKey: false
}, options);
this.fireEvent('onInit');
this.currentIter = 0;
this.lastIter = 0;
this.maxIter = 0;
this.galleryElement = element;
this.galleryData = this.options.manualData;
this.galleryInit = 1;
this.galleryElements = Array();
this.thumbnailElements = Array();
this.galleryElement.addClass(this.options.baseClass);
this.populateFrom = element;
if (this.options.populateFrom)
this.populateFrom = this.options.populateFrom;
if (this.options.populateData)
this.populateData();
element.style.display="block";
if (this.options.useHistoryManager)
this.initHistory();
if (this.options.embedLinks)
{
this.currentLink = new Element('a').addClass('open').setProperties({
href: '#',
title: ''
}).injectInside(element);
if ((!this.options.showArrows) && (!this.options.showCarousel))
this.galleryElement = element = this.currentLink;
else
this.currentLink.setStyle('display', 'none');
}
this.constructElements();
if ((this.galleryData.length>1)&&(this.options.showArrows))
{
var leftArrow = new Element('a').addClass('left').addEvent(
'click',
this.prevItem.bind(this)
).injectInside(element);
var rightArrow = new Element('a').addClass('right').addEvent(
'click',
this.nextItem.bind(this)
).injectInside(element);
this.galleryElement.addClass(this.options.withArrowsClass);
}
this.loadingElement = new Element('div').addClass('loadingElement').injectInside(element);
if (this.options.showInfopane) this.initInfoSlideshow();
if (this.options.showCarousel) this.initCarousel();
this.doSlideShow(1);
},
populateData: function() {
currentArrayPlace = this.galleryData.length;
options = this.options;
var data = $A(this.galleryData);
data.extend(this.populateGallery(this.populateFrom, currentArrayPlace));
this.galleryData = data;
this.fireEvent('onPopulated');
},
populateGallery: function(element, startNumber) {
var data = [];
options = this.options;
currentArrayPlace = startNumber;
element.getElements(options.elementSelector).each(function(el) {
elementDict = {
image: el.getElement(options.imageSelector).getProperty('src'),
number: currentArrayPlace,
transition: this.options.defaultTransition
};
elementDict.extend = $extend;
if ((options.showInfopane) | (options.showCarousel))
elementDict.extend({
title: el.getElement(options.titleSelector).innerHTML,
description: el.getElement(options.subtitleSelector).innerHTML
});
if (options.embedLinks)
elementDict.extend({
link: el.getElement(options.linkSelector).href||false,
linkTitle: el.getElement(options.linkSelector).title||false,
linkTarget: el.getElement(options.linkSelector).getProperty('target')||false
});
if ((!options.useThumbGenerator) && (options.showCarousel))
elementDict.extend({
thumbnail: el.getElement(options.thumbnailSelector).getProperty('src')
});
else if (options.useThumbGenerator)
elementDict.extend({
thumbnail: options.thumbGenerator + '?imgfile=' + elementDict.image + '&max_width=' + options.thumbWidth + '&max_height=' + options.thumbHeight
});
data.extend([elementDict]);
currentArrayPlace++;
if (this.options.destroyAfterPopulate)
el.remove();
});
return data;
},
constructElements: function() {
el = this.galleryElement;
this.maxIter = this.galleryData.length;
var currentImg;
for(i=0;i<this.galleryData.length;i++)
{
var currentImg = new Fx.Styles(
new Element('div').addClass('slideElement').setStyles({
'position':'absolute',
'left':'0px',
'right':'0px',
'margin':'0px',
'padding':'0px',
'backgroundPosition':"center center",
'opacity':'0'
}).injectInside(el),
'opacity',
{duration: this.options.fadeDuration}
);
if (this.options.preloader)
{
currentImg.source = this.galleryData[i].image;
currentImg.loaded = false;
currentImg.load = function(imageStyle) {
if (!imageStyle.loaded) {
new Asset.image(imageStyle.source, {
'onload' : function(img){
img.element.setStyle(
'backgroundImage',
"url('" + img.source + "')")
img.loaded = true;
}.bind(this, imageStyle)
});
}
}.pass(currentImg, this);
} else {
currentImg.element.setStyle('backgroundImage',
"url('" + this.galleryData[i].image + "')");
}
this.galleryElements[parseInt(i)] = currentImg;
}
},
destroySlideShow: function(element) {
var myClassName = element.className;
var newElement = new Element('div').addClass('myClassName');
element.parentNode.replaceChild(newElement, element);
},
startSlideShow: function() {
this.fireEvent('onStart');
this.loadingElement.style.display = "none";
this.lastIter = this.maxIter - 1;
this.currentIter = 0;
this.galleryInit = 0;
this.galleryElements[parseInt(this.currentIter)].set({opacity: 1});
if (this.options.showInfopane)
this.showInfoSlideShow.delay(1000, this);
var textShowCarousel = formatString(this.options.textShowCarousel, this.currentIter+1, this.maxIter);
if (this.options.showCarousel&&(!this.options.carouselPreloader))
this.carouselBtn.setHTML(textShowCarousel).setProperty('title', textShowCarousel);
this.prepareTimer();
if (this.options.embedLinks)
this.makeLink(this.currentIter);
},
nextItem: function() {
this.fireEvent('onNextCalled');
this.nextIter = this.currentIter+1;
if (this.nextIter >= this.maxIter)
this.nextIter = 0;
this.galleryInit = 0;
this.goTo(this.nextIter);
},
prevItem: function() {
this.fireEvent('onPreviousCalled');
this.nextIter = this.currentIter-1;
if (this.nextIter <= -1)
this.nextIter = this.maxIter - 1;
this.galleryInit = 0;
this.goTo(this.nextIter);
},
goTo: function(num) {
this.clearTimer();
if(this.options.preloader)
{
this.galleryElements[num].load();
if (num==0)
this.galleryElements[this.maxIter - 1].load();
else
this.galleryElements[num - 1].load();
if (num==(this.maxIter - 1))
this.galleryElements[0].load();
else
this.galleryElements[num + 1].load();
}
if (this.options.embedLinks)
this.clearLink();
if (this.options.showInfopane)
{
this.slideInfoZone.clearChain();
this.hideInfoSlideShow().chain(this.changeItem.pass(num, this));
} else
this.currentChangeDelay = this.changeItem.delay(500, this, num);
if (this.options.embedLinks)
this.makeLink(num);
this.prepareTimer();
/*if (this.options.showCarousel)
this.clearThumbnailsHighlights();*/
},
changeItem: function(num) {
this.fireEvent('onStartChanging');
this.galleryInit = 0;
if (this.currentIter != num)
{
for(i=0;i<this.maxIter;i++)
{
if ((i != this.currentIter)) this.galleryElements[i].set({opacity: 0});
}
gallery.Transitions[this.galleryData[num].transition].pass([
this.galleryElements[this.currentIter],
this.galleryElements[num],
this.currentIter,
num], this)();
this.currentIter = num;
}
var textShowCarousel = formatString(this.options.textShowCarousel, num+1, this.maxIter);
if (this.options.showCarousel)
this.carouselBtn.setHTML(textShowCarousel).setProperty('title', textShowCarousel);
this.doSlideShow.bind(this)();
this.fireEvent('onChanged');
},
clearTimer: function() {
if (this.options.timed)
$clear(this.timer);
},
prepareTimer: function() {
if (this.options.timed)
this.timer = this.nextItem.delay(this.options.delay, this);
},
doSlideShow: function(position) {
if (this.galleryInit == 1)
{
imgPreloader = new Image();
imgPreloader.onload=function(){
this.startSlideShow.delay(10, this);
}.bind(this);
imgPreloader.src = this.galleryData[0].image;
if(this.options.preloader)
this.galleryElements[0].load();
} else {
if (this.options.showInfopane)
{
if (this.options.showInfopane)
{
this.showInfoSlideShow.delay((500 + this.options.fadeDuration), this);
} else
if ((this.options.showCarousel)&&(this.options.activateCarouselScroller))
this.centerCarouselOn(position);
}
}
},
createCarousel: function() {
var carouselElement;
if (!this.options.useExternalCarousel)
{
var carouselContainerElement = new Element('div').addClass('carouselContainer').injectInside(this.galleryElement);
this.carouselContainer = new Fx.Styles(carouselContainerElement, {transition: Fx.Transitions.expoOut});
this.carouselContainer.normalHeight = carouselContainerElement.offsetHeight;
this.carouselContainer.set({'opacity': this.options.carouselMinimizedOpacity, 'top': (this.options.carouselMinimizedHeight - this.carouselContainer.normalHeight)});
this.carouselBtn = new Element('a').addClass('carouselBtn').setProperties({
title: this.options.textShowCarousel
}).injectInside(carouselContainerElement);
if(this.options.carouselPreloader)
this.carouselBtn.setHTML(this.options.textPreloadingCarousel);
else
this.carouselBtn.setHTML(this.options.textShowCarousel);
this.carouselBtn.addEvent(
'click',
function () {
this.carouselContainer.clearTimer();
this.toggleCarousel();
}.bind(this)
);
this.carouselActive = false;
carouselElement = new Element('div').addClass('carousel').injectInside(carouselContainerElement);
this.carousel = new Fx.Styles(carouselElement);
} else {
carouselElement = $(this.options.carouselElement).addClass('jdExtCarousel');
}
this.carouselElement = new Fx.Styles(carouselElement, {transition: Fx.Transitions.expoOut});
this.carouselElement.normalHeight = carouselElement.offsetHeight;
if (this.options.showCarouselLabel)
this.carouselLabel = new Element('p').addClass('label').injectInside(carouselElement);
carouselWrapper = new Element('div').addClass('carouselWrapper').injectInside(carouselElement);
this.carouselWrapper = new Fx.Styles(carouselWrapper, {transition: Fx.Transitions.expoOut});
this.carouselWrapper.normalHeight = carouselWrapper.offsetHeight;
this.carouselInner = new Element('div').addClass('carouselInner').injectInside(carouselWrapper);
if (this.options.activateCarouselScroller)
{
this.carouselWrapper.scroller = new Scroller(carouselWrapper, {
area: 100,
velocity: 0.2
})
this.carouselWrapper.elementScroller = new Fx.Scroll(carouselWrapper, {
duration: 400,
onStart: this.carouselWrapper.scroller.stop.bind(this.carouselWrapper.scroller),
onComplete: this.carouselWrapper.scroller.start.bind(this.carouselWrapper.scroller)
});
}
},
fillCarousel: function() {
this.constructThumbnails();
this.carouselInner.normalWidth = ((this.maxIter * (this.options.thumbWidth + this.options.thumbSpacing + 2))+this.options.thumbSpacing) + "px";
this.carouselInner.style.width = this.carouselInner.normalWidth;
},
initCarousel: function () {
this.createCarousel();
this.fillCarousel();
if (this.options.carouselPreloader)
this.preloadThumbnails();
},
flushCarousel: function() {
this.thumbnailElements.each(function(myFx) {
myFx.element.remove();
myFx = myFx.element = null;
});
this.thumbnailElements = [];
},
toggleCarousel: function() {
if (this.carouselActive)
this.hideCarousel();
else
this.showCarousel();
},
showCarousel: function () {
this.fireEvent('onShowCarousel');
this.carouselContainer.start({
'opacity': this.options.carouselMaximizedOpacity,
'top': 0
}).chain(function() {
this.carouselActive = true;
this.carouselWrapper.scroller.start();
this.fireEvent('onCarouselShown');
this.carouselContainer.options.onComplete = null;
}.bind(this));
},
hideCarousel: function () {
this.fireEvent('onHideCarousel');
var targetTop = this.options.carouselMinimizedHeight - this.carouselContainer.normalHeight;
this.carouselContainer.start({
'opacity': this.options.carouselMinimizedOpacity,
'top': targetTop
}).chain(function() {
this.carouselActive = false;
this.carouselWrapper.scroller.stop();
this.fireEvent('onCarouselHidden');
this.carouselContainer.options.onComplete = null;
}.bind(this));
},
constructThumbnails: function () {
element = this.carouselInner;
for(i=0;i<this.galleryData.length;i++)
{
var currentImg = new Fx.Style(new Element ('div').addClass("thumbnail").setStyles({
backgroundImage: "url('" + this.galleryData[i].thumbnail + "')",
backgroundPosition: "center center",
backgroundRepeat: 'no-repeat',
marginLeft: this.options.thumbSpacing + "px",
width: this.options.thumbWidth + "px",
height: this.options.thumbHeight + "px"
}).injectInside(element), "opacity", {duration: 200}).set(this.options.thumbIdleOpacity);
currentImg.element.addEvents({
'mouseover': function (myself) {
myself.clearTimer();
myself.start(0.99);
if (this.options.showCarouselLabel)
$(this.carouselLabel).setHTML('<span class="number">' + (myself.relatedImage.number + 1) + "/" + this.maxIter + ":</span> " + myself.relatedImage.title);
}.pass(currentImg, this),
'mouseout': function (myself) {
myself.clearTimer();
myself.start(this.options.thumbIdleOpacity);
}.pass(currentImg, this),
'click': function (myself) {
this.goTo(myself.relatedImage.number);
if (this.options.thumbCloseCarousel)
this.hideCarousel();
}.pass(currentImg, this)
});
currentImg.relatedImage = this.galleryData[i];
this.thumbnailElements[parseInt(i)] = currentImg;
}
},
log: function(value) {
if(console.log)
console.log(value);
},
preloadThumbnails: function() {
var thumbnails = [];
for(i=0;i<this.galleryData.length;i++)
{
thumbnails[parseInt(i)] = this.galleryData[i].thumbnail;
}
this.thumbnailPreloader = new Preloader();
this.thumbnailPreloader.addEvent('onComplete', function() {
var textShowCarousel = formatString(this.options.textShowCarousel, this.currentIter+1, this.maxIter);
this.carouselBtn.setHTML(textShowCarousel).setProperty('title', textShowCarousel);
}.bind(this));
this.thumbnailPreloader.load(thumbnails);
},
clearThumbnailsHighlights: function()
{
for(i=0;i<this.galleryData.length;i++)
{
this.thumbnailElements[i].clearTimer();
this.thumbnailElements[i].start(0.2);
}
},
changeThumbnailsSize: function(width, height)
{
for(i=0;i<this.galleryData.length;i++)
{
this.thumbnailElements[i].clearTimer();
this.thumbnailElements[i].element.setStyles({
'width': width + "px",
'height': height + "px"
});
}
},
centerCarouselOn: function(num) {
if (!this.carouselWallMode)
{
var carouselElement = this.thumbnailElements[num];
var position = carouselElement.element.offsetLeft + (carouselElement.element.offsetWidth / 2);
var carouselWidth = this.carouselWrapper.element.offsetWidth;
var carouselInnerWidth = this.carouselInner.offsetWidth;
var diffWidth = carouselWidth / 2;
var scrollPos = position-diffWidth;
this.carouselWrapper.elementScroller.scrollTo = (scrollPos,0);
}
},
initInfoSlideshow: function() {
/*if (this.slideInfoZone.element)
this.slideInfoZone.element.remove();*/
this.slideInfoZone = new Fx.Styles(new Element('div').addClass('slideInfoZone').injectInside($(this.galleryElement))).set({'opacity':0});
var slideInfoZoneTitle = new Element('h2').injectInside(this.slideInfoZone.element);
var slideInfoZoneDescription = new Element('p').injectInside(this.slideInfoZone.element);
this.slideInfoZone.normalHeight = this.slideInfoZone.element.offsetHeight;
this.slideInfoZone.element.setStyle('opacity',0);
},
changeInfoSlideShow: function()
{
this.hideInfoSlideShow.delay(10, this);
this.showInfoSlideShow.delay(500, this);
},
showInfoSlideShow: function() {
this.fireEvent('onShowInfopane');
this.slideInfoZone.clearTimer();
element = this.slideInfoZone.element;
element.getElement('h2').setHTML(this.galleryData[this.currentIter].title);
element.getElement('p').setHTML(this.galleryData[this.currentIter].description);
if(this.options.slideInfoZoneSlide)
this.slideInfoZone.start({'opacity': [0, this.options.slideInfoZoneOpacity], 'height': [0, this.slideInfoZone.normalHeight]});
else
this.slideInfoZone.start({'opacity': [0, this.options.slideInfoZoneOpacity]});
if (this.options.showCarousel)
this.slideInfoZone.chain(this.centerCarouselOn.pass(this.currentIter, this));
return this.slideInfoZone;
},
hideInfoSlideShow: function() {
this.fireEvent('onHideInfopane');
this.slideInfoZone.clearTimer();
if(this.options.slideInfoZoneSlide)
this.slideInfoZone.start({'opacity': 0, 'height': 0});
else
this.slideInfoZone.start({'opacity': 0});
return this.slideInfoZone;
},
makeLink: function(num) {
this.currentLink.setProperties({
href: this.galleryData[num].link,
title: this.galleryData[num].linkTitle
})
if (!((this.options.embedLinks) && (!this.options.showArrows) && (!this.options.showCarousel)))
this.currentLink.setStyle('display', 'block');
},
clearLink: function() {
this.currentLink.setProperties({href: '', title: ''});
if (!((this.options.embedLinks) && (!this.options.showArrows) && (!this.options.showCarousel)))
this.currentLink.setStyle('display', 'none');
},
/* To change the gallery data, those two functions : */
flushGallery: function() {
this.galleryElements.each(function(myFx) {
myFx.element.remove();
myFx = myFx.element = null;
});
this.galleryElements = [];
},
changeData: function(data) {
this.galleryData = data;
this.clearTimer();
this.flushGallery();
if (this.options.showCarousel) this.flushCarousel();
this.constructElements();
if (this.options.showCarousel) this.fillCarousel();
if (this.options.showInfopane) this.hideInfoSlideShow();
this.galleryInit=1;
this.lastIter=0;
this.currentIter=0;
this.doSlideShow(1);
},
/* Plugins: HistoryManager */
initHistory: function() {
this.fireEvent('onHistoryInit');
this.historyKey = this.galleryElement.id + '-picture';
if (this.options.customHistoryKey)
this.historyKey = this.options.customHistoryKey();
this.history = HistoryManager.register(
this.historyKey,
[1],
function(values) {
if (parseInt(values[0])-1 < this.maxIter)
this.goTo(parseInt(values[0])-1);
}.bind(this),
function(values) {
return [this.historyKey, '(', values[0], ')'].join('');
}.bind(this),
this.historyKey + '\\((\\d+)\\)');
this.addEvent('onChanged', function(){
this.history.setValue(0, this.currentIter+1);
}.bind(this));
this.fireEvent('onHistoryInited');
}
};
gallery = new Class(gallery);
gallery.implement(new Events);
gallery.implement(new Options);
gallery.Transitions = new Abstract ({
fade: function(oldFx, newFx, oldPos, newPos){
oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
if (newPos > oldPos) newFx.start({opacity: 1});
else
{
newFx.set({opacity: 1});
oldFx.start({opacity: 0});
}
},
crossfade: function(oldFx, newFx, oldPos, newPos){
oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
newFx.start({opacity: 1});
oldFx.start({opacity: 0});
},
fadebg: function(oldFx, newFx, oldPos, newPos){
oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
oldFx.options.duration = newFx.options.duration = this.options.fadeDuration / 2;
oldFx.start({opacity: 0}).chain(newFx.start.pass([{opacity: 1}], newFx));
}
});
/* All code copyright 2007 Jonathan Schemoul */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Follows: Preloader (class)
* Simple class for preloading images with support for progress reporting
* Copyright 2007 Tomocchino.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var Preloader = new Class({
Implements: [Events, Options],
options: {
root : '',
period : 100
},
initialize: function(options){
this.setOptions(options);
},
load: function(sources) {
this.index = 0;
this.images = [];
this.sources = this.temps = sources;
this.total = this. sources.length;
this.fireEvent('onStart', [this.index, this.total]);
this.timer = this.progress.periodical(this.options.period, this);
this.sources.each(function(source, index){
this.images[index] = new Asset.image(this.options.root + source, {
'onload' : function(){ this.index++; if(this.images[index]) this.fireEvent('onLoad', [this.images[index], index, source]); }.bind(this),
'onerror' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this),
'onabort' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this)
});
}, this);
},
progress: function() {
this.fireEvent('onProgress', [Math.min(this.index, this.total), this.total]);
if(this.index >= this.total) this.complete();
},
complete: function(){
$clear(this.timer);
this.fireEvent('onComplete', [this.images]);
},
cancel: function(){
$clear(this.timer);
}
});
Preloader.implement(new Events, new Options);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Follows: formatString (function)
* Original name: Yahoo.Tools.printf
* Copyright Yahoo.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function formatString() {
var num = arguments.length;
var oStr = arguments[0];
for (var i = 1; i < num; i++) {
var pattern = "\\{" + (i-1) + "\\}";
var re = new RegExp(pattern, "g");
oStr = oStr.replace(re, arguments[i]);
}
return oStr;
}
//]]> | JavaScript |
//< + b;
},
bounceout: 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;
}
},
bounceinout: function(x, t, b, c, d) {
if (t < d/2) return jQuery.easing['bouncein'] (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing['bounceout'] (x, t*2-d,0, c, d) * .5 + c*.5 + b;
},
elasin: 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;
},
elasout: 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;
},
elasinout: 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;
},
backin: function(x, t, b, c, d) {
var s=1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
backout: function(x, t, b, c, d) {
var s=1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
backinout: function(x, t, b, c, d) {
var 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;
},
linear: function(x, t, b, c, d) {
return c*t/d + b; //linear
}
};
//]]> | JavaScript |
//<![CDATA[
/*! Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* 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.
*
* Version: 3.0.2
*
* Requires: 1.2.2+
*/
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener )
for ( var i=types.length; i; )
this.addEventListener( types[--i], handler, false );
else
this.onmousewheel = handler;
},
teardown: function() {
if ( this.removeEventListener )
for ( var i=types.length; i; )
this.removeEventListener( types[--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 args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true;
event = $.event.fix(event || window.event);
event.type = "mousewheel";
if ( event.wheelDelta ) delta = event.wheelDelta/120;
if ( event.detail ) delta = -event.detail/3;
// Add events and delta to the front of the arguments
args.unshift(event, delta);
return $.event.handle.apply(this, args);
}
})(jQuery);
//]]> | JavaScript |
//<![CDATA[
function removeHtmlTag(strx,chop){
if(strx.indexOf("<")!=-1)
{
var s = strx.split("<");
for(var i=0;i<s.length;i++){
if(s[i].indexOf(">")!=-1){
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
strx = s.join("");
}
chop = (chop < strx.length-1) ? chop : strx.length-2;
while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++;
strx = strx.substring(0,chop-1);
return strx+'...';
}
function createSummaryAndThumb(pID){
var div = document.getElementById(pID);
var imgtag = "";
var img = div.getElementsByTagName("img");
var summ = summary_noimg;
if(img.length>=1) {
imgtag = '<span style="float:left; padding:0px 10px 5px 0px;"><img src="'+img[0].src+'" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/></span>';
summ = summary_img;
}
var summary = imgtag + '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>';
div.innerHTML = summary;
}
//]]> | JavaScript |
//<![CDATA[
/*
* 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() {
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 Cycle Plugin (with Transition Definitions)
* Examples and documentation at: http://malsup.com/jquery/cycle/
* Copyright (c) 2007-2008 M. Alsup
* Version: 2.32 (21-DEC-2008)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Requires: jQuery v1.2.3 or later
*
* Based on the work of:
* 1) Matt Oakes (http://portfolio.gizone.co.uk/applications/slideshow/)
* 2) Torsten Baldes (http://medienfreunde.com/lab/innerfade/)
* 3) Benjamin Sterling (http://www.benjaminsterling.com/experiments/jqShuffle/)
*/
;(function($) {
var ver = '2.32';
var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
function log() {
if (window.console && window.console.log)
window.console.log('[cycle] ' + Array.prototype.join.call(arguments,''));
};
$.fn.cycle = function(options) {
if (this.length == 0) {
// 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;
}
var opt2 = arguments[1];
return this.each(function() {
if (options === undefined || options === null)
options = {};
if (options.constructor == String) {
switch(options) {
case 'stop':
if (this.cycleTimeout) clearTimeout(this.cycleTimeout);
this.cycleTimeout = 0;
$(this).data('cycle.opts', '');
return;
case 'pause':
this.cyclePause = 1;
return;
case 'resume':
this.cyclePause = 0;
if (opt2 === true) { // resume now!
options = $(this).data('cycle.opts');
if (!options) {
log('options not found, can not resume');
return;
}
if (this.cycleTimeout) {
clearTimeout(this.cycleTimeout);
this.cycleTimeout = 0;
}
go(options.elements, options, 1, 1);
}
return;
default:
options = { fx: options };
};
}
else if (options.constructor == Number) {
// go to the requested slide
var num = options;
options = $(this).data('cycle.opts');
if (!options) {
log('options not found, can not advance slide');
return;
}
if (num < 0 || num >= options.elements.length) {
log('invalid slide index: ' + num);
return;
}
options.nextSlide = num;
if (this.cycleTimeout) {
clearTimeout(this.cycleTimeout);
this.cycleTimeout = 0;
}
go(options.elements, options, 1, num >= options.currSlide);
return;
}
// stop existing slideshow for this container (if there is one)
if (this.cycleTimeout) clearTimeout(this.cycleTimeout);
this.cycleTimeout = 0;
this.cyclePause = 0;
var $cont = $(this);
var $slides = options.slideExpr ? $(options.slideExpr, this) : $cont.children();
var els = $slides.get();
if (els.length < 2) {
log('terminating; too few slides: ' + els.length);
return; // don't bother
}
// 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;
$cont.data('cycle.opts', opts);
opts.container = this;
opts.elements = els;
opts.before = opts.before ? [opts.before] : [];
opts.after = opts.after ? [opts.after] : [];
opts.after.unshift(function(){ opts.busy=0; });
if (opts.continuous)
opts.after.push(function() { go(els,opts,0,!opts.rev); });
// clearType corrections
if (ie6 && opts.cleartype && !opts.cleartypeNoBg)
clearTypeFix($slides);
// allow shorthand overrides of width, height and timeout
var cls = this.className;
opts.width = parseInt((cls.match(/w:(\d+)/)||[])[1]) || opts.width;
opts.height = parseInt((cls.match(/h:(\d+)/)||[])[1]) || opts.height;
opts.timeout = parseInt((cls.match(/t:(\d+)/)||[])[1]) || opts.timeout;
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);
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 = 0;
opts.startingSlide = opts.randomMap[0];
}
else if (opts.startingSlide >= els.length)
opts.startingSlide = 0; // catch bogus input
var first = opts.startingSlide || 0;
$slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) {
var z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i;
$(this).css('z-index', z)
});
$(els[first]).css('opacity',1).show(); // opacity bit needed to handle reinit case
if ($.browser.msie) els[first].style.removeAttribute('filter');
if (opts.fit && opts.width)
$slides.width(opts.width);
if (opts.fit && opts.height && opts.height != 'auto')
$slides.height(opts.height);
if (opts.containerResize) {
var maxw = 0, maxh = 0;
for(var i=0; i < els.length; i++) {
var $e = $(els[i]), w = $e.outerWidth(), h = $e.outerHeight();
maxw = w > maxw ? w : maxw;
maxh = h > maxh ? h : maxh;
}
$cont.css({width:maxw+'px',height:maxh+'px'});
}
if (opts.pause)
$cont.hover(function(){this.cyclePause++;},function(){this.cyclePause--;});
// run transition init fn
var init = $.fn.cycle.transitions[opts.fx];
if ($.isFunction(init))
init($cont, $slides, opts);
else if (opts.fx != 'custom')
log('unknown transition: ' + opts.fx);
$slides.each(function() {
var $el = $(this);
this.cycleH = (opts.fit && opts.height) ? opts.height : $el.height();
this.cycleW = (opts.fit && opts.width) ? opts.width : $el.width();
});
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;
while((opts.timeout - opts.speed) < 250)
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 = first;
if (opts.random) {
opts.nextSlide = opts.currSlide;
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else
opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1;
// 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.click && !opts.next)
opts.next = opts.click;
if (opts.next)
$(opts.next).bind('click', function(){return advance(els,opts,opts.rev?-1:1)});
if (opts.prev)
$(opts.prev).bind('click', function(){return advance(els,opts,opts.rev?1:-1)});
if (opts.pager)
buildPager(els,opts);
// expose fn for adding slides after the show has started
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']($cont);
if (prepend) {
opts.currSlide++;
opts.nextSlide++;
}
if (ie6 && 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)
$.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts);
if (typeof opts.onAddSlide == 'function')
opts.onAddSlide($s);
};
if (opts.timeout || opts.continuous)
this.cycleTimeout = setTimeout(
function(){go(els,opts,0,!opts.rev)},
opts.continuous ? 10 : opts.timeout + (opts.delay||0));
});
};
function go(els, opts, manual, fwd) {
if (opts.busy) return;
var p = opts.container, curr = els[opts.currSlide], next = els[opts.nextSlide];
if (p.cycleTimeout === 0 && !manual)
return;
if (!manual && !p.cyclePause &&
((opts.autostop && (--opts.countdown <= 0)) ||
(opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) {
if (opts.end)
opts.end(opts);
return;
}
if (manual || !p.cyclePause) {
if (opts.before.length)
$.each(opts.before, function(i,o) { o.apply(next, [curr, next, opts, fwd]); });
var after = function() {
if ($.browser.msie && opts.cleartype)
this.style.removeAttribute('filter');
$.each(opts.after, function(i,o) { o.apply(next, [curr, next, opts, fwd]); });
};
if (opts.nextSlide != opts.currSlide) {
opts.busy = 1;
if (opts.fxFn)
opts.fxFn(curr, next, opts, after, fwd);
else if ($.isFunction($.fn.cycle[opts.fx]))
$.fn.cycle[opts.fx](curr, next, opts, after);
else
$.fn.cycle.custom(curr, next, opts, after, manual && opts.fastOnEvent);
}
if (opts.random) {
opts.currSlide = opts.nextSlide;
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else { // sequence
var roll = (opts.nextSlide + 1) == els.length;
opts.nextSlide = roll ? 0 : opts.nextSlide+1;
opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
}
if (opts.pager)
$.fn.cycle.updateActivePagerLink(opts.pager, opts.currSlide);
}
if (opts.timeout && !opts.continuous)
p.cycleTimeout = setTimeout(function() { go(els,opts,0,!opts.rev) }, getTimeout(curr,next,opts,fwd));
else if (opts.continuous && p.cyclePause)
p.cycleTimeout = setTimeout(function() { go(els,opts,0,!opts.rev) }, 10);
};
$.fn.cycle.updateActivePagerLink = function(pager, currSlide) {
$(pager).find('a').removeClass('activeSlide').filter('a:eq('+currSlide+')').addClass('activeSlide');
};
function getTimeout(curr, next, opts, fwd) {
if (opts.timeoutFn) {
var t = opts.timeoutFn(curr,next,opts,fwd);
if (t !== false)
return t;
}
return opts.timeout;
};
// advance slide forward or back
function advance(els, opts, val) {
var p = opts.container, 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) {
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
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;
}
}
if (opts.prevNextClick && typeof opts.prevNextClick == 'function')
opts.prevNextClick(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);
});
$.fn.cycle.updateActivePagerLink(opts.pager, opts.startingSlide);
};
$.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) {
var a = (typeof opts.pagerAnchorBuilder == 'function')
? opts.pagerAnchorBuilder(i,el)
: '<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)
$a.appendTo($p);
$a.bind(opts.pagerEvent, function() {
opts.nextSlide = i;
var p = opts.container, timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
if (typeof opts.pagerClick == 'function')
opts.pagerClick(opts.nextSlide, els[opts.nextSlide]);
go(els,opts,1,opts.currSlide < i);
return false;
});
if (opts.pauseOnPagerHover)
$a.hover(function() { opts.container.cyclePause++; }, function() { opts.container.cyclePause--; } );
};
// this fixes clearType problems in ie6 by setting an explicit bg color
function clearTypeFix($slides) {
function hex(s) {
var 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)); });
};
$.fn.cycle.custom = function(curr, next, opts, cb, immediate) {
var $l = $(curr), $n = $(next);
$n.css(opts.cssBefore);
var speedIn = immediate ? 1 : opts.speedIn;
var speedOut = immediate ? 1 : opts.speedOut;
var easeIn = immediate ? null : opts.easeIn;
var easeOut = immediate ? null : opts.easeOut;
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();
};
$.fn.cycle.transitions = {
fade: function($cont, $slides, opts) {
$slides.not(':eq('+opts.startingSlide+')').css('opacity',0);
opts.before.push(function() { $(this).show() });
opts.animIn = { opacity: 1 };
opts.animOut = { opacity: 0 };
opts.cssBefore = { opacity: 0 };
opts.cssAfter = { display: 'none' };
opts.onAddSlide = function($s) { $s.hide(); };
}
};
$.fn.cycle.ver = function() { return ver; };
// override these globally if you like (they are all optional)
$.fn.cycle.defaults = {
fx: 'fade', // one of: fade, shuffle, zoom, scrollLeft, etc
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 click trigger for next slide
prev: null, // selector for element to use as click trigger for previous slide
prevNextClick: null, // callback fn for prev/next clicks: function(isNext, zeroBasedSlideIndex, slideElement)
pager: null, // selector for element to use as pager container
pagerClick: null, // callback fn for pager clicks: function(zeroBasedSlideIndex, slideElement)
pagerEvent: 'click', // name of event which drives the pager navigation
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: 0, // true if clearType corrections should be applied (for IE)
nowrap: 0, // true to prevent slideshow from wrapping
fastOnEvent: 0 // force immediate transition when triggered manually (via pager or prev/next)
};
})(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-2008 M. Alsup
* Version: 2.22
* 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.
//
// scrollUp/Down/Left/Right
$.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push(function(curr, next, opts) {
$(this).show();
opts.cssBefore.top = next.offsetHeight;
opts.animOut.top = 0-curr.offsetHeight;
});
opts.cssFirst = { top: 0 };
opts.animIn = { top: 0 };
opts.cssAfter = { display: 'none' };
};
$.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push(function(curr, next, opts) {
$(this).show();
opts.cssBefore.top = 0-next.offsetHeight;
opts.animOut.top = curr.offsetHeight;
});
opts.cssFirst = { top: 0 };
opts.animIn = { top: 0 };
opts.cssAfter = { display: 'none' };
};
$.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push(function(curr, next, opts) {
$(this).show();
opts.cssBefore.left = next.offsetWidth;
opts.animOut.left = 0-curr.offsetWidth;
});
opts.cssFirst = { left: 0 };
opts.animIn = { left: 0 };
};
$.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push(function(curr, next, opts) {
$(this).show();
opts.cssBefore.left = 0-next.offsetWidth;
opts.animOut.left = curr.offsetWidth;
});
opts.cssFirst = { left: 0 };
opts.animIn = { left: 0 };
};
$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
$cont.css('overflow','hidden').width();
// $slides.show();
opts.before.push(function(curr, next, opts, fwd) {
$(this).show();
var currW = curr.offsetWidth, nextW = next.offsetWidth;
opts.cssBefore = fwd ? { left: nextW } : { left: -nextW };
opts.animIn.left = 0;
opts.animOut.left = fwd ? -currW : currW;
$slides.not(curr).css(opts.cssBefore);
});
opts.cssFirst = { left: 0 };
opts.cssAfter = { display: 'none' }
};
$.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
// $slides.show();
opts.before.push(function(curr, next, opts, fwd) {
$(this).show();
var currH = curr.offsetHeight, nextH = next.offsetHeight;
opts.cssBefore = fwd ? { top: -nextH } : { top: nextH };
opts.animIn.top = 0;
opts.animOut.top = fwd ? currH : -currH;
$slides.not(curr).css(opts.cssBefore);
});
opts.cssFirst = { top: 0 };
opts.cssAfter = { display: 'none' }
};
// slideX/slideY
$.fn.cycle.transitions.slideX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(curr).css('zIndex',1);
});
opts.onAddSlide = function($s) { $s.hide(); };
opts.cssBefore = { zIndex: 2 };
opts.animIn = { width: 'show' };
opts.animOut = { width: 'hide' };
};
$.fn.cycle.transitions.slideY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(curr).css('zIndex',1);
});
opts.onAddSlide = function($s) { $s.hide(); };
opts.cssBefore = { zIndex: 2 };
opts.animIn = { height: 'show' };
opts.animOut = { height: 'hide' };
};
// shuffle
$.fn.cycle.transitions.shuffle = function($cont, $slides, opts) {
var w = $cont.css('overflow', 'visible').width();
$slides.css({left: 0, top: 0});
opts.before.push(function() { $(this).show() });
opts.speed = opts.speed / 2; // shuffle has 2 transitions
opts.random = 0;
opts.shuffle = opts.shuffle || {left:-w, top:15};
opts.els = [];
for (var i=0; i < $slides.length; i++)
opts.els.push($slides[i]);
for (var i=0; i < opts.startingSlide; 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);
$el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() {
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);
else {
var z = $(curr).css('z-index');
$el.css('z-index', parseInt(z)+1);
}
$el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() {
$(fwd ? this : curr).hide();
if (cb) cb();
});
});
};
opts.onAddSlide = function($s) { $s.hide(); };
};
// turnUp/Down/Left/Right
$.fn.cycle.transitions.turnUp = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(this).show();
opts.cssBefore.top = next.cycleH;
opts.animIn.height = next.cycleH;
});
opts.onAddSlide = function($s) { $s.hide(); };
opts.cssFirst = { top: 0 };
opts.cssBefore = { height: 0 };
opts.animIn = { top: 0 };
opts.animOut = { height: 0 };
opts.cssAfter = { display: 'none' };
};
$.fn.cycle.transitions.turnDown = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(this).show();
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.onAddSlide = function($s) { $s.hide(); };
opts.cssFirst = { top: 0 };
opts.cssBefore = { top: 0, height: 0 };
opts.animOut = { height: 0 };
opts.cssAfter = { display: 'none' };
};
$.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(this).show();
opts.cssBefore.left = next.cycleW;
opts.animIn.width = next.cycleW;
});
opts.onAddSlide = function($s) { $s.hide(); };
opts.cssBefore = { width: 0 };
opts.animIn = { left: 0 };
opts.animOut = { width: 0 };
opts.cssAfter = { display: 'none' };
};
$.fn.cycle.transitions.turnRight = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(this).show();
opts.animIn.width = next.cycleW;
opts.animOut.left = curr.cycleW;
});
opts.onAddSlide = function($s) { $s.hide(); };
opts.cssBefore = { left: 0, width: 0 };
opts.animIn = { left: 0 };
opts.animOut = { width: 0 };
opts.cssAfter = { display: 'none' };
};
// zoom
$.fn.cycle.transitions.zoom = function($cont, $slides, opts) {
opts.cssFirst = { top:0, left: 0 };
opts.cssAfter = { display: 'none' };
opts.before.push(function(curr, next, opts) {
$(this).show();
opts.cssBefore = { width: 0, height: 0, top: next.cycleH/2, left: next.cycleW/2 };
opts.cssAfter = { display: 'none' };
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 };
$(curr).css('zIndex',2);
$(next).css('zIndex',1);
});
opts.onAddSlide = function($s) { $s.hide(); };
};
// fadeZoom
$.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
opts.cssBefore = { width: 0, height: 0, opacity: 1, left: next.cycleW/2, top: next.cycleH/2, zIndex: 1 };
opts.animIn = { top: 0, left: 0, width: next.cycleW, height: next.cycleH };
});
opts.animOut = { opacity: 0 };
opts.cssAfter = { zIndex: 0 };
};
// blindX
$.fn.cycle.transitions.blindX = function($cont, $slides, opts) {
var w = $cont.css('overflow','hidden').width();
$slides.show();
opts.before.push(function(curr, next, opts) {
$(curr).css('zIndex',1);
});
opts.cssBefore = { left: w, zIndex: 2 };
opts.cssAfter = { zIndex: 1 };
opts.animIn = { left: 0 };
opts.animOut = { left: w };
};
// blindY
$.fn.cycle.transitions.blindY = function($cont, $slides, opts) {
var h = $cont.css('overflow','hidden').height();
$slides.show();
opts.before.push(function(curr, next, opts) {
$(curr).css('zIndex',1);
});
opts.cssBefore = { top: h, zIndex: 2 };
opts.cssAfter = { zIndex: 1 };
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();
$slides.show();
opts.before.push(function(curr, next, opts) {
$(curr).css('zIndex',1);
});
opts.cssBefore = { top: h, left: w, zIndex: 2 };
opts.cssAfter = { zIndex: 1 };
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) {
opts.cssBefore = { left: this.cycleW/2, width: 0, zIndex: 2 };
opts.animIn = { left: 0, width: this.cycleW };
opts.animOut = { left: 0 };
$(curr).css('zIndex',1);
});
opts.onAddSlide = function($s) { $s.hide().css('zIndex',1); };
};
// growY - grow vertically from centered 0 height
$.fn.cycle.transitions.growY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
opts.cssBefore = { top: this.cycleH/2, height: 0, zIndex: 2 };
opts.animIn = { top: 0, height: this.cycleH };
opts.animOut = { top: 0 };
$(curr).css('zIndex',1);
});
opts.onAddSlide = function($s) { $s.hide().css('zIndex',1); };
};
// curtainX - squeeze in both edges horizontally
$.fn.cycle.transitions.curtainX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
opts.cssBefore = { left: next.cycleW/2, width: 0, zIndex: 1, display: 'block' };
opts.animIn = { left: 0, width: this.cycleW };
opts.animOut = { left: curr.cycleW/2, width: 0 };
$(curr).css('zIndex',2);
});
opts.onAddSlide = function($s) { $s.hide(); };
opts.cssAfter = { zIndex: 1, display: 'none' };
};
// curtainY - squeeze in both edges vertically
$.fn.cycle.transitions.curtainY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
opts.cssBefore = { top: next.cycleH/2, height: 0, zIndex: 1, display: 'block' };
opts.animIn = { top: 0, height: this.cycleH };
opts.animOut = { top: curr.cycleH/2, height: 0 };
$(curr).css('zIndex',2);
});
opts.onAddSlide = function($s) { $s.hide(); };
opts.cssAfter = { zIndex: 1, display: 'none' };
};
// 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) {
opts.cssBefore = opts.cssBefore || {};
opts.cssBefore.zIndex = 2;
opts.cssBefore.display = 'block';
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;
$(curr).css('zIndex',1);
});
if (!opts.animIn) opts.animIn = { left: 0, top: 0 };
if (!opts.animOut) opts.animOut = { left: 0, top: 0 };
opts.cssAfter = opts.cssAfter || {};
opts.cssAfter.zIndex = 2;
opts.cssAfter.display = 'none';
};
// 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) {
opts.cssBefore.display = 'block';
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;
$(curr).css('zIndex',2);
$(next).css('zIndex',1);
});
opts.onAddSlide = function($s) { $s.hide(); };
if (!opts.animIn) opts.animIn = { left: 0, top: 0 };
opts.cssBefore = opts.cssBefore || {};
opts.cssBefore.top = 0;
opts.cssBefore.left = 0;
opts.cssAfter = opts.cssAfter || {};
opts.cssAfter.zIndex = 1;
opts.cssAfter.display = 'none';
};
// 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) {
$(curr).css('zIndex',2);
opts.cssBefore.display = 'block';
// 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.onAddSlide = function($s) { $s.hide(); };
opts.cssBefore = { left: 0, top: 0, zIndex: 1, opacity: 1 };
opts.animIn = { left: 0 };
opts.cssAfter = { zIndex: 2, display: 'none' };
};
// 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 t = parseInt(h/2);
var l = parseInt(w/2);
clip = 'rect('+t+'px '+l+'px '+t+'px '+l+'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).css('zIndex',2);
var $next = $(next).css({
zIndex: 3,
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');
}
f();
});
opts.cssAfter = { };
opts.animIn = { left: 0 };
opts.animOut = { left: 0 };
};
})(jQuery); | JavaScript |
//** Step Carousel Viewer- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Script Download/ http://www.dynamicdrive.com/dynamicindex4/stepcarousel.htm
//** Usage Terms: http://www.dynamicdrive.com/notice.htm
//** Current version (Sept 29th, 09'): 1.8 See http://www.dynamicdrive.com/dynamicindex4/stepcarouselchangelog.txt for details
jQuery.noConflict()
var stepcarousel={
ajaxloadingmsg: '<div style="margin: 1em; font-weight: bold"><img src="ajaxloadr.gif" style="vertical-align: middle" /> Fetching Content. Please wait...</div>', //customize HTML to show while fetching Ajax content
defaultbuttonsfade: 0.4, //Fade degree for disabled nav buttons (0=completely transparent, 1=completely opaque)
configholder: {},
getCSSValue:function(val){ //Returns either 0 (if val contains 'auto') or val as an integer
return (val=="auto")? 0 : parseInt(val)
},
getremotepanels:function($, config){ //function to fetch external page containing the panel DIVs
config.$belt.html(this.ajaxloadingmsg)
$.ajax({
url: config.contenttype[1], //path to external content
async: true,
error:function(ajaxrequest){
config.$belt.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
},
success:function(content){
config.$belt.html(content)
config.$panels=config.$gallery.find('.'+config.panelclass)
stepcarousel.alignpanels($, config)
}
})
},
getoffset:function(what, offsettype){
return (what.offsetParent)? what[offsettype]+this.getoffset(what.offsetParent, offsettype) : what[offsettype]
},
getCookie:function(Name){
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
},
setCookie:function(name, value){
document.cookie = name+"="+value
},
fadebuttons:function(config, currentpanel){
config.$leftnavbutton.fadeTo('fast', currentpanel==0? this.defaultbuttonsfade : 1)
config.$rightnavbutton.fadeTo('fast', currentpanel==config.lastvisiblepanel? this.defaultbuttonsfade : 1)
if (currentpanel==config.lastvisiblepanel){
stepcarousel.stopautostep(config)
}
},
addnavbuttons:function($, config, currentpanel){
config.$leftnavbutton=$('<img src="'+config.defaultbuttons.leftnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Back '+config.defaultbuttons.moveby+' panels'}).appendTo('body')
config.$rightnavbutton=$('<img src="'+config.defaultbuttons.rightnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Forward '+config.defaultbuttons.moveby+' panels'}).appendTo('body')
config.$leftnavbutton.bind('click', function(){ //assign nav button event handlers
stepcarousel.stepBy(config.galleryid, -config.defaultbuttons.moveby)
})
config.$rightnavbutton.bind('click', function(){ //assign nav button event handlers
stepcarousel.stepBy(config.galleryid, config.defaultbuttons.moveby)
})
if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
this.fadebuttons(config, currentpanel)
}
return config.$leftnavbutton.add(config.$rightnavbutton)
},
alignpanels:function($, config){
var paneloffset=0
config.paneloffsets=[paneloffset] //array to store upper left offset of each panel (1st element=0)
config.panelwidths=[] //array to store widths of each panel
config.$panels.each(function(index){ //loop through panels
var $currentpanel=$(this)
$currentpanel.css({float: 'none', position: 'absolute', left: paneloffset+'px'}) //position panel
$currentpanel.bind('click', function(e){return config.onpanelclick(e.target)}) //bind onpanelclick() to onclick event
paneloffset+=stepcarousel.getCSSValue($currentpanel.css('marginRight')) + parseInt($currentpanel.get(0).offsetWidth || $currentpanel.css('width')) //calculate next panel offset
config.paneloffsets.push(paneloffset) //remember this offset
config.panelwidths.push(paneloffset-config.paneloffsets[config.paneloffsets.length-2]) //remember panel width
})
config.paneloffsets.pop() //delete last offset (redundant)
var addpanelwidths=0
var lastpanelindex=config.$panels.length-1
config.lastvisiblepanel=lastpanelindex
for (var i=config.$panels.length-1; i>=0; i--){
addpanelwidths+=(i==lastpanelindex? config.panelwidths[lastpanelindex] : config.paneloffsets[i+1]-config.paneloffsets[i])
if (config.gallerywidth>addpanelwidths){
config.lastvisiblepanel=i //calculate index of panel that when in 1st position reveals the very last panel all at once based on gallery width
}
}
config.$belt.css({width: paneloffset+'px'}) //Set Belt DIV to total panels' widths
config.currentpanel=(config.panelbehavior.persist)? parseInt(this.getCookie(config.galleryid+"persist")) : 0 //determine 1st panel to show by default
config.currentpanel=(typeof config.currentpanel=="number" && config.currentpanel<config.$panels.length)? config.currentpanel : 0
var endpoint=config.paneloffsets[config.currentpanel]+(config.currentpanel==0? 0 : config.beltoffset)
config.$belt.css({left: -endpoint+'px'})
if (config.defaultbuttons.enable==true){ //if enable default back/forth nav buttons
var $navbuttons=this.addnavbuttons($, config, config.currentpanel)
$(window).bind("load resize", function(){ //refresh position of nav buttons when page loads/resizes, in case offsets weren't available document.oncontentload
config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
config.$leftnavbutton.css({left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px'})
config.$rightnavbutton.css({left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px'})
})
}
if (config.autostep && config.autostep.enable){ //enable auto stepping of Carousel?
var $carouselparts=config.$gallery.add(typeof $navbuttons!="undefined"? $navbuttons : null)
$carouselparts.bind('click', function(){
config.autostep.status="stopped"
stepcarousel.stopautostep(config)
})
$carouselparts.hover(function(){ //onMouseover
stepcarousel.stopautostep(config)
config.autostep.hoverstate="over"
}, function(){ //onMouseout
if (config.steptimer && config.autostep.hoverstate=="over" && config.autostep.status!="stopped"){
config.steptimer=setInterval(function(){stepcarousel.autorotate(config.galleryid)}, config.autostep.pause)
config.autostep.hoverstate="out"
}
})
config.steptimer=setInterval(function(){stepcarousel.autorotate(config.galleryid)}, config.autostep.pause) //automatically rotate Carousel Viewer
} //end enable auto stepping check
this.createpaginate($, config)
this.statusreport(config.galleryid)
config.oninit()
config.onslideaction(this)
},
stepTo:function(galleryid, pindex){ /*User entered pindex starts at 1 for intuitiveness. Internally pindex still starts at 0 */
var config=stepcarousel.configholder[galleryid]
if (typeof config=="undefined"){
//alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
return
}
stepcarousel.stopautostep(config)
var pindex=Math.min(pindex-1, config.paneloffsets.length-1)
var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset)
if (config.panelbehavior.wraparound==false && config.defaultbuttons.enable==true){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
this.fadebuttons(config, pindex)
}
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
config.currentpanel=pindex
this.statusreport(galleryid)
},
stepBy:function(galleryid, steps, isauto){
var config=stepcarousel.configholder[galleryid]
if (typeof config=="undefined"){
//alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
return
}
if (!isauto) //if stepBy() function isn't called by autorotate() function
stepcarousel.stopautostep(config)
var direction=(steps>0)? 'forward' : 'back' //If "steps" is negative, that means backwards
var pindex=config.currentpanel+steps //index of panel to stop at
if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
pindex=(direction=="back" && pindex<=0)? 0 : (direction=="forward")? Math.min(pindex, config.lastvisiblepanel) : pindex
if (config.defaultbuttons.enable==true){ //if default nav buttons are enabled, fade them in and out depending on if at start or end of carousel
stepcarousel.fadebuttons(config, pindex)
}
}
else{ //else, for normal stepBy behavior
if (pindex>config.lastvisiblepanel && direction=="forward"){
//if destination pindex is greater than last visible panel, yet we're currently not at the end of the carousel yet
pindex=(config.currentpanel<config.lastvisiblepanel)? config.lastvisiblepanel : 0
}
else if (pindex<0 && direction=="back"){
//if destination pindex is less than 0, yet we're currently not at the beginning of the carousel yet
pindex=(config.currentpanel>0)? 0 : config.lastvisiblepanel /*wrap around left*/
}
}
var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset) //left distance for Belt DIV to travel to
if (pindex==0 && direction=='forward' || config.currentpanel==0 && direction=='back' && config.panelbehavior.wraparound==true){ //decide whether to apply "push pull" effect
config.$belt.animate({left: -config.paneloffsets[config.currentpanel]-(direction=='forward'? 100 : -30)+'px'}, 'normal', function(){
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
})
}
else
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
config.currentpanel=pindex
this.statusreport(galleryid)
},
autorotate:function(galleryid){
var config=stepcarousel.configholder[galleryid]
this.stepBy(galleryid, config.autostep.moveby, true)
},
stopautostep:function(config){
clearTimeout(config.steptimer)
},
statusreport:function(galleryid){
var config=stepcarousel.configholder[galleryid]
if (config.statusvars.length==3){ //if 3 status vars defined
var startpoint=config.currentpanel //index of first visible panel
var visiblewidth=0
for (var endpoint=startpoint; endpoint<config.paneloffsets.length; endpoint++){ //index (endpoint) of last visible panel
visiblewidth+=config.panelwidths[endpoint]
if (visiblewidth>config.gallerywidth){
break
}
}
startpoint+=1 //format startpoint for user friendiness
endpoint=(endpoint+1==startpoint)? startpoint : endpoint //If only one image visible on the screen and partially hidden, set endpoint to startpoint
var valuearray=[startpoint, endpoint, config.panelwidths.length]
for (var i=0; i<config.statusvars.length; i++){
window[config.statusvars[i]]=valuearray[i] //Define variable (with user specified name) and set to one of the status values
config.$statusobjs[i].text(valuearray[i]+" ") //Populate element on page with ID="user specified name" with one of the status values
}
}
stepcarousel.selectpaginate(jQuery, galleryid)
},
createpaginate:function($, config){
if (config.$paginatediv.length==1){
var $templateimg=config.$paginatediv.find('img["data-over"]:eq(0)') //reference first matching image on page
var controlpoints=[], controlsrc=[], imgarray=[], moveby=$templateimg.attr("data-moveby") || 1
var asize=(moveby==1? 0:1) + Math.floor((config.lastvisiblepanel+1) / moveby) //calculate # of pagination links to create
var imghtml=$('<div>').append($templateimg.clone()).html() //get HTML of first matching image
srcs=[$templateimg.attr('src'), $templateimg.attr('data-over'), $templateimg.attr('data-select')] //remember control's over and out, and selected image src
for (var i=0; i<asize; i++){
var moveto=Math.min(i*moveby, config.lastvisiblepanel)
imgarray.push(imghtml.replace(/>$/, ' data-index="'+i+'" data-moveto="'+moveto+'" title="Move to Panel '+(moveto+1)+'">') +'\n')
controlpoints.push(moveto) //store panel index each control goes to when clicked on
}
var $controls=$('<span></span>').replaceAll($templateimg).append(imgarray.join('')).find('img') //replace template link with links and return them
$controls.css({cursor:'pointer'})
config.$paginatediv.bind('click', function(e){
var $target=$(e.target)
if ($target.is('img') && $target.attr('data-over')){
stepcarousel.stepTo(config.galleryid, parseInt($target.attr('data-moveto'))+1)
}
})
config.$paginatediv.bind('mouseover mouseout', function(e){
var $target=$(e.target)
if ($target.is('img') && $target.attr('data-over')){
if (parseInt($target.attr('data-index')) != config.pageinfo.curselected) //if this isn't the selected link
$target.attr('src', srcs[(e.type=="mouseover")? 1 : 0])
}
})
config.pageinfo={controlpoints:controlpoints, $controls:$controls, srcs:srcs, prevselected:null, curselected:null}
}
},
selectpaginate:function($, galleryid){
var config=stepcarousel.configholder[galleryid]
if (config.$paginatediv.length==1){
for (var i=0; i<config.pageinfo.controlpoints.length; i++){
if (config.pageinfo.controlpoints[i] <= config.currentpanel) //find largest control point that's less than or equal to current panel shown
config.pageinfo.curselected=i
}
if (typeof config.pageinfo.prevselected!=null) //deselect previously selected link (if found)
config.pageinfo.$controls.eq(config.pageinfo.prevselected).attr('src', config.pageinfo.srcs[0])
config.pageinfo.$controls.eq(config.pageinfo.curselected).attr('src', config.pageinfo.srcs[2]) //select current paginate link
config.pageinfo.prevselected=config.pageinfo.curselected //set current selected link to previous
}
},
loadcontent:function(galleryid, url){
var config=stepcarousel.configholder[galleryid]
config.contenttype=['ajax', url]
stepcarousel.stopautostep(config)
stepcarousel.resetsettings($, config)
stepcarousel.init(jQuery, config)
},
init:function($, config){
config.gallerywidth=config.$gallery.width()
config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
config.$belt=config.$gallery.find('.'+config.beltclass) //Find Belt DIV that contains all the panels
config.$panels=config.$gallery.find('.'+config.panelclass) //Find Panel DIVs that each contain a slide
config.$paginatediv=$('#'+config.galleryid+'-paginate') //get pagination DIV (if defined)
if (config.autostep)
config.autostep.pause+=config.panelbehavior.speed
config.onpanelclick=(typeof config.onpanelclick=="undefined")? function(target){} : config.onpanelclick //attach custom "onpanelclick" event handler
config.onslideaction=(typeof config.onslide=="undefined")? function(){} : function(beltobj){$(beltobj).stop(); config.onslide()} //attach custom "onslide" event handler
config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
config.beltoffset=stepcarousel.getCSSValue(config.$belt.css('marginLeft')) //Find length of Belt DIV's left margin
config.statusvars=config.statusvars || [] //get variable names that will hold "start", "end", and "total" slides info
config.$statusobjs=[$('#'+config.statusvars[0]), $('#'+config.statusvars[1]), $('#'+config.statusvars[2])]
config.currentpanel=0
stepcarousel.configholder[config.galleryid]=config //store config parameter as a variable
if (config.contenttype[0]=="ajax" && typeof config.contenttype[1]!="undefined") //fetch ajax content?
stepcarousel.getremotepanels($, config)
else
stepcarousel.alignpanels($, config) //align panels and initialize gallery
},
resetsettings:function($, config){
config.$gallery.unbind()
config.$belt.stop()
config.$panels.remove()
if (config.$leftnavbutton){
config.$leftnavbutton.remove()
config.$rightnavbutton.remove()
}
if (config.$paginatediv.length==1){
config.$paginatediv.unbind()
config.pageinfo.$controls.eq(0).attr('src', config.pageinfo.srcs[0]).removeAttr('data-index').removeAttr('data-moveto').removeAttr('title') //reset first pagination link so it acts as template again
.end().slice(1).remove() //then remove all but first pagination link
}
if (config.autostep)
config.autostep.status=null
if (config.panelbehavior.persist){
stepcarousel.setCookie(window[config.galleryid+"persist"], 0) //set initial panel to 0, overridden w/ current panel if window.unload is invoked
}
},
setup:function(config){
//Disable Step Gallery scrollbars ASAP dynamically (enabled for sake of users with JS disabled)
document.write('<style type="text/css">\n#'+config.galleryid+'{overflow: hidden;}\n</style>')
jQuery(document).ready(function($){
config.$gallery=$('#'+config.galleryid)
stepcarousel.init($, config)
}) //end document.ready
jQuery(window).bind('unload', function(){ //clean up on page unload
stepcarousel.resetsettings($, config)
if (config.panelbehavior.persist)
stepcarousel.setCookie(config.galleryid+"persist", config.currentpanel)
jQuery.each(config, function(ai, oi){
oi=null
})
config=null
})
}
} | JavaScript |
/*
Script: Core.js
Mootools - My Object Oriented javascript.
License:
MIT-style license.
MooTools Copyright:
copyright (c) 2007 Valerio Proietti, <http://mad4milk.net>
MooTools Credits:
- Class is slightly based on Base.js <http://dean.edwards.name/weblog/2006/03/base/> (c) 2006 Dean Edwards, License <http://creativecommons.org/licenses/LGPL/2.1/>
- Some functions are inspired by those found in prototype.js <http://prototype.conio.net/> (c) 2005 Sam Stephenson sam [at] conio [dot] net, MIT-style license
- Documentation by Aaron Newton (aaron.newton [at] cnet [dot] com) and Valerio Proietti.
*/
var MooTools = {
version: '1.11'
};
/* Section: Core Functions */
/*
Function: $defined
Returns true if the passed in value/object is defined, that means is not null or undefined.
Arguments:
obj - object to inspect
*/
function $defined(obj){
return (obj != undefined);
};
/*
Function: $type
Returns the type of object that matches the element passed in.
Arguments:
obj - the object to inspect.
Example:
>var myString = 'hello';
>$type(myString); //returns "string"
Returns:
'element' - if obj is a DOM element node
'textnode' - if obj is a DOM text node
'whitespace' - if obj is a DOM whitespace node
'arguments' - if obj is an arguments object
'object' - if obj is an object
'string' - if obj is a string
'number' - if obj is a number
'boolean' - if obj is a boolean
'function' - if obj is a function
'regexp' - if obj is a regular expression
'class' - if obj is a Class. (created with new Class, or the extend of another class).
'collection' - if obj is a native htmlelements collection, such as childNodes, getElementsByTagName .. etc.
false - (boolean) if the object is not defined or none of the above.
*/
function $type(obj){
if (!$defined(obj)) return false;
if (obj.htmlElement) return 'element';
var type = typeof obj;
if (type == 'object' && obj.nodeName){
switch(obj.nodeType){
case 1: return 'element';
case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
}
}
if (type == 'object' || type == 'function'){
switch(obj.constructor){
case Array: return 'array';
case RegExp: return 'regexp';
case Class: return 'class';
}
if (typeof obj.length == 'number'){
if (obj.item) return 'collection';
if (obj.callee) return 'arguments';
}
}
return type;
};
/*
Function: $merge
merges a number of objects recursively without referencing them or their sub-objects.
Arguments:
any number of objects.
Example:
>var mergedObj = $merge(obj1, obj2, obj3);
>//obj1, obj2, and obj3 are unaltered
*/
function $merge(){
var mix = {};
for (var i = 0; i < arguments.length; i++){
for (var property in arguments[i]){
var ap = arguments[i][property];
var mp = mix[property];
if (mp && $type(ap) == 'object' && $type(mp) == 'object') mix[property] = $merge(mp, ap);
else mix[property] = ap;
}
}
return mix;
};
/*
Function: $extend
Copies all the properties from the second passed object to the first passed Object.
If you do myWhatever.extend = $extend the first parameter will become myWhatever, and your extend function will only need one parameter.
Example:
(start code)
var firstOb = {
'name': 'John',
'lastName': 'Doe'
};
var secondOb = {
'age': '20',
'sex': 'male',
'lastName': 'Dorian'
};
$extend(firstOb, secondOb);
//firstOb will become:
{
'name': 'John',
'lastName': 'Dorian',
'age': '20',
'sex': 'male'
};
(end)
Returns:
The first object, extended.
*/
var $extend = function(){
var args = arguments;
if (!args[1]) args = [this, args[0]];
for (var property in args[1]) args[0][property] = args[1][property];
return args[0];
};
/*
Function: $native
Will add a .extend method to the objects passed as a parameter, but the property passed in will be copied to the object's prototype only if non previously existent.
Its handy if you dont want the .extend method of an object to overwrite existing methods.
Used automatically in MooTools to implement Array/String/Function/Number methods to browser that dont support them whitout manual checking.
Arguments:
a number of classes/native javascript objects
*/
var $native = function(){
for (var i = 0, l = arguments.length; i < l; i++){
arguments[i].extend = function(props){
for (var prop in props){
if (!this.prototype[prop]) this.prototype[prop] = props[prop];
if (!this[prop]) this[prop] = $native.generic(prop);
}
};
}
};
$native.generic = function(prop){
return function(bind){
return this.prototype[prop].apply(bind, Array.prototype.slice.call(arguments, 1));
};
};
$native(Function, Array, String, Number);
/*
Function: $chk
Returns true if the passed in value/object exists or is 0, otherwise returns false.
Useful to accept zeroes.
Arguments:
obj - object to inspect
*/
function $chk(obj){
return !!(obj || obj === 0);
};
/*
Function: $pick
Returns the first object if defined, otherwise returns the second.
Arguments:
obj - object to test
picked - the default to return
Example:
(start code)
function say(msg){
alert($pick(msg, 'no meessage supplied'));
}
(end)
*/
function $pick(obj, picked){
return $defined(obj) ? obj : picked;
};
/*
Function: $random
Returns a random integer number between the two passed in values.
Arguments:
min - integer, the minimum value (inclusive).
max - integer, the maximum value (inclusive).
Returns:
a random integer between min and max.
*/
function $random(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
};
/*
Function: $time
Returns the current timestamp
Returns:
a timestamp integer.
*/
function $time(){
return new Date().getTime();
};
/*
Function: $clear
clears a timeout or an Interval.
Returns:
null
Arguments:
timer - the setInterval or setTimeout to clear.
Example:
>var myTimer = myFunction.delay(5000); //wait 5 seconds and execute my function.
>myTimer = $clear(myTimer); //nevermind
See also:
<Function.delay>, <Function.periodical>
*/
function $clear(timer){
clearTimeout(timer);
clearInterval(timer);
return null;
};
/*
Class: Abstract
Abstract class, to be used as singleton. Will add .extend to any object
Arguments:
an object
Returns:
the object with an .extend property, equivalent to <$extend>.
*/
var Abstract = function(obj){
obj = obj || {};
obj.extend = $extend;
return obj;
};
//window, document
var Window = new Abstract(window);
var Document = new Abstract(document);
document.head = document.getElementsByTagName('head')[0];
/*
Class: window
Some properties are attached to the window object by the browser detection.
Note:
browser detection is entirely object-based. We dont sniff.
Properties:
window.ie - will be set to true if the current browser is internet explorer (any).
window.ie6 - will be set to true if the current browser is internet explorer 6.
window.ie7 - will be set to true if the current browser is internet explorer 7.
window.gecko - will be set to true if the current browser is Mozilla/Gecko.
window.webkit - will be set to true if the current browser is Safari/Konqueror.
window.webkit419 - will be set to true if the current browser is Safari2 / webkit till version 419.
window.webkit420 - will be set to true if the current browser is Safari3 (Webkit SVN Build) / webkit over version 419.
window.opera - is set to true by opera itself.
*/
window.xpath = !!(document.evaluate);
if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
else if (document.childNodes && !document.all && !navigator.taintEnabled) window.webkit = window[window.xpath ? 'webkit420' : 'webkit419'] = true;
else if (document.getBoxObjectFor != null) window.gecko = true;
/*compatibility*/
window.khtml = window.webkit;
Object.extend = $extend;
/*end compatibility*/
//htmlelement
if (typeof HTMLElement == 'undefined'){
var HTMLElement = function(){};
if (window.webkit) document.createElement("iframe"); //fixes safari
HTMLElement.prototype = (window.webkit) ? window["[[DOMElement.prototype]]"] : {};
}
HTMLElement.prototype.htmlElement = function(){};
//enables background image cache for internet explorer 6
if (window.ie6) try {document.execCommand("BackgroundImageCache", false, true);} catch(e){};
/*
Script: Class.js
Contains the Class Function, aims to ease the creation of reusable Classes.
License:
MIT-style license.
*/
/*
Class: Class
The base class object of the <http://mootools.net> framework.
Creates a new class, its initialize method will fire upon class instantiation.
Initialize wont fire on instantiation when you pass *null*.
Arguments:
properties - the collection of properties that apply to the class.
Example:
(start code)
var Cat = new Class({
initialize: function(name){
this.name = name;
}
});
var myCat = new Cat('Micia');
alert(myCat.name); //alerts 'Micia'
(end)
*/
var Class = function(properties){
var klass = function(){
return (arguments[0] !== null && this.initialize && $type(this.initialize) == 'function') ? this.initialize.apply(this, arguments) : this;
};
$extend(klass, this);
klass.prototype = properties;
klass.constructor = Class;
return klass;
};
/*
Property: empty
Returns an empty function
*/
Class.empty = function(){};
Class.prototype = {
/*
Property: extend
Returns the copy of the Class extended with the passed in properties.
Arguments:
properties - the properties to add to the base class in this new Class.
Example:
(start code)
var Animal = new Class({
initialize: function(age){
this.age = age;
}
});
var Cat = Animal.extend({
initialize: function(name, age){
this.parent(age); //will call the previous initialize;
this.name = name;
}
});
var myCat = new Cat('Micia', 20);
alert(myCat.name); //alerts 'Micia'
alert(myCat.age); //alerts 20
(end)
*/
extend: function(properties){
var proto = new this(null);
for (var property in properties){
var pp = proto[property];
proto[property] = Class.Merge(pp, properties[property]);
}
return new Class(proto);
},
/*
Property: implement
Implements the passed in properties to the base Class prototypes, altering the base class, unlike <Class.extend>.
Arguments:
properties - the properties to add to the base class.
Example:
(start code)
var Animal = new Class({
initialize: function(age){
this.age = age;
}
});
Animal.implement({
setName: function(name){
this.name = name
}
});
var myAnimal = new Animal(20);
myAnimal.setName('Micia');
alert(myAnimal.name); //alerts 'Micia'
(end)
*/
implement: function(){
for (var i = 0, l = arguments.length; i < l; i++) $extend(this.prototype, arguments[i]);
}
};
//internal
Class.Merge = function(previous, current){
if (previous && previous != current){
var type = $type(current);
if (type != $type(previous)) return current;
switch(type){
case 'function':
var merged = function(){
this.parent = arguments.callee.parent;
return current.apply(this, arguments);
};
merged.parent = previous;
return merged;
case 'object': return $merge(previous, current);
}
}
return current;
};
/*
Script: Class.Extras.js
Contains common implementations for custom classes. In Mootools is implemented in <Ajax>, <XHR> and <Fx.Base> and many more.
License:
MIT-style license.
*/
/*
Class: Chain
An "Utility" Class. Its methods can be implemented with <Class.implement> into any <Class>.
Currently implemented in <Fx.Base>, <XHR> and <Ajax>. In <Fx.Base> for example, is used to execute a list of function, one after another, once the effect is completed.
The functions will not be fired all togheter, but one every completion, to create custom complex animations.
Example:
(start code)
var myFx = new Fx.Style('element', 'opacity');
myFx.start(1,0).chain(function(){
myFx.start(0,1);
}).chain(function(){
myFx.start(1,0);
}).chain(function(){
myFx.start(0,1);
});
//the element will appear and disappear three times
(end)
*/
var Chain = new Class({
/*
Property: chain
adds a function to the Chain instance stack.
Arguments:
fn - the function to append.
*/
chain: function(fn){
this.chains = this.chains || [];
this.chains.push(fn);
return this;
},
/*
Property: callChain
Executes the first function of the Chain instance stack, then removes it. The first function will then become the second.
*/
callChain: function(){
if (this.chains && this.chains.length) this.chains.shift().delay(10, this);
},
/*
Property: clearChain
Clears the stack of a Chain instance.
*/
clearChain: function(){
this.chains = [];
}
});
/*
Class: Events
An "Utility" Class. Its methods can be implemented with <Class.implement> into any <Class>.
In <Fx.Base> Class, for example, is used to give the possibility add any number of functions to the Effects events, like onComplete, onStart, onCancel.
Events in a Class that implements <Events> can be either added as an option, or with addEvent. Never with .options.onEventName.
Example:
(start code)
var myFx = new Fx.Style('element', 'opacity').addEvent('onComplete', function(){
alert('the effect is completed');
}).addEvent('onComplete', function(){
alert('I told you the effect is completed');
});
myFx.start(0,1);
//upon completion it will display the 2 alerts, in order.
(end)
Implementing:
This class can be implemented into other classes to add the functionality to them.
Goes well with the <Options> class.
Example:
(start code)
var Widget = new Class({
initialize: function(){},
finish: function(){
this.fireEvent('onComplete');
}
});
Widget.implement(new Events);
//later...
var myWidget = new Widget();
myWidget.addEvent('onComplete', myfunction);
(end)
*/
var Events = new Class({
/*
Property: addEvent
adds an event to the stack of events of the Class instance.
Arguments:
type - string; the event name (e.g. 'onComplete')
fn - function to execute
*/
addEvent: function(type, fn){
if (fn != Class.empty){
this.$events = this.$events || {};
this.$events[type] = this.$events[type] || [];
this.$events[type].include(fn);
}
return this;
},
/*
Property: fireEvent
fires all events of the specified type in the Class instance.
Arguments:
type - string; the event name (e.g. 'onComplete')
args - array or single object; arguments to pass to the function; if more than one argument, must be an array
delay - (integer) delay (in ms) to wait to execute the event
Example:
(start code)
var Widget = new Class({
initialize: function(arg1, arg2){
...
this.fireEvent("onInitialize", [arg1, arg2], 50);
}
});
Widget.implement(new Events);
(end)
*/
fireEvent: function(type, args, delay){
if (this.$events && this.$events[type]){
this.$events[type].each(function(fn){
fn.create({'bind': this, 'delay': delay, 'arguments': args})();
}, this);
}
return this;
},
/*
Property: removeEvent
removes an event from the stack of events of the Class instance.
Arguments:
type - string; the event name (e.g. 'onComplete')
fn - function that was added
*/
removeEvent: function(type, fn){
if (this.$events && this.$events[type]) this.$events[type].remove(fn);
return this;
}
});
/*
Class: Options
An "Utility" Class. Its methods can be implemented with <Class.implement> into any <Class>.
Used to automate the options settings, also adding Class <Events> when the option begins with on.
Example:
(start code)
var Widget = new Class({
options: {
color: '#fff',
size: {
width: 100
height: 100
}
},
initialize: function(options){
this.setOptions(options);
}
});
Widget.implement(new Options);
//later...
var myWidget = new Widget({
color: '#f00',
size: {
width: 200
}
});
//myWidget.options = {color: #f00, size: {width: 200, height: 100}}
(end)
*/
var Options = new Class({
/*
Property: setOptions
sets this.options
Arguments:
defaults - object; the default set of options
options - object; the user entered options. can be empty too.
Note:
if your Class has <Events> implemented, every option beginning with on, followed by a capital letter (onComplete) becomes an Class instance event.
*/
setOptions: function(){
this.options = $merge.apply(null, [this.options].extend(arguments));
if (this.addEvent){
for (var option in this.options){
if ($type(this.options[option] == 'function') && (/^on[A-Z]/).test(option)) this.addEvent(option, this.options[option]);
}
}
return this;
}
});
/*
Script: Array.js
Contains Array prototypes, <$A>, <$each>
License:
MIT-style license.
*/
/*
Class: Array
A collection of The Array Object prototype methods.
*/
//custom methods
Array.extend({
/*
Property: forEach
Iterates through an array; This method is only available for browsers without native *forEach* support.
For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:forEach>
*forEach* executes the provided function (callback) once for each element present in the array. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Arguments:
fn - function to execute with each item in the array; passed the item and the index of that item in the array
bind - the object to bind "this" to (see <Function.bind>)
Example:
>['apple','banana','lemon'].each(function(item, index){
> alert(index + " = " + item); //alerts "0 = apple" etc.
>}, bindObj); //optional second arg for binding, not used here
*/
forEach: function(fn, bind){
for (var i = 0, j = this.length; i < j; i++) fn.call(bind, this[i], i, this);
},
/*
Property: filter
This method is provided only for browsers without native *filter* support.
For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:filter>
*filter* calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.
Arguments:
fn - function to execute with each item in the array; passed the item and the index of that item in the array
bind - the object to bind "this" to (see <Function.bind>)
Example:
>var biggerThanTwenty = [10,3,25,100].filter(function(item, index){
> return item > 20;
>});
>//biggerThanTwenty = [25,100]
*/
filter: function(fn, bind){
var results = [];
for (var i = 0, j = this.length; i < j; i++){
if (fn.call(bind, this[i], i, this)) results.push(this[i]);
}
return results;
},
/*
Property: map
This method is provided only for browsers without native *map* support.
For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:map>
*map* calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Arguments:
fn - function to execute with each item in the array; passed the item and the index of that item in the array
bind - the object to bind "this" to (see <Function.bind>)
Example:
>var timesTwo = [1,2,3].map(function(item, index){
> return item*2;
>});
>//timesTwo = [2,4,6];
*/
map: function(fn, bind){
var results = [];
for (var i = 0, j = this.length; i < j; i++) results[i] = fn.call(bind, this[i], i, this);
return results;
},
/*
Property: every
This method is provided only for browsers without native *every* support.
For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:every>
*every* executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Arguments:
fn - function to execute with each item in the array; passed the item and the index of that item in the array
bind - the object to bind "this" to (see <Function.bind>)
Example:
>var areAllBigEnough = [10,4,25,100].every(function(item, index){
> return item > 20;
>});
>//areAllBigEnough = false
*/
every: function(fn, bind){
for (var i = 0, j = this.length; i < j; i++){
if (!fn.call(bind, this[i], i, this)) return false;
}
return true;
},
/*
Property: some
This method is provided only for browsers without native *some* support.
For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:some>
*some* executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some immediately returns true. Otherwise, some returns false. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Arguments:
fn - function to execute with each item in the array; passed the item and the index of that item in the array
bind - the object to bind "this" to (see <Function.bind>)
Example:
>var isAnyBigEnough = [10,4,25,100].some(function(item, index){
> return item > 20;
>});
>//isAnyBigEnough = true
*/
some: function(fn, bind){
for (var i = 0, j = this.length; i < j; i++){
if (fn.call(bind, this[i], i, this)) return true;
}
return false;
},
/*
Property: indexOf
This method is provided only for browsers without native *indexOf* support.
For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:indexOf>
*indexOf* compares a search element to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).
Arguments:
item - any type of object; element to locate in the array
from - integer; optional; the index of the array at which to begin the search (defaults to 0)
Example:
>['apple','lemon','banana'].indexOf('lemon'); //returns 1
>['apple','lemon'].indexOf('banana'); //returns -1
*/
indexOf: function(item, from){
var len = this.length;
for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
if (this[i] === item) return i;
}
return -1;
},
/*
Property: each
Same as <Array.forEach>.
Arguments:
fn - function to execute with each item in the array; passed the item and the index of that item in the array
bind - optional, the object that the "this" of the function will refer to.
Example:
>var Animals = ['Cat', 'Dog', 'Coala'];
>Animals.each(function(animal){
> document.write(animal)
>});
*/
/*
Property: copy
returns a copy of the array.
Returns:
a new array which is a copy of the current one.
Arguments:
start - integer; optional; the index where to start the copy, default is 0. If negative, it is taken as the offset from the end of the array.
length - integer; optional; the number of elements to copy. By default, copies all elements from start to the end of the array.
Example:
>var letters = ["a","b","c"];
>var copy = letters.copy(); // ["a","b","c"] (new instance)
*/
copy: function(start, length){
start = start || 0;
if (start < 0) start = this.length + start;
length = length || (this.length - start);
var newArray = [];
for (var i = 0; i < length; i++) newArray[i] = this[start++];
return newArray;
},
/*
Property: remove
Removes all occurrences of an item from the array.
Arguments:
item - the item to remove
Returns:
the Array with all occurrences of the item removed.
Example:
>["1","2","3","2"].remove("2") // ["1","3"];
*/
remove: function(item){
var i = 0;
var len = this.length;
while (i < len){
if (this[i] === item){
this.splice(i, 1);
len--;
} else {
i++;
}
}
return this;
},
/*
Property: contains
Tests an array for the presence of an item.
Arguments:
item - the item to search for in the array.
from - integer; optional; the index at which to begin the search, default is 0. If negative, it is taken as the offset from the end of the array.
Returns:
true - the item was found
false - it wasn't
Example:
>["a","b","c"].contains("a"); // true
>["a","b","c"].contains("d"); // false
*/
contains: function(item, from){
return this.indexOf(item, from) != -1;
},
/*
Property: associate
Creates an object with key-value pairs based on the array of keywords passed in
and the current content of the array.
Arguments:
keys - the array of keywords.
Example:
(start code)
var Animals = ['Cat', 'Dog', 'Coala', 'Lizard'];
var Speech = ['Miao', 'Bau', 'Fruuu', 'Mute'];
var Speeches = Animals.associate(Speech);
//Speeches['Miao'] is now Cat.
//Speeches['Bau'] is now Dog.
//...
(end)
*/
associate: function(keys){
var obj = {}, length = Math.min(this.length, keys.length);
for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
return obj;
},
/*
Property: extend
Extends an array with another one.
Arguments:
array - the array to extend ours with
Example:
>var Animals = ['Cat', 'Dog', 'Coala'];
>Animals.extend(['Lizard']);
>//Animals is now: ['Cat', 'Dog', 'Coala', 'Lizard'];
*/
extend: function(array){
for (var i = 0, j = array.length; i < j; i++) this.push(array[i]);
return this;
},
/*
Property: merge
merges an array in another array, without duplicates. (case- and type-sensitive)
Arguments:
array - the array to merge from.
Example:
>['Cat','Dog'].merge(['Dog','Coala']); //returns ['Cat','Dog','Coala']
*/
merge: function(array){
for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
return this;
},
/*
Property: include
includes the passed in element in the array, only if its not already present. (case- and type-sensitive)
Arguments:
item - item to add to the array (if not present)
Example:
>['Cat','Dog'].include('Dog'); //returns ['Cat','Dog']
>['Cat','Dog'].include('Coala'); //returns ['Cat','Dog','Coala']
*/
include: function(item){
if (!this.contains(item)) this.push(item);
return this;
},
/*
Property: getRandom
returns a random item in the Array
*/
getRandom: function(){
return this[$random(0, this.length - 1)] || null;
},
/*
Property: getLast
returns the last item in the Array
*/
getLast: function(){
return this[this.length - 1] || null;
}
});
//copies
Array.prototype.each = Array.prototype.forEach;
Array.each = Array.forEach;
/* Section: Utility Functions */
/*
Function: $A()
Same as <Array.copy>, but as function.
Useful to apply Array prototypes to iterable objects, as a collection of DOM elements or the arguments object.
Example:
(start code)
function myFunction(){
$A(arguments).each(argument, function(){
alert(argument);
});
};
//the above will alert all the arguments passed to the function myFunction.
(end)
*/
function $A(array){
return Array.copy(array);
};
/*
Function: $each
Use to iterate through iterables that are not regular arrays, such as builtin getElementsByTagName calls, arguments of a function, or an object.
Arguments:
iterable - an iterable element or an objct.
function - function to apply to the iterable.
bind - optional, the 'this' of the function will refer to this object.
Function argument:
The function argument will be passed the following arguments.
item - the current item in the iterator being procesed
index - integer; the index of the item, or key in case of an object.
Examples:
(start code)
$each(['Sun','Mon','Tue'], function(day, index){
alert('name:' + day + ', index: ' + index);
});
//alerts "name: Sun, index: 0", "name: Mon, index: 1", etc.
//over an object
$each({first: "Sunday", second: "Monday", third: "Tuesday"}, function(value, key){
alert("the " + key + " day of the week is " + value);
});
//alerts "the first day of the week is Sunday",
//"the second day of the week is Monday", etc.
(end)
*/
function $each(iterable, fn, bind){
if (iterable && typeof iterable.length == 'number' && $type(iterable) != 'object'){
Array.forEach(iterable, fn, bind);
} else {
for (var name in iterable) fn.call(bind || iterable, iterable[name], name);
}
};
/*compatibility*/
Array.prototype.test = Array.prototype.contains;
/*end compatibility*/
/*
Script: String.js
Contains String prototypes.
License:
MIT-style license.
*/
/*
Class: String
A collection of The String Object prototype methods.
*/
String.extend({
/*
Property: test
Tests a string with a regular expression.
Arguments:
regex - a string or regular expression object, the regular expression you want to match the string with
params - optional, if first parameter is a string, any parameters you want to pass to the regex ('g' has no effect)
Returns:
true if a match for the regular expression is found in the string, false if not.
See <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:RegExp:test>
Example:
>"I like cookies".test("cookie"); // returns true
>"I like cookies".test("COOKIE", "i") // ignore case, returns true
>"I like cookies".test("cake"); // returns false
*/
test: function(regex, params){
return (($type(regex) == 'string') ? new RegExp(regex, params) : regex).test(this);
},
/*
Property: toInt
parses a string to an integer.
Returns:
either an int or "NaN" if the string is not a number.
Example:
>var value = "10px".toInt(); // value is 10
*/
toInt: function(){
return parseInt(this, 10);
},
/*
Property: toFloat
parses a string to an float.
Returns:
either a float or "NaN" if the string is not a number.
Example:
>var value = "10.848".toFloat(); // value is 10.848
*/
toFloat: function(){
return parseFloat(this);
},
/*
Property: camelCase
Converts a hiphenated string to a camelcase string.
Example:
>"I-like-cookies".camelCase(); //"ILikeCookies"
Returns:
the camel cased string
*/
camelCase: function(){
return this.replace(/-\D/g, function(match){
return match.charAt(1).toUpperCase();
});
},
/*
Property: hyphenate
Converts a camelCased string to a hyphen-ated string.
Example:
>"ILikeCookies".hyphenate(); //"I-like-cookies"
*/
hyphenate: function(){
return this.replace(/\w[A-Z]/g, function(match){
return (match.charAt(0) + '-' + match.charAt(1).toLowerCase());
});
},
/*
Property: capitalize
Converts the first letter in each word of a string to Uppercase.
Example:
>"i like cookies".capitalize(); //"I Like Cookies"
Returns:
the capitalized string
*/
capitalize: function(){
return this.replace(/\b[a-z]/g, function(match){
return match.toUpperCase();
});
},
/*
Property: trim
Trims the leading and trailing spaces off a string.
Example:
>" i like cookies ".trim() //"i like cookies"
Returns:
the trimmed string
*/
trim: function(){
return this.replace(/^\s+|\s+$/g, '');
},
/*
Property: clean
trims (<String.trim>) a string AND removes all the double spaces in a string.
Returns:
the cleaned string
Example:
>" i like cookies \n\n".clean() //"i like cookies"
*/
clean: function(){
return this.replace(/\s{2,}/g, ' ').trim();
},
/*
Property: rgbToHex
Converts an RGB value to hexidecimal. The string must be in the format of "rgb(255,255,255)" or "rgba(255,255,255,1)";
Arguments:
array - boolean value, defaults to false. Use true if you want the array ['FF','33','00'] as output instead of "#FF3300"
Returns:
hex string or array. returns "transparent" if the output is set as string and the fourth value of rgba in input string is 0.
Example:
>"rgb(17,34,51)".rgbToHex(); //"#112233"
>"rgba(17,34,51,0)".rgbToHex(); //"transparent"
>"rgb(17,34,51)".rgbToHex(true); //['11','22','33']
*/
rgbToHex: function(array){
var rgb = this.match(/\d{1,3}/g);
return (rgb) ? rgb.rgbToHex(array) : false;
},
/*
Property: hexToRgb
Converts a hexidecimal color value to RGB. Input string must be the hex color value (with or without the hash). Also accepts triplets ('333');
Arguments:
array - boolean value, defaults to false. Use true if you want the array [255,255,255] as output instead of "rgb(255,255,255)";
Returns:
rgb string or array.
Example:
>"#112233".hexToRgb(); //"rgb(17,34,51)"
>"#112233".hexToRgb(true); //[17,34,51]
*/
hexToRgb: function(array){
var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return (hex) ? hex.slice(1).hexToRgb(array) : false;
},
/*
Property: contains
checks if the passed in string is contained in the String. also accepts an optional second parameter, to check if the string is contained in a list of separated values.
Example:
>'a b c'.contains('c', ' '); //true
>'a bc'.contains('bc'); //true
>'a bc'.contains('b', ' '); //false
*/
contains: function(string, s){
return (s) ? (s + this + s).indexOf(s + string + s) > -1 : this.indexOf(string) > -1;
},
/*
Property: escapeRegExp
Returns string with escaped regular expression characters
Example:
>var search = 'animals.sheeps[1]'.escapeRegExp(); // search is now 'animals\.sheeps\[1\]'
Returns:
Escaped string
*/
escapeRegExp: function(){
return this.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
}
});
Array.extend({
/*
Property: rgbToHex
see <String.rgbToHex>, but as an array method.
*/
rgbToHex: function(array){
if (this.length < 3) return false;
if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
var hex = [];
for (var i = 0; i < 3; i++){
var bit = (this[i] - 0).toString(16);
hex.push((bit.length == 1) ? '0' + bit : bit);
}
return array ? hex : '#' + hex.join('');
},
/*
Property: hexToRgb
same as <String.hexToRgb>, but as an array method.
*/
hexToRgb: function(array){
if (this.length != 3) return false;
var rgb = [];
for (var i = 0; i < 3; i++){
rgb.push(parseInt((this[i].length == 1) ? this[i] + this[i] : this[i], 16));
}
return array ? rgb : 'rgb(' + rgb.join(',') + ')';
}
});
/*
Script: Function.js
Contains Function prototypes and utility functions .
License:
MIT-style license.
Credits:
- Some functions are inspired by those found in prototype.js <http://prototype.conio.net/> (c) 2005 Sam Stephenson sam [at] conio [dot] net, MIT-style license
*/
/*
Class: Function
A collection of The Function Object prototype methods.
*/
Function.extend({
/*
Property: create
Main function to create closures.
Returns:
a function.
Arguments:
options - An Options object.
Options:
bind - The object that the "this" of the function will refer to. Default is the current function.
event - If set to true, the function will act as an event listener and receive an event as first argument.
If set to a class name, the function will receive a new instance of this class (with the event passed as argument's constructor) as first argument.
Default is false.
arguments - A single argument or array of arguments that will be passed to the function when called.
If both the event and arguments options are set, the event is passed as first argument and the arguments array will follow.
Default is no custom arguments, the function will receive the standard arguments when called.
delay - Numeric value: if set, the returned function will delay the actual execution by this amount of milliseconds and return a timer handle when called.
Default is no delay.
periodical - Numeric value: if set, the returned function will periodically perform the actual execution with this specified interval and return a timer handle when called.
Default is no periodical execution.
attempt - If set to true, the returned function will try to execute and return either the results or false on error. Default is false.
*/
create: function(options){
var fn = this;
options = $merge({
'bind': fn,
'event': false,
'arguments': null,
'delay': false,
'periodical': false,
'attempt': false
}, options);
if ($chk(options.arguments) && $type(options.arguments) != 'array') options.arguments = [options.arguments];
return function(event){
var args;
if (options.event){
event = event || window.event;
args = [(options.event === true) ? event : new options.event(event)];
if (options.arguments) args.extend(options.arguments);
}
else args = options.arguments || arguments;
var returns = function(){
return fn.apply($pick(options.bind, fn), args);
};
if (options.delay) return setTimeout(returns, options.delay);
if (options.periodical) return setInterval(returns, options.periodical);
if (options.attempt) try {return returns();} catch(err){return false;};
return returns();
};
},
/*
Property: pass
Shortcut to create closures with arguments and bind.
Returns:
a function.
Arguments:
args - the arguments passed. must be an array if arguments > 1
bind - optional, the object that the "this" of the function will refer to.
Example:
>myFunction.pass([arg1, arg2], myElement);
*/
pass: function(args, bind){
return this.create({'arguments': args, 'bind': bind});
},
/*
Property: attempt
Tries to execute the function, returns either the result of the function or false on error.
Arguments:
args - the arguments passed. must be an array if arguments > 1
bind - optional, the object that the "this" of the function will refer to.
Example:
>myFunction.attempt([arg1, arg2], myElement);
*/
attempt: function(args, bind){
return this.create({'arguments': args, 'bind': bind, 'attempt': true})();
},
/*
Property: bind
method to easily create closures with "this" altered.
Arguments:
bind - optional, the object that the "this" of the function will refer to.
args - optional, the arguments passed. must be an array if arguments > 1
Returns:
a function.
Example:
>function myFunction(){
> this.setStyle('color', 'red');
> // note that 'this' here refers to myFunction, not an element
> // we'll need to bind this function to the element we want to alter
>};
>var myBoundFunction = myFunction.bind(myElement);
>myBoundFunction(); // this will make the element myElement red.
*/
bind: function(bind, args){
return this.create({'bind': bind, 'arguments': args});
},
/*
Property: bindAsEventListener
cross browser method to pass event firer
Arguments:
bind - optional, the object that the "this" of the function will refer to.
args - optional, the arguments passed. must be an array if arguments > 1
Returns:
a function with the parameter bind as its "this" and as a pre-passed argument event or window.event, depending on the browser.
Example:
>function myFunction(event){
> alert(event.clientx) //returns the coordinates of the mouse..
>};
>myElement.onclick = myFunction.bindAsEventListener(myElement);
*/
bindAsEventListener: function(bind, args){
return this.create({'bind': bind, 'event': true, 'arguments': args});
},
/*
Property: delay
Delays the execution of a function by a specified duration.
Arguments:
delay - the duration to wait in milliseconds.
bind - optional, the object that the "this" of the function will refer to.
args - optional, the arguments passed. must be an array if arguments > 1
Example:
>myFunction.delay(50, myElement) //wait 50 milliseconds, then call myFunction and bind myElement to it
>(function(){alert('one second later...')}).delay(1000); //wait a second and alert
*/
delay: function(delay, bind, args){
return this.create({'delay': delay, 'bind': bind, 'arguments': args})();
},
/*
Property: periodical
Executes a function in the specified intervals of time
Arguments:
interval - the duration of the intervals between executions.
bind - optional, the object that the "this" of the function will refer to.
args - optional, the arguments passed. must be an array if arguments > 1
*/
periodical: function(interval, bind, args){
return this.create({'periodical': interval, 'bind': bind, 'arguments': args})();
}
});
/*
Script: Number.js
Contains the Number prototypes.
License:
MIT-style license.
*/
/*
Class: Number
A collection of The Number Object prototype methods.
*/
Number.extend({
/*
Property: toInt
Returns this number; useful because toInt must work on both Strings and Numbers.
*/
toInt: function(){
return parseInt(this);
},
/*
Property: toFloat
Returns this number as a float; useful because toFloat must work on both Strings and Numbers.
*/
toFloat: function(){
return parseFloat(this);
},
/*
Property: limit
Limits the number.
Arguments:
min - number, minimum value
max - number, maximum value
Returns:
the number in the given limits.
Example:
>(12).limit(2, 6.5) // returns 6.5
>(-4).limit(2, 6.5) // returns 2
>(4.3).limit(2, 6.5) // returns 4.3
*/
limit: function(min, max){
return Math.min(max, Math.max(min, this));
},
/*
Property: round
Returns the number rounded to specified precision.
Arguments:
precision - integer, number of digits after the decimal point. Can also be negative or zero (default).
Example:
>12.45.round() // returns 12
>12.45.round(1) // returns 12.5
>12.45.round(-1) // returns 10
Returns:
The rounded number.
*/
round: function(precision){
precision = Math.pow(10, precision || 0);
return Math.round(this * precision) / precision;
},
/*
Property: times
Executes a passed in function the specified number of times
Arguments:
function - the function to be executed on each iteration of the loop
Example:
>(4).times(alert);
*/
times: function(fn){
for (var i = 0; i < this; i++) fn(i);
}
});
/*
Script: Element.js
Contains useful Element prototypes, to be used with the dollar function <$>.
License:
MIT-style license.
Credits:
- Some functions are inspired by those found in prototype.js <http://prototype.conio.net/> (c) 2005 Sam Stephenson sam [at] conio [dot] net, MIT-style license
*/
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
var Element = new Class({
/*
Property: initialize
Creates a new element of the type passed in.
Arguments:
el - string; the tag name for the element you wish to create. you can also pass in an element reference, in which case it will be extended.
props - object; the properties you want to add to your element.
Accepts the same keys as <Element.setProperties>, but also allows events and styles
Props:
the key styles will be used as setStyles, the key events will be used as addEvents. any other key is used as setProperty.
Example:
(start code)
new Element('a', {
'styles': {
'display': 'block',
'border': '1px solid black'
},
'events': {
'click': function(){
//aaa
},
'mousedown': function(){
//aaa
}
},
'class': 'myClassSuperClass',
'href': 'http://mad4milk.net'
});
(end)
*/
initialize: function(el, props){
if ($type(el) == 'string'){
if (window.ie && props && (props.name || props.type)){
var name = (props.name) ? ' name="' + props.name + '"' : '';
var type = (props.type) ? ' type="' + props.type + '"' : '';
delete props.name;
delete props.type;
el = '<' + el + name + type + '>';
}
el = document.createElement(el);
}
el = $(el);
return (!props || !el) ? el : el.set(props);
}
});
/*
Class: Elements
- Every dom function such as <$$>, or in general every function that returns a collection of nodes in mootools, returns them as an Elements class.
- The purpose of the Elements class is to allow <Element> methods to work also on <Elements> array.
- Elements is also an Array, so it accepts all the <Array> methods.
- Every node of the Elements instance is already extended with <$>.
Example:
>$$('myselector').each(function(el){
> //...
>});
some iterations here, $$('myselector') is also an array.
>$$('myselector').setStyle('color', 'red');
every element returned by $$('myselector') also accepts <Element> methods, in this example every element will be made red.
*/
var Elements = new Class({
initialize: function(elements){
return (elements) ? $extend(elements, this) : this;
}
});
Elements.extend = function(props){
for (var prop in props){
this.prototype[prop] = props[prop];
this[prop] = $native.generic(prop);
}
};
/*
Section: Utility Functions
Function: $
returns the element passed in with all the Element prototypes applied.
Arguments:
el - a reference to an actual element or a string representing the id of an element
Example:
>$('myElement') // gets a DOM element by id with all the Element prototypes applied.
>var div = document.getElementById('myElement');
>$(div) //returns an Element also with all the mootools extentions applied.
You'll use this when you aren't sure if a variable is an actual element or an id, as
well as just shorthand for document.getElementById().
Returns:
a DOM element or false (if no id was found).
Note:
you need to call $ on an element only once to get all the prototypes.
But its no harm to call it multiple times, as it will detect if it has been already extended.
*/
function $(el){
if (!el) return null;
if (el.htmlElement) return Garbage.collect(el);
if ([window, document].contains(el)) return el;
var type = $type(el);
if (type == 'string'){
el = document.getElementById(el);
type = (el) ? 'element' : false;
}
if (type != 'element') return null;
if (el.htmlElement) return Garbage.collect(el);
if (['object', 'embed'].contains(el.tagName.toLowerCase())) return el;
$extend(el, Element.prototype);
el.htmlElement = function(){};
return Garbage.collect(el);
};
/*
Function: $$
Selects, and extends DOM elements. Elements arrays returned with $$ will also accept all the <Element> methods.
The return type of element methods run through $$ is always an array. If the return array is only made by elements,
$$ will be applied automatically.
Arguments:
HTML Collections, arrays of elements, arrays of strings as element ids, elements, strings as selectors.
Any number of the above as arguments are accepted.
Note:
if you load <Element.Selectors.js>, $$ will also accept CSS Selectors, otherwise the only selectors supported are tag names.
Example:
>$$('a') //an array of all anchor tags on the page
>$$('a', 'b') //an array of all anchor and bold tags on the page
>$$('#myElement') //array containing only the element with id = myElement. (only with <Element.Selectors.js>)
>$$('#myElement a.myClass') //an array of all anchor tags with the class "myClass"
>//within the DOM element with id "myElement" (only with <Element.Selectors.js>)
>$$(myelement, myelement2, 'a', ['myid', myid2, 'myid3'], document.getElementsByTagName('div')) //an array containing:
>// the element referenced as myelement if existing,
>// the element referenced as myelement2 if existing,
>// all the elements with a as tag in the page,
>// the element with id = myid if existing
>// the element with id = myid2 if existing
>// the element with id = myid3 if existing
>// all the elements with div as tag in the page
Returns:
array - array of all the dom elements matched, extended with <$>. Returns as <Elements>.
*/
document.getElementsBySelector = document.getElementsByTagName;
function $$(){
var elements = [];
for (var i = 0, j = arguments.length; i < j; i++){
var selector = arguments[i];
switch($type(selector)){
case 'element': elements.push(selector);
case 'boolean': break;
case false: break;
case 'string': selector = document.getElementsBySelector(selector, true);
default: elements.extend(selector);
}
}
return $$.unique(elements);
};
$$.unique = function(array){
var elements = [];
for (var i = 0, l = array.length; i < l; i++){
if (array[i].$included) continue;
var element = $(array[i]);
if (element && !element.$included){
element.$included = true;
elements.push(element);
}
}
for (var n = 0, d = elements.length; n < d; n++) elements[n].$included = null;
return new Elements(elements);
};
Elements.Multi = function(property){
return function(){
var args = arguments;
var items = [];
var elements = true;
for (var i = 0, j = this.length, returns; i < j; i++){
returns = this[i][property].apply(this[i], args);
if ($type(returns) != 'element') elements = false;
items.push(returns);
};
return (elements) ? $$.unique(items) : items;
};
};
Element.extend = function(properties){
for (var property in properties){
HTMLElement.prototype[property] = properties[property];
Element.prototype[property] = properties[property];
Element[property] = $native.generic(property);
var elementsProperty = (Array.prototype[property]) ? property + 'Elements' : property;
Elements.prototype[elementsProperty] = Elements.Multi(property);
}
};
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.extend({
/*
Property: set
you can set events, styles and properties with this shortcut. same as calling new Element.
*/
set: function(props){
for (var prop in props){
var val = props[prop];
switch(prop){
case 'styles': this.setStyles(val); break;
case 'events': if (this.addEvents) this.addEvents(val); break;
case 'properties': this.setProperties(val); break;
default: this.setProperty(prop, val);
}
}
return this;
},
inject: function(el, where){
el = $(el);
switch(where){
case 'before': el.parentNode.insertBefore(this, el); break;
case 'after':
var next = el.getNext();
if (!next) el.parentNode.appendChild(this);
else el.parentNode.insertBefore(this, next);
break;
case 'top':
var first = el.firstChild;
if (first){
el.insertBefore(this, first);
break;
}
default: el.appendChild(this);
}
return this;
},
/*
Property: injectBefore
Inserts the Element before the passed element.
Arguments:
el - an element reference or the id of the element to be injected in.
Example:
>html:
><div id="myElement"></div>
><div id="mySecondElement"></div>
>js:
>$('mySecondElement').injectBefore('myElement');
>resulting html:
><div id="mySecondElement"></div>
><div id="myElement"></div>
*/
injectBefore: function(el){
return this.inject(el, 'before');
},
/*
Property: injectAfter
Same as <Element.injectBefore>, but inserts the element after.
*/
injectAfter: function(el){
return this.inject(el, 'after');
},
/*
Property: injectInside
Same as <Element.injectBefore>, but inserts the element inside.
*/
injectInside: function(el){
return this.inject(el, 'bottom');
},
/*
Property: injectTop
Same as <Element.injectInside>, but inserts the element inside, at the top.
*/
injectTop: function(el){
return this.inject(el, 'top');
},
/*
Property: adopt
Inserts the passed elements inside the Element.
Arguments:
accepts elements references, element ids as string, selectors ($$('stuff')) / array of elements, array of ids as strings and collections.
*/
adopt: function(){
var elements = [];
$each(arguments, function(argument){
elements = elements.concat(argument);
});
$$(elements).inject(this);
return this;
},
/*
Property: remove
Removes the Element from the DOM.
Example:
>$('myElement').remove() //bye bye
*/
remove: function(){
return this.parentNode.removeChild(this);
},
/*
Property: clone
Clones the Element and returns the cloned one.
Arguments:
contents - boolean, when true the Element is cloned with childNodes, default true
Returns:
the cloned element
Example:
>var clone = $('myElement').clone().injectAfter('myElement');
>//clones the Element and append the clone after the Element.
*/
clone: function(contents){
var el = $(this.cloneNode(contents !== false));
if (!el.$events) return el;
el.$events = {};
for (var type in this.$events) el.$events[type] = {
'keys': $A(this.$events[type].keys),
'values': $A(this.$events[type].values)
};
return el.removeEvents();
},
/*
Property: replaceWith
Replaces the Element with an element passed.
Arguments:
el - a string representing the element to be injected in (myElementId, or div), or an element reference.
If you pass div or another tag, the element will be created.
Returns:
the passed in element
Example:
>$('myOldElement').replaceWith($('myNewElement')); //$('myOldElement') is gone, and $('myNewElement') is in its place.
*/
replaceWith: function(el){
el = $(el);
this.parentNode.replaceChild(el, this);
return el;
},
/*
Property: appendText
Appends text node to a DOM element.
Arguments:
text - the text to append.
Example:
><div id="myElement">hey</div>
>$('myElement').appendText(' howdy'); //myElement innerHTML is now "hey howdy"
*/
appendText: function(text){
this.appendChild(document.createTextNode(text));
return this;
},
/*
Property: hasClass
Tests the Element to see if it has the passed in className.
Returns:
true - the Element has the class
false - it doesn't
Arguments:
className - string; the class name to test.
Example:
><div id="myElement" class="testClass"></div>
>$('myElement').hasClass('testClass'); //returns true
*/
hasClass: function(className){
return this.className.contains(className, ' ');
},
/*
Property: addClass
Adds the passed in class to the Element, if the element doesnt already have it.
Arguments:
className - string; the class name to add
Example:
><div id="myElement" class="testClass"></div>
>$('myElement').addClass('newClass'); //<div id="myElement" class="testClass newClass"></div>
*/
addClass: function(className){
if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
return this;
},
/*
Property: removeClass
Works like <Element.addClass>, but removes the class from the element.
*/
removeClass: function(className){
this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1').clean();
return this;
},
/*
Property: toggleClass
Adds or removes the passed in class name to the element, depending on if it's present or not.
Arguments:
className - the class to add or remove
Example:
><div id="myElement" class="myClass"></div>
>$('myElement').toggleClass('myClass');
><div id="myElement" class=""></div>
>$('myElement').toggleClass('myClass');
><div id="myElement" class="myClass"></div>
*/
toggleClass: function(className){
return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);
},
/*
Property: setStyle
Sets a css property to the Element.
Arguments:
property - the property to set
value - the value to which to set it; for numeric values that require "px" you can pass an integer
Example:
>$('myElement').setStyle('width', '300px'); //the width is now 300px
>$('myElement').setStyle('width', 300); //the width is now 300px
*/
setStyle: function(property, value){
switch(property){
case 'opacity': return this.setOpacity(parseFloat(value));
case 'float': property = (window.ie) ? 'styleFloat' : 'cssFloat';
}
property = property.camelCase();
switch($type(value)){
case 'number': if (!['zIndex', 'zoom'].contains(property)) value += 'px'; break;
case 'array': value = 'rgb(' + value.join(',') + ')';
}
this.style[property] = value;
return this;
},
/*
Property: setStyles
Applies a collection of styles to the Element.
Arguments:
source - an object or string containing all the styles to apply. When its a string it overrides old style.
Examples:
>$('myElement').setStyles({
> border: '1px solid #000',
> width: 300,
> height: 400
>});
OR
>$('myElement').setStyles('border: 1px solid #000; width: 300px; height: 400px;');
*/
setStyles: function(source){
switch($type(source)){
case 'object': Element.setMany(this, 'setStyle', source); break;
case 'string': this.style.cssText = source;
}
return this;
},
/*
Property: setOpacity
Sets the opacity of the Element, and sets also visibility == "hidden" if opacity == 0, and visibility = "visible" if opacity > 0.
Arguments:
opacity - float; Accepts values from 0 to 1.
Example:
>$('myElement').setOpacity(0.5) //make it 50% transparent
*/
setOpacity: function(opacity){
if (opacity == 0){
if (this.style.visibility != "hidden") this.style.visibility = "hidden";
} else {
if (this.style.visibility != "visible") this.style.visibility = "visible";
}
if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1;
if (window.ie) this.style.filter = (opacity == 1) ? '' : "alpha(opacity=" + opacity * 100 + ")";
this.style.opacity = this.$tmp.opacity = opacity;
return this;
},
/*
Property: getStyle
Returns the style of the Element given the property passed in.
Arguments:
property - the css style property you want to retrieve
Example:
>$('myElement').getStyle('width'); //returns "400px"
>//but you can also use
>$('myElement').getStyle('width').toInt(); //returns 400
Returns:
the style as a string
*/
getStyle: function(property){
property = property.camelCase();
var result = this.style[property];
if (!$chk(result)){
if (property == 'opacity') return this.$tmp.opacity;
result = [];
for (var style in Element.Styles){
if (property == style){
Element.Styles[style].each(function(s){
var style = this.getStyle(s);
result.push(parseInt(style) ? style : '0px');
}, this);
if (property == 'border'){
var every = result.every(function(bit){
return (bit == result[0]);
});
return (every) ? result[0] : false;
}
return result.join(' ');
}
}
if (property.contains('border')){
if (Element.Styles.border.contains(property)){
return ['Width', 'Style', 'Color'].map(function(p){
return this.getStyle(property + p);
}, this).join(' ');
} else if (Element.borderShort.contains(property)){
return ['Top', 'Right', 'Bottom', 'Left'].map(function(p){
return this.getStyle('border' + p + property.replace('border', ''));
}, this).join(' ');
}
}
if (document.defaultView) result = document.defaultView.getComputedStyle(this, null).getPropertyValue(property.hyphenate());
else if (this.currentStyle) result = this.currentStyle[property];
}
if (window.ie) result = Element.fixStyle(property, result, this);
if (result && property.test(/color/i) && result.contains('rgb')){
return result.split('rgb').splice(1,4).map(function(color){
return color.rgbToHex();
}).join(' ');
}
return result;
},
/*
Property: getStyles
Returns an object of styles of the Element for each argument passed in.
Arguments:
properties - strings; any number of style properties
Example:
>$('myElement').getStyles('width','height','padding');
>//returns an object like:
>{width: "10px", height: "10px", padding: "10px 0px 10px 0px"}
*/
getStyles: function(){
return Element.getMany(this, 'getStyle', arguments);
},
walk: function(brother, start){
brother += 'Sibling';
var el = (start) ? this[start] : this[brother];
while (el && $type(el) != 'element') el = el[brother];
return $(el);
},
/*
Property: getPrevious
Returns the previousSibling of the Element, excluding text nodes.
Example:
>$('myElement').getPrevious(); //get the previous DOM element from myElement
Returns:
the sibling element or undefined if none found.
*/
getPrevious: function(){
return this.walk('previous');
},
/*
Property: getNext
Works as Element.getPrevious, but tries to find the nextSibling.
*/
getNext: function(){
return this.walk('next');
},
/*
Property: getFirst
Works as <Element.getPrevious>, but tries to find the firstChild.
*/
getFirst: function(){
return this.walk('next', 'firstChild');
},
/*
Property: getLast
Works as <Element.getPrevious>, but tries to find the lastChild.
*/
getLast: function(){
return this.walk('previous', 'lastChild');
},
/*
Property: getParent
returns the $(element.parentNode)
*/
getParent: function(){
return $(this.parentNode);
},
/*
Property: getChildren
returns all the $(element.childNodes), excluding text nodes. Returns as <Elements>.
*/
getChildren: function(){
return $$(this.childNodes);
},
/*
Property: hasChild
returns true if the passed in element is a child of the $(element).
*/
hasChild: function(el){
return !!$A(this.getElementsByTagName('*')).contains(el);
},
/*
Property: getProperty
Gets the an attribute of the Element.
Arguments:
property - string; the attribute to retrieve
Example:
>$('myImage').getProperty('src') // returns whatever.gif
Returns:
the value, or an empty string
*/
getProperty: function(property){
var index = Element.Properties[property];
if (index) return this[index];
var flag = Element.PropertiesIFlag[property] || 0;
if (!window.ie || flag) return this.getAttribute(property, flag);
var node = this.attributes[property];
return (node) ? node.nodeValue : null;
},
/*
Property: removeProperty
Removes an attribute from the Element
Arguments:
property - string; the attribute to remove
*/
removeProperty: function(property){
var index = Element.Properties[property];
if (index) this[index] = '';
else this.removeAttribute(property);
return this;
},
/*
Property: getProperties
same as <Element.getStyles>, but for properties
*/
getProperties: function(){
return Element.getMany(this, 'getProperty', arguments);
},
/*
Property: setProperty
Sets an attribute for the Element.
Arguments:
property - string; the property to assign the value passed in
value - the value to assign to the property passed in
Example:
>$('myImage').setProperty('src', 'whatever.gif'); //myImage now points to whatever.gif for its source
*/
setProperty: function(property, value){
var index = Element.Properties[property];
if (index) this[index] = value;
else this.setAttribute(property, value);
return this;
},
/*
Property: setProperties
Sets numerous attributes for the Element.
Arguments:
source - an object with key/value pairs.
Example:
(start code)
$('myElement').setProperties({
src: 'whatever.gif',
alt: 'whatever dude'
});
<img src="whatever.gif" alt="whatever dude">
(end)
*/
setProperties: function(source){
return Element.setMany(this, 'setProperty', source);
},
/*
Property: setHTML
Sets the innerHTML of the Element.
Arguments:
html - string; the new innerHTML for the element.
Example:
>$('myElement').setHTML(newHTML) //the innerHTML of myElement is now = newHTML
*/
setHTML: function(){
this.innerHTML = $A(arguments).join('');
return this;
},
/*
Property: setText
Sets the inner text of the Element.
Arguments:
text - string; the new text content for the element.
Example:
>$('myElement').setText('some text') //the text of myElement is now = 'some text'
*/
setText: function(text){
var tag = this.getTag();
if (['style', 'script'].contains(tag)){
if (window.ie){
if (tag == 'style') this.styleSheet.cssText = text;
else if (tag == 'script') this.setProperty('text', text);
return this;
} else {
this.removeChild(this.firstChild);
return this.appendText(text);
}
}
this[$defined(this.innerText) ? 'innerText' : 'textContent'] = text;
return this;
},
/*
Property: getText
Gets the inner text of the Element.
*/
getText: function(){
var tag = this.getTag();
if (['style', 'script'].contains(tag)){
if (window.ie){
if (tag == 'style') return this.styleSheet.cssText;
else if (tag == 'script') return this.getProperty('text');
} else {
return this.innerHTML;
}
}
return ($pick(this.innerText, this.textContent));
},
/*
Property: getTag
Returns the tagName of the element in lower case.
Example:
>$('myImage').getTag() // returns 'img'
Returns:
The tag name in lower case
*/
getTag: function(){
return this.tagName.toLowerCase();
},
/*
Property: empty
Empties an element of all its children.
Example:
>$('myDiv').empty() // empties the Div and returns it
Returns:
The element.
*/
empty: function(){
Garbage.trash(this.getElementsByTagName('*'));
return this.setHTML('');
}
});
Element.fixStyle = function(property, result, element){
if ($chk(parseInt(result))) return result;
if (['height', 'width'].contains(property)){
var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'];
var size = 0;
values.each(function(value){
size += element.getStyle('border-' + value + '-width').toInt() + element.getStyle('padding-' + value).toInt();
});
return element['offset' + property.capitalize()] - size + 'px';
} else if (property.test(/border(.+)Width|margin|padding/)){
return '0px';
}
return result;
};
Element.Styles = {'border': [], 'padding': [], 'margin': []};
['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
for (var style in Element.Styles) Element.Styles[style].push(style + direction);
});
Element.borderShort = ['borderWidth', 'borderStyle', 'borderColor'];
Element.getMany = function(el, method, keys){
var result = {};
$each(keys, function(key){
result[key] = el[method](key);
});
return result;
};
Element.setMany = function(el, method, pairs){
for (var key in pairs) el[method](key, pairs[key]);
return el;
};
Element.Properties = new Abstract({
'class': 'className', 'for': 'htmlFor', 'colspan': 'colSpan', 'rowspan': 'rowSpan',
'accesskey': 'accessKey', 'tabindex': 'tabIndex', 'maxlength': 'maxLength',
'readonly': 'readOnly', 'frameborder': 'frameBorder', 'value': 'value',
'disabled': 'disabled', 'checked': 'checked', 'multiple': 'multiple', 'selected': 'selected'
});
Element.PropertiesIFlag = {
'href': 2, 'src': 2
};
Element.Methods = {
Listeners: {
addListener: function(type, fn){
if (this.addEventListener) this.addEventListener(type, fn, false);
else this.attachEvent('on' + type, fn);
return this;
},
removeListener: function(type, fn){
if (this.removeEventListener) this.removeEventListener(type, fn, false);
else this.detachEvent('on' + type, fn);
return this;
}
}
};
window.extend(Element.Methods.Listeners);
document.extend(Element.Methods.Listeners);
Element.extend(Element.Methods.Listeners);
var Garbage = {
elements: [],
collect: function(el){
if (!el.$tmp){
Garbage.elements.push(el);
el.$tmp = {'opacity': 1};
}
return el;
},
trash: function(elements){
for (var i = 0, j = elements.length, el; i < j; i++){
if (!(el = elements[i]) || !el.$tmp) continue;
if (el.$events) el.fireEvent('trash').removeEvents();
for (var p in el.$tmp) el.$tmp[p] = null;
for (var d in Element.prototype) el[d] = null;
Garbage.elements[Garbage.elements.indexOf(el)] = null;
el.htmlElement = el.$tmp = el = null;
}
Garbage.elements.remove(null);
},
empty: function(){
Garbage.collect(window);
Garbage.collect(document);
Garbage.trash(Garbage.elements);
}
};
window.addListener('beforeunload', function(){
window.addListener('unload', Garbage.empty);
if (window.ie) window.addListener('unload', CollectGarbage);
});
/*
Script: Element.Event.js
Contains the Event Class, Element methods to deal with Element events, custom Events, and the Function prototype bindWithEvent.
License:
MIT-style license.
*/
/*
Class: Event
Cross browser methods to manage events.
Arguments:
event - the event
Properties:
shift - true if the user pressed the shift
control - true if the user pressed the control
alt - true if the user pressed the alt
meta - true if the user pressed the meta key
wheel - the amount of third button scrolling
code - the keycode of the key pressed
page.x - the x position of the mouse, relative to the full window
page.y - the y position of the mouse, relative to the full window
client.x - the x position of the mouse, relative to the viewport
client.y - the y position of the mouse, relative to the viewport
key - the key pressed as a lowercase string. key also returns 'enter', 'up', 'down', 'left', 'right', 'space', 'backspace', 'delete', 'esc'. Handy for these special keys.
target - the event target
relatedTarget - the event related target
Example:
(start code)
$('myLink').onkeydown = function(event){
var event = new Event(event);
//event is now the Event class.
alert(event.key); //returns the lowercase letter pressed
alert(event.shift); //returns true if the key pressed is shift
if (event.key == 's' && event.control) alert('document saved');
};
(end)
*/
var Event = new Class({
initialize: function(event){
if (event && event.$extended) return event;
this.$extended = true;
event = event || window.event;
this.event = event;
this.type = event.type;
this.target = event.target || event.srcElement;
if (this.target.nodeType == 3) this.target = this.target.parentNode;
this.shift = event.shiftKey;
this.control = event.ctrlKey;
this.alt = event.altKey;
this.meta = event.metaKey;
if (['DOMMouseScroll', 'mousewheel'].contains(this.type)){
this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
} else if (this.type.contains('key')){
this.code = event.which || event.keyCode;
for (var name in Event.keys){
if (Event.keys[name] == this.code){
this.key = name;
break;
}
}
if (this.type == 'keydown'){
var fKey = this.code - 111;
if (fKey > 0 && fKey < 13) this.key = 'f' + fKey;
}
this.key = this.key || String.fromCharCode(this.code).toLowerCase();
} else if (this.type.test(/(click|mouse|menu)/)){
this.page = {
'x': event.pageX || event.clientX + document.documentElement.scrollLeft,
'y': event.pageY || event.clientY + document.documentElement.scrollTop
};
this.client = {
'x': event.pageX ? event.pageX - window.pageXOffset : event.clientX,
'y': event.pageY ? event.pageY - window.pageYOffset : event.clientY
};
this.rightClick = (event.which == 3) || (event.button == 2);
switch(this.type){
case 'mouseover': this.relatedTarget = event.relatedTarget || event.fromElement; break;
case 'mouseout': this.relatedTarget = event.relatedTarget || event.toElement;
}
this.fixRelatedTarget();
}
return this;
},
/*
Property: stop
cross browser method to stop an event
*/
stop: function(){
return this.stopPropagation().preventDefault();
},
/*
Property: stopPropagation
cross browser method to stop the propagation of an event
*/
stopPropagation: function(){
if (this.event.stopPropagation) this.event.stopPropagation();
else this.event.cancelBubble = true;
return this;
},
/*
Property: preventDefault
cross browser method to prevent the default action of the event
*/
preventDefault: function(){
if (this.event.preventDefault) this.event.preventDefault();
else this.event.returnValue = false;
return this;
}
});
Event.fix = {
relatedTarget: function(){
if (this.relatedTarget && this.relatedTarget.nodeType == 3) this.relatedTarget = this.relatedTarget.parentNode;
},
relatedTargetGecko: function(){
try {Event.fix.relatedTarget.call(this);} catch(e){this.relatedTarget = this.target;}
}
};
Event.prototype.fixRelatedTarget = (window.gecko) ? Event.fix.relatedTargetGecko : Event.fix.relatedTarget;
/*
Property: keys
you can add additional Event keys codes this way:
Example:
(start code)
Event.keys.whatever = 80;
$(myelement).addEvent(keydown, function(event){
event = new Event(event);
if (event.key == 'whatever') console.log(whatever key clicked).
});
(end)
*/
Event.keys = new Abstract({
'enter': 13,
'up': 38,
'down': 40,
'left': 37,
'right': 39,
'esc': 27,
'space': 32,
'backspace': 8,
'tab': 9,
'delete': 46
});
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.Methods.Events = {
/*
Property: addEvent
Attaches an event listener to a DOM element.
Arguments:
type - the event to monitor ('click', 'load', etc) without the prefix 'on'.
fn - the function to execute
Example:
>$('myElement').addEvent('click', function(){alert('clicked!')});
*/
addEvent: function(type, fn){
this.$events = this.$events || {};
this.$events[type] = this.$events[type] || {'keys': [], 'values': []};
if (this.$events[type].keys.contains(fn)) return this;
this.$events[type].keys.push(fn);
var realType = type;
var custom = Element.Events[type];
if (custom){
if (custom.add) custom.add.call(this, fn);
if (custom.map) fn = custom.map;
if (custom.type) realType = custom.type;
}
if (!this.addEventListener) fn = fn.create({'bind': this, 'event': true});
this.$events[type].values.push(fn);
return (Element.NativeEvents.contains(realType)) ? this.addListener(realType, fn) : this;
},
/*
Property: removeEvent
Works as Element.addEvent, but instead removes the previously added event listener.
*/
removeEvent: function(type, fn){
if (!this.$events || !this.$events[type]) return this;
var pos = this.$events[type].keys.indexOf(fn);
if (pos == -1) return this;
var key = this.$events[type].keys.splice(pos,1)[0];
var value = this.$events[type].values.splice(pos,1)[0];
var custom = Element.Events[type];
if (custom){
if (custom.remove) custom.remove.call(this, fn);
if (custom.type) type = custom.type;
}
return (Element.NativeEvents.contains(type)) ? this.removeListener(type, value) : this;
},
/*
Property: addEvents
As <addEvent>, but accepts an object and add multiple events at once.
*/
addEvents: function(source){
return Element.setMany(this, 'addEvent', source);
},
/*
Property: removeEvents
removes all events of a certain type from an element. if no argument is passed in, removes all events.
Arguments:
type - string; the event name (e.g. 'click')
*/
removeEvents: function(type){
if (!this.$events) return this;
if (!type){
for (var evType in this.$events) this.removeEvents(evType);
this.$events = null;
} else if (this.$events[type]){
this.$events[type].keys.each(function(fn){
this.removeEvent(type, fn);
}, this);
this.$events[type] = null;
}
return this;
},
/*
Property: fireEvent
executes all events of the specified type present in the element.
Arguments:
type - string; the event name (e.g. 'click')
args - array or single object; arguments to pass to the function; if more than one argument, must be an array
delay - (integer) delay (in ms) to wait to execute the event
*/
fireEvent: function(type, args, delay){
if (this.$events && this.$events[type]){
this.$events[type].keys.each(function(fn){
fn.create({'bind': this, 'delay': delay, 'arguments': args})();
}, this);
}
return this;
},
/*
Property: cloneEvents
Clones all events from an element to this element.
Arguments:
from - element, copy all events from this element
type - optional, copies only events of this type
*/
cloneEvents: function(from, type){
if (!from.$events) return this;
if (!type){
for (var evType in from.$events) this.cloneEvents(from, evType);
} else if (from.$events[type]){
from.$events[type].keys.each(function(fn){
this.addEvent(type, fn);
}, this);
}
return this;
}
};
window.extend(Element.Methods.Events);
document.extend(Element.Methods.Events);
Element.extend(Element.Methods.Events);
/* Section: Custom Events */
Element.Events = new Abstract({
/*
Event: mouseenter
In addition to the standard javascript events (load, mouseover, mouseout, click, etc.) <Event.js> contains two custom events
this event fires when the mouse enters the area of the dom element; will not be fired again if the mouse crosses over children of the element (unlike mouseover)
Example:
>$(myElement).addEvent('mouseenter', myFunction);
*/
'mouseenter': {
type: 'mouseover',
map: function(event){
event = new Event(event);
if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseenter', event);
}
},
/*
Event: mouseleave
this event fires when the mouse exits the area of the dom element; will not be fired again if the mouse crosses over children of the element (unlike mouseout)
Example:
>$(myElement).addEvent('mouseleave', myFunction);
*/
'mouseleave': {
type: 'mouseout',
map: function(event){
event = new Event(event);
if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseleave', event);
}
},
'mousewheel': {
type: (window.gecko) ? 'DOMMouseScroll' : 'mousewheel'
}
});
Element.NativeEvents = [
'click', 'dblclick', 'mouseup', 'mousedown', //mouse buttons
'mousewheel', 'DOMMouseScroll', //mouse wheel
'mouseover', 'mouseout', 'mousemove', //mouse movement
'keydown', 'keypress', 'keyup', //keys
'load', 'unload', 'beforeunload', 'resize', 'move', //window
'focus', 'blur', 'change', 'submit', 'reset', 'select', //forms elements
'error', 'abort', 'contextmenu', 'scroll' //misc
];
/*
Class: Function
A collection of The Function Object prototype methods.
*/
Function.extend({
/*
Property: bindWithEvent
automatically passes MooTools Event Class.
Arguments:
bind - optional, the object that the "this" of the function will refer to.
args - optional, an argument to pass to the function; if more than one argument, it must be an array of arguments.
Returns:
a function with the parameter bind as its "this" and as a pre-passed argument event or window.event, depending on the browser.
Example:
>function myFunction(event){
> alert(event.client.x) //returns the coordinates of the mouse..
>};
>myElement.addEvent('click', myFunction.bindWithEvent(myElement));
*/
bindWithEvent: function(bind, args){
return this.create({'bind': bind, 'arguments': args, 'event': Event});
}
});
/*
Script: Element.Filters.js
add Filters capability to <Elements>.
License:
MIT-style license.
*/
/*
Class: Elements
A collection of methods to be used with <$$> elements collections.
*/
Elements.extend({
/*
Property: filterByTag
Filters the collection by a specified tag name.
Returns a new Elements collection, while the original remains untouched.
*/
filterByTag: function(tag){
return new Elements(this.filter(function(el){
return (Element.getTag(el) == tag);
}));
},
/*
Property: filterByClass
Filters the collection by a specified class name.
Returns a new Elements collection, while the original remains untouched.
*/
filterByClass: function(className, nocash){
var elements = this.filter(function(el){
return (el.className && el.className.contains(className, ' '));
});
return (nocash) ? elements : new Elements(elements);
},
/*
Property: filterById
Filters the collection by a specified ID.
Returns a new Elements collection, while the original remains untouched.
*/
filterById: function(id, nocash){
var elements = this.filter(function(el){
return (el.id == id);
});
return (nocash) ? elements : new Elements(elements);
},
/*
Property: filterByAttribute
Filters the collection by a specified attribute.
Returns a new Elements collection, while the original remains untouched.
Arguments:
name - the attribute name.
operator - optional, the attribute operator.
value - optional, the attribute value, only valid if the operator is specified.
*/
filterByAttribute: function(name, operator, value, nocash){
var elements = this.filter(function(el){
var current = Element.getProperty(el, name);
if (!current) return false;
if (!operator) return true;
switch(operator){
case '=': return (current == value);
case '*=': return (current.contains(value));
case '^=': return (current.substr(0, value.length) == value);
case '$=': return (current.substr(current.length - value.length) == value);
case '!=': return (current != value);
case '~=': return current.contains(value, ' ');
}
return false;
});
return (nocash) ? elements : new Elements(elements);
}
});
/*
Script: Element.Selectors.js
Css Query related functions and <Element> extensions
License:
MIT-style license.
*/
/* Section: Utility Functions */
/*
Function: $E
Selects a single (i.e. the first found) Element based on the selector passed in and an optional filter element.
Returns as <Element>.
Arguments:
selector - string; the css selector to match
filter - optional; a DOM element to limit the scope of the selector match; defaults to document.
Example:
>$E('a', 'myElement') //find the first anchor tag inside the DOM element with id 'myElement'
Returns:
a DOM element - the first element that matches the selector
*/
function $E(selector, filter){
return ($(filter) || document).getElement(selector);
};
/*
Function: $ES
Returns a collection of Elements that match the selector passed in limited to the scope of the optional filter.
See Also: <Element.getElements> for an alternate syntax.
Returns as <Elements>.
Returns:
an array of dom elements that match the selector within the filter
Arguments:
selector - string; css selector to match
filter - optional; a DOM element to limit the scope of the selector match; defaults to document.
Examples:
>$ES("a") //gets all the anchor tags; synonymous with $$("a")
>$ES('a','myElement') //get all the anchor tags within $('myElement')
*/
function $ES(selector, filter){
return ($(filter) || document).getElementsBySelector(selector);
};
$$.shared = {
'regexp': /^(\w*|\*)(?:#([\w-]+)|\.([\w-]+))?(?:\[(\w+)(?:([!*^$]?=)["']?([^"'\]]*)["']?)?])?$/,
'xpath': {
getParam: function(items, context, param, i){
var temp = [context.namespaceURI ? 'xhtml:' : '', param[1]];
if (param[2]) temp.push('[@id="', param[2], '"]');
if (param[3]) temp.push('[contains(concat(" ", @class, " "), " ', param[3], ' ")]');
if (param[4]){
if (param[5] && param[6]){
switch(param[5]){
case '*=': temp.push('[contains(@', param[4], ', "', param[6], '")]'); break;
case '^=': temp.push('[starts-with(@', param[4], ', "', param[6], '")]'); break;
case '$=': temp.push('[substring(@', param[4], ', string-length(@', param[4], ') - ', param[6].length, ' + 1) = "', param[6], '"]'); break;
case '=': temp.push('[@', param[4], '="', param[6], '"]'); break;
case '!=': temp.push('[@', param[4], '!="', param[6], '"]');
}
} else {
temp.push('[@', param[4], ']');
}
}
items.push(temp.join(''));
return items;
},
getItems: function(items, context, nocash){
var elements = [];
var xpath = document.evaluate('.//' + items.join('//'), context, $$.shared.resolver, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0, j = xpath.snapshotLength; i < j; i++) elements.push(xpath.snapshotItem(i));
return (nocash) ? elements : new Elements(elements.map($));
}
},
'normal': {
getParam: function(items, context, param, i){
if (i == 0){
if (param[2]){
var el = context.getElementById(param[2]);
if (!el || ((param[1] != '*') && (Element.getTag(el) != param[1]))) return false;
items = [el];
} else {
items = $A(context.getElementsByTagName(param[1]));
}
} else {
items = $$.shared.getElementsByTagName(items, param[1]);
if (param[2]) items = Elements.filterById(items, param[2], true);
}
if (param[3]) items = Elements.filterByClass(items, param[3], true);
if (param[4]) items = Elements.filterByAttribute(items, param[4], param[5], param[6], true);
return items;
},
getItems: function(items, context, nocash){
return (nocash) ? items : $$.unique(items);
}
},
resolver: function(prefix){
return (prefix == 'xhtml') ? 'http://www.w3.org/1999/xhtml' : false;
},
getElementsByTagName: function(context, tagName){
var found = [];
for (var i = 0, j = context.length; i < j; i++) found.extend(context[i].getElementsByTagName(tagName));
return found;
}
};
$$.shared.method = (window.xpath) ? 'xpath' : 'normal';
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.Methods.Dom = {
/*
Property: getElements
Gets all the elements within an element that match the given (single) selector.
Returns as <Elements>.
Arguments:
selector - string; the css selector to match
Examples:
>$('myElement').getElements('a'); // get all anchors within myElement
>$('myElement').getElements('input[name=dialog]') //get all input tags with name 'dialog'
>$('myElement').getElements('input[name$=log]') //get all input tags with names ending with 'log'
Notes:
Supports these operators in attribute selectors:
- = : is equal to
- ^= : starts-with
- $= : ends-with
- != : is not equal to
Xpath is used automatically for compliant browsers.
*/
getElements: function(selector, nocash){
var items = [];
selector = selector.trim().split(' ');
for (var i = 0, j = selector.length; i < j; i++){
var sel = selector[i];
var param = sel.match($$.shared.regexp);
if (!param) break;
param[1] = param[1] || '*';
var temp = $$.shared[$$.shared.method].getParam(items, this, param, i);
if (!temp) break;
items = temp;
}
return $$.shared[$$.shared.method].getItems(items, this, nocash);
},
/*
Property: getElement
Same as <Element.getElements>, but returns only the first. Alternate syntax for <$E>, where filter is the Element.
Returns as <Element>.
Arguments:
selector - string; css selector
*/
getElement: function(selector){
return $(this.getElements(selector, true)[0] || false);
},
/*
Property: getElementsBySelector
Same as <Element.getElements>, but allows for comma separated selectors, as in css. Alternate syntax for <$$>, where filter is the Element.
Returns as <Elements>.
Arguments:
selector - string; css selector
*/
getElementsBySelector: function(selector, nocash){
var elements = [];
selector = selector.split(',');
for (var i = 0, j = selector.length; i < j; i++) elements = elements.concat(this.getElements(selector[i], true));
return (nocash) ? elements : $$.unique(elements);
}
};
Element.extend({
/*
Property: getElementById
Targets an element with the specified id found inside the Element. Does not overwrite document.getElementById.
Arguments:
id - string; the id of the element to find.
*/
getElementById: function(id){
var el = document.getElementById(id);
if (!el) return false;
for (var parent = el.parentNode; parent != this; parent = parent.parentNode){
if (!parent) return false;
}
return el;
}/*compatibility*/,
getElementsByClassName: function(className){
return this.getElements('.' + className);
}
/*end compatibility*/
});
document.extend(Element.Methods.Dom);
Element.extend(Element.Methods.Dom);
/*
Script: Element.Form.js
Contains Element prototypes to deal with Forms and their elements.
License:
MIT-style license.
*/
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.extend({
/*
Property: getValue
Returns the value of the Element, if its tag is textarea, select or input. getValue called on a multiple select will return an array.
*/
getValue: function(){
switch(this.getTag()){
case 'select':
var values = [];
$each(this.options, function(option){
if (option.selected) values.push($pick(option.value, option.text));
});
return (this.multiple) ? values : values[0];
case 'input': if (!(this.checked && ['checkbox', 'radio'].contains(this.type)) && !['hidden', 'text', 'password'].contains(this.type)) break;
case 'textarea': return this.value;
}
return false;
},
getFormElements: function(){
return $$(this.getElementsByTagName('input'), this.getElementsByTagName('select'), this.getElementsByTagName('textarea'));
},
/*
Property: toQueryString
Reads the children inputs of the Element and generates a query string, based on their values. Used internally in <Ajax>
Example:
(start code)
<form id="myForm" action="submit.php">
<input name="email" value="bob@bob.com">
<input name="zipCode" value="90210">
</form>
<script>
$('myForm').toQueryString()
</script>
(end)
Returns:
email=bob@bob.com&zipCode=90210
*/
toQueryString: function(){
var queryString = [];
this.getFormElements().each(function(el){
var name = el.name;
var value = el.getValue();
if (value === false || !name || el.disabled) return;
var qs = function(val){
queryString.push(name + '=' + encodeURIComponent(val));
};
if ($type(value) == 'array') value.each(qs);
else qs(value);
});
return queryString.join('&');
}
});
/*
Script: Element.Dimensions.js
Contains Element prototypes to deal with Element size and position in space.
Note:
The functions in this script require n XHTML doctype.
License:
MIT-style license.
*/
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.extend({
/*
Property: scrollTo
Scrolls the element to the specified coordinated (if the element has an overflow)
Arguments:
x - the x coordinate
y - the y coordinate
Example:
>$('myElement').scrollTo(0, 100)
*/
scrollTo: function(x, y){
this.scrollLeft = x;
this.scrollTop = y;
},
/*
Property: getSize
Return an Object representing the size/scroll values of the element.
Example:
(start code)
$('myElement').getSize();
(end)
Returns:
(start code)
{
'scroll': {'x': 100, 'y': 100},
'size': {'x': 200, 'y': 400},
'scrollSize': {'x': 300, 'y': 500}
}
(end)
*/
getSize: function(){
return {
'scroll': {'x': this.scrollLeft, 'y': this.scrollTop},
'size': {'x': this.offsetWidth, 'y': this.offsetHeight},
'scrollSize': {'x': this.scrollWidth, 'y': this.scrollHeight}
};
},
/*
Property: getPosition
Returns the real offsets of the element.
Arguments:
overflown - optional, an array of nested scrolling containers for scroll offset calculation, use this if your element is inside any element containing scrollbars
Example:
>$('element').getPosition();
Returns:
>{x: 100, y:500};
*/
getPosition: function(overflown){
overflown = overflown || [];
var el = this, left = 0, top = 0;
do {
left += el.offsetLeft || 0;
top += el.offsetTop || 0;
el = el.offsetParent;
} while (el);
overflown.each(function(element){
left -= element.scrollLeft || 0;
top -= element.scrollTop || 0;
});
return {'x': left, 'y': top};
},
/*
Property: getTop
Returns the distance from the top of the window to the Element.
Arguments:
overflown - optional, an array of nested scrolling containers, see Element::getPosition
*/
getTop: function(overflown){
return this.getPosition(overflown).y;
},
/*
Property: getLeft
Returns the distance from the left of the window to the Element.
Arguments:
overflown - optional, an array of nested scrolling containers, see Element::getPosition
*/
getLeft: function(overflown){
return this.getPosition(overflown).x;
},
/*
Property: getCoordinates
Returns an object with width, height, left, right, top, and bottom, representing the values of the Element
Arguments:
overflown - optional, an array of nested scrolling containers, see Element::getPosition
Example:
(start code)
var myValues = $('myElement').getCoordinates();
(end)
Returns:
(start code)
{
width: 200,
height: 300,
left: 100,
top: 50,
right: 300,
bottom: 350
}
(end)
*/
getCoordinates: function(overflown){
var position = this.getPosition(overflown);
var obj = {
'width': this.offsetWidth,
'height': this.offsetHeight,
'left': position.x,
'top': position.y
};
obj.right = obj.left + obj.width;
obj.bottom = obj.top + obj.height;
return obj;
}
});
/*
Script: Window.DomReady.js
Contains the custom event domready, for window.
License:
MIT-style license.
*/
/* Section: Custom Events */
/*
Event: domready
executes a function when the dom tree is loaded, without waiting for images. Only works when called from window.
Credits:
(c) Dean Edwards/Matthias Miller/John Resig, remastered for MooTools.
Arguments:
fn - the function to execute when the DOM is ready
Example:
> window.addEvent('domready', function(){
> alert('the dom is ready');
> });
*/
Element.Events.domready = {
add: function(fn){
if (window.loaded){
fn.call(this);
return;
}
var domReady = function(){
if (window.loaded) return;
window.loaded = true;
window.timer = $clear(window.timer);
this.fireEvent('domready');
}.bind(this);
if (document.readyState && window.webkit){
window.timer = function(){
if (['loaded','complete'].contains(document.readyState)) domReady();
}.periodical(50);
} else if (document.readyState && window.ie){
if (!$('ie_ready')){
var src = (window.location.protocol == 'https:') ? '://0' : 'javascript:void(0)';
document.write('<script id="ie_ready" defer src="' + src + '"><\/script>');
$('ie_ready').onreadystatechange = function(){
if (this.readyState == 'complete') domReady();
};
}
} else {
window.addListener("load", domReady);
document.addListener("DOMContentLoaded", domReady);
}
}
};
/*compatibility*/
window.onDomReady = function(fn){
return this.addEvent('domready', fn);
};
/*end compatibility*/
/*
Script: Window.Size.js
Window cross-browser dimensions methods.
Note:
The Functions in this script require an XHTML doctype.
License:
MIT-style license.
*/
/*
Class: window
Cross browser methods to get various window dimensions.
Warning: All these methods require that the browser operates in strict mode, not quirks mode.
*/
window.extend({
/*
Property: getWidth
Returns an integer representing the width of the browser window (without the scrollbar).
*/
getWidth: function(){
if (this.webkit419) return this.innerWidth;
if (this.opera) return document.body.clientWidth;
return document.documentElement.clientWidth;
},
/*
Property: getHeight
Returns an integer representing the height of the browser window (without the scrollbar).
*/
getHeight: function(){
if (this.webkit419) return this.innerHeight;
if (this.opera) return document.body.clientHeight;
return document.documentElement.clientHeight;
},
/*
Property: getScrollWidth
Returns an integer representing the scrollWidth of the window.
This value is equal to or bigger than <getWidth>.
See Also:
<http://developer.mozilla.org/en/docs/DOM:element.scrollWidth>
*/
getScrollWidth: function(){
if (this.ie) return Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth);
if (this.webkit) return document.body.scrollWidth;
return document.documentElement.scrollWidth;
},
/*
Property: getScrollHeight
Returns an integer representing the scrollHeight of the window.
This value is equal to or bigger than <getHeight>.
See Also:
<http://developer.mozilla.org/en/docs/DOM:element.scrollHeight>
*/
getScrollHeight: function(){
if (this.ie) return Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight);
if (this.webkit) return document.body.scrollHeight;
return document.documentElement.scrollHeight;
},
/*
Property: getScrollLeft
Returns an integer representing the scrollLeft of the window (the number of pixels the window has scrolled from the left).
See Also:
<http://developer.mozilla.org/en/docs/DOM:element.scrollLeft>
*/
getScrollLeft: function(){
return this.pageXOffset || document.documentElement.scrollLeft;
},
/*
Property: getScrollTop
Returns an integer representing the scrollTop of the window (the number of pixels the window has scrolled from the top).
See Also:
<http://developer.mozilla.org/en/docs/DOM:element.scrollTop>
*/
getScrollTop: function(){
return this.pageYOffset || document.documentElement.scrollTop;
},
/*
Property: getSize
Same as <Element.getSize>
*/
getSize: function(){
return {
'size': {'x': this.getWidth(), 'y': this.getHeight()},
'scrollSize': {'x': this.getScrollWidth(), 'y': this.getScrollHeight()},
'scroll': {'x': this.getScrollLeft(), 'y': this.getScrollTop()}
};
},
//ignore
getPosition: function(){return {'x': 0, 'y': 0};}
});
/*
Script: Fx.Base.js
Contains <Fx.Base>, the foundamentals of the MooTools Effects.
License:
MIT-style license.
*/
var Fx = {};
/*
Class: Fx.Base
Base class for the Effects.
Options:
transition - the equation to use for the effect see <Fx.Transitions>; default is <Fx.Transitions.Sine.easeInOut>
duration - the duration of the effect in ms; 500 is the default.
unit - the unit is 'px' by default (other values include things like 'em' for fonts or '%').
wait - boolean: to wait or not to wait for a current transition to end before running another of the same instance. defaults to true.
fps - the frames per second for the transition; default is 50
Events:
onStart - the function to execute as the effect begins; nothing (<Class.empty>) by default.
onComplete - the function to execute after the effect has processed; nothing (<Class.empty>) by default.
onCancel - the function to execute when you manually stop the effect.
*/
Fx.Base = new Class({
options: {
onStart: Class.empty,
onComplete: Class.empty,
onCancel: Class.empty,
transition: function(p){
return -(Math.cos(Math.PI * p) - 1) / 2;
},
duration: 500,
unit: 'px',
wait: true,
fps: 50
},
initialize: function(options){
this.element = this.element || null;
this.setOptions(options);
if (this.options.initialize) this.options.initialize.call(this);
},
step: function(){
var time = $time();
if (time < this.time + this.options.duration){
this.delta = this.options.transition((time - this.time) / this.options.duration);
this.setNow();
this.increase();
} else {
this.stop(true);
this.set(this.to);
this.fireEvent('onComplete', this.element, 10);
this.callChain();
}
},
/*
Property: set
Immediately sets the value with no transition.
Arguments:
to - the point to jump to
Example:
>var myFx = new Fx.Style('myElement', 'opacity').set(0); //will make it immediately transparent
*/
set: function(to){
this.now = to;
this.increase();
return this;
},
setNow: function(){
this.now = this.compute(this.from, this.to);
},
compute: function(from, to){
return (to - from) * this.delta + from;
},
/*
Property: start
Executes an effect from one position to the other.
Arguments:
from - integer: staring value
to - integer: the ending value
Examples:
>var myFx = new Fx.Style('myElement', 'opacity').start(0,1); //display a transition from transparent to opaque.
*/
start: function(from, to){
if (!this.options.wait) this.stop();
else if (this.timer) return this;
this.from = from;
this.to = to;
this.change = this.to - this.from;
this.time = $time();
this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this);
this.fireEvent('onStart', this.element);
return this;
},
/*
Property: stop
Stops the transition.
*/
stop: function(end){
if (!this.timer) return this;
this.timer = $clear(this.timer);
if (!end) this.fireEvent('onCancel', this.element);
return this;
}/*compatibility*/,
custom: function(from, to){
return this.start(from, to);
},
clearTimer: function(end){
return this.stop(end);
}
/*end compatibility*/
});
Fx.Base.implement(new Chain, new Events, new Options);
/*
Script: Fx.CSS.js
Css parsing class for effects. Required by <Fx.Style>, <Fx.Styles>, <Fx.Elements>. No documentation needed, as its used internally.
License:
MIT-style license.
*/
Fx.CSS = {
select: function(property, to){
if (property.test(/color/i)) return this.Color;
var type = $type(to);
if ((type == 'array') || (type == 'string' && to.contains(' '))) return this.Multi;
return this.Single;
},
parse: function(el, property, fromTo){
if (!fromTo.push) fromTo = [fromTo];
var from = fromTo[0], to = fromTo[1];
if (!$chk(to)){
to = from;
from = el.getStyle(property);
}
var css = this.select(property, to);
return {'from': css.parse(from), 'to': css.parse(to), 'css': css};
}
};
Fx.CSS.Single = {
parse: function(value){
return parseFloat(value);
},
getNow: function(from, to, fx){
return fx.compute(from, to);
},
getValue: function(value, unit, property){
if (unit == 'px' && property != 'opacity') value = Math.round(value);
return value + unit;
}
};
Fx.CSS.Multi = {
parse: function(value){
return value.push ? value : value.split(' ').map(function(v){
return parseFloat(v);
});
},
getNow: function(from, to, fx){
var now = [];
for (var i = 0; i < from.length; i++) now[i] = fx.compute(from[i], to[i]);
return now;
},
getValue: function(value, unit, property){
if (unit == 'px' && property != 'opacity') value = value.map(Math.round);
return value.join(unit + ' ') + unit;
}
};
Fx.CSS.Color = {
parse: function(value){
return value.push ? value : value.hexToRgb(true);
},
getNow: function(from, to, fx){
var now = [];
for (var i = 0; i < from.length; i++) now[i] = Math.round(fx.compute(from[i], to[i]));
return now;
},
getValue: function(value){
return 'rgb(' + value.join(',') + ')';
}
};
/*
Script: Fx.Style.js
Contains <Fx.Style>
License:
MIT-style license.
*/
/*
Class: Fx.Style
The Style effect, used to transition any css property from one value to another. Includes colors.
Colors must be in hex format.
Inherits methods, properties, options and events from <Fx.Base>.
Arguments:
el - the $(element) to apply the style transition to
property - the property to transition
options - the Fx.Base options (see: <Fx.Base>)
Example:
>var marginChange = new Fx.Style('myElement', 'margin-top', {duration:500});
>marginChange.start(10, 100);
*/
Fx.Style = Fx.Base.extend({
initialize: function(el, property, options){
this.element = $(el);
this.property = property;
this.parent(options);
},
/*
Property: hide
Same as <Fx.Base.set> (0); hides the element immediately without transition.
*/
hide: function(){
return this.set(0);
},
setNow: function(){
this.now = this.css.getNow(this.from, this.to, this);
},
/*
Property: set
Sets the element's css property (specified at instantiation) to the specified value immediately.
Example:
(start code)
var marginChange = new Fx.Style('myElement', 'margin-top', {duration:500});
marginChange.set(10); //margin-top is set to 10px immediately
(end)
*/
set: function(to){
this.css = Fx.CSS.select(this.property, to);
return this.parent(this.css.parse(to));
},
/*
Property: start
Displays the transition to the value/values passed in
Arguments:
from - (integer; optional) the starting position for the transition
to - (integer) the ending position for the transition
Note:
If you provide only one argument, the transition will use the current css value for its starting value.
Example:
(start code)
var marginChange = new Fx.Style('myElement', 'margin-top', {duration:500});
marginChange.start(10); //tries to read current margin top value and goes from current to 10
(end)
*/
start: function(from, to){
if (this.timer && this.options.wait) return this;
var parsed = Fx.CSS.parse(this.element, this.property, [from, to]);
this.css = parsed.css;
return this.parent(parsed.from, parsed.to);
},
increase: function(){
this.element.setStyle(this.property, this.css.getValue(this.now, this.options.unit, this.property));
}
});
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.extend({
/*
Property: effect
Applies an <Fx.Style> to the Element; This a shortcut for <Fx.Style>.
Arguments:
property - (string) the css property to alter
options - (object; optional) key/value set of options (see <Fx.Style>)
Example:
>var myEffect = $('myElement').effect('height', {duration: 1000, transition: Fx.Transitions.linear});
>myEffect.start(10, 100);
>//OR
>$('myElement').effect('height', {duration: 1000, transition: Fx.Transitions.linear}).start(10,100);
*/
effect: function(property, options){
return new Fx.Style(this, property, options);
}
});
/*
Script: Fx.Styles.js
Contains <Fx.Styles>
License:
MIT-style license.
*/
/*
Class: Fx.Styles
Allows you to animate multiple css properties at once;
Colors must be in hex format.
Inherits methods, properties, options and events from <Fx.Base>.
Arguments:
el - the $(element) to apply the styles transition to
options - the fx options (see: <Fx.Base>)
Example:
(start code)
var myEffects = new Fx.Styles('myElement', {duration: 1000, transition: Fx.Transitions.linear});
//height from 10 to 100 and width from 900 to 300
myEffects.start({
'height': [10, 100],
'width': [900, 300]
});
//or height from current height to 100 and width from current width to 300
myEffects.start({
'height': 100,
'width': 300
});
(end)
*/
Fx.Styles = Fx.Base.extend({
initialize: function(el, options){
this.element = $(el);
this.parent(options);
},
setNow: function(){
for (var p in this.from) this.now[p] = this.css[p].getNow(this.from[p], this.to[p], this);
},
set: function(to){
var parsed = {};
this.css = {};
for (var p in to){
this.css[p] = Fx.CSS.select(p, to[p]);
parsed[p] = this.css[p].parse(to[p]);
}
return this.parent(parsed);
},
/*
Property: start
Executes a transition for any number of css properties in tandem.
Arguments:
obj - an object containing keys that specify css properties to alter and values that specify either the from/to values (as an array) or just the end value (an integer).
Example:
see <Fx.Styles>
*/
start: function(obj){
if (this.timer && this.options.wait) return this;
this.now = {};
this.css = {};
var from = {}, to = {};
for (var p in obj){
var parsed = Fx.CSS.parse(this.element, p, obj[p]);
from[p] = parsed.from;
to[p] = parsed.to;
this.css[p] = parsed.css;
}
return this.parent(from, to);
},
increase: function(){
for (var p in this.now) this.element.setStyle(p, this.css[p].getValue(this.now[p], this.options.unit, p));
}
});
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.extend({
/*
Property: effects
Applies an <Fx.Styles> to the Element; This a shortcut for <Fx.Styles>.
Example:
>var myEffects = $(myElement).effects({duration: 1000, transition: Fx.Transitions.Sine.easeInOut});
>myEffects.start({'height': [10, 100], 'width': [900, 300]});
*/
effects: function(options){
return new Fx.Styles(this, options);
}
});
/*
Script: Fx.Elements.js
Contains <Fx.Elements>
License:
MIT-style license.
*/
/*
Class: Fx.Elements
Fx.Elements allows you to apply any number of styles transitions to a selection of elements. Includes colors (must be in hex format).
Inherits methods, properties, options and events from <Fx.Base>.
Arguments:
elements - a collection of elements the effects will be applied to.
options - same as <Fx.Base> options.
*/
Fx.Elements = Fx.Base.extend({
initialize: function(elements, options){
this.elements = $$(elements);
this.parent(options);
},
setNow: function(){
for (var i in this.from){
var iFrom = this.from[i], iTo = this.to[i], iCss = this.css[i], iNow = this.now[i] = {};
for (var p in iFrom) iNow[p] = iCss[p].getNow(iFrom[p], iTo[p], this);
}
},
set: function(to){
var parsed = {};
this.css = {};
for (var i in to){
var iTo = to[i], iCss = this.css[i] = {}, iParsed = parsed[i] = {};
for (var p in iTo){
iCss[p] = Fx.CSS.select(p, iTo[p]);
iParsed[p] = iCss[p].parse(iTo[p]);
}
}
return this.parent(parsed);
},
/*
Property: start
Applies the passed in style transitions to each object named (see example). Each item in the collection is refered to as a numerical string ("1" for instance). The first item is "0", the second "1", etc.
Example:
(start code)
var myElementsEffects = new Fx.Elements($$('a'));
myElementsEffects.start({
'0': { //let's change the first element's opacity and width
'opacity': [0,1],
'width': [100,200]
},
'4': { //and the fifth one's opacity
'opacity': [0.2, 0.5]
}
});
(end)
*/
start: function(obj){
if (this.timer && this.options.wait) return this;
this.now = {};
this.css = {};
var from = {}, to = {};
for (var i in obj){
var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {}, iCss = this.css[i] = {};
for (var p in iProps){
var parsed = Fx.CSS.parse(this.elements[i], p, iProps[p]);
iFrom[p] = parsed.from;
iTo[p] = parsed.to;
iCss[p] = parsed.css;
}
}
return this.parent(from, to);
},
increase: function(){
for (var i in this.now){
var iNow = this.now[i], iCss = this.css[i];
for (var p in iNow) this.elements[i].setStyle(p, iCss[p].getValue(iNow[p], this.options.unit, p));
}
}
});
/*
Script: Fx.Scroll.js
Contains <Fx.Scroll>
License:
MIT-style license.
*/
/*
Class: Fx.Scroll
Scroll any element with an overflow, including the window element.
Inherits methods, properties, options and events from <Fx.Base>.
Note:
Fx.Scroll requires an XHTML doctype.
Arguments:
element - the element to scroll
options - optional, see Options below.
Options:
all the Fx.Base options and events, plus:
offset - the distance for the scrollTo point/element. an Object with x/y properties.
overflown - an array of nested scrolling containers, see <Element.getPosition>
*/
Fx.Scroll = Fx.Base.extend({
options: {
overflown: [],
offset: {'x': 0, 'y': 0},
wheelStops: true
},
initialize: function(element, options){
this.now = [];
this.element = $(element);
this.bound = {'stop': this.stop.bind(this, false)};
this.parent(options);
if (this.options.wheelStops){
this.addEvent('onStart', function(){
document.addEvent('mousewheel', this.bound.stop);
}.bind(this));
this.addEvent('onComplete', function(){
document.removeEvent('mousewheel', this.bound.stop);
}.bind(this));
}
},
setNow: function(){
for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]);
},
/*
Property: scrollTo
Scrolls the chosen element to the x/y coordinates.
Arguments:
x - the x coordinate to scroll the element to
y - the y coordinate to scroll the element to
*/
scrollTo: function(x, y){
if (this.timer && this.options.wait) return this;
var el = this.element.getSize();
var values = {'x': x, 'y': y};
for (var z in el.size){
var max = el.scrollSize[z] - el.size[z];
if ($chk(values[z])) values[z] = ($type(values[z]) == 'number') ? values[z].limit(0, max) : max;
else values[z] = el.scroll[z];
values[z] += this.options.offset[z];
}
return this.start([el.scroll.x, el.scroll.y], [values.x, values.y]);
},
/*
Property: toTop
Scrolls the chosen element to its maximum top.
*/
toTop: function(){
return this.scrollTo(false, 0);
},
/*
Property: toBottom
Scrolls the chosen element to its maximum bottom.
*/
toBottom: function(){
return this.scrollTo(false, 'full');
},
/*
Property: toLeft
Scrolls the chosen element to its maximum left.
*/
toLeft: function(){
return this.scrollTo(0, false);
},
/*
Property: toRight
Scrolls the chosen element to its maximum right.
*/
toRight: function(){
return this.scrollTo('full', false);
},
/*
Property: toElement
Scrolls the specified element to the position the passed in element is found.
Arguments:
el - the $(element) to scroll the window to
*/
toElement: function(el){
var parent = this.element.getPosition(this.options.overflown);
var target = $(el).getPosition(this.options.overflown);
return this.scrollTo(target.x - parent.x, target.y - parent.y);
},
increase: function(){
this.element.scrollTo(this.now[0], this.now[1]);
}
});
/*
Script: Fx.Slide.js
Contains <Fx.Slide>
License:
MIT-style license.
*/
/*
Class: Fx.Slide
The slide effect; slides an element in horizontally or vertically, the contents will fold inside.
Inherits methods, properties, options and events from <Fx.Base>.
Note:
Fx.Slide requires an XHTML doctype.
Options:
mode - set it to vertical or horizontal. Defaults to vertical.
options - all the <Fx.Base> options
Example:
(start code)
var mySlider = new Fx.Slide('myElement', {duration: 500});
mySlider.toggle() //toggle the slider up and down.
(end)
*/
Fx.Slide = Fx.Base.extend({
options: {
mode: 'vertical'
},
initialize: function(el, options){
this.element = $(el);
this.wrapper = new Element('div', {'styles': $extend(this.element.getStyles('margin'), {'overflow': 'hidden'})}).injectAfter(this.element).adopt(this.element);
this.element.setStyle('margin', 0);
this.setOptions(options);
this.now = [];
this.parent(this.options);
this.open = true;
this.addEvent('onComplete', function(){
this.open = (this.now[0] === 0);
});
if (window.webkit419) this.addEvent('onComplete', function(){
if (this.open) this.element.remove().inject(this.wrapper);
});
},
setNow: function(){
for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]);
},
vertical: function(){
this.margin = 'margin-top';
this.layout = 'height';
this.offset = this.element.offsetHeight;
},
horizontal: function(){
this.margin = 'margin-left';
this.layout = 'width';
this.offset = this.element.offsetWidth;
},
/*
Property: slideIn
Slides the elements in view horizontally or vertically.
Arguments:
mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode.
*/
slideIn: function(mode){
this[mode || this.options.mode]();
return this.start([this.element.getStyle(this.margin).toInt(), this.wrapper.getStyle(this.layout).toInt()], [0, this.offset]);
},
/*
Property: slideOut
Sides the elements out of view horizontally or vertically.
Arguments:
mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode.
*/
slideOut: function(mode){
this[mode || this.options.mode]();
return this.start([this.element.getStyle(this.margin).toInt(), this.wrapper.getStyle(this.layout).toInt()], [-this.offset, 0]);
},
/*
Property: hide
Hides the element without a transition.
Arguments:
mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode.
*/
hide: function(mode){
this[mode || this.options.mode]();
this.open = false;
return this.set([-this.offset, 0]);
},
/*
Property: show
Shows the element without a transition.
Arguments:
mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode.
*/
show: function(mode){
this[mode || this.options.mode]();
this.open = true;
return this.set([0, this.offset]);
},
/*
Property: toggle
Slides in or Out the element, depending on its state
Arguments:
mode - (optional, string) 'horizontal' or 'vertical'; defaults to options.mode.
*/
toggle: function(mode){
if (this.wrapper.offsetHeight == 0 || this.wrapper.offsetWidth == 0) return this.slideIn(mode);
return this.slideOut(mode);
},
increase: function(){
this.element.setStyle(this.margin, this.now[0] + this.options.unit);
this.wrapper.setStyle(this.layout, this.now[1] + this.options.unit);
}
});
/*
Script: Fx.Transitions.js
Effects transitions, to be used with all the effects.
License:
MIT-style license.
Credits:
Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified & optimized to be used with mootools.
*/
/*
Class: Fx.Transitions
A collection of tweening transitions for use with the <Fx.Base> classes.
Example:
>//Elastic.easeOut with default values:
>new Fx.Style('margin', {transition: Fx.Transitions.Elastic.easeOut});
>//Elastic.easeOut with user-defined value for elasticity.
> var myTransition = new Fx.Transition(Fx.Transitions.Elastic, 3);
>new Fx.Style('margin', {transition: myTransition.easeOut});
See also:
http://www.robertpenner.com/easing/
*/
Fx.Transition = function(transition, params){
params = params || [];
if ($type(params) != 'array') params = [params];
return $extend(transition, {
easeIn: function(pos){
return transition(pos, params);
},
easeOut: function(pos){
return 1 - transition(1 - pos, params);
},
easeInOut: function(pos){
return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2;
}
});
};
Fx.Transitions = new Abstract({
/*
Property: linear
displays a linear transition.
Graph:
(see Linear.png)
*/
linear: function(p){
return p;
}
});
Fx.Transitions.extend = function(transitions){
for (var transition in transitions){
Fx.Transitions[transition] = new Fx.Transition(transitions[transition]);
/*compatibility*/
Fx.Transitions.compat(transition);
/*end compatibility*/
}
};
/*compatibility*/
Fx.Transitions.compat = function(transition){
['In', 'Out', 'InOut'].each(function(easeType){
Fx.Transitions[transition.toLowerCase() + easeType] = Fx.Transitions[transition]['ease' + easeType];
});
};
/*end compatibility*/
Fx.Transitions.extend({
/*
Property: Quad
displays a quadratic transition. Must be used as Quad.easeIn or Quad.easeOut or Quad.easeInOut
Graph:
(see Quad.png)
*/
//auto generated
/*
Property: Cubic
displays a cubicular transition. Must be used as Cubic.easeIn or Cubic.easeOut or Cubic.easeInOut
Graph:
(see Cubic.png)
*/
//auto generated
/*
Property: Quart
displays a quartetic transition. Must be used as Quart.easeIn or Quart.easeOut or Quart.easeInOut
Graph:
(see Quart.png)
*/
//auto generated
/*
Property: Quint
displays a quintic transition. Must be used as Quint.easeIn or Quint.easeOut or Quint.easeInOut
Graph:
(see Quint.png)
*/
//auto generated
/*
Property: Pow
Used to generate Quad, Cubic, Quart and Quint.
By default is p^6.
Graph:
(see Pow.png)
*/
Pow: function(p, x){
return Math.pow(p, x[0] || 6);
},
/*
Property: Expo
displays a exponential transition. Must be used as Expo.easeIn or Expo.easeOut or Expo.easeInOut
Graph:
(see Expo.png)
*/
Expo: function(p){
return Math.pow(2, 8 * (p - 1));
},
/*
Property: Circ
displays a circular transition. Must be used as Circ.easeIn or Circ.easeOut or Circ.easeInOut
Graph:
(see Circ.png)
*/
Circ: function(p){
return 1 - Math.sin(Math.acos(p));
},
/*
Property: Sine
displays a sineousidal transition. Must be used as Sine.easeIn or Sine.easeOut or Sine.easeInOut
Graph:
(see Sine.png)
*/
Sine: function(p){
return 1 - Math.sin((1 - p) * Math.PI / 2);
},
/*
Property: Back
makes the transition go back, then all forth. Must be used as Back.easeIn or Back.easeOut or Back.easeInOut
Graph:
(see Back.png)
*/
Back: function(p, x){
x = x[0] || 1.618;
return Math.pow(p, 2) * ((x + 1) * p - x);
},
/*
Property: Bounce
makes the transition bouncy. Must be used as Bounce.easeIn or Bounce.easeOut or Bounce.easeInOut
Graph:
(see Bounce.png)
*/
Bounce: function(p){
var value;
for (var a = 0, b = 1; 1; a += b, b /= 2){
if (p >= (7 - 4 * a) / 11){
value = - Math.pow((11 - 6 * a - 11 * p) / 4, 2) + b * b;
break;
}
}
return value;
},
/*
Property: Elastic
Elastic curve. Must be used as Elastic.easeIn or Elastic.easeOut or Elastic.easeInOut
Graph:
(see Elastic.png)
*/
Elastic: function(p, x){
return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3);
}
});
['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){
Fx.Transitions[transition] = new Fx.Transition(function(p){
return Math.pow(p, [i + 2]);
});
/*compatibility*/
Fx.Transitions.compat(transition);
/*end compatibility*/
});
/*
Script: Drag.Base.js
Contains <Drag.Base>, <Element.makeResizable>
License:
MIT-style license.
*/
var Drag = {};
/*
Class: Drag.Base
Modify two css properties of an element based on the position of the mouse.
Note:
Drag.Base requires an XHTML doctype.
Arguments:
el - the $(element) to apply the transformations to.
options - optional. The options object.
Options:
handle - the $(element) to act as the handle for the draggable element. defaults to the $(element) itself.
modifiers - an object. see Modifiers Below.
limit - an object, see Limit below.
grid - optional, distance in px for snap-to-grid dragging
snap - optional, the distance you have to drag before the element starts to respond to the drag. defaults to false
modifiers:
x - string, the style you want to modify when the mouse moves in an horizontal direction. defaults to 'left'
y - string, the style you want to modify when the mouse moves in a vertical direction. defaults to 'top'
limit:
x - array with start and end limit relative to modifiers.x
y - array with start and end limit relative to modifiers.y
Events:
onStart - optional, function to execute when the user starts to drag (on mousedown);
onComplete - optional, function to execute when the user completes the drag.
onDrag - optional, function to execute at every step of the drag
*/
Drag.Base = new Class({
options: {
handle: false,
unit: 'px',
onStart: Class.empty,
onBeforeStart: Class.empty,
onComplete: Class.empty,
onSnap: Class.empty,
onDrag: Class.empty,
limit: false,
modifiers: {x: 'left', y: 'top'},
grid: false,
snap: 6
},
initialize: function(el, options){
this.setOptions(options);
this.element = $(el);
this.handle = $(this.options.handle) || this.element;
this.mouse = {'now': {}, 'pos': {}};
this.value = {'start': {}, 'now': {}};
this.bound = {
'start': this.start.bindWithEvent(this),
'check': this.check.bindWithEvent(this),
'drag': this.drag.bindWithEvent(this),
'stop': this.stop.bind(this)
};
this.attach();
if (this.options.initialize) this.options.initialize.call(this);
},
attach: function(){
this.handle.addEvent('mousedown', this.bound.start);
return this;
},
detach: function(){
this.handle.removeEvent('mousedown', this.bound.start);
return this;
},
start: function(event){
this.fireEvent('onBeforeStart', this.element);
this.mouse.start = event.page;
var limit = this.options.limit;
this.limit = {'x': [], 'y': []};
for (var z in this.options.modifiers){
if (!this.options.modifiers[z]) continue;
this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt();
this.mouse.pos[z] = event.page[z] - this.value.now[z];
if (limit && limit[z]){
for (var i = 0; i < 2; i++){
if ($chk(limit[z][i])) this.limit[z][i] = ($type(limit[z][i]) == 'function') ? limit[z][i]() : limit[z][i];
}
}
}
if ($type(this.options.grid) == 'number') this.options.grid = {'x': this.options.grid, 'y': this.options.grid};
document.addListener('mousemove', this.bound.check);
document.addListener('mouseup', this.bound.stop);
this.fireEvent('onStart', this.element);
event.stop();
},
check: function(event){
var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2)));
if (distance > this.options.snap){
document.removeListener('mousemove', this.bound.check);
document.addListener('mousemove', this.bound.drag);
this.drag(event);
this.fireEvent('onSnap', this.element);
}
event.stop();
},
drag: function(event){
this.out = false;
this.mouse.now = event.page;
for (var z in this.options.modifiers){
if (!this.options.modifiers[z]) continue;
this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z];
if (this.limit[z]){
if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){
this.value.now[z] = this.limit[z][1];
this.out = true;
} else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){
this.value.now[z] = this.limit[z][0];
this.out = true;
}
}
if (this.options.grid[z]) this.value.now[z] -= (this.value.now[z] % this.options.grid[z]);
this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.unit);
}
this.fireEvent('onDrag', this.element);
event.stop();
},
stop: function(){
document.removeListener('mousemove', this.bound.check);
document.removeListener('mousemove', this.bound.drag);
document.removeListener('mouseup', this.bound.stop);
this.fireEvent('onComplete', this.element);
}
});
Drag.Base.implement(new Events, new Options);
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.extend({
/*
Property: makeResizable
Makes an element resizable (by dragging) with the supplied options.
Arguments:
options - see <Drag.Base> for acceptable options.
*/
makeResizable: function(options){
return new Drag.Base(this, $merge({modifiers: {x: 'width', y: 'height'}}, options));
}
});
/*
Script: Drag.Move.js
Contains <Drag.Move>, <Element.makeDraggable>
License:
MIT-style license.
*/
/*
Class: Drag.Move
Extends <Drag.Base>, has additional functionality for dragging an element, support snapping and droppables.
Drag.move supports either position absolute or relative. If no position is found, absolute will be set.
Inherits methods, properties, options and events from <Drag.Base>.
Note:
Drag.Move requires an XHTML doctype.
Arguments:
el - the $(element) to apply the drag to.
options - optional. see Options below.
Options:
all the drag.Base options, plus:
container - an element, will fill automatically limiting options based on the $(element) size and position. defaults to false (no limiting)
droppables - an array of elements you can drop your draggable to.
overflown - an array of nested scrolling containers, see Element::getPosition
*/
Drag.Move = Drag.Base.extend({
options: {
droppables: [],
container: false,
overflown: []
},
initialize: function(el, options){
this.setOptions(options);
this.element = $(el);
this.droppables = $$(this.options.droppables);
this.container = $(this.options.container);
this.position = {'element': this.element.getStyle('position'), 'container': false};
if (this.container) this.position.container = this.container.getStyle('position');
if (!['relative', 'absolute', 'fixed'].contains(this.position.element)) this.position.element = 'absolute';
var top = this.element.getStyle('top').toInt();
var left = this.element.getStyle('left').toInt();
if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){
top = $chk(top) ? top : this.element.getTop(this.options.overflown);
left = $chk(left) ? left : this.element.getLeft(this.options.overflown);
} else {
top = $chk(top) ? top : 0;
left = $chk(left) ? left : 0;
}
this.element.setStyles({'top': top, 'left': left, 'position': this.position.element});
this.parent(this.element);
},
start: function(event){
this.overed = null;
if (this.container){
var cont = this.container.getCoordinates();
var el = this.element.getCoordinates();
if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){
this.options.limit = {
'x': [cont.left, cont.right - el.width],
'y': [cont.top, cont.bottom - el.height]
};
} else {
this.options.limit = {
'y': [0, cont.height - el.height],
'x': [0, cont.width - el.width]
};
}
}
this.parent(event);
},
drag: function(event){
this.parent(event);
var overed = this.out ? false : this.droppables.filter(this.checkAgainst, this).getLast();
if (this.overed != overed){
if (this.overed) this.overed.fireEvent('leave', [this.element, this]);
this.overed = overed ? overed.fireEvent('over', [this.element, this]) : null;
}
return this;
},
checkAgainst: function(el){
el = el.getCoordinates(this.options.overflown);
var now = this.mouse.now;
return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top);
},
stop: function(){
if (this.overed && !this.out) this.overed.fireEvent('drop', [this.element, this]);
else this.element.fireEvent('emptydrop', this);
this.parent();
return this;
}
});
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.extend({
/*
Property: makeDraggable
Makes an element draggable with the supplied options.
Arguments:
options - see <Drag.Move> and <Drag.Base> for acceptable options.
*/
makeDraggable: function(options){
return new Drag.Move(this, options);
}
});
/*
Script: XHR.js
Contains the basic XMLHttpRequest Class Wrapper.
License:
MIT-style license.
*/
/*
Class: XHR
Basic XMLHttpRequest Wrapper.
Arguments:
options - an object with options names as keys. See options below.
Options:
method - 'post' or 'get' - the protocol for the request; optional, defaults to 'post'.
async - boolean: asynchronous option; true uses asynchronous requests. Defaults to true.
encoding - the encoding, defaults to utf-8.
autoCancel - cancels the already running request if another one is sent. defaults to false.
headers - accepts an object, that will be set to request headers.
Events:
onRequest - function to execute when the XHR request is fired.
onSuccess - function to execute when the XHR request completes.
onStateChange - function to execute when the state of the XMLHttpRequest changes.
onFailure - function to execute when the state of the XMLHttpRequest changes.
Properties:
running - true if the request is running.
response - object, text and xml as keys. You can access this property in the onSuccess event.
Example:
>var myXHR = new XHR({method: 'get'}).send('http://site.com/requestHandler.php', 'name=john&lastname=dorian');
*/
var XHR = new Class({
options: {
method: 'post',
async: true,
onRequest: Class.empty,
onSuccess: Class.empty,
onFailure: Class.empty,
urlEncoded: true,
encoding: 'utf-8',
autoCancel: false,
headers: {}
},
setTransport: function(){
this.transport = (window.XMLHttpRequest) ? new XMLHttpRequest() : (window.ie ? new ActiveXObject('Microsoft.XMLHTTP') : false);
return this;
},
initialize: function(options){
this.setTransport().setOptions(options);
this.options.isSuccess = this.options.isSuccess || this.isSuccess;
this.headers = {};
if (this.options.urlEncoded && this.options.method == 'post'){
var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
this.setHeader('Content-type', 'application/x-www-form-urlencoded' + encoding);
}
if (this.options.initialize) this.options.initialize.call(this);
},
onStateChange: function(){
if (this.transport.readyState != 4 || !this.running) return;
this.running = false;
var status = 0;
try {status = this.transport.status;} catch(e){};
if (this.options.isSuccess.call(this, status)) this.onSuccess();
else this.onFailure();
this.transport.onreadystatechange = Class.empty;
},
isSuccess: function(status){
return ((status >= 200) && (status < 300));
},
onSuccess: function(){
this.response = {
'text': this.transport.responseText,
'xml': this.transport.responseXML
};
this.fireEvent('onSuccess', [this.response.text, this.response.xml]);
this.callChain();
},
onFailure: function(){
this.fireEvent('onFailure', this.transport);
},
/*
Property: setHeader
Add/modify an header for the request. It will not override headers from the options.
Example:
>var myXhr = new XHR(url, {method: 'get', headers: {'X-Request': 'JSON'}});
>myXhr.setHeader('Last-Modified','Sat, 1 Jan 2005 05:00:00 GMT');
*/
setHeader: function(name, value){
this.headers[name] = value;
return this;
},
/*
Property: send
Opens the XHR connection and sends the data. Data has to be null or a string.
Example:
>var myXhr = new XHR({method: 'post'});
>myXhr.send(url, querystring);
>
>var syncXhr = new XHR({async: false, method: 'post'});
>syncXhr.send(url, null);
>
*/
send: function(url, data){
if (this.options.autoCancel) this.cancel();
else if (this.running) return this;
this.running = true;
if (data && this.options.method == 'get'){
url = url + (url.contains('?') ? '&' : '?') + data;
data = null;
}
this.transport.open(this.options.method.toUpperCase(), url, this.options.async);
this.transport.onreadystatechange = this.onStateChange.bind(this);
if ((this.options.method == 'post') && this.transport.overrideMimeType) this.setHeader('Connection', 'close');
$extend(this.headers, this.options.headers);
for (var type in this.headers) try {this.transport.setRequestHeader(type, this.headers[type]);} catch(e){};
this.fireEvent('onRequest');
this.transport.send($pick(data, null));
return this;
},
/*
Property: cancel
Cancels the running request. No effect if the request is not running.
Example:
>var myXhr = new XHR({method: 'get'}).send(url);
>myXhr.cancel();
*/
cancel: function(){
if (!this.running) return this;
this.running = false;
this.transport.abort();
this.transport.onreadystatechange = Class.empty;
this.setTransport();
this.fireEvent('onCancel');
return this;
}
});
XHR.implement(new Chain, new Events, new Options);
/*
Script: Ajax.js
Contains the <Ajax> class. Also contains methods to generate querystings from forms and Objects.
Credits:
Loosely based on the version from prototype.js <http://prototype.conio.net>
License:
MIT-style license.
*/
/*
Class: Ajax
An Ajax class, For all your asynchronous needs.
Inherits methods, properties, options and events from <XHR>.
Arguments:
url - the url pointing to the server-side script.
options - optional, an object containing options.
Options:
data - you can write parameters here. Can be a querystring, an object or a Form element.
update - $(element) to insert the response text of the XHR into, upon completion of the request.
evalScripts - boolean; default is false. Execute scripts in the response text onComplete. When the response is javascript the whole response is evaluated.
evalResponse - boolean; default is false. Force global evalulation of the whole response, no matter what content-type it is.
Events:
onComplete - function to execute when the ajax request completes.
Example:
>var myAjax = new Ajax(url, {method: 'get'}).request();
*/
var Ajax = XHR.extend({
options: {
data: null,
update: null,
onComplete: Class.empty,
evalScripts: false,
evalResponse: false
},
initialize: function(url, options){
this.addEvent('onSuccess', this.onComplete);
this.setOptions(options);
/*compatibility*/
this.options.data = this.options.data || this.options.postBody;
/*end compatibility*/
if (!['post', 'get'].contains(this.options.method)){
this._method = '_method=' + this.options.method;
this.options.method = 'post';
}
this.parent();
this.setHeader('X-Requested-With', 'XMLHttpRequest');
this.setHeader('Accept', 'text/javascript, text/html, application/xml, text/xml, */*');
this.url = url;
},
onComplete: function(){
if (this.options.update) $(this.options.update).empty().setHTML(this.response.text);
if (this.options.evalScripts || this.options.evalResponse) this.evalScripts();
this.fireEvent('onComplete', [this.response.text, this.response.xml], 20);
},
/*
Property: request
Executes the ajax request.
Example:
>var myAjax = new Ajax(url, {method: 'get'});
>myAjax.request();
OR
>new Ajax(url, {method: 'get'}).request();
*/
request: function(data){
data = data || this.options.data;
switch($type(data)){
case 'element': data = $(data).toQueryString(); break;
case 'object': data = Object.toQueryString(data);
}
if (this._method) data = (data) ? [this._method, data].join('&') : this._method;
return this.send(this.url, data);
},
/*
Property: evalScripts
Executes scripts in the response text
*/
evalScripts: function(){
var script, scripts;
if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) scripts = this.response.text;
else {
scripts = [];
var regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
while ((script = regexp.exec(this.response.text))) scripts.push(script[1]);
scripts = scripts.join('\n');
}
if (scripts) (window.execScript) ? window.execScript(scripts) : window.setTimeout(scripts, 0);
},
/*
Property: getHeader
Returns the given response header or null
*/
getHeader: function(name){
try {return this.transport.getResponseHeader(name);} catch(e){};
return null;
}
});
/* Section: Object related Functions */
/*
Function: Object.toQueryString
Generates a querystring from key/pair values in an object
Arguments:
source - the object to generate the querystring from.
Returns:
the query string.
Example:
>Object.toQueryString({apple: "red", lemon: "yellow"}); //returns "apple=red&lemon=yellow"
*/
Object.toQueryString = function(source){
var queryString = [];
for (var property in source) queryString.push(encodeURIComponent(property) + '=' + encodeURIComponent(source[property]));
return queryString.join('&');
};
/*
Class: Element
Custom class to allow all of its methods to be used with any DOM element via the dollar function <$>.
*/
Element.extend({
/*
Property: send
Sends a form with an ajax post request
Arguments:
options - option collection for ajax request. See <Ajax> for the options list.
Returns:
The Ajax Class Instance
Example:
(start code)
<form id="myForm" action="submit.php">
<input name="email" value="bob@bob.com">
<input name="zipCode" value="90210">
</form>
<script>
$('myForm').send()
</script>
(end)
*/
send: function(options){
return new Ajax(this.getProperty('action'), $merge({data: this.toQueryString()}, options, {method: 'post'})).request();
}
});
/*
Script: Cookie.js
A cookie reader/creator
Credits:
based on the functions by Peter-Paul Koch (http://quirksmode.org)
*/
/*
Class: Cookie
Class for creating, getting, and removing cookies.
*/
var Cookie = new Abstract({
options: {
domain: false,
path: false,
duration: false,
secure: false
},
/*
Property: set
Sets a cookie in the browser.
Arguments:
key - the key (name) for the cookie
value - the value to set, cannot contain semicolons
options - an object representing the Cookie options. See Options below. Default values are stored in Cookie.options.
Options:
domain - the domain the Cookie belongs to. If you want to share the cookie with pages located on a different domain, you have to set this value. Defaults to the current domain.
path - the path the Cookie belongs to. If you want to share the cookie with pages located in a different path, you have to set this value, for example to "/" to share the cookie with all pages on the domain. Defaults to the current path.
duration - the duration of the Cookie before it expires, in days.
If set to false or 0, the cookie will be a session cookie that expires when the browser is closed. This is default.
secure - Stored cookie information can be accessed only from a secure environment.
Returns:
An object with the options, the key and the value. You can give it as first parameter to Cookie.remove.
Example:
>Cookie.set('username', 'Harald'); // session cookie (duration is false), or ...
>Cookie.set('username', 'JackBauer', {duration: 1}); // save this for 1 day
*/
set: function(key, value, options){
options = $merge(this.options, options);
value = encodeURIComponent(value);
if (options.domain) value += '; domain=' + options.domain;
if (options.path) value += '; path=' + options.path;
if (options.duration){
var date = new Date();
date.setTime(date.getTime() + options.duration * 24 * 60 * 60 * 1000);
value += '; expires=' + date.toGMTString();
}
if (options.secure) value += '; secure';
document.cookie = key + '=' + value;
return $extend(options, {'key': key, 'value': value});
},
/*
Property: get
Gets the value of a cookie.
Arguments:
key - the name of the cookie you wish to retrieve.
Returns:
The cookie string value, or false if not found.
Example:
>Cookie.get("username") //returns JackBauer
*/
get: function(key){
var value = document.cookie.match('(?:^|;)\\s*' + key.escapeRegExp() + '=([^;]*)');
return value ? decodeURIComponent(value[1]) : false;
},
/*
Property: remove
Removes a cookie from the browser.
Arguments:
cookie - the name of the cookie to remove or a previous cookie (for domains)
options - optional. you can also pass the domain and path here. Same as options in <Cookie.set>
Examples:
>Cookie.remove('username') //bye-bye JackBauer, cya in 24 hours
>
>var myCookie = Cookie.set('username', 'Aaron', {domain: 'mootools.net'}); // Cookie.set returns an object with all values need to remove the cookie
>Cookie.remove(myCookie);
*/
remove: function(cookie, options){
if ($type(cookie) == 'object') this.set(cookie.key, '', $merge(cookie, {duration: -1}));
else this.set(cookie, '', $merge(options, {duration: -1}));
}
});
/*
Script: Json.js
Simple Json parser and Stringyfier, See: <http://www.json.org/>
License:
MIT-style license.
*/
/*
Class: Json
Simple Json parser and Stringyfier, See: <http://www.json.org/>
*/
var Json = {
/*
Property: toString
Converts an object to a string, to be passed in server-side scripts as a parameter. Although its not normal usage for this class, this method can also be used to convert functions and arrays to strings.
Arguments:
obj - the object to convert to string
Returns:
A json string
Example:
(start code)
Json.toString({apple: 'red', lemon: 'yellow'}); '{"apple":"red","lemon":"yellow"}'
(end)
*/
toString: function(obj){
switch($type(obj)){
case 'string':
return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
case 'array':
return '[' + obj.map(Json.toString).join(',') + ']';
case 'object':
var string = [];
for (var property in obj) string.push(Json.toString(property) + ':' + Json.toString(obj[property]));
return '{' + string.join(',') + '}';
case 'number':
if (isFinite(obj)) break;
case false:
return 'null';
}
return String(obj);
},
/*
Property: evaluate
converts a json string to an javascript Object.
Arguments:
str - the string to evaluate. if its not a string, it returns false.
secure - optionally, performs syntax check on json string. Defaults to false.
Credits:
Json test regexp is by Douglas Crockford <http://crockford.org>.
Example:
>var myObject = Json.evaluate('{"apple":"red","lemon":"yellow"}');
>//myObject will become {apple: 'red', lemon: 'yellow'}
*/
evaluate: function(str, secure){
return (($type(str) != 'string') || (secure && !str.test(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/))) ? null : eval('(' + str + ')');
}
};
/*
Script: Json.Remote.js
Contains <Json.Remote>.
License:
MIT-style license.
*/
/*
Class: Json.Remote
Wrapped XHR with automated sending and receiving of Javascript Objects in Json Format.
Inherits methods, properties, options and events from <XHR>.
Arguments:
url - the url you want to send your object to.
options - see <XHR> options
Example:
this code will send user information based on name/last name
(start code)
var jSonRequest = new Json.Remote("http://site.com/tellMeAge.php", {onComplete: function(person){
alert(person.age); //is 25 years
alert(person.height); //is 170 cm
alert(person.weight); //is 120 kg
}}).send({'name': 'John', 'lastName': 'Doe'});
(end)
*/
Json.Remote = XHR.extend({
initialize: function(url, options){
this.url = url;
this.addEvent('onSuccess', this.onComplete);
this.parent(options);
this.setHeader('X-Request', 'JSON');
},
send: function(obj){
return this.parent(this.url, 'json=' + Json.toString(obj));
},
onComplete: function(){
this.fireEvent('onComplete', [Json.evaluate(this.response.text, this.options.secure)]);
}
});
/*
Script: Assets.js
provides dynamic loading for images, css and javascript files.
License:
MIT-style license.
*/
var Asset = new Abstract({
/*
Property: javascript
Injects a javascript file in the page.
Arguments:
source - the path of the javascript file
properties - some additional attributes you might want to add to the script element
Example:
> new Asset.javascript('/scripts/myScript.js', {id: 'myScript'});
*/
javascript: function(source, properties){
properties = $merge({
'onload': Class.empty
}, properties);
var script = new Element('script', {'src': source}).addEvents({
'load': properties.onload,
'readystatechange': function(){
if (this.readyState == 'complete') this.fireEvent('load');
}
});
delete properties.onload;
return script.setProperties(properties).inject(document.head);
},
/*
Property: css
Injects a css file in the page.
Arguments:
source - the path of the css file
properties - some additional attributes you might want to add to the link element
Example:
> new Asset.css('/css/myStyle.css', {id: 'myStyle', title: 'myStyle'});
*/
css: function(source, properties){
return new Element('link', $merge({
'rel': 'stylesheet', 'media': 'screen', 'type': 'text/css', 'href': source
}, properties)).inject(document.head);
},
/*
Property: image
Preloads an image and returns the img element. does not inject it to the page.
Arguments:
source - the path of the image file
properties - some additional attributes you might want to add to the img element
Example:
> new Asset.image('/images/myImage.png', {id: 'myImage', title: 'myImage', onload: myFunction});
Returns:
the img element. you can inject it anywhere you want with <Element.injectInside>/<Element.injectAfter>/<Element.injectBefore>
*/
image: function(source, properties){
properties = $merge({
'onload': Class.empty,
'onabort': Class.empty,
'onerror': Class.empty
}, properties);
var image = new Image();
image.src = source;
var element = new Element('img', {'src': source});
['load', 'abort', 'error'].each(function(type){
var event = properties['on' + type];
delete properties['on' + type];
element.addEvent(type, function(){
this.removeEvent(type, arguments.callee);
event.call(this);
});
});
if (image.width && image.height) element.fireEvent('load', element, 1);
return element.setProperties(properties);
},
/*
Property: images
Preloads an array of images (as strings) and returns an array of img elements. does not inject them to the page.
Arguments:
sources - array, the paths of the image files
options - object, see below
Options:
onComplete - a function to execute when all image files are loaded in the browser's cache
onProgress - a function to execute when one image file is loaded in the browser's cache
Example:
(start code)
new Asset.images(['/images/myImage.png', '/images/myImage2.gif'], {
onComplete: function(){
alert('all images loaded!');
}
});
(end)
Returns:
the img elements as $$. you can inject them anywhere you want with <Element.injectInside>/<Element.injectAfter>/<Element.injectBefore>
*/
images: function(sources, options){
options = $merge({
onComplete: Class.empty,
onProgress: Class.empty
}, options);
if (!sources.push) sources = [sources];
var images = [];
var counter = 0;
sources.each(function(source){
var img = new Asset.image(source, {
'onload': function(){
options.onProgress.call(this, counter);
counter++;
if (counter == sources.length) options.onComplete();
}
});
images.push(img);
});
return new Elements(images);
}
});
/*
Script: Hash.js
Contains the class Hash.
License:
MIT-style license.
*/
/*
Class: Hash
It wraps an object that it uses internally as a map. The user must use set(), get(), and remove() to add/change, retrieve and remove values, it must not access the internal object directly. null/undefined values are allowed.
Note:
Each hash instance has the length property.
Arguments:
obj - an object to convert into a Hash instance.
Example:
(start code)
var hash = new Hash({a: 'hi', b: 'world', c: 'howdy'});
hash.remove('b'); // b is removed.
hash.set('c', 'hello');
hash.get('c'); // returns 'hello'
hash.length // returns 2 (a and c)
(end)
*/
var Hash = new Class({
length: 0,
initialize: function(object){
this.obj = object || {};
this.setLength();
},
/*
Property: get
Retrieves a value from the hash.
Arguments:
key - The key
Returns:
The value
*/
get: function(key){
return (this.hasKey(key)) ? this.obj[key] : null;
},
/*
Property: hasKey
Check the presence of a specified key-value pair in the hash.
Arguments:
key - The key
Returns:
True if the Hash contains a value for the specified key, otherwise false
*/
hasKey: function(key){
return (key in this.obj);
},
/*
Property: set
Adds a key-value pair to the hash or replaces a previous value associated with the key.
Arguments:
key - The key
value - The value
*/
set: function(key, value){
if (!this.hasKey(key)) this.length++;
this.obj[key] = value;
return this;
},
setLength: function(){
this.length = 0;
for (var p in this.obj) this.length++;
return this;
},
/*
Property: remove
Removes a key-value pair from the hash.
Arguments:
key - The key
*/
remove: function(key){
if (this.hasKey(key)){
delete this.obj[key];
this.length--;
}
return this;
},
/*
Property: each
Calls a function for each key-value pair. The first argument passed to the function will be the value, the second one will be the key, like $each.
Arguments:
fn - The function to call for each key-value pair
bind - Optional, the object that will be referred to as "this" in the function
*/
each: function(fn, bind){
$each(this.obj, fn, bind);
},
/*
Property: extend
Extends the current hash with an object containing key-value pairs. Values for duplicate keys will be replaced by the new ones.
Arguments:
obj - An object containing key-value pairs
*/
extend: function(obj){
$extend(this.obj, obj);
return this.setLength();
},
/*
Property: merge
Merges the current hash with multiple objects.
*/
merge: function(){
this.obj = $merge.apply(null, [this.obj].extend(arguments));
return this.setLength();
},
/*
Property: empty
Empties all hash values properties and values.
*/
empty: function(){
this.obj = {};
this.length = 0;
return this;
},
/*
Property: keys
Returns an array containing all the keys, in the same order as the values returned by <Hash.values>.
Returns:
An array containing all the keys of the hash
*/
keys: function(){
var keys = [];
for (var property in this.obj) keys.push(property);
return keys;
},
/*
Property: values
Returns an array containing all the values, in the same order as the keys returned by <Hash.keys>.
Returns:
An array containing all the values of the hash
*/
values: function(){
var values = [];
for (var property in this.obj) values.push(this.obj[property]);
return values;
}
});
/* Section: Utility Functions */
/*
Function: $H
Shortcut to create a Hash from an Object.
*/
function $H(obj){
return new Hash(obj);
};
/*
Script: Hash.Cookie.js
Stores and loads an Hash as a cookie using Json format.
*/
/*
Class: Hash.Cookie
Inherits all the methods from <Hash>, additional methods are save and load.
Hash json string has a limit of 4kb (4096byte), so be careful with your Hash size.
Creating a new instance automatically loads the data from the Cookie into the Hash.
If the Hash is emptied, the cookie is also removed.
Arguments:
name - the key (name) for the cookie
options - options are identical to <Cookie> and are simply passed along to it.
In addition, it has the autoSave option, to save the cookie at every operation. defaults to true.
Example:
(start code)
var fruits = new Hash.Cookie('myCookieName', {duration: 3600});
fruits.extend({
'lemon': 'yellow',
'apple': 'red'
});
fruits.set('melon', 'green');
fruits.get('lemon'); // yellow
// ... on another page ... values load automatically
var fruits = new Hash.Cookie('myCookieName', {duration: 365});
fruits.get('melon'); // green
fruits.erase(); // delete cookie
(end)
*/
Hash.Cookie = Hash.extend({
initialize: function(name, options){
this.name = name;
this.options = $extend({'autoSave': true}, options || {});
this.load();
},
/*
Property: save
Saves the Hash to the cookie. If the hash is empty, removes the cookie.
Returns:
Returns false when the JSON string cookie is too long (4kb), otherwise true.
Example:
(start code)
var login = new Hash.Cookie('userstatus', {autoSave: false});
login.extend({
'username': 'John',
'credentials': [4, 7, 9]
});
login.set('last_message', 'User logged in!');
login.save(); // finally save the Hash
(end)
*/
save: function(){
if (this.length == 0){
Cookie.remove(this.name, this.options);
return true;
}
var str = Json.toString(this.obj);
if (str.length > 4096) return false; //cookie would be truncated!
Cookie.set(this.name, str, this.options);
return true;
},
/*
Property: load
Loads the cookie and assigns it to the Hash.
*/
load: function(){
this.obj = Json.evaluate(Cookie.get(this.name), true) || {};
this.setLength();
}
});
Hash.Cookie.Methods = {};
['extend', 'set', 'merge', 'empty', 'remove'].each(function(method){
Hash.Cookie.Methods[method] = function(){
Hash.prototype[method].apply(this, arguments);
if (this.options.autoSave) this.save();
return this;
};
});
Hash.Cookie.implement(Hash.Cookie.Methods);
/*
Script: Color.js
Contains the Color class.
License:
MIT-style license.
*/
/*
Class: Color
Creates a new Color Object, which is an array with some color specific methods.
Arguments:
color - the hex, the RGB array or the HSB array of the color to create. For HSB colors, you need to specify the second argument.
type - a string representing the type of the color to create. needs to be specified if you intend to create the color with HSB values, or an array of HEX values. Can be 'rgb', 'hsb' or 'hex'.
Example:
(start code)
var black = new Color('#000');
var purple = new Color([255,0,255]);
// mix black with white and purple, each time at 10% of the new color
var darkpurple = black.mix('#fff', purple, 10);
$('myDiv').setStyle('background-color', darkpurple);
(end)
*/
var Color = new Class({
initialize: function(color, type){
type = type || (color.push ? 'rgb' : 'hex');
var rgb, hsb;
switch(type){
case 'rgb':
rgb = color;
hsb = rgb.rgbToHsb();
break;
case 'hsb':
rgb = color.hsbToRgb();
hsb = color;
break;
default:
rgb = color.hexToRgb(true);
hsb = rgb.rgbToHsb();
}
rgb.hsb = hsb;
rgb.hex = rgb.rgbToHex();
return $extend(rgb, Color.prototype);
},
/*
Property: mix
Mixes two or more colors with the Color.
Arguments:
color - a color to mix. you can use as arguments how many colors as you want to mix with the original one.
alpha - if you use a number as the last argument, it will be threated as the amount of the color to mix.
*/
mix: function(){
var colors = $A(arguments);
var alpha = ($type(colors[colors.length - 1]) == 'number') ? colors.pop() : 50;
var rgb = this.copy();
colors.each(function(color){
color = new Color(color);
for (var i = 0; i < 3; i++) rgb[i] = Math.round((rgb[i] / 100 * (100 - alpha)) + (color[i] / 100 * alpha));
});
return new Color(rgb, 'rgb');
},
/*
Property: invert
Inverts the Color.
*/
invert: function(){
return new Color(this.map(function(value){
return 255 - value;
}));
},
/*
Property: setHue
Modifies the hue of the Color, and returns a new one.
Arguments:
value - the hue to set
*/
setHue: function(value){
return new Color([value, this.hsb[1], this.hsb[2]], 'hsb');
},
/*
Property: setSaturation
Changes the saturation of the Color, and returns a new one.
Arguments:
percent - the percentage of the saturation to set
*/
setSaturation: function(percent){
return new Color([this.hsb[0], percent, this.hsb[2]], 'hsb');
},
/*
Property: setBrightness
Changes the brightness of the Color, and returns a new one.
Arguments:
percent - the percentage of the brightness to set
*/
setBrightness: function(percent){
return new Color([this.hsb[0], this.hsb[1], percent], 'hsb');
}
});
/* Section: Utility Functions */
/*
Function: $RGB
Shortcut to create a new color, based on red, green, blue values.
Arguments:
r - (integer) red value (0-255)
g - (integer) green value (0-255)
b - (integer) blue value (0-255)
*/
function $RGB(r, g, b){
return new Color([r, g, b], 'rgb');
};
/*
Function: $HSB
Shortcut to create a new color, based on hue, saturation, brightness values.
Arguments:
h - (integer) hue value (0-100)
s - (integer) saturation value (0-100)
b - (integer) brightness value (0-100)
*/
function $HSB(h, s, b){
return new Color([h, s, b], 'hsb');
};
/*
Class: Array
A collection of The Array Object prototype methods.
*/
Array.extend({
/*
Property: rgbToHsb
Converts a RGB array to an HSB array.
Returns:
the HSB array.
*/
rgbToHsb: function(){
var red = this[0], green = this[1], blue = this[2];
var hue, saturation, brightness;
var max = Math.max(red, green, blue), min = Math.min(red, green, blue);
var delta = max - min;
brightness = max / 255;
saturation = (max != 0) ? delta / max : 0;
if (saturation == 0){
hue = 0;
} else {
var rr = (max - red) / delta;
var gr = (max - green) / delta;
var br = (max - blue) / delta;
if (red == max) hue = br - gr;
else if (green == max) hue = 2 + rr - br;
else hue = 4 + gr - rr;
hue /= 6;
if (hue < 0) hue++;
}
return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)];
},
/*
Property: hsbToRgb
Converts an HSB array to an RGB array.
Returns:
the RGB array.
*/
hsbToRgb: function(){
var br = Math.round(this[2] / 100 * 255);
if (this[1] == 0){
return [br, br, br];
} else {
var hue = this[0] % 360;
var f = hue % 60;
var p = Math.round((this[2] * (100 - this[1])) / 10000 * 255);
var q = Math.round((this[2] * (6000 - this[1] * f)) / 600000 * 255);
var t = Math.round((this[2] * (6000 - this[1] * (60 - f))) / 600000 * 255);
switch(Math.floor(hue / 60)){
case 0: return [br, t, p];
case 1: return [q, br, p];
case 2: return [p, br, t];
case 3: return [p, q, br];
case 4: return [t, p, br];
case 5: return [br, p, q];
}
}
return false;
}
});
/*
Script: Scroller.js
Contains the <Scroller>.
License:
MIT-style license.
*/
/*
Class: Scroller
The Scroller is a class to scroll any element with an overflow (including the window) when the mouse cursor reaches certain buondaries of that element.
You must call its start method to start listening to mouse movements.
Note:
The Scroller requires an XHTML doctype.
Arguments:
element - required, the element to scroll.
options - optional, see options below, and <Fx.Base> options.
Options:
area - integer, the necessary boundaries to make the element scroll.
velocity - integer, velocity ratio, the modifier for the window scrolling speed.
Events:
onChange - optionally, when the mouse reaches some boundaries, you can choose to alter some other values, instead of the scrolling offsets.
Automatically passes as parameters x and y values.
*/
var Scroller = new Class({
options: {
area: 20,
velocity: 1,
onChange: function(x, y){
this.element.scrollTo(x, y);
}
},
initialize: function(element, options){
this.setOptions(options);
this.element = $(element);
this.mousemover = ([window, document].contains(element)) ? $(document.body) : this.element;
},
/*
Property: start
The scroller starts listening to mouse movements.
*/
start: function(){
this.coord = this.getCoords.bindWithEvent(this);
this.mousemover.addListener('mousemove', this.coord);
},
/*
Property: stop
The scroller stops listening to mouse movements.
*/
stop: function(){
this.mousemover.removeListener('mousemove', this.coord);
this.timer = $clear(this.timer);
},
getCoords: function(event){
this.page = (this.element == window) ? event.client : event.page;
if (!this.timer) this.timer = this.scroll.periodical(50, this);
},
scroll: function(){
var el = this.element.getSize();
var pos = this.element.getPosition();
var change = {'x': 0, 'y': 0};
for (var z in this.page){
if (this.page[z] < (this.options.area + pos[z]) && el.scroll[z] != 0)
change[z] = (this.page[z] - this.options.area - pos[z]) * this.options.velocity;
else if (this.page[z] + this.options.area > (el.size[z] + pos[z]) && el.scroll[z] + el.size[z] != el.scrollSize[z])
change[z] = (this.page[z] - el.size[z] + this.options.area - pos[z]) * this.options.velocity;
}
if (change.y || change.x) this.fireEvent('onChange', [el.scroll.x + change.x, el.scroll.y + change.y]);
}
});
Scroller.implement(new Events, new Options);
/*
Script: Slider.js
Contains <Slider>
License:
MIT-style license.
*/
/*
Class: Slider
Creates a slider with two elements: a knob and a container. Returns the values.
Note:
The Slider requires an XHTML doctype.
Arguments:
element - the knob container
knob - the handle
options - see Options below
Options:
steps - the number of steps for your slider.
mode - either 'horizontal' or 'vertical'. defaults to horizontal.
offset - relative offset for knob position. default to 0.
Events:
onChange - a function to fire when the value changes.
onComplete - a function to fire when you're done dragging.
onTick - optionally, you can alter the onTick behavior, for example displaying an effect of the knob moving to the desired position.
Passes as parameter the new position.
*/
var Slider = new Class({
options: {
onChange: Class.empty,
onComplete: Class.empty,
onTick: function(pos){
this.knob.setStyle(this.p, pos);
},
mode: 'horizontal',
steps: 100,
offset: 0
},
initialize: function(el, knob, options){
this.element = $(el);
this.knob = $(knob);
this.setOptions(options);
this.previousChange = -1;
this.previousEnd = -1;
this.step = -1;
this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this));
var mod, offset;
switch(this.options.mode){
case 'horizontal':
this.z = 'x';
this.p = 'left';
mod = {'x': 'left', 'y': false};
offset = 'offsetWidth';
break;
case 'vertical':
this.z = 'y';
this.p = 'top';
mod = {'x': false, 'y': 'top'};
offset = 'offsetHeight';
}
this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
this.half = this.knob[offset]/2;
this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);
var lim = {};
lim[this.z] = [- this.options.offset, this.max - this.options.offset];
this.drag = new Drag.Base(this.knob, {
limit: lim,
modifiers: mod,
snap: 0,
onStart: function(){
this.draggedKnob();
}.bind(this),
onDrag: function(){
this.draggedKnob();
}.bind(this),
onComplete: function(){
this.draggedKnob();
this.end();
}.bind(this)
});
if (this.options.initialize) this.options.initialize.call(this);
},
/*
Property: set
The slider will get the step you pass.
Arguments:
step - one integer
*/
set: function(step){
this.step = step.limit(0, this.options.steps);
this.checkStep();
this.end();
this.fireEvent('onTick', this.toPosition(this.step));
return this;
},
clickedElement: function(event){
var position = event.page[this.z] - this.getPos() - this.half;
position = position.limit(-this.options.offset, this.max -this.options.offset);
this.step = this.toStep(position);
this.checkStep();
this.end();
this.fireEvent('onTick', position);
},
draggedKnob: function(){
this.step = this.toStep(this.drag.value.now[this.z]);
this.checkStep();
},
checkStep: function(){
if (this.previousChange != this.step){
this.previousChange = this.step;
this.fireEvent('onChange', this.step);
}
},
end: function(){
if (this.previousEnd !== this.step){
this.previousEnd = this.step;
this.fireEvent('onComplete', this.step + '');
}
},
toStep: function(position){
return Math.round((position + this.options.offset) / this.max * this.options.steps);
},
toPosition: function(step){
return this.max * step / this.options.steps;
}
});
Slider.implement(new Events);
Slider.implement(new Options);
/*
Script: SmoothScroll.js
Contains <SmoothScroll>
License:
MIT-style license.
*/
/*
Class: SmoothScroll
Auto targets all the anchors in a page and display a smooth scrolling effect upon clicking them.
Inherits methods, properties, options and events from <Fx.Scroll>.
Note:
SmoothScroll requires an XHTML doctype.
Arguments:
options - the Fx.Scroll options (see: <Fx.Scroll>) plus links, a collection of elements you want your smoothscroll on. Defaults to document.links.
Example:
>new SmoothScroll();
*/
var SmoothScroll = Fx.Scroll.extend({
initialize: function(options){
this.parent(window, options);
this.links = (this.options.links) ? $$(this.options.links) : $$(document.links);
var location = window.location.href.match(/^[^#]*/)[0] + '#';
this.links.each(function(link){
if (link.href.indexOf(location) != 0) return;
var anchor = link.href.substr(location.length);
if (anchor && $(anchor)) this.useLink(link, anchor);
}, this);
if (!window.webkit419) this.addEvent('onComplete', function(){
window.location.hash = this.anchor;
});
},
useLink: function(link, anchor){
link.addEvent('click', function(event){
this.anchor = anchor;
this.toElement(anchor);
event.stop();
}.bindWithEvent(this));
}
});
/*
Script: Sortables.js
Contains <Sortables> Class.
License:
MIT-style license.
*/
/*
Class: Sortables
Creates an interface for <Drag.Base> and drop, resorting of a list.
Note:
The Sortables require an XHTML doctype.
Arguments:
list - required, the list that will become sortable.
options - an Object, see options below.
Options:
handles - a collection of elements to be used for drag handles. defaults to the elements.
Events:
onStart - function executed when the item starts dragging
onComplete - function executed when the item ends dragging
*/
var Sortables = new Class({
options: {
handles: false,
onStart: Class.empty,
onComplete: Class.empty,
ghost: true,
snap: 3,
onDragStart: function(element, ghost){
ghost.setStyle('opacity', 0.7);
element.setStyle('opacity', 0.7);
},
onDragComplete: function(element, ghost){
element.setStyle('opacity', 1);
ghost.remove();
this.trash.remove();
}
},
initialize: function(list, options){
this.setOptions(options);
this.list = $(list);
this.elements = this.list.getChildren();
this.handles = (this.options.handles) ? $$(this.options.handles) : this.elements;
this.bound = {
'start': [],
'moveGhost': this.moveGhost.bindWithEvent(this)
};
for (var i = 0, l = this.handles.length; i < l; i++){
this.bound.start[i] = this.start.bindWithEvent(this, this.elements[i]);
}
this.attach();
if (this.options.initialize) this.options.initialize.call(this);
this.bound.move = this.move.bindWithEvent(this);
this.bound.end = this.end.bind(this);
},
attach: function(){
this.handles.each(function(handle, i){
handle.addEvent('mousedown', this.bound.start[i]);
}, this);
},
detach: function(){
this.handles.each(function(handle, i){
handle.removeEvent('mousedown', this.bound.start[i]);
}, this);
},
start: function(event, el){
this.active = el;
this.coordinates = this.list.getCoordinates();
if (this.options.ghost){
var position = el.getPosition();
this.offset = event.page.y - position.y;
this.trash = new Element('div').inject(document.body);
this.ghost = el.clone().inject(this.trash).setStyles({
'position': 'absolute',
'left': position.x,
'top': event.page.y - this.offset
});
document.addListener('mousemove', this.bound.moveGhost);
this.fireEvent('onDragStart', [el, this.ghost]);
}
document.addListener('mousemove', this.bound.move);
document.addListener('mouseup', this.bound.end);
this.fireEvent('onStart', el);
event.stop();
},
moveGhost: function(event){
var value = event.page.y - this.offset;
value = value.limit(this.coordinates.top, this.coordinates.bottom - this.ghost.offsetHeight);
this.ghost.setStyle('top', value);
event.stop();
},
move: function(event){
var now = event.page.y;
this.previous = this.previous || now;
var up = ((this.previous - now) > 0);
var prev = this.active.getPrevious();
var next = this.active.getNext();
if (prev && up && now < prev.getCoordinates().bottom) this.active.injectBefore(prev);
if (next && !up && now > next.getCoordinates().top) this.active.injectAfter(next);
this.previous = now;
},
serialize: function(converter){
return this.list.getChildren().map(converter || function(el){
return this.elements.indexOf(el);
}, this);
},
end: function(){
this.previous = null;
document.removeListener('mousemove', this.bound.move);
document.removeListener('mouseup', this.bound.end);
if (this.options.ghost){
document.removeListener('mousemove', this.bound.moveGhost);
this.fireEvent('onDragComplete', [this.active, this.ghost]);
}
this.fireEvent('onComplete', this.active);
}
});
Sortables.implement(new Events, new Options);
/*
Script: Tips.js
Tooltips, BubbleTips, whatever they are, they will appear on mouseover
License:
MIT-style license.
Credits:
The idea behind Tips.js is based on Bubble Tooltips (<http://web-graphics.com/mtarchive/001717.php>) by Alessandro Fulcitiniti <http://web-graphics.com>
*/
/*
Class: Tips
Display a tip on any element with a title and/or href.
Note:
Tips requires an XHTML doctype.
Arguments:
elements - a collection of elements to apply the tooltips to on mouseover.
options - an object. See options Below.
Options:
maxTitleChars - the maximum number of characters to display in the title of the tip. defaults to 30.
showDelay - the delay the onShow method is called. (defaults to 100 ms)
hideDelay - the delay the onHide method is called. (defaults to 100 ms)
className - the prefix for your tooltip classNames. defaults to 'tool'.
the whole tooltip will have as classname: tool-tip
the title will have as classname: tool-title
the text will have as classname: tool-text
offsets - the distance of your tooltip from the mouse. an Object with x/y properties.
fixed - if set to true, the toolTip will not follow the mouse.
Events:
onShow - optionally you can alter the default onShow behaviour with this option (like displaying a fade in effect);
onHide - optionally you can alter the default onHide behaviour with this option (like displaying a fade out effect);
Example:
(start code)
<img src="/images/i.png" title="The body of the tooltip is stored in the title" class="toolTipImg"/>
<script>
var myTips = new Tips($$('.toolTipImg'), {
maxTitleChars: 50 //I like my captions a little long
});
</script>
(end)
Note:
The title of the element will always be used as the tooltip body. If you put :: on your title, the text before :: will become the tooltip title.
*/
var Tips = new Class({
options: {
onShow: function(tip){
tip.setStyle('visibility', 'visible');
},
onHide: function(tip){
tip.setStyle('visibility', 'hidden');
},
maxTitleChars: 30,
showDelay: 100,
hideDelay: 100,
className: 'tool',
offsets: {'x': 16, 'y': 16},
fixed: false
},
initialize: function(elements, options){
this.setOptions(options);
this.toolTip = new Element('div', {
'class': this.options.className + '-tip',
'styles': {
'position': 'absolute',
'top': '0',
'left': '0',
'visibility': 'hidden'
}
}).inject(document.body);
this.wrapper = new Element('div').inject(this.toolTip);
$$(elements).each(this.build, this);
if (this.options.initialize) this.options.initialize.call(this);
},
build: function(el){
el.$tmp.myTitle = (el.href && el.getTag() == 'a') ? el.href.replace('http://', '') : (el.rel || false);
if (el.title){
var dual = el.title.split('::');
if (dual.length > 1){
el.$tmp.myTitle = dual[0].trim();
el.$tmp.myText = dual[1].trim();
} else {
el.$tmp.myText = el.title;
}
el.removeAttribute('title');
} else {
el.$tmp.myText = false;
}
if (el.$tmp.myTitle && el.$tmp.myTitle.length > this.options.maxTitleChars) el.$tmp.myTitle = el.$tmp.myTitle.substr(0, this.options.maxTitleChars - 1) + "…";
el.addEvent('mouseenter', function(event){
this.start(el);
if (!this.options.fixed) this.locate(event);
else this.position(el);
}.bind(this));
if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this));
var end = this.end.bind(this);
el.addEvent('mouseleave', end);
el.addEvent('trash', end);
},
start: function(el){
this.wrapper.empty();
if (el.$tmp.myTitle){
this.title = new Element('span').inject(new Element('div', {'class': this.options.className + '-title'}).inject(this.wrapper)).setHTML(el.$tmp.myTitle);
}
if (el.$tmp.myText){
this.text = new Element('span').inject(new Element('div', {'class': this.options.className + '-text'}).inject(this.wrapper)).setHTML(el.$tmp.myText);
}
$clear(this.timer);
this.timer = this.show.delay(this.options.showDelay, this);
},
end: function(event){
$clear(this.timer);
this.timer = this.hide.delay(this.options.hideDelay, this);
},
position: function(element){
var pos = element.getPosition();
this.toolTip.setStyles({
'left': pos.x + this.options.offsets.x,
'top': pos.y + this.options.offsets.y
});
},
locate: function(event){
var win = {'x': window.getWidth(), 'y': window.getHeight()};
var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight};
var prop = {'x': 'left', 'y': 'top'};
for (var z in prop){
var pos = event.page[z] + this.options.offsets[z];
if ((pos + tip[z] - scroll[z]) > win[z]) pos = event.page[z] - this.options.offsets[z] - tip[z];
this.toolTip.setStyle(prop[z], pos);
};
},
show: function(){
if (this.options.timeout) this.timer = this.hide.delay(this.options.timeout, this);
this.fireEvent('onShow', [this.toolTip]);
},
hide: function(){
this.fireEvent('onHide', [this.toolTip]);
}
});
Tips.implement(new Events, new Options);
/*
Script: Group.js
For Grouping Classes or Elements Events. The Event added to the Group will fire when all of the events of the items of the group are fired.
License:
MIT-style license.
*/
/*
Class: Group
An "Utility" Class.
Arguments:
List of Class instances
Example:
(start code)
xhr1 = new Ajax('data.js', {evalScript: true});
xhr2 = new Ajax('abstraction.js', {evalScript: true});
xhr3 = new Ajax('template.js', {evalScript: true});
var group = new Group(xhr1, xhr2, xhr3);
group.addEvent('onComplete', function(){
alert('All Scripts loaded');
});
xhr1.request();
xhr2.request();
xhr3.request();
(end)
*/
var Group = new Class({
initialize: function(){
this.instances = $A(arguments);
this.events = {};
this.checker = {};
},
/*
Property: addEvent
adds an event to the stack of events of the Class instances.
Arguments:
type - string; the event name (e.g. 'onComplete')
fn - function to execute when all instances fired this event
*/
addEvent: function(type, fn){
this.checker[type] = this.checker[type] || {};
this.events[type] = this.events[type] || [];
if (this.events[type].contains(fn)) return false;
else this.events[type].push(fn);
this.instances.each(function(instance, i){
instance.addEvent(type, this.check.bind(this, [type, instance, i]));
}, this);
return this;
},
check: function(type, instance, i){
this.checker[type][i] = true;
var every = this.instances.every(function(current, j){
return this.checker[type][j] || false;
}, this);
if (!every) return;
this.checker[type] = {};
this.events[type].each(function(event){
event.call(this, this.instances, instance);
}, this);
}
});
/*
Script: Accordion.js
Contains <Accordion>
License:
MIT-style license.
*/
/*
Class: Accordion
The Accordion class creates a group of elements that are toggled when their handles are clicked. When one elements toggles in, the others toggles back.
Inherits methods, properties, options and events from <Fx.Elements>.
Note:
The Accordion requires an XHTML doctype.
Arguments:
togglers - required, a collection of elements, the elements handlers that will be clickable.
elements - required, a collection of elements the transitions will be applied to.
options - optional, see options below, and <Fx.Base> options and events.
Options:
show - integer, the Index of the element to show at start.
display - integer, the Index of the element to show at start (with a transition). defaults to 0.
fixedHeight - integer, if you want the elements to have a fixed height. defaults to false.
fixedWidth - integer, if you want the elements to have a fixed width. defaults to false.
height - boolean, will add a height transition to the accordion if true. defaults to true.
opacity - boolean, will add an opacity transition to the accordion if true. defaults to true.
width - boolean, will add a width transition to the accordion if true. defaults to false, css mastery is required to make this work!
alwaysHide - boolean, will allow to hide all elements if true, instead of always keeping one element shown. defaults to false.
Events:
onActive - function to execute when an element starts to show
onBackground - function to execute when an element starts to hide
*/
var Accordion = Fx.Elements.extend({
options: {
onActive: Class.empty,
onBackground: Class.empty,
display: 0,
show: false,
height: true,
width: false,
opacity: true,
fixedHeight: false,
fixedWidth: false,
wait: false,
alwaysHide: false
},
initialize: function(){
var options, togglers, elements, container;
$each(arguments, function(argument, i){
switch($type(argument)){
case 'object': options = argument; break;
case 'element': container = $(argument); break;
default:
var temp = $$(argument);
if (!togglers) togglers = temp;
else elements = temp;
}
});
this.togglers = togglers || [];
this.elements = elements || [];
this.container = $(container);
this.setOptions(options);
this.previous = -1;
if (this.options.alwaysHide) this.options.wait = true;
if ($chk(this.options.show)){
this.options.display = false;
this.previous = this.options.show;
}
if (this.options.start){
this.options.display = false;
this.options.show = false;
}
this.effects = {};
if (this.options.opacity) this.effects.opacity = 'fullOpacity';
if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth';
if (this.options.height) this.effects.height = this.options.fixedHeight ? 'fullHeight' : 'scrollHeight';
for (var i = 0, l = this.togglers.length; i < l; i++) this.addSection(this.togglers[i], this.elements[i]);
this.elements.each(function(el, i){
if (this.options.show === i){
this.fireEvent('onActive', [this.togglers[i], el]);
} else {
for (var fx in this.effects) el.setStyle(fx, 0);
}
}, this);
this.parent(this.elements);
if ($chk(this.options.display)) this.display(this.options.display);
},
/*
Property: addSection
Dynamically adds a new section into the accordion at the specified position.
Arguments:
toggler - (dom element) the element that toggles the accordion section open.
element - (dom element) the element that stretches open when the toggler is clicked.
pos - (integer) the index where these objects are to be inserted within the accordion.
*/
addSection: function(toggler, element, pos){
toggler = $(toggler);
element = $(element);
var test = this.togglers.contains(toggler);
var len = this.togglers.length;
this.togglers.include(toggler);
this.elements.include(element);
if (len && (!test || pos)){
pos = $pick(pos, len - 1);
toggler.injectBefore(this.togglers[pos]);
element.injectAfter(toggler);
} else if (this.container && !test){
toggler.inject(this.container);
element.inject(this.container);
}
var idx = this.togglers.indexOf(toggler);
toggler.addEvent('click', this.display.bind(this, idx));
if (this.options.height) element.setStyles({'padding-top': 0, 'border-top': 'none', 'padding-bottom': 0, 'border-bottom': 'none'});
if (this.options.width) element.setStyles({'padding-left': 0, 'border-left': 'none', 'padding-right': 0, 'border-right': 'none'});
element.fullOpacity = 1;
if (this.options.fixedWidth) element.fullWidth = this.options.fixedWidth;
if (this.options.fixedHeight) element.fullHeight = this.options.fixedHeight;
element.setStyle('overflow', 'hidden');
if (!test){
for (var fx in this.effects) element.setStyle(fx, 0);
}
return this;
},
/*
Property: display
Shows a specific section and hides all others. Useful when triggering an accordion from outside.
Arguments:
index - integer, the index of the item to show, or the actual element to show.
*/
display: function(index){
index = ($type(index) == 'element') ? this.elements.indexOf(index) : index;
if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this;
this.previous = index;
var obj = {};
this.elements.each(function(el, i){
obj[i] = {};
var hide = (i != index) || (this.options.alwaysHide && (el.offsetHeight > 0));
this.fireEvent(hide ? 'onBackground' : 'onActive', [this.togglers[i], el]);
for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]];
}, this);
return this.start(obj);
},
showThisHideOpen: function(index){return this.display(index);}
});
Fx.Accordion = Accordion; | JavaScript |
/* Copyright (c) 2008 Kean Loong Tan http://www.gimiti.com/kltan
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* jFlow
* Version: 1.2 (July 7, 2008)
* Requires: jQuery 1.2+
*/
(function($) {
$.fn.jFlow = function(options) {
var opts = $.extend({}, $.fn.jFlow.defaults, options);
var randNum = Math.floor(Math.random()*11);
var jFC = opts.controller;
var jFS = opts.slideWrapper;
var jSel = opts.selectedWrapper;
var cur = 0;
var timer;
var maxi = $(jFC).length;
// sliding function
var slide = function (dur, i) {
$(opts.slides).children().css({
overflow:"hidden"
});
$(opts.slides + " iframe").hide().addClass("temp_hide");
$(opts.slides).animate({
marginLeft: "-" + (i * $(opts.slides).find(":first-child").width() + "px")
},
opts.duration*(dur),
opts.easing,
function(){
$(opts.slides).children().css({
overflow:"hidden"
});
$(".temp_hide").show();
}
);
}
$(this).find(jFC).each(function(i){
$(this).click(function(){
dotimer();
if ($(opts.slides).is(":not(:animated)")) {
$(jFC).removeClass(jSel);
$(this).addClass(jSel);
var dur = Math.abs(cur-i);
slide(dur,i);
cur = i;
}
});
});
$(opts.slides).before('<div id="'+jFS.substring(1, jFS.length)+'"></div>').appendTo(jFS);
$(opts.slides).find("div").each(function(){
$(this).before('<div class="jFlowSlideContainer"></div>').appendTo($(this).prev());
});
//initialize the controller
$(jFC).eq(cur).addClass(jSel);
var resize = function (x){
$(jFS).css({
position:"relative",
width: opts.width,
height: opts.height,
overflow: "hidden"
});
//opts.slides or #mySlides container
$(opts.slides).css({
position:"relative",
width: $(jFS).width()*$(jFC).length+"px",
height: $(jFS).height()+"px",
overflow: "hidden"
});
// jFlowSlideContainer
$(opts.slides).children().css({
position:"relative",
width: $(jFS).width()+"px",
height: $(jFS).height()+"px",
"float":"left",
overflow:"hidden"
});
$(opts.slides).css({
marginLeft: "-" + (cur * $(opts.slides).find(":eq(0)").width() + "px")
});
}
// sets initial size
resize();
// resets size
$(window).resize(function(){
resize();
});
$(opts.prev).click(function(){
dotimer();
doprev();
});
$(opts.next).click(function(){
dotimer();
donext();
});
var doprev = function (x){
if ($(opts.slides).is(":not(:animated)")) {
var dur = 1;
if (cur > 0)
cur--;
else {
cur = maxi -1;
dur = cur;
}
$(jFC).removeClass(jSel);
slide(dur,cur);
$(jFC).eq(cur).addClass(jSel);
}
}
var donext = function (x){
if ($(opts.slides).is(":not(:animated)")) {
var dur = 1;
if (cur < maxi - 1)
cur++;
else {
cur = 0;
dur = maxi -1;
}
$(jFC).removeClass(jSel);
//$(jFS).fadeOut("fast");
slide(dur, cur);
//$(jFS).fadeIn("fast");
$(jFC).eq(cur).addClass(jSel);
}
}
var dotimer = function (x){
if((opts.auto) == true) {
if(timer != null)
clearInterval(timer);
timer = setInterval(function() {
$(opts.next).click();
}, 10000);
}
}
dotimer();
};
$.fn.jFlow.defaults = {
controller: ".jFlowControl", // must be class, use . sign
slideWrapper : "#jFlowSlide", // must be id, use # sign
selectedWrapper: "jFlowSelected", // just pure text, no sign
auto: false,
easing: "swing",
duration: 400,
width: "100%",
prev: ".jFlowPrev", // must be class, use . sign
next: ".jFlowNext" // must be class, use . sign
};
})(jQuery);
| JavaScript |
// SET THIS VARIABLE FOR DELAY, 1000 = 1 SECOND
var delayLength = 4000;
function doMove(panelWidth, tooFar) {
var leftValue = $("#mover").css("left");
// Fix for IE
if (leftValue == "auto") { leftValue = 0; };
var movement = parseFloat(leftValue, 10) - panelWidth;
if (movement == tooFar) {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": 0
}, function() {
$(".slide img").animate({
"top": 50
});
});
});
}
else {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": movement
}, function() {
$(".slide img").animate({
"top": 50
});
});
});
}
}
$(function(){
var $slide1 = $(".slide");
var panelWidth = $slide1.css("width");
var panelPaddingLeft = $slide1.css("paddingLeft");
var panelPaddingRight = $slide1.css("paddingRight");
panelWidth = parseFloat(panelWidth, 10);
panelPaddingLeft = parseFloat(panelPaddingLeft, 10);
panelPaddingRight = parseFloat(panelPaddingRight, 10);
panelWidth = panelWidth + panelPaddingLeft + panelPaddingRight;
var numPanels = $(".slide").length;
var tooFar = -(panelWidth * numPanels);
var totalMoverwidth = numPanels * panelWidth;
$("#mover").css("width", totalMoverwidth);
$("#slider").append('<a href="#" id="slider-stopper">Stop</a>');
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$("#slider-stopper").click(function(){
if ($(this).text() == "Stop") {
clearInterval(sliderIntervalID);
$(this).text("Start");
}
else {
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$(this).text("Stop");
}
});
}); | JavaScript |
//** Featured Content Slider script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
//** May 2nd, 08'- Script rewritten and updated to 2.0.
//** June 12th, 08'- Script updated to v 2.3, which adds the following features:
//1) Changed behavior of script to actually collapse the previous content when the active one is shown, instead of just tucking it underneath the later.
//2) Added setting to reveal a content either via "click" or "mouseover" of pagination links (default is former).
//3) Added public function for jumping to a particular slide within a Featured Content instance using an arbitrary link, for example.
//** July 11th, 08'- Script updated to v 2.4:
//1) Added ability to select a particular slide when the page first loads using a URL parameter (ie: mypage.htm?myslider=4 to select 4th slide in "myslider")
//2) Fixed bug where the first slide disappears when the mouse clicks or mouses over it when page first loads.
var featuredcontentslider={
//3 variables below you can customize if desired:
ajaxloadingmsg: '<div style="margin: 20px 0 0 20px"><img src="https://lh6.googleusercontent.com/-JicBKebJ_RM/Tg7xRsdxAEI/AAAAAAAABOE/CK5Ubw1CAd4/s800/loading.gif" /> Fetching slider Contents. Please wait...</div>',
bustajaxcache: true, //bust caching of external ajax page after 1st request?
enablepersist: true, //persist to last content viewed when returning to page?
settingcaches: {}, //object to cache "setting" object of each script instance
jumpTo:function(fcsid, pagenumber){ //public function to go to a slide manually.
this.turnpage(this.settingcaches[fcsid], pagenumber)
},
ajaxconnect:function(setting){
var page_request = false
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else
return false
var pageurl=setting.contentsource[1]
page_request.onreadystatechange=function(){
featuredcontentslider.ajaxpopulate(page_request, setting)
}
document.getElementById(setting.id).innerHTML=this.ajaxloadingmsg
var bustcache=(!this.bustajaxcache)? "" : (pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', pageurl+bustcache, true)
page_request.send(null)
},
ajaxpopulate:function(page_request, setting){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
document.getElementById(setting.id).innerHTML=page_request.responseText
this.buildpaginate(setting)
}
},
buildcontentdivs:function(setting){
var alldivs=document.getElementById(setting.id).getElementsByTagName("div")
for (var i=0; i<alldivs.length; i++){
if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv"
setting.contentdivs.push(alldivs[i])
alldivs[i].style.display="none" //collapse all content DIVs to begin with
}
}
},
buildpaginate:function(setting){
this.buildcontentdivs(setting)
var sliderdiv=document.getElementById(setting.id)
var pdiv=document.getElementById("paginate-"+setting.id)
var phtml=""
var toc=setting.toc
var nextprev=setting.nextprev
if (typeof toc=="string" && toc!="markup" || typeof toc=="object"){
for (var i=1; i<=setting.contentdivs.length; i++){
phtml+='<a href="#'+i+'" class="toc">'+(typeof toc=="string"? toc.replace(/#increment/, i) : toc[i-1])+'</a> '
}
phtml=(nextprev[0]!=''? '<a href="#prev" class="prev">'+nextprev[0]+'</a> ' : '') + phtml + (nextprev[1]!=''? '<a href="#next" class="next">'+nextprev[1]+'</a>' : '')
pdiv.innerHTML=phtml
}
var pdivlinks=pdiv.getElementsByTagName("a")
var toclinkscount=0 //var to keep track of actual # of toc links
for (var i=0; i<pdivlinks.length; i++){
if (this.css(pdivlinks[i], "toc", "check")){
if (toclinkscount>setting.contentdivs.length-1){ //if this toc link is out of range (user defined more toc links then there are contents)
pdivlinks[i].style.display="none" //hide this toc link
continue
}
pdivlinks[i].setAttribute("rel", ++toclinkscount) //store page number inside toc link
pdivlinks[i][setting.revealtype]=function(){
featuredcontentslider.turnpage(setting, this.getAttribute("rel"))
return false
}
setting.toclinks.push(pdivlinks[i])
}
else if (this.css(pdivlinks[i], "prev", "check") || this.css(pdivlinks[i], "next", "check")){ //check for links with class "prev" or "next"
pdivlinks[i].onclick=function(){
featuredcontentslider.turnpage(setting, this.className)
return false
}
}
}
this.turnpage(setting, setting.currentpage, true)
if (setting.autorotate[0]){ //if auto rotate enabled
pdiv[setting.revealtype]=function(){
featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id])
}
sliderdiv["onclick"]=function(){ //stop content slider when slides themselves are clicked on
featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id])
}
setting.autorotate[1]=setting.autorotate[1]+(1/setting.enablefade[1]*50) //add time to run fade animation (roughly) to delay between rotation
this.autorotate(setting)
}
},
urlparamselect:function(fcsid){
var result=window.location.search.match(new RegExp(fcsid+"=(\\d+)", "i")) //check for "?featuredcontentsliderid=2" in URL
return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index
},
turnpage:function(setting, thepage, autocall){
var currentpage=setting.currentpage //current page # before change
var totalpages=setting.contentdivs.length
var turntopage=(/prev/i.test(thepage))? currentpage-1 : (/next/i.test(thepage))? currentpage+1 : parseInt(thepage)
turntopage=(turntopage<1)? totalpages : (turntopage>totalpages)? 1 : turntopage //test for out of bound and adjust
if (turntopage==setting.currentpage && typeof autocall=="undefined") //if a pagination link is clicked on repeatedly
return
setting.currentpage=turntopage
setting.contentdivs[turntopage-1].style.zIndex=++setting.topzindex
this.cleartimer(setting, window["fcsfade"+setting.id])
setting.cacheprevpage=setting.prevpage
if (setting.enablefade[0]==true){
setting.curopacity=0
this.fadeup(setting)
}
if (setting.enablefade[0]==false){ //if fade is disabled, fire onChange event immediately (verus after fade is complete)
setting.contentdivs[setting.prevpage-1].style.display="none" //collapse last content div shown (it was set to "block")
setting.onChange(setting.prevpage, setting.currentpage)
}
setting.contentdivs[turntopage-1].style.visibility="visible"
setting.contentdivs[turntopage-1].style.display="block"
if (setting.prevpage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted)
this.css(setting.toclinks[setting.prevpage-1], "selected", "remove")
if (turntopage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted)
this.css(setting.toclinks[turntopage-1], "selected", "add")
setting.prevpage=turntopage
if (this.enablepersist)
this.setCookie("fcspersist"+setting.id, turntopage)
},
setopacity:function(setting, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between)
var targetobject=setting.contentdivs[setting.currentpage-1]
if (targetobject.filters && targetobject.filters[0]){ //IE syntax
if (typeof targetobject.filters[0].opacity=="number") //IE6
targetobject.filters[0].opacity=value*100
else //IE 5.5
targetobject.style.filter="alpha(opacity="+value*100+")"
}
else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
targetobject.style.MozOpacity=value
else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
targetobject.style.opacity=value
setting.curopacity=value
},
fadeup:function(setting){
if (setting.curopacity<1){
this.setopacity(setting, setting.curopacity+setting.enablefade[1])
window["fcsfade"+setting.id]=setTimeout(function(){featuredcontentslider.fadeup(setting)}, 50)
}
else{ //when fade is complete
if (setting.cacheprevpage!=setting.currentpage) //if previous content isn't the same as the current shown div (happens the first time the page loads/ script is run)
setting.contentdivs[setting.cacheprevpage-1].style.display="none" //collapse last content div shown (it was set to "block")
setting.onChange(setting.cacheprevpage, setting.currentpage)
}
},
cleartimer:function(setting, timervar){
if (typeof timervar!="undefined"){
clearTimeout(timervar)
clearInterval(timervar)
if (setting.cacheprevpage!=setting.currentpage){ //if previous content isn't the same as the current shown div
setting.contentdivs[setting.cacheprevpage-1].style.display="none"
}
}
},
css:function(el, targetclass, action){
var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig")
if (action=="check")
return needle.test(el.className)
else if (action=="remove")
el.className=el.className.replace(needle, "")
else if (action=="add")
el.className+=" "+targetclass
},
autorotate:function(setting){
window["fcsautorun"+setting.id]=setInterval(function(){featuredcontentslider.turnpage(setting, "next")}, setting.autorotate[1])
},
getCookie:function(Name){
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
},
setCookie:function(name, value){
document.cookie = name+"="+value
},
init:function(setting){
var persistedpage=this.getCookie("fcspersist"+setting.id) || 1
var urlselectedpage=this.urlparamselect(setting.id) //returns null or index from: mypage.htm?featuredcontentsliderid=index
this.settingcaches[setting.id]=setting //cache "setting" object
setting.contentdivs=[]
setting.toclinks=[]
setting.topzindex=0
setting.currentpage=urlselectedpage || ((this.enablepersist)? persistedpage : 1)
setting.prevpage=setting.currentpage
setting.revealtype="on"+(setting.revealtype || "click")
setting.curopacity=0
setting.onChange=setting.onChange || function(){}
if (setting.contentsource[0]=="inline")
this.buildpaginate(setting)
if (setting.contentsource[0]=="ajax")
this.ajaxconnect(setting)
}
} | JavaScript |
var showpostthumbnails_gal = true;
var showpostsummary_gal = true;
var random_posts = false;
var numchars_gal = 150;
var numposts_gal = 10;
function showgalleryposts(json) {
document.write('<div class="slider-wrap">');
document.write('<div id="main-photo-slider" class="csw"><div class="panelContainer">');
var numPosts = json.feed.openSearch$totalResults.$t;
var indexPosts = new Array();
document.write('<ul>');
for (var i = 0; i < numPosts; ++i) {
indexPosts[i] = i;
}
if (random_posts == true){
indexPosts.sort(function() {return 0.5 - Math.random()});
}
if (numposts_gal > numPosts) {
numposts_gal = numPosts;
}
for (i = 0; i < numposts_gal; ++i) {
var entry_gal = json.feed.entry[indexPosts[i]];
var posttitle_gal = entry_gal.title.$t;
for (var k = 0; k < entry_gal.link.length; k++) {
if ( entry_gal.link[k].rel == 'alternate') {
posturl_gal = entry_gal.link[k].href;
break;
}
}
if("content"in entry_gal){
var postcontent_gal=entry_gal.content.$t;
}
s = postcontent_gal;
a = s.indexOf("<img");
b = s.indexOf("src=\"", a);
c = s.indexOf("\"", b + 5);
d = s.substr(b + 5, c - b - 5);
if ((a != -1) && (b != -1) && (c != -1) && (d != "")) {
var thumburl_gal = d;
}
else var thumburl_gal = 'http://i1133.photobucket.com/albums/m596/abu-farhan/Images_no_image.gif';
var _no=i+1;
document.write('<div class="panel" title="'+posttitle_gal+'">');
document.write('<div class="wrapper">');
document.write('<a href="'+ posturl_gal + '"><img src="'+thumburl_gal+'" alt="temp" width="420px" height="270px"/></a>');
document.write('<div class="photo-meta-data"><span>'+posttitle_gal+'</span><br>');
var re = /<\S[^>]*>/g;
postcontent_gal = postcontent_gal.replace(re, "");
if (showpostsummary_gal == true) {
if (postcontent_gal.length < numchars_gal) {
document.write(postcontent_gal);
}
else {
postcontent_gal = postcontent_gal.substring(0, numchars_gal);
var quoteEnd_gal = postcontent_gal.lastIndexOf(" ");
postcontent_gal = postcontent_gal.substring(0,quoteEnd_gal);
document.write(postcontent_gal + '...');
}
}
document.write('</div>');
document.write('</div>');
document.write('</div>');
}
document.write('</div>');
document.write('</div>');
for (var i = 0; i < numposts_gal; i++) {
if (random_posts == true){
var random_int = Math.floor(Math.random()*json.feed.entry.length);
var entry_gal = json.feed.entry[random_int];
}
else{
var entry_gal = json.feed.entry[i];
}
if("content"in entry_gal){
var postcontent_gal=entry_gal.content.$t;
}
s = postcontent_gal;
a = s.indexOf("<img");
b = s.indexOf("src=\"", a);
c = s.indexOf("\"", b + 5);
d = s.substr(b + 5, c - b - 5);
if ((a != -1) && (b != -1) && (c != -1) && (d != "")) {
var thumburl_gal = d;
}
else var thumburl_gal = 'http://i1133.photobucket.com/albums/m596/abu-farhan/Images_no_image.gif';
<!-- Note this caption is before the image, all others it is after -->
var _no=i+1;
if (_no==1){
document.write('<a href="#'+_no+'" class="cross-link active-thumb"><img src="'+thumburl_gal+'" class="nav-thumb" alt="temp-thumb" width="60px" height="40px" /></a>');
document.write('<div id="movers-row">');
}
else{
document.write('<div><a href="#'+_no+'" class="cross-link"><img src="'+thumburl_gal+'" class="nav-thumb" alt="temp-thumb" width="60px" height="40px"/></a></div>');
}
}
document.write('</div>');
document.write('</div>');
document.write('</div>');
}
| JavaScript |
//<![CDATA[
(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 |
/*
This file is part of JonDesign's SmoothGallery v2.0.
JonDesign's SmoothGallery is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
JonDesign's SmoothGallery is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with JonDesign's SmoothGallery; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Main Developer: Jonathan Schemoul (JonDesign: http://www.jondesign.net/)
Contributed code by:
- Christian Ehret (bugfix)
- Nitrix (bugfix)
- Valerio from Mad4Milk for his great help with the carousel scrolling and many other things.
- Archie Cowan for helping me find a bugfix on carousel inner width problem.
- Tomocchino from #mootools for the preloader class
Many thanks to:
- The mootools team for the great mootools lib, and it's help and support throughout the project.
*/
// declaring the class
var gallery = {
initialize: function(element, options) {
this.setOptions({
showArrows: true,
showCarousel: true,
showInfopane: true,
embedLinks: true,
fadeDuration: 500,
timed: false,
delay: 9000,
preloader: true,
preloaderImage: true,
preloaderErrorImage: true,
/* Data retrieval */
manualData: [],
populateFrom: false,
populateData: true,
destroyAfterPopulate: true,
elementSelector: "div.imageElement",
titleSelector: "h2",
subtitleSelector: "p",
linkSelector: "a.open",
imageSelector: "img.full",
thumbnailSelector: "img.thumbnail",
defaultTransition: "fade",
/* InfoPane options */
slideInfoZoneOpacity: 0.7,
slideInfoZoneSlide: true,
/* Carousel options */
carouselMinimizedOpacity: 0.4,
carouselMinimizedHeight: 20,
carouselMaximizedOpacity: 0.9,
thumbHeight: 75,
thumbWidth: 100,
thumbSpacing: 10,
thumbIdleOpacity: 0.2,
textShowCarousel: 'Featured Content',
showCarouselLabel: true,
thumbCloseCarousel: true,
useThumbGenerator: false,
thumbGenerator: 'resizer.php',
useExternalCarousel: false,
carouselElement: false,
carouselHorizontal: true,
activateCarouselScroller: true,
carouselPreloader: true,
textPreloadingCarousel: 'Loading...',
/* CSS Classes */
baseClass: 'jdGallery',
withArrowsClass: 'withArrows',
/* Plugins: HistoryManager */
useHistoryManager: false,
customHistoryKey: false
}, options);
this.fireEvent('onInit');
this.currentIter = 0;
this.lastIter = 0;
this.maxIter = 0;
this.galleryElement = element;
this.galleryData = this.options.manualData;
this.galleryInit = 1;
this.galleryElements = Array();
this.thumbnailElements = Array();
this.galleryElement.addClass(this.options.baseClass);
this.populateFrom = element;
if (this.options.populateFrom)
this.populateFrom = this.options.populateFrom;
if (this.options.populateData)
this.populateData();
element.style.display="block";
if (this.options.useHistoryManager)
this.initHistory();
if (this.options.embedLinks)
{
this.currentLink = new Element('a').addClass('open').setProperties({
href: '#',
title: ''
}).injectInside(element);
if ((!this.options.showArrows) && (!this.options.showCarousel))
this.galleryElement = element = this.currentLink;
else
this.currentLink.setStyle('display', 'none');
}
this.constructElements();
if ((this.galleryData.length>1)&&(this.options.showArrows))
{
var leftArrow = new Element('a').addClass('left').addEvent(
'click',
this.prevItem.bind(this)
).injectInside(element);
var rightArrow = new Element('a').addClass('right').addEvent(
'click',
this.nextItem.bind(this)
).injectInside(element);
this.galleryElement.addClass(this.options.withArrowsClass);
}
this.loadingElement = new Element('div').addClass('loadingElement').injectInside(element);
if (this.options.showInfopane) this.initInfoSlideshow();
if (this.options.showCarousel) this.initCarousel();
this.doSlideShow(1);
},
populateData: function() {
currentArrayPlace = this.galleryData.length;
options = this.options;
var data = $A(this.galleryData);
data.extend(this.populateGallery(this.populateFrom, currentArrayPlace));
this.galleryData = data;
this.fireEvent('onPopulated');
},
populateGallery: function(element, startNumber) {
var data = [];
options = this.options;
currentArrayPlace = startNumber;
element.getElements(options.elementSelector).each(function(el) {
elementDict = {
image: el.getElement(options.imageSelector).getProperty('src'),
number: currentArrayPlace,
transition: this.options.defaultTransition
};
elementDict.extend = $extend;
if ((options.showInfopane) | (options.showCarousel))
elementDict.extend({
title: el.getElement(options.titleSelector).innerHTML,
description: el.getElement(options.subtitleSelector).innerHTML
});
if (options.embedLinks)
elementDict.extend({
link: el.getElement(options.linkSelector).href||false,
linkTitle: el.getElement(options.linkSelector).title||false,
linkTarget: el.getElement(options.linkSelector).getProperty('target')||false
});
if ((!options.useThumbGenerator) && (options.showCarousel))
elementDict.extend({
thumbnail: el.getElement(options.thumbnailSelector).getProperty('src')
});
else if (options.useThumbGenerator)
elementDict.extend({
thumbnail: options.thumbGenerator + '?imgfile=' + elementDict.image + '&max_width=' + options.thumbWidth + '&max_height=' + options.thumbHeight
});
data.extend([elementDict]);
currentArrayPlace++;
if (this.options.destroyAfterPopulate)
el.remove();
});
return data;
},
constructElements: function() {
el = this.galleryElement;
this.maxIter = this.galleryData.length;
var currentImg;
for(i=0;i<this.galleryData.length;i++)
{
var currentImg = new Fx.Styles(
new Element('div').addClass('slideElement').setStyles({
'position':'absolute',
'left':'0px',
'right':'0px',
'margin':'0px',
'padding':'0px',
'backgroundPosition':"center center",
'opacity':'0'
}).injectInside(el),
'opacity',
{duration: this.options.fadeDuration}
);
if (this.options.preloader)
{
currentImg.source = this.galleryData[i].image;
currentImg.loaded = false;
currentImg.load = function(imageStyle) {
if (!imageStyle.loaded) {
new Asset.image(imageStyle.source, {
'onload' : function(img){
img.element.setStyle(
'backgroundImage',
"url('" + img.source + "')")
img.loaded = true;
}.bind(this, imageStyle)
});
}
}.pass(currentImg, this);
} else {
currentImg.element.setStyle('backgroundImage',
"url('" + this.galleryData[i].image + "')");
}
this.galleryElements[parseInt(i)] = currentImg;
}
},
destroySlideShow: function(element) {
var myClassName = element.className;
var newElement = new Element('div').addClass('myClassName');
element.parentNode.replaceChild(newElement, element);
},
startSlideShow: function() {
this.fireEvent('onStart');
this.loadingElement.style.display = "none";
this.lastIter = this.maxIter - 1;
this.currentIter = 0;
this.galleryInit = 0;
this.galleryElements[parseInt(this.currentIter)].set({opacity: 1});
if (this.options.showInfopane)
this.showInfoSlideShow.delay(1000, this);
var textShowCarousel = formatString(this.options.textShowCarousel, this.currentIter+1, this.maxIter);
if (this.options.showCarousel&&(!this.options.carouselPreloader))
this.carouselBtn.setHTML(textShowCarousel).setProperty('title', textShowCarousel);
this.prepareTimer();
if (this.options.embedLinks)
this.makeLink(this.currentIter);
},
nextItem: function() {
this.fireEvent('onNextCalled');
this.nextIter = this.currentIter+1;
if (this.nextIter >= this.maxIter)
this.nextIter = 0;
this.galleryInit = 0;
this.goTo(this.nextIter);
},
prevItem: function() {
this.fireEvent('onPreviousCalled');
this.nextIter = this.currentIter-1;
if (this.nextIter <= -1)
this.nextIter = this.maxIter - 1;
this.galleryInit = 0;
this.goTo(this.nextIter);
},
goTo: function(num) {
this.clearTimer();
if(this.options.preloader)
{
this.galleryElements[num].load();
if (num==0)
this.galleryElements[this.maxIter - 1].load();
else
this.galleryElements[num - 1].load();
if (num==(this.maxIter - 1))
this.galleryElements[0].load();
else
this.galleryElements[num + 1].load();
}
if (this.options.embedLinks)
this.clearLink();
if (this.options.showInfopane)
{
this.slideInfoZone.clearChain();
this.hideInfoSlideShow().chain(this.changeItem.pass(num, this));
} else
this.currentChangeDelay = this.changeItem.delay(500, this, num);
if (this.options.embedLinks)
this.makeLink(num);
this.prepareTimer();
/*if (this.options.showCarousel)
this.clearThumbnailsHighlights();*/
},
changeItem: function(num) {
this.fireEvent('onStartChanging');
this.galleryInit = 0;
if (this.currentIter != num)
{
for(i=0;i<this.maxIter;i++)
{
if ((i != this.currentIter)) this.galleryElements[i].set({opacity: 0});
}
gallery.Transitions[this.galleryData[num].transition].pass([
this.galleryElements[this.currentIter],
this.galleryElements[num],
this.currentIter,
num], this)();
this.currentIter = num;
}
var textShowCarousel = formatString(this.options.textShowCarousel, num+1, this.maxIter);
if (this.options.showCarousel)
this.carouselBtn.setHTML(textShowCarousel).setProperty('title', textShowCarousel);
this.doSlideShow.bind(this)();
this.fireEvent('onChanged');
},
clearTimer: function() {
if (this.options.timed)
$clear(this.timer);
},
prepareTimer: function() {
if (this.options.timed)
this.timer = this.nextItem.delay(this.options.delay, this);
},
doSlideShow: function(position) {
if (this.galleryInit == 1)
{
imgPreloader = new Image();
imgPreloader.onload=function(){
this.startSlideShow.delay(10, this);
}.bind(this);
imgPreloader.src = this.galleryData[0].image;
if(this.options.preloader)
this.galleryElements[0].load();
} else {
if (this.options.showInfopane)
{
if (this.options.showInfopane)
{
this.showInfoSlideShow.delay((500 + this.options.fadeDuration), this);
} else
if ((this.options.showCarousel)&&(this.options.activateCarouselScroller))
this.centerCarouselOn(position);
}
}
},
createCarousel: function() {
var carouselElement;
if (!this.options.useExternalCarousel)
{
var carouselContainerElement = new Element('div').addClass('carouselContainer').injectInside(this.galleryElement);
this.carouselContainer = new Fx.Styles(carouselContainerElement, {transition: Fx.Transitions.expoOut});
this.carouselContainer.normalHeight = carouselContainerElement.offsetHeight;
this.carouselContainer.set({'opacity': this.options.carouselMinimizedOpacity, 'top': (this.options.carouselMinimizedHeight - this.carouselContainer.normalHeight)});
this.carouselBtn = new Element('a').addClass('carouselBtn').setProperties({
title: this.options.textShowCarousel
}).injectInside(carouselContainerElement);
if(this.options.carouselPreloader)
this.carouselBtn.setHTML(this.options.textPreloadingCarousel);
else
this.carouselBtn.setHTML(this.options.textShowCarousel);
this.carouselBtn.addEvent(
'click',
function () {
this.carouselContainer.clearTimer();
this.toggleCarousel();
}.bind(this)
);
this.carouselActive = false;
carouselElement = new Element('div').addClass('carousel').injectInside(carouselContainerElement);
this.carousel = new Fx.Styles(carouselElement);
} else {
carouselElement = $(this.options.carouselElement).addClass('jdExtCarousel');
}
this.carouselElement = new Fx.Styles(carouselElement, {transition: Fx.Transitions.expoOut});
this.carouselElement.normalHeight = carouselElement.offsetHeight;
if (this.options.showCarouselLabel)
this.carouselLabel = new Element('p').addClass('label').injectInside(carouselElement);
carouselWrapper = new Element('div').addClass('carouselWrapper').injectInside(carouselElement);
this.carouselWrapper = new Fx.Styles(carouselWrapper, {transition: Fx.Transitions.expoOut});
this.carouselWrapper.normalHeight = carouselWrapper.offsetHeight;
this.carouselInner = new Element('div').addClass('carouselInner').injectInside(carouselWrapper);
if (this.options.activateCarouselScroller)
{
this.carouselWrapper.scroller = new Scroller(carouselWrapper, {
area: 100,
velocity: 0.2
})
this.carouselWrapper.elementScroller = new Fx.Scroll(carouselWrapper, {
duration: 400,
onStart: this.carouselWrapper.scroller.stop.bind(this.carouselWrapper.scroller),
onComplete: this.carouselWrapper.scroller.start.bind(this.carouselWrapper.scroller)
});
}
},
fillCarousel: function() {
this.constructThumbnails();
this.carouselInner.normalWidth = ((this.maxIter * (this.options.thumbWidth + this.options.thumbSpacing + 2))+this.options.thumbSpacing) + "px";
this.carouselInner.style.width = this.carouselInner.normalWidth;
},
initCarousel: function () {
this.createCarousel();
this.fillCarousel();
if (this.options.carouselPreloader)
this.preloadThumbnails();
},
flushCarousel: function() {
this.thumbnailElements.each(function(myFx) {
myFx.element.remove();
myFx = myFx.element = null;
});
this.thumbnailElements = [];
},
toggleCarousel: function() {
if (this.carouselActive)
this.hideCarousel();
else
this.showCarousel();
},
showCarousel: function () {
this.fireEvent('onShowCarousel');
this.carouselContainer.start({
'opacity': this.options.carouselMaximizedOpacity,
'top': 0
}).chain(function() {
this.carouselActive = true;
this.carouselWrapper.scroller.start();
this.fireEvent('onCarouselShown');
this.carouselContainer.options.onComplete = null;
}.bind(this));
},
hideCarousel: function () {
this.fireEvent('onHideCarousel');
var targetTop = this.options.carouselMinimizedHeight - this.carouselContainer.normalHeight;
this.carouselContainer.start({
'opacity': this.options.carouselMinimizedOpacity,
'top': targetTop
}).chain(function() {
this.carouselActive = false;
this.carouselWrapper.scroller.stop();
this.fireEvent('onCarouselHidden');
this.carouselContainer.options.onComplete = null;
}.bind(this));
},
constructThumbnails: function () {
element = this.carouselInner;
for(i=0;i<this.galleryData.length;i++)
{
var currentImg = new Fx.Style(new Element ('div').addClass("thumbnail").setStyles({
backgroundImage: "url('" + this.galleryData[i].thumbnail + "')",
backgroundPosition: "center center",
backgroundRepeat: 'no-repeat',
marginLeft: this.options.thumbSpacing + "px",
width: this.options.thumbWidth + "px",
height: this.options.thumbHeight + "px"
}).injectInside(element), "opacity", {duration: 200}).set(this.options.thumbIdleOpacity);
currentImg.element.addEvents({
'mouseover': function (myself) {
myself.clearTimer();
myself.start(0.99);
if (this.options.showCarouselLabel)
$(this.carouselLabel).setHTML('<span class="number">' + (myself.relatedImage.number + 1) + "/" + this.maxIter + ":</span> " + myself.relatedImage.title);
}.pass(currentImg, this),
'mouseout': function (myself) {
myself.clearTimer();
myself.start(this.options.thumbIdleOpacity);
}.pass(currentImg, this),
'click': function (myself) {
this.goTo(myself.relatedImage.number);
if (this.options.thumbCloseCarousel)
this.hideCarousel();
}.pass(currentImg, this)
});
currentImg.relatedImage = this.galleryData[i];
this.thumbnailElements[parseInt(i)] = currentImg;
}
},
log: function(value) {
if(console.log)
console.log(value);
},
preloadThumbnails: function() {
var thumbnails = [];
for(i=0;i<this.galleryData.length;i++)
{
thumbnails[parseInt(i)] = this.galleryData[i].thumbnail;
}
this.thumbnailPreloader = new Preloader();
this.thumbnailPreloader.addEvent('onComplete', function() {
var textShowCarousel = formatString(this.options.textShowCarousel, this.currentIter+1, this.maxIter);
this.carouselBtn.setHTML(textShowCarousel).setProperty('title', textShowCarousel);
}.bind(this));
this.thumbnailPreloader.load(thumbnails);
},
clearThumbnailsHighlights: function()
{
for(i=0;i<this.galleryData.length;i++)
{
this.thumbnailElements[i].clearTimer();
this.thumbnailElements[i].start(0.2);
}
},
changeThumbnailsSize: function(width, height)
{
for(i=0;i<this.galleryData.length;i++)
{
this.thumbnailElements[i].clearTimer();
this.thumbnailElements[i].element.setStyles({
'width': width + "px",
'height': height + "px"
});
}
},
centerCarouselOn: function(num) {
if (!this.carouselWallMode)
{
var carouselElement = this.thumbnailElements[num];
var position = carouselElement.element.offsetLeft + (carouselElement.element.offsetWidth / 2);
var carouselWidth = this.carouselWrapper.element.offsetWidth;
var carouselInnerWidth = this.carouselInner.offsetWidth;
var diffWidth = carouselWidth / 2;
var scrollPos = position-diffWidth;
this.carouselWrapper.elementScroller.scrollTo = (scrollPos,0);
}
},
initInfoSlideshow: function() {
/*if (this.slideInfoZone.element)
this.slideInfoZone.element.remove();*/
this.slideInfoZone = new Fx.Styles(new Element('div').addClass('slideInfoZone').injectInside($(this.galleryElement))).set({'opacity':0});
var slideInfoZoneTitle = new Element('h2').injectInside(this.slideInfoZone.element);
var slideInfoZoneDescription = new Element('p').injectInside(this.slideInfoZone.element);
this.slideInfoZone.normalHeight = this.slideInfoZone.element.offsetHeight;
this.slideInfoZone.element.setStyle('opacity',0);
},
changeInfoSlideShow: function()
{
this.hideInfoSlideShow.delay(10, this);
this.showInfoSlideShow.delay(500, this);
},
showInfoSlideShow: function() {
this.fireEvent('onShowInfopane');
this.slideInfoZone.clearTimer();
element = this.slideInfoZone.element;
element.getElement('h2').setHTML(this.galleryData[this.currentIter].title);
element.getElement('p').setHTML(this.galleryData[this.currentIter].description);
if(this.options.slideInfoZoneSlide)
this.slideInfoZone.start({'opacity': [0, this.options.slideInfoZoneOpacity], 'height': [0, this.slideInfoZone.normalHeight]});
else
this.slideInfoZone.start({'opacity': [0, this.options.slideInfoZoneOpacity]});
if (this.options.showCarousel)
this.slideInfoZone.chain(this.centerCarouselOn.pass(this.currentIter, this));
return this.slideInfoZone;
},
hideInfoSlideShow: function() {
this.fireEvent('onHideInfopane');
this.slideInfoZone.clearTimer();
if(this.options.slideInfoZoneSlide)
this.slideInfoZone.start({'opacity': 0, 'height': 0});
else
this.slideInfoZone.start({'opacity': 0});
return this.slideInfoZone;
},
makeLink: function(num) {
this.currentLink.setProperties({
href: this.galleryData[num].link,
title: this.galleryData[num].linkTitle
})
if (!((this.options.embedLinks) && (!this.options.showArrows) && (!this.options.showCarousel)))
this.currentLink.setStyle('display', 'block');
},
clearLink: function() {
this.currentLink.setProperties({href: '', title: ''});
if (!((this.options.embedLinks) && (!this.options.showArrows) && (!this.options.showCarousel)))
this.currentLink.setStyle('display', 'none');
},
/* To change the gallery data, those two functions : */
flushGallery: function() {
this.galleryElements.each(function(myFx) {
myFx.element.remove();
myFx = myFx.element = null;
});
this.galleryElements = [];
},
changeData: function(data) {
this.galleryData = data;
this.clearTimer();
this.flushGallery();
if (this.options.showCarousel) this.flushCarousel();
this.constructElements();
if (this.options.showCarousel) this.fillCarousel();
if (this.options.showInfopane) this.hideInfoSlideShow();
this.galleryInit=1;
this.lastIter=0;
this.currentIter=0;
this.doSlideShow(1);
},
/* Plugins: HistoryManager */
initHistory: function() {
this.fireEvent('onHistoryInit');
this.historyKey = this.galleryElement.id + '-picture';
if (this.options.customHistoryKey)
this.historyKey = this.options.customHistoryKey();
this.history = HistoryManager.register(
this.historyKey,
[1],
function(values) {
if (parseInt(values[0])-1 < this.maxIter)
this.goTo(parseInt(values[0])-1);
}.bind(this),
function(values) {
return [this.historyKey, '(', values[0], ')'].join('');
}.bind(this),
this.historyKey + '\\((\\d+)\\)');
this.addEvent('onChanged', function(){
this.history.setValue(0, this.currentIter+1);
}.bind(this));
this.fireEvent('onHistoryInited');
}
};
gallery = new Class(gallery);
gallery.implement(new Events);
gallery.implement(new Options);
gallery.Transitions = new Abstract ({
fade: function(oldFx, newFx, oldPos, newPos){
oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
if (newPos > oldPos) newFx.start({opacity: 1});
else
{
newFx.set({opacity: 1});
oldFx.start({opacity: 0});
}
},
crossfade: function(oldFx, newFx, oldPos, newPos){
oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
newFx.start({opacity: 1});
oldFx.start({opacity: 0});
},
fadebg: function(oldFx, newFx, oldPos, newPos){
oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
oldFx.options.duration = newFx.options.duration = this.options.fadeDuration / 2;
oldFx.start({opacity: 0}).chain(newFx.start.pass([{opacity: 1}], newFx));
}
});
/* All code copyright 2007 Jonathan Schemoul */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Follows: Preloader (class)
* Simple class for preloading images with support for progress reporting
* Copyright 2007 Tomocchino.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var Preloader = new Class({
Implements: [Events, Options],
options: {
root : '',
period : 100
},
initialize: function(options){
this.setOptions(options);
},
load: function(sources) {
this.index = 0;
this.images = [];
this.sources = this.temps = sources;
this.total = this. sources.length;
this.fireEvent('onStart', [this.index, this.total]);
this.timer = this.progress.periodical(this.options.period, this);
this.sources.each(function(source, index){
this.images[index] = new Asset.image(this.options.root + source, {
'onload' : function(){ this.index++; if(this.images[index]) this.fireEvent('onLoad', [this.images[index], index, source]); }.bind(this),
'onerror' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this),
'onabort' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this)
});
}, this);
},
progress: function() {
this.fireEvent('onProgress', [Math.min(this.index, this.total), this.total]);
if(this.index >= this.total) this.complete();
},
complete: function(){
$clear(this.timer);
this.fireEvent('onComplete', [this.images]);
},
cancel: function(){
$clear(this.timer);
}
});
Preloader.implement(new Events, new Options);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Follows: formatString (function)
* Original name: Yahoo.Tools.printf
* Copyright Yahoo.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function formatString() {
var num = arguments.length;
var oStr = arguments[0];
for (var i = 1; i < num; i++) {
var pattern = "\\{" + (i-1) + "\\}";
var re = new RegExp(pattern, "g");
oStr = oStr.replace(re, arguments[i]);
}
return oStr;
} | JavaScript |
/*
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*
* Uses the built in easing capabilities added In jQuery 1.1
* to offer multiple easing options
*
* TERMS OF USE - jQuery Easing
*
* Open source under the BSD License.
*
* Copyright © 2008 George McGinley Smith
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('h.i[\'1a\']=h.i[\'z\'];h.O(h.i,{y:\'D\',z:9(x,t,b,c,d){6 h.i[h.i.y](x,t,b,c,d)},17:9(x,t,b,c,d){6 c*(t/=d)*t+b},D:9(x,t,b,c,d){6-c*(t/=d)*(t-2)+b},13:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t+b;6-c/2*((--t)*(t-2)-1)+b},X:9(x,t,b,c,d){6 c*(t/=d)*t*t+b},U:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t+1)+b},R:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t+b;6 c/2*((t-=2)*t*t+2)+b},N:9(x,t,b,c,d){6 c*(t/=d)*t*t*t+b},M:9(x,t,b,c,d){6-c*((t=t/d-1)*t*t*t-1)+b},L:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t+b;6-c/2*((t-=2)*t*t*t-2)+b},K:9(x,t,b,c,d){6 c*(t/=d)*t*t*t*t+b},J:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t*t*t+1)+b},I:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t*t+b;6 c/2*((t-=2)*t*t*t*t+2)+b},G:9(x,t,b,c,d){6-c*8.C(t/d*(8.g/2))+c+b},15:9(x,t,b,c,d){6 c*8.n(t/d*(8.g/2))+b},12:9(x,t,b,c,d){6-c/2*(8.C(8.g*t/d)-1)+b},Z:9(x,t,b,c,d){6(t==0)?b:c*8.j(2,10*(t/d-1))+b},Y:9(x,t,b,c,d){6(t==d)?b+c:c*(-8.j(2,-10*t/d)+1)+b},W:9(x,t,b,c,d){e(t==0)6 b;e(t==d)6 b+c;e((t/=d/2)<1)6 c/2*8.j(2,10*(t-1))+b;6 c/2*(-8.j(2,-10*--t)+2)+b},V:9(x,t,b,c,d){6-c*(8.o(1-(t/=d)*t)-1)+b},S:9(x,t,b,c,d){6 c*8.o(1-(t=t/d-1)*t)+b},Q:9(x,t,b,c,d){e((t/=d/2)<1)6-c/2*(8.o(1-t*t)-1)+b;6 c/2*(8.o(1-(t-=2)*t)+1)+b},P:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6-(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b},H:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6 a*8.j(2,-10*t)*8.n((t*d-s)*(2*8.g)/p)+c+b},T:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d/2)==2)6 b+c;e(!p)p=d*(.3*1.5);e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);e(t<1)6-.5*(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b;6 a*8.j(2,-10*(t-=1))*8.n((t*d-s)*(2*8.g)/p)*.5+c+b},F:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*(t/=d)*t*((s+1)*t-s)+b},E:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},16:9(x,t,b,c,d,s){e(s==u)s=1.l;e((t/=d/2)<1)6 c/2*(t*t*(((s*=(1.B))+1)*t-s))+b;6 c/2*((t-=2)*t*(((s*=(1.B))+1)*t+s)+2)+b},A:9(x,t,b,c,d){6 c-h.i.v(x,d-t,0,c,d)+b},v:9(x,t,b,c,d){e((t/=d)<(1/2.k)){6 c*(7.q*t*t)+b}m e(t<(2/2.k)){6 c*(7.q*(t-=(1.5/2.k))*t+.k)+b}m e(t<(2.5/2.k)){6 c*(7.q*(t-=(2.14/2.k))*t+.11)+b}m{6 c*(7.q*(t-=(2.18/2.k))*t+.19)+b}},1b:9(x,t,b,c,d){e(t<d/2)6 h.i.A(x,t*2,0,c,d)*.5+b;6 h.i.v(x,t*2-d,0,c,d)*.5+c*.5+b}});',62,74,'||||||return||Math|function|||||if|var|PI|jQuery|easing|pow|75|70158|else|sin|sqrt||5625|asin|||undefined|easeOutBounce|abs||def|swing|easeInBounce|525|cos|easeOutQuad|easeOutBack|easeInBack|easeInSine|easeOutElastic|easeInOutQuint|easeOutQuint|easeInQuint|easeInOutQuart|easeOutQuart|easeInQuart|extend|easeInElastic|easeInOutCirc|easeInOutCubic|easeOutCirc|easeInOutElastic|easeOutCubic|easeInCirc|easeInOutExpo|easeInCubic|easeOutExpo|easeInExpo||9375|easeInOutSine|easeInOutQuad|25|easeOutSine|easeInOutBack|easeInQuad|625|984375|jswing|easeInOutBounce'.split('|'),0,{}))
/*
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright © 2001 Robert Penner
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
| JavaScript |
//<![CDATA[
// SET THIS VARIABLE FOR DELAY, 1000 = 1 SECOND
var delayLength = 4000;
function doMove(panelWidth, tooFar) {
var leftValue = $("#mover").css("left");
// Fix for IE
if (leftValue == "auto") { leftValue = 0; };
var movement = parseFloat(leftValue, 10) - panelWidth;
if (movement == tooFar) {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": 0
}, function() {
$(".slide img").animate({
"top": 20
});
});
});
}
else {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": movement
}, function() {
$(".slide img").animate({
"top": 20
});
});
});
}
}
$(function(){
var $slide1 = $("#slide-1");
var panelWidth = $slide1.css("width");
var panelPaddingLeft = $slide1.css("paddingLeft");
var panelPaddingRight = $slide1.css("paddingRight");
panelWidth = parseFloat(panelWidth, 10);
panelPaddingLeft = parseFloat(panelPaddingLeft, 10);
panelPaddingRight = parseFloat(panelPaddingRight, 10);
panelWidth = panelWidth + panelPaddingLeft + panelPaddingRight;
var numPanels = $(".slide").length;
var tooFar = -(panelWidth * numPanels);
var totalMoverwidth = numPanels * panelWidth;
$("#mover").css("width", totalMoverwidth);
$("#slider").append('<a href="#" id="slider-stopper">Stop</a>');
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$("#slider-stopper").click(function(){
if ($(this).text() == "Stop") {
clearInterval(sliderIntervalID);
$(this).text("Start");
}
else {
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$(this).text("Stop");
}
});
});
//]]> | JavaScript |
//Step Carousel Viewer: By Dynamic Drive, at http://www.dynamicdrive.com
//** Created: March 19th, 08'
//** Aug 16th, 08'- Updated to v 1.4:
//1) Adds ability to set speed/duration of panel animation (in milliseconds)
//2) Adds persistence support, so the last viewed panel is recalled when viewer returns within same browser session
//3) Adds ability to specify whether panels should stop at the very last and first panel, or wrap around and start all over again
//4) Adds option to specify two navigational image links positioned to the left and right of the Carousel Viewer to move the panels back and forth
//** Aug 27th, 08'- Nav buttons (if enabled) also repositions themselves now if window is resized
//** Sept 23rd, 08'- Updated to v 1.6:
//1) Carousel now stops at the very last visible panel, instead of the last panel itself. In other words, no more white space at the end.
//2) Adds ability for Carousel to auto rotate dictated by the new parameter: autostep: {enable:true, moveby:1, pause:3000}
//2i) During Auto Rotate, Carousel pauses onMouseover, resumes onMouseout. Clicking Carousel halts auto rotate.
//** Oct 22nd, 08'- Updated to v 1.6.1, which fixes functions stepBy() and stepTo() not stopping auto stepping of Carousel when called.
var stepcarousel={
ajaxloadingmsg: '<div style="margin: 1em; font-weight: bold"><img src="ajaxloadr.gif" style="vertical-align: middle" /> Fetching Content. Please wait...</div>', //customize HTML to show while fetching Ajax content
defaultbuttonsfade: 0.4, //Fade degree for disabled nav buttons (0=completely transparent, 1=completely opaque)
configholder: {},
getCSSValue:function(val){ //Returns either 0 (if val contains 'auto') or val as an integer
return (val=="auto")? 0 : parseInt(val)
},
getremotepanels:function($, config){ //function to fetch external page containing the panel DIVs
config.$belt.html(this.ajaxloadingmsg)
$.ajax({
url: config.contenttype[1], //path to external content
async: true,
error:function(ajaxrequest){
config.$belt.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
},
success:function(content){
config.$belt.html(content)
config.$panels=config.$gallery.find('.'+config.panelclass)
stepcarousel.alignpanels($, config)
}
})
},
getoffset:function(what, offsettype){
return (what.offsetParent)? what[offsettype]+this.getoffset(what.offsetParent, offsettype) : what[offsettype]
},
getCookie:function(Name){
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
},
setCookie:function(name, value){
document.cookie = name+"="+value
},
fadebuttons:function(config, currentpanel){
config.$leftnavbutton.fadeTo('fast', currentpanel==0? this.defaultbuttonsfade : 1)
config.$rightnavbutton.fadeTo('fast', currentpanel==config.lastvisiblepanel? this.defaultbuttonsfade : 1)
},
addnavbuttons:function(config, currentpanel){
config.$leftnavbutton=$('<img src="'+config.defaultbuttons.leftnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Back '+config.defaultbuttons.moveby+' panels'}).appendTo('body')
config.$rightnavbutton=$('<img src="'+config.defaultbuttons.rightnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Forward '+config.defaultbuttons.moveby+' panels'}).appendTo('body')
config.$leftnavbutton.bind('click', function(){ //assign nav button event handlers
stepcarousel.stepBy(config.galleryid, -config.defaultbuttons.moveby)
})
config.$rightnavbutton.bind('click', function(){ //assign nav button event handlers
stepcarousel.stepBy(config.galleryid, config.defaultbuttons.moveby)
})
if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
this.fadebuttons(config, currentpanel)
}
return config.$leftnavbutton.add(config.$rightnavbutton)
},
stopautostep:function(config){
clearTimeout(config.steptimer)
clearTimeout(config.resumeautostep)
},
alignpanels:function($, config){
var paneloffset=0
config.paneloffsets=[paneloffset] //array to store upper left offset of each panel (1st element=0)
config.panelwidths=[] //array to store widths of each panel
config.$panels.each(function(index){ //loop through panels
var $currentpanel=$(this)
$currentpanel.css({float: 'none', position: 'absolute', left: paneloffset+'px'}) //position panel
$currentpanel.bind('click', function(e){return config.onpanelclick(e.target)}) //bind onpanelclick() to onclick event
paneloffset+=stepcarousel.getCSSValue($currentpanel.css('marginRight')) + parseInt($currentpanel.get(0).offsetWidth || $currentpanel.css('width')) //calculate next panel offset
config.paneloffsets.push(paneloffset) //remember this offset
config.panelwidths.push(paneloffset-config.paneloffsets[config.paneloffsets.length-2]) //remember panel width
})
config.paneloffsets.pop() //delete last offset (redundant)
var addpanelwidths=0
var lastpanelindex=config.$panels.length-1
config.lastvisiblepanel=lastpanelindex
for (var i=config.$panels.length-1; i>=0; i--){
addpanelwidths+=(i==lastpanelindex? config.panelwidths[lastpanelindex] : config.paneloffsets[i+1]-config.paneloffsets[i])
if (config.gallerywidth>addpanelwidths){
config.lastvisiblepanel=i //calculate index of panel that when in 1st position reveals the very last panel all at once based on gallery width
}
}
config.$belt.css({width: paneloffset+'px'}) //Set Belt DIV to total panels' widths
config.currentpanel=(config.panelbehavior.persist)? parseInt(this.getCookie(window[config.galleryid+"persist"])) : 0 //determine 1st panel to show by default
config.currentpanel=(typeof config.currentpanel=="number" && config.currentpanel<config.$panels.length)? config.currentpanel : 0
if (config.currentpanel!=0){
var endpoint=config.paneloffsets[config.currentpanel]+(config.currentpanel==0? 0 : config.beltoffset)
config.$belt.css({left: -endpoint+'px'})
}
if (config.defaultbuttons.enable==true){ //if enable default back/forth nav buttons
var $navbuttons=this.addnavbuttons(config, config.currentpanel)
$(window).bind("load resize", function(){ //refresh position of nav buttons when page loads/resizes, in case offsets weren't available document.oncontentload
config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
config.$leftnavbutton.css({left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px'})
config.$rightnavbutton.css({left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px'})
})
}
if (config.autostep && config.autostep.enable){ //enable auto stepping of Carousel?
var $carouselparts=config.$gallery.add(typeof $navbuttons!="undefined"? $navbuttons : null)
$carouselparts.bind('click', function(){
stepcarousel.stopautostep(config)
config.autostep.status="stopped"
})
$carouselparts.hover(function(){ //onMouseover
stepcarousel.stopautostep(config)
config.autostep.hoverstate="over"
}, function(){ //onMouseout
if (config.steptimer && config.autostep.hoverstate=="over" && config.autostep.status!="stopped"){
config.resumeautostep=setTimeout(function(){
stepcarousel.autorotate(config.galleryid)
config.autostep.hoverstate="out"
}, 500)
}
})
config.steptimer=setTimeout(function(){stepcarousel.autorotate(config.galleryid)}, config.autostep.pause) //automatically rotate Carousel Viewer
} //end enable auto stepping check
this.statusreport(config.galleryid)
config.oninit()
config.onslideaction(this)
},
stepTo:function(galleryid, pindex){ /*User entered pindex starts at 1 for intuitiveness. Internally pindex still starts at 0 */
var config=stepcarousel.configholder[galleryid]
if (typeof config=="undefined"){
alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
return
}
stepcarousel.stopautostep(config)
var pindex=Math.min(pindex-1, config.paneloffsets.length-1)
var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset)
if (config.panelbehavior.wraparound==false && config.defaultbuttons.enable==true){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
this.fadebuttons(config, pindex)
}
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
config.currentpanel=pindex
this.statusreport(galleryid)
this.setlinkclass(pindex)
},
stepBy:function(galleryid, steps){ //isauto if defined indicates stepBy() is being called automatically
var config=stepcarousel.configholder[galleryid]
if (typeof config=="undefined"){
alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
return
}
stepcarousel.stopautostep(config)
var direction=(steps>0)? 'forward' : 'back' //If "steps" is negative, that means backwards
var pindex=config.currentpanel+steps //index of panel to stop at
if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
pindex=(direction=="back" && pindex<=0)? 0 : (direction=="forward")? Math.min(pindex, config.lastvisiblepanel) : pindex
if (config.defaultbuttons.enable==true){ //if default nav buttons are enabled, fade them in and out depending on if at start or end of carousel
stepcarousel.fadebuttons(config, pindex)
}
}
else{ //else, for normal stepBy behavior
if (pindex>config.lastvisiblepanel && direction=="forward"){
//if destination pindex is greater than last visible panel, yet we're currently not at the end of the carousel yet
pindex=(config.currentpanel<config.lastvisiblepanel)? config.lastvisiblepanel : 0
}
else if (pindex<0 && direction=="back"){
//if destination pindex is less than 0, yet we're currently not at the beginning of the carousel yet
pindex=(config.currentpanel>0)? 0 : config.lastvisiblepanel /*wrap around left*/
}
}
var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset) //left distance for Belt DIV to travel to
if (pindex==0 && direction=='forward' || config.currentpanel==0 && direction=='back' && config.panelbehavior.wraparound==true){ //decide whether to apply "push pull" effect
config.$belt.animate({left: -config.paneloffsets[config.currentpanel]-(direction=='forward'? 100 : -30)+'px'}, 'normal', function(){
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
})
}
else
config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
config.currentpanel=pindex
this.statusreport(galleryid)
this.setlinkclass(pindex)
},
/* CALSS FOR NAVIGATION BAR */
setlinkclass:function(pindex){
$("#board_carusel_nav a").removeClass("selected");
$("#board_carusel_nav #board_carusel_nav_"+(pindex+1)+" a").addClass("selected");
},
autorotate:function(galleryid){
var config=stepcarousel.configholder[galleryid]
if (config.$gallery.attr('_ismouseover')!="yes"){
this.stepBy(galleryid, config.autostep.moveby)
}
config.steptimer=setTimeout(function(){stepcarousel.autorotate(galleryid)}, config.autostep.pause)
},
statusreport:function(galleryid){
var config=stepcarousel.configholder[galleryid]
var startpoint=config.currentpanel //index of first visible panel
var visiblewidth=0
for (var endpoint=startpoint; endpoint<config.paneloffsets.length; endpoint++){ //index (endpoint) of last visible panel
visiblewidth+=config.panelwidths[endpoint]
if (visiblewidth>config.gallerywidth){
break
}
}
startpoint+=1 //format startpoint for user friendiness
endpoint=(endpoint+1==startpoint)? startpoint : endpoint //If only one image visible on the screen and partially hidden, set endpoint to startpoint
var valuearray=[startpoint, endpoint, config.panelwidths.length]
for (var i=0; i<config.statusvars.length; i++){
window[config.statusvars[i]]=valuearray[i] //Define variable (with user specified name) and set to one of the status values
config.$statusobjs[i].text(valuearray[i]+" ") //Populate element on page with ID="user specified name" with one of the status values
}
},
setup:function(config){
//Disable Step Gallery scrollbars ASAP dynamically (enabled for sake of users with JS disabled)
document.write('<style type="text/css">\n#'+config.galleryid+'{overflow: hidden;}\n</style>')
jQuery(document).ready(function($){
config.$gallery=$('#'+config.galleryid)
config.gallerywidth=config.$gallery.width()
config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
config.$belt=config.$gallery.find('.'+config.beltclass) //Find Belt DIV that contains all the panels
config.$panels=config.$gallery.find('.'+config.panelclass) //Find Panel DIVs that each contain a slide
config.panelbehavior.wraparound=(config.autostep && config.autostep.enable)? true : config.panelbehavior.wraparound //if auto step enabled, set "wraparound" to true
config.onpanelclick=(typeof config.onpanelclick=="undefined")? function(target){} : config.onpanelclick //attach custom "onpanelclick" event handler
config.onslideaction=(typeof config.onslide=="undefined")? function(){} : function(beltobj){$(beltobj).stop(); config.onslide()} //attach custom "onslide" event handler
config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
config.beltoffset=stepcarousel.getCSSValue(config.$belt.css('marginLeft')) //Find length of Belt DIV's left margin
config.statusvars=config.statusvars || [] //get variable names that will hold "start", "end", and "total" slides info
config.$statusobjs=[$('#'+config.statusvars[0]), $('#'+config.statusvars[1]), $('#'+config.statusvars[2])]
config.currentpanel=0
stepcarousel.configholder[config.galleryid]=config //store config parameter as a variable
if (config.contenttype[0]=="ajax" && typeof config.contenttype[1]!="undefined") //fetch ajax content?
stepcarousel.getremotepanels($, config)
else
stepcarousel.alignpanels($, config) //align panels and initialize gallery
}) //end document.ready
jQuery(window).bind('unload', function(){ //clean up
if (config.panelbehavior.persist){
stepcarousel.setCookie(window[config.galleryid+"persist"], config.currentpanel)
}
jQuery.each(config, function(ai, oi){
oi=null
})
config=null
})
}
}
| JavaScript |
/* Copyright (c) 2008 Kean Loong Tan http://www.gimiti.com/kltan
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* jFlow
* Version: 1.2 (July 7, 2008)
* Requires: jQuery 1.2+
*/
(function($) {
$.fn.jFlow = function(options) {
var opts = $.extend({}, $.fn.jFlow.defaults, options);
var randNum = Math.floor(Math.random()*11);
var jFC = opts.controller;
var jFS = opts.slideWrapper;
var jSel = opts.selectedWrapper;
var cur = 0;
var timer;
var maxi = $(jFC).length;
// sliding function
var slide = function (dur, i) {
$(opts.slides).children().css({
overflow:"hidden"
});
$(opts.slides + " iframe").hide().addClass("temp_hide");
$(opts.slides).animate({
marginLeft: "-" + (i * $(opts.slides).find(":first-child").width() + "px")
},
opts.duration*(dur),
opts.easing,
function(){
$(opts.slides).children().css({
overflow:"hidden"
});
$(".temp_hide").show();
}
);
}
$(this).find(jFC).each(function(i){
$(this).click(function(){
dotimer();
if ($(opts.slides).is(":not(:animated)")) {
$(jFC).removeClass(jSel);
$(this).addClass(jSel);
var dur = Math.abs(cur-i);
slide(dur,i);
cur = i;
}
});
});
$(opts.slides).before('<div id="'+jFS.substring(1, jFS.length)+'"></div>').appendTo(jFS);
$(opts.slides).find("div").each(function(){
$(this).before('<div class="jFlowSlideContainer"></div>').appendTo($(this).prev());
});
//initialize the controller
$(jFC).eq(cur).addClass(jSel);
var resize = function (x){
$(jFS).css({
position:"relative",
width: opts.width,
height: opts.height,
overflow: "hidden"
});
//opts.slides or #mySlides container
$(opts.slides).css({
position:"relative",
width: $(jFS).width()*$(jFC).length+"px",
height: $(jFS).height()+"px",
overflow: "hidden"
});
// jFlowSlideContainer
$(opts.slides).children().css({
position:"relative",
width: $(jFS).width()+"px",
height: $(jFS).height()+"px",
"float":"left",
overflow:"hidden"
});
$(opts.slides).css({
marginLeft: "-" + (cur * $(opts.slides).find(":eq(0)").width() + "px")
});
}
// sets initial size
resize();
// resets size
$(window).resize(function(){
resize();
});
$(opts.prev).click(function(){
dotimer();
doprev();
});
$(opts.next).click(function(){
dotimer();
donext();
});
var doprev = function (x){
if ($(opts.slides).is(":not(:animated)")) {
var dur = 1;
if (cur > 0)
cur--;
else {
cur = maxi -1;
dur = cur;
}
$(jFC).removeClass(jSel);
slide(dur,cur);
$(jFC).eq(cur).addClass(jSel);
}
}
var donext = function (x){
if ($(opts.slides).is(":not(:animated)")) {
var dur = 1;
if (cur < maxi - 1)
cur++;
else {
cur = 0;
dur = maxi -1;
}
$(jFC).removeClass(jSel);
//$(jFS).fadeOut("fast");
slide(dur, cur);
//$(jFS).fadeIn("fast");
$(jFC).eq(cur).addClass(jSel);
}
}
var dotimer = function (x){
if((opts.auto) == true) {
if(timer != null)
clearInterval(timer);
timer = setInterval(function() {
$(opts.next).click();
}, 10000);
}
}
dotimer();
};
$.fn.jFlow.defaults = {
controller: ".jFlowControl", // must be class, use . sign
slideWrapper : "#jFlowSlide", // must be id, use # sign
selectedWrapper: "jFlowSelected", // just pure text, no sign
auto: false,
easing: "swing",
duration: 400,
width: "100%",
prev: ".jFlowPrev", // must be class, use . sign
next: ".jFlowNext" // must be class, use . sign
};
})(jQuery);
| JavaScript |
//<![CDATA[
/*
* 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 |
window.onerror=function(desc,page,line,chr){
/* alert('JavaScript error occurred! \n'
+'\nError description: \t'+desc
+'\nPage address: \t'+page
+'\nLine number: \t'+line
);*/
}
$(function(){
$('a').focus(function(){this.blur();});
SI.Files.stylizeAll();
slider.init();
$('input.text-default').each(function(){
$(this).attr('default',$(this).val());
}).focus(function(){
if($(this).val()==$(this).attr('default'))
$(this).val('');
}).blur(function(){
if($(this).val()=='')
$(this).val($(this).attr('default'));
});
$('input.text,textarea.text').focus(function(){
$(this).addClass('textfocus');
}).blur(function(){
$(this).removeClass('textfocus');
});
var popopenobj=0,popopenaobj=null;
$('a.popup').click(function(){
var pid=$(this).attr('rel').split('|')[0],_os=parseInt($(this).attr('rel').split('|')[1]);
var pobj=$('#'+pid);
if(!pobj.length)
return false;
if(typeof popopenobj=='object' && popopenobj.attr('id')!=pid){
popopenobj.hide(50);
$(popopenaobj).parent().removeClass(popopenobj.attr('id').split('-')[1]+'-open');
popopenobj=null;
}
return false;
});
$('p.images img').click(function(){
var newbg=$(this).attr('src').split('bg/bg')[1].split('-thumb')[0];
$(document.body).css('backgroundImage','url('+_siteRoot+'images/bg/bg'+newbg+'.jpg)');
$(this).parent().find('img').removeClass('on');
$(this).addClass('on');
return false;
});
$(window).load(function(){
$.each(css_ims,function(){(new Image()).src=_siteRoot+'css/images/'+this;});
$.each(css_cims,function(){
var css_im=this;
$.each(['blue','purple','pink','red','grey','green','yellow','orange'],function(){
(new Image()).src=_siteRoot+'css/'+this+'/'+css_im;
});
});
});
$('div.sc-large div.img:has(div.tml)').each(function(){
$('div.tml',this).hide();
$(this).append('<a href="#" class="tml_open"> </a>').find('a').css({
left:parseInt($(this).offset().left)+864,top:parseInt($(this).offset().top)+1
}).click(function(){
$(this).siblings('div.tml').slideToggle();
return false;
}).focus(function(){this.blur();});
});
});
var slider={
num:-1,
cur:0,
cr:[],
al:null,
at:10*1000,
ar:true,
init:function(){
if(!slider.data || !slider.data.length)
return false;
var d=slider.data;
slider.num=d.length;
var pos=Math.floor(Math.random()*1);//slider.num);
for(var i=0;i<slider.num;i++){
$('#'+d[i].id).css({left:((i-pos)*1000)});
$('#slide-nav').append('<a id="slide-link-'+i+'" href="#" onclick="slider.slide('+i+');return false;" onfocus="this.blur();">'+(i+1)+'</a>');
}
$('img,div#slide-controls',$('div#slide-holder')).fadeIn();
slider.text(d[pos]);
slider.on(pos);
slider.cur=pos;
window.setTimeout('slider.auto();',slider.at);
},
auto:function(){
if(!slider.ar)
return false;
var next=slider.cur+1;
if(next>=slider.num) next=0;
slider.slide(next);
},
slide:function(pos){
if(pos<0 || pos>=slider.num || pos==slider.cur)
return;
window.clearTimeout(slider.al);
slider.al=window.setTimeout('slider.auto();',slider.at);
var d=slider.data;
for(var i=0;i<slider.num;i++)
$('#'+d[i].id).stop().animate({left:((i-pos)*1000)},1000,'swing');
slider.on(pos);
slider.text(d[pos]);
slider.cur=pos;
},
on:function(pos){
$('#slide-nav a').removeClass('on');
$('#slide-nav a#slide-link-'+pos).addClass('on');
},
text:function(di){
slider.cr['a']=di.client;
slider.cr['b']=di.desc;
slider.ticker('#slide-client span',di.client,0,'a');
slider.ticker('#slide-desc',di.desc,0,'b');
},
ticker:function(el,text,pos,unique){
if(slider.cr[unique]!=text)
return false;
ctext=text.substring(0,pos)+(pos%2?'-':'_');
$(el).html(ctext);
if(pos==text.length)
$(el).html(text);
else
window.setTimeout('slider.ticker("'+el+'","'+text+'",'+(pos+1)+',"'+unique+'");',30);
}
};
// STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
if(!window.SI){var SI={};};
SI.Files={
htmlClass:'SI-FILES-STYLIZED',
fileClass:'file',
wrapClass:'cabinet',
fini:false,
able:false,
init:function(){
this.fini=true;
},
stylize:function(elem){
if(!this.fini){this.init();};
if(!this.able){return;};
elem.parentNode.file=elem;
elem.parentNode.onmousemove=function(e){
if(typeof e=='undefined') e=window.event;
if(typeof e.pageY=='undefined' && typeof e.clientX=='number' && document.documentElement){
e.pageX=e.clientX+document.documentElement.scrollLeft;
e.pageY=e.clientY+document.documentElement.scrollTop;
};
var ox=oy=0;
var elem=this;
if(elem.offsetParent){
ox=elem.offsetLeft;
oy=elem.offsetTop;
while(elem=elem.offsetParent){
ox+=elem.offsetLeft;
oy+=elem.offsetTop;
};
};
};
},
stylizeAll:function(){
if(!this.fini){this.init();};
if(!this.able){return;};
}
}; | JavaScript |
/*
* Inline Form Validation Engine 2.2.4, 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($) {
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 ) {
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) {
var form = this;
var options;
if(userOptions)
options = methods._saveOptions(form, userOptions);
else
options = form.data('jqv');
var validateAttribute = (form.find("[data-validation-engine*=validate]")) ? "data-validation-engine" : "class";
if (!options.binded) {
if (options.bindMethod == "bind"){
// bind fields
form.find("[class*=validate]").not("[type=checkbox]").not("[type=radio]").not(".datepicker").bind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox],[class*=validate][type=radio]").bind("click", methods._onFieldEvent);
form.find("[class*=validate][class*=datepicker]").bind(options.validationEventTrigger,{"delay": 300}, methods._onFieldEvent);
// bind form.submit
form.bind("submit", methods._onSubmitEvent);
} else if (options.bindMethod == "live") {
// bind fields with LIVE (for persistant state)
form.find("[class*=validate]").not("[type=checkbox]").not(".datepicker").live(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").live("click", methods._onFieldEvent);
form.find("[class*=validate][class*=datepicker]").live(options.validationEventTrigger,{"delay": 300}, methods._onFieldEvent);
// bind form.submit
form.live("submit", methods._onSubmitEvent);
}
options.binded = true;
if (options.autoPositionUpdate) {
$(window).bind("resize", {
"noAnimation": true,
"formElem": form
}, methods.updatePromptsPosition);
}
}
return this;
},
/**
* Unregisters any bindings that may point to jQuery.validaitonEngine
*/
detach: function() {
var form = this;
var options = form.data('jqv');
if (options.binded) {
// unbind fields
form.find("[class*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=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("[class*=validate]").not("[type=checkbox]").die(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=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 the form 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() {
return methods._validateFields(this);
},
/**
* Validates one field, shows prompt 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
*/
validateField: function(el) {
var options = $(this).data('jqv');
var r = methods._validateField($(el), options);
if (options.onSuccess && options.InvalidFields.length == 0)
options.onSuccess();
else if (options.onFailure && options.InvalidFields.length > 0)
options.onFailure();
return r;
},
/**
* Validates the form fields, shows prompts accordingly.
* Note: this methods performs fields and form ajax validations(if setup)
*
* @return true if the form validates, false if it fails, undefined if ajax is used for form validation
*/
validateform: function() {
return methods._onSubmitEvent.call(this);
},
/**
* Redraw prompts position, useful when you change the DOM state when validating
*/
updatePromptsPosition: function(event) {
if (event && this == window)
var form = event.data.formElem, noAnimation = event.data.noAnimation;
else
var form = $(this.closest('form'));
var options = form.data('jqv');
// No option, take default one
form.find('[class*=validate]').not(':hidden').not(":disabled").each(function(){
var field = $(this);
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 all error prompts on the page
*/
hidePrompt: function() {
var promptClass = "."+ methods._getClassName($(this).attr("id")) + "formError";
$(promptClass).fadeTo("fast", 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Closes form error prompts, CAN be invidual
*/
hide: function() {
var closingtag;
if($(this).is("form")){
closingtag = "parentForm"+methods._getClassName($(this).attr("id"));
}else{
closingtag = methods._getClassName($(this).attr("id")) +"formError";
}
$('.'+closingtag).fadeTo("fast", 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Closes all error prompts on the page
*/
hideAll: function() {
$('.formError').fadeTo("fast", 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');
// validate the current field
window.setTimeout(function() {
methods._validateField(field, options);
if (options.InvalidFields.length == 0 && options.onSuccess) {
options.onSuccess();
} else if (options.InvalidFields.length > 0 && options.onFailure) {
options.onFailure();
}
}, (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');
// validate each field (- skip field ajax validation, no necessary since we will perform an ajax form validation)
var r=methods._validateFields(form, true);
if (r && options.ajaxFormValidation) {
methods._validateFormWithAjax(form, options);
return false;
}
if(options.onValidationComplete) {
options.onValidationComplete(form, r);
return false;
}
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;
},
/**
* 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, skipAjaxValidation) {
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('[class*=validate]').not(':hidden').not(":disabled").each( function() {
var field = $(this);
errorFound |= methods._validateField(field, options, skipAjaxValidation);
field.focus();
if (options.doNotShowAllErrosOnSubmit)
return false;
if (errorFound && first_err==null) first_err=field;
});
// second, check to see if all ajax calls completed ok
// errorFound |= !methods._checkAjaxStatus(options);
// thrird, 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') {
if (positionType.indexOf(":")!=-1) {
positionType=positionType.substring(0,positionType.indexOf(":"));
}
}
if (positionType!="bottomRight"&&
positionType!="bottomLeft") {
var prompt_err= methods._getPrompt(first_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);
}else{
$("html:not(:animated),body:not(:animated)").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 url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action");
$.ajax({
type: "GET",
url: url,
cache: false,
dataType: "json",
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 (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, "", options);
}
});
},
/**
* Validates field, shows prompts accordingly
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @param {Map}
* user options
* @return true if field is valid
*/
_validateField: function(field, options, skipAjaxValidation) {
if (!field.attr("id"))
$.error("jQueryValidate: an ID attribute is required for this field: " + field.attr("name") + " class:" +
field.attr("class"));
var rulesParsing = field.attr('class');
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 required = false;
options.isError = false;
options.showArrow = true;
var form = $(field.closest("form"));
for (var i = 0; i < rules.length; i++) {
// Fix for adding spaces in the rules
rules[i] = rules[i].replace(" ", "")
var errorMsg = undefined;
switch (rules[i]) {
case "required":
required = true;
errorMsg = methods._required(field, rules, i, options);
break;
case "custom":
errorMsg = methods._customRegex(field, rules, i, options);
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 = "[class*=" +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._groupRequired(field, rules, i, options);
if(errorMsg) required = true;
options.showArrow = false;
break;
case "ajax":
// ajax has its own prompts handling technique
if(!skipAjaxValidation){
methods._ajax(field, rules, i, options);
isAjaxValidator = true;
}
break;
case "minSize":
errorMsg = methods._minSize(field, rules, i, options);
break;
case "maxSize":
errorMsg = methods._maxSize(field, rules, i, options);
break;
case "min":
errorMsg = methods._min(field, rules, i, options);
break;
case "max":
errorMsg = methods._max(field, rules, i, options);
break;
case "past":
errorMsg = methods._past(field, rules, i, options);
break;
case "future":
errorMsg = methods._future(field, rules, i, options);
break;
case "dateRange":
var classGroup = "[class*=" + rules[i + 1] + "]";
var firstOfGroup = form.find(classGroup).eq(0);
var secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (firstOfGroup[0].value || secondOfGroup[0].value) {
errorMsg = methods._dateRange(firstOfGroup, secondOfGroup, rules, i, options);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "dateTimeRange":
var classGroup = "[class*=" + rules[i + 1] + "]";
var firstOfGroup = form.find(classGroup).eq(0);
var secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (firstOfGroup[0].value || secondOfGroup[0].value) {
errorMsg = methods._dateTimeRange(firstOfGroup, secondOfGroup, rules, i, options);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "maxCheckbox":
errorMsg = methods._maxCheckbox(form, field, rules, i, options);
field = $(form.find("input[name='" + fieldName + "']"));
break;
case "minCheckbox":
errorMsg = methods._minCheckbox(form, field, rules, i, options);
field = $(form.find("input[name='" + fieldName + "']"));
break;
case "equals":
errorMsg = methods._equals(field, rules, i, options);
break;
case "funcCall":
errorMsg = methods._funcCall(field, rules, i, options);
break;
default:
//$.error("jQueryValidator rule not found"+rules[i]);
}
if (errorMsg !== undefined) {
promptText += errorMsg + "<br/>";
options.isError = true;
}
}
// If the rules required is not added, an empty field is not validated
if(!required && field.val() == "") 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 (fieldType == "text" && form.find("input[name='" + fieldName + "']").size() > 1) {
field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first"));
options.showArrow = false;
}
if (options.isError){
methods._showPrompt(field, promptText, "", 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);
}
return options.isError;
},
/**
* 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":
default:
if (!field.val())
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 + "']").size() == 1)
return options.allrules[rules[i]].alertTextCheckboxe;
else
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
// required for <select>
case "select-one":
// added by paul@kinetek.net for select boxes, Thank you
if (!field.val())
return options.allrules[rules[i]].alertText;
break;
case "select-multiple":
// added by paul@kinetek.net for select boxes, Thank you
if (!field.find("option:selected").val())
return options.allrules[rules[i]].alertText;
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 = "[class*=" +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 Regex rules
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_customRegex: function(field, rules, i, options) {
var customRule = rules[i + 1];
var rule = options.allrules[customRule];
if(!rule) {
alert("jqv:custom rule not found "+customRule);
return;
}
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;
},
/**
* 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 = 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(field, rules, i, options) {
var p=rules[i + 1];
var pdate = (p.toLowerCase() == "now")? new Date():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(field, rules, i, options) {
var p=rules[i + 1];
var pdate = (p.toLowerCase() == "now")? new Date():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]))$/);
if (dateRegEx.test(value)) {
return true;
}
return false;
},
/**
* 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})$/);
if (dateTimeRegEx.test(value)) {
return true;
}
return false;
},
//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 (first, second, rules, i, options) {
//are not both populated
if ((!first[0].value && second[0].value) || (first[0].value && !second[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDate(first[0].value) || !methods._isDate(second[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(first[0].value, second[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 (first, second, rules, i, options) {
//are not both populated
if ((!first[0].value && second[0].value) || (first[0].value && !second[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDateTime(first[0].value) || !methods._isDateTime(second[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(first[0].value, second[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;
}
},
/**
* 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;
if (!extraData)
extraData = "";
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);
tmpData.push(keyValue);
}
}
extraDataDynamic = tmpData.join("&");
} else {
extraDataDynamic = "";
}
if (!options.isError) {
$.ajax({
type: "GET",
url: rule.url,
cache: false,
dataType: "json",
data: "fieldId=" + field.attr("id") + "&fieldValue=" + field.val() + "&extraData=" + extraData + "&" + extraDataDynamic,
field: field,
rule: rule,
methods: methods,
options: options,
beforeSend: function() {
// build the loading prompt
var loadingText = rule.alertTextLoad;
if (loadingText)
methods._showPrompt(field, loadingText, "load", true, options);
},
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]);
// 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 {
if (options.ajaxValidCache[errorFieldId] !== undefined)
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);
}
}
errorField.trigger("jqv.field.result", [errorField, !options.isError, msg]);
}
});
}
},
/**
* 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
if(field.is(":input")) 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 */
options.InvalidCount++;
}
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') {
if (positionType.indexOf(":")!=-1) {
positionType=positionType.substring(0,positionType.indexOf(":"));
};
};
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;
}
}
if (options.relative) {
// empty relative span does not disturb page layout
// prompt positioned absolute to relative span
// vertical-align:top so position calculations are the same as isOverflown
var outer = $('<span>').css('position','relative').css('vertical-align','top').addClass('formErrorOuter').append(prompt.css('position','absolute'));
field.before(outer);
} else if (options.isOverflown) {
//Cedric: Needed if a container is in position:relative
// insert prompt in the form or in the overflown container?
field.before(prompt);
} else {
$("body").append(prompt);
}
var pos = methods._calculatePosition(field, prompt, options);
prompt.css({
"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize,
"opacity": 0
}).data("callerField", field);
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);
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 className = methods._getClassName(field.attr("id")) + "formError";
var match = $("." + methods._escapeExpression(className))[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 promptHeight = promptElmt.height();
var overflow = options.isOverflown || options.relative;
if (overflow) {
// is the form contained in an overflown container?
promptTopPosition = promptleftPosition = 0;
// compensation for the arrow
marginTopSize = -promptHeight;
} else {
var offset = field.offset();
promptTopPosition = offset.top;
promptleftPosition = offset.left;
marginTopSize = 0;
}
//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;};
};
};
if(!methods.isRTL(field))
{
switch (positionType) {
default:
case "topRight":
if (overflow)
// Is the form contained in an overflown container?
promptleftPosition += fieldWidth - 30;
else {
promptleftPosition += fieldWidth - 30;
promptTopPosition += -promptHeight -2;
}
break;
case "topLeft":
promptTopPosition += -promptHeight - 10;
break;
case "centerRight":
if (overflow) {
promptTopPosition=field.outerHeight();
promptleftPosition=field.outerWidth(1)+5;
} else {
promptleftPosition+=field.outerWidth()+5;
}
break;
case "centerLeft":
promptleftPosition -= promptElmt.width() + 2;
break;
case "bottomLeft":
promptTopPosition = promptTopPosition + field.height() + 15;
break;
case "bottomRight":
promptleftPosition += fieldWidth - 30;
promptTopPosition += field.height() + 5;
}
}
else
{
switch (positionType) {
default:
case "topLeft":
if (overflow)
// Is the form contained in an overflown container?
promptleftPosition -= promptElmt.width() - 30;
else {
promptleftPosition -= promptElmt.width() - 30;
promptTopPosition += -promptHeight -2;
}
break;
case "topRight":
if (overflow)
// Is the form contained in an overflown container?
promptleftPosition += fieldWidth - promptElmt.width();
else {
promptleftPosition += fieldWidth - promptElmt.width();
promptTopPosition += -promptHeight -2;
}
break;
case "centerRight":
if (overflow) {
promptTopPosition=field.outerHeight();
promptleftPosition=field.outerWidth(1)+5;
} else {
promptleftPosition+=field.outerWidth()+5;
}
break;
case "centerLeft":
promptleftPosition -= promptElmt.width() + 2;
break;
case "bottomLeft":
promptleftPosition += -promptElmt.width() + 30;
promptTopPosition = promptTopPosition + field.height() + 15;
break;
case "bottomRight":
promptleftPosition += fieldWidth - promptElmt.width();
promptTopPosition += field.height() + 15;
}
}
//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);
// Needed to be retro compatible
if (userOptions.isOverflown) userOptions.relative = true;
if (userOptions.relative) userOptions.isOverflown = true;
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, "_");
}
}
};
/**
* 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 false; // 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 != "hidePrompt" && 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= {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,
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
ajaxFormValidationURL: false,
// The url to send the submit ajax validation (default to action)
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,
// better relative positioning
relative: false,
// Used when the form is displayed within a scrolling DIV
isOverflown: false,
overflownDIV: "",
// Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages
doNotShowAllErrosOnSubmit: false,
// true when form and fields are binded
binded: false,
// 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,
// 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: [],
onSuccess: false,
onFailure: false
}};
$(function(){$.validationEngine.defaults.promptPosition = methods.isRTL()?'topLeft':"topRight"});
})(jQuery);
| JavaScript |
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(jQuery) | JavaScript |
$(document).ready(function() {
$("#w2bForm").validationEngine('attach');
$("span.colorbox").each(function(){
$(this).css({backgroundColor:"#" + $(this).siblings("input.inputcolor").val()});
});
$(".inputcolor").ColorPicker({
onShow: function (colpkr) {
$(colpkr).fadeIn(200);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(200);
return false;
},
onSubmit: function(hsb, hex, rgb, el) {
$(el).val(hex);
$(el).next("span.colorbox").css("backgroundColor", "#" + hex);
$(el).ColorPickerHide();
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
}).bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
$(this).next("span.colorbox").css("backgroundColor", "#" + $(this).val());
});
$("span.colorbox").ColorPicker({
onBeforeShow: function () {
$(this).ColorPickerSetColor($(this).siblings("input.inputcolor").val());
},
onShow: function (colpkr) {
$(colpkr).fadeIn(200);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(200);
return false;
},
onSubmit: function(hsb, hex, rgb, el) {
$(el).css({'backgroundColor': '#' + hex});
$(el).siblings("input.inputcolor").val(hex);
$(el).ColorPickerHide();
}
});
}); | JavaScript |
/*
* Inline Form Validation Engine 2.2.4, 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($) {
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 ) {
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) {
var form = this;
var options;
if(userOptions)
options = methods._saveOptions(form, userOptions);
else
options = form.data('jqv');
var validateAttribute = (form.find("[data-validation-engine*=validate]")) ? "data-validation-engine" : "class";
if (!options.binded) {
if (options.bindMethod == "bind"){
// bind fields
form.find("[class*=validate]").not("[type=checkbox]").not("[type=radio]").not(".datepicker").bind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox],[class*=validate][type=radio]").bind("click", methods._onFieldEvent);
form.find("[class*=validate][class*=datepicker]").bind(options.validationEventTrigger,{"delay": 300}, methods._onFieldEvent);
// bind form.submit
form.bind("submit", methods._onSubmitEvent);
} else if (options.bindMethod == "live") {
// bind fields with LIVE (for persistant state)
form.find("[class*=validate]").not("[type=checkbox]").not(".datepicker").live(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").live("click", methods._onFieldEvent);
form.find("[class*=validate][class*=datepicker]").live(options.validationEventTrigger,{"delay": 300}, methods._onFieldEvent);
// bind form.submit
form.live("submit", methods._onSubmitEvent);
}
options.binded = true;
if (options.autoPositionUpdate) {
$(window).bind("resize", {
"noAnimation": true,
"formElem": form
}, methods.updatePromptsPosition);
}
}
return this;
},
/**
* Unregisters any bindings that may point to jQuery.validaitonEngine
*/
detach: function() {
var form = this;
var options = form.data('jqv');
if (options.binded) {
// unbind fields
form.find("[class*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=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("[class*=validate]").not("[type=checkbox]").die(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=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 the form 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() {
return methods._validateFields(this);
},
/**
* Validates one field, shows prompt 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
*/
validateField: function(el) {
var options = $(this).data('jqv');
var r = methods._validateField($(el), options);
if (options.onSuccess && options.InvalidFields.length == 0)
options.onSuccess();
else if (options.onFailure && options.InvalidFields.length > 0)
options.onFailure();
return r;
},
/**
* Validates the form fields, shows prompts accordingly.
* Note: this methods performs fields and form ajax validations(if setup)
*
* @return true if the form validates, false if it fails, undefined if ajax is used for form validation
*/
validateform: function() {
return methods._onSubmitEvent.call(this);
},
/**
* Redraw prompts position, useful when you change the DOM state when validating
*/
updatePromptsPosition: function(event) {
if (event && this == window)
var form = event.data.formElem, noAnimation = event.data.noAnimation;
else
var form = $(this.closest('form'));
var options = form.data('jqv');
// No option, take default one
form.find('[class*=validate]').not(':hidden').not(":disabled").each(function(){
var field = $(this);
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 all error prompts on the page
*/
hidePrompt: function() {
var promptClass = "."+ methods._getClassName($(this).attr("id")) + "formError";
$(promptClass).fadeTo("fast", 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Closes form error prompts, CAN be invidual
*/
hide: function() {
var closingtag;
if($(this).is("form")){
closingtag = "parentForm"+methods._getClassName($(this).attr("id"));
}else{
closingtag = methods._getClassName($(this).attr("id")) +"formError";
}
$('.'+closingtag).fadeTo("fast", 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Closes all error prompts on the page
*/
hideAll: function() {
$('.formError').fadeTo("fast", 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');
// validate the current field
window.setTimeout(function() {
methods._validateField(field, options);
if (options.InvalidFields.length == 0 && options.onSuccess) {
options.onSuccess();
} else if (options.InvalidFields.length > 0 && options.onFailure) {
options.onFailure();
}
}, (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');
// validate each field (- skip field ajax validation, no necessary since we will perform an ajax form validation)
var r=methods._validateFields(form, true);
if (r && options.ajaxFormValidation) {
methods._validateFormWithAjax(form, options);
return false;
}
if(options.onValidationComplete) {
options.onValidationComplete(form, r);
return false;
}
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;
},
/**
* 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, skipAjaxValidation) {
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('[class*=validate]').not(':hidden').not(":disabled").each( function() {
var field = $(this);
errorFound |= methods._validateField(field, options, skipAjaxValidation);
field.focus();
if (options.doNotShowAllErrosOnSubmit)
return false;
if (errorFound && first_err==null) first_err=field;
});
// second, check to see if all ajax calls completed ok
// errorFound |= !methods._checkAjaxStatus(options);
// thrird, 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') {
if (positionType.indexOf(":")!=-1) {
positionType=positionType.substring(0,positionType.indexOf(":"));
}
}
if (positionType!="bottomRight"&&
positionType!="bottomLeft") {
var prompt_err= methods._getPrompt(first_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);
}else{
$("html:not(:animated),body:not(:animated)").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 url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action");
$.ajax({
type: "GET",
url: url,
cache: false,
dataType: "json",
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 (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, "", options);
}
});
},
/**
* Validates field, shows prompts accordingly
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @param {Map}
* user options
* @return true if field is valid
*/
_validateField: function(field, options, skipAjaxValidation) {
if (!field.attr("id"))
$.error("jQueryValidate: an ID attribute is required for this field: " + field.attr("name") + " class:" +
field.attr("class"));
var rulesParsing = field.attr('class');
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 required = false;
options.isError = false;
options.showArrow = true;
var form = $(field.closest("form"));
for (var i = 0; i < rules.length; i++) {
// Fix for adding spaces in the rules
rules[i] = rules[i].replace(" ", "")
var errorMsg = undefined;
switch (rules[i]) {
case "required":
required = true;
errorMsg = methods._required(field, rules, i, options);
break;
case "custom":
errorMsg = methods._customRegex(field, rules, i, options);
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 = "[class*=" +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._groupRequired(field, rules, i, options);
if(errorMsg) required = true;
options.showArrow = false;
break;
case "ajax":
// ajax has its own prompts handling technique
if(!skipAjaxValidation){
methods._ajax(field, rules, i, options);
isAjaxValidator = true;
}
break;
case "minSize":
errorMsg = methods._minSize(field, rules, i, options);
break;
case "maxSize":
errorMsg = methods._maxSize(field, rules, i, options);
break;
case "min":
errorMsg = methods._min(field, rules, i, options);
break;
case "max":
errorMsg = methods._max(field, rules, i, options);
break;
case "past":
errorMsg = methods._past(field, rules, i, options);
break;
case "future":
errorMsg = methods._future(field, rules, i, options);
break;
case "dateRange":
var classGroup = "[class*=" + rules[i + 1] + "]";
var firstOfGroup = form.find(classGroup).eq(0);
var secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (firstOfGroup[0].value || secondOfGroup[0].value) {
errorMsg = methods._dateRange(firstOfGroup, secondOfGroup, rules, i, options);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "dateTimeRange":
var classGroup = "[class*=" + rules[i + 1] + "]";
var firstOfGroup = form.find(classGroup).eq(0);
var secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (firstOfGroup[0].value || secondOfGroup[0].value) {
errorMsg = methods._dateTimeRange(firstOfGroup, secondOfGroup, rules, i, options);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "maxCheckbox":
errorMsg = methods._maxCheckbox(form, field, rules, i, options);
field = $(form.find("input[name='" + fieldName + "']"));
break;
case "minCheckbox":
errorMsg = methods._minCheckbox(form, field, rules, i, options);
field = $(form.find("input[name='" + fieldName + "']"));
break;
case "equals":
errorMsg = methods._equals(field, rules, i, options);
break;
case "funcCall":
errorMsg = methods._funcCall(field, rules, i, options);
break;
default:
//$.error("jQueryValidator rule not found"+rules[i]);
}
if (errorMsg !== undefined) {
promptText += errorMsg + "<br/>";
options.isError = true;
}
}
// If the rules required is not added, an empty field is not validated
if(!required && field.val() == "") 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 (fieldType == "text" && form.find("input[name='" + fieldName + "']").size() > 1) {
field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first"));
options.showArrow = false;
}
if (options.isError){
methods._showPrompt(field, promptText, "", 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);
}
return options.isError;
},
/**
* 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":
default:
if (!field.val())
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 + "']").size() == 1)
return options.allrules[rules[i]].alertTextCheckboxe;
else
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
// required for <select>
case "select-one":
// added by paul@kinetek.net for select boxes, Thank you
if (!field.val())
return options.allrules[rules[i]].alertText;
break;
case "select-multiple":
// added by paul@kinetek.net for select boxes, Thank you
if (!field.find("option:selected").val())
return options.allrules[rules[i]].alertText;
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 = "[class*=" +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 Regex rules
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_customRegex: function(field, rules, i, options) {
var customRule = rules[i + 1];
var rule = options.allrules[customRule];
if(!rule) {
alert("jqv:custom rule not found "+customRule);
return;
}
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;
},
/**
* 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 = 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(field, rules, i, options) {
var p=rules[i + 1];
var pdate = (p.toLowerCase() == "now")? new Date():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(field, rules, i, options) {
var p=rules[i + 1];
var pdate = (p.toLowerCase() == "now")? new Date():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]))$/);
if (dateRegEx.test(value)) {
return true;
}
return false;
},
/**
* 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})$/);
if (dateTimeRegEx.test(value)) {
return true;
}
return false;
},
//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 (first, second, rules, i, options) {
//are not both populated
if ((!first[0].value && second[0].value) || (first[0].value && !second[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDate(first[0].value) || !methods._isDate(second[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(first[0].value, second[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 (first, second, rules, i, options) {
//are not both populated
if ((!first[0].value && second[0].value) || (first[0].value && !second[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDateTime(first[0].value) || !methods._isDateTime(second[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(first[0].value, second[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;
}
},
/**
* 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;
if (!extraData)
extraData = "";
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);
tmpData.push(keyValue);
}
}
extraDataDynamic = tmpData.join("&");
} else {
extraDataDynamic = "";
}
if (!options.isError) {
$.ajax({
type: "GET",
url: rule.url,
cache: false,
dataType: "json",
data: "fieldId=" + field.attr("id") + "&fieldValue=" + field.val() + "&extraData=" + extraData + "&" + extraDataDynamic,
field: field,
rule: rule,
methods: methods,
options: options,
beforeSend: function() {
// build the loading prompt
var loadingText = rule.alertTextLoad;
if (loadingText)
methods._showPrompt(field, loadingText, "load", true, options);
},
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]);
// 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 {
if (options.ajaxValidCache[errorFieldId] !== undefined)
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);
}
}
errorField.trigger("jqv.field.result", [errorField, !options.isError, msg]);
}
});
}
},
/**
* 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
if(field.is(":input")) 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 */
options.InvalidCount++;
}
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') {
if (positionType.indexOf(":")!=-1) {
positionType=positionType.substring(0,positionType.indexOf(":"));
};
};
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;
}
}
if (options.relative) {
// empty relative span does not disturb page layout
// prompt positioned absolute to relative span
// vertical-align:top so position calculations are the same as isOverflown
var outer = $('<span>').css('position','relative').css('vertical-align','top').addClass('formErrorOuter').append(prompt.css('position','absolute'));
field.before(outer);
} else if (options.isOverflown) {
//Cedric: Needed if a container is in position:relative
// insert prompt in the form or in the overflown container?
field.before(prompt);
} else {
$("body").append(prompt);
}
var pos = methods._calculatePosition(field, prompt, options);
prompt.css({
"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize,
"opacity": 0
}).data("callerField", field);
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);
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 className = methods._getClassName(field.attr("id")) + "formError";
var match = $("." + methods._escapeExpression(className))[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 promptHeight = promptElmt.height();
var overflow = options.isOverflown || options.relative;
if (overflow) {
// is the form contained in an overflown container?
promptTopPosition = promptleftPosition = 0;
// compensation for the arrow
marginTopSize = -promptHeight;
} else {
var offset = field.offset();
promptTopPosition = offset.top;
promptleftPosition = offset.left;
marginTopSize = 0;
}
//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;};
};
};
if(!methods.isRTL(field))
{
switch (positionType) {
default:
case "topRight":
if (overflow)
// Is the form contained in an overflown container?
promptleftPosition += fieldWidth - 30;
else {
promptleftPosition += fieldWidth - 30;
promptTopPosition += -promptHeight -2;
}
break;
case "topLeft":
promptTopPosition += -promptHeight - 10;
break;
case "centerRight":
if (overflow) {
promptTopPosition=field.outerHeight();
promptleftPosition=field.outerWidth(1)+5;
} else {
promptleftPosition+=field.outerWidth()+5;
}
break;
case "centerLeft":
promptleftPosition -= promptElmt.width() + 2;
break;
case "bottomLeft":
promptTopPosition = promptTopPosition + field.height() + 15;
break;
case "bottomRight":
promptleftPosition += fieldWidth - 30;
promptTopPosition += field.height() + 5;
}
}
else
{
switch (positionType) {
default:
case "topLeft":
if (overflow)
// Is the form contained in an overflown container?
promptleftPosition -= promptElmt.width() - 30;
else {
promptleftPosition -= promptElmt.width() - 30;
promptTopPosition += -promptHeight -2;
}
break;
case "topRight":
if (overflow)
// Is the form contained in an overflown container?
promptleftPosition += fieldWidth - promptElmt.width();
else {
promptleftPosition += fieldWidth - promptElmt.width();
promptTopPosition += -promptHeight -2;
}
break;
case "centerRight":
if (overflow) {
promptTopPosition=field.outerHeight();
promptleftPosition=field.outerWidth(1)+5;
} else {
promptleftPosition+=field.outerWidth()+5;
}
break;
case "centerLeft":
promptleftPosition -= promptElmt.width() + 2;
break;
case "bottomLeft":
promptleftPosition += -promptElmt.width() + 30;
promptTopPosition = promptTopPosition + field.height() + 15;
break;
case "bottomRight":
promptleftPosition += fieldWidth - promptElmt.width();
promptTopPosition += field.height() + 15;
}
}
//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);
// Needed to be retro compatible
if (userOptions.isOverflown) userOptions.relative = true;
if (userOptions.relative) userOptions.isOverflown = true;
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, "_");
}
}
};
/**
* 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 false; // 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 != "hidePrompt" && 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= {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,
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
ajaxFormValidationURL: false,
// The url to send the submit ajax validation (default to action)
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,
// better relative positioning
relative: false,
// Used when the form is displayed within a scrolling DIV
isOverflown: false,
overflownDIV: "",
// Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages
doNotShowAllErrosOnSubmit: false,
// true when form and fields are binded
binded: false,
// 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,
// 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: [],
onSuccess: false,
onFailure: false
}};
$(function(){$.validationEngine.defaults.promptPosition = methods.isRTL()?'topLeft':"topRight"});
})(jQuery);
| JavaScript |
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(jQuery) | JavaScript |
$(document).ready(function() {
$("#w2bForm").validationEngine('attach');
$("span.colorbox").each(function(){
$(this).css({backgroundColor:"#" + $(this).siblings("input.inputcolor").val()});
});
$(".inputcolor").ColorPicker({
onShow: function (colpkr) {
$(colpkr).fadeIn(200);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(200);
return false;
},
onSubmit: function(hsb, hex, rgb, el) {
$(el).val(hex);
$(el).next("span.colorbox").css("backgroundColor", "#" + hex);
$(el).ColorPickerHide();
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
}).bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
$(this).next("span.colorbox").css("backgroundColor", "#" + $(this).val());
});
$("span.colorbox").ColorPicker({
onBeforeShow: function () {
$(this).ColorPickerSetColor($(this).siblings("input.inputcolor").val());
},
onShow: function (colpkr) {
$(colpkr).fadeIn(200);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(200);
return false;
},
onSubmit: function(hsb, hex, rgb, el) {
$(el).css({'backgroundColor': '#' + hex});
$(el).siblings("input.inputcolor").val(hex);
$(el).ColorPickerHide();
}
});
}); | JavaScript |
//Snow - http://www.btinternet.com/~kurt.grigg/javascript
if ((document.getElementById) &&
window.addEventListener || window.attachEvent){
(function(){
//Configure here.
var num = 100; //Number of flakes
var timer = 0; //setTimeout speed. Varies on different comps
var enableinNS6 = 1 //Enable script in NS6/Mozilla? Snow animation could be slow in those browsers. (1=yes, 0=no).
//End.
var y = [];
var x = [];
var fall = [];
var theFlakes = [];
var sfs = [];
var step = [];
var currStep = [];
var h,w,r;
var d = document;
var pix = "px";
var domWw = (typeof window.innerWidth == "number");
var domSy = (typeof window.pageYOffset == "number");
var idx = d.getElementsByTagName('div').length;
if (d.documentElement.style &&
typeof d.documentElement.style.MozOpacity == "string")
num = 12;
for (i = 0; i < num; i++){
sfs[i] = Math.round(1 + Math.random() * 1);
document.write('<div id="flake'+(idx+i)+'" style="position:absolute;top:0px;left:0px;width:'
+sfs[i]+'px;height:'+sfs[i]+'px;background-color:#ffffff;font-size:'+sfs[i]+'px"><\/div>');
currStep[i] = 0;
fall[i] = (sfs[i] == 1)?
Math.round(2 + Math.random() * 2): Math.round(3 + Math.random() * 2);
step[i] = (sfs[i] == 1)?
0.05 + Math.random() * 0.1 : 0.05 + Math.random() * 0.05 ;
}
if (domWw) r = window;
else{
if (d.documentElement &&
typeof d.documentElement.clientWidth == "number" &&
d.documentElement.clientWidth != 0)
r = d.documentElement;
else{
if (d.body &&
typeof d.body.clientWidth == "number")
r = d.body;
}
}
function winsize(){
var oh,sy,ow,sx,rh,rw;
if (domWw){
if (d.documentElement && d.defaultView &&
typeof d.defaultView.scrollMaxY == "number"){
oh = d.documentElement.offsetHeight;
sy = d.defaultView.scrollMaxY;
ow = d.documentElement.offsetWidth;
sx = d.defaultView.scrollMaxX;
rh = oh-sy;
rw = ow-sx;
}
else{
rh = r.innerHeight;
rw = r.innerWidth;
}
h = rh - 2;
w = rw - 2;
}
else{
h = r.clientHeight - 2;
w = r.clientWidth - 2;
}
}
;
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function scrl(yx){
var y,x;
if (domSy){
y = r.pageYOffset;
x = r.pageXOffset;
}
else{
y = r.scrollTop;
x = r.scrollLeft;
}
return (yx == 0)?y:x;
}
function snow(){
var dy,dx;
for (i = 0; i < num; i++){
dy = fall[i];
dx = fall[i] * Math.cos(currStep[i]);
y[i]+=dy;
x[i]+=dx;
if (x[i] >= w || y[i] >= h){
y[i] = -10;
x[i] = Math.round(Math.random() * w);
fall[i] = (sfs[i] == 1)?
Math.round(2 + Math.random() * 2): Math.round(3 + Math.random() * 2);
step[i] = (sfs[i] == 1)?
0.05 + Math.random() * 0.1 : 0.05 + Math.random() * 0.05 ;
}
theFlakes[i].top = y[i] + scrl(0) + pix;
theFlakes[i].left = x[i] + scrl(1) + pix;
currStep[i]+=step[i];
}
setTimeout(snow,timer);
}
function init(){
winsize();
for (i = 0; i < num; i++){
theFlakes[i] = document.getElementById("flake"+(idx+i)).style;
y[i] = Math.round(Math.random()*h);
x[i] = Math.round(Math.random()*w);
}
snow();
}
if (window.addEventListener){
window.addEventListener("resize",winsize,false);
window.addEventListener("load",init,false);
}
else if (window.attachEvent){
window.attachEvent("onresize",winsize);
window.attachEvent("onload",init);
}
})();
}//End. | JavaScript |
/*
DHTML Snowstorm! OO-style Jascript-based Snow effect
----------------------------------------------------
Version 1.4.20091115 (Previous rev: v1.3.20081215)
Code by Scott Schiller - http://schillmania.com
----------------------------------------------------
Initializes after body onload() by default (via addEventHandler() call at bottom.)
To customize properties, edit below or override configuration after this script
has run (but before body.onload), eg. snowStorm.snowStick = false;
*/
var snowStorm = null;
function SnowStorm() {
// --- PROPERTIES ---
this.flakesMax = 128; // Limit total amount of snow made (falling + sticking)
this.flakesMaxActive = 100; // Limit amount of snow falling at once (less = lower CPU use)
this.animationInterval = 33; // Theoretical "miliseconds per frame" measurement. 20 = fast + smooth, but high CPU use. 50 = more conservative, but slower
this.flakeBottom = null; // Integer for Y axis snow limit, 0 or null for "full-screen" snow effect
this.targetElement = null; // element which snow will be appended to (document body if null/undefined) - can be an element ID string, or a DOM node reference
this.followMouse = true; // Snow will change movement with the user's mouse
this.snowColor = '#fff'; // Don't eat (or use?) yellow snow.
this.snowCharacter = '•'; // • = bullet, · is square on some systems etc.
this.snowStick = true; // Whether or not snow should "stick" at the bottom. When off, will never collect.
this.useMeltEffect = true; // When recycling fallen snow (or rarely, when falling), have it "melt" and fade out if browser supports it
this.useTwinkleEffect = false; // Allow snow to randomly "flicker" in and out of view while falling
this.usePositionFixed = false; // true = snow not affected by window scroll. may increase CPU load, disabled by default - if enabled, used only where supported
// --- less-used bits ---
this.flakeLeftOffset = 0; // amount to subtract from edges of container
this.flakeRightOffset = 0; // amount to subtract from edges of container
this.flakeWidth = 8; // max pixel width for snow element
this.flakeHeight = 8; // max pixel height for snow element
this.vMaxX = 5; // Maximum X velocity range for snow
this.vMaxY = 4; // Maximum Y velocity range
this.zIndex = 0; // CSS stacking order applied to each snowflake
// --- End of user section ---
// jslint global declarations
/*global window, document, navigator, clearInterval, setInterval */
var addEvent = (typeof(window.attachEvent)=='undefined'?function(o,evtName,evtHandler) {
return o.addEventListener(evtName,evtHandler,false);
}:function(o,evtName,evtHandler) {
return o.attachEvent('on'+evtName,evtHandler);
});
var removeEvent = (typeof(window.attachEvent)=='undefined'?function(o,evtName,evtHandler) {
return o.removeEventListener(evtName,evtHandler,false);
}:function(o,evtName,evtHandler) {
return o.detachEvent('on'+evtName,evtHandler);
});
function rnd(n,min) {
if (isNaN(min)) {
min = 0;
}
return (Math.random()*n)+min;
}
function plusMinus(n) {
return (parseInt(rnd(2),10)==1?n*-1:n);
}
var s = this;
var storm = this;
this.timers = [];
this.flakes = [];
this.disabled = false;
this.active = false;
var isIE = navigator.userAgent.match(/msie/i);
var isIE6 = navigator.userAgent.match(/msie 6/i);
var isOldIE = (isIE && (isIE6 || navigator.userAgent.match(/msie 5/i)));
var isWin9X = navigator.appVersion.match(/windows 98/i);
var isiPhone = navigator.userAgent.match(/iphone/i);
var isBackCompatIE = (isIE && document.compatMode == 'BackCompat');
var noFixed = ((isBackCompatIE || isIE6 || isiPhone)?true:false);
var screenX = null;
var screenX2 = null;
var screenY = null;
var scrollY = null;
var vRndX = null;
var vRndY = null;
var windOffset = 1;
var windMultiplier = 2;
var flakeTypes = 6;
var fixedForEverything = false;
var opacitySupported = (function(){
try {
document.createElement('div').style.opacity = '0.5';
} catch (e) {
return false;
}
return true;
})();
var docFrag = document.createDocumentFragment();
if (s.flakeLeftOffset === null) {
s.flakeLeftOffset = 0;
}
if (s.flakeRightOffset === null) {
s.flakeRightOffset = 0;
}
this.meltFrameCount = 20;
this.meltFrames = [];
for (var i=0; i<this.meltFrameCount; i++) {
this.meltFrames.push(1-(i/this.meltFrameCount));
}
this.randomizeWind = function() {
vRndX = plusMinus(rnd(s.vMaxX,0.2));
vRndY = rnd(s.vMaxY,0.2);
if (this.flakes) {
for (var i=0; i<this.flakes.length; i++) {
if (this.flakes[i].active) {
this.flakes[i].setVelocities();
}
}
}
};
this.scrollHandler = function() {
// "attach" snowflakes to bottom of window if no absolute bottom value was given
scrollY = (s.flakeBottom?0:parseInt(window.scrollY||document.documentElement.scrollTop||document.body.scrollTop,10));
if (isNaN(scrollY)) {
scrollY = 0; // Netscape 6 scroll fix
}
if (!fixedForEverything && !s.flakeBottom && s.flakes) {
for (var i=s.flakes.length; i--;) {
if (s.flakes[i].active === 0) {
s.flakes[i].stick();
}
}
}
};
this.resizeHandler = function() {
if (window.innerWidth || window.innerHeight) {
screenX = window.innerWidth-(!isIE?16:2)-s.flakeRightOffset;
screenY = (s.flakeBottom?s.flakeBottom:window.innerHeight);
} else {
screenX = (document.documentElement.clientWidth||document.body.clientWidth||document.body.scrollWidth)-(!isIE?8:0)-s.flakeRightOffset;
screenY = s.flakeBottom?s.flakeBottom:(document.documentElement.clientHeight||document.body.clientHeight||document.body.scrollHeight);
}
screenX2 = parseInt(screenX/2,10);
};
this.resizeHandlerAlt = function() {
screenX = s.targetElement.offsetLeft+s.targetElement.offsetWidth-s.flakeRightOffset;
screenY = s.flakeBottom?s.flakeBottom:s.targetElement.offsetTop+s.targetElement.offsetHeight;
screenX2 = parseInt(screenX/2,10);
};
this.freeze = function() {
// pause animation
if (!s.disabled) {
s.disabled = 1;
} else {
return false;
}
for (var i=s.timers.length; i--;) {
clearInterval(s.timers[i]);
}
};
this.resume = function() {
if (s.disabled) {
s.disabled = 0;
} else {
return false;
}
s.timerInit();
};
this.toggleSnow = function() {
if (!s.flakes.length) {
// first run
s.start();
} else {
s.active = !s.active;
if (s.active) {
s.show();
s.resume();
} else {
s.stop();
s.freeze();
}
}
};
this.stop = function() {
this.freeze();
for (var i=this.flakes.length; i--;) {
this.flakes[i].o.style.display = 'none';
}
removeEvent(window,'scroll',s.scrollHandler);
removeEvent(window,'resize',s.resizeHandler);
if (!isOldIE) {
removeEvent(window,'blur',s.freeze);
removeEvent(window,'focus',s.resume);
}
};
this.show = function() {
for (var i=this.flakes.length; i--;) {
this.flakes[i].o.style.display = 'block';
}
};
this.SnowFlake = function(parent,type,x,y) {
var s = this;
var storm = parent;
this.type = type;
this.x = x||parseInt(rnd(screenX-20),10);
this.y = (!isNaN(y)?y:-rnd(screenY)-12);
this.vX = null;
this.vY = null;
this.vAmpTypes = [1,1.2,1.4,1.6,1.8]; // "amplification" for vX/vY (based on flake size/type)
this.vAmp = this.vAmpTypes[this.type];
this.melting = false;
this.meltFrameCount = storm.meltFrameCount;
this.meltFrames = storm.meltFrames;
this.meltFrame = 0;
this.twinkleFrame = 0;
this.active = 1;
this.fontSize = (10+(this.type/5)*10);
this.o = document.createElement('div');
this.o.innerHTML = storm.snowCharacter;
this.o.style.color = storm.snowColor;
this.o.style.position = (fixedForEverything?'fixed':'absolute');
this.o.style.width = storm.flakeWidth+'px';
this.o.style.height = storm.flakeHeight+'px';
this.o.style.fontFamily = 'arial,verdana';
this.o.style.overflow = 'hidden';
this.o.style.fontWeight = 'normal';
this.o.style.zIndex = storm.zIndex;
docFrag.appendChild(this.o);
this.refresh = function() {
if (isNaN(s.x) || isNaN(s.y)) {
// safety check
return false;
}
s.o.style.left = s.x+'px';
s.o.style.top = s.y+'px';
};
this.stick = function() {
if (noFixed || (storm.targetElement != document.documentElement && storm.targetElement != document.body)) {
s.o.style.top = (screenY+scrollY-storm.flakeHeight)+'px';
} else if (storm.flakeBottom) {
s.o.style.top = storm.flakeBottom+'px';
} else {
s.o.style.display = 'none';
s.o.style.top = 'auto';
s.o.style.bottom = '0px';
s.o.style.position = 'fixed';
s.o.style.display = 'block';
}
};
this.vCheck = function() {
if (s.vX>=0 && s.vX<0.2) {
s.vX = 0.2;
} else if (s.vX<0 && s.vX>-0.2) {
s.vX = -0.2;
}
if (s.vY>=0 && s.vY<0.2) {
s.vY = 0.2;
}
};
this.move = function() {
var vX = s.vX*windOffset;
s.x += vX;
s.y += (s.vY*s.vAmp);
if (s.x >= screenX || screenX-s.x < storm.flakeWidth) { // X-axis scroll check
s.x = 0;
} else if (vX < 0 && s.x-storm.flakeLeftOffset<0-storm.flakeWidth) {
s.x = screenX-storm.flakeWidth-1; // flakeWidth;
}
s.refresh();
var yDiff = screenY+scrollY-s.y;
if (yDiff<storm.flakeHeight) {
s.active = 0;
if (storm.snowStick) {
s.stick();
} else {
s.recycle();
}
} else {
if (storm.useMeltEffect && s.active && s.type < 3 && !s.melting && Math.random()>0.998) {
// ~1/1000 chance of melting mid-air, with each frame
s.melting = true;
s.melt();
// only incrementally melt one frame
// s.melting = false;
}
if (storm.useTwinkleEffect) {
if (!s.twinkleFrame) {
if (Math.random()>0.9) {
s.twinkleFrame = parseInt(Math.random()*20,10);
}
} else {
s.twinkleFrame--;
s.o.style.visibility = (s.twinkleFrame && s.twinkleFrame%2===0?'hidden':'visible');
}
}
}
};
this.animate = function() {
// main animation loop
// move, check status, die etc.
s.move();
};
this.setVelocities = function() {
s.vX = vRndX+rnd(storm.vMaxX*0.12,0.1);
s.vY = vRndY+rnd(storm.vMaxY*0.12,0.1);
};
this.setOpacity = function(o,opacity) {
if (!opacitySupported) {
return false;
}
o.style.opacity = opacity;
};
this.melt = function() {
if (!storm.useMeltEffect || !s.melting) {
s.recycle();
} else {
if (s.meltFrame < s.meltFrameCount) {
s.meltFrame++;
s.setOpacity(s.o,s.meltFrames[s.meltFrame]);
s.o.style.fontSize = s.fontSize-(s.fontSize*(s.meltFrame/s.meltFrameCount))+'px';
s.o.style.lineHeight = storm.flakeHeight+2+(storm.flakeHeight*0.75*(s.meltFrame/s.meltFrameCount))+'px';
} else {
s.recycle();
}
}
};
this.recycle = function() {
s.o.style.display = 'none';
s.o.style.position = (fixedForEverything?'fixed':'absolute');
s.o.style.bottom = 'auto';
s.setVelocities();
s.vCheck();
s.meltFrame = 0;
s.melting = false;
s.setOpacity(s.o,1);
s.o.style.padding = '0px';
s.o.style.margin = '0px';
s.o.style.fontSize = s.fontSize+'px';
s.o.style.lineHeight = (storm.flakeHeight+2)+'px';
s.o.style.textAlign = 'center';
s.o.style.verticalAlign = 'baseline';
s.x = parseInt(rnd(screenX-storm.flakeWidth-20),10);
s.y = parseInt(rnd(screenY)*-1,10)-storm.flakeHeight;
s.refresh();
s.o.style.display = 'block';
s.active = 1;
};
this.recycle(); // set up x/y coords etc.
this.refresh();
};
this.snow = function() {
var active = 0;
var used = 0;
var waiting = 0;
var flake = null;
for (var i=s.flakes.length; i--;) {
if (s.flakes[i].active == 1) {
s.flakes[i].move();
active++;
} else if (s.flakes[i].active === 0) {
used++;
} else {
waiting++;
}
if (s.flakes[i].melting) {
s.flakes[i].melt();
}
}
if (active<s.flakesMaxActive) {
flake = s.flakes[parseInt(rnd(s.flakes.length),10)];
if (flake.active === 0) {
flake.melting = true;
}
}
};
this.mouseMove = function(e) {
if (!s.followMouse) {
return true;
}
var x = parseInt(e.clientX,10);
if (x<screenX2) {
windOffset = -windMultiplier+(x/screenX2*windMultiplier);
} else {
x -= screenX2;
windOffset = (x/screenX2)*windMultiplier;
}
};
this.createSnow = function(limit,allowInactive) {
for (var i=0; i<limit; i++) {
s.flakes[s.flakes.length] = new s.SnowFlake(s,parseInt(rnd(flakeTypes),10));
if (allowInactive || i>s.flakesMaxActive) {
s.flakes[s.flakes.length-1].active = -1;
}
}
storm.targetElement.appendChild(docFrag);
};
this.timerInit = function() {
s.timers = (!isWin9X?[setInterval(s.snow,s.animationInterval)]:[setInterval(s.snow,s.animationInterval*3),setInterval(s.snow,s.animationInterval)]);
};
;
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
this.init = function() {
s.randomizeWind();
s.createSnow(s.flakesMax); // create initial batch
addEvent(window,'resize',s.resizeHandler);
addEvent(window,'scroll',s.scrollHandler);
if (!isOldIE) {
addEvent(window,'blur',s.freeze);
addEvent(window,'focus',s.resume);
}
s.resizeHandler();
s.scrollHandler();
if (s.followMouse) {
addEvent(document,'mousemove',s.mouseMove);
}
s.animationInterval = Math.max(20,s.animationInterval);
s.timerInit();
};
var didInit = false;
this.start = function(bFromOnLoad) {
if (!didInit) {
didInit = true;
} else if (bFromOnLoad) {
// already loaded and running
return true;
}
if (typeof s.targetElement == 'string') {
var targetID = s.targetElement;
s.targetElement = document.getElementById(targetID);
if (!s.targetElement) {
throw new Error('Snowstorm: Unable to get targetElement "'+targetID+'"');
}
}
if (!s.targetElement) {
s.targetElement = (!isIE?(document.documentElement?document.documentElement:document.body):document.body);
}
if (s.targetElement != document.documentElement && s.targetElement != document.body) {
s.resizeHandler = s.resizeHandlerAlt; // re-map handler to get element instead of screen dimensions
}
s.resizeHandler(); // get bounding box elements
s.usePositionFixed = (s.usePositionFixed && !noFixed); // whether or not position:fixed is supported
fixedForEverything = s.usePositionFixed;
if (screenX && screenY && !s.disabled) {
s.init();
s.active = true;
}
};
function doStart() {
s.start(true);
}
if (document.addEventListener) {
// safari 3.0.4 doesn't do DOMContentLoaded, maybe others - use a fallback to be safe.
document.addEventListener('DOMContentLoaded',doStart,false);
window.addEventListener('load',doStart,false);
} else {
addEvent(window,'load',doStart);
}
}
snowStorm = new SnowStorm(); | JavaScript |
// JavaScript Document<script type='text/javascript'>
// <![CDATA[
var colour="#c8b560";
var sparkles=100;
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="3px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="3px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
};
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
| JavaScript |
// JavaScript Document<script type='text/javascript'>
// <![CDATA[
var colour="#806517";
var sparkles=100;
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="3px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="3px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
};
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
| JavaScript |
// JavaScript Document<script type='text/javascript'>
// <![CDATA[
var colour="#e9cfec";
var sparkles=100;
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="3px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="3px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
};
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
| JavaScript |
// JavaScript Document<script type='text/javascript'>
// <![CDATA[
var colour="#8d38c9";
var sparkles=100;
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="3px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="3px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
};
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
| JavaScript |
// JavaScript Document<script type='text/javascript'>
// <![CDATA[
var colour="#6698ff";
var sparkles=100;
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="3px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="3px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
};
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
| JavaScript |
// JavaScript Document<script type='text/javascript'>
// <![CDATA[
var colour="#c48793";
var sparkles=100;
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="3px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="3px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
};
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
| JavaScript |
// JavaScript Document<script type='text/javascript'>
// <![CDATA[
var colour="#6960ec";
var sparkles=100;
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="3px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="3px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
};
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
| JavaScript |
// JavaScript Document<script type='text/javascript'>
// <![CDATA[
var colour="#387c44";
var sparkles=100;
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="3px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="3px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
};
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
| JavaScript |
// JavaScript Document<script type='text/javascript'>
// <![CDATA[
var colour="#348781";
var sparkles=100;
var x=ox=400;
var y=oy=300;
var swide=800;
var shigh=600;
var sleft=sdown=0;
var tiny=new Array();
var star=new Array();
var starv=new Array();
var starx=new Array();
var stary=new Array();
var tinyx=new Array();
var tinyy=new Array();
var tinyv=new Array();
window.onload=function() { if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i=0; i<sparkles; i++) {
var rats=createDiv(3, 3);
rats.style.visibility="hidden";
document.body.appendChild(tiny[i]=rats);
starv[i]=0;
tinyv[i]=0;
var rats=createDiv(5, 5);
rats.style.backgroundColor="transparent";
rats.style.visibility="hidden";
var rlef=createDiv(1, 5);
var rdow=createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top="3px";
rlef.style.left="0px";
rdow.style.top="0px";
rdow.style.left="3px";
document.body.appendChild(star[i]=rats);
}
set_width();
sparkle();
}}
function sparkle() {
var c;
if (x!=ox || y!=oy) {
ox=x;
oy=y;
for (c=0; c<sparkles; c++) if (!starv[c]) {
star[c].style.left=(starx[c]=x)+"px";
star[c].style.top=(stary[c]=y)+"px";
star[c].style.clip="rect(0px, 5px, 5px, 0px)";
star[c].style.visibility="visible";
starv[c]=50;
break;
}
}
for (c=0; c<sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i]==25) star[i].style.clip="rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i]+=1+Math.random()*3;
if (stary[i]<shigh+sdown) {
star[i].style.top=stary[i]+"px";
starx[i]+=(i%5-2)/5;
star[i].style.left=starx[i]+"px";
}
else {
star[i].style.visibility="hidden";
starv[i]=0;
return;
}
}
else {
tinyv[i]=50;
tiny[i].style.top=(tinyy[i]=stary[i])+"px";
tiny[i].style.left=(tinyx[i]=starx[i])+"px";
tiny[i].style.width="2px";
tiny[i].style.height="2px";
star[i].style.visibility="hidden";
tiny[i].style.visibility="visible"
}
};
document['write']('<a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Latest Tips and Tricks"><img src="https://bitly.com/24workpng1" alt="Latest Tips and Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%;" /></a><a href="http://24work.blogspot.com/" rel="dofollow" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; left: 0%;" /></a>');
function update_tiny(i) {
if (--tinyv[i]==25) {
tiny[i].style.width="1px";
tiny[i].style.height="1px";
}
if (tinyv[i]) {
tinyy[i]+=1+Math.random()*3;
if (tinyy[i]<shigh+sdown) {
tiny[i].style.top=tinyy[i]+"px";
tinyx[i]+=(i%5-2)/5;
tiny[i].style.left=tinyx[i]+"px";
}
else {
tiny[i].style.visibility="hidden";
tinyv[i]=0;
return;
}
}
else tiny[i].style.visibility="hidden";
}
document.onmousemove=mouse;
function mouse(e) {
set_scroll();
y=(e)?e.pageY:event.y+sdown;
x=(e)?e.pageX:event.x+sleft;
}
function set_scroll() {
if (typeof(self.pageYOffset)=="number") {
sdown=self.pageYOffset;
sleft=self.pageXOffset;
}
else if (document.body.scrollTop || document.body.scrollLeft) {
sdown=document.body.scrollTop;
sleft=document.body.scrollLeft;
}
else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft=document.documentElement.scrollLeft;
sdown=document.documentElement.scrollTop;
}
else {
sdown=0;
sleft=0;
}
}
window.onresize=set_width;
function set_width() {
if (typeof(self.innerWidth)=="number") {
swide=self.innerWidth;
shigh=self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
swide=document.documentElement.clientWidth;
shigh=document.documentElement.clientHeight;
}
else if (document.body.clientWidth) {
swide=document.body.clientWidth;
shigh=document.body.clientHeight;
}
}
function createDiv(height, width) {
var div=document.createElement("div");
div.style.position="absolute";
div.style.height=height+"px";
div.style.width=width+"px";
div.style.overflow="hidden";
div.style.backgroundColor=colour;
return (div);
}
// ]]>
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.