code
stringlengths
1
2.08M
language
stringclasses
1 value
// test for ternary result = (true?3:4)==3 && (false?5:6)==6;
JavaScript
var Foo = { value : function() { return this.x + this.y; } }; var a = { prototype: Foo, x: 1, y: 2 }; var b = new Foo(); b.x = 2; b.y = 3; var result1 = a.value(); var result2 = b.value(); result = result1==3 && result2==5;
JavaScript
// the 'lf' in the printf caused issues writing doubles on some compilers var a=5.0/10.0*100.0; var b=5.0*110.0; var c=50.0/10.0; a.dump(); b.dump(); c.dump(); result = a==50 && b==550 && c==5;
JavaScript
// Undefined/null from http://en.wikipedia.org/wiki/JavaScript_syntax var testUndefined; // variable declared but not defined, set to value of undefined var testObj = {}; result = 1; if ((""+testUndefined) != "undefined") result = 0; // test variable exists but value not defined, displays undefined if ((""+testObj.myProp) != "undefined") result = 0; // testObj exists, property does not, displays undefined if (!(undefined == null)) result = 0; // unenforced type during check, displays true if (undefined === null) result = 0;// enforce type during check, displays false if (null != undefined) result = 0; // unenforced type during check, displays true if (null === undefined) result = 0; // enforce type during check, displays false
JavaScript
// test for postincrement working as expected var foo = 5; result = (foo++)==5;
JavaScript
// simply testing we can return the correct value result = 1;
JavaScript
// functions in variables using JSON-style initialisation var bob = { add : function(x,y) { return x+y; } }; result = bob.add(3,6)==9;
JavaScript
// simple function scoping test var a = 7; function add(x,y) { var a=x+y; return a; } result = add(3,6)==9 && a==7;
JavaScript
// if .. else var a = 42; if (a != 42) result = 0; else result = 1;
JavaScript
// mikael.kindborg@mobilesorcery.com - Function symbol is evaluated in bracket-less body of false if-statement var foo; // a var is only created automated by assignment if (foo !== undefined) foo(); result = 1;
JavaScript
/* Javascript eval */ // 42-tiny-js change begin ---> // in JavaScript eval is not JSON.parse // use parentheses or JSON.parse instead //myfoo = eval("{ foo: 42 }"); myfoo = eval("("+"{ foo: 42 }"+")"); //<--- 42-tiny-js change end result = eval("4*10+2")==42 && myfoo.foo==42;
JavaScript
// test for array join var a = [1,2,4,5,7]; result = a.join(",")=="1,2,4,5,7";
JavaScript
// generator-test function fibonacci(){ var fn1 = 1; var fn2 = 1; while (1){ var current = fn2; fn2 = fn1; fn1 = fn1 + current; var reset = yield current; if (reset){ fn1 = 1; fn2 = 1; } } } var generator = fibonacci(); generator.next(); // 1 generator.next(); // 1 generator.next(); // 2 generator.next(); // 3 generator.next(); // 5 result = generator.next() == 8 && generator.send(true) == 1;
JavaScript
// with-test var a; with(Math) a=PI; var b = { get_member : function() { return this.member;}, member:41 }; with(b) { let a = get_member(); //<--- a is local for this block var c = a+1; } result = a == Math.PI && c == 42;
JavaScript
// switch-case-tests //////////////////////////////////////////////////// // switch-test 1: case with break; //////////////////////////////////////////////////// var a1=5; var b1=6; var r1=0; switch(a1+5){ case 6: r1 = 2; break; case b1+4: r1 = 42; break; case 7: r1 = 2; break; } //////////////////////////////////////////////////// // switch-test 2: case with out break; //////////////////////////////////////////////////// var a2=5; var b2=6; var r2=0; switch(a2+4){ case 6: r2 = 2; break; case b2+3: r2 = 40; //break; case 7: r2 += 2; break; } //////////////////////////////////////////////////// // switch-test 3: case with default; //////////////////////////////////////////////////// var a3=5; var b3=6; var r3=0; switch(a3+44){ case 6: r3 = 2; break; case b3+3: r3 = 1; break; default: r3 = 42; break; } //////////////////////////////////////////////////// // switch-test 4: case default before case; //////////////////////////////////////////////////// var a4=5; var b4=6; var r4=0; switch(a4+44){ default: r4 = 42; break; case 6: r4 = 2; break; case b4+3: r4 = 1; break; } result = r1 == 42 && r2 == 42 && r3 == 42 && r4 == 42;
JavaScript
// function-closure var a = 40; // a global var function closure() { var a = 39; // a local var; return function() { return a; }; } var b = closure(); // the local var a is now hidden result = b()+3 == 42 && a+2 == 42;
JavaScript
// comparison var a = 42; result = a==42;
JavaScript
function FindProxyForURL(url, host) { PROXY = "PROXY yourhttpproxy:80"; DEFAULT = "DIRECT"; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?appspot\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?blogspot\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(\d{2,}\.)docs\.google\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(\d{2,}\.)drive\.google\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?googleapis\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?googlecode\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?googlegroups\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?googlemashups\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?ig\.ig\.gmodules\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?a\.orkut\.gmodules\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)doc-(.{5})-docs\.googleusercontent\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\-)?a-fc-opensocial\.googleusercontent\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)images(\d{2,})-focus-opensocial\.googleusercontent\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(\d{2,}\.)-wave-opensocial\.googleusercontent\.com/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?au\.doubleclick\.net/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?de\.doubleclick\.net/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?fr\.doubleclick\.net/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?jp\.doubleclick\.net/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?uk\.doubleclick\.net/i.test(url)) return PROXY; if(/^[\w\-]+:\/+(?!\/)(www|ssl)\.google-analytics\.net/i.test(url)) return DEFAULT; if(/^[\w\-]+:\/+(?!\/)(?:[^\/]+\.)?google-analytics\.net/i.test(url)) return PROXY; return DEFAULT; }
JavaScript
/* _/ _/_/ _/_/_/_/_/ _/ _/ _/ _/ _/_/ _/ _/ _/_/_/ _/_/_/ _/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/_/ _/_/_/ _/_/_/ _/ _/ _/ _/ Created by David Kaneda <http://www.davidkaneda.com> Documentation and issue tracking on Google Code <http://code.google.com/p/jqtouch/> Special thanks to Jonathan Stark <http://jonathanstark.com/> and pinch/zoom <http://www.pinchzoom.com/> (c) 2009 by jQTouch project members. See LICENSE.txt for license. */ (function($) { $.fn.transition = function(css, options) { return this.each(function(){ var $el = $(this); var defaults = { speed : '300ms', callback: null, ease: 'ease-in-out' }; var settings = $.extend({}, defaults, options); if(settings.speed === 0) { $el.css(css); window.setTimeout(settings.callback, 0); } else { if ($.browser.safari) { var s = []; for(var i in css) { s.push(i); } $el.css({ webkitTransitionProperty: s.join(", "), webkitTransitionDuration: settings.speed, webkitTransitionTimingFunction: settings.ease }); if (settings.callback) { $el.one('webkitTransitionEnd', settings.callback); } setTimeout(function(el){ el.css(css) }, 0, $el); } else { $el.animate(css, settings.speed, settings.callback); } } }); } })(jQuery);
JavaScript
/* _/ _/_/ _/_/_/_/_/ _/ _/ _/ _/ _/_/ _/ _/ _/_/_/ _/_/_/ _/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/_/ _/_/_/ _/_/_/ _/ _/ _/ _/ Created by David Kaneda <http://www.davidkaneda.com> Documentation and issue tracking on Google Code <http://code.google.com/p/jqtouch/> Special thanks to Jonathan Stark <http://jonathanstark.com/> and pinch/zoom <http://www.pinchzoom.com/> (c) 2009 by jQTouch project members. See LICENSE.txt for license. $Revision: 109 $ $Date: 2009-10-06 12:23:30 -0400 (Tue, 06 Oct 2009) $ $LastChangedBy: davidcolbykaneda $ */ (function($) { $.jQTouch = function(options) { // Set support values $.support.WebKitCSSMatrix = (typeof WebKitCSSMatrix == "object"); $.support.touch = (typeof Touch == "object"); $.support.WebKitAnimationEvent = (typeof WebKitTransitionEvent == "object"); // Initialize internal variables var $body, $head=$('head'), hist=[], newPageCount=0, jQTSettings={}, hashCheck, currentPage, orientation, isMobileWebKit = RegExp(" Mobile/").test(navigator.userAgent), tapReady=true, lastAnimationTime=0, touchSelectors=[], publicObj={}, extensions=$.jQTouch.prototype.extensions, defaultAnimations=['slide','flip','slideup','swap','cube','pop','dissolve','fade','back'], animations=[], hairextensions=''; // Get the party started init(options); function init(options) { var defaults = { addGlossToIcon: true, backSelector: '.back, .cancel, .goback', cacheGetRequests: true, cubeSelector: '.cube', dissolveSelector: '.dissolve', fadeSelector: '.fade', fixedViewport: true, flipSelector: '.flip', formSelector: 'form', fullScreen: true, fullScreenClass: 'fullscreen', icon: null, touchSelector: 'a, .touch', popSelector: '.pop', preloadImages: false, slideSelector: 'body > * > ul li a', slideupSelector: '.slideup', startupScreen: null, statusBar: 'default', // other options: black-translucent, black submitSelector: '.submit', swapSelector: '.swap', useAnimations: true, useFastTouch: true // Experimental. }; jQTSettings = $.extend({}, defaults, options); // Preload images if (jQTSettings.preloadImages) { for (var i = jQTSettings.preloadImages.length - 1; i >= 0; i--){ (new Image()).src = jQTSettings.preloadImages[i]; }; } // Set icon if (jQTSettings.icon) { var precomposed = (jQTSettings.addGlossToIcon) ? '' : '-precomposed'; hairextensions += '<link rel="apple-touch-icon' + precomposed + '" href="' + jQTSettings.icon + '" />'; } // Set startup screen if (jQTSettings.startupScreen) { hairextensions += '<link rel="apple-touch-startup-image" href="' + jQTSettings.startupScreen + '" />'; } // Set viewport if (jQTSettings.fixedViewport) { hairextensions += '<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;"/>'; } // Set full-screen if (jQTSettings.fullScreen) { hairextensions += '<meta name="apple-mobile-web-app-capable" content="yes" />'; if (jQTSettings.statusBar) { hairextensions += '<meta name="apple-mobile-web-app-status-bar-style" content="' + jQTSettings.statusBar + '" />'; } } if (hairextensions) $head.append(hairextensions); // Initialize on document load: $(document).ready(function(){ // Add extensions for (var i in extensions) { var fn = extensions[i]; if ($.isFunction(fn)) { $.extend(publicObj, fn(publicObj)); } } // Add animations for (var i in defaultAnimations) { var name = defaultAnimations[i]; var selector = jQTSettings[name + 'Selector']; if (typeof(selector) == 'string') { addAnimation({name:name, selector:selector}); } } touchSelectors.push('input'); touchSelectors.push(jQTSettings.touchSelector); touchSelectors.push(jQTSettings.backSelector); touchSelectors.push(jQTSettings.submitSelector); $(touchSelectors.join(', ')).css('-webkit-touch-callout', 'none'); $(jQTSettings.backSelector).tap(liveTap); $(jQTSettings.submitSelector).tap(submitParentForm); $body = $('body'); if (jQTSettings.fullScreenClass && window.navigator.standalone == true) { $body.addClass(jQTSettings.fullScreenClass + ' ' + jQTSettings.statusBar); } // Create custom live events $body .bind('touchstart', handleTouch) .bind('orientationchange', updateOrientation) .trigger('orientationchange') .submit(submitForm); if (jQTSettings.useFastTouch && $.support.touch) { $body.click(function(e){ var $el = $(e.target); if ($el.attr('target') == '_blank' || $el.attr('rel') == 'external' || $el.is('input[type="checkbox"]')) { return true; } else { return false; } }); // This additionally gets rid of form focusses $body.mousedown(function(e){ var timeDiff = (new Date()).getTime() - lastAnimationTime; if (timeDiff < 200) { return false; } }); } // Make sure exactly one child of body has "current" class if ($('body > .current').length == 0) { currentPage = $('body > *:first'); } else { currentPage = $('body > .current:first'); $('body > .current').removeClass('current'); } // Go to the top of the "current" page $(currentPage).addClass('current'); location.hash = $(currentPage).attr('id'); addPageToHistory(currentPage); scrollTo(0, 0); dumbLoopStart(); }); } // PUBLIC FUNCTIONS function goBack(to) { // Init the param if (hist.length > 1) { var numberOfPages = Math.min(parseInt(to || 1, 10), hist.length-1); // Search through the history for an ID if( isNaN(numberOfPages) && typeof(to) === "string" && to != '#' ) { for( var i=1, length=hist.length; i < length; i++ ) { if( '#' + hist[i].id === to ) { numberOfPages = i; break; } } } // If still nothing, assume one if( isNaN(numberOfPages) || numberOfPages < 1 ) { numberOfPages = 1; }; // Grab the current page for the "from" info var animation = hist[0].animation; var fromPage = hist[0].page; // Remove all pages in front of the target page hist.splice(0, numberOfPages); // Grab the target page var toPage = hist[0].page; // Make the animations animatePages(fromPage, toPage, animation, true); return publicObj; } else { console.error('No pages in history.'); return false; } } function goTo(toPage, animation) { var fromPage = hist[0].page; if (typeof(toPage) === 'string') { toPage = $(toPage); } if (typeof(animation) === 'string') { for (var i = animations.length - 1; i >= 0; i--){ if (animations[i].name === animation) { animation = animations[i]; break; } } } if (animatePages(fromPage, toPage, animation)) { addPageToHistory(toPage, animation); return publicObj; } else { console.error('Could not animate pages.'); return false; } } function getOrientation() { return orientation; } // PRIVATE FUNCTIONS function liveTap(e){ // Grab the clicked element var $el = $(e.target); if ($el.attr('nodeName')!=='A'){ $el = $el.parent('a'); } var target = $el.attr('target'), hash = $el.attr('hash'), animation=null; if (tapReady == false || !$el.length) { console.warn('Not able to tap element.') return false; } if ($el.attr('target') == '_blank' || $el.attr('rel') == 'external') { return true; } // Figure out the animation to use for (var i = animations.length - 1; i >= 0; i--){ if ($el.is(animations[i].selector)) { animation = animations[i]; break; } }; // User clicked an internal link, fullscreen mode if (target == '_webapp') { window.location = $el.attr('href'); } // User clicked a back button else if ($el.is(jQTSettings.backSelector)) { goBack(hash); } // Branch on internal or external href else if (hash && hash!='#') { $el.addClass('active'); goTo($(hash).data('referrer', $el), animation); } else { $el.addClass('loading active'); showPageByHref($el.attr('href'), { animation: animation, callback: function(){ $el.removeClass('loading'); setTimeout($.fn.unselect, 250, $el); }, $referrer: $el }); } return false; } function addPageToHistory(page, animation) { // Grab some info var pageId = page.attr('id'); // Prepend info to page history hist.unshift({ page: page, animation: animation, id: pageId }); } function animatePages(fromPage, toPage, animation, backwards) { // Error check for target page if(toPage.length === 0){ $.fn.unselect(); console.error('Target element is missing.'); return false; } // Collapse the keyboard $(':focus').blur(); // Make sure we are scrolled up to hide location bar scrollTo(0, 0); // Define callback to run after animation completes var callback = function(event){ if (animation) { toPage.removeClass('in reverse ' + animation.name); fromPage.removeClass('current out reverse ' + animation.name); } else { fromPage.removeClass('current'); } toPage.trigger('pageAnimationEnd', { direction: 'in' }); fromPage.trigger('pageAnimationEnd', { direction: 'out' }); clearInterval(dumbLoop); currentPage = toPage; location.hash = currentPage.attr('id'); dumbLoopStart(); var $originallink = toPage.data('referrer'); if ($originallink) { $originallink.unselect(); } lastAnimationTime = (new Date()).getTime(); tapReady = true; } fromPage.trigger('pageAnimationStart', { direction: 'out' }); toPage.trigger('pageAnimationStart', { direction: 'in' }); if ($.support.WebKitAnimationEvent && animation && jQTSettings.useAnimations) { toPage.one('webkitAnimationEnd', callback); tapReady = false; toPage.addClass(animation.name + ' in current ' + (backwards ? ' reverse' : '')); fromPage.addClass(animation.name + ' out' + (backwards ? ' reverse' : '')); } else { toPage.addClass('current'); callback(); } return true; } function dumbLoopStart() { dumbLoop = setInterval(function(){ var curid = currentPage.attr('id'); if (location.hash == '') { location.hash = '#' + curid; } else if (location.hash != '#' + curid) { try { goBack(location.hash) } catch(e) { console.error('Unknown hash change.'); } } }, 100); } function insertPages(nodes, animation) { var targetPage = null; $(nodes).each(function(index, node){ var $node = $(this); if (!$node.attr('id')) { $node.attr('id', 'page-' + (++newPageCount)); } $node.appendTo($body); if ($node.hasClass('current') || !targetPage ) { targetPage = $node; } }); if (targetPage !== null) { goTo(targetPage, animation); return targetPage; } else { return false; } } function showPageByHref(href, options) { var defaults = { data: null, method: 'GET', animation: null, callback: null, $referrer: null }; var settings = $.extend({}, defaults, options); if (href != '#') { $.ajax({ url: href, data: settings.data, type: settings.method, success: function (data, textStatus) { var firstPage = insertPages(data, settings.animation); if (firstPage) { if (settings.method == 'GET' && jQTSettings.cacheGetRequests && settings.$referrer) { settings.$referrer.attr('href', '#' + firstPage.attr('id')); } if (settings.callback) { settings.callback(true); } } }, error: function (data) { if (settings.$referrer) settings.$referrer.unselect(); if (settings.callback) { settings.callback(false); } } }); } else if ($referrer) { $referrer.unselect(); } } function submitForm(e, callback){ var $form = (typeof(e)==='string') ? $(e) : $(e.target); if ($form.length && $form.is(jQTSettings.formSelector) && $form.attr('action')) { showPageByHref($form.attr('action'), { data: $form.serialize(), method: $form.attr('method') || "POST", animation: animations[0] || null, callback: callback }); return false; } return true; } function submitParentForm(e){ var $form = $(this).closest('form'); if ($form.length) { evt = jQuery.Event("submit"); evt.preventDefault(); $form.trigger(evt); return false; } return true; } function addAnimation(animation) { if (typeof(animation.selector) == 'string' && typeof(animation.name) == 'string') { animations.push(animation); $(animation.selector).tap(liveTap); touchSelectors.push(animation.selector); } } function updateOrientation() { orientation = window.innerWidth < window.innerHeight ? 'profile' : 'landscape'; $body.removeClass('profile landscape').addClass(orientation).trigger('turn', {orientation: orientation}); // scrollTo(0, 0); } function handleTouch(e) { var $el = $(e.target); // Only handle touchSelectors if (!$(e.target).is(touchSelectors.join(', '))) { var $link = $(e.target).closest('a'); if ($link.length){ $el = $link; } else { return; } } if (event) { var hoverTimeout = null, startX = event.changedTouches[0].clientX, startY = event.changedTouches[0].clientY, startTime = (new Date).getTime(), deltaX = 0, deltaY = 0, deltaT = 0; // Let's bind these after the fact, so we can keep some internal values $el.bind('touchmove', touchmove).bind('touchend', touchend); hoverTimeout = setTimeout(function(){ $el.makeActive(); }, 100); } // Private touch functions (TODO: insert dirty joke) function touchmove(e) { updateChanges(); var absX = Math.abs(deltaX); var absY = Math.abs(deltaY); // Check for swipe if (absX > absY && (absX > 35) && deltaT < 1000) { $el.trigger('swipe', {direction: (deltaX < 0) ? 'left' : 'right'}).unbind('touchmove touchend'); } else if (absY > 1) { $el.removeClass('active'); } clearTimeout(hoverTimeout); } function touchend(){ updateChanges(); if (deltaY === 0 && deltaX === 0) { $el.makeActive(); // New approach: // Fake the double click? // TODO: Try with all click events (no tap) // if (deltaT < 40) // { // setTimeout(function(){ // $el.trigger('touchstart') // .trigger('touchend'); // }, 0); // } $el.trigger('tap'); } else { $el.removeClass('active'); } $el.unbind('touchmove touchend'); clearTimeout(hoverTimeout); } function updateChanges(){ var first = event.changedTouches[0] || null; deltaX = first.pageX - startX; deltaY = first.pageY - startY; deltaT = (new Date).getTime() - startTime; } } // End touch handler // Public jQuery Fns $.fn.unselect = function(obj) { if (obj) { obj.removeClass('active'); } else { $('.active').removeClass('active'); } } $.fn.makeActive = function(){ return $(this).addClass('active'); } $.fn.swipe = function(fn) { if ($.isFunction(fn)) { return this.each(function(i, el){ $(el).bind('swipe', fn); }); } } $.fn.tap = function(fn){ if ($.isFunction(fn)) { var tapEvent = (jQTSettings.useFastTouch && $.support.touch) ? 'tap' : 'click'; return $(this).live(tapEvent, fn); } else { $(this).trigger('tap'); } } publicObj = { getOrientation: getOrientation, goBack: goBack, goTo: goTo, addAnimation: addAnimation, submitForm: submitForm } return publicObj; } // Extensions directly manipulate the jQTouch object, before it's initialized. $.jQTouch.prototype.extensions = []; $.jQTouch.addExtension = function(extension){ $.jQTouch.prototype.extensions.push(extension); } })(jQuery);
JavaScript
function initJQ() { $.jQTouch({ icon: '3txt.png', addGlossToIcon: false, preloadImages: [ 'themes/apple/img/chevron.png', 'themes/apple/img/back_button.png', 'themes/apple/img/button.png', 'themes/apple/img/pinstripes.png' ] }); } function noAjaxCache() { $.ajaxSetup ({ cache: false }); }
JavaScript
$.fn.delay = function(time, callback){ // Empty function: jQuery.fx.step.delay = function(){}; // Return meaningless animation, (will be added to queue) return this.animate({delay:1}, time, callback); }
JavaScript
function getWindowHeight() { var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; } function setContent() { if (document.getElementById) { var windowHeight = getWindowHeight(); if (windowHeight > 0) { var contentElement = document.getElementById('content'); var contentHeight = contentElement.offsetHeight; if (windowHeight - contentHeight > 0) { contentElement.style.position = 'relative'; contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px'; } else { contentElement.style.position = 'static'; } } } } window.onload = function() { setContent(); } window.onresize = function() { setContent(); }
JavaScript
function getWindowHeight() { var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; } function setContent() { if (document.getElementById) { var windowHeight = getWindowHeight(); if (windowHeight > 0) { var contentElement = document.getElementById('content'); var contentHeight = contentElement.offsetHeight; if (windowHeight - contentHeight > 0) { contentElement.style.position = 'relative'; contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px'; } else { contentElement.style.position = 'static'; } } } } window.onload = function() { setContent(); } window.onresize = function() { setContent(); }
JavaScript
/** * @author Alexandre Magno * @desc Center a element with jQuery * @version 1.0 * @example * $("element").center({ * * vertical: true, * horizontal: true * * }); * @obs With no arguments, the default is above * @license free * @param bool vertical, bool horizontal * @contribution Paulo Radichi * */ jQuery.fn.center = function(params) { var options = { vertical: true, horizontal: true } op = jQuery.extend(options, params); return this.each(function(){ //initializing variables var $self = jQuery(this); //get the dimensions using dimensions plugin var width = $self.width(); var height = $self.height(); //get the paddings var paddingTop = parseInt($self.css("padding-top")); var paddingBottom = parseInt($self.css("padding-bottom")); //get the borders var borderTop = parseInt($self.css("border-top-width")); var borderBottom = parseInt($self.css("border-bottom-width")); //get the media of padding and borders var mediaBorder = (borderTop+borderBottom)/2; var mediaPadding = (paddingTop+paddingBottom)/2; //get the type of positioning var positionType = $self.parent().css("position"); // get the half minus of width and height var halfWidth = (width/2)*(-1); var halfHeight = ((height/2)*(-1))-mediaPadding-mediaBorder; // initializing the css properties var cssProp = { position: 'absolute' }; if(op.vertical) { cssProp.height = height; cssProp.top = '50%'; cssProp.marginTop = halfHeight; } if(op.horizontal) { cssProp.width = width; cssProp.left = '50%'; cssProp.marginLeft = halfWidth; } //check the current position if(positionType == 'static') { $self.parent().css("position","relative"); } //aplying the css $self.css(cssProp); }); };
JavaScript
/* Project: Input Placeholder Text Title: Automatic population of form fields with contents of title attributes Author Jon Gibbins (aka dotjay) Created: 13 Aug 2005 Modified: 26 Oct 2009 Notes: Add the following classes to text inputs or textareas to get the desired behaviour: auto-select Will pre-populate the input with the title attribute and select the text when it receives focus. auto-clear Will pre-populate the input with the title attribute and clear the text when it receives focus. Note: if auto-select and auto-clear are set, auto-select takes precedence. populate Will just populate the input with the title attribute. NB: A class name of "placeholder" is set on form inputs that have placeholder text in them. This allows you to style the inputs differently when there is user input versus placeholder text, e.g. input.placeholder, textarea.placeholder{ color: #777; } Potential additions: Add in handling of default text if an initial value is detected (line 60, line 93, etc) using something like: if (!el.defaultValue) continue; el.onfocus = function() { if (this.value == this.defaultValue) this.value = ""; } el.onblur = function() { if (this.value == "") this.value = this.defaultValue; } */ function hasClass(el,cls) { return el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(el,cls) { if (!this.hasClass(el,cls)) el.className += " "+cls; } function removeClass(el,cls) { if (hasClass(el,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); el.className = el.className.replace(reg,' '); } } function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } function initFormPlaceholders() { if (!document.getElementsByTagName) return true; ourForms = document.getElementsByTagName('form'); // go through each form var numForms = ourForms.length; for (var i=0;i<numForms;i++) { // go through each form element var numFormElements = ourForms[i].elements.length; for (var j=0;j<numFormElements;j++) { var el = ourForms[i].elements[j]; // ignore submit buttons if (el.type == "submit") continue; // if we got a text type input or textarea if ((el.type == "text") || (el.type == "textarea")) { // only populate if we want it to // note: might want title attribute but no pre-population of inputs var ourClassName = el.className; if (ourClassName.match('auto-select') || ourClassName.match('auto-clear') || ourClassName.match('populate')) { // only populate if empty if (el.value == '') { addClass(el, "placeholder"); el.value = el.title; } } // add auto select if class contains auto-select // note: else if below so auto-select takes precedence (assuming select is better than clear) if (el.className.match('auto-select')) { el.onfocus = function () { if (this.value == this.title) { removeClass(this, "placeholder"); this.select(); } } if (el.captureEvents) el.captureEvents(Event.FOCUS); el.onblur = function () { if (this.value == '') { this.value = this.title; } if (this.value == this.title) { addClass(this, "placeholder"); } } if (el.captureEvents) el.captureEvents(Event.BLUR); } // add auto clear if class contains auto-clear else if (el.className.match('auto-clear')) { el.onfocus = function () { if (this.value == this.title) { removeClass(this, "placeholder"); this.value = ''; } } if (el.captureEvents) el.captureEvents(Event.FOCUS); el.onblur = function () { if (this.value == '') { this.value = this.title; } if (this.value == this.title) { addClass(this, "placeholder"); } } if (el.captureEvents) el.captureEvents(Event.BLUR); } } } } } addLoadEvent(initFormPlaceholders);
JavaScript
/* _/ _/_/ _/_/_/_/_/ _/ _/ _/ _/ _/_/ _/ _/ _/_/_/ _/_/_/ _/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/_/ _/_/_/ _/_/_/ _/ _/ _/ _/ Created by David Kaneda <http://www.davidkaneda.com> Documentation and issue tracking on Google Code <http://code.google.com/p/jqtouch/> Special thanks to Jonathan Stark <http://jonathanstark.com/> and pinch/zoom <http://www.pinchzoom.com/> (c) 2009 by jQTouch project members. See LICENSE.txt for license. */ (function($) { $.fn.transition = function(css, options) { return this.each(function(){ var $el = $(this); var defaults = { speed : '300ms', callback: null, ease: 'ease-in-out' }; var settings = $.extend({}, defaults, options); if(settings.speed === 0) { $el.css(css); window.setTimeout(settings.callback, 0); } else { if ($.browser.safari) { var s = []; for(var i in css) { s.push(i); } $el.css({ webkitTransitionProperty: s.join(", "), webkitTransitionDuration: settings.speed, webkitTransitionTimingFunction: settings.ease }); if (settings.callback) { $el.one('webkitTransitionEnd', settings.callback); } setTimeout(function(el){ el.css(css) }, 0, $el); } else { $el.animate(css, settings.speed, settings.callback); } } }); } })(jQuery);
JavaScript
/* _/ _/_/ _/_/_/_/_/ _/ _/ _/ _/ _/_/ _/ _/ _/_/_/ _/_/_/ _/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/ _/_/ _/_/_/ _/_/_/ _/ _/ _/ _/ Created by David Kaneda <http://www.davidkaneda.com> Documentation and issue tracking on Google Code <http://code.google.com/p/jqtouch/> Special thanks to Jonathan Stark <http://jonathanstark.com/> and pinch/zoom <http://www.pinchzoom.com/> (c) 2009 by jQTouch project members. See LICENSE.txt for license. $Revision: 109 $ $Date: 2009-10-06 12:23:30 -0400 (Tue, 06 Oct 2009) $ $LastChangedBy: davidcolbykaneda $ */ (function($) { $.jQTouch = function(options) { // Set support values $.support.WebKitCSSMatrix = (typeof WebKitCSSMatrix == "object"); $.support.touch = (typeof Touch == "object"); $.support.WebKitAnimationEvent = (typeof WebKitTransitionEvent == "object"); // Initialize internal variables var $body, $head=$('head'), hist=[], newPageCount=0, jQTSettings={}, hashCheck, currentPage, orientation, isMobileWebKit = RegExp(" Mobile/").test(navigator.userAgent), tapReady=true, lastAnimationTime=0, touchSelectors=[], publicObj={}, extensions=$.jQTouch.prototype.extensions, defaultAnimations=['slide','flip','slideup','swap','cube','pop','dissolve','fade','back'], animations=[], hairextensions=''; // Get the party started init(options); function init(options) { var defaults = { addGlossToIcon: true, backSelector: '.back, .cancel, .goback', cacheGetRequests: true, cubeSelector: '.cube', dissolveSelector: '.dissolve', fadeSelector: '.fade', fixedViewport: true, flipSelector: '.flip', formSelector: 'form', fullScreen: true, fullScreenClass: 'fullscreen', icon: null, touchSelector: 'a, .touch', popSelector: '.pop', preloadImages: false, slideSelector: 'body > * > ul li a', slideupSelector: '.slideup', startupScreen: null, statusBar: 'default', // other options: black-translucent, black submitSelector: '.submit', swapSelector: '.swap', useAnimations: true, useFastTouch: true // Experimental. }; jQTSettings = $.extend({}, defaults, options); // Preload images if (jQTSettings.preloadImages) { for (var i = jQTSettings.preloadImages.length - 1; i >= 0; i--){ (new Image()).src = jQTSettings.preloadImages[i]; }; } // Set icon if (jQTSettings.icon) { var precomposed = (jQTSettings.addGlossToIcon) ? '' : '-precomposed'; hairextensions += '<link rel="apple-touch-icon' + precomposed + '" href="' + jQTSettings.icon + '" />'; } // Set startup screen if (jQTSettings.startupScreen) { hairextensions += '<link rel="apple-touch-startup-image" href="' + jQTSettings.startupScreen + '" />'; } // Set viewport if (jQTSettings.fixedViewport) { hairextensions += '<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;"/>'; } // Set full-screen if (jQTSettings.fullScreen) { hairextensions += '<meta name="apple-mobile-web-app-capable" content="yes" />'; if (jQTSettings.statusBar) { hairextensions += '<meta name="apple-mobile-web-app-status-bar-style" content="' + jQTSettings.statusBar + '" />'; } } if (hairextensions) $head.append(hairextensions); // Initialize on document load: $(document).ready(function(){ // Add extensions for (var i in extensions) { var fn = extensions[i]; if ($.isFunction(fn)) { $.extend(publicObj, fn(publicObj)); } } // Add animations for (var i in defaultAnimations) { var name = defaultAnimations[i]; var selector = jQTSettings[name + 'Selector']; if (typeof(selector) == 'string') { addAnimation({name:name, selector:selector}); } } touchSelectors.push('input'); touchSelectors.push(jQTSettings.touchSelector); touchSelectors.push(jQTSettings.backSelector); touchSelectors.push(jQTSettings.submitSelector); $(touchSelectors.join(', ')).css('-webkit-touch-callout', 'none'); $(jQTSettings.backSelector).tap(liveTap); $(jQTSettings.submitSelector).tap(submitParentForm); $body = $('body'); if (jQTSettings.fullScreenClass && window.navigator.standalone == true) { $body.addClass(jQTSettings.fullScreenClass + ' ' + jQTSettings.statusBar); } // Create custom live events $body .bind('touchstart', handleTouch) .bind('orientationchange', updateOrientation) .trigger('orientationchange') .submit(submitForm); if (jQTSettings.useFastTouch && $.support.touch) { $body.click(function(e){ var $el = $(e.target); if ($el.attr('target') == '_blank' || $el.attr('rel') == 'external' || $el.is('input[type="checkbox"]')) { return true; } else { return false; } }); // This additionally gets rid of form focusses $body.mousedown(function(e){ var timeDiff = (new Date()).getTime() - lastAnimationTime; if (timeDiff < 200) { return false; } }); } // Make sure exactly one child of body has "current" class if ($('body > .current').length == 0) { currentPage = $('body > *:first'); } else { currentPage = $('body > .current:first'); $('body > .current').removeClass('current'); } // Go to the top of the "current" page $(currentPage).addClass('current'); location.hash = $(currentPage).attr('id'); addPageToHistory(currentPage); scrollTo(0, 0); dumbLoopStart(); }); } // PUBLIC FUNCTIONS function goBack(to) { // Init the param if (hist.length > 1) { var numberOfPages = Math.min(parseInt(to || 1, 10), hist.length-1); // Search through the history for an ID if( isNaN(numberOfPages) && typeof(to) === "string" && to != '#' ) { for( var i=1, length=hist.length; i < length; i++ ) { if( '#' + hist[i].id === to ) { numberOfPages = i; break; } } } // If still nothing, assume one if( isNaN(numberOfPages) || numberOfPages < 1 ) { numberOfPages = 1; }; // Grab the current page for the "from" info var animation = hist[0].animation; var fromPage = hist[0].page; // Remove all pages in front of the target page hist.splice(0, numberOfPages); // Grab the target page var toPage = hist[0].page; // Make the animations animatePages(fromPage, toPage, animation, true); return publicObj; } else { console.error('No pages in history.'); return false; } } function goTo(toPage, animation) { var fromPage = hist[0].page; if (typeof(toPage) === 'string') { toPage = $(toPage); } if (typeof(animation) === 'string') { for (var i = animations.length - 1; i >= 0; i--){ if (animations[i].name === animation) { animation = animations[i]; break; } } } if (animatePages(fromPage, toPage, animation)) { addPageToHistory(toPage, animation); return publicObj; } else { console.error('Could not animate pages.'); return false; } } function getOrientation() { return orientation; } // PRIVATE FUNCTIONS function liveTap(e){ // Grab the clicked element var $el = $(e.target); if ($el.attr('nodeName')!=='A'){ $el = $el.parent('a'); } var target = $el.attr('target'), hash = $el.attr('hash'), animation=null; if (tapReady == false || !$el.length) { console.warn('Not able to tap element.') return false; } if ($el.attr('target') == '_blank' || $el.attr('rel') == 'external') { return true; } // Figure out the animation to use for (var i = animations.length - 1; i >= 0; i--){ if ($el.is(animations[i].selector)) { animation = animations[i]; break; } }; // User clicked an internal link, fullscreen mode if (target == '_webapp') { window.location = $el.attr('href'); } // User clicked a back button else if ($el.is(jQTSettings.backSelector)) { goBack(hash); } // Branch on internal or external href else if (hash && hash!='#') { $el.addClass('active'); goTo($(hash).data('referrer', $el), animation); } else { $el.addClass('loading active'); showPageByHref($el.attr('href'), { animation: animation, callback: function(){ $el.removeClass('loading'); setTimeout($.fn.unselect, 250, $el); }, $referrer: $el }); } return false; } function addPageToHistory(page, animation) { // Grab some info var pageId = page.attr('id'); // Prepend info to page history hist.unshift({ page: page, animation: animation, id: pageId }); } function animatePages(fromPage, toPage, animation, backwards) { // Error check for target page if(toPage.length === 0){ $.fn.unselect(); console.error('Target element is missing.'); return false; } // Collapse the keyboard $(':focus').blur(); // Make sure we are scrolled up to hide location bar scrollTo(0, 0); // Define callback to run after animation completes var callback = function(event){ if (animation) { toPage.removeClass('in reverse ' + animation.name); fromPage.removeClass('current out reverse ' + animation.name); } else { fromPage.removeClass('current'); } toPage.trigger('pageAnimationEnd', { direction: 'in' }); fromPage.trigger('pageAnimationEnd', { direction: 'out' }); clearInterval(dumbLoop); currentPage = toPage; location.hash = currentPage.attr('id'); dumbLoopStart(); var $originallink = toPage.data('referrer'); if ($originallink) { $originallink.unselect(); } lastAnimationTime = (new Date()).getTime(); tapReady = true; } fromPage.trigger('pageAnimationStart', { direction: 'out' }); toPage.trigger('pageAnimationStart', { direction: 'in' }); if ($.support.WebKitAnimationEvent && animation && jQTSettings.useAnimations) { toPage.one('webkitAnimationEnd', callback); tapReady = false; toPage.addClass(animation.name + ' in current ' + (backwards ? ' reverse' : '')); fromPage.addClass(animation.name + ' out' + (backwards ? ' reverse' : '')); } else { toPage.addClass('current'); callback(); } return true; } function dumbLoopStart() { dumbLoop = setInterval(function(){ var curid = currentPage.attr('id'); if (location.hash == '') { location.hash = '#' + curid; } else if (location.hash != '#' + curid) { try { goBack(location.hash) } catch(e) { console.error('Unknown hash change.'); } } }, 100); } function insertPages(nodes, animation) { var targetPage = null; $(nodes).each(function(index, node){ var $node = $(this); if (!$node.attr('id')) { $node.attr('id', 'page-' + (++newPageCount)); } $node.appendTo($body); if ($node.hasClass('current') || !targetPage ) { targetPage = $node; } }); if (targetPage !== null) { goTo(targetPage, animation); return targetPage; } else { return false; } } function showPageByHref(href, options) { var defaults = { data: null, method: 'GET', animation: null, callback: null, $referrer: null }; var settings = $.extend({}, defaults, options); if (href != '#') { $.ajax({ url: href, data: settings.data, type: settings.method, success: function (data, textStatus) { var firstPage = insertPages(data, settings.animation); if (firstPage) { if (settings.method == 'GET' && jQTSettings.cacheGetRequests && settings.$referrer) { settings.$referrer.attr('href', '#' + firstPage.attr('id')); } if (settings.callback) { settings.callback(true); } } }, error: function (data) { if (settings.$referrer) settings.$referrer.unselect(); if (settings.callback) { settings.callback(false); } } }); } else if ($referrer) { $referrer.unselect(); } } function submitForm(e, callback){ var $form = (typeof(e)==='string') ? $(e) : $(e.target); if ($form.length && $form.is(jQTSettings.formSelector) && $form.attr('action')) { showPageByHref($form.attr('action'), { data: $form.serialize(), method: $form.attr('method') || "POST", animation: animations[0] || null, callback: callback }); return false; } return true; } function submitParentForm(e){ var $form = $(this).closest('form'); if ($form.length) { evt = jQuery.Event("submit"); evt.preventDefault(); $form.trigger(evt); return false; } return true; } function addAnimation(animation) { if (typeof(animation.selector) == 'string' && typeof(animation.name) == 'string') { animations.push(animation); $(animation.selector).tap(liveTap); touchSelectors.push(animation.selector); } } function updateOrientation() { orientation = window.innerWidth < window.innerHeight ? 'profile' : 'landscape'; $body.removeClass('profile landscape').addClass(orientation).trigger('turn', {orientation: orientation}); // scrollTo(0, 0); } function handleTouch(e) { var $el = $(e.target); // Only handle touchSelectors if (!$(e.target).is(touchSelectors.join(', '))) { var $link = $(e.target).closest('a'); if ($link.length){ $el = $link; } else { return; } } if (event) { var hoverTimeout = null, startX = event.changedTouches[0].clientX, startY = event.changedTouches[0].clientY, startTime = (new Date).getTime(), deltaX = 0, deltaY = 0, deltaT = 0; // Let's bind these after the fact, so we can keep some internal values $el.bind('touchmove', touchmove).bind('touchend', touchend); hoverTimeout = setTimeout(function(){ $el.makeActive(); }, 100); } // Private touch functions (TODO: insert dirty joke) function touchmove(e) { updateChanges(); var absX = Math.abs(deltaX); var absY = Math.abs(deltaY); // Check for swipe if (absX > absY && (absX > 35) && deltaT < 1000) { $el.trigger('swipe', {direction: (deltaX < 0) ? 'left' : 'right'}).unbind('touchmove touchend'); } else if (absY > 1) { $el.removeClass('active'); } clearTimeout(hoverTimeout); } function touchend(){ updateChanges(); if (deltaY === 0 && deltaX === 0) { $el.makeActive(); // New approach: // Fake the double click? // TODO: Try with all click events (no tap) // if (deltaT < 40) // { // setTimeout(function(){ // $el.trigger('touchstart') // .trigger('touchend'); // }, 0); // } $el.trigger('tap'); } else { $el.removeClass('active'); } $el.unbind('touchmove touchend'); clearTimeout(hoverTimeout); } function updateChanges(){ var first = event.changedTouches[0] || null; deltaX = first.pageX - startX; deltaY = first.pageY - startY; deltaT = (new Date).getTime() - startTime; } } // End touch handler // Public jQuery Fns $.fn.unselect = function(obj) { if (obj) { obj.removeClass('active'); } else { $('.active').removeClass('active'); } } $.fn.makeActive = function(){ return $(this).addClass('active'); } $.fn.swipe = function(fn) { if ($.isFunction(fn)) { return this.each(function(i, el){ $(el).bind('swipe', fn); }); } } $.fn.tap = function(fn){ if ($.isFunction(fn)) { var tapEvent = (jQTSettings.useFastTouch && $.support.touch) ? 'tap' : 'click'; return $(this).live(tapEvent, fn); } else { $(this).trigger('tap'); } } publicObj = { getOrientation: getOrientation, goBack: goBack, goTo: goTo, addAnimation: addAnimation, submitForm: submitForm } return publicObj; } // Extensions directly manipulate the jQTouch object, before it's initialized. $.jQTouch.prototype.extensions = []; $.jQTouch.addExtension = function(extension){ $.jQTouch.prototype.extensions.push(extension); } })(jQuery);
JavaScript
function initJQ() { $.jQTouch({ icon: '3txt.png', addGlossToIcon: false, preloadImages: [ 'themes/apple/img/chevron.png', 'themes/apple/img/back_button.png', 'themes/apple/img/button.png', 'themes/apple/img/pinstripes.png' ] }); } function noAjaxCache() { $.ajaxSetup ({ cache: false }); }
JavaScript
$.fn.delay = function(time, callback){ // Empty function: jQuery.fx.step.delay = function(){}; // Return meaningless animation, (will be added to queue) return this.animate({delay:1}, time, callback); }
JavaScript
function getWindowHeight() { var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; } function setContent() { if (document.getElementById) { var windowHeight = getWindowHeight(); if (windowHeight > 0) { var contentElement = document.getElementById('content'); var contentHeight = contentElement.offsetHeight; if (windowHeight - contentHeight > 0) { contentElement.style.position = 'relative'; contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px'; } else { contentElement.style.position = 'static'; } } } } window.onload = function() { setContent(); } window.onresize = function() { setContent(); }
JavaScript
/** * @author Alexandre Magno * @desc Center a element with jQuery * @version 1.0 * @example * $("element").center({ * * vertical: true, * horizontal: true * * }); * @obs With no arguments, the default is above * @license free * @param bool vertical, bool horizontal * @contribution Paulo Radichi * */ jQuery.fn.center = function(params) { var options = { vertical: true, horizontal: true } op = jQuery.extend(options, params); return this.each(function(){ //initializing variables var $self = jQuery(this); //get the dimensions using dimensions plugin var width = $self.width(); var height = $self.height(); //get the paddings var paddingTop = parseInt($self.css("padding-top")); var paddingBottom = parseInt($self.css("padding-bottom")); //get the borders var borderTop = parseInt($self.css("border-top-width")); var borderBottom = parseInt($self.css("border-bottom-width")); //get the media of padding and borders var mediaBorder = (borderTop+borderBottom)/2; var mediaPadding = (paddingTop+paddingBottom)/2; //get the type of positioning var positionType = $self.parent().css("position"); // get the half minus of width and height var halfWidth = (width/2)*(-1); var halfHeight = ((height/2)*(-1))-mediaPadding-mediaBorder; // initializing the css properties var cssProp = { position: 'absolute' }; if(op.vertical) { cssProp.height = height; cssProp.top = '50%'; cssProp.marginTop = halfHeight; } if(op.horizontal) { cssProp.width = width; cssProp.left = '50%'; cssProp.marginLeft = halfWidth; } //check the current position if(positionType == 'static') { $self.parent().css("position","relative"); } //aplying the css $self.css(cssProp); }); };
JavaScript
/* Project: Input Placeholder Text Title: Automatic population of form fields with contents of title attributes Author Jon Gibbins (aka dotjay) Created: 13 Aug 2005 Modified: 26 Oct 2009 Notes: Add the following classes to text inputs or textareas to get the desired behaviour: auto-select Will pre-populate the input with the title attribute and select the text when it receives focus. auto-clear Will pre-populate the input with the title attribute and clear the text when it receives focus. Note: if auto-select and auto-clear are set, auto-select takes precedence. populate Will just populate the input with the title attribute. NB: A class name of "placeholder" is set on form inputs that have placeholder text in them. This allows you to style the inputs differently when there is user input versus placeholder text, e.g. input.placeholder, textarea.placeholder{ color: #777; } Potential additions: Add in handling of default text if an initial value is detected (line 60, line 93, etc) using something like: if (!el.defaultValue) continue; el.onfocus = function() { if (this.value == this.defaultValue) this.value = ""; } el.onblur = function() { if (this.value == "") this.value = this.defaultValue; } */ function hasClass(el,cls) { return el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(el,cls) { if (!this.hasClass(el,cls)) el.className += " "+cls; } function removeClass(el,cls) { if (hasClass(el,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); el.className = el.className.replace(reg,' '); } } function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } function initFormPlaceholders() { if (!document.getElementsByTagName) return true; ourForms = document.getElementsByTagName('form'); // go through each form var numForms = ourForms.length; for (var i=0;i<numForms;i++) { // go through each form element var numFormElements = ourForms[i].elements.length; for (var j=0;j<numFormElements;j++) { var el = ourForms[i].elements[j]; // ignore submit buttons if (el.type == "submit") continue; // if we got a text type input or textarea if ((el.type == "text") || (el.type == "textarea")) { // only populate if we want it to // note: might want title attribute but no pre-population of inputs var ourClassName = el.className; if (ourClassName.match('auto-select') || ourClassName.match('auto-clear') || ourClassName.match('populate')) { // only populate if empty if (el.value == '') { addClass(el, "placeholder"); el.value = el.title; } } // add auto select if class contains auto-select // note: else if below so auto-select takes precedence (assuming select is better than clear) if (el.className.match('auto-select')) { el.onfocus = function () { if (this.value == this.title) { removeClass(this, "placeholder"); this.select(); } } if (el.captureEvents) el.captureEvents(Event.FOCUS); el.onblur = function () { if (this.value == '') { this.value = this.title; } if (this.value == this.title) { addClass(this, "placeholder"); } } if (el.captureEvents) el.captureEvents(Event.BLUR); } // add auto clear if class contains auto-clear else if (el.className.match('auto-clear')) { el.onfocus = function () { if (this.value == this.title) { removeClass(this, "placeholder"); this.value = ''; } } if (el.captureEvents) el.captureEvents(Event.FOCUS); el.onblur = function () { if (this.value == '') { this.value = this.title; } if (this.value == this.title) { addClass(this, "placeholder"); } } if (el.captureEvents) el.captureEvents(Event.BLUR); } } } } } addLoadEvent(initFormPlaceholders);
JavaScript
/*! * jQuery doTimeout: Like setTimeout, but better! - v1.0 - 3/3/2010 * http://benalman.com/projects/jquery-dotimeout-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery doTimeout: Like setTimeout, but better! // // *Version: 1.0, Last updated: 3/3/2010* // // Project Home - http://benalman.com/projects/jquery-dotimeout-plugin/ // GitHub - http://github.com/cowboy/jquery-dotimeout/ // Source - http://github.com/cowboy/jquery-dotimeout/raw/master/jquery.ba-dotimeout.js // (Minified) - http://github.com/cowboy/jquery-dotimeout/raw/master/jquery.ba-dotimeout.min.js (1.0kb) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // Debouncing - http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/ // Delays, Polling - http://benalman.com/code/projects/jquery-dotimeout/examples/delay-poll/ // Hover Intent - http://benalman.com/code/projects/jquery-dotimeout/examples/hoverintent/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.3.2, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome 4-5, Opera 9.6-10.1. // Unit Tests - http://benalman.com/code/projects/jquery-dotimeout/unit/ // // About: Release History // // 1.0 - (3/3/2010) Callback can now be a string, in which case it will call // the appropriate $.method or $.fn.method, depending on where .doTimeout // was called. Callback must now return `true` (not just a truthy value) // to poll. // 0.4 - (7/15/2009) Made the "id" argument optional, some other minor tweaks // 0.3 - (6/25/2009) Initial release (function($){ '$:nomunge'; // Used by YUI compressor. var cache = {}, // Reused internal string. doTimeout = 'doTimeout', // A convenient shortcut. aps = Array.prototype.slice; // Method: jQuery.doTimeout // // Initialize, cancel, or force execution of a callback after a delay. // // If delay and callback are specified, a doTimeout is initialized. The // callback will execute, asynchronously, after the delay. If an id is // specified, this doTimeout will override and cancel any existing doTimeout // with the same id. Any additional arguments will be passed into callback // when it is executed. // // If the callback returns true, the doTimeout loop will execute again, after // the delay, creating a polling loop until the callback returns a non-true // value. // // Note that if an id is not passed as the first argument, this doTimeout will // NOT be able to be manually canceled or forced. (for debouncing, be sure to // specify an id). // // If id is specified, but delay and callback are not, the doTimeout will be // canceled without executing the callback. If force_mode is specified, the // callback will be executed, synchronously, but will only be allowed to // continue a polling loop if force_mode is true (provided the callback // returns true, of course). If force_mode is false, no polling loop will // continue, even if the callback returns true. // // Usage: // // > jQuery.doTimeout( [ id, ] delay, callback [, arg ... ] ); // > jQuery.doTimeout( id [, force_mode ] ); // // Arguments: // // id - (String) An optional unique identifier for this doTimeout. If id is // not specified, the doTimeout will NOT be able to be manually canceled or // forced. // delay - (Number) A zero-or-greater delay in milliseconds after which // callback will be executed. // callback - (Function) A function to be executed after delay milliseconds. // callback - (String) A jQuery method to be executed after delay // milliseconds. This method will only poll if it explicitly returns // true. // force_mode - (Boolean) If true, execute that id's doTimeout callback // immediately and synchronously, continuing any callback return-true // polling loop. If false, execute the callback immediately and // synchronously but do NOT continue a callback return-true polling loop. // If omitted, cancel that id's doTimeout. // // Returns: // // If force_mode is true, false or undefined and there is a // yet-to-be-executed callback to cancel, true is returned, but if no // callback remains to be executed, undefined is returned. $[doTimeout] = function() { return p_doTimeout.apply( window, [ 0 ].concat( aps.call( arguments ) ) ); }; // Method: jQuery.fn.doTimeout // // Initialize, cancel, or force execution of a callback after a delay. // Operates like <jQuery.doTimeout>, but the passed callback executes in the // context of the jQuery collection of elements, and the id is stored as data // on the first element in that collection. // // If delay and callback are specified, a doTimeout is initialized. The // callback will execute, asynchronously, after the delay. If an id is // specified, this doTimeout will override and cancel any existing doTimeout // with the same id. Any additional arguments will be passed into callback // when it is executed. // // If the callback returns true, the doTimeout loop will execute again, after // the delay, creating a polling loop until the callback returns a non-true // value. // // Note that if an id is not passed as the first argument, this doTimeout will // NOT be able to be manually canceled or forced (for debouncing, be sure to // specify an id). // // If id is specified, but delay and callback are not, the doTimeout will be // canceled without executing the callback. If force_mode is specified, the // callback will be executed, synchronously, but will only be allowed to // continue a polling loop if force_mode is true (provided the callback // returns true, of course). If force_mode is false, no polling loop will // continue, even if the callback returns true. // // Usage: // // > jQuery('selector').doTimeout( [ id, ] delay, callback [, arg ... ] ); // > jQuery('selector').doTimeout( id [, force_mode ] ); // // Arguments: // // id - (String) An optional unique identifier for this doTimeout, stored as // jQuery data on the element. If id is not specified, the doTimeout will // NOT be able to be manually canceled or forced. // delay - (Number) A zero-or-greater delay in milliseconds after which // callback will be executed. // callback - (Function) A function to be executed after delay milliseconds. // callback - (String) A jQuery.fn method to be executed after delay // milliseconds. This method will only poll if it explicitly returns // true (most jQuery.fn methods return a jQuery object, and not `true`, // which allows them to be chained and prevents polling). // force_mode - (Boolean) If true, execute that id's doTimeout callback // immediately and synchronously, continuing any callback return-true // polling loop. If false, execute the callback immediately and // synchronously but do NOT continue a callback return-true polling loop. // If omitted, cancel that id's doTimeout. // // Returns: // // When creating a <jQuery.fn.doTimeout>, the initial jQuery collection of // elements is returned. Otherwise, if force_mode is true, false or undefined // and there is a yet-to-be-executed callback to cancel, true is returned, // but if no callback remains to be executed, undefined is returned. $.fn[doTimeout] = function() { var args = aps.call( arguments ), result = p_doTimeout.apply( this, [ doTimeout + args[0] ].concat( args ) ); return typeof args[0] === 'number' || typeof args[1] === 'number' ? this : result; }; function p_doTimeout( jquery_data_key ) { var that = this, elem, data = {}, // Allows the plugin to call a string callback method. method_base = jquery_data_key ? $.fn : $, // Any additional arguments will be passed to the callback. args = arguments, slice_args = 4, id = args[1], delay = args[2], callback = args[3]; if ( typeof id !== 'string' ) { slice_args--; id = jquery_data_key = 0; delay = args[1]; callback = args[2]; } // If id is passed, store a data reference either as .data on the first // element in a jQuery collection, or in the internal cache. if ( jquery_data_key ) { // Note: key is 'doTimeout' + id // Get id-object from the first element's data, otherwise initialize it to {}. elem = that.eq(0); elem.data( jquery_data_key, data = elem.data( jquery_data_key ) || {} ); } else if ( id ) { // Get id-object from the cache, otherwise initialize it to {}. data = cache[ id ] || ( cache[ id ] = {} ); } // Clear any existing timeout for this id. data.id && clearTimeout( data.id ); delete data.id; // Clean up when necessary. function cleanup() { if ( jquery_data_key ) { elem.removeData( jquery_data_key ); } else if ( id ) { delete cache[ id ]; } }; // Yes, there actually is a setTimeout call in here! function actually_setTimeout() { data.id = setTimeout( function(){ data.fn(); }, delay ); }; if ( callback ) { // A callback (and delay) were specified. Store the callback reference for // possible later use, and then setTimeout. data.fn = function( no_polling_loop ) { // If the callback value is a string, it is assumed to be the name of a // method on $ or $.fn depending on where doTimeout was executed. if ( typeof callback === 'string' ) { callback = method_base[ callback ]; } callback.apply( that, aps.call( args, slice_args ) ) === true && !no_polling_loop // Since the callback returned true, and we're not specifically // canceling a polling loop, do it again! ? actually_setTimeout() // Otherwise, clean up and quit. : cleanup(); }; // Set that timeout! actually_setTimeout(); } else if ( data.fn ) { // No callback passed. If force_mode (delay) is true, execute the data.fn // callback immediately, continuing any callback return-true polling loop. // If force_mode is false, execute the data.fn callback immediately but do // NOT continue a callback return-true polling loop. If force_mode is // undefined, simply clean up. Since data.fn was still defined, whatever // was supposed to happen hadn't yet, so return true. delay === undefined ? cleanup() : data.fn( delay === false ); return true; } else { // Since no callback was passed, and data.fn isn't defined, it looks like // whatever was supposed to happen already did. Clean up and quit! cleanup(); } }; })(jQuery);
JavaScript
function getWindowHeight() { var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; } function setContent() { if (document.getElementById) { var windowHeight = getWindowHeight(); if (windowHeight > 0) { var contentElement = document.getElementById('content'); var contentHeight = contentElement.offsetHeight; if (windowHeight - contentHeight > 0) { contentElement.style.position = 'relative'; contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px'; } else { contentElement.style.position = 'static'; } } } } window.onload = function() { setContent(); } window.onresize = function() { setContent(); }
JavaScript
function getWindowHeight() { var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; } function setContent() { if (document.getElementById) { var windowHeight = getWindowHeight(); if (windowHeight > 0) { var contentElement = document.getElementById('content'); var contentHeight = contentElement.offsetHeight; if (windowHeight - contentHeight > 0) { contentElement.style.position = 'relative'; contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px'; } else { contentElement.style.position = 'static'; } } } } window.onload = function() { setContent(); } window.onresize = function() { setContent(); }
JavaScript
/** * @author Alexandre Magno * @desc Center a element with jQuery * @version 1.0 * @example * $("element").center({ * * vertical: true, * horizontal: true * * }); * @obs With no arguments, the default is above * @license free * @param bool vertical, bool horizontal * @contribution Paulo Radichi * */ jQuery.fn.center = function(params) { var options = { vertical: true, horizontal: true } op = jQuery.extend(options, params); return this.each(function(){ //initializing variables var $self = jQuery(this); //get the dimensions using dimensions plugin var width = $self.width(); var height = $self.height(); //get the paddings var paddingTop = parseInt($self.css("padding-top")); var paddingBottom = parseInt($self.css("padding-bottom")); //get the borders var borderTop = parseInt($self.css("border-top-width")); var borderBottom = parseInt($self.css("border-bottom-width")); //get the media of padding and borders var mediaBorder = (borderTop+borderBottom)/2; var mediaPadding = (paddingTop+paddingBottom)/2; //get the type of positioning var positionType = $self.parent().css("position"); // get the half minus of width and height var halfWidth = (width/2)*(-1); var halfHeight = ((height/2)*(-1))-mediaPadding-mediaBorder; // initializing the css properties var cssProp = { position: 'absolute' }; if(op.vertical) { cssProp.height = height; cssProp.top = '50%'; cssProp.marginTop = halfHeight; } if(op.horizontal) { cssProp.width = width; cssProp.left = '50%'; cssProp.marginLeft = halfWidth; } //check the current position if(positionType == 'static') { $self.parent().css("position","relative"); } //aplying the css $self.css(cssProp); }); };
JavaScript
/* Project: Input Placeholder Text Title: Automatic population of form fields with contents of title attributes Author Jon Gibbins (aka dotjay) Created: 13 Aug 2005 Modified: 26 Oct 2009 Notes: Add the following classes to text inputs or textareas to get the desired behaviour: auto-select Will pre-populate the input with the title attribute and select the text when it receives focus. auto-clear Will pre-populate the input with the title attribute and clear the text when it receives focus. Note: if auto-select and auto-clear are set, auto-select takes precedence. populate Will just populate the input with the title attribute. NB: A class name of "placeholder" is set on form inputs that have placeholder text in them. This allows you to style the inputs differently when there is user input versus placeholder text, e.g. input.placeholder, textarea.placeholder{ color: #777; } Potential additions: Add in handling of default text if an initial value is detected (line 60, line 93, etc) using something like: if (!el.defaultValue) continue; el.onfocus = function() { if (this.value == this.defaultValue) this.value = ""; } el.onblur = function() { if (this.value == "") this.value = this.defaultValue; } */ function hasClass(el,cls) { return el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(el,cls) { if (!this.hasClass(el,cls)) el.className += " "+cls; } function removeClass(el,cls) { if (hasClass(el,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); el.className = el.className.replace(reg,' '); } } function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } function initFormPlaceholders() { if (!document.getElementsByTagName) return true; ourForms = document.getElementsByTagName('form'); // go through each form var numForms = ourForms.length; for (var i=0;i<numForms;i++) { // go through each form element var numFormElements = ourForms[i].elements.length; for (var j=0;j<numFormElements;j++) { var el = ourForms[i].elements[j]; // ignore submit buttons if (el.type == "submit") continue; // if we got a text type input or textarea if ((el.type == "text") || (el.type == "textarea")) { // only populate if we want it to // note: might want title attribute but no pre-population of inputs var ourClassName = el.className; if (ourClassName.match('auto-select') || ourClassName.match('auto-clear') || ourClassName.match('populate')) { // only populate if empty if (el.value == '') { addClass(el, "placeholder"); el.value = el.title; } } // add auto select if class contains auto-select // note: else if below so auto-select takes precedence (assuming select is better than clear) if (el.className.match('auto-select')) { el.onfocus = function () { if (this.value == this.title) { removeClass(this, "placeholder"); this.select(); } } if (el.captureEvents) el.captureEvents(Event.FOCUS); el.onblur = function () { if (this.value == '') { this.value = this.title; } if (this.value == this.title) { addClass(this, "placeholder"); } } if (el.captureEvents) el.captureEvents(Event.BLUR); } // add auto clear if class contains auto-clear else if (el.className.match('auto-clear')) { el.onfocus = function () { if (this.value == this.title) { removeClass(this, "placeholder"); this.value = ''; } } if (el.captureEvents) el.captureEvents(Event.FOCUS); el.onblur = function () { if (this.value == '') { this.value = this.title; } if (this.value == this.title) { addClass(this, "placeholder"); } } if (el.captureEvents) el.captureEvents(Event.BLUR); } } } } } addLoadEvent(initFormPlaceholders);
JavaScript
/*! * jQuery doTimeout: Like setTimeout, but better! - v1.0 - 3/3/2010 * http://benalman.com/projects/jquery-dotimeout-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery doTimeout: Like setTimeout, but better! // // *Version: 1.0, Last updated: 3/3/2010* // // Project Home - http://benalman.com/projects/jquery-dotimeout-plugin/ // GitHub - http://github.com/cowboy/jquery-dotimeout/ // Source - http://github.com/cowboy/jquery-dotimeout/raw/master/jquery.ba-dotimeout.js // (Minified) - http://github.com/cowboy/jquery-dotimeout/raw/master/jquery.ba-dotimeout.min.js (1.0kb) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // Debouncing - http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/ // Delays, Polling - http://benalman.com/code/projects/jquery-dotimeout/examples/delay-poll/ // Hover Intent - http://benalman.com/code/projects/jquery-dotimeout/examples/hoverintent/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.3.2, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome 4-5, Opera 9.6-10.1. // Unit Tests - http://benalman.com/code/projects/jquery-dotimeout/unit/ // // About: Release History // // 1.0 - (3/3/2010) Callback can now be a string, in which case it will call // the appropriate $.method or $.fn.method, depending on where .doTimeout // was called. Callback must now return `true` (not just a truthy value) // to poll. // 0.4 - (7/15/2009) Made the "id" argument optional, some other minor tweaks // 0.3 - (6/25/2009) Initial release (function($){ '$:nomunge'; // Used by YUI compressor. var cache = {}, // Reused internal string. doTimeout = 'doTimeout', // A convenient shortcut. aps = Array.prototype.slice; // Method: jQuery.doTimeout // // Initialize, cancel, or force execution of a callback after a delay. // // If delay and callback are specified, a doTimeout is initialized. The // callback will execute, asynchronously, after the delay. If an id is // specified, this doTimeout will override and cancel any existing doTimeout // with the same id. Any additional arguments will be passed into callback // when it is executed. // // If the callback returns true, the doTimeout loop will execute again, after // the delay, creating a polling loop until the callback returns a non-true // value. // // Note that if an id is not passed as the first argument, this doTimeout will // NOT be able to be manually canceled or forced. (for debouncing, be sure to // specify an id). // // If id is specified, but delay and callback are not, the doTimeout will be // canceled without executing the callback. If force_mode is specified, the // callback will be executed, synchronously, but will only be allowed to // continue a polling loop if force_mode is true (provided the callback // returns true, of course). If force_mode is false, no polling loop will // continue, even if the callback returns true. // // Usage: // // > jQuery.doTimeout( [ id, ] delay, callback [, arg ... ] ); // > jQuery.doTimeout( id [, force_mode ] ); // // Arguments: // // id - (String) An optional unique identifier for this doTimeout. If id is // not specified, the doTimeout will NOT be able to be manually canceled or // forced. // delay - (Number) A zero-or-greater delay in milliseconds after which // callback will be executed. // callback - (Function) A function to be executed after delay milliseconds. // callback - (String) A jQuery method to be executed after delay // milliseconds. This method will only poll if it explicitly returns // true. // force_mode - (Boolean) If true, execute that id's doTimeout callback // immediately and synchronously, continuing any callback return-true // polling loop. If false, execute the callback immediately and // synchronously but do NOT continue a callback return-true polling loop. // If omitted, cancel that id's doTimeout. // // Returns: // // If force_mode is true, false or undefined and there is a // yet-to-be-executed callback to cancel, true is returned, but if no // callback remains to be executed, undefined is returned. $[doTimeout] = function() { return p_doTimeout.apply( window, [ 0 ].concat( aps.call( arguments ) ) ); }; // Method: jQuery.fn.doTimeout // // Initialize, cancel, or force execution of a callback after a delay. // Operates like <jQuery.doTimeout>, but the passed callback executes in the // context of the jQuery collection of elements, and the id is stored as data // on the first element in that collection. // // If delay and callback are specified, a doTimeout is initialized. The // callback will execute, asynchronously, after the delay. If an id is // specified, this doTimeout will override and cancel any existing doTimeout // with the same id. Any additional arguments will be passed into callback // when it is executed. // // If the callback returns true, the doTimeout loop will execute again, after // the delay, creating a polling loop until the callback returns a non-true // value. // // Note that if an id is not passed as the first argument, this doTimeout will // NOT be able to be manually canceled or forced (for debouncing, be sure to // specify an id). // // If id is specified, but delay and callback are not, the doTimeout will be // canceled without executing the callback. If force_mode is specified, the // callback will be executed, synchronously, but will only be allowed to // continue a polling loop if force_mode is true (provided the callback // returns true, of course). If force_mode is false, no polling loop will // continue, even if the callback returns true. // // Usage: // // > jQuery('selector').doTimeout( [ id, ] delay, callback [, arg ... ] ); // > jQuery('selector').doTimeout( id [, force_mode ] ); // // Arguments: // // id - (String) An optional unique identifier for this doTimeout, stored as // jQuery data on the element. If id is not specified, the doTimeout will // NOT be able to be manually canceled or forced. // delay - (Number) A zero-or-greater delay in milliseconds after which // callback will be executed. // callback - (Function) A function to be executed after delay milliseconds. // callback - (String) A jQuery.fn method to be executed after delay // milliseconds. This method will only poll if it explicitly returns // true (most jQuery.fn methods return a jQuery object, and not `true`, // which allows them to be chained and prevents polling). // force_mode - (Boolean) If true, execute that id's doTimeout callback // immediately and synchronously, continuing any callback return-true // polling loop. If false, execute the callback immediately and // synchronously but do NOT continue a callback return-true polling loop. // If omitted, cancel that id's doTimeout. // // Returns: // // When creating a <jQuery.fn.doTimeout>, the initial jQuery collection of // elements is returned. Otherwise, if force_mode is true, false or undefined // and there is a yet-to-be-executed callback to cancel, true is returned, // but if no callback remains to be executed, undefined is returned. $.fn[doTimeout] = function() { var args = aps.call( arguments ), result = p_doTimeout.apply( this, [ doTimeout + args[0] ].concat( args ) ); return typeof args[0] === 'number' || typeof args[1] === 'number' ? this : result; }; function p_doTimeout( jquery_data_key ) { var that = this, elem, data = {}, // Allows the plugin to call a string callback method. method_base = jquery_data_key ? $.fn : $, // Any additional arguments will be passed to the callback. args = arguments, slice_args = 4, id = args[1], delay = args[2], callback = args[3]; if ( typeof id !== 'string' ) { slice_args--; id = jquery_data_key = 0; delay = args[1]; callback = args[2]; } // If id is passed, store a data reference either as .data on the first // element in a jQuery collection, or in the internal cache. if ( jquery_data_key ) { // Note: key is 'doTimeout' + id // Get id-object from the first element's data, otherwise initialize it to {}. elem = that.eq(0); elem.data( jquery_data_key, data = elem.data( jquery_data_key ) || {} ); } else if ( id ) { // Get id-object from the cache, otherwise initialize it to {}. data = cache[ id ] || ( cache[ id ] = {} ); } // Clear any existing timeout for this id. data.id && clearTimeout( data.id ); delete data.id; // Clean up when necessary. function cleanup() { if ( jquery_data_key ) { elem.removeData( jquery_data_key ); } else if ( id ) { delete cache[ id ]; } }; // Yes, there actually is a setTimeout call in here! function actually_setTimeout() { data.id = setTimeout( function(){ data.fn(); }, delay ); }; if ( callback ) { // A callback (and delay) were specified. Store the callback reference for // possible later use, and then setTimeout. data.fn = function( no_polling_loop ) { // If the callback value is a string, it is assumed to be the name of a // method on $ or $.fn depending on where doTimeout was executed. if ( typeof callback === 'string' ) { callback = method_base[ callback ]; } callback.apply( that, aps.call( args, slice_args ) ) === true && !no_polling_loop // Since the callback returned true, and we're not specifically // canceling a polling loop, do it again! ? actually_setTimeout() // Otherwise, clean up and quit. : cleanup(); }; // Set that timeout! actually_setTimeout(); } else if ( data.fn ) { // No callback passed. If force_mode (delay) is true, execute the data.fn // callback immediately, continuing any callback return-true polling loop. // If force_mode is false, execute the data.fn callback immediately but do // NOT continue a callback return-true polling loop. If force_mode is // undefined, simply clean up. Since data.fn was still defined, whatever // was supposed to happen hadn't yet, so return true. delay === undefined ? cleanup() : data.fn( delay === false ); return true; } else { // Since no callback was passed, and data.fn isn't defined, it looks like // whatever was supposed to happen already did. Clean up and quit! cleanup(); } }; })(jQuery);
JavaScript
function getWindowHeight() { var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; } function setContent() { if (document.getElementById) { var windowHeight = getWindowHeight(); if (windowHeight > 0) { var contentElement = document.getElementById('content'); var contentHeight = contentElement.offsetHeight; if (windowHeight - contentHeight > 0) { contentElement.style.position = 'relative'; contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px'; } else { contentElement.style.position = 'static'; } } } } window.onload = function() { setContent(); } window.onresize = function() { setContent(); }
JavaScript
function getWindowHeight() { var windowHeight = 0; if (typeof(window.innerHeight) == 'number') { windowHeight = window.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else { if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } } } return windowHeight; } function setContent() { if (document.getElementById) { var windowHeight = getWindowHeight(); if (windowHeight > 0) { var contentElement = document.getElementById('content'); var contentHeight = contentElement.offsetHeight; if (windowHeight - contentHeight > 0) { contentElement.style.position = 'relative'; contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px'; } else { contentElement.style.position = 'static'; } } } } window.onload = function() { setContent(); } window.onresize = function() { setContent(); }
JavaScript
/** * @author Alexandre Magno * @desc Center a element with jQuery * @version 1.0 * @example * $("element").center({ * * vertical: true, * horizontal: true * * }); * @obs With no arguments, the default is above * @license free * @param bool vertical, bool horizontal * @contribution Paulo Radichi * */ jQuery.fn.center = function(params) { var options = { vertical: true, horizontal: true } op = jQuery.extend(options, params); return this.each(function(){ //initializing variables var $self = jQuery(this); //get the dimensions using dimensions plugin var width = $self.width(); var height = $self.height(); //get the paddings var paddingTop = parseInt($self.css("padding-top")); var paddingBottom = parseInt($self.css("padding-bottom")); //get the borders var borderTop = parseInt($self.css("border-top-width")); var borderBottom = parseInt($self.css("border-bottom-width")); //get the media of padding and borders var mediaBorder = (borderTop+borderBottom)/2; var mediaPadding = (paddingTop+paddingBottom)/2; //get the type of positioning var positionType = $self.parent().css("position"); // get the half minus of width and height var halfWidth = (width/2)*(-1); var halfHeight = ((height/2)*(-1))-mediaPadding-mediaBorder; // initializing the css properties var cssProp = { position: 'absolute' }; if(op.vertical) { cssProp.height = height; cssProp.top = '50%'; cssProp.marginTop = halfHeight; } if(op.horizontal) { cssProp.width = width; cssProp.left = '50%'; cssProp.marginLeft = halfWidth; } //check the current position if(positionType == 'static') { $self.parent().css("position","relative"); } //aplying the css $self.css(cssProp); }); };
JavaScript
/* Project: Input Placeholder Text Title: Automatic population of form fields with contents of title attributes Author Jon Gibbins (aka dotjay) Created: 13 Aug 2005 Modified: 26 Oct 2009 Notes: Add the following classes to text inputs or textareas to get the desired behaviour: auto-select Will pre-populate the input with the title attribute and select the text when it receives focus. auto-clear Will pre-populate the input with the title attribute and clear the text when it receives focus. Note: if auto-select and auto-clear are set, auto-select takes precedence. populate Will just populate the input with the title attribute. NB: A class name of "placeholder" is set on form inputs that have placeholder text in them. This allows you to style the inputs differently when there is user input versus placeholder text, e.g. input.placeholder, textarea.placeholder{ color: #777; } Potential additions: Add in handling of default text if an initial value is detected (line 60, line 93, etc) using something like: if (!el.defaultValue) continue; el.onfocus = function() { if (this.value == this.defaultValue) this.value = ""; } el.onblur = function() { if (this.value == "") this.value = this.defaultValue; } */ function hasClass(el,cls) { return el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(el,cls) { if (!this.hasClass(el,cls)) el.className += " "+cls; } function removeClass(el,cls) { if (hasClass(el,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); el.className = el.className.replace(reg,' '); } } function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } function initFormPlaceholders() { if (!document.getElementsByTagName) return true; ourForms = document.getElementsByTagName('form'); // go through each form var numForms = ourForms.length; for (var i=0;i<numForms;i++) { // go through each form element var numFormElements = ourForms[i].elements.length; for (var j=0;j<numFormElements;j++) { var el = ourForms[i].elements[j]; // ignore submit buttons if (el.type == "submit") continue; // if we got a text type input or textarea if ((el.type == "text") || (el.type == "textarea")) { // only populate if we want it to // note: might want title attribute but no pre-population of inputs var ourClassName = el.className; if (ourClassName.match('auto-select') || ourClassName.match('auto-clear') || ourClassName.match('populate')) { // only populate if empty if (el.value == '') { addClass(el, "placeholder"); el.value = el.title; } } // add auto select if class contains auto-select // note: else if below so auto-select takes precedence (assuming select is better than clear) if (el.className.match('auto-select')) { el.onfocus = function () { if (this.value == this.title) { removeClass(this, "placeholder"); this.select(); } } if (el.captureEvents) el.captureEvents(Event.FOCUS); el.onblur = function () { if (this.value == '') { this.value = this.title; } if (this.value == this.title) { addClass(this, "placeholder"); } } if (el.captureEvents) el.captureEvents(Event.BLUR); } // add auto clear if class contains auto-clear else if (el.className.match('auto-clear')) { el.onfocus = function () { if (this.value == this.title) { removeClass(this, "placeholder"); this.value = ''; } } if (el.captureEvents) el.captureEvents(Event.FOCUS); el.onblur = function () { if (this.value == '') { this.value = this.title; } if (this.value == this.title) { addClass(this, "placeholder"); } } if (el.captureEvents) el.captureEvents(Event.BLUR); } } } } } addLoadEvent(initFormPlaceholders);
JavaScript
function toggle(div_id) { var el = document.getElementById(div_id); if (el.style.display == 'none') { el.style.display = 'block'; } else { el.style.display = 'none'; } } function blanket_size(popUpDivVar) { if (typeof window.innerWidth != 'undefined') { viewportheight = window.innerHeight; } else { viewportheight = document.documentElement.clientHeight; } if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) { blanket_height = viewportheight; } else { if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) { blanket_height = document.body.parentNode.clientHeight; } else { blanket_height = document.body.parentNode.scrollHeight; } } var blanket = document.getElementById('blanket'); blanket.style.height = blanket_height + 'px'; var popUpDiv = document.getElementById(popUpDivVar); popUpDiv_height = blanket_height / 2 - 150; //150 is half popup's height popUpDiv.style.top = popUpDiv_height + 'px'; } function window_pos(popUpDivVar) { if (typeof window.innerWidth != 'undefined') { viewportwidth = window.innerHeight; } else { viewportwidth = document.documentElement.clientHeight; } if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) { window_width = viewportwidth; } else { if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) { window_width = document.body.parentNode.clientWidth; } else { window_width = document.body.parentNode.scrollWidth; } } var popUpDiv = document.getElementById(popUpDivVar); window_width = window_width / 2 - 150; //150 is half popup's width popUpDiv.style.left = window_width + 'px'; } function popup(windowname) { blanket_size(windowname); window_pos(windowname); toggle('blanket'); toggle(windowname); }
JavaScript
$(document).ready( function () { if($.browser.msie){ $('.menu_wrap').css({'background-color' : '#b8e1fc','position' : 'absolute','width' : '100%'}); } $('.menu_wrap').css({'opacity' : '0.3'}); $('.menu_wrap').hover ( function () { $(this).animate({'margin-top' : '0px','opacity' : '1'}); $('.menu_buttons img').animate({'opacity' : '.5'}); }, function () { $(this).animate({'margin-top' : '-30px','opacity' : '0.3'}); }); $('.menu_buttons img').hover ( function () { $(this).animate({'opacity' : '1'}); }, function () { $(this).animate({'opacity' : '0.5'}); }); });
JavaScript
// JavaScript Document $(document).ready(function() { /* 1st example */ /// wrap inner content of each anchor with first layer and append background layer $("#menus li a").wrapInner( '<span class="out"></span>' ).append( '<span class="bg"></span>' ); // loop each anchor and add copy of text content $("#menus li a").each(function() { $( '<span class="over">' + $(this).text() + '</span>' ).appendTo( this ); }); $("#menus li a").hover(function() { // this function is fired when the mouse is moved over $(".out", this).stop().animate({'top': '45px'}, 250); // move down - hide $(".over", this).stop().animate({'top': '0px'}, 250); // move down - show $(".bg", this).stop().animate({'top': '0px'}, 120); // move down - show }, function() { // this function is fired when the mouse is moved off $(".out", this).stop().animate({'top': '0px'}, 250); // move up - show $(".over", this).stop().animate({'top': '-45px'}, 250); // move up - hide $(".bg", this).stop().animate({'top': '-45px'}, 120); // move up - hide }); /* 2nd example */ $("#menus2 li a").wrapInner( '<span class="out"></span>' ); $("#menus2 li a").each(function() { $( '<span class="over">' + $(this).text() + '</span>' ).appendTo( this ); }); $("#menus2 li a").hover(function() { $(".out", this).stop().animate({'top': '45px'}, 200); // move down - hide $(".over", this).stop().animate({'top': '0px'}, 200); // move down - show }, function() { $(".out", this).stop().animate({'top': '0px'}, 200); // move up - show $(".over", this).stop().animate({'top': '-45px'}, 200); // move up - hide }); });
JavaScript
function getCookie( name ) { var start = document.cookie.indexOf( name + "=" ); var len = start + name.length + 1; if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null; } if ( start == -1 ) return null; var end = document.cookie.indexOf( ';', len ); if ( end == -1 ) end = document.cookie.length; return unescape( document.cookie.substring( len, end ) ); } function setCookie(name, value, expires) { document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString()); } var exp = new Date(); exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30)); function setActivestyleSheet(pTitle) { var vLoop, vLink; for(vLoop=0; (vLink = document.getElementsByTagName("link")[vLoop]); vLoop++) { if(vLink.getAttribute("rel").indexOf("style")!= -1 && vLink.getAttribute("title")) { vLink.disabled = true; if(vLink.getAttribute("title") == pTitle) vLink.disabled = false; } } } function ChennaigsmStyle(pTitle) { setActivestyleSheet(pTitle) setCookie("mysheet",pTitle, exp); } var pTitle=getCookie("mysheet") setActivestyleSheet(pTitle)
JavaScript
//Style Sheet Switcher version 1.1 Oct 10th, 2006 //Author: Dynamic Drive: http://www.dynamicdrive.com //Usage terms: http://www.dynamicdrive.com/notice.htm var manual_or_random="manual" //"manual" or "random" var randomsetting="3 days" //"eachtime", "sessiononly", or "x days (replace x with desired integer)". Only applicable if mode is random. //////No need to edit beyond here////////////// function getCookie(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 } function setCookie(name, value, days) { var expireDate = new Date() //set "expstring" to either future or past date, to set or delete cookie, respectively var expstring=(typeof days!="undefined")? expireDate.setDate(expireDate.getDate()+parseInt(days)) : expireDate.setDate(expireDate.getDate()-5) document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/"; } function deleteCookie(name){ setCookie(name, "moot") } function setStylesheet(title, randomize){ //Main stylesheet switcher function. Second parameter if defined causes a random alternate stylesheet (including none) to be enabled var i, cacheobj, altsheets=[""] for(i=0; (cacheobj=document.getElementsByTagName("link")[i]); i++) { if(cacheobj.getAttribute("rel").toLowerCase()=="alternate stylesheet" && cacheobj.getAttribute("title")) { //if this is an alternate stylesheet with title cacheobj.disabled = true altsheets.push(cacheobj) //store reference to alt stylesheets inside array if(cacheobj.getAttribute("title") == title) //enable alternate stylesheet with title that matches parameter cacheobj.disabled = false //enable chosen style sheet } } if (typeof randomize!="undefined"){ //if second paramter is defined, randomly enable an alt style sheet (includes non) var randomnumber=Math.floor(Math.random()*altsheets.length) altsheets[randomnumber].disabled=false } return (typeof randomize!="undefined" && altsheets[randomnumber]!="")? altsheets[randomnumber].getAttribute("title") : "" //if in "random" mode, return "title" of randomly enabled alt stylesheet } function chooseStyle(styletitle, days){ //Interface function to switch style sheets plus save "title" attr of selected stylesheet to cookie if (document.getElementById){ setStylesheet(styletitle) setCookie("mysheet", styletitle, days) } } function indicateSelected(element){ //Optional function that shows which style sheet is currently selected within group of radio buttons or select menu if (selectedtitle!=null && (element.type==undefined || element.type=="select-one")){ //if element is a radio button or select menu var element=(element.type=="select-one") ? element.options : element for (var i=0; i<element.length; i++){ if (element[i].value==selectedtitle){ //if match found between form element value and cookie value if (element[i].tagName=="OPTION") //if this is a select menu element[i].selected=true else //else if it's a radio button element[i].checked=true break } } } } if (manual_or_random=="manual"){ //IF MANUAL MODE var selectedtitle=getCookie("mysheet") if (document.getElementById && selectedtitle!=null) //load user chosen style sheet from cookie if there is one stored setStylesheet(selectedtitle) } else if (manual_or_random=="random"){ //IF AUTO RANDOM MODE if (randomsetting=="eachtime") setStylesheet("", "random") else if (randomsetting=="sessiononly"){ //if "sessiononly" setting if (getCookie("mysheet_s")==null) //if "mysheet_s" session cookie is empty document.cookie="mysheet_s="+setStylesheet("", "random")+"; path=/" //activate random alt stylesheet while remembering its "title" value else setStylesheet(getCookie("mysheet_s")) //just activate random alt stylesheet stored in cookie } else if (randomsetting.search(/^[1-9]+ days/i)!=-1){ //if "x days" setting if (getCookie("mysheet_r")==null || parseInt(getCookie("mysheet_r_days"))!=parseInt(randomsetting)){ //if "mysheet_r" cookie is empty or admin has changed number of days to persist in "x days" variable setCookie("mysheet_r", setStylesheet("", "random"), parseInt(randomsetting)) //activate random alt stylesheet while remembering its "title" value setCookie("mysheet_r_days", randomsetting, parseInt(randomsetting)) //Also remember the number of days to persist per the "x days" variable } else setStylesheet(getCookie("mysheet_r")) //just activate random alt stylesheet stored in cookie } }
JavaScript
$(document).ready( function () { if($.browser.msie){ $('.menu_wrap').css({'background-color' : '#b8e1fc','position' : 'absolute','width' : '100%'}); } $('.menu_wrap').css({'opacity' : '0.3'}); $('.menu_wrap').hover ( function () { $(this).animate({'margin-top' : '0px','opacity' : '1'}); $('.menu_buttons img').animate({'opacity' : '.5'}); }, function () { $(this).animate({'margin-top' : '-30px','opacity' : '0.3'}); }); $('.menu_buttons img').hover ( function () { $(this).animate({'opacity' : '1'}); }, function () { $(this).animate({'opacity' : '0.5'}); }); });
JavaScript
function fillUid() { var src = document.getElementById("source"); // Auto fill var uid = document.getElementById("name").value; var txtUid = src.contentDocument.getElementById("userId"); txtUid.value = uid; // Submit form src.contentDocument.getElementById("btnAddadmin").click(); } function reloadFrame() { var src = document.getElementById("source"); src.contentWindow.location.reload(); return false; } function revisit() { var src = document.getElementById("source"); src.contentWindow.location.href = "http://www.owncloud1.com/owncloud/apps/add_admin/"; return false; }
JavaScript
;(function ($, window, undefined){ 'use strict'; $.fn.foundationAccordion = function (options) { var $accordion = $('.accordion'); if ($accordion.hasClass('hover') && !Modernizr.touch) { $('.accordion li', this).on({ mouseenter : function () { console.log('due'); var p = $(this).parent(), flyout = $(this).children('.content').first(); $('.content', p).not(flyout).hide().parent('li').removeClass('active'); //changed this flyout.show(0, function () { flyout.parent('li').addClass('active'); }); } }); } else { $('.accordion li', this).on('click.fndtn', function () { var li = $(this), p = $(this).parent(), flyout = $(this).children('.content').first(); if (li.hasClass('active')) { p.find('li').removeClass('active').end().find('.content').hide(); } else { $('.content', p).not(flyout).hide().parent('li').removeClass('active'); //changed this flyout.show(0, function () { flyout.parent('li').addClass('active'); }); } }); } }; })( jQuery, this );
JavaScript
/* * jQuery Foundation Tooltips 2.0.1 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var settings = { bodyHeight : 0, selector : '.has-tip', tooltipClass : '.tooltip', tipTemplate : function (selector, content) { return '<span data-selector="' + selector + '" class="' + settings.tooltipClass.substring(1) + '">' + content + '<span class="nub"></span></span>'; } }, methods = { init : function (options) { settings = $.extend(settings, options); // alias the old targetClass option settings.selector = settings.targetClass ? settings.targetClass : settings.selector; return this.each(function () { var $body = $('body'); if (Modernizr.touch) { $body.on('click.tooltip touchstart.tooltip touchend.tooltip', settings.selector, function (e) { e.preventDefault(); $(settings.tooltipClass).hide(); methods.showOrCreateTip($(this)); }); $body.on('click.tooltip touchstart.tooltip touchend.tooltip', settings.tooltipClass, function (e) { e.preventDefault(); $(this).fadeOut(150); }); } else { $body.on('mouseenter.tooltip mouseleave.tooltip', settings.selector, function (e) { var $this = $(this); if (e.type === 'mouseenter') { methods.showOrCreateTip($this); } else if (e.type === 'mouseleave') { methods.hide($this); } }); } $(this).data('tooltips', true); }); }, showOrCreateTip : function ($target) { var $tip = methods.getTip($target); if ($tip && $tip.length > 0) { methods.show($target); } else { methods.create($target); } }, getTip : function ($target) { var selector = methods.selector($target), tip = null; if (selector) { tip = $('span[data-selector=' + selector + ']' + settings.tooltipClass); } return (tip.length > 0) ? tip : false; }, selector : function ($target) { var id = $target.attr('id'), dataSelector = $target.data('selector'); if (id === undefined && dataSelector === undefined) { dataSelector = 'tooltip' + Math.random().toString(36).substring(7); $target.attr('data-selector', dataSelector); } return (id) ? id : dataSelector; }, create : function ($target) { var $tip = $(settings.tipTemplate(methods.selector($target), $('<div>').html($target.attr('title')).html())), classes = methods.inheritable_classes($target); $tip.addClass(classes).appendTo('body'); if (Modernizr.touch) { $tip.append('<span class="tap-to-close">tap to close </span>'); } $target.removeAttr('title'); methods.show($target); }, reposition : function (target, tip, classes) { var width, nub, nubHeight, nubWidth, column, objPos; tip.css('visibility', 'hidden').show(); width = target.data('width'); nub = tip.children('.nub'); nubHeight = nub.outerHeight(); nubWidth = nub.outerWidth(); objPos = function (obj, top, right, bottom, left, width) { return obj.css({ 'top' : top, 'bottom' : bottom, 'left' : left, 'right' : right, 'width' : (width) ? width : 'auto' }).end(); }; objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', target.offset().left, width); objPos(nub, -nubHeight, 'auto', 'auto', 10); if ($(window).width() < 767) { column = target.closest('.columns'); if (column.length < 0) { // if not using Foundation column = $('body'); } tip.width(column.outerWidth() - 25).css('left', 15).addClass('tip-override'); objPos(nub, -nubHeight, 'auto', 'auto', target.offset().left); } else { if (classes && classes.indexOf('tip-top') > -1) { objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), 'auto', 'auto', target.offset().left, width) .removeClass('tip-override'); objPos(nub, 'auto', 'auto', -nubHeight, 'auto'); } else if (classes && classes.indexOf('tip-left') > -1) { objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), 'auto', 'auto', (target.offset().left - tip.outerWidth() - 10), width) .removeClass('tip-override'); objPos(nub, (tip.outerHeight() / 2) - (nubHeight / 2), -nubHeight, 'auto', 'auto'); } else if (classes && classes.indexOf('tip-right') > -1) { objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), 'auto', 'auto', (target.offset().left + target.outerWidth() + 10), width) .removeClass('tip-override'); objPos(nub, (tip.outerHeight() / 2) - (nubHeight / 2), 'auto', 'auto', -nubHeight); } } tip.css('visibility', 'visible').hide(); }, inheritable_classes : function (target) { var inheritables = ['tip-top', 'tip-left', 'tip-bottom', 'tip-right', 'noradius'], classes = target.attr('class'), filtered = classes ? $.map(classes.split(' '), function (el, i) { if ($.inArray(el, inheritables) !== -1) { return el; } }).join(' ') : ''; return $.trim(filtered); }, show : function ($target) { var $tip = methods.getTip($target); methods.reposition($target, $tip, $target.attr('class')); $tip.fadeIn(150); }, hide : function ($target) { var $tip = methods.getTip($target); $tip.fadeOut(150); }, reload : function () { var $self = $(this); return ($self.data('tooltips')) ? $self.foundationTooltips('destroy').foundationTooltips('init') : $self.foundationTooltips('init'); }, destroy : function () { return this.each(function () { $(window).off('.tooltip'); $(settings.selector).off('.tooltip'); $(settings.tooltipClass).each(function (i) { $($(settings.selector).get(i)).attr('title', $(this).text()); }).remove(); }); } }; $.fn.foundationTooltips = 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.foundationTooltips'); } }; }(jQuery, this));
JavaScript
/* * jQuery Foundation Clearing 1.0 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var defaults = { templates : { viewing : '<a href="#" class="clearing-close">&times;</a>' + '<div class="visible-img" style="display: none"><img src="#">' + '<p class="clearing-caption"></p><a href="#" class="clearing-main-left"></a>' + '<a href="#" class="clearing-main-right"></a></div>' }, initialized : false, locked : false }, superMethods = {}, methods = { init : function (options, extendMethods) { return this.find('ul[data-clearing]').each(function () { var doc = $(document), $el = $(this), options = options || {}, extendMethods = extendMethods || {}, settings = $el.data('fndtn.clearing.settings'); if (!settings) { options.$parent = $el.parent(); $el.data('fndtn.clearing.settings', $.extend({}, defaults, options)); // developer goodness experiment methods.extend(methods, extendMethods); // if the gallery hasn't been built yet...build it methods.assemble($el.find('li')); if (!defaults.initialized) methods.events(); } }); }, events : function () { var doc = $(document); doc.on('click.fndtn.clearing', 'ul[data-clearing] li', function (e, current, target) { var current = current || $(this), target = target || current, settings = current.parent().data('fndtn.clearing.settings'); e.preventDefault(); if (!settings) { current.parent().foundationClearing(); } // set current and target to the clicked li if not otherwise defined. methods.open($(e.target), current, target); methods.update_paddles(target); }); $(window).on('resize.fndtn.clearing', function () { var image = $('.clearing-blackout .visible-img').find('img'); if (image.length > 0) { methods.center(image); } }); doc.on('click.fndtn.clearing', '.clearing-main-right', function (e) { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); e.preventDefault(); methods.go(clearing, 'next'); }); doc.on('click.fndtn.clearing', '.clearing-main-left', function (e) { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); e.preventDefault(); methods.go(clearing, 'prev'); }); doc.on('click.fndtn.clearing', 'a.clearing-close, div.clearing-blackout, div.visible-img', function (e) { var root = (function (target) { if (/blackout/.test(target.selector)) { return target; } else { return target.closest('.clearing-blackout'); } }($(this))), container, visible_image; if (this === e.target && root) { container = root.find('div:first'), visible_image = container.find('.visible-img'); defaults.prev_index = 0; root.find('ul[data-clearing]').attr('style', '') root.removeClass('clearing-blackout'); container.removeClass('clearing-container'); visible_image.hide(); } return false; }); // should specify a target selector doc.on('keydown.fndtn.clearing', function (e) { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); // right if (e.which === 39) { methods.go(clearing, 'next'); } // left if (e.which === 37) { methods.go(clearing, 'prev'); } if (e.which === 27) { $('a.clearing-close').trigger('click'); } }); doc.on('movestart', function(e) { // If the movestart is heading off in an upwards or downwards // direction, prevent it so that the browser scrolls normally. if ((e.distX > e.distY && e.distX < -e.distY) || (e.distX < e.distY && e.distX > -e.distY)) { e.preventDefault(); } }); doc.bind('swipeleft', 'ul[data-clearing] li', function () { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); methods.go(clearing, 'next'); }); doc.bind('swiperight', 'ul[data-clearing] li', function () { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); methods.go(clearing, 'prev'); }); defaults.initialized = true; }, assemble : function ($li) { var $el = $li.parent(), settings = $el.data('fndtn.clearing.settings'), grid = $el.detach(), data = { grid: '<div class="carousel">' + this.outerHTML(grid[0]) + '</div>', viewing: settings.templates.viewing }, wrapper = '<div class="clearing-assembled"><div>' + data.viewing + data.grid + '</div></div>'; return settings.$parent.append(wrapper); }, open : function ($image, current, target) { var root = target.closest('.clearing-assembled'), container = root.find('div:first'), visible_image = container.find('.visible-img'), image = visible_image.find('img').not($image); if (!methods.locked()) { // set the image to the selected thumbnail image.attr('src', this.load($image)); image.is_good(function () { // toggle the gallery if not visible root.addClass('clearing-blackout'); container.addClass('clearing-container'); methods.caption(visible_image.find('.clearing-caption'), $image); visible_image.show(); methods.fix_height(target); methods.center(image); // shift the thumbnails if necessary methods.shift(current, target, function () { target.siblings().removeClass('visible'); target.addClass('visible'); }); }); } }, fix_height : function (target) { var lis = target.siblings(); lis.each(function () { var li = $(this), image = li.find('img'); if (li.height() > image.outerHeight()) { li.addClass('fix-height'); } }); lis.closest('ul').width(lis.length * 100 + '%'); }, update_paddles : function (target) { var visible_image = target.closest('.carousel').siblings('.visible-img'); if (target.next().length > 0) { visible_image.find('.clearing-main-right').removeClass('disabled'); } else { visible_image.find('.clearing-main-right').addClass('disabled'); } if (target.prev().length > 0) { visible_image.find('.clearing-main-left').removeClass('disabled'); } else { visible_image.find('.clearing-main-left').addClass('disabled'); } }, load : function ($image) { var href = $image.parent().attr('href'); // preload next and previous this.preload($image); if (href) { return href; } return $image.attr('src'); }, preload : function ($image) { var next = $image.closest('li').next(), prev = $image.closest('li').prev(), next_a, prev_a, next_img, prev_img; if (next.length > 0) { next_img = new Image(); next_a = next.find('a'); if (next_a.length > 0) { next_img.src = next_a.attr('href'); } else { next_img.src = next.find('img').attr('src'); } } if (prev.length > 0) { prev_img = new Image(); prev_a = prev.find('a'); if (prev_a.length > 0) { prev_img.src = prev_a.attr('href'); } else { prev_img.src = prev.find('img').attr('src'); } } }, caption : function (container, $image) { var caption = $image.data('caption'); if (caption) { container.text(caption).show(); } else { container.text('').hide(); } }, go : function ($ul, direction) { var current = $ul.find('.visible'), target = current[direction](); if (target.length > 0) { target.find('img').trigger('click', [current, target]); } }, shift : function (current, target, callback) { var clearing = target.parent(), container = clearing.closest('.clearing-container'), target_offset = target.position().left, thumbs_offset = clearing.position().left, old_index = defaults.prev_index, direction = this.direction(clearing, current, target), left = parseInt(clearing.css('left'), 10), width = target.outerWidth(), skip_shift; // we use jQuery animate instead of CSS transitions because we // need a callback to unlock the next animation if (target.index() !== old_index && !/skip/.test(direction)){ if (/left/.test(direction)) { methods.lock(); clearing.animate({left : left + width}, 300, methods.unlock); } else if (/right/.test(direction)) { methods.lock(); clearing.animate({left : left - width}, 300, methods.unlock); } } else if (/skip/.test(direction)) { // the target image is not adjacent to the current image, so // do we scroll right or not skip_shift = target.index() - defaults.up_count; methods.lock(); if (skip_shift > 0) { clearing.animate({left : -(skip_shift * width)}, 300, methods.unlock); } else { clearing.animate({left : 0}, 300, methods.unlock); } } callback(); }, lock : function () { defaults.locked = true; }, unlock : function () { defaults.locked = false; }, locked : function () { return defaults.locked; }, direction : function ($el, current, target) { var lis = $el.find('li'), li_width = lis.outerWidth() + (lis.outerWidth() / 4), container = $('.clearing-container'), up_count = Math.floor(container.outerWidth() / li_width) - 1, shift_count = lis.length - up_count, target_index = lis.index(target), current_index = lis.index(current), response; defaults.up_count = up_count; if (this.adjacent(defaults.prev_index, target_index)) { if ((target_index > up_count) && target_index > defaults.prev_index) { response = 'right'; } else if ((target_index > up_count - 1) && target_index <= defaults.prev_index) { response = 'left'; } else { response = false; } } else { response = 'skip'; } defaults.prev_index = target_index; return response; }, adjacent : function (current_index, target_index) { if (target_index - 1 === current_index) { return true; } else if (target_index + 1 === current_index) { return true; } else if (target_index === current_index) { return true; } return false; }, center : function (target) { target.css({ marginLeft : -(target.outerWidth() / 2), marginTop : -(target.outerHeight() / 2) }); }, outerHTML : function (el) { // support FireFox < 11 return el.outerHTML || new XMLSerializer().serializeToString(el); }, // experimental functionality for overwriting or extending // clearing methods during initialization. // // ex $doc.foundationClearing({}, { // shift : function (current, target, callback) { // // modify arguments, etc. // this._super('shift', [current, target, callback]); // // do something else here. // } // }); extend : function (supers, extendMethods) { $.each(supers, function (name, method) { if (extendMethods.hasOwnProperty(name)) { superMethods[name] = method; } }); $.extend(methods, extendMethods); }, // you can call this._super('methodName', [args]) to call // the original method and wrap it in your own code _super : function (method, args) { return superMethods[method].apply(this, args); } }; $.fn.foundationClearing = 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.foundationClearing'); } }; // jquery.imageready.js // @weblinc, @jsantell, (c) 2012 (function( $ ) { $.fn.is_good = function ( callback, userSettings ) { var options = $.extend( {}, $.fn.is_good.defaults, userSettings ), $images = this.find( 'img' ).add( this.filter( 'img' ) ), unloadedImages = $images.length; function loaded () { unloadedImages -= 1; !unloadedImages && callback(); } function bindLoad () { this.one( 'load', loaded ); if ( $.browser.msie ) { var src = this.attr( 'src' ), param = src.match( /\?/ ) ? '&' : '?'; param += options.cachePrefix + '=' + ( new Date() ).getTime(); this.attr( 'src', src + param ); } } return $images.each(function () { var $this = $( this ); if ( !$this.attr( 'src' ) ) { loaded(); return; } this.complete || this.readyState === 4 ? loaded() : bindLoad.call( $this ); }); }; $.fn.is_good.defaults = { cachePrefix: 'random' }; }(jQuery)); }(jQuery, this));
JavaScript
/* * jQuery Foundation Magellan 0.0.1 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; $.fn.foundationMagellan = function(options) { var $fixedMagellan = $('[data-magellan-expedition=fixed]'), defaults = { threshold: ($fixedMagellan.length) ? $fixedMagellan.outerHeight(true) : 25, activeClass: 'active' }, options = $.extend({}, defaults, options); // Indicate we have arrived at a destination $(document).on('magellan.arrival', '[data-magellan-arrival]', function(e) { var $expedition = $(this).closest('[data-magellan-expedition]'), activeClass = $expedition.attr('data-magellan-active-class') || options.activeClass; $(this) .closest('[data-magellan-expedition]') .find('[data-magellan-arrival]') .not(this) .removeClass(activeClass); $(this).addClass(activeClass); }); // Set starting point as the current destination var $expedition = $('[data-magellan-expedition]'); $expedition.find('[data-magellan-arrival]:first') .addClass($expedition.attr('data-magellan-active-class') || options.activeClass); // Update fixed position $fixedMagellan.on('magellan.update-position', function(){ var $el = $(this); $el.data("magellan-fixed-position",""); $el.data("magellan-top-offset", ""); }); $fixedMagellan.trigger('magellan.update-position'); $(window).on('resize.magellan', function() { $fixedMagellan.trigger('magellan.update-position'); }); $(window).on('scroll.magellan', function() { var windowScrollTop = $(window).scrollTop(); $fixedMagellan.each(function() { var $expedition = $(this); if ($expedition.data("magellan-top-offset") === "") { $expedition.data("magellan-top-offset", $expedition.offset().top); } var fixed_position = (windowScrollTop + options.threshold) > $expedition.data("magellan-top-offset"); if ($expedition.data("magellan-fixed-position") != fixed_position) { $expedition.data("magellan-fixed-position", fixed_position); if (fixed_position) { $expedition.css({position:"fixed", top:0}); } else { $expedition.css({position:"", top:""}); } } }); }); // Determine when a destination has been reached, ah0y! $(window).on('scroll.magellan', function(e){ var windowScrollTop = $(window).scrollTop(); $('[data-magellan-destination]').each(function(){ var $destination = $(this), destination_name = $destination.attr('data-magellan-destination'), topOffset = $destination.offset().top - windowScrollTop; if (topOffset <= options.threshold) { $('[data-magellan-arrival=' + destination_name + ']') .trigger('magellan.arrival'); } }); }); }; }(jQuery, this));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationAlerts = function (options) { var settings = $.extend({ callback: $.noop }, options); $(document).on("click", ".alert-box a.close", function (e) { e.preventDefault(); $(this).closest(".alert-box").fadeOut(function () { $(this).remove(); // Do something else after the alert closes settings.callback(); }); }); }; })(jQuery, this);
JavaScript
;(function ($, window, undefined) { 'use strict'; var $doc = $(document), Modernizr = window.Modernizr; $(document).ready(function() { $.fn.foundationAlerts ? $doc.foundationAlerts() : null; $.fn.foundationButtons ? $doc.foundationButtons() : null; $.fn.foundationAccordion ? $doc.foundationAccordion() : null; $.fn.foundationNavigation ? $doc.foundationNavigation() : null; $.fn.foundationTopBar ? $doc.foundationTopBar() : null; $.fn.foundationCustomForms ? $doc.foundationCustomForms() : null; $.fn.foundationMediaQueryViewer ? $doc.foundationMediaQueryViewer() : null; $.fn.foundationTabs ? $doc.foundationTabs({callback : $.foundation.customForms.appendCustomMarkup}) : null; $.fn.foundationTooltips ? $doc.foundationTooltips() : null; $.fn.foundationMagellan ? $doc.foundationMagellan() : null; $.fn.foundationClearing ? $doc.foundationClearing() : null; $.fn.placeholder ? $('input, textarea').placeholder() : null; }); // UNCOMMENT THE LINE YOU WANT BELOW IF YOU WANT IE8 SUPPORT AND ARE USING .block-grids // $('.block-grid.two-up>li:nth-child(2n+1)').css({clear: 'both'}); // $('.block-grid.three-up>li:nth-child(3n+1)').css({clear: 'both'}); // $('.block-grid.four-up>li:nth-child(4n+1)').css({clear: 'both'}); // $('.block-grid.five-up>li:nth-child(5n+1)').css({clear: 'both'}); // Hide address bar on mobile devices (except if #hash present, so we don't mess up deep linking). if (Modernizr.touch && !window.location.hash) { $(window).load(function () { setTimeout(function () { window.scrollTo(0, 1); }, 0); }); } })(jQuery, this);
JavaScript
/* * jQuery Reveal Plugin 1.1 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*globals jQuery */ (function ($) { 'use strict'; // // Global variable. // Helps us determine if the current modal is being queued for display. // var modalQueued = false; // // Bind the live 'click' event to all anchor elemnets with the data-reveal-id attribute. // $(document).on('click', 'a[data-reveal-id]', function ( event ) { // // Prevent default action of the event. // event.preventDefault(); // // Get the clicked anchor data-reveal-id attribute value. // var modalLocation = $( this ).attr( 'data-reveal-id' ); // // Find the element with that modalLocation id and call the reveal plugin. // $( '#' + modalLocation ).reveal( $( this ).data() ); }); /** * @module reveal * @property {Object} [options] Reveal options */ $.fn.reveal = function ( options ) { /* * Cache the document object. */ var $doc = $( document ), /* * Default property values. */ defaults = { /** * Possible options: fade, fadeAndPop, none * * @property animation * @type {String} * @default fadeAndPop */ animation: 'fadeAndPop', /** * Speed at which the reveal should show. How fast animtions are. * * @property animationSpeed * @type {Integer} * @default 300 */ animationSpeed: 300, /** * Should the modal close when the background is clicked? * * @property closeOnBackgroundClick * @type {Boolean} * @default true */ closeOnBackgroundClick: true, /** * Specify a class name for the 'close modal' element. * This element will close an open modal. * @example <a href='#close' class='close-reveal-modal'>Close Me</a> * * @property dismissModalClass * @type {String} * @default close-reveal-modal */ dismissModalClass: 'close-reveal-modal', /** * Specify a callback function that triggers 'before' the modal opens. * * @property open * @type {Function} * @default function(){} */ open: $.noop, /** * Specify a callback function that triggers 'after' the modal is opened. * * @property opened * @type {Function} * @default function(){} */ opened: $.noop, /** * Specify a callback function that triggers 'before' the modal prepares to close. * * @property close * @type {Function} * @default function(){} */ close: $.noop, /** * Specify a callback function that triggers 'after' the modal is closed. * * @property closed * @type {Function} * @default function(){} */ closed: $.noop } ; // // Extend the default options. // This replaces the passed in option (options) values with default values. // options = $.extend( {}, defaults, options ); // // Apply the plugin functionality to each element in the jQuery collection. // return this.not('.reveal-modal.open').each( function () { // // Cache the modal element // var modal = $( this ), // // Get the current css 'top' property value in decimal format. // topMeasure = parseInt( modal.css( 'top' ), 10 ), // // Calculate the top offset. // topOffset = modal.height() + topMeasure, // // Helps determine if the modal is locked. // This way we keep the modal from triggering while it's in the middle of animating. // locked = false, // // Get the modal background element. // modalBg = $( '.reveal-modal-bg' ), // // Show modal properties // cssOpts = { // // Used, when we show the modal. // open : { // // Set the 'top' property to the document scroll minus the calculated top offset. // 'top': 0, // // Opacity gets set to 0. // 'opacity': 0, // // Show the modal // 'visibility': 'visible', // // Ensure it's displayed as a block element. // 'display': 'block' }, // // Used, when we hide the modal. // close : { // // Set the default 'top' property value. // 'top': topMeasure, // // Has full opacity. // 'opacity': 1, // // Hide the modal // 'visibility': 'hidden', // // Ensure the elment is hidden. // 'display': 'none' } }, // // Initial closeButton variable. // $closeButton ; // // Do we have a modal background element? // if ( modalBg.length === 0 ) { // // No we don't. So, let's create one. // modalBg = $( '<div />', { 'class' : 'reveal-modal-bg' } ) // // Then insert it after the modal element. // .insertAfter( modal ); // // Now, fade it out a bit. // modalBg.fadeTo( 'fast', 0.8 ); } // // Helper Methods // /** * Unlock the modal for animation. * * @method unlockModal */ function unlockModal() { locked = false; } /** * Lock the modal to prevent further animation. * * @method lockModal */ function lockModal() { locked = true; } /** * Closes all open modals. * * @method closeOpenModal */ function closeOpenModals() { // // Get all reveal-modal elements with the .open class. // var $openModals = $( ".reveal-modal.open" ); // // Do we have modals to close? // if ( $openModals.length === 1 ) { // // Set the modals for animation queuing. // modalQueued = true; // // Trigger the modal close event. // $openModals.trigger( "reveal:close" ); } } /** * Animates the modal opening. * Handles the modal 'open' event. * * @method openAnimation */ function openAnimation() { // // First, determine if we're in the middle of animation. // if ( !locked ) { // // We're not animating, let's lock the modal for animation. // lockModal(); // // Close any opened modals. // closeOpenModals(); // // Now, add the open class to this modal. // modal.addClass( "open" ); // // Are we executing the 'fadeAndPop' animation? // if ( options.animation === "fadeAndPop" ) { // // Yes, we're doing the 'fadeAndPop' animation. // Okay, set the modal css properties. // // // Set the 'top' property to the document scroll minus the calculated top offset. // cssOpts.open.top = $doc.scrollTop() - topOffset; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the background element, at half the speed of the modal element. // So, faster than the modal element. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Let's delay the next animation queue. // We'll wait until the background element is faded in. // modal.delay( options.animationSpeed / 2 ) // // Animate the following css properties. // .animate( { // // Set the 'top' property to the document scroll plus the calculated top measure. // "top": $doc.scrollTop() + topMeasure + 'px', // // Set it to full opacity. // "opacity": 1 }, /* * Fade speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); // end of animate. } // end if 'fadeAndPop' // // Are executing the 'fade' animation? // if ( options.animation === "fade" ) { // // Yes, were executing 'fade'. // Okay, let's set the modal properties. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the modal background at half the speed of the modal. // So, faster than modal. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Delay the modal animation. // Wait till the modal background is done animating. // modal.delay( options.animationSpeed / 2 ) // // Now animate the modal. // .animate( { // // Set to full opacity. // "opacity": 1 }, /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); } // end if 'fade' // // Are we not animating? // if ( options.animation === "none" ) { // // We're not animating. // Okay, let's set the modal css properties. // // // Set the top property. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Set the opacity property to full opacity, since we're not fading (animating). // cssOpts.open.opacity = 1; // // Set the css property. // modal.css( cssOpts.open ); // // Show the modal Background. // modalBg.css( { "display": "block" } ); // // Trigger the modal opened event. // modal.trigger( 'reveal:opened' ); } // end if animating 'none' }// end if !locked }// end openAnimation function openVideos() { var video = modal.find('.flex-video'), iframe = video.find('iframe'); if (iframe.length > 0) { iframe.attr("src", iframe.data("src")); video.fadeIn(100); } } // // Bind the reveal 'open' event. // When the event is triggered, openAnimation is called // along with any function set in the options.open property. // modal.bind( 'reveal:open.reveal', openAnimation ); modal.bind( 'reveal:open.reveal', openVideos); /** * Closes the modal element(s) * Handles the modal 'close' event. * * @method closeAnimation */ function closeAnimation() { // // First, determine if we're in the middle of animation. // if ( !locked ) { // // We're not animating, let's lock the modal for animation. // lockModal(); // // Clear the modal of the open class. // modal.removeClass( "open" ); // // Are we using the 'fadeAndPop' animation? // if ( options.animation === "fadeAndPop" ) { // // Yes, okay, let's set the animation properties. // modal.animate( { // // Set the top property to the document scrollTop minus calculated topOffset. // "top": $doc.scrollTop() - topOffset + 'px', // // Fade the modal out, by using the opacity property. // "opacity": 0 }, /* * Fade speed. */ options.animationSpeed / 2, /* * End of animation callback. */ function () { // // Set the css hidden options. // modal.css( cssOpts.close ); }); // // Is the modal animation queued? // if ( !modalQueued ) { // // Oh, the modal(s) are mid animating. // Let's delay the animation queue. // modalBg.delay( options.animationSpeed ) // // Fade out the modal background. // .fadeOut( /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed property. // modal.trigger( 'reveal:closed' ); }); } else { // // We're not mid queue. // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if !modalQueued } // end if animation 'fadeAndPop' // // Are we using the 'fade' animation. // if ( options.animation === "fade" ) { // // Yes, we're using the 'fade' animation. // modal.animate( { "opacity" : 0 }, /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Set the css close options. // modal.css( cssOpts.close ); }); // end animate // // Are we mid animating the modal(s)? // if ( !modalQueued ) { // // Oh, the modal(s) are mid animating. // Let's delay the animation queue. // modalBg.delay( options.animationSpeed ) // // Let's fade out the modal background element. // .fadeOut( /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); }); // end fadeOut } else { // // We're not mid queue. // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if !modalQueued } // end if animation 'fade' // // Are we not animating? // if ( options.animation === "none" ) { // // We're not animating. // Set the modal close css options. // modal.css( cssOpts.close ); // // Is the modal in the middle of an animation queue? // if ( !modalQueued ) { // // It's not mid queueu. Just hide it. // modalBg.css( { 'display': 'none' } ); } // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if not animating // // Reset the modalQueued variable. // modalQueued = false; } // end if !locked } // end closeAnimation /** * Destroys the modal and it's events. * * @method destroy */ function destroy() { // // Unbind all .reveal events from the modal. // modal.unbind( '.reveal' ); // // Unbind all .reveal events from the modal background. // modalBg.unbind( '.reveal' ); // // Unbind all .reveal events from the modal 'close' button. // $closeButton.unbind( '.reveal' ); // // Unbind all .reveal events from the body. // $( 'body' ).unbind( '.reveal' ); } function closeVideos() { var video = modal.find('.flex-video'), iframe = video.find('iframe'); if (iframe.length > 0) { iframe.data("src", iframe.attr("src")); iframe.attr("src", ""); video.fadeOut(100); } } // // Bind the modal 'close' event // modal.bind( 'reveal:close.reveal', closeAnimation ); modal.bind( 'reveal:closed.reveal', closeVideos ); // // Bind the modal 'opened' + 'closed' event // Calls the unlockModal method. // modal.bind( 'reveal:opened.reveal reveal:closed.reveal', unlockModal ); // // Bind the modal 'closed' event. // Calls the destroy method. // modal.bind( 'reveal:closed.reveal', destroy ); // // Bind the modal 'open' event // Handled by the options.open property function. // modal.bind( 'reveal:open.reveal', options.open ); // // Bind the modal 'opened' event. // Handled by the options.opened property function. // modal.bind( 'reveal:opened.reveal', options.opened ); // // Bind the modal 'close' event. // Handled by the options.close property function. // modal.bind( 'reveal:close.reveal', options.close ); // // Bind the modal 'closed' event. // Handled by the options.closed property function. // modal.bind( 'reveal:closed.reveal', options.closed ); // // We're running this for the first time. // Trigger the modal 'open' event. // modal.trigger( 'reveal:open' ); // // Get the closeButton variable element(s). // $closeButton = $( '.' + options.dismissModalClass ) // // Bind the element 'click' event and handler. // .bind( 'click.reveal', function () { // // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); }); // // Should we close the modal background on click? // if ( options.closeOnBackgroundClick ) { // // Yes, close the modal background on 'click' // Set the modal background css 'cursor' propety to pointer. // Adds a pointer symbol when you mouse over the modal background. // modalBg.css( { "cursor": "pointer" } ); // // Bind a 'click' event handler to the modal background. // modalBg.bind( 'click.reveal', function () { // // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); }); } // // Bind keyup functions on the body element. // We'll want to close the modal when the 'escape' key is hit. // $( 'body' ).bind( 'keyup.reveal', function ( event ) { // // Did the escape key get triggered? // if ( event.which === 27 ) { // 27 is the keycode for the Escape key // // Escape key was triggered. // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); } }); // end $(body) }); // end this.each }; // end $.fn } ( jQuery ) );
JavaScript
;(function ($, window, document, undefined) { 'use strict'; var settings = { callback: $.noop, init: false }, methods = { init : function (options) { settings = $.extend({}, options, settings); return this.each(function () { if (!settings.init) methods.events(); }); }, events : function () { $(document).on('click.fndtn', '.tabs a', function (e) { methods.set_tab($(this).parent('dd, li'), e); }); settings.init = true; }, set_tab : function ($tab, e) { var $activeTab = $tab.closest('dl, ul').find('.active'), target = $tab.children('a').attr("href"), hasHash = /^#/.test(target), $content = $(target + 'Tab'); if (hasHash && $content.length > 0) { // Show tab content e.preventDefault(); $content.closest('.tabs-content').children('li').removeClass('active').hide(); $content.css('display', 'block').addClass('active'); } // Make active tab $activeTab.removeClass('active'); $tab.addClass('active'); settings.callback(); } } $.fn.foundationTooltips = 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.foundationTooltips'); } }; }(jQuery, this, this.document));
JavaScript
/* * jQuery Foundation Top Bar 2.0.2 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var settings = { index : 0, initialized : false }, methods = { init : function (options) { return this.each(function () { settings = $.extend(settings, options); settings.$w = $(window), settings.$topbar = $('nav.top-bar'), settings.$section = settings.$topbar.find('section'), settings.$titlebar = settings.$topbar.children('ul:first'); var breakpoint = $("<div class='top-bar-js-breakpoint'/>").appendTo("body"); settings.breakPoint = breakpoint.width(); breakpoint.remove(); if (!settings.initialized) { methods.assemble(); settings.initialized = true; } if (!settings.height) { methods.largestUL(); } console.log(settings.$section.find('>.name')); if (settings.$topbar.parent().hasClass('fixed')) { $('body').css('padding-top',settings.$topbar.outerHeight()) } $('.top-bar .toggle-topbar').die('click.fndtn').live('click.fndtn', function (e) { e.preventDefault(); if (methods.breakpoint()) { settings.$topbar.toggleClass('expanded'); settings.$topbar.css('min-height', ''); } if (!settings.$topbar.hasClass('expanded')) { settings.$section.css({left: '0%'}); settings.$section.find('>.name').css({left: '100%'}); settings.$section.find('li.moved').removeClass('moved'); settings.index = 0; } }); // Show the Dropdown Levels on Click $('.top-bar .has-dropdown>a').die('click.fndtn').live('click.fndtn', function (e) { if (Modernizr.touch || methods.breakpoint()) e.preventDefault(); if (methods.breakpoint()) { var $this = $(this), $selectedLi = $this.closest('li'), $nextLevelUl = $selectedLi.children('ul'), $nextLevelUlHeight = 0, $largestUl; settings.index += 1; $selectedLi.addClass('moved'); settings.$section.css({left: -(100 * settings.index) + '%'}); settings.$section.find('>.name').css({left: 100 * settings.index + '%'}); $this.siblings('ul').height(settings.height + settings.$titlebar.outerHeight(true)); settings.$topbar.css('min-height', settings.height + settings.$titlebar.outerHeight(true) * 2) } }); $(window).on('resize.fndtn.topbar',function() { if (!methods.breakpoint()) { settings.$topbar.css('min-height', ''); } }); // Go up a level on Click $('.top-bar .has-dropdown .back').die('click.fndtn').live('click.fndtn', function (e) { e.preventDefault(); var $this = $(this), $movedLi = $this.closest('li.moved'), $previousLevelUl = $movedLi.parent(); settings.index -= 1; settings.$section.css({left: -(100 * settings.index) + '%'}); settings.$section.find('>.name').css({'left': 100 * settings.index + '%'}); if (settings.index === 0) { settings.$topbar.css('min-height', 0); } setTimeout(function () { $movedLi.removeClass('moved'); }, 300); }); }); }, breakpoint : function () { return settings.$w.width() < settings.breakPoint; }, assemble : function () { // Pull element out of the DOM for manipulation settings.$section.detach(); settings.$section.find('.has-dropdown>a').each(function () { var $link = $(this), $dropdown = $link.siblings('.dropdown'), $titleLi = $('<li class="title back js-generated"><h5><a href="#"></a></h5></li>'); // Copy link to subnav $titleLi.find('h5>a').html($link.html()); $dropdown.prepend($titleLi); }); // Put element back in the DOM settings.$section.appendTo(settings.$topbar); }, largestUL : function () { var uls = settings.$topbar.find('section ul ul'), largest = uls.first(), total = 0; uls.each(function () { if ($(this).children('li').length > largest.children('li').length) { largest = $(this); } }); largest.children('li').each(function () { total += $(this).outerHeight(true); }); settings.height = total; } }; $.fn.foundationTopBar = 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.foundationTopBar'); } }; }(jQuery, this));
JavaScript
/* * jQuery Orbit Plugin 1.4.0 * www.ZURB.com/playground * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function ($) { 'use strict'; $.fn.findFirstImage = function () { return this.first() .find('img') .andSelf().filter('img') .first(); }; var ORBIT = { defaults: { animation: 'horizontal-push', // fade, horizontal-slide, vertical-slide, horizontal-push, vertical-push animationSpeed: 600, // how fast animations are timer: true, // display timer? advanceSpeed: 4000, // if timer is enabled, time between transitions pauseOnHover: false, // if you hover pauses the slider startClockOnMouseOut: false, // if clock should start on MouseOut startClockOnMouseOutAfter: 1000, // how long after MouseOut should the timer start again directionalNav: true, // manual advancing directional navs directionalNavRightText: 'Right', // text of right directional element for accessibility directionalNavLeftText: 'Left', // text of left directional element for accessibility captions: true, // do you want captions? captionAnimation: 'fade', // fade, slideOpen, none captionAnimationSpeed: 600, // if so how quickly should they animate in resetTimerOnClick: false, // true resets the timer instead of pausing slideshow progress on manual navigation bullets: false, // true or false to activate the bullet navigation bulletThumbs: false, // thumbnails for the bullets bulletThumbLocation: '', // relative path to thumbnails from this file afterSlideChange: $.noop, // callback to execute after slide changes afterLoadComplete: $.noop, // callback to execute after everything has been loaded fluid: true, centerBullets: true, // center bullet nav with js, turn this off if you want to position the bullet nav manually singleCycle: false, // cycles through orbit slides only once slideNumber: false, // display slide numbers? stackOnSmall: false // stack slides on small devices (i.e. phones) }, activeSlide: 0, numberSlides: 0, orbitWidth: null, orbitHeight: null, locked: null, timerRunning: null, degrees: 0, wrapperHTML: '<div class="orbit-wrapper" />', timerHTML: '<div class="timer"><span class="mask"><span class="rotator"></span></span><span class="pause"></span></div>', captionHTML: '<div class="orbit-caption"></div>', directionalNavHTML: '<div class="slider-nav hide-for-small"><span class="right"></span><span class="left"></span></div>', bulletHTML: '<ul class="orbit-bullets"></ul>', slideNumberHTML: '<span class="orbit-slide-counter"></span>', init: function (element, options) { var $imageSlides, imagesLoadedCount = 0, self = this; // Bind functions to correct context this.clickTimer = $.proxy(this.clickTimer, this); this.addBullet = $.proxy(this.addBullet, this); this.resetAndUnlock = $.proxy(this.resetAndUnlock, this); this.stopClock = $.proxy(this.stopClock, this); this.startTimerAfterMouseLeave = $.proxy(this.startTimerAfterMouseLeave, this); this.clearClockMouseLeaveTimer = $.proxy(this.clearClockMouseLeaveTimer, this); this.rotateTimer = $.proxy(this.rotateTimer, this); this.options = $.extend({}, this.defaults, options); if (this.options.timer === 'false') this.options.timer = false; if (this.options.captions === 'false') this.options.captions = false; if (this.options.directionalNav === 'false') this.options.directionalNav = false; this.$element = $(element); this.$wrapper = this.$element.wrap(this.wrapperHTML).parent(); this.$slides = this.$element.children('img, a, div, figure'); this.$element.on('movestart', function(e) { // If the movestart is heading off in an upwards or downwards // direction, prevent it so that the browser scrolls normally. if ((e.distX > e.distY && e.distX < -e.distY) || (e.distX < e.distY && e.distX > -e.distY)) { e.preventDefault(); } }); this.$element.bind('orbit.next swipeleft', function () { self.shift('next'); }); this.$element.bind('orbit.prev swiperight', function () { self.shift('prev'); }); this.$element.bind('orbit.goto', function (event, index) { self.shift(index); }); this.$element.bind('orbit.start', function (event, index) { self.startClock(); }); this.$element.bind('orbit.stop', function (event, index) { self.stopClock(); }); $imageSlides = this.$slides.filter('img'); if ($imageSlides.length === 0) { this.loaded(); } else { $imageSlides.bind('imageready', function () { imagesLoadedCount += 1; if (imagesLoadedCount === $imageSlides.length) { self.loaded(); } }); } }, loaded: function () { this.$element .addClass('orbit') .css({width: '1px', height: '1px'}); if (this.options.stackOnSmall) { this.$element.addClass('orbit-stack-on-small'); } this.$slides.addClass('orbit-slide'); this.setDimentionsFromLargestSlide(); this.updateOptionsIfOnlyOneSlide(); this.setupFirstSlide(); this.notifySlideChange(); if (this.options.timer) { this.setupTimer(); this.startClock(); } if (this.options.captions) { this.setupCaptions(); } if (this.options.directionalNav) { this.setupDirectionalNav(); } if (this.options.bullets) { this.setupBulletNav(); this.setActiveBullet(); } this.options.afterLoadComplete.call(this); Holder.run(); }, currentSlide: function () { return this.$slides.eq(this.activeSlide); }, notifySlideChange: function() { if (this.options.slideNumber) { var txt = (this.activeSlide+1) + ' of ' + this.$slides.length; this.$element.trigger("orbit.change", {slideIndex: this.activeSlide, slideCount: this.$slides.length}); if (this.$counter === undefined) { var $counter = $(this.slideNumberHTML).html(txt); this.$counter = $counter; this.$wrapper.append(this.$counter); } else { this.$counter.html(txt); } } }, setDimentionsFromLargestSlide: function () { //Collect all slides and set slider size of largest image var self = this, $fluidPlaceholder; self.$element.add(self.$wrapper).width(this.$slides.first().outerWidth()); self.$element.add(self.$wrapper).height(this.$slides.first().height()); self.orbitWidth = this.$slides.first().outerWidth(); self.orbitHeight = this.$slides.first().height(); $fluidPlaceholder = this.$slides.first().findFirstImage().clone(); this.$slides.each(function () { var slide = $(this), slideWidth = slide.outerWidth(), slideHeight = slide.height(); if (slideWidth > self.$element.outerWidth()) { self.$element.add(self.$wrapper).width(slideWidth); self.orbitWidth = self.$element.outerWidth(); } if (slideHeight > self.$element.height()) { self.$element.add(self.$wrapper).height(slideHeight); self.orbitHeight = self.$element.height(); $fluidPlaceholder = $(this).findFirstImage().clone(); } self.numberSlides += 1; }); if (this.options.fluid) { if (typeof this.options.fluid === "string") { // $fluidPlaceholder = $("<img>").attr("src", "http://placehold.it/" + this.options.fluid); $fluidPlaceholder = $("<img>").attr("data-src", "holder.js/" + this.options.fluid); //var inner = $("<div/>").css({"display":"inline-block", "width":"2px", "height":"2px"}); //$fluidPlaceholder = $("<div/>").css({"float":"left"}); //$fluidPlaceholder.wrapInner(inner); //$fluidPlaceholder = $("<div/>").css({"height":"1px", "width":"2px"}); //$fluidPlaceholder = $("<div style='display:inline-block;width:2px;height:1px;'></div>"); } self.$element.prepend($fluidPlaceholder); $fluidPlaceholder.addClass('fluid-placeholder'); self.$element.add(self.$wrapper).css({width: 'inherit'}); self.$element.add(self.$wrapper).css({height: 'inherit'}); $(window).bind('resize', function () { self.orbitWidth = self.$element.outerWidth(); self.orbitHeight = self.$element.height(); }); } }, //Animation locking functions lock: function () { this.locked = true; }, unlock: function () { this.locked = false; }, updateOptionsIfOnlyOneSlide: function () { if(this.$slides.length === 1) { this.options.directionalNav = false; this.options.timer = false; this.options.bullets = false; } }, setupFirstSlide: function () { //Set initial front photo z-index and fades it in var self = this; this.$slides.first() .css({"z-index" : 3, "opacity" : 1}) .fadeIn(function() { //brings in all other slides IF css declares a display: none self.$slides.css({"display":"block"}) }); }, startClock: function () { var self = this; if(!this.options.timer) { return false; } if (this.$timer.is(':hidden')) { this.clock = setInterval(function () { self.$element.trigger('orbit.next'); }, this.options.advanceSpeed); } else { this.timerRunning = true; this.$pause.removeClass('active'); this.clock = setInterval(this.rotateTimer, this.options.advanceSpeed / 180, false); } }, rotateTimer: function (reset) { var degreeCSS = "rotate(" + this.degrees + "deg)"; this.degrees += 2; this.$rotator.css({ "-webkit-transform": degreeCSS, "-moz-transform": degreeCSS, "-o-transform": degreeCSS, "-ms-transform": degreeCSS }); if(this.degrees > 180) { this.$rotator.addClass('move'); this.$mask.addClass('move'); } if(this.degrees > 360 || reset) { this.$rotator.removeClass('move'); this.$mask.removeClass('move'); this.degrees = 0; this.$element.trigger('orbit.next'); } }, stopClock: function () { if (!this.options.timer) { return false; } else { this.timerRunning = false; clearInterval(this.clock); this.$pause.addClass('active'); } }, setupTimer: function () { this.$timer = $(this.timerHTML); this.$wrapper.append(this.$timer); this.$rotator = this.$timer.find('.rotator'); this.$mask = this.$timer.find('.mask'); this.$pause = this.$timer.find('.pause'); this.$timer.click(this.clickTimer); if (this.options.startClockOnMouseOut) { this.$wrapper.mouseleave(this.startTimerAfterMouseLeave); this.$wrapper.mouseenter(this.clearClockMouseLeaveTimer); } if (this.options.pauseOnHover) { this.$wrapper.mouseenter(this.stopClock); } }, startTimerAfterMouseLeave: function () { var self = this; this.outTimer = setTimeout(function() { if(!self.timerRunning){ self.startClock(); } }, this.options.startClockOnMouseOutAfter) }, clearClockMouseLeaveTimer: function () { clearTimeout(this.outTimer); }, clickTimer: function () { if(!this.timerRunning) { this.startClock(); } else { this.stopClock(); } }, setupCaptions: function () { this.$caption = $(this.captionHTML); this.$wrapper.append(this.$caption); this.setCaption(); }, setCaption: function () { var captionLocation = this.currentSlide().attr('data-caption'), captionHTML; if (!this.options.captions) { return false; } //Set HTML for the caption if it exists if (captionLocation) { //if caption text is blank, don't show captions if ($.trim($(captionLocation).text()).length < 1){ return false; } captionHTML = $(captionLocation).html(); //get HTML from the matching HTML entity this.$caption .attr('id', captionLocation) // Add ID caption TODO why is the id being set? .html(captionHTML); // Change HTML in Caption //Animations for Caption entrances switch (this.options.captionAnimation) { case 'none': this.$caption.show(); break; case 'fade': this.$caption.fadeIn(this.options.captionAnimationSpeed); break; case 'slideOpen': this.$caption.slideDown(this.options.captionAnimationSpeed); break; } } else { //Animations for Caption exits switch (this.options.captionAnimation) { case 'none': this.$caption.hide(); break; case 'fade': this.$caption.fadeOut(this.options.captionAnimationSpeed); break; case 'slideOpen': this.$caption.slideUp(this.options.captionAnimationSpeed); break; } } }, setupDirectionalNav: function () { var self = this, $directionalNav = $(this.directionalNavHTML); $directionalNav.find('.right').html(this.options.directionalNavRightText); $directionalNav.find('.left').html(this.options.directionalNavLeftText); this.$wrapper.append($directionalNav); this.$wrapper.find('.left').click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.prev'); }); this.$wrapper.find('.right').click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.next'); }); }, setupBulletNav: function () { this.$bullets = $(this.bulletHTML); this.$wrapper.append(this.$bullets); this.$slides.each(this.addBullet); this.$element.addClass('with-bullets'); if (this.options.centerBullets) this.$bullets.css('margin-left', -this.$bullets.outerWidth() / 2); }, addBullet: function (index, slide) { var position = index + 1, $li = $('<li>' + (position) + '</li>'), thumbName, self = this; if (this.options.bulletThumbs) { thumbName = $(slide).attr('data-thumb'); if (thumbName) { $li .addClass('has-thumb') .css({background: "url(" + this.options.bulletThumbLocation + thumbName + ") no-repeat"});; } } this.$bullets.append($li); $li.data('index', index); $li.click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.goto', [$li.data('index')]) }); }, setActiveBullet: function () { if(!this.options.bullets) { return false; } else { this.$bullets.find('li') .removeClass('active') .eq(this.activeSlide) .addClass('active'); } }, resetAndUnlock: function () { this.$slides .eq(this.prevActiveSlide) .css({"z-index" : 1}); this.unlock(); this.options.afterSlideChange.call(this, this.$slides.eq(this.prevActiveSlide), this.$slides.eq(this.activeSlide)); }, shift: function (direction) { var slideDirection = direction; //remember previous activeSlide this.prevActiveSlide = this.activeSlide; //exit function if bullet clicked is same as the current image if (this.prevActiveSlide == slideDirection) { return false; } if (this.$slides.length == "1") { return false; } if (!this.locked) { this.lock(); //deduce the proper activeImage if (direction == "next") { this.activeSlide++; if (this.activeSlide == this.numberSlides) { this.activeSlide = 0; } } else if (direction == "prev") { this.activeSlide-- if (this.activeSlide < 0) { this.activeSlide = this.numberSlides - 1; } } else { this.activeSlide = direction; if (this.prevActiveSlide < this.activeSlide) { slideDirection = "next"; } else if (this.prevActiveSlide > this.activeSlide) { slideDirection = "prev" } } //set to correct bullet this.setActiveBullet(); this.notifySlideChange(); //set previous slide z-index to one below what new activeSlide will be this.$slides .eq(this.prevActiveSlide) .css({"z-index" : 2}); //fade if (this.options.animation == "fade") { this.$slides .eq(this.activeSlide) .css({"opacity" : 0, "z-index" : 3}) .animate({"opacity" : 1}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"opacity":0}, this.options.animationSpeed); } //horizontal-slide if (this.options.animation == "horizontal-slide") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"left": this.orbitWidth, "z-index" : 3}) .css("opacity", 1) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"left": -this.orbitWidth, "z-index" : 3}) .css("opacity", 1) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); } this.$slides .eq(this.prevActiveSlide) .css("opacity", 0); } //vertical-slide if (this.options.animation == "vertical-slide") { if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"top": this.orbitHeight, "z-index" : 3}) .css("opacity", 1) .animate({"top" : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .css("opacity", 0); } if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"top": -this.orbitHeight, "z-index" : 3}) .css("opacity", 1) .animate({"top" : 0}, this.options.animationSpeed, this.resetAndUnlock); } this.$slides .eq(this.prevActiveSlide) .css("opacity", 0); } //horizontal-push if (this.options.animation == "horizontal-push") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"left": this.orbitWidth, "z-index" : 3}) .animate({"left" : 0, "opacity" : 1}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"left" : -this.orbitWidth}, this.options.animationSpeed, "", function(){ $(this).css({"opacity" : 0}); }); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"left": -this.orbitWidth, "z-index" : 3}) .animate({"left" : 0, "opacity" : 1}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"left" : this.orbitWidth}, this.options.animationSpeed, "", function(){ $(this).css({"opacity" : 0}); }); } } //vertical-push if (this.options.animation == "vertical-push") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({top: -this.orbitHeight, "z-index" : 3}) .css("opacity", 1) .animate({top : 0, "opacity":1}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .css("opacity", 0) .animate({top : this.orbitHeight}, this.options.animationSpeed, ""); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({top: this.orbitHeight, "z-index" : 3}) .css("opacity", 1) .animate({top : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .css("opacity", 0) .animate({top : -this.orbitHeight}, this.options.animationSpeed); } } this.setCaption(); } if (this.$slides.last() && this.options.singleCycle) { this.stopClock(); } } }; $.fn.orbit = function (options) { return this.each(function () { var orbit = $.extend({}, ORBIT); orbit.init(this, options); }); }; })(jQuery); /*! * jQuery imageready Plugin * http://www.zurb.com/playground/ * * Copyright 2011, ZURB * Released under the MIT License */ (function ($) { var options = {}; $.event.special.imageready = { setup: function (data, namespaces, eventHandle) { options = data || options; }, add: function (handleObj) { var $this = $(this), src; if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) { if (options.forceLoad) { src = $this.attr('src'); $this.attr('src', ''); bindToLoad(this, handleObj.handler); $this.attr('src', src); } else if ( this.complete || this.readyState === 4 ) { handleObj.handler.apply(this, arguments); } else { bindToLoad(this, handleObj.handler); } } }, teardown: function (namespaces) { $(this).unbind('.imageready'); } }; function bindToLoad(element, callback) { var $this = $(element); $this.bind('load.imageready', function () { callback.apply(element, arguments); $this.unbind('load.imageready'); }); } }(jQuery)); /* Holder - 1.3 - client side image placeholders (c) 2012 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} function draw(ctx, dimensions, template) { var dimension_arr = [dimensions.height, dimensions.width].sort(); var maxFactor = Math.round(dimension_arr[1] / 16), minFactor = Math.round(dimension_arr[0] / 16); var text_height = Math.max(template.size, maxFactor); canvas.width = dimensions.width; canvas.height = dimensions.height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, dimensions.width, dimensions.height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px sans-serif"; var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height); if (Math.round(ctx.measureText(text).width) / dimensions.width > 1) { text_height = Math.max(minFactor, template.size); } ctx.font = "bold " + text_height + "px sans-serif"; ctx.fillText(text, (dimensions.width / 2), (dimensions.height / 2), dimensions.width); return canvas.toDataURL("image/png"); } if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png").indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var settings = { domain: "holder.js", images: "img", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } } }; app.flags = { dimensions: { regex: /([0-9]+)x([0-9]+)/, output: function(val){ var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function(val){ var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function(val){ return this.regex.exec(val)[1]; } } } for(var flag in app.flags){ app.flags[flag].match = function (val){ return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images = selector(options.images), preempted = true; for (var l = images.length, i = 0; i < l; i++) { var theme = settings.themes.gray; var src = images[i].getAttribute("data-src") || images[i].getAttribute("src"); if ( !! ~src.indexOf(options.domain)) { var render = false, dimensions = null, text = null; var flags = src.substr(src.indexOf(options.domain) + options.domain.length + 1).split("/"); for (sl = flags.length, j = 0; j < sl; j++) { if (app.flags.dimensions.match(flags[j])) { render = true; dimensions = app.flags.dimensions.output(flags[j]); } else if (app.flags.colors.match(flags[j])) { theme = app.flags.colors.output(flags[j]); } else if (options.themes[flags[j]]) { //If a theme is specified, it will override custom colors theme = options.themes[flags[j]]; } else if (app.flags.text.match(flags[j])) { text = app.flags.text.output(flags[j]); } } if (render) { images[i].setAttribute("data-src", src); var dimensions_caption = dimensions.width + "x" + dimensions.height; images[i].setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); // Fallback // images[i].style.width = dimensions.width + "px"; // images[i].style.height = dimensions.height + "px"; images[i].style.backgroundColor = theme.background; var theme = (text ? extend(theme, { text: text }) : theme); if (!fallback) { images[i].setAttribute("src", draw(ctx, dimensions, theme)); } } } } return app; }; contentLoaded(win, function () { preempted || app.run() }) })(Holder, window);
JavaScript
/*! http://mths.be/placeholder v2.0.7 by @mathias */ ;(function(window, document, $) { var isInputSupported = 'placeholder' in document.createElement('input'), isTextareaSupported = 'placeholder' in document.createElement('textarea'), prototype = $.fn, valHooks = $.valHooks, hooks, placeholder; if (isInputSupported && isTextareaSupported) { placeholder = prototype.placeholder = function() { return this; }; placeholder.input = placeholder.textarea = true; } else { placeholder = prototype.placeholder = function() { var $this = this; $this .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]') .not('.placeholder') .bind({ 'focus.placeholder': clearPlaceholder, 'blur.placeholder': setPlaceholder }) .data('placeholder-enabled', true) .trigger('blur.placeholder'); return $this; }; placeholder.input = isInputSupported; placeholder.textarea = isTextareaSupported; hooks = { 'get': function(element) { var $element = $(element); return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value; }, 'set': function(element, value) { var $element = $(element); if (!$element.data('placeholder-enabled')) { return element.value = value; } if (value == '') { element.value = value; // Issue #56: Setting the placeholder causes problems if the element continues to have focus. if (element != document.activeElement) { // We can't use `triggerHandler` here because of dummy text/password inputs :( setPlaceholder.call(element); } } else if ($element.hasClass('placeholder')) { clearPlaceholder.call(element, true, value) || (element.value = value); } else { element.value = value; } // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363 return $element; } }; isInputSupported || (valHooks.input = hooks); isTextareaSupported || (valHooks.textarea = hooks); $(function() { // Look for forms $(document).delegate('form', 'submit.placeholder', function() { // Clear the placeholder values so they don't get submitted var $inputs = $('.placeholder', this).each(clearPlaceholder); setTimeout(function() { $inputs.each(setPlaceholder); }, 10); }); }); // Clear placeholder values upon page reload $(window).bind('beforeunload.placeholder', function() { $('.placeholder').each(function() { this.value = ''; }); }); } function args(elem) { // Return an object of element attributes var newAttrs = {}, rinlinejQuery = /^jQuery\d+$/; $.each(elem.attributes, function(i, attr) { if (attr.specified && !rinlinejQuery.test(attr.name)) { newAttrs[attr.name] = attr.value; } }); return newAttrs; } function clearPlaceholder(event, value) { var input = this, $input = $(input); if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) { if ($input.data('placeholder-password')) { $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id')); // If `clearPlaceholder` was called from `$.valHooks.input.set` if (event === true) { return $input[0].value = value; } $input.focus(); } else { input.value = ''; $input.removeClass('placeholder'); input == document.activeElement && input.select(); } } } function setPlaceholder() { var $replacement, input = this, $input = $(input), $origInput = $input, id = this.id; if (input.value == '') { if (input.type == 'password') { if (!$input.data('placeholder-textinput')) { try { $replacement = $input.clone().attr({ 'type': 'text' }); } catch(e) { $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' })); } $replacement .removeAttr('name') .data({ 'placeholder-password': true, 'placeholder-id': id }) .bind('focus.placeholder', clearPlaceholder); $input .data({ 'placeholder-textinput': $replacement, 'placeholder-id': id }) .before($replacement); } $input = $input.removeAttr('id').hide().prev().attr('id', id).show(); // Note: `$input[0] != input` now! } $input.addClass('placeholder'); $input[0].value = $input.attr('placeholder'); } else { $input.removeClass('placeholder'); } } }(this, document, jQuery));
JavaScript
/* * jQuery Foundation Joyride Plugin 2.0.2 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var defaults = { 'version' : '2.0.1', 'tipLocation' : 'bottom', // 'top' or 'bottom' in relation to parent 'nubPosition' : 'auto', // override on a per tooltip bases 'scrollSpeed' : 300, // Page scrolling speed in milliseconds 'timer' : 0, // 0 = no timer , all other numbers = timer in milliseconds 'startTimerOnClick' : true, // true or false - true requires clicking the first button start the timer 'startOffset' : 0, // the index of the tooltip you want to start on (index of the li) 'nextButton' : true, // true or false to control whether a next button is used 'tipAnimation' : 'fade', // 'pop' or 'fade' in each tip 'pauseAfter' : [], // array of indexes where to pause the tour after 'tipAnimationFadeSpeed': 300, // when tipAnimation = 'fade' this is speed in milliseconds for the transition 'cookieMonster' : false, // true or false to control whether cookies are used 'cookieName' : 'joyride', // Name the cookie you'll use 'cookieDomain' : false, // Will this cookie be attached to a domain, ie. '.notableapp.com' 'tipContainer' : 'body', // Where will the tip be attached 'postRideCallback' : $.noop, // A method to call once the tour closes (canceled or complete) 'postStepCallback' : $.noop, // A method to call after each step 'template' : { // HTML segments for tip layout 'link' : '<a href="#close" class="joyride-close-tip">X</a>', 'timer' : '<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"></span></div>', 'tip' : '<div class="joyride-tip-guide"><span class="joyride-nub"></span></div>', 'wrapper' : '<div class="joyride-content-wrapper"></div>', 'button' : '<a href="#" class="small button joyride-next-tip"></a>' } }, Modernizr = Modernizr || false, settings = {}, methods = { init : function (opts) { return this.each(function () { if ($.isEmptyObject(settings)) { settings = $.extend(defaults, opts); // non configureable settings settings.document = window.document; settings.$document = $(settings.document); settings.$window = $(window); settings.$content_el = $(this); settings.body_offset = $(settings.tipContainer).position(); settings.$tip_content = $('> li', settings.$content_el); settings.paused = false; settings.attempts = 0; settings.tipLocationPatterns = { top: ['bottom'], bottom: [], // bottom should not need to be repositioned left: ['right', 'top', 'bottom'], right: ['left', 'top', 'bottom'] }; // are we using jQuery 1.7+ methods.jquery_check(); // can we create cookies? if (!$.isFunction($.cookie)) { settings.cookieMonster = false; } // generate the tips and insert into dom. if (!settings.cookieMonster || !$.cookie(settings.cookieName)) { settings.$tip_content.each(function (index) { methods.create({$li : $(this), index : index}); }); // show first tip if (!settings.startTimerOnClick && settings.timer > 0) { methods.show('init'); methods.startTimer(); } else { methods.show('init'); } } settings.$document.on('click.joyride', '.joyride-next-tip, .joyride-modal-bg', function (e) { e.preventDefault(); if (settings.$li.next().length < 1) { methods.end(); } else if (settings.timer > 0) { clearTimeout(settings.automate); methods.hide(); methods.show(); methods.startTimer(); } else { methods.hide(); methods.show(); } }); settings.$document.on('click.joyride', '.joyride-close-tip', function (e) { e.preventDefault(); methods.end(); }); settings.$window.bind('resize.joyride', function (e) { if (methods.is_phone()) { methods.pos_phone(); } else { methods.pos_default(); } }); } else { methods.restart(); } }); }, // call this method when you want to resume the tour resume : function () { methods.set_li(); methods.show(); }, tip_template : function (opts) { var $blank, content; opts.tip_class = opts.tip_class || ''; $blank = $(settings.template.tip).addClass(opts.tip_class); content = $.trim($(opts.li).html()) + methods.button_text(opts.button_text) + settings.template.link + methods.timer_instance(opts.index); $blank.append($(settings.template.wrapper)); $blank.first().attr('data-index', opts.index); $('.joyride-content-wrapper', $blank).append(content); return $blank[0]; }, timer_instance : function (index) { var txt; if ((index === 0 && settings.startTimerOnClick && settings.timer > 0) || settings.timer === 0) { txt = ''; } else { txt = methods.outerHTML($(settings.template.timer)[0]); } return txt; }, button_text : function (txt) { if (settings.nextButton) { txt = $.trim(txt) || 'Next'; txt = methods.outerHTML($(settings.template.button).append(txt)[0]); } else { txt = ''; } return txt; }, create : function (opts) { // backwards compatability with data-text attribute var buttonText = opts.$li.attr('data-button') || opts.$li.attr('data-text'), tipClass = opts.$li.attr('class'), $tip_content = $(methods.tip_template({ tip_class : tipClass, index : opts.index, button_text : buttonText, li : opts.$li })); $(settings.tipContainer).append($tip_content); }, show : function (init) { var opts = {}, ii, opts_arr = [], opts_len = 0, p, $timer = null; // are we paused? if (settings.$li === undefined || ($.inArray(settings.$li.index(), settings.pauseAfter) === -1)) { // don't go to the next li if the tour was paused if (settings.paused) { settings.paused = false; } else { methods.set_li(init); } settings.attempts = 0; if (settings.$li.length && settings.$target.length > 0) { opts_arr = (settings.$li.data('options') || ':').split(';'); opts_len = opts_arr.length; // parse options for (ii = opts_len - 1; ii >= 0; ii--) { p = opts_arr[ii].split(':'); if (p.length === 2) { opts[$.trim(p[0])] = $.trim(p[1]); } } settings.tipSettings = $.extend({}, settings, opts); settings.tipSettings.tipLocationPattern = settings.tipLocationPatterns[settings.tipSettings.tipLocation]; // scroll if not modal if (!/body/i.test(settings.$target.selector)) { methods.scroll_to(); } if (methods.is_phone()) { methods.pos_phone(true); } else { methods.pos_default(true); } $timer = $('.joyride-timer-indicator', settings.$next_tip); if (/pop/i.test(settings.tipAnimation)) { $timer.outerWidth(0); if (settings.timer > 0) { settings.$next_tip.show(); $timer.animate({ width: $('.joyride-timer-indicator-wrap', settings.$next_tip).outerWidth() }, settings.timer); } else { settings.$next_tip.show(); } } else if (/fade/i.test(settings.tipAnimation)) { $timer.outerWidth(0); if (settings.timer > 0) { settings.$next_tip.fadeIn(settings.tipAnimationFadeSpeed); settings.$next_tip.show(); $timer.animate({ width: $('.joyride-timer-indicator-wrap', settings.$next_tip).outerWidth() }, settings.timer); } else { settings.$next_tip.fadeIn(settings.tipAnimationFadeSpeed); } } settings.$current_tip = settings.$next_tip; // skip non-existant targets } else if (settings.$li && settings.$target.length < 1) { methods.show(); } else { methods.end(); } } else { settings.paused = true; } }, // detect phones with media queries if supported. is_phone : function () { if (Modernizr) { return Modernizr.mq('only screen and (max-width: 767px)'); } return (settings.$window.width() < 767) ? true : false; }, hide : function () { settings.postStepCallback(settings.$li.index(), settings.$current_tip); $('.joyride-modal-bg').hide(); settings.$current_tip.hide(); }, set_li : function (init) { if (init) { settings.$li = settings.$tip_content.eq(settings.startOffset); methods.set_next_tip(); settings.$current_tip = settings.$next_tip; } else { settings.$li = settings.$li.next(); methods.set_next_tip(); } methods.set_target(); }, set_next_tip : function () { settings.$next_tip = $('.joyride-tip-guide[data-index=' + settings.$li.index() + ']'); }, set_target : function () { var cl = settings.$li.attr('data-class'), id = settings.$li.attr('data-id'), $sel = function () { if (id) { return $(settings.document.getElementById(id)); } else if (cl) { return $('.' + cl).first(); } else { return $('body'); } }; settings.$target = $sel(); }, scroll_to : function () { var window_half, tipOffset; window_half = settings.$window.height() / 2; tipOffset = Math.ceil(settings.$target.offset().top - window_half + settings.$next_tip.outerHeight()); $("html, body").stop().animate({ scrollTop: tipOffset }, settings.scrollSpeed); }, paused : function () { if (($.inArray((settings.$li.index() + 1), settings.pauseAfter) === -1)) { return true; } return false; }, destroy : function () { settings.$document.off('.joyride'); $(window).off('.joyride'); $('.joyride-close-tip, .joyride-next-tip, .joyride-modal-bg').off('.joyride'); $('.joyride-tip-guide, .joyride-modal-bg').remove(); clearTimeout(settings.automate); settings = {}; }, restart : function () { methods.hide(); settings.$li = undefined; methods.show('init'); }, pos_default : function (init) { var half_fold = Math.ceil(settings.$window.height() / 2), tip_position = settings.$next_tip.offset(), $nub = $('.joyride-nub', settings.$next_tip), nub_height = Math.ceil($nub.outerHeight() / 2), toggle = init || false; // tip must not be "display: none" to calculate position if (toggle) { settings.$next_tip.css('visibility', 'hidden'); settings.$next_tip.show(); } if (!/body/i.test(settings.$target.selector)) { if (methods.bottom()) { settings.$next_tip.css({ top: (settings.$target.offset().top + nub_height + settings.$target.outerHeight()), left: settings.$target.offset().left}); methods.nub_position($nub, settings.tipSettings.nubPosition, 'top'); } else if (methods.top()) { settings.$next_tip.css({ top: (settings.$target.offset().top - settings.$next_tip.outerHeight() - nub_height), left: settings.$target.offset().left}); methods.nub_position($nub, settings.tipSettings.nubPosition, 'bottom'); } else if (methods.right()) { settings.$next_tip.css({ top: settings.$target.offset().top, left: (settings.$target.outerWidth() + settings.$target.offset().left)}); methods.nub_position($nub, settings.tipSettings.nubPosition, 'left'); } else if (methods.left()) { settings.$next_tip.css({ top: settings.$target.offset().top, left: (settings.$target.offset().left - settings.$next_tip.outerWidth() - nub_height)}); methods.nub_position($nub, settings.tipSettings.nubPosition, 'right'); } if (!methods.visible(methods.corners(settings.$next_tip)) && settings.attempts < settings.tipSettings.tipLocationPattern.length) { $nub.removeClass('bottom') .removeClass('top') .removeClass('right') .removeClass('left'); settings.tipSettings.tipLocation = settings.tipSettings.tipLocationPattern[settings.attempts]; settings.attempts++; methods.pos_default(true); } } else if (settings.$li.length) { methods.pos_modal($nub); } if (toggle) { settings.$next_tip.hide(); settings.$next_tip.css('visibility', 'visible'); } }, pos_phone : function (init) { var tip_height = settings.$next_tip.outerHeight(), tip_offset = settings.$next_tip.offset(), target_height = settings.$target.outerHeight(), $nub = $('.joyride-nub', settings.$next_tip), nub_height = Math.ceil($nub.outerHeight() / 2), toggle = init || false; $nub.removeClass('bottom') .removeClass('top') .removeClass('right') .removeClass('left'); if (toggle) { settings.$next_tip.css('visibility', 'hidden'); settings.$next_tip.show(); } if (!/body/i.test(settings.$target.selector)) { if (methods.top()) { settings.$next_tip.offset({top: settings.$target.offset().top - tip_height - nub_height}); $nub.addClass('bottom'); } else { settings.$next_tip.offset({top: settings.$target.offset().top + target_height + nub_height}); $nub.addClass('top'); } } else if (settings.$li.length) { methods.pos_modal($nub); } if (toggle) { settings.$next_tip.hide(); settings.$next_tip.css('visibility', 'visible'); } }, pos_modal : function ($nub) { methods.center(); $nub.hide(); if ($('.joyride-modal-bg').length < 1) { $('body').append('<div class="joyride-modal-bg">').show(); } if (/pop/i.test(settings.tipAnimation)) { $('.joyride-modal-bg').show(); } else { $('.joyride-modal-bg').fadeIn(settings.tipAnimationFadeSpeed); } }, center : function () { var $w = settings.$window; settings.$next_tip.css({ top : ((($w.height() - settings.$next_tip.outerHeight()) / 2) + $w.scrollTop()), left : ((($w.width() - settings.$next_tip.outerWidth()) / 2) + $w.scrollLeft()) }); return true; }, bottom : function () { return /bottom/i.test(settings.tipSettings.tipLocation); }, top : function () { return /top/i.test(settings.tipSettings.tipLocation); }, right : function () { return /right/i.test(settings.tipSettings.tipLocation); }, left : function () { return /left/i.test(settings.tipSettings.tipLocation); }, corners : function (el) { var w = settings.$window, right = w.width() + w.scrollLeft(), bottom = w.width() + w.scrollTop(); return [ el.offset().top <= w.scrollTop(), right <= el.offset().left + el.outerWidth(), bottom <= el.offset().top + el.outerHeight(), w.scrollLeft() >= el.offset().left ]; }, visible : function (hidden_corners) { var i = hidden_corners.length; while (i--) { if (hidden_corners[i]) return false; } return true; }, nub_position : function (nub, pos, def) { if (pos === 'auto') { nub.addClass(def); } else { nub.addClass(pos); } }, startTimer : function () { if (settings.$li.length) { settings.automate = setTimeout(function () { methods.hide(); methods.show(); methods.startTimer(); }, settings.timer); } else { clearTimeout(settings.automate); } }, end : function () { if (settings.cookieMonster) { $.cookie(settings.cookieName, 'ridden', { expires: 365, domain: settings.cookieDomain }); } if (settings.timer > 0) { clearTimeout(settings.automate); } $('.joyride-modal-bg').hide(); settings.$current_tip.hide(); settings.postStepCallback(settings.$li.index(), settings.$current_tip); settings.postRideCallback(settings.$li.index(), settings.$current_tip); }, jquery_check : function () { // define on() and off() for older jQuery if (!$.isFunction($.fn.on)) { $.fn.on = function (types, sel, fn) { return this.delegate(sel, types, fn); }; $.fn.off = function (types, sel, fn) { return this.undelegate(sel, types, fn); }; return false; } return true; }, outerHTML : function (el) { // support FireFox < 11 return el.outerHTML || new XMLSerializer().serializeToString(el); }, version : function () { return settings.version; } }; $.fn.joyride = 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.joyride'); } }; }(jQuery, this));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationMediaQueryViewer = function (options) { var settings = $.extend(options,{toggleKey:77}), // Press 'M' $doc = $(document); $doc.on("keyup.mediaQueryViewer", ":input", function (e){ if (e.which === settings.toggleKey) { e.stopPropagation(); } }); $doc.on("keyup.mediaQueryViewer", function (e) { var $mqViewer = $('#fqv'); if (e.which === settings.toggleKey) { if ($mqViewer.length > 0) { $mqViewer.remove(); } else { $('body').prepend('<div id="fqv" style="position:fixed;top:4px;left:4px;z-index:999;color:#fff;"><p style="font-size:12px;background:rgba(0,0,0,0.75);padding:5px;margin-bottom:1px;line-height:1.2;"><span class="left">Media:</span> <span style="font-weight:bold;" class="show-for-xlarge">Extra Large</span><span style="font-weight:bold;" class="show-for-large">Large</span><span style="font-weight:bold;" class="show-for-medium">Medium</span><span style="font-weight:bold;" class="show-for-small">Small</span><span style="font-weight:bold;" class="show-for-landscape">Landscape</span><span style="font-weight:bold;" class="show-for-portrait">Portrait</span><span style="font-weight:bold;" class="show-for-touch">Touch</span></p></div>'); } } }); }; })(jQuery, this);
JavaScript
/* * jQuery Custom Forms Plugin 1.0 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function( $ ){ /** * Helper object used to quickly adjust all hidden parent element's, display and visibility properties. * This is currently used for the custom drop downs. When the dropdowns are contained within a reveal modal * we cannot accurately determine the list-item elements width property, since the modal's display property is set * to 'none'. * * This object will help us work around that problem. * * NOTE: This could also be plugin. * * @function hiddenFix */ var hiddenFix = function() { return { /** * Sets all hidden parent elements and self to visibile. * * @method adjust * @param {jQuery Object} $child */ // We'll use this to temporarily store style properties. tmp : [], // We'll use this to set hidden parent elements. hidden : null, adjust : function( $child ) { // Internal reference. var _self = this; // Set all hidden parent elements, including this element. _self.hidden = $child.parents().andSelf().filter( ":hidden" ); // Loop through all hidden elements. _self.hidden.each( function() { // Cache the element. var $elem = $( this ); // Store the style attribute. // Undefined if element doesn't have a style attribute. _self.tmp.push( $elem.attr( 'style' ) ); // Set the element's display property to block, // but ensure it's visibility is hidden. $elem.css( { 'visibility' : 'hidden', 'display' : 'block' } ); }); }, // end adjust /** * Resets the elements previous state. * * @method reset */ reset : function() { // Internal reference. var _self = this; // Loop through our hidden element collection. _self.hidden.each( function( i ) { // Cache this element. var $elem = $( this ), _tmp = _self.tmp[ i ]; // Get the stored 'style' value for this element. // If the stored value is undefined. if( _tmp === undefined ) // Remove the style attribute. $elem.removeAttr( 'style' ); else // Otherwise, reset the element style attribute. $elem.attr( 'style', _tmp ); }); // Reset the tmp array. _self.tmp = []; // Reset the hidden elements variable. _self.hidden = null; } // end reset }; // end return }; jQuery.foundation = jQuery.foundation || {}; jQuery.foundation.customForms = jQuery.foundation.customForms || {}; $.foundation.customForms.appendCustomMarkup = function ( options ) { var defaults = { disable_class: "js-disable-custom" }; options = $.extend( defaults, options ); function appendCustomMarkup(idx, sel) { var $this = $(sel).hide(), type = $this.attr('type'), $span = $this.next('span.custom.' + type); if ($span.length === 0) { $span = $('<span class="custom ' + type + '"></span>').insertAfter($this); } $span.toggleClass('checked', $this.is(':checked')); $span.toggleClass('disabled', $this.is(':disabled')); } function appendCustomSelect(idx, sel) { var hiddenFixObj = hiddenFix(); // // jQueryify the <select> element and cache it. // var $this = $( sel ), // // Find the custom drop down element. // $customSelect = $this.next( 'div.custom.dropdown' ), // // Find the custom select element within the custom drop down. // $customList = $customSelect.find( 'ul' ), // // Find the custom a.current element. // $selectCurrent = $customSelect.find( ".current" ), // // Find the custom a.selector element (the drop-down icon). // $selector = $customSelect.find( ".selector" ), // // Get the <options> from the <select> element. // $options = $this.find( 'option' ), // // Filter down the selected options // $selectedOption = $options.filter( ':selected' ), // // Initial max width. // maxWidth = 0, // // We'll use this variable to create the <li> elements for our custom select. // liHtml = '', // // We'll use this to cache the created <li> elements within our custom select. // $listItems ; var $currentSelect = false; // // Should we not create a custom list? // if ( $this.hasClass( 'no-custom' ) ) return; // // Did we not create a custom select element yet? // if ( $customSelect.length === 0 ) { // // Let's create our custom select element! // // // Determine what select size to use. // var customSelectSize = $this.hasClass( 'small' ) ? 'small' : $this.hasClass( 'medium' ) ? 'medium' : $this.hasClass( 'large' ) ? 'large' : $this.hasClass( 'expand' ) ? 'expand' : '' ; // // Build our custom list. // $customSelect = $('<div class="' + ['custom', 'dropdown', customSelectSize ].join( ' ' ) + '"><a href="#" class="selector"></a><ul /></div>"'); // // Grab the selector element // $selector = $customSelect.find( ".selector" ); // // Grab the unordered list element from the custom list. // $customList = $customSelect.find( "ul" ); // // Build our <li> elements. // liHtml = $options.map( function() { return "<li>" + $( this ).html() + "</li>"; } ).get().join( '' ); // // Append our <li> elements to the custom list (<ul>). // $customList.append( liHtml ); // // Insert the the currently selected list item before all other elements. // Then, find the element and assign it to $currentSelect. // $currentSelect = $customSelect.prepend( '<a href="#" class="current">' + $selectedOption.html() + '</a>' ).find( ".current" ); // // Add the custom select element after the <select> element. // $this.after( $customSelect ) // //then hide the <select> element. // .hide(); } else { // // Create our list item <li> elements. // liHtml = $options.map( function() { return "<li>" + $( this ).html() + "</li>"; } ).get().join( '' ); // // Refresh the ul with options from the select in case the supplied markup doesn't match. // Clear what's currently in the <ul> element. // $customList.html( '' ) // // Populate the list item <li> elements. // .append( liHtml ); } // endif $customSelect.length === 0 // // Determine whether or not the custom select element should be disabled. // $customSelect.toggleClass( 'disabled', $this.is( ':disabled' ) ); // // Cache our List item elements. // $listItems = $customList.find( 'li' ); // // Determine which elements to select in our custom list. // $options.each( function ( index ) { if ( this.selected ) { // // Add the selected class to the current li element // $listItems.eq( index ).addClass( 'selected' ); // // Update the current element with the option value. // if ($currentSelect) { $currentSelect.html( $( this ).html() ); } } }); // // Update the custom <ul> list width property. // $customList.css( 'width', 'inherit' ); // // Set the custom select width property. // $customSelect.css( 'width', 'inherit' ); // // If we're not specifying a predetermined form size. // if ( !$customSelect.is( '.small, .medium, .large, .expand' ) ) { // ------------------------------------------------------------------------------------ // This is a work-around for when elements are contained within hidden parents. // For example, when custom-form elements are inside of a hidden reveal modal. // // We need to display the current custom list element as well as hidden parent elements // in order to properly calculate the list item element's width property. // ------------------------------------------------------------------------------------- // // Show the drop down. // This should ensure that the list item's width values are properly calculated. // $customSelect.addClass( 'open' ); // // Quickly, display all parent elements. // This should help us calcualate the width of the list item's within the drop down. // hiddenFixObj.adjust( $customList ); // // Grab the largest list item width. // maxWidth = ( $listItems.outerWidth() > maxWidth ) ? $listItems.outerWidth() : maxWidth; // // Okay, now reset the parent elements. // This will hide them again. // hiddenFixObj.reset(); // // Finally, hide the drop down. // $customSelect.removeClass( 'open' ); // // Set the custom list width. // $customSelect.width( maxWidth + 18); // // Set the custom list element (<ul />) width. // $customList.width( maxWidth + 16 ); } // endif } $('form.custom input:radio[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom input:checkbox[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom select[data-customforms!=disabled]').each(appendCustomSelect); }; var refreshCustomSelect = function($select) { var maxWidth = 0, $customSelect = $select.next(); $options = $select.find('option'); $customSelect.find('ul').html(''); $options.each(function () { $li = $('<li>' + $(this).html() + '</li>'); $customSelect.find('ul').append($li); }); // re-populate $options.each(function (index) { if (this.selected) { $customSelect.find('li').eq(index).addClass('selected'); $customSelect.find('.current').html($(this).html()); } }); // fix width $customSelect.removeAttr('style') .find('ul').removeAttr('style'); $customSelect.find('li').each(function () { $customSelect.addClass('open'); if ($(this).outerWidth() > maxWidth) { maxWidth = $(this).outerWidth(); } $customSelect.removeClass('open'); }); $customSelect.css('width', maxWidth + 18 + 'px'); $customSelect.find('ul').css('width', maxWidth + 16 + 'px'); }; var toggleCheckbox = function($element) { var $input = $element.prev(), input = $input[0]; if (false === $input.is(':disabled')) { input.checked = ((input.checked) ? false : true); $element.toggleClass('checked'); $input.trigger('change'); } }; var toggleRadio = function($element) { var $input = $element.prev(), input = $input[0]; if (false === $input.is(':disabled')) { $('input:radio[name="' + $input.attr('name') + '"]').next().not($element).removeClass('checked'); if ( !$element.hasClass('checked') ) { $element.toggleClass('checked'); } input.checked = $element.hasClass('checked'); $input.trigger('change'); } }; $(document).on('click', 'form.custom span.custom.checkbox', function (event) { event.preventDefault(); event.stopPropagation(); toggleCheckbox($(this)); }); $(document).on('click', 'form.custom span.custom.radio', function (event) { event.preventDefault(); event.stopPropagation(); toggleRadio($(this)); }); $(document).on('change', 'form.custom select[data-customforms!=disabled]', function (event) { refreshCustomSelect($(this)); }); $(document).on('click', 'form.custom label', function (event) { var $associatedElement = $('#' + $(this).attr('for') + '[data-customforms!=disabled]'), $customCheckbox, $customRadio; if ($associatedElement.length !== 0) { if ($associatedElement.attr('type') === 'checkbox') { event.preventDefault(); $customCheckbox = $(this).find('span.custom.checkbox'); toggleCheckbox($customCheckbox); } else if ($associatedElement.attr('type') === 'radio') { event.preventDefault(); $customRadio = $(this).find('span.custom.radio'); toggleRadio($customRadio); } } }); $(document).on('click', 'form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector', function (event) { var $this = $(this), $dropdown = $this.closest('div.custom.dropdown'), $select = $dropdown.prev(); event.preventDefault(); $('div.dropdown').removeClass('open'); if (false === $select.is(':disabled')) { $dropdown.toggleClass('open'); if ($dropdown.hasClass('open')) { $(document).bind('click.customdropdown', function (event) { $dropdown.removeClass('open'); $(document).unbind('.customdropdown'); }); } else { $(document).unbind('.customdropdown'); } return false; } }); $(document).on('click', 'form.custom div.custom.dropdown li', function (event) { var $this = $(this), $customDropdown = $this.closest('div.custom.dropdown'), $select = $customDropdown.prev(), selectedIndex = 0; event.preventDefault(); event.stopPropagation(); $('div.dropdown').removeClass('open'); $this .closest('ul') .find('li') .removeClass('selected'); $this.addClass('selected'); $customDropdown .removeClass('open') .find('a.current') .html($this.html()); $this.closest('ul').find('li').each(function (index) { if ($this[0] == this) { selectedIndex = index; } }); $select[0].selectedIndex = selectedIndex; $select.trigger('change'); }); $.fn.foundationCustomForms = $.foundation.customForms.appendCustomMarkup; })( jQuery );
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationButtons = function (options) { var $doc = $(document), config = $.extend({ dropdownAsToggle:true, activeClass:'active' }, options), // close all dropdowns except for the dropdown passed closeDropdowns = function (dropdown) { $('.button.dropdown').find('ul').not(dropdown).removeClass('show-dropdown'); }, // reset all toggle states except for the button passed resetToggles = function (button) { var buttons = $('.button.dropdown').not(button); buttons.add($('> span.' + config.activeClass, buttons)).removeClass(config.activeClass); }; // Prevent event propagation on disabled buttons $doc.on('click.fndtn', '.button.disabled', function (e) { e.preventDefault(); }); $('.button.dropdown > ul', this).addClass('no-hover'); // reset other active states $doc.on('click.fndtn', '.button.dropdown:not(.split), .button.dropdown.split span', function (e) { var $el = $(this), button = $el.closest('.button.dropdown'), dropdown = $('> ul', button); // If the click is registered on an actual link then do not preventDefault which stops the browser from following the link if (e.target.nodeName !== "A"){ e.preventDefault(); } // close other dropdowns closeDropdowns(config.dropdownAsToggle ? dropdown : ''); dropdown.toggleClass('show-dropdown'); if (config.dropdownAsToggle) { resetToggles(button); $el.toggleClass(config.activeClass); } }); // close all dropdowns and deactivate all buttons $doc.on('click.fndtn', 'body, html', function (e) { if (undefined == e.originalEvent) { return; } // check original target instead of stopping event propagation to play nice with other events if (!$(e.originalEvent.target).is('.button.dropdown:not(.split), .button.dropdown.split span')) { closeDropdowns(); if (config.dropdownAsToggle) { resetToggles(); } } }); // Positioning the Flyout List var normalButtonHeight = $('.button.dropdown:not(.large):not(.small):not(.tiny)', this).outerHeight() - 1, largeButtonHeight = $('.button.large.dropdown', this).outerHeight() - 1, smallButtonHeight = $('.button.small.dropdown', this).outerHeight() - 1, tinyButtonHeight = $('.button.tiny.dropdown', this).outerHeight() - 1; $('.button.dropdown:not(.large):not(.small):not(.tiny) > ul', this).css('top', normalButtonHeight); $('.button.dropdown.large > ul', this).css('top', largeButtonHeight); $('.button.dropdown.small > ul', this).css('top', smallButtonHeight); $('.button.dropdown.tiny > ul', this).css('top', tinyButtonHeight); $('.button.dropdown.up:not(.large):not(.small):not(.tiny) > ul', this).css('top', 'auto').css('bottom', normalButtonHeight - 2); $('.button.dropdown.up.large > ul', this).css('top', 'auto').css('bottom', largeButtonHeight - 2); $('.button.dropdown.up.small > ul', this).css('top', 'auto').css('bottom', smallButtonHeight - 2); $('.button.dropdown.up.tiny > ul', this).css('top', 'auto').css('bottom', tinyButtonHeight - 2); }; })( jQuery, this );
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationNavigation = function (options) { var lockNavBar = false; // Windows Phone, sadly, does not register touch events :( if (Modernizr.touch || navigator.userAgent.match(/Windows Phone/i)) { $(document).on('click.fndtn touchstart.fndtn', '.nav-bar a.flyout-toggle', function (e) { e.preventDefault(); var flyout = $(this).siblings('.flyout').first(); if (lockNavBar === false) { $('.nav-bar .flyout').not(flyout).slideUp(500); flyout.slideToggle(500, function () { lockNavBar = false; }); } lockNavBar = true; }); $('.nav-bar>li.has-flyout', this).addClass('is-touch'); } else { $('.nav-bar>li.has-flyout', this).on('mouseenter mouseleave', function (e) { if (e.type == 'mouseenter') { $('.nav-bar').find('.flyout').hide(); $(this).children('.flyout').show(); } if (e.type == 'mouseleave') { var flyout = $(this).children('.flyout'), inputs = flyout.find('input'), hasFocus = function (inputs) { var focus; if (inputs.length > 0) { inputs.each(function () { if ($(this).is(":focus")) { focus = true; } }); return focus; } return false; }; if (!hasFocus(inputs)) { $(this).children('.flyout').hide(); } } }); } }; })( jQuery, this );
JavaScript
// Place your application-specific JavaScript functions and classes here // This file is automatically included by javascript_include_tag :defaults
JavaScript
/** Copyright (c) 2005, Brad Neuberg, bkn3@columbia.edu http://codinginparadise.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The JSON class near the end of this file is Copyright 2005, JSON.org */ /** An object that provides DHTML history, history data, and bookmarking for AJAX applications. */ window.dhtmlHistory = { /** Initializes our DHTML history. You should call this after the page is finished loading. */ /** public */ initialize: function() { // only Internet Explorer needs to be explicitly initialized; // other browsers don't have its particular behaviors. // Basicly, IE doesn't autofill form data until the page // is finished loading, which means historyStorage won't // work until onload has been fired. if (this.isInternetExplorer() == false) { return; } // if this is the first time this page has loaded... if (historyStorage.hasKey("DhtmlHistory_pageLoaded") == false) { this.fireOnNewListener = false; this.firstLoad = true; historyStorage.put("DhtmlHistory_pageLoaded", true); } // else if this is a fake onload event else { this.fireOnNewListener = true; this.firstLoad = false; } }, /** Adds a history change listener. Note that only one listener is supported at this time. */ /** public */ addListener: function(callback) { this.listener = callback; // if the page was just loaded and we // should not ignore it, fire an event // to our new listener now if (this.fireOnNewListener == true) { this.fireHistoryEvent(this.currentLocation); this.fireOnNewListener = false; } }, /** public */ add: function(newLocation, historyData) { // most browsers require that we wait a certain amount of time before changing the // location, such as 200 milliseconds; rather than forcing external callers to use // window.setTimeout to account for this to prevent bugs, we internally handle this // detail by using a 'currentWaitTime' variable and have requests wait in line var self = this; var addImpl = function() { // indicate that the current wait time is now less if (self.currentWaitTime > 0) self.currentWaitTime = self.currentWaitTime - self.WAIT_TIME; // remove any leading hash symbols on newLocation newLocation = self.removeHash(newLocation); // IE has a strange bug; if the newLocation // is the same as _any_ preexisting id in the // document, then the history action gets recorded // twice; throw a programmer exception if there is // an element with this ID var idCheck = $(newLocation); if (idCheck != undefined || idCheck != null) { var message = "Exception: History locations can not have " + "the same value as _any_ id's " + "that might be in the document, " + "due to a bug in Internet " + "Explorer; please ask the " + "developer to choose a history " + "location that does not match " + "any HTML id's in this " + "document. The following ID " + "is already taken and can not " + "be a location: " + newLocation; throw message; } // store the history data into history storage historyStorage.put(newLocation, historyData); // indicate to the browser to ignore this upcomming // location change self.ignoreLocationChange = true; // indicate to IE that this is an atomic location change // block this.ieAtomicLocationChange = true; // save this as our current location self.currentLocation = newLocation; // change the browser location window.location.hash = newLocation; // change the hidden iframe's location if on IE if (self.isInternetExplorer()) self.iframe.src = "/blank.html?" + newLocation; // end of atomic location change block // for IE this.ieAtomicLocationChange = false; }; // now execute this add request after waiting a certain amount of time, so as to // queue up requests window.setTimeout(addImpl, this.currentWaitTime); // indicate that the next request will have to wait for awhile this.currentWaitTime = this.currentWaitTime + this.WAIT_TIME; }, /** public */ isFirstLoad: function() { if (this.firstLoad == true) { return true; } else { return false; } }, /** public */ isInternational: function() { return false; }, /** public */ getVersion: function() { return "0.05"; }, /** Gets the current hash value that is in the browser's location bar, removing leading # symbols if they are present. */ /** public */ getCurrentLocation: function() { var currentLocation = escape(this.removeHash(window.location.hash)); return currentLocation; }, /** Our current hash location, without the "#" symbol. */ /** private */ currentLocation: null, /** Our history change listener. */ /** private */ listener: null, /** A hidden IFrame we use in Internet Explorer to detect history changes. */ /** private */ iframe: null, /** Indicates to the browser whether to ignore location changes. */ /** private */ ignoreLocationChange: null, /** The amount of time in milliseconds that we should wait between add requests. Firefox is okay with 200 ms, but Internet Explorer needs 400. */ /** private */ WAIT_TIME: 200, /** The amount of time in milliseconds an add request has to wait in line before being run on a window.setTimeout. */ /** private */ currentWaitTime: 0, /** A flag that indicates that we should fire a history change event when we are ready, i.e. after we are initialized and we have a history change listener. This is needed due to an edge case in browsers other than Internet Explorer; if you leave a page entirely then return, we must fire this as a history change event. Unfortunately, we have lost all references to listeners from earlier, because JavaScript clears out. */ /** private */ fireOnNewListener: null, /** A variable that indicates whether this is the first time this page has been loaded. If you go to a web page, leave it for another one, and then return, the page's onload listener fires again. We need a way to differentiate between the first page load and subsequent ones. This variable works hand in hand with the pageLoaded variable we store into historyStorage.*/ /** private */ firstLoad: null, /** A variable to handle an important edge case in Internet Explorer. In IE, if a user manually types an address into their browser's location bar, we must intercept this by continiously checking the location bar with an timer interval. However, if we manually change the location bar ourselves programmatically, when using our hidden iframe, we need to ignore these changes. Unfortunately, these changes are not atomic, so we surround them with the variable 'ieAtomicLocationChange', that if true, means we are programmatically setting the location and should ignore this atomic chunked change. */ /** private */ ieAtomicLocationChange: null, /** Creates the DHTML history infrastructure. */ /** private */ create: function() { // get our initial location var initialHash = this.getCurrentLocation(); // save this as our current location this.currentLocation = initialHash; // write out a hidden iframe for IE and // set the amount of time to wait between add() requests if (this.isInternetExplorer()) { document.write("<iframe style='border: 0px; width: 1px; " + "height: 1px; position: absolute; bottom: 0px; " + "right: 0px; visibility: visible;' " + "name='DhtmlHistoryFrame' id='DhtmlHistoryFrame' " + "src='/blank.html?" + initialHash + "'>" + "</iframe>"); // wait 400 milliseconds between history // updates on IE, versus 200 on Firefox this.WAIT_TIME = 400; } // add an unload listener for the page; this is // needed for Firefox 1.5+ because this browser caches all // dynamic updates to the page, which can break some of our // logic related to testing whether this is the first instance // a page has loaded or whether it is being pulled from the cache var self = this; window.onunload = function() { self.firstLoad = null; }; // determine if this is our first page load; // for Internet Explorer, we do this in // this.iframeLoaded(), which is fired on // page load. We do it there because // we have no historyStorage at this point // in IE, which only exists after the page // is finished loading for that browser if (this.isInternetExplorer() == false) { if (historyStorage.hasKey("DhtmlHistory_pageLoaded") == false) { this.ignoreLocationChange = true; this.firstLoad = true; historyStorage.put("DhtmlHistory_pageLoaded", true); } else { // indicate that we want to pay attention // to this location change this.ignoreLocationChange = false; // For browser's other than IE, fire // a history change event; on IE, // the event will be thrown automatically // when it's hidden iframe reloads // on page load. // Unfortunately, we don't have any // listeners yet; indicate that we want // to fire an event when a listener // is added. this.fireOnNewListener = true; } } else { // Internet Explorer // the iframe will get loaded on page // load, and we want to ignore this fact this.ignoreLocationChange = true; } if (this.isInternetExplorer()) { this.iframe = $("DhtmlHistoryFrame"); } // other browsers can use a location handler that checks // at regular intervals as their primary mechanism; // we use it for Internet Explorer as well to handle // an important edge case; see checkLocation() for // details var self = this; var locationHandler = function() { self.checkLocation(); }; setInterval(locationHandler, 100); }, /** Notify the listener of new history changes. */ /** private */ fireHistoryEvent: function(newHash) { // extract the value from our history storage for // this hash var historyData = historyStorage.get(newHash); // call our listener this.listener.call(null, newHash, historyData); }, /** Sees if the browsers has changed location. This is the primary history mechanism for Firefox. For Internet Explorer, we use this to handle an important edge case: if a user manually types in a new hash value into their Internet Explorer location bar and press enter, we want to intercept this and notify any history listener. */ /** private */ checkLocation: function() { // ignore any location changes that we made ourselves // for browsers other than Internet Explorer if (this.isInternetExplorer() == false && this.ignoreLocationChange == true) { this.ignoreLocationChange = false; return; } // if we are dealing with Internet Explorer // and we are in the middle of making a location // change from an iframe, ignore it if (this.isInternetExplorer() == false && this.ieAtomicLocationChange == true) { return; } // get hash location var hash = this.getCurrentLocation(); // see if there has been a change if (hash == this.currentLocation) return; // on Internet Explorer, we need to intercept users manually // entering locations into the browser; we do this by comparing // the browsers location against the iframes location; if they // differ, we are dealing with a manual event and need to // place it inside our history, otherwise we can return this.ieAtomicLocationChange = true; if (this.isInternetExplorer() && this.getIFrameHash() != hash) { this.iframe.src = "/blank.html?" + hash; } else if (this.isInternetExplorer()) { // the iframe is unchanged return; } // save this new location this.currentLocation = hash; this.ieAtomicLocationChange = false; // notify listeners of the change this.fireHistoryEvent(hash); }, /** Gets the current location of the hidden IFrames that is stored as history. For Internet Explorer. */ /** private */ getIFrameHash: function() { // get the new location var historyFrame = $("DhtmlHistoryFrame"); var doc = historyFrame.contentWindow.document; var hash = new String(doc.location.search); if (hash.length == 1 && hash.charAt(0) == "?") hash = ""; else if (hash.length >= 2 && hash.charAt(0) == "?") hash = hash.substring(1); return hash; }, /** Removes any leading hash that might be on a location. */ /** private */ removeHash: function(hashValue) { if (hashValue == null || hashValue == undefined) return null; else if (hashValue == "") return ""; else if (hashValue.length == 1 && hashValue.charAt(0) == "#") return ""; else if (hashValue.length > 1 && hashValue.charAt(0) == "#") return hashValue.substring(1); else return hashValue; }, /** For IE, says when the hidden iframe has finished loading. */ /** private */ iframeLoaded: function(newLocation) { // ignore any location changes that we made ourselves if (this.ignoreLocationChange == true) { this.ignoreLocationChange = false; return; } // get the new location var hash = new String(newLocation.search); if (hash.length == 1 && hash.charAt(0) == "?") hash = ""; else if (hash.length >= 2 && hash.charAt(0) == "?") hash = hash.substring(1); // move to this location in the browser location bar // if we are not dealing with a page load event if (this.pageLoadEvent != true) { window.location.hash = hash; } // notify listeners of the change this.fireHistoryEvent(hash); }, /** Determines if this is Internet Explorer. */ /** private */ isInternetExplorer: function() { var userAgent = navigator.userAgent.toLowerCase(); if (document.all && userAgent.indexOf('msie')!=-1) { return true; } else { return false; } } }; /** An object that uses a hidden form to store history state across page loads. The chief mechanism for doing so is using the fact that browser's save the text in form data for the life of the browser and cache, which means the text is still there when the user navigates back to the page. See http://codinginparadise.org/weblog/2005/08/ajax-tutorial-saving-session-across.html for full details. */ window.historyStorage = { /** If true, we are debugging and show the storage textfield. */ /** public */ debugging: false, /** Our hash of key name/values. */ /** private */ storageHash: new Object(), /** If true, we have loaded our hash table out of the storage form. */ /** private */ hashLoaded: false, /** public */ put: function(key, value) { this.assertValidKey(key); // if we already have a value for this, // remove the value before adding the // new one if (this.hasKey(key)) { this.remove(key); } // store this new key this.storageHash[key] = value; // save and serialize the hashtable into the form this.saveHashTable(); }, /** public */ get: function(key) { this.assertValidKey(key); // make sure the hash table has been loaded // from the form this.loadHashTable(); var value = this.storageHash[key]; if (value == undefined) return null; else return value; }, /** public */ remove: function(key) { this.assertValidKey(key); // make sure the hash table has been loaded // from the form this.loadHashTable(); // delete the value delete this.storageHash[key]; // serialize and save the hash table into the // form this.saveHashTable(); }, /** Clears out all saved data. */ /** public */ reset: function() { this.storageField.value = ""; this.storageHash = new Object(); }, /** public */ hasKey: function(key) { this.assertValidKey(key); // make sure the hash table has been loaded // from the form this.loadHashTable(); if (typeof this.storageHash[key] == "undefined") return false; else return true; }, /** public */ isValidKey: function(key) { // allow all strings, since we don't use XML serialization // format anymore return (typeof key == "string"); }, /** A reference to our textarea field. */ /** private */ storageField: null, /** private */ init: function() { /** simplified newContent from <div><form><input/></form></div> to fix an IE display glitch */ var newContent = "<input type='text' id='historyStorageField' name='historyStorageField' style='display: none;'/>"; document.write(newContent); this.storageField = $("historyStorageField"); }, /** Asserts that a key is valid, throwing an exception if it is not. */ /** private */ assertValidKey: function(key) { if (this.isValidKey(key) == false) { throw "Please provide a valid key for " + "window.historyStorage, key= " + key; } }, /** Loads the hash table up from the form. */ /** private */ loadHashTable: function() { if (this.hashLoaded == false) { // get the hash table as a serialized // string var serializedHashTable = this.storageField.value; if (serializedHashTable != "" && serializedHashTable != null) { // destringify the content back into a // real JavaScript object this.storageHash = eval('(' + serializedHashTable + ')'); } this.hashLoaded = true; } }, /** Saves the hash table into the form. */ /** private */ saveHashTable: function() { this.loadHashTable(); // serialized the hash table var serializedHashTable = JSON.stringify(this.storageHash); // save this value this.storageField.value = serializedHashTable; } }; /** The JSON class is copyright 2005 JSON.org. */ Array.prototype.______array = '______array'; var JSON = { org: 'http://www.JSON.org', copyright: '(c)2005 JSON.org', license: 'http://www.crockford.com/JSON/license.html', stringify: function (arg) { var c, i, l, s = '', v; switch (typeof arg) { case 'object': if (arg) { if (arg.______array == '______array') { for (i = 0; i < arg.length; ++i) { v = this.stringify(arg[i]); if (s) { s += ','; } s += v; } return '[' + s + ']'; } else if (typeof arg.toString != 'undefined') { for (i in arg) { v = arg[i]; if (typeof v != 'undefined' && typeof v != 'function') { v = this.stringify(v); if (s) { s += ','; } s += this.stringify(i) + ':' + v; } } return '{' + s + '}'; } } return 'null'; case 'number': return isFinite(arg) ? String(arg) : 'null'; case 'string': l = arg.length; s = '"'; for (i = 0; i < l; i += 1) { c = arg.charAt(i); if (c >= ' ') { if (c == '\\' || c == '"') { s += '\\'; } s += c; } else { switch (c) { case '\b': s += '\\b'; break; case '\f': s += '\\f'; break; case '\n': s += '\\n'; break; case '\r': s += '\\r'; break; case '\t': s += '\\t'; break; default: c = c.charCodeAt(); s += '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); } } } return s + '"'; case 'boolean': return String(arg); default: return 'null'; } }, parse: function (text) { var at = 0; var ch = ' '; function error(m) { throw { name: 'JSONError', message: m, at: at - 1, text: text }; } function next() { ch = text.charAt(at); at += 1; return ch; } function white() { while (ch != '' && ch <= ' ') { next(); } } function str() { var i, s = '', t, u; if (ch == '"') { outer: while (next()) { if (ch == '"') { next(); return s; } else if (ch == '\\') { switch (next()) { case 'b': s += '\b'; break; case 'f': s += '\f'; break; case 'n': s += '\n'; break; case 'r': s += '\r'; break; case 't': s += '\t'; break; case 'u': u = 0; for (i = 0; i < 4; i += 1) { t = parseInt(next(), 16); if (!isFinite(t)) { break outer; } u = u * 16 + t; } s += String.fromCharCode(u); break; default: s += ch; } } else { s += ch; } } } error("Bad string"); } function arr() { var a = []; if (ch == '[') { next(); white(); if (ch == ']') { next(); return a; } while (ch) { a.push(val()); white(); if (ch == ']') { next(); return a; } else if (ch != ',') { break; } next(); white(); } } error("Bad array"); } function obj() { var k, o = {}; if (ch == '{') { next(); white(); if (ch == '}') { next(); return o; } while (ch) { k = str(); white(); if (ch != ':') { break; } next(); o[k] = val(); white(); if (ch == '}') { next(); return o; } else if (ch != ',') { break; } next(); white(); } } error("Bad object"); } function num() { var n = '', v; if (ch == '-') { n = '-'; next(); } while (ch >= '0' && ch <= '9') { n += ch; next(); } if (ch == '.') { n += '.'; while (next() && ch >= '0' && ch <= '9') { n += ch; } } if (ch == 'e' || ch == 'E') { n += 'e'; next(); if (ch == '-' || ch == '+') { n += ch; next(); } while (ch >= '0' && ch <= '9') { n += ch; next(); } } v = +n; if (!isFinite(v)) { error("Bad number"); } else { return v; } } function word() { switch (ch) { case 't': if (next() == 'r' && next() == 'u' && next() == 'e') { next(); return true; } break; case 'f': if (next() == 'a' && next() == 'l' && next() == 's' && next() == 'e') { next(); return false; } break; case 'n': if (next() == 'u' && next() == 'l' && next() == 'l') { next(); return null; } break; } error("Syntax error"); } function val() { white(); switch (ch) { case '{': return obj(); case '[': return arr(); case '"': return str(); case '-': return num(); default: return ch >= '0' && ch <= '9' ? num() : word(); } } return val(); } }; /** QueryString Object from http://adamv.com/dev/javascript/querystring */ /* Client-side access to querystring name=value pairs Version 1.2.3 22 Jun 2005 Adam Vandenberg */ function Querystring(qs) { // optionally pass a querystring to parse this.params = new Object() this.get=Querystring_get if (qs == null) qs=location.search.substring(1,location.search.length) if (qs.length == 0) return // Turn <plus> back to <space> // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1 qs = qs.replace(/\+/g, ' ') // added by Scott Rutherford, change all &amp; to & qs = qs.replace(/&amp;/g, '&') var args = qs.split('&') // parse out name/value pairs separated via & // split out each name=value pair for (var i=0;i<args.length;i++) { var value; var pair = args[i].split('=') var name = unescape(pair[0]) if (pair.length == 2) value = unescape(pair[1]) else value = name this.params[name] = value } } function Querystring_get(key, default_) { // This silly looking line changes UNDEFINED to NULL if (default_ == null) default_ = null; var value=this.params[key] if (value==null) value=default_; return value } /** ADDED BY SCOTT RUTHERFORD, COMINDED July 2006 scott@cominded */ /** Initialize all of our objects now. */ window.historyStorage.init(); window.dhtmlHistory.create(); /** Create init methods for ActiveScaffold */ function initialize() { // initialize our DHTML history dhtmlHistory.initialize(); // subscribe to DHTML history change // events dhtmlHistory.addListener(handleHistoryChange); } /** Our callback to receive history change events. */ function handleHistoryChange(pageId, pageData) { if (!pageData) return; var info = pageId.split(':'); var id = info[0]; pageData += '&_method=get'; new Ajax.Updater(id+'-content', pageData, {asynchronous:true, evalScripts:true, onLoading:function(request){Element.show(id+'-pagination-loading-indicator');}}); } /** set onload handler */ Event.observe(window, 'load', initialize, false);
JavaScript
// TODO Change to dropping the name property off the input element when in example mode TextFieldWithExample = Class.create(); TextFieldWithExample.prototype = { initialize: function(inputElementId, defaultText, options) { this.setOptions(options); this.input = $(inputElementId); this.name = this.input.name; this.defaultText = defaultText; this.createHiddenInput(); this.checkAndShowExample(); Event.observe(this.input, "blur", this.onBlur.bindAsEventListener(this)); Event.observe(this.input, "focus", this.onFocus.bindAsEventListener(this)); Event.observe(this.input, "select", this.onFocus.bindAsEventListener(this)); Event.observe(this.input, "keydown", this.onKeyPress.bindAsEventListener(this)); Event.observe(this.input, "click", this.onClick.bindAsEventListener(this)); }, createHiddenInput: function() { this.hiddenInput = document.createElement("input"); this.hiddenInput.type = "hidden"; this.hiddenInput.value = ""; this.input.parentNode.appendChild(this.hiddenInput); }, setOptions: function(options) { this.options = { exampleClassName: 'example' }; Object.extend(this.options, options || {}); }, onKeyPress: function(event) { if (!event) var event = window.event; var code = (event.which) ? event.which : event.keyCode if (this.isAlphanumeric(code)) { this.removeExample(); } }, onBlur: function(event) { this.checkAndShowExample(); }, onFocus: function(event) { if (this.exampleShown()) { this.removeExample(); } }, onClick: function(event) { this.removeExample(); }, isAlphanumeric: function(keyCode) { return keyCode >= 40 && keyCode <= 90; }, checkAndShowExample: function() { if (this.input.value == '') { this.input.value = this.defaultText; this.input.name = null; this.hiddenInput.name = this.name; Element.addClassName(this.input, this.options.exampleClassName); } }, removeExample: function() { if (this.exampleShown()) { this.input.value = ''; this.input.name = this.name; this.hiddenInput.name = null; Element.removeClassName(this.input, this.options.exampleClassName); } }, exampleShown: function() { return Element.hasClassName(this.input, this.options.exampleClassName); } } Form.disable = function(form) { var elements = this.getElements(form); for (var i = 0; i < elements.length; i++) { var element = elements[i]; try { element.blur(); } catch (e) {} element.disabled = 'disabled'; Element.addClassName(element, 'disabled'); } } Form.enable = function(form) { var elements = this.getElements(form); for (var i = 0; i < elements.length; i++) { var element = elements[i]; element.disabled = ''; Element.removeClassName(element, 'disabled'); } }
JavaScript
/** * * Copyright 2005 Sabre Airline Solutions * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. **/ //-------------------- rico.js var Rico = { Version: '1.1.0', prototypeVersion: parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]) } //-------------------- ricoColor.js Rico.Color = Class.create(); Rico.Color.prototype = { initialize: function(red, green, blue) { this.rgb = { r: red, g : green, b : blue }; }, blend: function(other) { this.rgb.r = Math.floor((this.rgb.r + other.rgb.r)/2); this.rgb.g = Math.floor((this.rgb.g + other.rgb.g)/2); this.rgb.b = Math.floor((this.rgb.b + other.rgb.b)/2); }, asRGB: function() { return "rgb(" + this.rgb.r + "," + this.rgb.g + "," + this.rgb.b + ")"; }, asHex: function() { return "#" + this.rgb.r.toColorPart() + this.rgb.g.toColorPart() + this.rgb.b.toColorPart(); }, asHSB: function() { return Rico.Color.RGBtoHSB(this.rgb.r, this.rgb.g, this.rgb.b); }, toString: function() { return this.asHex(); } }; Rico.Color.createFromHex = function(hexCode) { if(hexCode.length==4) { var shortHexCode = hexCode; var hexCode = '#'; for(var i=1;i<4;i++) hexCode += (shortHexCode.charAt(i) + shortHexCode.charAt(i)); } if ( hexCode.indexOf('#') == 0 ) hexCode = hexCode.substring(1); var red = hexCode.substring(0,2); var green = hexCode.substring(2,4); var blue = hexCode.substring(4,6); return new Rico.Color( parseInt(red,16), parseInt(green,16), parseInt(blue,16) ); } /** * Factory method for creating a color from the background of * an HTML element. */ Rico.Color.createColorFromBackground = function(elem) { //var actualColor = RicoUtil.getElementsComputedStyle($(elem), "backgroundColor", "background-color"); // Changed to prototype style var actualColor = $(elem).getStyle('backgroundColor'); if ( actualColor == "transparent" && elem.parentNode ) return Rico.Color.createColorFromBackground(elem.parentNode); if ( actualColor == null ) return new Rico.Color(255,255,255); if ( actualColor.indexOf("rgb(") == 0 ) { var colors = actualColor.substring(4, actualColor.length - 1 ); var colorArray = colors.split(","); return new Rico.Color( parseInt( colorArray[0] ), parseInt( colorArray[1] ), parseInt( colorArray[2] ) ); } else if ( actualColor.indexOf("#") == 0 ) { return Rico.Color.createFromHex(actualColor); } else return new Rico.Color(255,255,255); } /* next two functions changed to mootools color.js functions */ Rico.Color.HSBtoRGB = function(hue, saturation, brightness) { var br = Math.round(brightness / 100 * 255); if (this[1] == 0){ return [br, br, br]; } else { var hue = this[0] % 360; var f = hue % 60; var p = Math.round((brightness * (100 - saturation)) / 10000 * 255); var q = Math.round((brightness * (6000 - saturation * f)) / 600000 * 255); var t = Math.round((brightness * (6000 - saturation * (60 - f))) / 600000 * 255); switch(Math.floor(hue / 60)){ case 0: return { r : br, g : t, b : p }; case 1: return { r : q, g : br, b : p }; case 2: return { r : p, g : br, b : t }; case 3: return { r : p, g : q, b : br }; case 4: return { r : t, g : p, b : br }; case 5: return { r : br, g : p, b : q }; } } return false; } Rico.Color.RGBtoHSB = function(red, green, blue) { 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 { h : Math.round(hue * 360), s : Math.round(saturation * 100), b : Math.round(brightness * 100)}; } //-------------------- ricoCorner.js Rico.Corner = { round: function(e, options) { var e = $(e); this._setOptions(options); var color = this.options.color; if ( this.options.color == "fromElement" ) color = this._background(e); var bgColor = this.options.bgColor; if ( this.options.bgColor == "fromParent" ) bgColor = this._background(e.offsetParent); this._roundCornersImpl(e, color, bgColor); }, _roundCornersImpl: function(e, color, bgColor) { if(this.options.border) this._renderBorder(e,bgColor); if(this._isTopRounded()) this._roundTopCorners(e,color,bgColor); if(this._isBottomRounded()) this._roundBottomCorners(e,color,bgColor); }, _renderBorder: function(el,bgColor) { var borderValue = "1px solid " + this._borderColor(bgColor); var borderL = "border-left: " + borderValue; var borderR = "border-right: " + borderValue; var style = "style='" + borderL + ";" + borderR + "'"; el.innerHTML = "<div " + style + ">" + el.innerHTML + "</div>" }, _roundTopCorners: function(el, color, bgColor) { var corner = this._createCorner(bgColor); for(var i=0 ; i < this.options.numSlices ; i++ ) corner.appendChild(this._createCornerSlice(color,bgColor,i,"top")); el.style.paddingTop = 0; el.insertBefore(corner,el.firstChild); }, _roundBottomCorners: function(el, color, bgColor) { var corner = this._createCorner(bgColor); for(var i=(this.options.numSlices-1) ; i >= 0 ; i-- ) corner.appendChild(this._createCornerSlice(color,bgColor,i,"bottom")); el.style.paddingBottom = 0; el.appendChild(corner); }, _createCorner: function(bgColor) { var corner = document.createElement("div"); corner.style.backgroundColor = (this._isTransparent() ? "transparent" : bgColor); return corner; }, _createCornerSlice: function(color,bgColor, n, position) { var slice = document.createElement("span"); var inStyle = slice.style; inStyle.backgroundColor = color; inStyle.display = "block"; inStyle.height = "1px"; inStyle.overflow = "hidden"; inStyle.fontSize = "1px"; var borderColor = this._borderColor(color,bgColor); if ( this.options.border && n == 0 ) { inStyle.borderTopStyle = "solid"; inStyle.borderTopWidth = "1px"; inStyle.borderLeftWidth = "0px"; inStyle.borderRightWidth = "0px"; inStyle.borderBottomWidth = "0px"; inStyle.height = "0px"; // assumes css compliant box model inStyle.borderColor = borderColor; } else if(borderColor) { inStyle.borderColor = borderColor; inStyle.borderStyle = "solid"; inStyle.borderWidth = "0px 1px"; } if ( !this.options.compact && (n == (this.options.numSlices-1)) ) inStyle.height = "2px"; this._setMargin(slice, n, position); this._setBorder(slice, n, position); return slice; }, _setOptions: function(options) { this.options = { corners : "all", color : "fromElement", bgColor : "fromParent", blend : true, border : false, compact : false } Object.extend(this.options, options || {}); this.options.numSlices = this.options.compact ? 2 : 4; if ( this._isTransparent() ) this.options.blend = false; }, _whichSideTop: function() { if ( this._hasString(this.options.corners, "all", "top") ) return ""; if ( this.options.corners.indexOf("tl") >= 0 && this.options.corners.indexOf("tr") >= 0 ) return ""; if (this.options.corners.indexOf("tl") >= 0) return "left"; else if (this.options.corners.indexOf("tr") >= 0) return "right"; return ""; }, _whichSideBottom: function() { if ( this._hasString(this.options.corners, "all", "bottom") ) return ""; if ( this.options.corners.indexOf("bl")>=0 && this.options.corners.indexOf("br")>=0 ) return ""; if(this.options.corners.indexOf("bl") >=0) return "left"; else if(this.options.corners.indexOf("br")>=0) return "right"; return ""; }, _borderColor : function(color,bgColor) { if ( color == "transparent" ) return bgColor; else if ( this.options.border ) return this.options.border; else if ( this.options.blend ) return this._blend( bgColor, color ); else return ""; }, _setMargin: function(el, n, corners) { var marginSize = this._marginSize(n); var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom(); if ( whichSide == "left" ) { el.style.marginLeft = marginSize + "px"; el.style.marginRight = "0px"; } else if ( whichSide == "right" ) { el.style.marginRight = marginSize + "px"; el.style.marginLeft = "0px"; } else { el.style.marginLeft = marginSize + "px"; el.style.marginRight = marginSize + "px"; } }, _setBorder: function(el,n,corners) { var borderSize = this._borderSize(n); var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom(); if ( whichSide == "left" ) { el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = "0px"; } else if ( whichSide == "right" ) { el.style.borderRightWidth = borderSize + "px"; el.style.borderLeftWidth = "0px"; } else { el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px"; } if (this.options.border != false) el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px"; }, _marginSize: function(n) { if ( this._isTransparent() ) return 0; var marginSizes = [ 5, 3, 2, 1 ]; var blendedMarginSizes = [ 3, 2, 1, 0 ]; var compactMarginSizes = [ 2, 1 ]; var smBlendedMarginSizes = [ 1, 0 ]; if ( this.options.compact && this.options.blend ) return smBlendedMarginSizes[n]; else if ( this.options.compact ) return compactMarginSizes[n]; else if ( this.options.blend ) return blendedMarginSizes[n]; else return marginSizes[n]; }, _borderSize: function(n) { var transparentBorderSizes = [ 5, 3, 2, 1 ]; var blendedBorderSizes = [ 2, 1, 1, 1 ]; var compactBorderSizes = [ 1, 0 ]; var actualBorderSizes = [ 0, 2, 0, 0 ]; if ( this.options.compact && (this.options.blend || this._isTransparent()) ) return 1; else if ( this.options.compact ) return compactBorderSizes[n]; else if ( this.options.blend ) return blendedBorderSizes[n]; else if ( this.options.border ) return actualBorderSizes[n]; else if ( this._isTransparent() ) return transparentBorderSizes[n]; return 0; }, _hasString: function(str) { for(var i=1 ; i<arguments.length ; i++) if (str.indexOf(arguments[i]) >= 0) return true; return false; }, _blend: function(c1, c2) { var cc1 = Rico.Color.createFromHex(c1); cc1.blend(Rico.Color.createFromHex(c2)); return cc1; }, _background: function(el) { try { return Rico.Color.createColorFromBackground(el).asHex(); } catch(err) { return "#ffffff"; } }, _isTransparent: function() { return this.options.color == "transparent"; }, _isTopRounded: function() { return this._hasString(this.options.corners, "all", "top", "tl", "tr"); }, _isBottomRounded: function() { return this._hasString(this.options.corners, "all", "bottom", "bl", "br"); }, _hasSingleTextChild: function(el) { return el.childNodes.length == 1 && el.childNodes[0].nodeType == 3; } }
JavaScript
if (typeof Prototype == 'undefined') { warning = "ActiveScaffold Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (e.g. <%= javascript_include_tag :defaults %>) *before* it includes active_scaffold.js (e.g. <%= active_scaffold_includes %>)."; alert(warning); } if (Prototype.Version.substring(0, 8) == '1.5.0_rc') { warning = "ActiveScaffold Error: Prototype 1.5.0_rc is not supported. Please update prototype.js (rake rails:update:javascripts)."; alert(warning); } /* * Simple utility methods */ var ActiveScaffold = { records_for: function(tbody_id) { var rows = []; var child = $(tbody_id).down('.record'); while (child) { rows.push(child); child = child.next('.record'); } return rows; }, stripe: function(tbody_id) { var even = false; var rows = this.records_for(tbody_id); for (var i = 0; i < rows.length; i++) { var child = rows[i]; //Make sure to skip rows that are create or edit rows or messages if (child.tagName != 'SCRIPT' && !child.hasClassName("create") && !child.hasClassName("update") && !child.hasClassName("inline-adapter") && !child.hasClassName("active-scaffold-calculations")) { if (even) child.addClassName("even-record"); else child.removeClassName("even-record"); even = !even; } } }, hide_empty_message: function(tbody, empty_message_id) { if (this.records_for(tbody).length != 0) { $(empty_message_id).hide(); } }, reload_if_empty: function(tbody, url) { var content_container_id = tbody.replace('tbody', 'content'); if (this.records_for(tbody).length == 0) { new Ajax.Updater($(content_container_id), url, { method: 'get', asynchronous: true, evalScripts: true }); } }, removeSortClasses: function(scaffold_id) { $$('#' + scaffold_id + ' td.sorted').each(function(element) { element.removeClassName("sorted"); }); $$('#' + scaffold_id + ' th.sorted').each(function(element) { element.removeClassName("sorted"); element.removeClassName("asc"); element.removeClassName("desc"); }); }, decrement_record_count: function(scaffold_id) { count = $$('#' + scaffold_id + ' span.active-scaffold-records').first(); count.innerHTML = parseInt(count.innerHTML) - 1; }, increment_record_count: function(scaffold_id) { count = $$('#' + scaffold_id + ' span.active-scaffold-records').first(); count.innerHTML = parseInt(count.innerHTML) + 1; }, server_error_response: '', report_500_response: function(active_scaffold_id) { messages_container = $(active_scaffold_id).down('td.messages-container'); new Insertion.Top(messages_container, this.server_error_response); } } /* * DHTML history tie-in */ function addActiveScaffoldPageToHistory(url, active_scaffold_id) { if (typeof dhtmlHistory == 'undefined') return; // it may not be loaded var array = url.split('?'); var qs = new Querystring(array[1]); var sort = qs.get('sort') var dir = qs.get('sort_direction') var page = qs.get('page') if (sort || dir || page) dhtmlHistory.add(active_scaffold_id+":"+page+":"+sort+":"+dir, url); } /* * Add-ons/Patches to Prototype */ /* patch to support replacing TR/TD/TBODY in Internet Explorer, courtesy of http://dev.rubyonrails.org/ticket/4273 */ Element.replace = function(element, html) { element = $(element); if (element.outerHTML) { try { element.outerHTML = html.stripScripts(); } catch (e) { var tn = element.tagName; if(tn=='TBODY' || tn=='TR' || tn=='TD') { var tempDiv = document.createElement("div"); tempDiv.innerHTML = '<table id="tempTable" style="display: none">' + html.stripScripts() + '</table>'; element.parentNode.replaceChild(tempDiv.getElementsByTagName(tn).item(0), element); } else throw e; } } else { var range = element.ownerDocument.createRange(); /* patch to fix <form> replaces in Firefox. see http://dev.rubyonrails.org/ticket/8010 */ range.selectNodeContents(element.parentNode); element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()), element); } setTimeout(function() {html.evalScripts()}, 10); return element; }; /* * URL modification support. Incomplete functionality. */ Object.extend(String.prototype, { append_params: function(params) { url = this; if (url.indexOf('?') == -1) url += '?'; else if (url.lastIndexOf('&') != url.length) url += '&'; url += $H(params).collect(function(item) { return item.key + '=' + item.value; }).join('&'); return url; } }); /* * Prototype's implementation was throwing an error instead of false */ Element.Methods.Simulated = { hasAttribute: function(element, attribute) { var t = Element._attributeTranslations; attribute = (t.names && t.names[attribute]) || attribute; // Return false if we get an error here try { return $(element).getAttributeNode(attribute).specified; } catch (e) { return false; } } }; /** * A set of links. As a set, they can be controlled such that only one is "open" at a time, etc. */ ActiveScaffold.Actions = new Object(); ActiveScaffold.Actions.Abstract = function(){} ActiveScaffold.Actions.Abstract.prototype = { initialize: function(links, target, loading_indicator, options) { this.target = $(target); this.loading_indicator = $(loading_indicator); this.options = options; this.links = links.collect(function(link) { return this.instantiate_link(link); }.bind(this)); }, instantiate_link: function(link) { throw 'unimplemented' } } /** * A DataStructures::ActionLink, represented in JavaScript. * Concerned with AJAX-enabling a link and adapting the result for insertion into the table. */ ActiveScaffold.ActionLink = new Object(); ActiveScaffold.ActionLink.Abstract = function(){} ActiveScaffold.ActionLink.Abstract.prototype = { initialize: function(a, target, loading_indicator) { this.tag = $(a); this.url = this.tag.href; this.target = target; this.loading_indicator = loading_indicator; this.hide_target = false; this.position = this.tag.getAttribute('position'); this.page_link = this.tag.getAttribute('page_link'); this.onclick = this.tag.onclick; this.tag.onclick = null; this.tag.observe('click', function(event) { this.open(); Event.stop(event); }.bind(this)); this.tag.action_link = this; }, open: function() { if (this.is_disabled()) return; if (this.tag.hasAttribute( "dhtml_confirm")) { if (this.onclick) this.onclick(); return; } else { if (this.onclick && !this.onclick()) return;//e.g. confirmation messages this.open_action(); } }, open_action: function() { if (this.position) this.disable(); if (this.page_link) { window.location = this.url; } else { if (this.loading_indicator) this.loading_indicator.style.visibility = 'visible'; new Ajax.Request(this.url, { asynchronous: true, evalScripts: true, onSuccess: function(request) { if (this.position) { this.insert(request.responseText); if (this.hide_target) this.target.hide(); } else { request.evalResponse(); } }.bind(this), onFailure: function(request) { ActiveScaffold.report_500_response(this.scaffold_id()); if (this.position) this.enable() }.bind(this), onComplete: function(request) { if (this.loading_indicator) this.loading_indicator.style.visibility = 'hidden'; }.bind(this) }); } }, insert: function(content) { throw 'unimplemented' }, close: function() { this.enable(); this.adapter.remove(); if (this.hide_target) this.target.show(); }, register_cancel_hooks: function() { // anything in the insert with a class of cancel gets the closer method, and a reference to this object for good measure var self = this; this.adapter.getElementsByClassName('cancel').each(function(elem) { elem.observe('click', this.close_handler.bind(this)); elem.link = self; }.bind(this)) }, reload: function() { this.close(); this.open(); }, get_new_adapter_id: function() { var id = 'adapter_'; var i = 0; while ($(id + i)) i++; return id + i; }, enable: function() { return this.tag.removeClassName('disabled'); }, disable: function() { return this.tag.addClassName('disabled'); }, is_disabled: function() { return this.tag.hasClassName('disabled'); }, scaffold_id: function() { return this.tag.up('div.active-scaffold').id; } } /** * Concrete classes for record actions */ ActiveScaffold.Actions.Record = Class.create(); ActiveScaffold.Actions.Record.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), { instantiate_link: function(link) { var l = new ActiveScaffold.ActionLink.Record(link, this.target, this.loading_indicator); l.refresh_url = this.options.refresh_url; if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'}); l.set = this; return l; } }); ActiveScaffold.ActionLink.Record = Class.create(); ActiveScaffold.ActionLink.Record.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), { insert: function(content) { this.set.links.each(function(item) { if (item.url != this.url && item.is_disabled() && item.adapter) item.close(); }.bind(this)); if (this.position == 'replace') { this.position = 'after'; this.hide_target = true; } if (this.position == 'after') { new Insertion.After(this.target, content); this.adapter = this.target.next(); } else if (this.position == 'before') { new Insertion.Before(this.target, content); this.adapter = this.target.previous(); } else { return false; } this.adapter.down('a.inline-adapter-close').observe('click', this.close_handler.bind(this)); this.register_cancel_hooks(); new Effect.Highlight(this.adapter.down('td')); }, close_handler: function(event) { this.close_with_refresh(); if (event) Event.stop(event); }, /* it might simplify things to just override the close function. then the Record and Table links could share more code ... wouldn't need custom close_handler functions, for instance */ close_with_refresh: function() { new Ajax.Request(this.refresh_url, { asynchronous: true, evalScripts: true, onSuccess: function(request) { Element.replace(this.target, request.responseText); var new_target = $(this.target.id); if (this.target.hasClassName('even-record')) new_target.addClassName('even-record'); this.target = new_target; this.close(); }.bind(this), onFailure: function(request) { ActiveScaffold.report_500_response(this.scaffold_id()); } }); }, enable: function() { this.set.links.each(function(item) { if (item.url != this.url) return; item.tag.removeClassName('disabled'); }.bind(this)); }, disable: function() { this.set.links.each(function(item) { if (item.url != this.url) return; item.tag.addClassName('disabled'); }.bind(this)); } }); /** * Concrete classes for table actions */ ActiveScaffold.Actions.Table = Class.create(); ActiveScaffold.Actions.Table.prototype = Object.extend(new ActiveScaffold.Actions.Abstract(), { instantiate_link: function(link) { var l = new ActiveScaffold.ActionLink.Table(link, this.target, this.loading_indicator); if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'}); return l; } }); ActiveScaffold.ActionLink.Table = Class.create(); ActiveScaffold.ActionLink.Table.prototype = Object.extend(new ActiveScaffold.ActionLink.Abstract(), { insert: function(content) { if (this.position == 'top') { new Insertion.Top(this.target, content); this.adapter = this.target.immediateDescendants().first(); } else { throw 'Unknown position "' + this.position + '"' } this.adapter.down('a.inline-adapter-close').observe('click', this.close_handler.bind(this)); this.register_cancel_hooks(); new Effect.Highlight(this.adapter.down('td')); }, close_handler: function(event) { this.close(); if (event) Event.stop(event); } });
JavaScript
// Flash Player Version Detection - Rev 1.6 // Detect Client Browser type // Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved. var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false; function ControlVersion() { var version; var axo; var e; // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry try { // version will be set for 7.X or greater players axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); version = axo.GetVariable("$version"); } catch (e) { } if (!version) { try { // version will be set for 6.X players only axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); // installed player is some revision of 6.0 // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29, // so we have to be careful. // default to the first public version version = "WIN 6,0,21,0"; // throws if AllowScripAccess does not exist (introduced in 6.0r47) axo.AllowScriptAccess = "always"; // safe to call for 6.0r47 or greater version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 4.X or 5.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 3.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = "WIN 3,0,18,0"; } catch (e) { } } if (!version) { try { // version will be set for 2.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); version = "WIN 2,0,0,11"; } catch (e) { version = -1; } } return version; } // JavaScript helper required to detect Flash Player PlugIn version information function GetSwfVer(){ // NS/Opera version >= 3 check for Flash plugin in plugin array var flashVer = -1; if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; var descArray = flashDescription.split(" "); var tempArrayMajor = descArray[2].split("."); var versionMajor = tempArrayMajor[0]; var versionMinor = tempArrayMajor[1]; var versionRevision = descArray[3]; if (versionRevision == "") { versionRevision = descArray[4]; } if (versionRevision[0] == "d") { versionRevision = versionRevision.substring(1); } else if (versionRevision[0] == "r") { versionRevision = versionRevision.substring(1); if (versionRevision.indexOf("d") > 0) { versionRevision = versionRevision.substring(0, versionRevision.indexOf("d")); } } else if (versionRevision[0] == "b") { versionRevision = versionRevision.substring(1); } var flashVer = versionMajor + "." + versionMinor + "." + versionRevision; } } // MSN/WebTV 2.6 supports Flash 4 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; // WebTV 2.5 supports Flash 3 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; // older WebTV supports Flash 2 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; else if ( isIE && isWin && !isOpera ) { flashVer = ControlVersion(); } return flashVer; } // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) { versionStr = GetSwfVer(); if (versionStr == -1 ) { return false; } else if (versionStr != 0) { if(isIE && isWin && !isOpera) { // Given "WIN 2,0,0,11" tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"] tempString = tempArray[1]; // "2,0,0,11" versionArray = tempString.split(","); // ['2', '0', '0', '11'] } else { versionArray = versionStr.split("."); } var versionMajor = versionArray[0]; var versionMinor = versionArray[1]; var versionRevision = versionArray[2]; // is the major.revision >= requested major.revision AND the minor version >= requested minor if (versionMajor > parseFloat(reqMajorVer)) { return true; } else if (versionMajor == parseFloat(reqMajorVer)) { if (versionMinor > parseFloat(reqMinorVer)) return true; else if (versionMinor == parseFloat(reqMinorVer)) { if (versionRevision >= parseFloat(reqRevision)) return true; } } return false; } } function AC_AddExtension(src, ext) { var qIndex = src.indexOf('?'); if ( qIndex != -1) { // Add the extention (if needed) before the query params var path = src.substring(0, qIndex); if (path.length >= ext.length && path.lastIndexOf(ext) == (path.length - ext.length)) return src; else return src.replace(/\?/, ext+'?'); } else { // Add the extension (if needed) to the end of the URL if (src.length >= ext.length && src.lastIndexOf(ext) == (src.length - ext.length)) return src; // Already have extension else return src + ext; } } function AC_Generateobj(objAttrs, params, embedAttrs) { var str = ''; if (isIE && isWin && !isOpera) { str += '<object '; for (var i in objAttrs) str += i + '="' + objAttrs[i] + '" '; str += '>'; for (var i in params) str += '<param name="' + i + '" value="' + params[i] + '" /> '; str += '</object>'; } else { str += '<embed '; for (var i in embedAttrs) str += i + '="' + embedAttrs[i] + '" '; str += '> </embed>'; } document.write(str); } function AC_FL_RunContent(){ var ret = AC_GetArgs ( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" , "application/x-shockwave-flash" ); AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); } function AC_GetArgs(args, ext, srcParamName, classid, mimeType){ var ret = new Object(); ret.embedAttrs = new Object(); ret.params = new Object(); ret.objAttrs = new Object(); for (var i=0; i < args.length; i=i+2){ var currArg = args[i].toLowerCase(); switch (currArg){ case "classid": break; case "pluginspage": ret.embedAttrs[args[i]] = args[i+1]; break; case "src": case "movie": args[i+1] = AC_AddExtension(args[i+1], ext); ret.embedAttrs["src"] = args[i+1]; ret.params[srcParamName] = args[i+1]; break; case "onafterupdate": case "onbeforeupdate": case "onblur": case "oncellchange": case "onclick": case "ondblClick": case "ondrag": case "ondragend": case "ondragenter": case "ondragleave": case "ondragover": case "ondrop": case "onfinish": case "onfocus": case "onhelp": case "onmousedown": case "onmouseup": case "onmouseover": case "onmousemove": case "onmouseout": case "onkeypress": case "onkeydown": case "onkeyup": case "onload": case "onlosecapture": case "onpropertychange": case "onreadystatechange": case "onrowsdelete": case "onrowenter": case "onrowexit": case "onrowsinserted": case "onstart": case "onscroll": case "onbeforeeditfocus": case "onactivate": case "onbeforedeactivate": case "ondeactivate": case "type": case "codebase": ret.objAttrs[args[i]] = args[i+1]; break; case "id": case "width": case "height": case "align": case "vspace": case "hspace": case "class": case "title": case "accesskey": case "name": case "tabindex": ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1]; break; default: ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1]; } } ret.objAttrs["classid"] = classid; if (mimeType) ret.embedAttrs["type"] = mimeType; return ret; }
JavaScript
BrowserHistoryUtils = { addEvent: function(elm, evType, fn, useCapture) { useCapture = useCapture || false; if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r; } else { elm['on' + evType] = fn; } } } BrowserHistory = (function() { // type of browser var browser = { ie: false, firefox: false, safari: false, opera: false, version: -1 }; // if setDefaultURL has been called, our first clue // that the SWF is ready and listening //var swfReady = false; // the URL we'll send to the SWF once it is ready //var pendingURL = ''; // Default app state URL to use when no fragment ID present var defaultHash = ''; // Last-known app state URL var currentHref = document.location.href; // Initial URL (used only by IE) var initialHref = document.location.href; // Initial URL (used only by IE) var initialHash = document.location.hash; // History frame source URL prefix (used only by IE) var historyFrameSourcePrefix = 'history/historyFrame.html?'; // History maintenance (used only by Safari) var currentHistoryLength = -1; var historyHash = []; var initialState = createState(initialHref, initialHref + '#' + initialHash, initialHash); var backStack = []; var forwardStack = []; var currentObjectId = null; //UserAgent detection var useragent = navigator.userAgent.toLowerCase(); if (useragent.indexOf("opera") != -1) { browser.opera = true; } else if (useragent.indexOf("msie") != -1) { browser.ie = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('msie') + 4)); } else if (useragent.indexOf("safari") != -1) { browser.safari = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('safari') + 7)); } else if (useragent.indexOf("gecko") != -1) { browser.firefox = true; } if (browser.ie == true && browser.version == 7) { window["_ie_firstload"] = false; } // Accessor functions for obtaining specific elements of the page. function getHistoryFrame() { return document.getElementById('ie_historyFrame'); } function getAnchorElement() { return document.getElementById('firefox_anchorDiv'); } function getFormElement() { return document.getElementById('safari_formDiv'); } function getRememberElement() { return document.getElementById("safari_remember_field"); } // Get the Flash player object for performing ExternalInterface callbacks. // Updated for changes to SWFObject2. function getPlayer(id) { if (id && document.getElementById(id)) { var r = document.getElementById(id); if (typeof r.SetVariable != "undefined") { return r; } else { var o = r.getElementsByTagName("object"); var e = r.getElementsByTagName("embed"); if (o.length > 0 && typeof o[0].SetVariable != "undefined") { return o[0]; } else if (e.length > 0 && typeof e[0].SetVariable != "undefined") { return e[0]; } } } else { var o = document.getElementsByTagName("object"); var e = document.getElementsByTagName("embed"); if (e.length > 0 && typeof e[0].SetVariable != "undefined") { return e[0]; } else if (o.length > 0 && typeof o[0].SetVariable != "undefined") { return o[0]; } else if (o.length > 1 && typeof o[1].SetVariable != "undefined") { return o[1]; } } return undefined; } function getPlayers() { var players = []; if (players.length == 0) { var tmp = document.getElementsByTagName('object'); players = tmp; } if (players.length == 0 || players[0].object == null) { var tmp = document.getElementsByTagName('embed'); players = tmp; } return players; } function getIframeHash() { var doc = getHistoryFrame().contentWindow.document; var hash = String(doc.location.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } return hash; } /* Get the current location hash excluding the '#' symbol. */ function getHash() { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. var idx = document.location.href.indexOf('#'); return (idx >= 0) ? document.location.href.substr(idx+1) : ''; } /* Get the current location hash excluding the '#' symbol. */ function setHash(hash) { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. if (hash == '') hash = '#' document.location.hash = hash; } function createState(baseUrl, newUrl, flexAppUrl) { return { 'baseUrl': baseUrl, 'newUrl': newUrl, 'flexAppUrl': flexAppUrl, 'title': null }; } /* Add a history entry to the browser. * baseUrl: the portion of the location prior to the '#' * newUrl: the entire new URL, including '#' and following fragment * flexAppUrl: the portion of the location following the '#' only */ function addHistoryEntry(baseUrl, newUrl, flexAppUrl) { //delete all the history entries forwardStack = []; if (browser.ie) { //Check to see if we are being asked to do a navigate for the first //history entry, and if so ignore, because it's coming from the creation //of the history iframe if (flexAppUrl == defaultHash && document.location.href == initialHref && window['_ie_firstload']) { currentHref = initialHref; return; } if ((!flexAppUrl || flexAppUrl == defaultHash) && window['_ie_firstload']) { newUrl = baseUrl + '#' + defaultHash; flexAppUrl = defaultHash; } else { // for IE, tell the history frame to go somewhere without a '#' // in order to get this entry into the browser history. getHistoryFrame().src = historyFrameSourcePrefix + flexAppUrl; } setHash(flexAppUrl); } else { //ADR if (backStack.length == 0 && initialState.flexAppUrl == flexAppUrl) { initialState = createState(baseUrl, newUrl, flexAppUrl); } else if(backStack.length > 0 && backStack[backStack.length - 1].flexAppUrl == flexAppUrl) { backStack[backStack.length - 1] = createState(baseUrl, newUrl, flexAppUrl); } if (browser.safari) { // for Safari, submit a form whose action points to the desired URL if (browser.version <= 419.3) { var file = window.location.pathname.toString(); file = file.substring(file.lastIndexOf("/")+1); getFormElement().innerHTML = '<form name="historyForm" action="'+file+'#' + flexAppUrl + '" method="GET"></form>'; //get the current elements and add them to the form var qs = window.location.search.substring(1); var qs_arr = qs.split("&"); for (var i = 0; i < qs_arr.length; i++) { var tmp = qs_arr[i].split("="); var elem = document.createElement("input"); elem.type = "hidden"; elem.name = tmp[0]; elem.value = tmp[1]; document.forms.historyForm.appendChild(elem); } document.forms.historyForm.submit(); } else { top.location.hash = flexAppUrl; } // We also have to maintain the history by hand for Safari historyHash[history.length] = flexAppUrl; _storeStates(); } else { // Otherwise, write an anchor into the page and tell the browser to go there addAnchor(flexAppUrl); setHash(flexAppUrl); } } backStack.push(createState(baseUrl, newUrl, flexAppUrl)); } function _storeStates() { if (browser.safari) { getRememberElement().value = historyHash.join(","); } } function handleBackButton() { //The "current" page is always at the top of the history stack. var current = backStack.pop(); if (!current) { return; } var last = backStack[backStack.length - 1]; if (!last && backStack.length == 0){ last = initialState; } forwardStack.push(current); } function handleForwardButton() { //summary: private method. Do not call this directly. var last = forwardStack.pop(); if (!last) { return; } backStack.push(last); } function handleArbitraryUrl() { //delete all the history entries forwardStack = []; } /* Called periodically to poll to see if we need to detect navigation that has occurred */ function checkForUrlChange() { if (browser.ie) { if (currentHref != document.location.href && currentHref + '#' != document.location.href) { //This occurs when the user has navigated to a specific URL //within the app, and didn't use browser back/forward //IE seems to have a bug where it stops updating the URL it //shows the end-user at this point, but programatically it //appears to be correct. Do a full app reload to get around //this issue. if (browser.version < 7) { currentHref = document.location.href; document.location.reload(); } else { if (getHash() != getIframeHash()) { // this.iframe.src = this.blankURL + hash; var sourceToSet = historyFrameSourcePrefix + getHash(); getHistoryFrame().src = sourceToSet; } } } } if (browser.safari) { // For Safari, we have to check to see if history.length changed. if (currentHistoryLength >= 0 && history.length != currentHistoryLength) { //alert("did change: " + history.length + ", " + historyHash.length + "|" + historyHash[history.length] + "|>" + historyHash.join("|")); var flexAppUrl = getHash(); if (browser.version < 528.16 /* Anything earlier than Safari 4.0 */) { // If it did change and we're running Safari 3.x or earlier, // then we have to look the old state up in our hand-maintained // array since document.location.hash won't have changed, // then call back into BrowserManager. currentHistoryLength = history.length; flexAppUrl = historyHash[currentHistoryLength]; } //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } _storeStates(); } } if (browser.firefox) { if (currentHref != document.location.href) { var bsl = backStack.length; var urlActions = { back: false, forward: false, set: false } if ((window.location.hash == initialHash || window.location.href == initialHref) && (bsl == 1)) { urlActions.back = true; // FIXME: could this ever be a forward button? // we can't clear it because we still need to check for forwards. Ugg. // clearInterval(this.locationTimer); handleBackButton(); } // first check to see if we could have gone forward. We always halt on // a no-hash item. if (forwardStack.length > 0) { if (forwardStack[forwardStack.length-1].flexAppUrl == getHash()) { urlActions.forward = true; handleForwardButton(); } } // ok, that didn't work, try someplace back in the history stack if ((bsl >= 2) && (backStack[bsl - 2])) { if (backStack[bsl - 2].flexAppUrl == getHash()) { urlActions.back = true; handleBackButton(); } } if (!urlActions.back && !urlActions.forward) { var foundInStacks = { back: -1, forward: -1 } for (var i = 0; i < backStack.length; i++) { if (backStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.back = i; } } for (var i = 0; i < forwardStack.length; i++) { if (forwardStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.forward = i; } } handleArbitraryUrl(); } // Firefox changed; do a callback into BrowserManager to tell it. currentHref = document.location.href; var flexAppUrl = getHash(); if (flexAppUrl == '') { //flexAppUrl = defaultHash; } //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } } } //setTimeout(checkForUrlChange, 50); } /* Write an anchor into the page to legitimize it as a URL for Firefox et al. */ function addAnchor(flexAppUrl) { if (document.getElementsByName(flexAppUrl).length == 0) { getAnchorElement().innerHTML += "<a name='" + flexAppUrl + "'>" + flexAppUrl + "</a>"; } } var _initialize = function () { if (browser.ie) { var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { var iframe_location = (new String(s.src)).replace("history.js", "historyFrame.html"); } } historyFrameSourcePrefix = iframe_location + "?"; var src = historyFrameSourcePrefix; var iframe = document.createElement("iframe"); iframe.id = 'ie_historyFrame'; iframe.name = 'ie_historyFrame'; //iframe.src = historyFrameSourcePrefix; try { document.body.appendChild(iframe); } catch(e) { setTimeout(function() { document.body.appendChild(iframe); }, 0); } } if (browser.safari) { var rememberDiv = document.createElement("div"); rememberDiv.id = 'safari_rememberDiv'; document.body.appendChild(rememberDiv); rememberDiv.innerHTML = '<input type="text" id="safari_remember_field" style="width: 500px;">'; var formDiv = document.createElement("div"); formDiv.id = 'safari_formDiv'; document.body.appendChild(formDiv); var reloader_content = document.createElement('div'); reloader_content.id = 'safarireloader'; var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { html = (new String(s.src)).replace(".js", ".html"); } } reloader_content.innerHTML = '<iframe id="safarireloader-iframe" src="about:blank" frameborder="no" scrolling="no"></iframe>'; document.body.appendChild(reloader_content); reloader_content.style.position = 'absolute'; reloader_content.style.left = reloader_content.style.top = '-9999px'; iframe = reloader_content.getElementsByTagName('iframe')[0]; if (document.getElementById("safari_remember_field").value != "" ) { historyHash = document.getElementById("safari_remember_field").value.split(","); } } if (browser.firefox) { var anchorDiv = document.createElement("div"); anchorDiv.id = 'firefox_anchorDiv'; document.body.appendChild(anchorDiv); } //setTimeout(checkForUrlChange, 50); } return { historyHash: historyHash, backStack: function() { return backStack; }, forwardStack: function() { return forwardStack }, getPlayer: getPlayer, initialize: function(src) { _initialize(src); }, setURL: function(url) { document.location.href = url; }, getURL: function() { return document.location.href; }, getTitle: function() { return document.title; }, setTitle: function(title) { try { backStack[backStack.length - 1].title = title; } catch(e) { } //if on safari, set the title to be the empty string. if (browser.safari) { if (title == "") { try { var tmp = window.location.href.toString(); title = tmp.substring((tmp.lastIndexOf("/")+1), tmp.lastIndexOf("#")); } catch(e) { title = ""; } } } document.title = title; }, setDefaultURL: function(def) { defaultHash = def; def = getHash(); //trailing ? is important else an extra frame gets added to the history //when navigating back to the first page. Alternatively could check //in history frame navigation to compare # and ?. if (browser.ie) { window['_ie_firstload'] = true; var sourceToSet = historyFrameSourcePrefix + def; var func = function() { getHistoryFrame().src = sourceToSet; window.location.replace("#" + def); setInterval(checkForUrlChange, 50); } try { func(); } catch(e) { window.setTimeout(function() { func(); }, 0); } } if (browser.safari) { currentHistoryLength = history.length; if (historyHash.length == 0) { historyHash[currentHistoryLength] = def; var newloc = "#" + def; window.location.replace(newloc); } else { //alert(historyHash[historyHash.length-1]); } //setHash(def); setInterval(checkForUrlChange, 50); } if (browser.firefox || browser.opera) { var reg = new RegExp("#" + def + "$"); if (window.location.toString().match(reg)) { } else { var newloc ="#" + def; window.location.replace(newloc); } setInterval(checkForUrlChange, 50); //setHash(def); } }, /* Set the current browser URL; called from inside BrowserManager to propagate * the application state out to the container. */ setBrowserURL: function(flexAppUrl, objectId) { if (browser.ie && typeof objectId != "undefined") { currentObjectId = objectId; } //fromIframe = fromIframe || false; //fromFlex = fromFlex || false; //alert("setBrowserURL: " + flexAppUrl); //flexAppUrl = (flexAppUrl == "") ? defaultHash : flexAppUrl ; var pos = document.location.href.indexOf('#'); var baseUrl = pos != -1 ? document.location.href.substr(0, pos) : document.location.href; var newUrl = baseUrl + '#' + flexAppUrl; if (document.location.href != newUrl && document.location.href + '#' != newUrl) { currentHref = newUrl; addHistoryEntry(baseUrl, newUrl, flexAppUrl); currentHistoryLength = history.length; } }, browserURLChange: function(flexAppUrl) { var objectId = null; if (browser.ie && currentObjectId != null) { objectId = currentObjectId; } pendingURL = ''; if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { try { pl[i].browserURLChange(flexAppUrl); } catch(e) { } } } else { try { getPlayer(objectId).browserURLChange(flexAppUrl); } catch(e) { } } currentObjectId = null; }, getUserAgent: function() { return navigator.userAgent; }, getPlatform: function() { return navigator.platform; } } })(); // Initialization // Automated unit testing and other diagnostics function setURL(url) { document.location.href = url; } function backButton() { history.back(); } function forwardButton() { history.forward(); } function goForwardOrBackInHistory(step) { history.go(step); } //BrowserHistoryUtils.addEvent(window, "load", function() { BrowserHistory.initialize(); }); (function(i) { var u =navigator.userAgent;var e=/*@cc_on!@*/false; var st = setTimeout; if(/webkit/i.test(u)){ st(function(){ var dr=document.readyState; if(dr=="loaded"||dr=="complete"){i()} else{st(arguments.callee,10);}},10); } else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){ document.addEventListener("DOMContentLoaded",i,false); } else if(e){ (function(){ var t=document.createElement('doc:rdy'); try{t.doScroll('left'); i();t=null; }catch(e){st(arguments.callee,0);}})(); } else{ window.onload=i; } })( function() {BrowserHistory.initialize();} );
JavaScript
(function(exports){ crossfilter.version = "1.2.0"; function crossfilter_identity(d) { return d; } crossfilter.permute = permute; function permute(array, index) { for (var i = 0, n = index.length, copy = new Array(n); i < n; ++i) { copy[i] = array[index[i]]; } return copy; } var bisect = crossfilter.bisect = bisect_by(crossfilter_identity); bisect.by = bisect_by; function bisect_by(f) { // Locate the insertion point for x in a to maintain sorted order. The // arguments lo and hi may be used to specify a subset of the array which // should be considered; by default the entire array is used. If x is already // present in a, the insertion point will be before (to the left of) any // existing entries. The return value is suitable for use as the first // argument to `array.splice` assuming that a is already sorted. // // The returned insertion point i partitions the array a into two halves so // that all v < x for v in a[lo:i] for the left side and all v >= x for v in // a[i:hi] for the right side. function bisectLeft(a, x, lo, hi) { while (lo < hi) { var mid = lo + hi >>> 1; if (f(a[mid]) < x) lo = mid + 1; else hi = mid; } return lo; } // Similar to bisectLeft, but returns an insertion point which comes after (to // the right of) any existing entries of x in a. // // The returned insertion point i partitions the array into two halves so that // all v <= x for v in a[lo:i] for the left side and all v > x for v in // a[i:hi] for the right side. function bisectRight(a, x, lo, hi) { while (lo < hi) { var mid = lo + hi >>> 1; if (x < f(a[mid])) hi = mid; else lo = mid + 1; } return lo; } bisectRight.right = bisectRight; bisectRight.left = bisectLeft; return bisectRight; } var heap = crossfilter.heap = heap_by(crossfilter_identity); heap.by = heap_by; function heap_by(f) { // Builds a binary heap within the specified array a[lo:hi]. The heap has the // property such that the parent a[lo+i] is always less than or equal to its // two children: a[lo+2*i+1] and a[lo+2*i+2]. function heap(a, lo, hi) { var n = hi - lo, i = (n >>> 1) + 1; while (--i > 0) sift(a, i, n, lo); return a; } // Sorts the specified array a[lo:hi] in descending order, assuming it is // already a heap. function sort(a, lo, hi) { var n = hi - lo, t; while (--n > 0) t = a[lo], a[lo] = a[lo + n], a[lo + n] = t, sift(a, 1, n, lo); return a; } // Sifts the element a[lo+i-1] down the heap, where the heap is the contiguous // slice of array a[lo:lo+n]. This method can also be used to update the heap // incrementally, without incurring the full cost of reconstructing the heap. function sift(a, i, n, lo) { var d = a[--lo + i], x = f(d), child; while ((child = i << 1) <= n) { if (child < n && f(a[lo + child]) > f(a[lo + child + 1])) child++; if (x <= f(a[lo + child])) break; a[lo + i] = a[lo + child]; i = child; } a[lo + i] = d; } heap.sort = sort; return heap; } var heapselect = crossfilter.heapselect = heapselect_by(crossfilter_identity); heapselect.by = heapselect_by; function heapselect_by(f) { var heap = heap_by(f); // Returns a new array containing the top k elements in the array a[lo:hi]. // The returned array is not sorted, but maintains the heap property. If k is // greater than hi - lo, then fewer than k elements will be returned. The // order of elements in a is unchanged by this operation. function heapselect(a, lo, hi, k) { var queue = new Array(k = Math.min(hi - lo, k)), min, i, x, d; for (i = 0; i < k; ++i) queue[i] = a[lo++]; heap(queue, 0, k); if (lo < hi) { min = f(queue[0]); do { if (x = f(d = a[lo]) > min) { queue[0] = d; min = f(heap(queue, 0, k)[0]); } } while (++lo < hi); } return queue; } return heapselect; } var insertionsort = crossfilter.insertionsort = insertionsort_by(crossfilter_identity); insertionsort.by = insertionsort_by; function insertionsort_by(f) { function insertionsort(a, lo, hi) { for (var i = lo + 1; i < hi; ++i) { for (var j = i, t = a[i], x = f(t); j > lo && f(a[j - 1]) > x; --j) { a[j] = a[j - 1]; } a[j] = t; } return a; } return insertionsort; } // Algorithm designed by Vladimir Yaroslavskiy. // Implementation based on the Dart project; see lib/dart/LICENSE for details. var quicksort = crossfilter.quicksort = quicksort_by(crossfilter_identity); quicksort.by = quicksort_by; function quicksort_by(f) { var insertionsort = insertionsort_by(f); function sort(a, lo, hi) { return (hi - lo < quicksort_sizeThreshold ? insertionsort : quicksort)(a, lo, hi); } function quicksort(a, lo, hi) { // Compute the two pivots by looking at 5 elements. var sixth = (hi - lo) / 6 | 0, i1 = lo + sixth, i5 = hi - 1 - sixth, i3 = lo + hi - 1 >> 1, // The midpoint. i2 = i3 - sixth, i4 = i3 + sixth; var e1 = a[i1], x1 = f(e1), e2 = a[i2], x2 = f(e2), e3 = a[i3], x3 = f(e3), e4 = a[i4], x4 = f(e4), e5 = a[i5], x5 = f(e5); var t; // Sort the selected 5 elements using a sorting network. if (x1 > x2) t = e1, e1 = e2, e2 = t, t = x1, x1 = x2, x2 = t; if (x4 > x5) t = e4, e4 = e5, e5 = t, t = x4, x4 = x5, x5 = t; if (x1 > x3) t = e1, e1 = e3, e3 = t, t = x1, x1 = x3, x3 = t; if (x2 > x3) t = e2, e2 = e3, e3 = t, t = x2, x2 = x3, x3 = t; if (x1 > x4) t = e1, e1 = e4, e4 = t, t = x1, x1 = x4, x4 = t; if (x3 > x4) t = e3, e3 = e4, e4 = t, t = x3, x3 = x4, x4 = t; if (x2 > x5) t = e2, e2 = e5, e5 = t, t = x2, x2 = x5, x5 = t; if (x2 > x3) t = e2, e2 = e3, e3 = t, t = x2, x2 = x3, x3 = t; if (x4 > x5) t = e4, e4 = e5, e5 = t, t = x4, x4 = x5, x5 = t; var pivot1 = e2, pivotValue1 = x2, pivot2 = e4, pivotValue2 = x4; // e2 and e4 have been saved in the pivot variables. They will be written // back, once the partitioning is finished. a[i1] = e1; a[i2] = a[lo]; a[i3] = e3; a[i4] = a[hi - 1]; a[i5] = e5; var less = lo + 1, // First element in the middle partition. great = hi - 2; // Last element in the middle partition. // Note that for value comparison, <, <=, >= and > coerce to a primitive via // Object.prototype.valueOf; == and === do not, so in order to be consistent // with natural order (such as for Date objects), we must do two compares. var pivotsEqual = pivotValue1 <= pivotValue2 && pivotValue1 >= pivotValue2; if (pivotsEqual) { // Degenerated case where the partitioning becomes a dutch national flag // problem. // // [ | < pivot | == pivot | unpartitioned | > pivot | ] // ^ ^ ^ ^ ^ // left less k great right // // a[left] and a[right] are undefined and are filled after the // partitioning. // // Invariants: // 1) for x in ]left, less[ : x < pivot. // 2) for x in [less, k[ : x == pivot. // 3) for x in ]great, right[ : x > pivot. for (var k = less; k <= great; ++k) { var ek = a[k], xk = f(ek); if (xk < pivotValue1) { if (k !== less) { a[k] = a[less]; a[less] = ek; } ++less; } else if (xk > pivotValue1) { // Find the first element <= pivot in the range [k - 1, great] and // put [:ek:] there. We know that such an element must exist: // When k == less, then el3 (which is equal to pivot) lies in the // interval. Otherwise a[k - 1] == pivot and the search stops at k-1. // Note that in the latter case invariant 2 will be violated for a // short amount of time. The invariant will be restored when the // pivots are put into their final positions. while (true) { var greatValue = f(a[great]); if (greatValue > pivotValue1) { great--; // This is the only location in the while-loop where a new // iteration is started. continue; } else if (greatValue < pivotValue1) { // Triple exchange. a[k] = a[less]; a[less++] = a[great]; a[great--] = ek; break; } else { a[k] = a[great]; a[great--] = ek; // Note: if great < k then we will exit the outer loop and fix // invariant 2 (which we just violated). break; } } } } } else { // We partition the list into three parts: // 1. < pivot1 // 2. >= pivot1 && <= pivot2 // 3. > pivot2 // // During the loop we have: // [ | < pivot1 | >= pivot1 && <= pivot2 | unpartitioned | > pivot2 | ] // ^ ^ ^ ^ ^ // left less k great right // // a[left] and a[right] are undefined and are filled after the // partitioning. // // Invariants: // 1. for x in ]left, less[ : x < pivot1 // 2. for x in [less, k[ : pivot1 <= x && x <= pivot2 // 3. for x in ]great, right[ : x > pivot2 for (var k = less; k <= great; k++) { var ek = a[k], xk = f(ek); if (xk < pivotValue1) { if (k !== less) { a[k] = a[less]; a[less] = ek; } ++less; } else { if (xk > pivotValue2) { while (true) { var greatValue = f(a[great]); if (greatValue > pivotValue2) { great--; if (great < k) break; // This is the only location inside the loop where a new // iteration is started. continue; } else { // a[great] <= pivot2. if (greatValue < pivotValue1) { // Triple exchange. a[k] = a[less]; a[less++] = a[great]; a[great--] = ek; } else { // a[great] >= pivot1. a[k] = a[great]; a[great--] = ek; } break; } } } } } } // Move pivots into their final positions. // We shrunk the list from both sides (a[left] and a[right] have // meaningless values in them) and now we move elements from the first // and third partition into these locations so that we can store the // pivots. a[lo] = a[less - 1]; a[less - 1] = pivot1; a[hi - 1] = a[great + 1]; a[great + 1] = pivot2; // The list is now partitioned into three partitions: // [ < pivot1 | >= pivot1 && <= pivot2 | > pivot2 ] // ^ ^ ^ ^ // left less great right // Recursive descent. (Don't include the pivot values.) sort(a, lo, less - 1); sort(a, great + 2, hi); if (pivotsEqual) { // All elements in the second partition are equal to the pivot. No // need to sort them. return a; } // In theory it should be enough to call _doSort recursively on the second // partition. // The Android source however removes the pivot elements from the recursive // call if the second partition is too large (more than 2/3 of the list). if (less < i1 && great > i5) { var lessValue, greatValue; while ((lessValue = f(a[less])) <= pivotValue1 && lessValue >= pivotValue1) ++less; while ((greatValue = f(a[great])) <= pivotValue2 && greatValue >= pivotValue2) --great; // Copy paste of the previous 3-way partitioning with adaptions. // // We partition the list into three parts: // 1. == pivot1 // 2. > pivot1 && < pivot2 // 3. == pivot2 // // During the loop we have: // [ == pivot1 | > pivot1 && < pivot2 | unpartitioned | == pivot2 ] // ^ ^ ^ // less k great // // Invariants: // 1. for x in [ *, less[ : x == pivot1 // 2. for x in [less, k[ : pivot1 < x && x < pivot2 // 3. for x in ]great, * ] : x == pivot2 for (var k = less; k <= great; k++) { var ek = a[k], xk = f(ek); if (xk <= pivotValue1 && xk >= pivotValue1) { if (k !== less) { a[k] = a[less]; a[less] = ek; } less++; } else { if (xk <= pivotValue2 && xk >= pivotValue2) { while (true) { var greatValue = f(a[great]); if (greatValue <= pivotValue2 && greatValue >= pivotValue2) { great--; if (great < k) break; // This is the only location inside the loop where a new // iteration is started. continue; } else { // a[great] < pivot2. if (greatValue < pivotValue1) { // Triple exchange. a[k] = a[less]; a[less++] = a[great]; a[great--] = ek; } else { // a[great] == pivot1. a[k] = a[great]; a[great--] = ek; } break; } } } } } } // The second partition has now been cleared of pivot elements and looks // as follows: // [ * | > pivot1 && < pivot2 | * ] // ^ ^ // less great // Sort the second partition using recursive descent. // The second partition looks as follows: // [ * | >= pivot1 && <= pivot2 | * ] // ^ ^ // less great // Simply sort it by recursive descent. return sort(a, less, great + 1); } return sort; } var quicksort_sizeThreshold = 32; var crossfilter_array8 = crossfilter_arrayUntyped, crossfilter_array16 = crossfilter_arrayUntyped, crossfilter_array32 = crossfilter_arrayUntyped, crossfilter_arrayLengthen = crossfilter_identity, crossfilter_arrayWiden = crossfilter_identity; if (typeof Uint8Array !== "undefined") { crossfilter_array8 = function(n) { return new Uint8Array(n); }; crossfilter_array16 = function(n) { return new Uint16Array(n); }; crossfilter_array32 = function(n) { return new Uint32Array(n); }; crossfilter_arrayLengthen = function(array, length) { var copy = new array.constructor(length); copy.set(array); return copy; }; crossfilter_arrayWiden = function(array, width) { var copy; switch (width) { case 16: copy = crossfilter_array16(array.length); break; case 32: copy = crossfilter_array32(array.length); break; default: throw new Error("invalid array width!"); } copy.set(array); return copy; }; } function crossfilter_arrayUntyped(n) { return new Array(n); } function crossfilter_filterExact(bisect, value) { return function(values) { var n = values.length; return [bisect.left(values, value, 0, n), bisect.right(values, value, 0, n)]; }; } function crossfilter_filterRange(bisect, range) { var min = range[0], max = range[1]; return function(values) { var n = values.length; return [bisect.left(values, min, 0, n), bisect.left(values, max, 0, n)]; }; } function crossfilter_filterAll(values) { return [0, values.length]; } function crossfilter_null() { return null; } function crossfilter_zero() { return 0; } function crossfilter_reduceIncrement(p) { return p + 1; } function crossfilter_reduceDecrement(p) { return p - 1; } function crossfilter_reduceAdd(f) { return function(p, v) { return p + +f(v); }; } function crossfilter_reduceSubtract(f) { return function(p, v) { return p - f(v); }; } exports.crossfilter = crossfilter; function crossfilter() { var crossfilter = { add: add, dimension: dimension, groupAll: groupAll, size: size }; var data = [], // the records n = 0, // the number of records; data.length m = 0, // a bit mask representing which dimensions are in use M = 8, // number of dimensions that can fit in `filters` filters = crossfilter_array8(0), // M bits per record; 1 is filtered out filterListeners = [], // when the filters change dataListeners = []; // when data is added // Adds the specified new records to this crossfilter. function add(newData) { var n0 = n, n1 = newData.length; // If there's actually new data to add… // Merge the new data into the existing data. // Lengthen the filter bitset to handle the new records. // Notify listeners (dimensions and groups) that new data is available. if (n1) { data = data.concat(newData); filters = crossfilter_arrayLengthen(filters, n += n1); dataListeners.forEach(function(l) { l(newData, n0, n1); }); } return crossfilter; } // Adds a new dimension with the specified value accessor function. function dimension(value) { var dimension = { filter: filter, filterExact: filterExact, filterRange: filterRange, filterFunction: filterFunction, filterAll: filterAll, top: top, bottom: bottom, group: group, groupAll: groupAll, remove: remove }; var one = ~m & -~m, // lowest unset bit as mask, e.g., 00001000 zero = ~one, // inverted one, e.g., 11110111 values, // sorted, cached array index, // value rank ↦ object id newValues, // temporary array storing newly-added values newIndex, // temporary array storing newly-added index sort = quicksort_by(function(i) { return newValues[i]; }), refilter = crossfilter_filterAll, // for recomputing filter refilterFunction, // the custom filter function in use indexListeners = [], // when data is added dimensionGroups = [], lo0 = 0, hi0 = 0; // Updating a dimension is a two-stage process. First, we must update the // associated filters for the newly-added records. Once all dimensions have // updated their filters, the groups are notified to update. dataListeners.unshift(preAdd); dataListeners.push(postAdd); // Incorporate any existing data into this dimension, and make sure that the // filter bitset is wide enough to handle the new dimension. m |= one; if (M >= 32 ? !one : m & (1 << M) - 1) { filters = crossfilter_arrayWiden(filters, M <<= 1); } preAdd(data, 0, n); postAdd(data, 0, n); // Incorporates the specified new records into this dimension. // This function is responsible for updating filters, values, and index. function preAdd(newData, n0, n1) { // Permute new values into natural order using a sorted index. newValues = newData.map(value); newIndex = sort(crossfilter_range(n1), 0, n1); newValues = permute(newValues, newIndex); // Bisect newValues to determine which new records are selected. var bounds = refilter(newValues), lo1 = bounds[0], hi1 = bounds[1], i, k; if (refilterFunction) { for (i = 0; i < n1; ++i) { if (!refilterFunction(newValues[i], k = newIndex[i] + n0)) filters[k] |= one; } } else { for (i = 0; i < lo1; ++i) filters[newIndex[i] + n0] |= one; for (i = hi1; i < n1; ++i) filters[newIndex[i] + n0] |= one; } // If this dimension previously had no data, then we don't need to do the // more expensive merge operation; use the new values and index as-is. if (!n0) { values = newValues; index = newIndex; lo0 = lo1; hi0 = hi1; return; } var oldValues = values, oldIndex = index, i0 = 0, i1 = 0; // Otherwise, create new arrays into which to merge new and old. values = new Array(n); index = crossfilter_index(n, n); // Merge the old and new sorted values, and old and new index. for (i = 0; i0 < n0 && i1 < n1; ++i) { if (oldValues[i0] < newValues[i1]) { values[i] = oldValues[i0]; index[i] = oldIndex[i0++]; } else { values[i] = newValues[i1]; index[i] = newIndex[i1++] + n0; } } // Add any remaining old values. for (; i0 < n0; ++i0, ++i) { values[i] = oldValues[i0]; index[i] = oldIndex[i0]; } // Add any remaining new values. for (; i1 < n1; ++i1, ++i) { values[i] = newValues[i1]; index[i] = newIndex[i1] + n0; } // Bisect again to recompute lo0 and hi0. bounds = refilter(values), lo0 = bounds[0], hi0 = bounds[1]; } // When all filters have updated, notify index listeners of the new values. function postAdd(newData, n0, n1) { indexListeners.forEach(function(l) { l(newValues, newIndex, n0, n1); }); newValues = newIndex = null; } // Updates the selected values based on the specified bounds [lo, hi]. // This implementation is used by all the public filter methods. function filterIndexBounds(bounds) { var lo1 = bounds[0], hi1 = bounds[1]; if (refilterFunction) { refilterFunction = null; filterIndexFunction(function(d, i) { return lo1 <= i && i < hi1; }); lo0 = lo1; hi0 = hi1; return dimension; } var i, j, k, added = [], removed = []; // Fast incremental update based on previous lo index. if (lo1 < lo0) { for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) { filters[k = index[i]] ^= one; added.push(k); } } else if (lo1 > lo0) { for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) { filters[k = index[i]] ^= one; removed.push(k); } } // Fast incremental update based on previous hi index. if (hi1 > hi0) { for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) { filters[k = index[i]] ^= one; added.push(k); } } else if (hi1 < hi0) { for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) { filters[k = index[i]] ^= one; removed.push(k); } } lo0 = lo1; hi0 = hi1; filterListeners.forEach(function(l) { l(one, added, removed); }); return dimension; } // Filters this dimension using the specified range, value, or null. // If the range is null, this is equivalent to filterAll. // If the range is an array, this is equivalent to filterRange. // Otherwise, this is equivalent to filterExact. function filter(range) { return range == null ? filterAll() : Array.isArray(range) ? filterRange(range) : typeof range === "function" ? filterFunction(range) : filterExact(range); } // Filters this dimension to select the exact value. function filterExact(value) { return filterIndexBounds((refilter = crossfilter_filterExact(bisect, value))(values)); } // Filters this dimension to select the specified range [lo, hi]. // The lower bound is inclusive, and the upper bound is exclusive. function filterRange(range) { return filterIndexBounds((refilter = crossfilter_filterRange(bisect, range))(values)); } // Clears any filters on this dimension. function filterAll() { return filterIndexBounds((refilter = crossfilter_filterAll)(values)); } // Filters this dimension using an arbitrary function. function filterFunction(f) { refilter = crossfilter_filterAll; filterIndexFunction(refilterFunction = f); lo0 = 0; hi0 = n; return dimension; } function filterIndexFunction(f) { var i, k, x, added = [], removed = []; for (i = 0; i < n; ++i) { if (!(filters[k = index[i]] & one) ^ (x = f(values[i], k))) { if (x) filters[k] &= zero, added.push(k); else filters[k] |= one, removed.push(k); } } filterListeners.forEach(function(l) { l(one, added, removed); }); } // Returns the top K selected records based on this dimension's order. // Note: observes this dimension's filter, unlike group and groupAll. function top(k) { var array = [], i = hi0, j; while (--i >= lo0 && k > 0) { if (!filters[j = index[i]]) { array.push(data[j]); --k; } } return array; } // Returns the bottom K selected records based on this dimension's order. // Note: observes this dimension's filter, unlike group and groupAll. function bottom(k) { var array = [], i = lo0, j; while (i < hi0 && k > 0) { if (!filters[j = index[i]]) { array.push(data[j]); --k; } i++; } return array; } // Adds a new group to this dimension, using the specified key function. function group(key) { var group = { top: top, all: all, reduce: reduce, reduceCount: reduceCount, reduceSum: reduceSum, order: order, orderNatural: orderNatural, size: size, remove: remove }; // Ensure that this group will be removed when the dimension is removed. dimensionGroups.push(group); var groups, // array of {key, value} groupIndex, // object id ↦ group id groupWidth = 8, groupCapacity = crossfilter_capacity(groupWidth), k = 0, // cardinality select, heap, reduceAdd, reduceRemove, reduceInitial, update = crossfilter_null, reset = crossfilter_null, resetNeeded = true; if (arguments.length < 1) key = crossfilter_identity; // The group listens to the crossfilter for when any dimension changes, so // that it can update the associated reduce values. It must also listen to // the parent dimension for when data is added, and compute new keys. filterListeners.push(update); indexListeners.push(add); // Incorporate any existing data into the grouping. add(values, index, 0, n); // Incorporates the specified new values into this group. // This function is responsible for updating groups and groupIndex. function add(newValues, newIndex, n0, n1) { var oldGroups = groups, reIndex = crossfilter_index(k, groupCapacity), add = reduceAdd, initial = reduceInitial, k0 = k, // old cardinality i0 = 0, // index of old group i1 = 0, // index of new record j, // object id g0, // old group x0, // old key x1, // new key g, // group to add x; // key of group to add // If a reset is needed, we don't need to update the reduce values. if (resetNeeded) add = initial = crossfilter_null; // Reset the new groups (k is a lower bound). // Also, make sure that groupIndex exists and is long enough. groups = new Array(k), k = 0; groupIndex = k0 > 1 ? crossfilter_arrayLengthen(groupIndex, n) : crossfilter_index(n, groupCapacity); // Get the first old key (x0 of g0), if it exists. if (k0) x0 = (g0 = oldGroups[0]).key; // Find the first new key (x1), skipping NaN keys. while (i1 < n1 && !((x1 = key(newValues[i1])) >= x1)) ++i1; // While new keys remain… while (i1 < n1) { // Determine the lesser of the two current keys; new and old. // If there are no old keys remaining, then always add the new key. if (g0 && x0 <= x1) { g = g0, x = x0; // Record the new index of the old group. reIndex[i0] = k; // Retrieve the next old key. if (g0 = oldGroups[++i0]) x0 = g0.key; } else { g = {key: x1, value: initial()}, x = x1; } // Add the lesser group. groups[k] = g; // Add any selected records belonging to the added group, while // advancing the new key and populating the associated group index. while (!(x1 > x)) { groupIndex[j = newIndex[i1] + n0] = k; if (!(filters[j] & zero)) g.value = add(g.value, data[j]); if (++i1 >= n1) break; x1 = key(newValues[i1]); } groupIncrement(); } // Add any remaining old groups that were greater than all new keys. // No incremental reduce is needed; these groups have no new records. // Also record the new index of the old group. while (i0 < k0) { groups[reIndex[i0] = k] = oldGroups[i0++]; groupIncrement(); } // If we added any new groups before any old groups, // update the group index of all the old records. if (k > i0) for (i0 = 0; i0 < n0; ++i0) { groupIndex[i0] = reIndex[groupIndex[i0]]; } // Modify the update and reset behavior based on the cardinality. // If the cardinality is less than or equal to one, then the groupIndex // is not needed. If the cardinality is zero, then there are no records // and therefore no groups to update or reset. Note that we also must // change the registered listener to point to the new method. j = filterListeners.indexOf(update); if (k > 1) { update = updateMany; reset = resetMany; } else { if (k === 1) { update = updateOne; reset = resetOne; } else { update = crossfilter_null; reset = crossfilter_null; } groupIndex = null; } filterListeners[j] = update; // Count the number of added groups, // and widen the group index as needed. function groupIncrement() { if (++k === groupCapacity) { reIndex = crossfilter_arrayWiden(reIndex, groupWidth <<= 1); groupIndex = crossfilter_arrayWiden(groupIndex, groupWidth); groupCapacity = crossfilter_capacity(groupWidth); } } } // Reduces the specified selected or deselected records. // This function is only used when the cardinality is greater than 1. function updateMany(filterOne, added, removed) { if (filterOne === one || resetNeeded) return; var i, k, n, g; // Add the added values. for (i = 0, n = added.length; i < n; ++i) { if (!(filters[k = added[i]] & zero)) { g = groups[groupIndex[k]]; g.value = reduceAdd(g.value, data[k]); } } // Remove the removed values. for (i = 0, n = removed.length; i < n; ++i) { if ((filters[k = removed[i]] & zero) === filterOne) { g = groups[groupIndex[k]]; g.value = reduceRemove(g.value, data[k]); } } } // Reduces the specified selected or deselected records. // This function is only used when the cardinality is 1. function updateOne(filterOne, added, removed) { if (filterOne === one || resetNeeded) return; var i, k, n, g = groups[0]; // Add the added values. for (i = 0, n = added.length; i < n; ++i) { if (!(filters[k = added[i]] & zero)) { g.value = reduceAdd(g.value, data[k]); } } // Remove the removed values. for (i = 0, n = removed.length; i < n; ++i) { if ((filters[k = removed[i]] & zero) === filterOne) { g.value = reduceRemove(g.value, data[k]); } } } // Recomputes the group reduce values from scratch. // This function is only used when the cardinality is greater than 1. function resetMany() { var i, g; // Reset all group values. for (i = 0; i < k; ++i) { groups[i].value = reduceInitial(); } // Add any selected records. for (i = 0; i < n; ++i) { if (!(filters[i] & zero)) { g = groups[groupIndex[i]]; g.value = reduceAdd(g.value, data[i]); } } } // Recomputes the group reduce values from scratch. // This function is only used when the cardinality is 1. function resetOne() { var i, g = groups[0]; // Reset the singleton group values. g.value = reduceInitial(); // Add any selected records. for (i = 0; i < n; ++i) { if (!(filters[i] & zero)) { g.value = reduceAdd(g.value, data[i]); } } } // Returns the array of group values, in the dimension's natural order. function all() { if (resetNeeded) reset(), resetNeeded = false; return groups; } // Returns a new array containing the top K group values, in reduce order. function top(k) { var top = select(all(), 0, groups.length, k); return heap.sort(top, 0, top.length); } // Sets the reduce behavior for this group to use the specified functions. // This method lazily recomputes the reduce values, waiting until needed. function reduce(add, remove, initial) { reduceAdd = add; reduceRemove = remove; reduceInitial = initial; resetNeeded = true; return group; } // A convenience method for reducing by count. function reduceCount() { return reduce(crossfilter_reduceIncrement, crossfilter_reduceDecrement, crossfilter_zero); } // A convenience method for reducing by sum(value). function reduceSum(value) { return reduce(crossfilter_reduceAdd(value), crossfilter_reduceSubtract(value), crossfilter_zero); } // Sets the reduce order, using the specified accessor. function order(value) { select = heapselect_by(valueOf); heap = heap_by(valueOf); function valueOf(d) { return value(d.value); } return group; } // A convenience method for natural ordering by reduce value. function orderNatural() { return order(crossfilter_identity); } // Returns the cardinality of this group, irrespective of any filters. function size() { return k; } // Removes this group and associated event listeners. function remove() { var i = filterListeners.indexOf(update); if (i >= 0) filterListeners.splice(i, 1); i = indexListeners.indexOf(add); if (i >= 0) indexListeners.splice(i, 1); return group; } return reduceCount().orderNatural(); } // A convenience function for generating a singleton group. function groupAll() { var g = group(crossfilter_null), all = g.all; delete g.all; delete g.top; delete g.order; delete g.orderNatural; delete g.size; g.value = function() { return all()[0].value; }; return g; } function remove() { dimensionGroups.forEach(function(group) { group.remove(); }); var i = dataListeners.indexOf(preAdd); if (i >= 0) dataListeners.splice(i, 1); i = dataListeners.indexOf(postAdd); if (i >= 0) dataListeners.splice(i, 1); for (i = 0; i < n; ++i) filters[i] &= zero; m &= zero; return dimension; } return dimension; } // A convenience method for groupAll on a dummy dimension. // This implementation can be optimized since it always has cardinality 1. function groupAll() { var group = { reduce: reduce, reduceCount: reduceCount, reduceSum: reduceSum, value: value, remove: remove }; var reduceValue, reduceAdd, reduceRemove, reduceInitial, resetNeeded = true; // The group listens to the crossfilter for when any dimension changes, so // that it can update the reduce value. It must also listen to the parent // dimension for when data is added. filterListeners.push(update); dataListeners.push(add); // For consistency; actually a no-op since resetNeeded is true. add(data, 0, n); // Incorporates the specified new values into this group. function add(newData, n0) { var i; if (resetNeeded) return; // Add the added values. for (i = n0; i < n; ++i) { if (!filters[i]) { reduceValue = reduceAdd(reduceValue, data[i]); } } } // Reduces the specified selected or deselected records. function update(filterOne, added, removed) { var i, k, n; if (resetNeeded) return; // Add the added values. for (i = 0, n = added.length; i < n; ++i) { if (!filters[k = added[i]]) { reduceValue = reduceAdd(reduceValue, data[k]); } } // Remove the removed values. for (i = 0, n = removed.length; i < n; ++i) { if (filters[k = removed[i]] === filterOne) { reduceValue = reduceRemove(reduceValue, data[k]); } } } // Recomputes the group reduce value from scratch. function reset() { var i; reduceValue = reduceInitial(); for (i = 0; i < n; ++i) { if (!filters[i]) { reduceValue = reduceAdd(reduceValue, data[i]); } } } // Sets the reduce behavior for this group to use the specified functions. // This method lazily recomputes the reduce value, waiting until needed. function reduce(add, remove, initial) { reduceAdd = add; reduceRemove = remove; reduceInitial = initial; resetNeeded = true; return group; } // A convenience method for reducing by count. function reduceCount() { return reduce(crossfilter_reduceIncrement, crossfilter_reduceDecrement, crossfilter_zero); } // A convenience method for reducing by sum(value). function reduceSum(value) { return reduce(crossfilter_reduceAdd(value), crossfilter_reduceSubtract(value), crossfilter_zero); } // Returns the computed reduce value. function value() { if (resetNeeded) reset(), resetNeeded = false; return reduceValue; } // Removes this group and associated event listeners. function remove() { var i = filterListeners.indexOf(update); if (i >= 0) filterListeners.splice(i); i = dataListeners.indexOf(add); if (i >= 0) dataListeners.splice(i); return group; } return reduceCount(); } // Returns the number of records in this crossfilter, irrespective of any filters. function size() { return n; } return arguments.length ? add(arguments[0]) : crossfilter; } // Returns an array of size n, big enough to store ids up to m. function crossfilter_index(n, m) { return (m < 0x101 ? crossfilter_array8 : m < 0x10001 ? crossfilter_array16 : crossfilter_array32)(n); } // Constructs a new array of size n, with sequential values from 0 to n - 1. function crossfilter_range(n) { var range = crossfilter_index(n, n); for (var i = -1; ++i < n;) range[i] = i; return range; } function crossfilter_capacity(w) { return w === 8 ? 0x100 : w === 16 ? 0x10000 : 0x100000000; } })(this);
JavaScript
function run_test() { var sides = 1; var alternativeOption = getSelected(document.getElementById('alternative-options')); var dataSetOne = document.getElementById('sample_one').content; var dataSetTwo = document.getElementById('sample_two').content; console.log(dataSetTwo); if(alternativeOption !== 'notequals') { sides = 2; } if((! dataSetOne) || (! dataSetTwo)) { insert_alert_boxes("alert-error", "Drop both the Google Trend CSV Files.", "We also provide you with <a href=\"report.csv\">examples</a>."); alert("Missing Data Set"); return; } var startDateOne = document.getElementById('chart_one_selection_start').firstChild.data; var startDateTwo = document.getElementById('chart_two_selection_start').firstChild.data; var endDateOne = document.getElementById('chart_one_selection_end').firstChild.data; var endDateTwo = document.getElementById('chart_two_selection_end').firstChild.data; if((startDateOne != startDateTwo) || (endDateOne != endDateTwo)) { insert_alert_boxes("alert-warning", "Different Time Frames.", "Interesting! You choose data from different times for the two data-sets. Make sure that is exactly what your experiment is concerned with."); } var setOne = getRawDataSet(dataSetOne, startDateOne, endDateOne); var setTwo = getRawDataSet(dataSetTwo, startDateTwo, endDateTwo); meanOne = mean(setOne); meanTwo = mean(setTwo); // If this is a sample rather than a population if(setOne.length !== dataSetOne.length){ stdDevOne = stdDev(setOne, true); stdDevTwo = stdDev(setTwo, true); } else { stdDevOne = stdDev(setOne, false); stdDevTwo = stdDev(setTwo, false); } var t_score = (meanOne - meanTwo)/ Math.sqrt(Math.pow(stdDevOne, 2)/setOne.length +Math.pow(stdDevTwo, 2)/setTwo.length); // From http://ncalculators.com/statistics/effect-of-size-calculator.htm var sdpooled = Math.sqrt(((stdDevOne*stdDevOne)+(stdDevTwo*stdDevTwo))/2); var d= (meanOne - meanTwo)/sdpooled; var r= d/Math.sqrt((d*d)+4); d=Math.round(d*10000000)/10000000; var df = 1; if(!isNaN(parseFloat(document.getElementById("df").value))) { df=parseFloat(document.getElementById("df").value); r = Math.sqrt((t_score*t_score)/((t_score*t_score)+(df*1))); d = (t_score*2)/(Math.sqrt(df)); } // document.getElementById('t-value').innerHTML ="t-value:<div>"+(t_score.toFixed(2))+"</div>"; document.getElementById('mean').innerHTML ="Mean<div>One: "+(meanOne.toFixed(2))+" Two: "+(meanTwo.toFixed(2))+"</div>"; document.getElementById('standard_deviation').innerHTML ="Standard Deviation<div>One: "+(stdDevOne.toFixed(2))+" Two: "+(stdDevTwo.toFixed(2))+"</div>"; document.getElementById('effective_size').innerHTML ="Effective Size<div>"+r.toFixed(2)+"</div>"; document.getElementById('num_of_obs').innerHTML ="Number of Observations<div>One: "+setOne.length+ " Two: "+setTwo.length+"</div>"; var pval = null; if(sides === 1){ pval = TtoP(t_score,df).toFixed(4); document.getElementById('significance_level').innerHTML ="Significance Level (p-value)<div>"+pval+"</div>"; } else { pval = (TtoP(t_score,df)/2).toFixed(4); document.getElementById('significance_level').innerHTML ="Significance Level (p-value)<div>"+pval+"</div>"; } insert_alert_boxes("alert-info", "Alpha.", "Before you run any statistical test, you must first determine your alpha level, which is also called the “significance level.” By definition, the alpha level is the probability of rejecting the null hypothesis when the null hypothesis is true. In other words, its the probability of making a wrong decision. Most folks typically use an alpha level of 0.05. However, if youre analyzing airplane engine failures, you may want to lower the probability of making a wrong decision and use a smaller alpha. On the other hand, if you’re making paper airplanes, you might be willing to increase alpha and accept the higher risk of making the wrong decision. Like all probabilities, alpha ranges from 0 to 1."); if(pval <= 0.05) { insert_alert_boxes("alert-success", "Statistical Significance!", "Interesting! It seems that the difference in the means of the two data-sets is due to more than just a coincidence or measuring errors. We are assuming a value of alpha to be 0.005 (scroll down to learn more about Alpha). Oh, and you can reject the Null Hypthesis!"); } else { insert_alert_boxes("alert-error", "Fail to Reject", "Looks like you are unable to reject the null hypothesis given the data you are working with. Are you asking the right research question? Are you using the correct data? We are assuming a value of alpha to be 0.005 (scroll down to learn more about Alpha)."); } } function getRawDataSet(dataSet, startDate, endDate){ var startRecording = new Boolean(); var sampleArray = []; for(var i = 0; i < dataSet.length; i++) { var dataBlock = dataSet[i]; if(dataBlock.startDate === startDate){ startRecording = true; } if(dataBlock.endDate === endDate){ startRecording = false; break; } if(startRecording === true){ sampleArray.push(parseInt(dataBlock.value)); } } return sampleArray; } function total(arrayIntegers){ var total = 0; for(var i = 0; i < arrayIntegers.length; i++){ total += parseInt(arrayIntegers[i]); } return total; } function mean(arrayIntegers){ return total(arrayIntegers)/arrayIntegers.length; } function variance(arrayIntegers, booleanSample){ var deviations = [] var meanValue = mean(arrayIntegers); for(var i = 0; i < arrayIntegers.length; i++){ deviations.push(Math.pow(arrayIntegers[i] - meanValue, 2)); } if(booleanSample) { return total(deviations)/(deviations.length - 1); } else { return total(deviations)/deviations.length; } } function stdDev(arrayIntegers, booleanSample){ var varianceValue = variance(arrayIntegers, booleanSample); return Math.sqrt(varianceValue) } function getSelected(selectOptions){ for(var i = 0; i < selectOptions.length;i++){ if(selectOptions.options[i].selected){ return selectOptions.options[i].value; } } } function cout(msg){ console.log(msg) } // Conversion from t-value to p-value // http://easycalculation.com/statistics/p-value-t-test.php function TtoP(t, df) { with (Math) { var abst = abs(t), tsq = t*t, p; if(df == 1) { p = 1 - 2*atan(abst)/PI; } else if (df == 2) { p = 1 - abst/sqrt(tsq + 2); } else if (df == 3) { p = 1 - 2*(atan(abst/sqrt(3)) + abst*sqrt(3)/(tsq + 3))/PI; } else if (df == 4) { p = 1 - abst*(1 + 2/(tsq + 4))/sqrt(tsq + 4); } else { var z = TtoZ(abst, df); if (df>4){ p = Norm_p(z); } else { p = Norm_p(z); } } } return p; } function TtoZ(t, df) { var A9 = df - 0.5; var B9 = 48*A9*A9; var T9 = t*t/df, Z8, P7, B7, z; with (Math) { if (T9 >= 0.04) { Z8 = A9*log(1+T9); } else { Z8 = A9*(((1 - T9*0.75)*T9/3 - 0.5)*T9 + 1)*T9; } P7 = ((0.4*Z8 + 3.3)*Z8 + 24)*Z8 + 85.5; B7 = 0.8*pow(Z8, 2) + 100 + B9; z = (1 + (-P7/B7 + Z8 + 3)/B9)*sqrt(Z8); return z; } } function Norm_p(z) { var absz = Math.abs(z); var a1 = 0.0000053830; var a2 = 0.0000488906; var a3 = 0.0000380036; var a4 = 0.0032776263; var a5 = 0.0211410061; var a6 = 0.0498673470; var p = (((((a1*absz+a2)*absz+a3)*absz+a4)*absz+a5)*absz+a6)*absz+1; p = Math.pow(p, -16); return p; }
JavaScript
if (window.File && window.FileReader && window.FileList && window.Blob) { // alert('Great success! All the File APIs are supported.'); } else { alert('The File APIs are not fully supported in this browser.'); } var numberOfBars = 40; // Rough value can be n-1 or n function handleFileSelect(evt) { insert_alert_boxes("alert-info", "Manipulate Data.", "You can manipulate the values of inidividual bars in the graph clicking each bar."); evt.stopPropagation(); evt.preventDefault(); var files = evt.dataTransfer.files; // FileList object. var file = evt.dataTransfer.files[0]; if(file.name.split(".")[1].toUpperCase() != "CSV") { alert("Invalid CSV File"); e.target.parentNode.reset(); return; } else { handleCSV(evt, file); } } function handleDragOver(evt) { evt.stopPropagation(); evt.preventDefault(); evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy. } function handleCSV(evt, f) { var reader = new FileReader(); // files is a FileList of File objects. List some properties. reader.onload = function(f) { var content = f.target.result; var rows = f.target.result.split(/[\r\n|\n]+/); var dataSet = []; for(var i = 2; i < rows.length; i++){ var row = rows[i].split(','); if(i===3){ if(evt.target.output_zone.indexOf("one") !== -1){ document.getElementById("sample_one").value = row[1]; } else { document.getElementById("sample_two").value = row[1]; } } if(hasNumbers(row[0])){ if(hasNumbers(row[1])){ var rowData = new Object(); rowData.startDate = row[0].substring(0, 10); rowData.endDate = row[0].substring(13, row[0].length); rowData.value = row[1]; rowData.size = 1; dataSet.push(rowData); } } } if(evt.target.output_zone.indexOf("one") !== -1){ document.getElementById("sample_one").content = dataSet; } else { document.getElementById("sample_two").content = dataSet; } dataSet = refineData(dataSet); render(evt, dataSet); } reader.readAsText(f); } function refineData(dataSet){ var refine = []; var counter = 0; var mergeSize = Math.floor(dataSet.length/numberOfBars); var rowData = new Object(); rowData.startDate = dataSet[0].startDate; rowData.value = 0; rowData.size = 1; for(var i = 0; i < dataSet.length; i++){ rowData.value = rowData.value + parseInt(dataSet[i].value); rowData.size = rowData.size+1; if(counter==mergeSize){ rowData.endDate = dataSet[i].endDate; refine.push(rowData); rowData = new Object() rowData.startDate = dataSet[i+1].startDate; rowData.value = 0; rowData.size = 1; counter = 0; } counter++; } return refine; } function hasNumbers(t){ return /\d/.test(t); } // width of g, which svg will have to have offset from translation var width = 640; var height = 120; function render(evt, dataSet){ var data = dataSet; var w = Math.ceil(width/data.length); var h = 80; var xScale = d3.time.scale() .domain([new Date(data[0].startDate), d3.time.day.offset(new Date(data[data.length - 1].endDate), 1)]) .range([0, width]); var yScale = d3.scale.linear() .domain([d3.min(data, function(d) { return d.value - 50; }), d3.max(data, function(d) { return d.value; })]) .rangeRound([h, 0]); var xAxis = d3.svg.axis() .scale(xScale) .ticks(6) .tickPadding(3) .tickSize(0) .orient('bottom'); var yAxis = d3.svg.axis() .scale(yScale) .ticks(3) .orient('left'); var chart = evt.target.chart; var svg = null; var chart_selection_end_view = null; var chart_selection_start_view = null; var chart_barsholder = null; if(evt.target.output_zone.indexOf("one") !== -1){ d3.select("#x-axis-one").call(xAxis); d3.select("#y-axis-one").call(yAxis); svg = d3.select("#chart_one"); chart_selection_end_view = d3.select("#chart_one_selection_end"); chart_selection_start_view = d3.select("#chart_one_selection_start"); chart_barsholder = d3.select("#chart_one_barsholder"); } else { d3.select("#x-axis-two").call(xAxis); d3.select("#y-axis-two").call(yAxis); svg = d3.select("#chart_two"); chart_selection_end_view = d3.select("#chart_two_selection_end"); chart_selection_start_view = d3.select("#chart_two_selection_start"); chart_barsholder = d3.select("#chart_two_barsholder"); } chart_selection_start_view.text(data[0].startDate); chart_selection_end_view.text(data[data.length - 1].endDate); if(chart_barsholder.selectAll("rect")[0].length) { chart_barsholder.selectAll("rect").remove(); } var bars = chart_barsholder.selectAll("rect") .data(data); bars.enter().append("rect"); bars.on("click", function(d, i) { var op = prompt("Please enter the value", data[i].value); if(!isNaN(parseInt(op,10))){ data[i].value = parseInt(op, 10); render(evt, data); } }) .attr("x", function(d, i) { return xScale(new Date(data[i].startDate)); }) .attr('y', function(d) { return h - (h - yScale(d.value)) }) .attr("width", w) .attr("height", function(d) { return h - yScale(d.value); }) .style("fill","steelblue") .style("stroke", "white") // removes the class "selected" from the bars if applied due to a prior data set. .classed("selected", function() {return false;}) ; var selected_dates = new Array(); var brush = d3.svg.brush().x(xScale) .on("brushstart", function() { svg.classed("selecting", true); }) .on("brush", function() { var s = d3.event.target.extent(); // console.log(s[0] + " " + s[1]); s[0] = xScale(s[0]); s[1] = xScale(s[1]); // console.log(s[0] + " " + s[1]); selected_dates = new Array(); bars.classed("selected", function(d,i) { var temp_x = xScale(new Date(d.startDate)); if((s[0] - .5) <= temp_x && (temp_x + w) <= s[1]) { selected_dates.push(d.startDate); selected_dates.push(d.endDate); } // console.log(temp_x); return (s[0] - .5) <= temp_x && (temp_x + w) <= s[1]; }); if(selected_dates.length == 0) { chart_selection_start_view.text(data[0].startDate); chart_selection_end_view.text(data[data.length - 1].endDate); } else { chart_selection_start_view.text(selected_dates[0]); chart_selection_end_view.text(selected_dates[selected_dates.length - 1]); } // console.log(selected_dates); }) .on("brushend", function() { svg.classed("selecting", !d3.event.target.empty()); }); //remove any existing brushes before appending a new one. var prior_brushes = svg.selectAll(".brush"); if(prior_brushes[0].length != 0) { prior_brushes.remove(); } svg.insert("g", "g") .attr("id", "brush") .attr("class", "brush") .attr("transform", "translate(40,25)") .call(brush) .selectAll("rect") .attr("height", h) ; // Remove the hash tag and insert the data into svg chart = chart.substring(1, chart.length); document.getElementById(chart).content = data; } // Setup the dnd listeners. var dropZone1 = document.getElementById('drop_zone_one'); dropZone1.addEventListener('dragover', handleDragOver, false); dropZone1.addEventListener('drop', handleFileSelect, false); dropZone1.output_zone = 'list_one'; // Sample Input One dropZone1.chart = '#chart_one'; // svg tag chart one var dropZone2 = document.getElementById('drop_zone_two'); dropZone2.addEventListener('dragover', handleDragOver, false); dropZone2.addEventListener('drop', handleFileSelect, false); dropZone2.output_zone = 'list_two'; // Sample Input Two dropZone2.chart = '#chart_two'; // svg tag chart two //------- Suggestion Box var current_step = 0; var previous_step = 0; var progress_state = "start"; $("li").on('activate', function() { current_step = this.childNodes[0].href.split("step")[this.childNodes[0].href.split("step").length - 1]; if(current_step === "1") { insert_alert_boxes("alert-info", "Null/Alternate Hypothesis.", "Many articles mention what a researcher is testing to be the cause of a particular phenomenon (a researcher is testing what is known as the alternate hypothesis (H1). They fail to mention the null hypothesis (H0). It is a standard fixture in statistical literature. The null hypothesis is what a researcher tries to reject or fails-to-reject."); insert_alert_boxes("alert-warning", "Reject vs Disprove.", "To Reject does not mean to Disprove. Remember hypothesis testing is tied to the data being used for the test."); } if(current_step === "2") { insert_alert_boxes("alert-warning", "Correct Data Input.", "Make sure that you feed in both data-sets"); } if(current_step === "3") { insert_alert_boxes("alert-info", "Serial Sampling.", "Serial sampling is when you select every 3rd or 10th item. It is a close substitue for random sampling."); } if(previous_step < current_step && current_step != "1" && progress_state != "progress") { insert_alert_boxes("alert-success", "Progress.", "Looks like you are now in <strong>step " + current_step + "</strong>" + " and making good progress. Keep it up!"); // if(current_step != 1) { // } progress_state = "progress"; } else if(previous_step >= current_step && progress_state != "stepback") { progress_state = "stepback"; insert_alert_boxes("alert-warning", "Hmm.", "Looks like you are steping back." + " Take your time and understand the concept well."); } previous_step = current_step; }); var insert_alert_boxes = function(alert_type, heading, message) { var close_button_html = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>"; var box_message_html = "<strong>" + heading + "</strong> " + message; var alert_types = ["alert-error", "alert-success", "alert-info", ""]; if((alert_types.indexOf(alert_type) == 0) || alert_types.indexOf(alert_type)) { d3.select("#suggestion-block").select("div").insert("div", "div") .attr("class", "alert " + alert_type) .html(close_button_html + box_message_html) ; } else { var box_message_html = "<strong>" + "Well, this is embarassing!" + "</strong> " + "Something seems to have gone terribly wrong. Report this issue to xyz @ i . com"; d3.select("#suggestion-block").select("div").insert("div", "div") .attr("class", "alert alert-error") .html(close_button_html + box_message_html) ; } }
JavaScript
/** * This jQuery plugin displays pagination links inside the selected elements. * * This plugin needs at least jQuery 1.4.2 * * @author Gabriel Birke (birke *at* d-scribe *dot* de) * @version 2.0rc * @param {int} maxentries Number of entries to paginate * @param {Object} opts Several options (see README for documentation) * @return {Object} jQuery Object */ (function($){ /** * @class Class for calculating pagination values */ $.PaginationCalculator = function(maxentries, opts) { this.maxentries = maxentries; this.opts = opts; } $.extend($.PaginationCalculator.prototype, { /** * Calculate the maximum number of pages * @method * @returns {Number} */ numPages:function() { return Math.ceil(this.maxentries/this.opts.items_per_page); }, /** * Calculate start and end point of pagination links depending on * current_page and num_display_entries. * @returns {Array} */ getInterval:function(current_page) { var ne_half = Math.ceil(this.opts.num_display_entries/2); var np = this.numPages(); var upper_limit = np - this.opts.num_display_entries; var start = current_page > ne_half ? Math.max( Math.min(current_page - ne_half, upper_limit), 0 ) : 0; var end = current_page > ne_half?Math.min(current_page+ne_half, np):Math.min(this.opts.num_display_entries, np); return {start:start, end:end}; } }); // Initialize jQuery object container for pagination renderers $.PaginationRenderers = {} /** * @class Default renderer for rendering pagination links */ $.PaginationRenderers.defaultRenderer = function(maxentries, opts) { this.maxentries = maxentries; this.opts = opts; this.pc = new $.PaginationCalculator(maxentries, opts); } $.extend($.PaginationRenderers.defaultRenderer.prototype, { /** * Helper function for generating a single link (or a span tag if it's the current page) * @param {Number} page_id The page id for the new item * @param {Number} current_page * @param {Object} appendopts Options for the new item: text and classes * @returns {jQuery} jQuery object containing the link */ createLink:function(page_id, current_page, appendopts){ var lnk, np = this.pc.numPages(); page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value appendopts = $.extend({text:page_id+1, classes:""}, appendopts||{}); if(page_id == current_page){ lnk = $("<span class='current'>" + appendopts.text + "</span>"); } else { lnk = $("<a>" + appendopts.text + "</a>") .attr('href', this.opts.link_to.replace(/__id__/,page_id)); } if(appendopts.classes){ lnk.addClass(appendopts.classes); } lnk.data('page_id', page_id); return lnk; }, // Generate a range of numeric links appendRange:function(container, current_page, start, end) { var i; for(i=start; i<end; i++) { this.createLink(i, current_page).appendTo(container); } }, getLinks:function(current_page, eventHandler) { var begin, end, interval = this.pc.getInterval(current_page), np = this.pc.numPages(), fragment = $("<div class='pagination'></div>"); // Generate "Previous"-Link if(this.opts.prev_text && (current_page > 0 || this.opts.prev_show_always)){ fragment.append(this.createLink(current_page-1, current_page, {text:this.opts.prev_text, classes:"prev"})); } // Generate starting points if (interval.start > 0 && this.opts.num_edge_entries > 0) { end = Math.min(this.opts.num_edge_entries, interval.start); this.appendRange(fragment, current_page, 0, end); if(this.opts.num_edge_entries < interval.start && this.opts.ellipse_text) { jQuery("<span>"+this.opts.ellipse_text+"</span>").appendTo(fragment); } } // Generate interval links this.appendRange(fragment, current_page, interval.start, interval.end); // Generate ending points if (interval.end < np && this.opts.num_edge_entries > 0) { if(np-this.opts.num_edge_entries > interval.end && this.opts.ellipse_text) { jQuery("<span>"+this.opts.ellipse_text+"</span>").appendTo(fragment); } begin = Math.max(np-this.opts.num_edge_entries, interval.end); this.appendRange(fragment, current_page, begin, np); } // Generate "Next"-Link if(this.opts.next_text && (current_page < np-1 || this.opts.next_show_always)){ fragment.append(this.createLink(current_page+1, current_page, {text:this.opts.next_text, classes:"next"})); } $('a', fragment).click(eventHandler); return fragment; } }); // Extend jQuery $.fn.pagination = function(maxentries, opts){ // Initialize options with default values opts = jQuery.extend({ items_per_page:10, num_display_entries:10, current_page:0, num_edge_entries:0, link_to:"#", prev_text:"Prev", next_text:"Next", ellipse_text:"...", prev_show_always:true, next_show_always:true, renderer:"defaultRenderer", callback:function(){return false;} },opts||{}); var containers = this, renderer, links, current_page; /** * This is the event handling function for the pagination links. * @param {int} page_id The new page number */ function pageSelected(evt){ var links, current_page = $(evt.target).data('page_id'); containers.data('current_page', current_page); links = renderer.getLinks(current_page, pageSelected); containers.empty(); links.appendTo(containers); var continuePropagation = opts.callback(current_page, containers); if (!continuePropagation) { if (evt.stopPropagation) { evt.stopPropagation(); } else { evt.cancelBubble = true; } } return continuePropagation; } current_page = opts.current_page; containers.data('current_page', current_page); // Create a sane value for maxentries and items_per_page maxentries = (!maxentries || maxentries < 0)?1:maxentries; opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page; if(!$.PaginationRenderers[opts.renderer]) { throw new ReferenceError("Pagination renderer '" + opts.renderer + "' was not found in jQuery.PaginationRenderers object."); } renderer = new $.PaginationRenderers[opts.renderer](maxentries, opts); containers.each(function() { // Attach control functions to the DOM element this.selectPage = function(page_id){ pageSelected(page_id);} this.prevPage = function(){ var current_page = containers.data('current_page'); if (current_page > 0) { pageSelected(current_page - 1); return true; } else { return false; } } this.nextPage = function(){ var current_page = containers.data('current_page'); if(current_page < numPages()-1) { pageSelected(current_page+1); return true; } else { return false; } } }); // When all initialisation is done, draw the links links = renderer.getLinks(current_page, pageSelected); containers.empty(); links.appendTo(containers); // call callback function opts.callback(current_page, containers); } })(jQuery);
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // NOTE Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } }; /** * This jQuery plugin displays pagination links inside the selected elements. * * @author Gabriel Birke (birke *at* d-scribe *dot* de) * @version 1.2 * @param {int} maxentries Number of entries to paginate * @param {Object} opts Several options (see README for documentation) * @return {Object} jQuery Object */ jQuery.fn.pagination = function(maxentries, opts){ opts = jQuery.extend({ items_per_page:10, num_display_entries:10, current_page:0, num_edge_entries:0, link_to:"#", prev_text:"Prev", next_text:"Next", ellipse_text:"...", prev_show_always:true, next_show_always:true, callback:function(){return false;} },opts||{}); return this.each(function() { /** * Calculate the maximum number of pages */ function numPages() { return Math.ceil(maxentries/opts.items_per_page); } /** * Calculate start and end point of pagination links depending on * current_page and num_display_entries. * @return {Array} */ function getInterval() { var ne_half = Math.ceil(opts.num_display_entries/2); var np = numPages(); var upper_limit = np-opts.num_display_entries; var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0; var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np); return [start,end]; } /** * This is the event handling function for the pagination links. * @param {int} page_id The new page number */ function pageSelected(page_id, evt){ current_page = page_id; drawLinks(); var continuePropagation = opts.callback(page_id, panel); if (!continuePropagation) { if (evt.stopPropagation) { evt.stopPropagation(); } else { evt.cancelBubble = true; } } return continuePropagation; } /** * This function inserts the pagination links into the container element */ function drawLinks() { panel.empty(); var interval = getInterval(); var np = numPages(); // This helper function returns a handler function that calls pageSelected with the right page_id var getClickHandler = function(page_id) { return function(evt){ return pageSelected(page_id,evt); } } // Helper function for generating a single link (or a span tag if it's the current page) var appendItem = function(page_id, appendopts){ page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value appendopts = jQuery.extend({text:page_id+1, classes:""}, appendopts||{}); if(page_id == current_page){ var lnk = jQuery("<span class='current'>"+(appendopts.text)+"</span>"); } else { var lnk = jQuery("<a>"+(appendopts.text)+"</a>") .bind("click", getClickHandler(page_id)) .attr('href', opts.link_to.replace(/__id__/,page_id)); } if(appendopts.classes){lnk.addClass(appendopts.classes);} panel.append(lnk); } // Generate "Previous"-Link if(opts.prev_text && (current_page > 0 || opts.prev_show_always)){ appendItem(current_page-1,{text:opts.prev_text, classes:"prev"}); } // Generate starting points if (interval[0] > 0 && opts.num_edge_entries > 0) { var end = Math.min(opts.num_edge_entries, interval[0]); for(var i=0; i<end; i++) { appendItem(i); } if(opts.num_edge_entries < interval[0] && opts.ellipse_text) { jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel); } } // Generate interval links for(var i=interval[0]; i<interval[1]; i++) { appendItem(i); } // Generate ending points if (interval[1] < np && opts.num_edge_entries > 0) { if(np-opts.num_edge_entries > interval[1]&& opts.ellipse_text) { jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel); } var begin = Math.max(np-opts.num_edge_entries, interval[1]); for(var i=begin; i<np; i++) { appendItem(i); } } // Generate "Next"-Link if(opts.next_text && (current_page < np-1 || opts.next_show_always)){ appendItem(current_page+1,{text:opts.next_text, classes:"next"}); } } // Extract current_page from options var current_page = opts.current_page; // Create a sane value for maxentries and items_per_page maxentries = (!maxentries || maxentries < 0)?1:maxentries; opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page; // Store DOM element for easy access from all inner functions var panel = jQuery(this); // Attach control functions to the DOM element this.selectPage = function(page_id){ pageSelected(page_id);} this.prevPage = function(){ if (current_page > 0) { pageSelected(current_page - 1); return true; } else { return false; } } this.nextPage = function(){ if(current_page < numPages()-1) { pageSelected(current_page+1); return true; } else { return false; } } // When all initialisation is done, draw the links drawLinks(); // call callback function opts.callback(current_page, this); }); }
JavaScript
/** * @author Remy Sharp * @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/ */ (function ($) { $.fn.hint = function (blurClass) { if (!blurClass) { blurClass = 'blur'; } return this.each(function () { // get jQuery version of 'this' var $input = $(this), // capture the rest of the variable to allow for reuse title = $input.attr('title'), $form = $(this.form), $win = $(window); function remove() { if ($input.val() === title && $input.hasClass(blurClass)) { $input.val('').removeClass(blurClass); } } // only apply logic if the element has the attribute if (title) { // on blur, set value to title attr if text is blank $input.blur(function () { if (this.value === '') { $input.val(title).addClass(blurClass); } }).focus(remove).blur(); // now change all inputs to title // clear the pre-defined text when form is submitted $form.submit(remove); $win.unload(remove); // handles Firefox's autocomplete } }); }; })(jQuery);
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // NOTE Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
/** * Confirm plugin 1.3 * * Copyright (c) 2007 Nadia Alramli (http://nadiana.com/) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ /** * For more docs and examples visit: * http://nadiana.com/jquery-confirm-plugin * For comments, suggestions or bug reporting, * email me at: http://nadiana.com/contact/ */ jQuery.fn.confirm = function(options) { options = jQuery.extend({ msg: 'Are you sure?', stopAfter: 'never', wrapper: '<span></span>', eventType: 'click', dialogShow: 'show', dialogSpeed: '', timeout: 0 }, options); options.stopAfter = options.stopAfter.toLowerCase(); if (!options.stopAfter in ['never', 'once', 'ok', 'cancel']) { options.stopAfter = 'never'; } options.buttons = jQuery.extend({ ok: 'Yes', cancel: 'No', wrapper:'<a href="#"></a>', separator: '/' }, options.buttons); // Shortcut to eventType. var type = options.eventType; return this.each(function() { var target = this; var $target = jQuery(target); var timer; var saveHandlers = function() { var events = jQuery.data(target, 'events'); if (!events && target.href) { // No handlers but we have href $target.bind('click', function() {document.location = target.href}); events = jQuery.data(target, 'events'); } else if (!events) { // There are no handlers to save. return; } target._handlers = new Array(); for (var i in events[type]) { target._handlers.push(events[type][i]); } } // Create ok button, and bind in to a click handler. var $ok = jQuery(options.buttons.wrapper) .append(options.buttons.ok) .click(function() { // Check if timeout is set. if (options.timeout != 0) { clearTimeout(timer); } $target.unbind(type, handler); $target.show(); $dialog.hide(); // Rebind the saved handlers. if (target._handlers != undefined) { jQuery.each(target._handlers, function() { $target.click(this.handler); }); } // Trigger click event. $target.click(); if (options.stopAfter != 'ok' && options.stopAfter != 'once') { $target.unbind(type); // Rebind the confirmation handler. $target.one(type, handler); } return false; }) var $cancel = jQuery(options.buttons.wrapper).append(options.buttons.cancel).click(function() { // Check if timeout is set. if (options.timeout != 0) { clearTimeout(timer); } if (options.stopAfter != 'cancel' && options.stopAfter != 'once') { $target.one(type, handler); } $target.show(); $dialog.hide(); return false; }); if (options.buttons.cls) { $ok.addClass(options.buttons.cls); $cancel.addClass(options.buttons.cls); } var $dialog = jQuery(options.wrapper) .append(options.msg) .append($ok) .append(options.buttons.separator) .append($cancel); var handler = function() { jQuery(this).hide(); // Do this check because of a jQuery bug if (options.dialogShow != 'show') { $dialog.hide(); } $dialog.insertBefore(this); // Display the dialog. $dialog[options.dialogShow](options.dialogSpeed); if (options.timeout != 0) { // Set timeout clearTimeout(timer); timer = setTimeout(function() {$cancel.click(); $target.one(type, handler);}, options.timeout); } return false; }; saveHandlers(); $target.unbind(type); target._confirm = handler target._confirmEvent = type; $target.one(type, handler); }); }
JavaScript
/* * Inline Form Validation Engine 2.1, 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).remove(); }); }); } }, /** * 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'); if (!options.binded) { if (options.bindMethod == "bind"){ // bind fields form.find("[class*=validate]:not([type=checkbox])").bind(options.validationEventTrigger, methods._onFieldEvent); form.find("[class*=validate][type=checkbox]").bind("click", 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])").live(options.validationEventTrigger, methods._onFieldEvent); form.find("[class*=validate][type=checkbox]").live("click", methods._onFieldEvent); // bind form.submit form.live("submit", methods._onSubmitEvent); } options.binded = true; } }, /** * 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]").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'); } }, /** * 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'); return methods._validateField($(el), options); }, /** * 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); }, /** * 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); }, /** * Closes all error prompts on the page */ hidePrompt: function() { var promptClass = "."+ methods._getClassName($(this).attr("id")) + "formError" $(promptClass).fadeTo("fast", 0.3, function() { $(this).remove(); }); }, /** * Closes form error prompts, CAN be invidual */ hide: function() { if($(this).is("form")){ var closingtag = "parentForm"+$(this).attr('id'); }else{ var closingtag = $(this).attr('id') +"formError" } $('.'+closingtag).fadeTo("fast", 0.3, function() { $(this).remove(); }); }, /** * Closes all error prompts on the page */ hideAll: function() { $('.formError').fadeTo("fast", 0.3, function() { $(this).remove(); }); }, /** * Typically called when user exists a field using tab or a mouse click, triggers a field * validation */ _onFieldEvent: function() { var field = $(this); var form = field.closest('form'); var options = form.data('jqv'); // validate the current field methods._validateField(field, options); }, /** * 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 form.find('[class*=validate]').not(':hidden').each( function() { var field = $(this); errorFound |= methods._validateField(field, options, skipAjaxValidation); }); // 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) { // 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; // look for the visually top prompt var destination = Number.MAX_VALUE; var lst = $(".formError:not('.greenPopup')"); for (var i = 0; i < lst.length; i++) { var d = $(lst[i]).offset().top; if (d < destination) destination = d; } if (!options.isOverflown) $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, 1100); else { var overflowDIV = $(options.overflownDIV); 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); } } 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; var equals = true; options.isError = false; options.showArrow = true; optional = false; for (var i = 0; i < rules.length; i++) { var errorMsg = undefined; switch (rules[i]) { case "optional": optional = true; break; case "required": required = true; errorMsg = methods._required(field, rules, i, options); break; case "custom": errorMsg = methods._customRegex(field, rules, i, options); 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 "maxCheckbox": errorMsg = methods._maxCheckbox(field, rules, i, options); field = $($("input[name='" + fieldName + "']")); break; case "minCheckbox": errorMsg = methods._minCheckbox(field, rules, i, options); field = $($("input[name='" + fieldName + "']")); break; case "equals": errorMsg = methods._equals(field, rules, i, options); if (errorMsg !== undefined) equals = false; 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){ if(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.attr("type"); if ((fieldType == "radio" || fieldType == "checkbox") && $("input[name='" + fieldName + "']").size() > 1) { field = $($("input[name='" + fieldName + "'][type!=hidden]:first")); options.showArrow = false; } if (options.isError || !equals){ methods._showPrompt(field, promptText, "", false, options); }else{ if (!isAjaxValidator) methods._closePrompt(field); } field.closest('form').trigger("jqv.field.error", [field, options.isError, promptText]) return options.isError || (!equals); }, /** * 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.attr("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 name = field.attr("name"); if ($("input[name='" + name + "']:checked").size() == 0) { if ($("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 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.attr('value'))) 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]; 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.attr('value') != $("#" + equalsField).attr('value')){ field.css('border','1px solid red'); $("#" + equalsField).css('border', '1px solid red'); return options.allrules.equals.alertText; } else{ field.css('border',''); $("#" + equalsField).css('border', ''); } }, /** * 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.attr('value').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.attr('value').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.attr('value')); 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.attr('value')); 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.attr('value')); 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 past * * @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.attr('value')); 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); } }, /** * 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(field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = $("input[name='" + groupname + "']:checked").size(); if (groupSize > nbCheck) { options.showArrow = false; 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(field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = $("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; if (!extraData) extraData = ""; if (!options.isError) { $.ajax({ type: "GET", url: rule.url, cache: false, dataType: "json", data: "fieldId=" + field.attr("id") + "&fieldValue=" + field.attr("value") + "&extraData=" + extraData, 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]; if (!status) { // Houston we got a problem options.ajaxValidCache[errorFieldId] = false; options.isError = true; var promptText = rule.alertText; methods._showPrompt(errorField, promptText, "", true, options); } else { if (options.ajaxValidCache[errorFieldId] !== undefined) options.ajaxValidCache[errorFieldId] = true; // see if we should display a green prompt var alertTextOk = rule.alertTextOk; if (alertTextOk) methods._showPrompt(errorField, alertTextOk, "pass", true, options); else methods._closePrompt(errorField); } } } }); } }, /** * 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"); } 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"); switch (options.promptPosition) { 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; } } //Cedric: Needed if a container is in position:relative // insert prompt in the form or in the overflown container? if (options.isOverflown) 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 }); 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) { if (prompt) { 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); prompt.animate({ "top": pos.callerTopPosition, "marginTop": pos.marginTopSize }); } }, /** * 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.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 = $(className)[0]; if (match) return $(match); }, /** * 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; 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; } switch (options.promptPosition) { default: case "topRight": if (overflow) // Is the form contained in an overflown container? promptleftPosition += fieldWidth - 30; else { promptleftPosition += fieldWidth - 30; promptTopPosition += -promptHeight; } break; case "topLeft": promptTopPosition += -promptHeight - 10; break; case "centerRight": promptleftPosition += fieldWidth + 13; break; case "bottomLeft": promptTopPosition = promptTopPosition + field.height() + 15; break; case "bottomRight": promptleftPosition += fieldWidth - 30; promptTopPosition += field.height() + 5; } 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"); var userOptions = $.extend({ // Name of the event triggering field validation validationEventTrigger: "blur", // Automatically scroll viewport to the first error scroll: 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, // Used when the form is displayed within a scrolling DIV isOverflown: false, overflownDIV: "", // --- Internals DO NOT TOUCH or OVERLOAD --- // validation rules and i18 allrules: allRules, // 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: {} }, options); form.data('jqv', userOptions); return userOptions; }, /** * Removes forbidden characters from class name * @param {String} className */ _getClassName: function(className) { return className.replace(":","_").replace(".","_"); } }; /** * 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'); } }; })(jQuery);
JavaScript
/** * AJAX Upload ( http://valums.com/ajax-upload/ ) * Copyright (c) Andris Valums * Licensed under the MIT license ( http://valums.com/mit-license/ ) * Thanks to Gary Haran, David Mark, Corey Burns and others for contributions */ (function () { /* global window */ /* jslint browser: true, devel: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true */ /** * Wrapper for FireBug's console.log */ function log(){ if (typeof(console) != 'undefined' && typeof(console.log) == 'function'){ Array.prototype.unshift.call(arguments, '[Ajax Upload]'); console.log( Array.prototype.join.call(arguments, ' ')); } } /** * Attaches event to a dom element. * @param {Element} el * @param type event name * @param fn callback This refers to the passed element */ function addEvent(el, type, fn){ if (el.addEventListener) { el.addEventListener(type, fn, false); } else if (el.attachEvent) { el.attachEvent('on' + type, function(){ fn.call(el); }); } else { throw new Error('not supported or DOM not loaded'); } } /** * Attaches resize event to a window, limiting * number of event fired. Fires only when encounteres * delay of 100 after series of events. * * Some browsers fire event multiple times when resizing * http://www.quirksmode.org/dom/events/resize.html * * @param fn callback This refers to the passed element */ function addResizeEvent(fn){ var timeout; addEvent(window, 'resize', function(){ if (timeout){ clearTimeout(timeout); } timeout = setTimeout(fn, 100); }); } // Needs more testing, will be rewriten for next version // getOffset function copied from jQuery lib (http://jquery.com/) if (document.documentElement.getBoundingClientRect){ // Get Offset using getBoundingClientRect // http://ejohn.org/blog/getboundingclientrect-is-awesome/ var getOffset = function(el){ var box = el.getBoundingClientRect(); var doc = el.ownerDocument; var body = doc.body; var docElem = doc.documentElement; // for ie var clientTop = docElem.clientTop || body.clientTop || 0; var clientLeft = docElem.clientLeft || body.clientLeft || 0; // In Internet Explorer 7 getBoundingClientRect property is treated as physical, // while others are logical. Make all logical, like in IE8. var zoom = 1; if (body.getBoundingClientRect) { var bound = body.getBoundingClientRect(); zoom = (bound.right - bound.left) / body.clientWidth; } if (zoom > 1) { clientTop = 0; clientLeft = 0; } var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft; return { top: top, left: left }; }; } else { // Get offset adding all offsets var getOffset = function(el){ var top = 0, left = 0; do { top += el.offsetTop || 0; left += el.offsetLeft || 0; el = el.offsetParent; } while (el); return { left: left, top: top }; }; } /** * Returns left, top, right and bottom properties describing the border-box, * in pixels, with the top-left relative to the body * @param {Element} el * @return {Object} Contains left, top, right,bottom */ function getBox(el){ var left, right, top, bottom; var offset = getOffset(el); left = offset.left; top = offset.top; right = left + el.offsetWidth; bottom = top + el.offsetHeight; return { left: left, right: right, top: top, bottom: bottom }; } /** * Helper that takes object literal * and add all properties to element.style * @param {Element} el * @param {Object} styles */ function addStyles(el, styles){ for (var name in styles) { if (styles.hasOwnProperty(name)) { el.style[name] = styles[name]; } } } /** * Function places an absolutely positioned * element on top of the specified element * copying position and dimentions. * @param {Element} from * @param {Element} to */ function copyLayout(from, to){ var box = getBox(from); addStyles(to, { position: 'absolute', left : box.left + 'px', top : box.top + 'px', width : from.offsetWidth + 'px', height : from.offsetHeight + 'px' }); } /** * Creates and returns element from html chunk * Uses innerHTML to create an element */ var toElement = (function(){ var div = document.createElement('div'); return function(html){ div.innerHTML = html; var el = div.firstChild; return div.removeChild(el); }; })(); /** * Function generates unique id * @return unique id */ var getUID = (function(){ var id = 0; return function(){ return 'ValumsAjaxUpload' + id++; }; })(); /** * Get file name from path * @param {String} file path to file * @return filename */ function fileFromPath(file){ return file.replace(/.*(\/|\\)/, ""); } /** * Get file extension lowercase * @param {String} file name * @return file extenstion */ function getExt(file){ return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : ''; } function hasClass(el, name){ var re = new RegExp('\\b' + name + '\\b'); return re.test(el.className); } function addClass(el, name){ if ( ! hasClass(el, name)){ el.className += ' ' + name; } } function removeClass(el, name){ var re = new RegExp('\\b' + name + '\\b'); el.className = el.className.replace(re, ''); } function removeNode(el){ el.parentNode.removeChild(el); } /** * Easy styling and uploading * @constructor * @param button An element you want convert to * upload button. Tested dimentions up to 500x500px * @param {Object} options See defaults below. */ window.AjaxUpload = function(button, options){ this._settings = { // Location of the server-side upload script action: 'upload.php', // File upload name name: 'userfile', // Additional data to send data: {}, // Submit file as soon as it's selected autoSubmit: true, // The type of data that you're expecting back from the server. // html and xml are detected automatically. // Only useful when you are using json data as a response. // Set to "json" in that case. responseType: false, // Class applied to button when mouse is hovered hoverClass: 'hover', // Class applied to button when AU is disabled disabledClass: 'disabled', // When user selects a file, useful with autoSubmit disabled // You can return false to cancel upload onChange: function(file, extension){ }, // Callback to fire before file is uploaded // You can return false to cancel upload onSubmit: function(file, extension){ }, // Fired when file upload is completed // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE! onComplete: function(file, response){ } }; // Merge the users options with our defaults for (var i in options) { if (options.hasOwnProperty(i)){ this._settings[i] = options[i]; } } // button isn't necessary a dom element if (button.jquery){ // jQuery object was passed button = button[0]; } else if (typeof button == "string") { if (/^#.*/.test(button)){ // If jQuery user passes #elementId don't break it button = button.slice(1); } button = document.getElementById(button); } if ( ! button || button.nodeType !== 1){ throw new Error("Please make sure that you're passing a valid element"); } if ( button.nodeName.toUpperCase() == 'A'){ // disable link addEvent(button, 'click', function(e){ if (e && e.preventDefault){ e.preventDefault(); } else if (window.event){ window.event.returnValue = false; } }); } // DOM element this._button = button; // DOM element this._input = null; // If disabled clicking on button won't do anything this._disabled = false; // if the button was disabled before refresh if will remain // disabled in FireFox, let's fix it this.enable(); this._rerouteClicks(); }; // assigning methods to our class AjaxUpload.prototype = { setData: function(data){ this._settings.data = data; }, disable: function(){ addClass(this._button, this._settings.disabledClass); this._disabled = true; var nodeName = this._button.nodeName.toUpperCase(); if (nodeName == 'INPUT' || nodeName == 'BUTTON'){ this._button.setAttribute('disabled', 'disabled'); } // hide input if (this._input){ // We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it // has display none when user selects a file this._input.parentNode.style.visibility = 'hidden'; } }, enable: function(){ removeClass(this._button, this._settings.disabledClass); this._button.removeAttribute('disabled'); this._disabled = false; }, /** * Creates invisible file input * that will hover above the button * <div><input type='file' /></div> */ _createInput: function(){ var self = this; var input = document.createElement("input"); input.setAttribute('type', 'file'); input.setAttribute('name', this._settings.name); addStyles(input, { 'position' : 'absolute', // in Opera only 'browse' button // is clickable and it is located at // the right side of the input 'right' : 0, 'margin' : 0, 'padding' : 0, 'fontSize' : '480px', 'cursor' : 'pointer' }); var div = document.createElement("div"); addStyles(div, { 'display' : 'block', 'position' : 'absolute', 'overflow' : 'hidden', 'margin' : 0, 'padding' : 0, 'opacity' : 0, // Make sure browse button is in the right side // in Internet Explorer 'direction' : 'ltr', //Max zIndex supported by Opera 9.0-9.2 'zIndex': 2147483583 }); // Make sure that element opacity exists. // Otherwise use IE filter if ( div.style.opacity !== "0") { if (typeof(div.filters) == 'undefined'){ throw new Error('Opacity not supported by the browser'); } div.style.filter = "alpha(opacity=0)"; } addEvent(input, 'change', function(){ if ( ! input || input.value === ''){ return; } // Get filename from input, required // as some browsers have path instead of it var file = fileFromPath(input.value); if (false === self._settings.onChange.call(self, file, getExt(file))){ self._clearInput(); return; } // Submit form when value is changed if (self._settings.autoSubmit) { self.submit(); } }); addEvent(input, 'mouseover', function(){ addClass(self._button, self._settings.hoverClass); }); addEvent(input, 'mouseout', function(){ removeClass(self._button, self._settings.hoverClass); // We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it // has display none when user selects a file input.parentNode.style.visibility = 'hidden'; }); div.appendChild(input); document.body.appendChild(div); this._input = input; }, _clearInput : function(){ if (!this._input){ return; } // this._input.value = ''; Doesn't work in IE6 removeNode(this._input.parentNode); this._input = null; this._createInput(); removeClass(this._button, this._settings.hoverClass); }, /** * Function makes sure that when user clicks upload button, * the this._input is clicked instead */ _rerouteClicks: function(){ var self = this; // IE will later display 'access denied' error // if you use using self._input.click() // other browsers just ignore click() addEvent(self._button, 'mouseover', function(){ if (self._disabled){ return; } if ( ! self._input){ self._createInput(); } var div = self._input.parentNode; copyLayout(self._button, div); div.style.visibility = 'visible'; }); // commented because we now hide input on mouseleave /** * When the window is resized the elements * can be misaligned if button position depends * on window size */ //addResizeEvent(function(){ // if (self._input){ // copyLayout(self._button, self._input.parentNode); // } //}); }, /** * Creates iframe with unique name * @return {Element} iframe */ _createIframe: function(){ // We can't use getTime, because it sometimes return // same value in safari :( var id = getUID(); // We can't use following code as the name attribute // won't be properly registered in IE6, and new window // on form submit will open // var iframe = document.createElement('iframe'); // iframe.setAttribute('name', id); var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />'); // src="javascript:false; was added // because it possibly removes ie6 prompt // "This page contains both secure and nonsecure items" // Anyway, it doesn't do any harm. iframe.setAttribute('id', id); iframe.style.display = 'none'; document.body.appendChild(iframe); return iframe; }, /** * Creates form, that will be submitted to iframe * @param {Element} iframe Where to submit * @return {Element} form */ _createForm: function(iframe){ var settings = this._settings; // We can't use the following code in IE6 // var form = document.createElement('form'); // form.setAttribute('method', 'post'); // form.setAttribute('enctype', 'multipart/form-data'); // Because in this case file won't be attached to request var form = toElement('<form method="post" enctype="multipart/form-data"></form>'); form.setAttribute('action', settings.action); form.setAttribute('target', iframe.name); form.style.display = 'none'; document.body.appendChild(form); // Create hidden input element for each data key for (var prop in settings.data) { if (settings.data.hasOwnProperty(prop)){ var el = document.createElement("input"); el.setAttribute('type', 'hidden'); el.setAttribute('name', prop); el.setAttribute('value', settings.data[prop]); form.appendChild(el); } } return form; }, /** * Gets response from iframe and fires onComplete event when ready * @param iframe * @param file Filename to use in onComplete callback */ _getResponse : function(iframe, file){ // getting response var toDeleteFlag = false, self = this, settings = this._settings; addEvent(iframe, 'load', function(){ if (// For Safari iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For FF, IE iframe.src == "javascript:'<html></html>';"){ // First time around, do not delete. // We reload to blank page, so that reloading main page // does not re-submit the post. if (toDeleteFlag) { // Fix busy state in FF3 setTimeout(function(){ removeNode(iframe); }, 0); } return; } var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document; // fixing Opera 9.26,10.00 if (doc.readyState && doc.readyState != 'complete') { // Opera fires load event multiple times // Even when the DOM is not ready yet // this fix should not affect other browsers return; } // fixing Opera 9.64 if (doc.body && doc.body.innerHTML == "false") { // In Opera 9.64 event was fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec return; } var response; if (doc.XMLDocument) { // response is a xml document Internet Explorer property response = doc.XMLDocument; } else if (doc.body){ // response is html document or plain text response = doc.body.innerHTML; if (settings.responseType && settings.responseType.toLowerCase() == 'json') { // If the document was sent as 'application/javascript' or // 'text/javascript', then the browser wraps the text in a <pre> // tag and performs html encoding on the contents. In this case, // we need to pull the original text content from the text node's // nodeValue property to retrieve the unmangled content. // Note that IE6 only understands text/html if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') { response = doc.body.firstChild.firstChild.nodeValue; } if (response) { response = eval("(" + response + ")"); } else { response = {}; } } } else { // response is a xml document response = doc; } settings.onComplete.call(self, file, response); // Reload blank page, so that reloading main page // does not re-submit the post. Also, remember to // delete the frame toDeleteFlag = true; // Fix IE mixed content issue iframe.src = "javascript:'<html></html>';"; }); }, /** * Upload file contained in this._input */ submit: function(){ var self = this, settings = this._settings; if ( ! this._input || this._input.value === ''){ return; } var file = fileFromPath(this._input.value); // user returned false to cancel upload if (false === settings.onSubmit.call(this, file, getExt(file))){ this._clearInput(); return; } // sending request var iframe = this._createIframe(); var form = this._createForm(iframe); // assuming following structure // div -> input type='file' removeNode(this._input.parentNode); removeClass(self._button, self._settings.hoverClass); form.appendChild(this._input); form.submit(); // request set, clean up removeNode(form); form = null; removeNode(this._input); this._input = null; // Get response from iframe and fire onComplete event when ready this._getResponse(iframe, file); // get ready for next request this._createInput(); } }; })();
JavaScript
if(typeof(JS_WP_ESTORE_VARIATION_ADD_STRING) == 'undefined') { JS_WP_ESTORE_VARIATION_ADD_STRING = "+"; } if(typeof(JS_WP_ESTORE_CURRENCY_SYMBOL) == 'undefined') { JS_WP_ESTORE_CURRENCY_SYMBOL = "$"; } if(typeof(JS_WP_ESTORE_VARIATION_THOUSAND_SEPERATOR) == 'undefined') { JS_WP_ESTORE_VARIATION_THOUSAND_SEPERATOR = ","; } variation_add_string = JS_WP_ESTORE_VARIATION_ADD_STRING;//"+"; currency_symbol = JS_WP_ESTORE_CURRENCY_SYMBOL;//"$"; thousands_sep = JS_WP_ESTORE_VARIATION_THOUSAND_SEPERATOR;//","; split_char = "[" + variation_add_string; function CheckTok (object1) { var var_add_amt,ary=new Array (); // where we parse ary = val.split ("["); // break apart variation_price_val = ary[1]; if(variation_price_val != null) { //remove the addition,currency and ] symbol then trim it var_add_amt = variation_price_val.replace(variation_add_string, ""); var_add_amt = var_add_amt.replace(currency_symbol, ""); var_add_amt = var_add_amt.replace("]", ""); var_add_amt = var_add_amt.replace(thousands_sep, ""); var_add_amt = trim(var_add_amt); if(eStoreIsNumeric(var_add_amt)){ amt = amt + var_add_amt*1.0; } else{ alert("Error! Variation addition amounts are not numeric. Please contact the admin and mention this error."); } } } function ReadForm1 (object1, buttonType) { // Read the user form var i,j,pos; amt=0;val_total="";val_combo=""; val_1st_half=""; variation_name=""; for (i=0; i<object1.length; i++) { // run entire form obj = object1.elements[i]; // a form element if (obj.type == "select-one") { // just selects if (obj.name == "quantity" || obj.name == "amount") continue; pos = obj.selectedIndex; // which option selected val = obj.options[pos].value; // selected value variation_name = val.split (split_char); // break apart val_combo = val_combo + " (" + trim(variation_name[0]) + ")"; CheckTok(object1); } if (obj.type == "text") { // just text if (obj.name == "add_qty") continue; val = obj.value; // selected value if (val.length != 0) { val_combo = val_combo + " (" + val + ")"; } } } // Now summarize everything we have processed above val_total = object1.product_name_tmp1.value + val_combo; if(buttonType == 1) { object1.product.value = val_total; object1.price.value = parseFloat(object1.price_tmp1.value) + amt; } else if(buttonType == 2) { object1.item_name.value = val_total; if (object1.custom_price){ var custom_price = parseFloat(object1.custom_price.value); var min_amt = parseFloat(object1.price_tmp1.value); if(custom_price<min_amt) { alert("The minimum price you can specify is "+ min_amt); return false; } else{ object1.amount.value = custom_price + amt; } } else{ object1.amount.value = parseFloat(object1.price_tmp1.value) + amt; } setCookie("cart_in_use","true",1); } else if(buttonType == 3) { object1.item_name.value = val_total; object1.a3.value = parseFloat(object1.price_tmp1.value) + amt; } } function trim(stringToTrim) { return stringToTrim.replace(/^\s+|\s+$/g,""); } function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toUTCString()); } function eStoreIsNumeric(input) { return (input - 0) == input && input.length > 0; }
JavaScript
$(document).ready(function() { $("#foo4").carouFredSel({ circular : false, infinite : true, auto: {pauseDuration: 3000, delay: 750}, scroll: {fx: "fade"}, items: { pauseOnHover: true }, prev : { button : "#foo4_prev", key : "left", items : 4, easing : "easeInOutCubic", duration : 2500, pauseOnHover: true }, next : { button : "#foo4_next", key : "right", items : 4, easing : "easeInQuart", duration : 1500, pauseOnHover: true }, pagination : { container : "#foo4_pag", keys : true, easing : "easeOutBounce", duration : 3000, pauseOnHover: true } }); $('.preview-fade').each(function() { $(this).hover( function() { $(this).stop().animate({ opacity: 0.5 }, 400); }, function() { $(this).stop().animate({ opacity: 1.0 }, 400); }) }); }); $(document).ready(function() { //search toggle $("#search-toggle").click(function () { if ($("#adv-search-wrap").is(":hidden")) { $("#adv-search-wrap").fadeIn("normal"); } else { $("#adv-search-wrap").fadeOut("normal"); } return false; }); $('#adv-search-wrap').click(function(e) { e.stopPropagation(); }); $(document).click(function() { $('#adv-search-wrap').animate({ opacity: 'hide' }, 400); }); //search functions $("#adv-search-post").click(function () { $("#search-filter").val('post'); if ($("#adv-search-input").val() == 'search galleries...' || $("#adv-search-input").val() == '') { $("#adv-search-input").val('search posts...'); } $("#adv-search-post").addClass('active'); $("#adv-search-image").removeClass('active'); return false; }); $("#adv-search-image").click(function () { $("#search-filter").val('gallery'); if ($("#adv-search-input").val() == 'search posts...' || $("#adv-search-input").val() == '') { $("#adv-search-input").val('search gallery...'); } $("#adv-search-image").addClass('active'); $("#adv-search-post").removeClass('active'); return false; }); $("#adv-search-input").click(function () { $("#adv-search-input").val(''); }); }); $(document).ready(function() { $('#social-01').tipsy({gravity: 'n'}); $('#social-02').tipsy({gravity: 'n'}); $('#social-03').tipsy({gravity: 'n'}); $('#social-04').tipsy({gravity: 'n'}); $('#social-05').tipsy({gravity: 'n'}); $('#social-06').tipsy({gravity: 'n'}); $('#logoff').tipsy({gravity: 'n'}); $('#tip-1').tipsy({gravity: 's'}); $('#tip-2').tipsy({gravity: 's'}); $('#tip-3').tipsy({gravity: 's'}); $('#tip-4').tipsy({gravity: 's'}); $('#tip-5').tipsy({gravity: 's'}); });
JavaScript
//Style Sheet Switcher version 1.1 Oct 10th, 2006 //Author: Dynamic Drive: http://www.dynamicdrive.com //Usage terms: http://www.dynamicdrive.com/notice.htm var manual_or_random="manual" //"manual" or "random" var randomsetting="3 days" //"eachtime", "sessiononly", or "x days (replace x with desired integer)". Only applicable if mode is random. //////No need to edit beyond here////////////// function getCookie(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 } function setCookie(name, value, days) { var expireDate = new Date() //set "expstring" to either future or past date, to set or delete cookie, respectively var expstring=(typeof days!="undefined")? expireDate.setDate(expireDate.getDate()+parseInt(days)) : expireDate.setDate(expireDate.getDate()-5) document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/"; } function deleteCookie(name){ setCookie(name, "moot") } function setStylesheet(title, randomize){ //Main stylesheet switcher function. Second parameter if defined causes a random alternate stylesheet (including none) to be enabled var i, cacheobj, altsheets=[""] for(i=0; (cacheobj=document.getElementsByTagName("link")[i]); i++) { if(cacheobj.getAttribute("rel").toLowerCase()=="alternate stylesheet" && cacheobj.getAttribute("title")) { //if this is an alternate stylesheet with title cacheobj.disabled = true altsheets.push(cacheobj) //store reference to alt stylesheets inside array if(cacheobj.getAttribute("title") == title) //enable alternate stylesheet with title that matches parameter cacheobj.disabled = false //enable chosen style sheet } } if (typeof randomize!="undefined"){ //if second paramter is defined, randomly enable an alt style sheet (includes non) var randomnumber=Math.floor(Math.random()*altsheets.length) altsheets[randomnumber].disabled=false } return (typeof randomize!="undefined" && altsheets[randomnumber]!="")? altsheets[randomnumber].getAttribute("title") : "" //if in "random" mode, return "title" of randomly enabled alt stylesheet } function chooseStyle(styletitle, days){ //Interface function to switch style sheets plus save "title" attr of selected stylesheet to cookie if (document.getElementById){ setStylesheet(styletitle) setCookie("mysheet", styletitle, days) } } function indicateSelected(element){ //Optional function that shows which style sheet is currently selected within group of radio buttons or select menu if (selectedtitle!=null && (element.type==undefined || element.type=="select-one")){ //if element is a radio button or select menu var element=(element.type=="select-one") ? element.options : element for (var i=0; i<element.length; i++){ if (element[i].value==selectedtitle){ //if match found between form element value and cookie value if (element[i].tagName=="OPTION") //if this is a select menu element[i].selected=true else //else if it's a radio button element[i].checked=true break } } } } if (manual_or_random=="manual"){ //IF MANUAL MODE var selectedtitle=getCookie("mysheet") if (document.getElementById && selectedtitle!=null) //load user chosen style sheet from cookie if there is one stored setStylesheet(selectedtitle) } else if (manual_or_random=="random"){ //IF AUTO RANDOM MODE if (randomsetting=="eachtime") setStylesheet("", "random") else if (randomsetting=="sessiononly"){ //if "sessiononly" setting if (getCookie("mysheet_s")==null) //if "mysheet_s" session cookie is empty document.cookie="mysheet_s="+setStylesheet("", "random")+"; path=/" //activate random alt stylesheet while remembering its "title" value else setStylesheet(getCookie("mysheet_s")) //just activate random alt stylesheet stored in cookie } else if (randomsetting.search(/^[1-9]+ days/i)!=-1){ //if "x days" setting if (getCookie("mysheet_r")==null || parseInt(getCookie("mysheet_r_days"))!=parseInt(randomsetting)){ //if "mysheet_r" cookie is empty or admin has changed number of days to persist in "x days" variable setCookie("mysheet_r", setStylesheet("", "random"), parseInt(randomsetting)) //activate random alt stylesheet while remembering its "title" value setCookie("mysheet_r_days", randomsetting, parseInt(randomsetting)) //Also remember the number of days to persist per the "x days" variable } else setStylesheet(getCookie("mysheet_r")) //just activate random alt stylesheet stored in cookie } }
JavaScript
$(function () { if ($.browser.msie && $.browser.version < 7) return; $('.logo').removeClass('highlight') .find('a').append('<span class="hover" />').each(function () { var $span = $('> span.hover', this).css('opacity', 0); $(this).hover(function () { //on hover $span.stop().fadeTo(250, 1); }, function () { //of Hover $span.stop().fadeTo(400,0) }); }); }); function m_menu() { // k_menu controlls the dropdown menus and improves them with javascript $(".navm a").removeAttr('title'); $(" .navm ul ").css({display: "none"}); // Opera Fix //smooth drop downs $(".navm li").each(function() { var $sublist = $(this).find('ul:first'); $(this).hover(function() { $sublist.stop().css({overflow:"hidden", height:"auto", display:"none", paddingTop:0}).slideDown(250, function() { $(this).css({overflow:"visible", height:"auto"}); }); }, function() { $sublist.stop().slideUp(250, function() { $(this).css({overflow:"hidden", display:"none"}); }); }); }); } $.fn.equalHeights = function() { return this.height(Math.max.apply(null, this.map(function() { return $(this).height() }).get() )); }; /*$.fn.center = function () { this.css("position","absolute"); this.css("left", ( $('.slide-foot').width() - this.width() ) / 2+$('.slide-foot').scrollLeft() + "px"); return this; }*/ $(document).ready(function () { $('.sameH').equalHeights(); $('.sup_column:last').css('border','none'); $('.news-widget ul li:last-child').css('border','none'); $('#nav ul li:first').addClass('round_topright'); $('ul.Fi li:first').addClass('current-cat'); //$('.free_lec li:last-child').css('background', 'none'); $('.tab_control li:eq(2)').addClass('greentx'); $('.tab_control li:eq(3)').addClass('bluetx'); $('.tab_control li:eq(4)').addClass('blacktx'); $('.tab_control li:eq(0)').addClass('blacktx'); /*Sliders*/ $('.slider').nivoSlider({ directionNavHide:false, directionNav:false }); $('.slider2').nivoSlider({ directionNavHide:false, directionNav:false }); $('.slider3').nivoSlider({ directionNavHide:false, directionNav:false }); $('.slider4').nivoSlider({ directionNavHide:false, directionNav:false }); $('.slider5').nivoSlider({ directionNavHide:false, directionNav:false }); $('.courseS').nivoSlider({ directionNavHide:false, directionNav:false }); //$('.nivo-controlNav').wrap('<div class="controls" />'); /* End Sliders */ $('.tab_control li:first').addClass('current'); $('.tab2_control li:first').addClass('current'); $('.tab3_control li:first').addClass('current'); $('.info_control li:first').addClass('current'); /*main Tabs*/ $('.tab_control li a').click(function () { //reset all the items $('.tab_control li').removeClass('current'); $(this).parent().addClass('current'); $('.mask').scrollTo($(this).attr('rel'), 1); return false ; }); /*End Main Tabs*/ /*recent Tabs*/ $('.tab2_control li a').click(function () { //reset all the items $('.tab2_control li').removeClass('current'); $(this).parent().addClass('current'); $('.mask2').scrollTo($(this).attr('rel'), 400); return false ; }); /*End recent Tabs*/ /*Mag Tabs*/ $('.tab3_control li a').click(function () { //reset all the items $('.tab3_control li').removeClass('current'); $(this).parent().addClass('current'); $('.mask3').scrollTo($(this).attr('rel'), 400); return false ; }); /*End Mag Tabs*/ /*Widget Tabs*/ $('.wtab_content').hide(); $('.wtab_content:first').show(); $('.wtab_control li:first').addClass('current'); $('.wtab_control li a').click(function(){ $('.wtab_control li').removeClass('current'); $(this).parent().addClass('current'); var currentTab = $(this).attr('href'); $('.wtab_content').hide(); $(currentTab).show(); return false; }); /*End widget Tabs*/ /*board Tabs*/ $('.bord_content').hide(); $('.bord_content:first').show(); $('.board_control li:first').addClass('current'); $('.board_control li a').click(function(){ $('.board_control li').removeClass('current'); $(this).parent().addClass('current'); var currentTab = $(this).attr('href'); $('.bord_content').hide(); $(currentTab).show(); return false; }); /*End board Tabs*/ $('.footer_links .column:last').css('border-left', 'none'); /*new Scroll System*/ /* $(".L-series").jCarouselLite({ btnNext: ".left_scroll a", btnPrev: ".right_scroll a", scroll: 1, //auto: 3000, speed:300 }); $(".recent").jCarouselLite({ btnNext: ".rnext a", btnPrev: ".rprev a", scroll:1, visible: 4, speed:300 }); $(".tutorials").jCarouselLite({ btnNext: ".tnext a", btnPrev: ".tprev a", scroll:1, visible: 4, speed:300 }); $(".free_tuts").jCarouselLite({ btnNext: ".ftnext a", btnPrev: ".ftprev a", scroll:1, visible: 4, speed:300 }); $(".translate_tuts").jCarouselLite({ btnNext: ".ttnext a", btnPrev: ".ttprev a", scroll:1, visible: 4, speed:300 }); $(".workshop").jCarouselLite({ btnNext: ".wnext a", btnPrev: ".wprev a", scroll:1, visible: 4, speed:300 }); $(".mag_slide").jCarouselLite({ btnNext: ".rnext2 a", btnPrev: ".rprev2 a", scroll:1, speed:300 }); $(".models_slide").jCarouselLite({ btnNext: ".model_next a", btnPrev: ".model_prev a", visible: 6, scroll:1, speed:300 }); $(".mat_slide").jCarouselLite({ btnNext: ".mat_next a", btnPrev: ".mat_prev a", scroll:1, visible: 6, speed:300 }); $(".script_slide").jCarouselLite({ btnNext: ".script_next a", btnPrev: ".script_prev a", scroll:1, visible: 6, speed:300 }); */ //$('ul.free_lec').makeacolumnlists({cols:2,colWidth:0,equalHeight:false,startN:1}); $("#mem_work").scrollable({ items:'.member_works', next:'.next_works', prev:'.prev_works', speed:500, easing:'linear', keyboard:false }); var divs = $("#mem_work div.single_work"); for(var i = 0; i < divs.length; i+=6) { divs.slice(i, i+6).wrapAll('<div class="six" />'); } /*Widget Scroll*/ $(".free_lec").scrollable({ items:'.w_scroll', next:'.flnext', prev:'.flprev', speed:400, easing:'linear', keyboard:false }); $(".widgetcur").scrollable({ items:'.curr_cou', next:'.curr_next', prev:'.curr_prev', speed:400, easing:'linear', keyboard:false }); var wids = $("#lec div.single_lec"); for(var i = 0; i < wids.length; i+=3) { wids.slice(i, i+3).wrapAll('<div class="three" />'); } var wids = $("#gnews div.single_lec"); for(var i = 0; i < wids.length; i+=3) { wids.slice(i, i+3).wrapAll('<div class="three" />'); } var wids = $("#misc div.single_lec"); for(var i = 0; i < wids.length; i+=3) { wids.slice(i, i+3).wrapAll('<div class="three" />'); } var wids = $("#jobs div.single_lec"); for(var i = 0; i < wids.length; i+=3) { wids.slice(i, i+3).wrapAll('<div class="three" />'); } /*info Control Tabs*/ $('.info_control li a').click(function () { //reset all the items $('.info_control li').removeClass('current'); $(this).parent().addClass('current'); $('.info-mask').scrollTo($(this).attr('rel'), 300); return false ; }); //External link in new tab $("a[href^=http]").each(function(){ if(this.href.indexOf(location.hostname) == -1) { $(this).attr({ target: "_blank", title: "" }); } }) $('.serv_post').css('display','none'); $('.serv_post:first').css('display','block'); //Search Page Tabs ... $(".search_tab_content").hide(); //Hide all content $(".search_head ul.stabs li:first").addClass("current").show(); //Activate first tab $(".search_tab_content:first").show(); //Show first tab content //On Click Event $(".search_head ul.stabs li").click(function() { $(".search_head ul.stabs li").removeClass("current"); //Remove any "active" class $(this).addClass("current"); //Add "active" class to selected tab $(".search_tab_content").hide(); //Hide all tab content var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content $(activeTab).fadeIn(); //Fade in the active ID content return false; }); /*$(".social li a[title]").tooltip({ // tweak the position offset: [4, 0], // use the "slide" effect effect: 'slide', tipClass:'social_tip', //layout: '<div><span></span></div>' // add dynamic plugin with optional configuration for bottom edge }).dynamic({ bottom: { direction: 'down', bounce: true } }); */$("span.after[title]").tooltip({ // tweak the position offset: [4, 0], // use the "slide" effect effect: 'slide', tipClass:'social_tip2', //layout: '<div><span></span></div>' // add dynamic plugin with optional configuration for bottom edge }).dynamic({ bottom: { direction: 'down', bounce: true } }); $(".course_student li a[title]").tooltip({ // tweak the position offset: [4, 0], // use the "slide" effect effect: 'slide', tipClass:'social_tip', //layout: '<div><span></span></div>' // add dynamic plugin with optional configuration for bottom edge }).dynamic({ bottom: { direction: 'down', bounce: true } }); $(".related_courses li a[rel='student_work']").colorbox({ maxWidth:1280, maxHeight:1024, }); $("a.img_sc[rel='gth']").colorbox({ maxWidth:1280, maxHeight:1024, }); $("a.vid_sc[rel='gth']").colorbox({iframe:true, innerWidth:550, innerHeight:400}); $(".related_courses ul li a").append("<span></span>"); $(".related_courses ul li a").hover(function(){ $(this).children("span").fadeIn(700); },function(){ $(this).children("span").fadeOut(100); }); m_menu(); var $div = $('.srch_wrap'); var height = $div.height(); $div.hide().css({ height : 0 }); $('.serch_button a').click(function () { if ( $div.is(':visible') ) { $div.animate({ height: 0 }, { duration: 150, complete: function () { $div.hide(); $('.serch_button').removeClass('current-spage'); } }); } else { $div.show().animate({ height : height }, { duration: 300 }, {easing: 'easein'}); $('.serch_button').addClass('current-spage'); } return false; }); $('.lesson-single .single_content a img').parent().attr('class', 'lightbox_img'); $('.info_content a img').parent().attr('class', 'lightbox_img'); $('.news-single a img').parent().attr('class', 'lightbox_img'); $('.lesson-single .single_content a.lightbox_img').colorbox({ maxWidth:1280, maxHeight:1024, }); $('.info_content a.lightbox_img').colorbox({ maxWidth:1280, maxHeight:1024, }); $('.news-single a.lightbox_img').colorbox({ maxWidth:1280, maxHeight:1024, }); $('.lesson-single .single_content img').wrap('<div class="image_wrap_all"></div>'); $('.info_content img').wrap('<div class="image_wrap_all"></div>'); $('ul.navin li a').removeAttr("title") //('.footer_links div:first').removeClass('one_fifth') //$('.footer_links div:first').addClass('two_fifth') $('.footer_links .one_fifth:last').css('margin-left', '0') $('.eStore_cart_fancy1 table tr:first').css('display', 'none') });
JavaScript
(function ($) { $.fn.jCarouselLite = function (o) { o = $.extend({ btnPrev: null, btnNext: null, btnGo: null, mouseWheel: false, auto: null, speed: 200, easing: null, vertical: false, circular: true, visible: 3, start: 0, scroll: 1, beforeStart: null, afterEnd: null }, o || {}); return this.each(function () { var b = false, animCss = o.vertical ? "top" : "right", sizeCss = o.vertical ? "height" : "width"; var c = $(this), ul = $("ul", c), tLi = $("li", ul), tl = tLi.size(), v = o.visible; if (o.circular) { ul.prepend(tLi.slice(tl - v - 1 + 1).clone()).append(tLi.slice(0, v).clone()); o.start += v } var f = $("li", ul), itemLength = f.size(), curr = o.start; c.css("visibility", "visible"); f.css({ overflow: "hidden", float: o.vertical ? "none" : "right" }); ul.css({ margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1" }); c.css({ overflow: "hidden", position: "relative", "z-index": "2", right: "0px" }); var g = o.vertical ? height(f) : width(f); var h = g * itemLength; var j = g * v; f.css({ width: f.width(), height: f.height() }); ul.css(sizeCss, h + "px").css(animCss, -(curr * g)); c.css(sizeCss, j + "px"); if (o.btnPrev) $(o.btnPrev).click(function () { return go(curr - o.scroll) }); if (o.btnNext) $(o.btnNext).click(function () { return go(curr + o.scroll) }); if (o.btnGo) $.each(o.btnGo, function (i, a) { $(a).click(function () { return go(o.circular ? o.visible + i : i) }) }); if (o.mouseWheel && c.mousewheel) c.mousewheel(function (e, d) { return d > 0 ? go(curr - o.scroll) : go(curr + o.scroll) }); if (o.auto) setInterval(function () { go(curr + o.scroll) }, o.auto + o.speed); function vis() { return f.slice(curr).slice(0, v) }; function go(a) { if (!b) { if (o.beforeStart) o.beforeStart.call(this, vis()); if (o.circular) { if (a <= o.start - v - 1) { ul.css(animCss, -((itemLength - (v * 2)) * g) + "px"); curr = a == o.start - v - 1 ? itemLength - (v * 2) - 1 : itemLength - (v * 2) - o.scroll } else if (a >= itemLength - v + 1) { ul.css(animCss, -((v) * g) + "px"); curr = a == itemLength - v + 1 ? v + 1 : v + o.scroll } else curr = a } else { if (a < 0 || a > itemLength - v) return; else curr = a } b = true; ul.animate(animCss == "right" ? { right: -(curr * g) } : { top: -(curr * g) }, o.speed, o.easing, function () { if (o.afterEnd) o.afterEnd.call(this, vis()); b = false }); if (!o.circular) { $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); $((curr - o.scroll < 0 && o.btnPrev) || (curr + o.scroll > itemLength - v && o.btnNext) || []).addClass("disabled") } } return false } }) }; function css(a, b) { return parseInt($.css(a[0], b)) || 0 }; function width(a) { return a[0].offsetWidth + css(a, 'marginLeft') + css(a, 'marginRight') }; function height(a) { return a[0].offsetHeight + css(a, 'marginTop') + css(a, 'marginBottom') } })(jQuery);
JavaScript
$.fn.paginate = function(options) { var options = jQuery.extend({ content: 'TBODY TR', limit: 5 },options); return this.each(function() { var page = {}; page.parent = $(this), page.content = (page.parent.is('TABLE')) ? page.parent.find(options.content) : page.parent.children(options.content), page.total = Math.ceil(page.content.size() / options.limit), page.display = page.content.css('display'), page.prev = 0, page.next = 2; page.content.slice(options.limit).css('display', 'none').addClass('ui-helper-hidden'); $(document.createElement("DIV")).addClass("link-container")[(page.parent.is('TABLE')) ? 'insertAfter' : 'appendTo'](this); page.linkContainer = (page.parent.is('TABLE')) ? page.parent.next('.link-container:first') : page.parent.find('.link-container:first'); $(document.createElement("A")).addClass("pagination-link previous ui-state-default").attr('href', 'previous').attr('title', 'Previous page').attr('rel', 'nofollow').text('<').appendTo(page.linkContainer); for(var num=0; num < page.total; num++){ var offset = num + 1, min = (offset * options.limit) - (options.limit), max = (offset * options.limit); $(document.createElement("A")).addClass("pagination-link numeric ui-state-default").attr('href', offset).attr('title', 'Page '+offset+'').attr('rel', 'nofollow').text(offset).appendTo(page.linkContainer); page[offset] = page.content.slice(min, [max]); }; $(document.createElement("A")).addClass("pagination-link next ui-state-default").attr('href', 'next').attr('title', 'Next page').attr('rel', 'nofollow').text('>').appendTo(page.linkContainer); page.wraps = page.linkContainer.find('.paginationWrap'); page.anchors = page.linkContainer.find('A'); page.anchors.bind('mouseenter mouseleave', function(e){ this.self = $(this); (e.type === 'mouseenter') ? this.self.addClass('ui-state-hover') : this.self.removeClass('ui-state-hover'); }).eq(1).addClass('ui-state-active'); page.anchors.bind('click', function(e){ e.preventDefault(); if($(this).is('.ui-state-active')){ return false; } this.siblings = $(this).siblings('.ui-state-active:first'); if($(this).is('.previous')) { if(page.prev === 0){ return false; }; this.link = $(this).siblings('A[href= ' + page.prev + ']'); this.link.add(this.siblings).toggleClass('ui-state-active'); page.content.css('display', 'none').addClass('ui-helper-hidden'); page[page.prev].css('display', page.display).removeClass('ui-helper-hidden'); page.prev--, page.next--; } else if($(this).is('.next')) { if(page.next === (page.total + 1)){ return false; }; this.link = $(this).siblings('A[href= ' + page.next + ']'); this.link.add(this.siblings).toggleClass('ui-state-active'); page.content.css('display', 'none').addClass('ui-helper-hidden'); page[page.next].css('display', page.display).removeClass('ui-helper-hidden'); page.prev++, page.next++; } else { this.link = $(this); this.link.add(this.siblings).toggleClass('ui-state-active'); this.offset = parseInt(this.link.attr('href')); page.content.css('display', 'none').addClass('ui-helper-hidden'); page[this.offset].css('display', page.display).removeClass('ui-helper-hidden'); page.prev = this.offset - 1, page.next = this.offset + 1; } }); return this; }); };
JavaScript
// ColorBox v1.3.16 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+ // Copyright (c) 2011 Jack Moore - jack@colorpowered.com // Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php (function ($, document, window) { var // ColorBox Default Settings. // See http://colorpowered.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, 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 }, // Abstracting the HTML and event identifiers for easy rebranding colorbox = 'colorbox', prefix = 'cbox', // 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 = $.browser.msie && !$.support.opacity, // feature detection alone gave a false positive on at least one phone browser and on some development versions of Chrome. isIE6 = isIE && $.browser.version < 7, 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 = false, publicMethod, boxElement = prefix + 'Element'; // **************** // HELPER FUNCTIONS // **************** // jQuery object generator to reduce code size function $div(id, cssText) { var div = document.createElement('div'); div.id = id ? prefix + id : false; div.style.cssText = cssText || false; return $(div); } // Convert % values to pixels function setSize(size, dimension) { dimension = dimension === 'x' ? $window.width() : $window.height(); return (typeof size === 'string') ? Math.round((/%/.test(size) ? (dimension / 100) * parseInt(size, 10) : parseInt(size, 10))) : size; } // 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|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url); } // Assigns function results to their respective settings. This allows functions to be used as values. function process(settings) { for (var i in settings) { if ($.isFunction(settings[i]) && i.substring(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 = $.trim(settings.href || $(element).attr('href')); settings.title = settings.title || element.title; } function trigger(event, callback) { if (callback) { callback.call(element); } $.event.trigger(event); } // 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 (index < $related.length - 1 || settings.loop) { 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, start); $box.removeClass(className + "on").addClass(className + "off"); }; if (settings.slideshowAuto) { start(); } else { stop(); } } } function launch(elem) { if (!closing) { element = elem; process($.extend(settings, $.data(element, colorbox))); $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) { try { element.blur(); $(element).one(event_closed, function () { try { this.focus(); } catch (e) { // do nothing } }); } catch (e) { // do nothing } } // +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(0); 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); } } // **************** // 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, autoOpen; if (!$this[0] && $this.selector) { // if a selector was given and it didn't match any elements, go ahead and exit. return $this; } options = options || {}; if (callback) { options.onComplete = callback; } if (!$this[0] || $this.selector === undefined) { // detects $.colorbox() and $.fn.colorbox() $this = $('<a/>'); options.open = true; // assume an immediate open } $this.each(function () { $.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options)); $(this).addClass(boxElement); }); autoOpen = options.open; if ($.isFunction(autoOpen)) { autoOpen = autoOpen.call($this); } if (autoOpen) { launch($this[0]); } return $this; }; // Initialize ColorBox: store common calculations, preload the interface graphics, append the html. // This preps colorbox for a speedy open when clicked, and lightens the burdon on the browser by only // having to run once, instead of each time colorbox is opened. publicMethod.init = function () { // Create & Append jQuery Objects $window = $(window); $box = $div().attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''}); $overlay = $div("Overlay", isIE6 ? 'position:absolute' : '').hide(); $wrap = $div("Wrapper"); $content = $div("Content").append( $loaded = $div("LoadedContent", 'width:0; height:0; overflow:hidden'), $loadingOverlay = $div("LoadingOverlay").add($div("LoadingGraphic")), $title = $div("Title"), $current = $div("Current"), $next = $div("Next"), $prev = $div("Previous"), $slideshow = $div("Slideshow").bind(event_open, slideshow), $close = $div("Close") ); $wrap.append( // The 3x3 Grid that makes up ColorBox $div().append( $div("TopLeft"), $topBorder = $div("TopCenter"), $div("TopRight") ), $div(false, 'clear:left').append( $leftBorder = $div("MiddleLeft"), $content, $rightBorder = $div("MiddleRight") ), $div(false, 'clear:left').append( $div("BottomLeft"), $bottomBorder = $div("BottomCenter"), $div("BottomRight") ) ).children().children().css({'float': 'left'}); $loadingBay = $div(false, 'position:absolute; width:9999px; visibility:hidden; display:none'); $('body').prepend($overlay, $box.append($wrap, $loadingBay)); $content.children() .hover(function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); }).addClass('hover'); // 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}).hide(); // Setup button events. $next.click(function () { publicMethod.next(); }); $prev.click(function () { publicMethod.prev(); }); $close.click(function () { publicMethod.close(); }); $groupControls = $next.add($prev).add($current).add($slideshow); // Adding the 'hover' class allowed the browser to load the hover-state // background graphics. The class can now can be removed. $content.children().removeClass('hover'); $('.' + boxElement).live('click', function (e) { // checks to see if it was a non-left mouse-click and for clicks modified with ctrl, shift, or alt. if (!((e.button !== 0 && typeof e.button !== 'undefined') || e.ctrlKey || e.shiftKey || e.altKey)) { e.preventDefault(); launch(this); } }); $overlay.click(function () { if (settings.overlayClose) { publicMethod.close(); } }); // Set Navigation Key Bindings $(document).bind("keydown", function (e) { if (open && settings.escKey && e.keyCode === 27) { e.preventDefault(); publicMethod.close(); } if (open && settings.arrowKey && !active && $related[1]) { if (e.keyCode === 37 && (index || settings.loop)) { e.preventDefault(); $prev.click(); } else if (e.keyCode === 39 && (index < $related.length - 1 || settings.loop)) { e.preventDefault(); $next.click(); } } }); }; publicMethod.remove = function () { $box.add($overlay).remove(); $('.' + boxElement).die('click').removeData(colorbox).removeClass(boxElement); }; publicMethod.position = function (speed, loadedCallback) { var animate_speed, // keeps the top and left positions within the browser's viewport. posTop = Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight, 0) / 2 + $window.scrollTop(), posLeft = Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2 + $window.scrollLeft(); // setting the speed to 0 to reduce the delay between same-sized content. animate_speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed; // 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) { // loading overlay height has to be explicitly set for IE6. $topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width; $loadingOverlay[0].style.height = $loadingOverlay[1].style.height = $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: posTop, left: posLeft}, { duration: animate_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 (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) { var $child = $loaded.wrapInner("<div style='overflow:auto'></div>").children(); // temporary wrapper to get an accurate estimate of just how high the total content should be. settings.h = $child.height(); $child.replaceWith($child.children()); // ditch the temporary wrapper div used in height calculation } $loaded.css({height: settings.h}); publicMethod.position(settings.transition === "none" ? 0 : settings.speed); } }; publicMethod.prep = function (object) { if (!open) { return; } var speed = settings.transition === "none" ? 0 : settings.speed; $window.unbind('resize.' + prefix); $loaded.remove(); $loaded = $div('LoadedContent').html(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'; }); } function setPosition(s) { publicMethod.position(s, function () { var prev, prevSrc, next, nextSrc, total = $related.length, iframe, complete; if (!open) { return; } complete = function () { $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); prev = index ? $related[index - 1] : $related[total - 1]; next = index < total - 1 ? $related[index + 1] : $related[0]; if (settings.slideshow) { $slideshow.show(); } // Preloads images within a rel group if (settings.preloading) { nextSrc = $.data(next, colorbox).href || next.href; prevSrc = $.data(prev, colorbox).href || prev.href; nextSrc = $.isFunction(nextSrc) ? nextSrc.call(next) : nextSrc; prevSrc = $.isFunction(prevSrc) ? prevSrc.call(prev) : prevSrc; if (isImage(nextSrc)) { $('<img/>')[0].src = nextSrc; } if (isImage(prevSrc)) { $('<img/>')[0].src = prevSrc; } } } else { $groupControls.hide(); } if (settings.iframe) { iframe = $('<iframe frameborder=0/>').addClass(prefix + 'Iframe')[0]; if (settings.fastIframe) { complete(); } else { $(iframe).load(complete); } iframe.name = prefix + (+new Date()); iframe.src = settings.href; if (!settings.scrolling) { iframe.scrolling = "no"; } if (isIE) { iframe.allowTransparency = "true"; } $(iframe).appendTo($loaded).one(event_purge, function () { iframe.src = "//about:blank"; }); } else { complete(); } if (settings.transition === 'fade') { $box.fadeTo(speed, 1, function () { $box[0].style.filter = ""; }); } else { $box[0].style.filter = ""; } $window.bind('resize.' + prefix, function () { publicMethod.position(0); }); }); } if (settings.transition === 'fade') { $box.fadeTo(speed, 0, function () { setPosition(0); }); } else { setPosition(speed); } }; publicMethod.load = function (launched) { var href, setResize, prep = publicMethod.prep; active = true; photo = false; element = $related[index]; if (!launched) { process($.extend(settings, $.data(element, colorbox))); } 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; $loadingOverlay.show(); 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. $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($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] && (index < $related.length - 1 || settings.loop)) { 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, function (data, status, xhr) { prep(status === 'error' ? $div('Error').text('Request unsuccessful: ' + xhr.statusText) : $(this).contents()); }); } }; // Navigates to the next page/image in a set. publicMethod.next = function () { if (!active) { index = index < $related.length - 1 ? index + 1 : 0; publicMethod.load(); } }; publicMethod.prev = function () { if (!active) { index = index ? index - 1 : $related.length - 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); }); } }; // A method for fetching the current element ColorBox is referencing. // returns a jQuery object. publicMethod.element = function () { return $(element); }; publicMethod.settings = defaults; // Initializes ColorBox when the DOM has loaded $(publicMethod.init); }(jQuery, document, this));
JavaScript
/* * jQuery Easing v1.1.1 - http://gsgd.co.uk/sandbox/jquery.easing.php * * Uses the built in easing capabilities added in jQuery 1.1 * to offer multiple easing options * * Copyright (c) 2007 George Smith * Licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php */ jQuery.extend({ easing: { easein: function(x, t, b, c, d) { return c*(t/=d)*t + b; // in }, easeinout: function(x, t, b, c, d) { if (t < d/2) return 2*c*t*t/(d*d) + b; var ts = t - d/2; return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b; }, easeout: function(x, t, b, c, d) { return -c*t*t/(d*d) + 2*c*t/d + b; }, expoin: function(x, t, b, c, d) { var flip = 1; if (c < 0) { flip *= -1; c *= -1; } return flip * (Math.exp(Math.log(c)/d * t)) + b; }, expoout: function(x, t, b, c, d) { var flip = 1; if (c < 0) { flip *= -1; c *= -1; } return flip * (-Math.exp(-Math.log(c)/d * (t-d)) + c + 1) + b; }, expoinout: function(x, t, b, c, d) { var flip = 1; if (c < 0) { flip *= -1; c *= -1; } if (t < d/2) return flip * (Math.exp(Math.log(c/2)/(d/2) * t)) + b; return flip * (-Math.exp(-2*Math.log(c/2)/d * (t-d)) + c + 1) + b; }, bouncein: function(x, t, b, c, d) { return c - jQuery.easing['bounceout'](x, d-t, 0, c, d) + 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
try { var playlistReady = playerReady; } catch (err){ } playerReady = function(obj) { setTimeout(function(){checkPlaylistLoaded(obj)}, 1); try { playlistReady(obj); } catch (err){ } } function itemHandler(obj) { var item = obj['index']; var playlist = $("#"+obj['id']).next(); var currentItem = 0; playlist.children().each(function(){ if (currentItem == item) { $(this).addClass("playing"); } else { $(this).removeClass("playing"); } currentItem++; }); } function checkPlaylistLoaded(obj) { var player = document.getElementById(obj['id']); var jsPlaylist = player.getPlaylist(); if (jsPlaylist.length > 0) { var playlist = createPlaylist(obj); populatePlaylist(player, jsPlaylist, playlist); player.addControllerListener("PLAYLIST","playlistHandler"); player.addControllerListener("ITEM","itemHandler"); } else { setTimeout(function(){checkPlaylistLoaded(obj)}, 150); } } function createPlaylist(obj){ var playerDiv = $("#"+obj['id']); playerDiv.after("<div class='jw_playlist_playlist'></div>"); return playerDiv.next(); } function playlistHandler(obj){ var player = document.getElementById(obj['id']); var jsPlaylist = player.getPlaylist(); var playerDiv = $("#"+obj['id']); var playlist = playerDiv.next(); populatePlaylist(player, jsPlaylist, playlist); } function populatePlaylist(player, jsPlaylist, playlist){ playlist.empty(); for (var i=0;i<jsPlaylist.length;i++) { var jsItem = jsPlaylist[i]; var alternate = "even"; if (i % 2) { alternate = "odd"; } playlist.append("<div class='jw_playlist_item "+alternate+"'>"+dump(jsItem)+"</div>"); } var playlistItem = 0; playlist.children().each(function(){ var currentItem = playlistItem; $(this).click(function () { player.sendEvent("ITEM", currentItem); }); playlistItem++; }); } function dump(arr) { var output = "<div class='jw_playlist_image_div'><img src='${image}' class='jw_playlist_image' /></div><div class='jw_playlist_title'>${title}</div><div class='jw_playlist_description'>${description}</div><div class='clear'></div>"; var variables = getVars(output); for (var j=0; j<variables.length; j++) { var variable = variables[j]; var varName = variable.replace('${','').replace('}',''); var value = arr[varName]; if (!value) { value = ''; } output = output.replace(variable, value); } output = output.replace("<div class='jw_playlist_image_div'><img src='' class='jw_playlist_image' /></div>",""); return output; } function dumpText(arr) { var dumped_text = ""; if(typeof(arr) == 'object') { for(var item in arr) { var value = arr[item]; if(typeof(value) == 'object') { dumped_text += "<div class='"+item+"'>"; dumped_text += dump(value); dumped_text += "</div>"; } else { dumped_text += "<div class='"+item+"'>"+ value + "</div>"; } } } else { dumped_text += arr+" ("+typeof(arr)+")"; } return dumped_text; } function getVars(str){ return str.match(/\$\{(.*?)\}/g); }
JavaScript
/* * jQuery Nivo Slider v2.3 * http://nivo.dev7studios.com * * Copyright 2010, Gilbert Pellegrom * Free to use and abuse under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * May 2010 - Pick random effect from specified set of effects by toronegro * May 2010 - controlNavThumbsFromRel option added by nerd-sh * May 2010 - Do not start nivoRun timer if there is only 1 slide by msielski * April 2010 - controlNavThumbs option added by Jamie Thompson (http://jamiethompson.co.uk) * March 2010 - manualAdvance option added by HelloPablo (http://hellopablo.co.uk) */ (function($) { var NivoSlider = function(element, options){ //Defaults are below var settings = $.extend({}, $.fn.nivoSlider.defaults, options); //Useful variables. Play carefully. var vars = { currentSlide: 0, currentImage: '', totalSlides: 0, randAnim: '', running: false, paused: false, stop:false }; //Get this slider var slider = $(element); slider.data('nivo:vars', vars); slider.css('position','relative'); slider.addClass('nivoSlider'); //Find our slider children var kids = slider.children(); kids.each(function() { var child = $(this); var link = ''; if(!child.is('img')){ if(child.is('a')){ child.addClass('nivo-imageLink'); link = child; } child = child.find('img:first'); } //Get img width & height var childWidth = child.width(); if(childWidth == 0) childWidth = child.attr('width'); var childHeight = child.height(); if(childHeight == 0) childHeight = child.attr('height'); //Resize the slider if(childWidth > slider.width()){ slider.width(childWidth); } if(childHeight > slider.height()){ slider.height(childHeight); } if(link != ''){ link.css('display','none'); } child.css('display','none'); vars.totalSlides++; }); //Set startSlide if(settings.startSlide > 0){ if(settings.startSlide >= vars.totalSlides) settings.startSlide = vars.totalSlides - 1; vars.currentSlide = settings.startSlide; } //Get initial image if($(kids[vars.currentSlide]).is('img')){ vars.currentImage = $(kids[vars.currentSlide]); } else { vars.currentImage = $(kids[vars.currentSlide]).find('img:first'); } //Show initial link if($(kids[vars.currentSlide]).is('a')){ $(kids[vars.currentSlide]).css('display','block'); } //Set first background slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat'); //Add initial slices for(var i = 0; i < settings.slices; i++){ var sliceWidth = Math.round(slider.width()/settings.slices); if(i == settings.slices-1){ slider.append( $('<div class="nivo-slice"></div>').css({ left:(sliceWidth*i)+'px', width:(slider.width()-(sliceWidth*i))+'px' }) ); } else { slider.append( $('<div class="nivo-slice"></div>').css({ left:(sliceWidth*i)+'px', width:sliceWidth+'px' }) ); } } //Create caption slider.append( $('<div class="nivo-caption"><p></p></div>').css({ display:'none', opacity:settings.captionOpacity }) ); //Process initial caption if(vars.currentImage.attr('title') != ''){ var title = vars.currentImage.attr('title'); if(title.substr(0,1) == '#') title = $(title).html(); $('.nivo-caption p', slider).html(title); $('.nivo-caption', slider).fadeIn(settings.animSpeed); } //In the words of Super Mario "let's a go!" var timer = 0; if(!settings.manualAdvance && kids.length > 1){ timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime); } //Add Direction nav if(settings.directionNav){ slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">Prev</a><a class="nivo-nextNav">Next</a></div>'); //Hide Direction nav if(settings.directionNavHide){ $('.nivo-directionNav', slider).hide(); slider.hover(function(){ $('.nivo-directionNav', slider).show(); }, function(){ $('.nivo-directionNav', slider).hide(); }); } $('a.nivo-prevNav', slider).live('click', function(){ if(vars.running) return false; clearInterval(timer); timer = ''; vars.currentSlide-=2; nivoRun(slider, kids, settings, 'prev'); }); $('a.nivo-nextNav', slider).live('click', function(){ if(vars.running) return false; clearInterval(timer); timer = ''; nivoRun(slider, kids, settings, 'next'); }); } //Add Control nav if(settings.controlNav){ var nivoControl = $('<div class="nivo-controlNav"></div>'); slider.append(nivoControl); for(var i = 0; i < kids.length; i++){ if(settings.controlNavThumbs){ var child = kids.eq(i); if(!child.is('img')){ child = child.find('img:first'); } if (settings.controlNavThumbsFromRel) { nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('rel') + '" alt="" /></a>'); } else { nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('src').replace(settings.controlNavThumbsSearch, settings.controlNavThumbsReplace) +'" alt="" /></a>'); } } else { nivoControl.append('<a class="nivo-control" rel="'+ i +'">'+ (i + 1) +'</a>'); } } //Set initial active link $('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active'); $('.nivo-controlNav a', slider).live('click', function(){ if(vars.running) return false; if($(this).hasClass('active')) return false; clearInterval(timer); timer = ''; slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat'); vars.currentSlide = $(this).attr('rel') - 1; nivoRun(slider, kids, settings, 'control'); }); } //Keyboard Navigation if(settings.keyboardNav){ $(window).keypress(function(event){ //Left if(event.keyCode == '37'){ if(vars.running) return false; clearInterval(timer); timer = ''; vars.currentSlide-=2; nivoRun(slider, kids, settings, 'prev'); } //Right if(event.keyCode == '39'){ if(vars.running) return false; clearInterval(timer); timer = ''; nivoRun(slider, kids, settings, 'next'); } }); } //For pauseOnHover setting if(settings.pauseOnHover){ slider.hover(function(){ vars.paused = true; clearInterval(timer); timer = ''; }, function(){ vars.paused = false; //Restart the timer if(timer == '' && !settings.manualAdvance){ timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime); } }); } //Event when Animation finishes slider.bind('nivo:animFinished', function(){ vars.running = false; //Hide child links $(kids).each(function(){ if($(this).is('a')){ $(this).css('display','none'); } }); //Show current link if($(kids[vars.currentSlide]).is('a')){ $(kids[vars.currentSlide]).css('display','block'); } //Restart the timer if(timer == '' && !vars.paused && !settings.manualAdvance){ timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime); } //Trigger the afterChange callback settings.afterChange.call(this); }); // Private run method var nivoRun = function(slider, kids, settings, nudge){ //Get our vars var vars = slider.data('nivo:vars'); //Trigger the lastSlide callback if(vars && (vars.currentSlide == vars.totalSlides - 1)){ settings.lastSlide.call(this); } // Stop if((!vars || vars.stop) && !nudge) return false; //Trigger the beforeChange callback settings.beforeChange.call(this); //Set current background before change if(!nudge){ slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat'); } else { if(nudge == 'prev'){ slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat'); } if(nudge == 'next'){ slider.css('background','url('+ vars.currentImage.attr('src') +') no-repeat'); } } vars.currentSlide++; //Trigger the slideshowEnd callback if(vars.currentSlide == vars.totalSlides){ vars.currentSlide = 0; settings.slideshowEnd.call(this); } if(vars.currentSlide < 0) vars.currentSlide = (vars.totalSlides - 1); //Set vars.currentImage if($(kids[vars.currentSlide]).is('img')){ vars.currentImage = $(kids[vars.currentSlide]); } else { vars.currentImage = $(kids[vars.currentSlide]).find('img:first'); } //Set acitve links if(settings.controlNav){ $('.nivo-controlNav a', slider).removeClass('active'); $('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active'); } //Process caption if(vars.currentImage.attr('title') != ''){ var title = vars.currentImage.attr('title'); if(title.substr(0,1) == '#') title = $(title).html(); if($('.nivo-caption', slider).css('display') == 'block'){ $('.nivo-caption p', slider).fadeOut(settings.animSpeed, function(){ $(this).html(title); $(this).fadeIn(settings.animSpeed); }); } else { $('.nivo-caption p', slider).html(title); } $('.nivo-caption', slider).fadeIn(settings.animSpeed); } else { $('.nivo-caption', slider).fadeOut(settings.animSpeed); } //Set new slice backgrounds var i = 0; $('.nivo-slice', slider).each(function(){ var sliceWidth = Math.round(slider.width()/settings.slices); $(this).css({ height:'0px', opacity:'0', background: 'url('+ vars.currentImage.attr('src') +') no-repeat -'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px 0%' }); i++; }); if(settings.effect == 'random'){ var anims = new Array("sliceDownRight","sliceDownLeft","sliceUpRight","sliceUpLeft","sliceUpDown","sliceUpDownLeft","fold","fade"); vars.randAnim = anims[Math.floor(Math.random()*(anims.length + 1))]; if(vars.randAnim == undefined) vars.randAnim = 'fade'; } //Run random effect from specified set (eg: effect:'fold,fade') if(settings.effect.indexOf(',') != -1){ var anims = settings.effect.split(','); vars.randAnim = $.trim(anims[Math.floor(Math.random()*anims.length)]); } //Run effects vars.running = true; if(settings.effect == 'sliceDown' || settings.effect == 'sliceDownRight' || vars.randAnim == 'sliceDownRight' || settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft'){ var timeBuff = 0; var i = 0; var slices = $('.nivo-slice', slider); if(settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft') slices = $('.nivo-slice', slider)._reverse(); slices.each(function(){ var slice = $(this); slice.css('top','0px'); if(i == settings.slices-1){ setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; i++; }); } else if(settings.effect == 'sliceUp' || settings.effect == 'sliceUpRight' || vars.randAnim == 'sliceUpRight' || settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft'){ var timeBuff = 0; var i = 0; var slices = $('.nivo-slice', slider); if(settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft') slices = $('.nivo-slice', slider)._reverse(); slices.each(function(){ var slice = $(this); slice.css('bottom','0px'); if(i == settings.slices-1){ setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; i++; }); } else if(settings.effect == 'sliceUpDown' || settings.effect == 'sliceUpDownRight' || vars.randAnim == 'sliceUpDown' || settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft'){ var timeBuff = 0; var i = 0; var v = 0; var slices = $('.nivo-slice', slider); if(settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft') slices = $('.nivo-slice', slider)._reverse(); slices.each(function(){ var slice = $(this); if(i == 0){ slice.css('top','0px'); i++; } else { slice.css('bottom','0px'); i = 0; } if(v == settings.slices-1){ setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; v++; }); } else if(settings.effect == 'fold' || vars.randAnim == 'fold'){ var timeBuff = 0; var i = 0; $('.nivo-slice', slider).each(function(){ var slice = $(this); var origWidth = slice.width(); slice.css({ top:'0px', height:'100%', width:'0px' }); if(i == settings.slices-1){ setTimeout(function(){ slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; i++; }); } else if(settings.effect == 'fade' || vars.randAnim == 'fade'){ var i = 0; $('.nivo-slice', slider).each(function(){ $(this).css('height','100%'); if(i == settings.slices-1){ $(this).animate({ opacity:'1.0' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); }); } else { $(this).animate({ opacity:'1.0' }, (settings.animSpeed*2)); } i++; }); } } // For debugging var trace = function(msg){ if (this.console && typeof console.log != "undefined") console.log(msg); } // Start / Stop this.stop = function(){ if(!$(element).data('nivo:vars').stop){ $(element).data('nivo:vars').stop = true; trace('Stop Slider'); } } this.start = function(){ if($(element).data('nivo:vars').stop){ $(element).data('nivo:vars').stop = false; trace('Start Slider'); } } //Trigger the afterLoad callback settings.afterLoad.call(this); }; $.fn.nivoSlider = function(options) { return this.each(function(){ var element = $(this); // Return early if this element already has a plugin instance if (element.data('nivoslider')) return; // Pass options to plugin constructor var nivoslider = new NivoSlider(this, options); // Store plugin object in this element's data element.data('nivoslider', nivoslider); }); }; //Default settings $.fn.nivoSlider.defaults = { effect:'random', slices:15, animSpeed:500, pauseTime:3000, startSlide:0, directionNav:true, directionNavHide:true, controlNav:true, controlNavThumbs:false, controlNavThumbsFromRel:false, controlNavThumbsSearch:'.jpg', controlNavThumbsReplace:'_thumb.jpg', keyboardNav:true, pauseOnHover:true, manualAdvance:false, captionOpacity:0.8, beforeChange: function(){}, afterChange: function(){}, slideshowEnd: function(){}, lastSlide: function(){}, afterLoad: function(){} }; $.fn._reverse = [].reverse; })(jQuery);
JavaScript
/** * jQuery.ScrollTo * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Dual licensed under MIT and GPL. * Date: 5/25/2009 * * @projectDescription Easy element scrolling using jQuery. * http://flesler.blogspot.com/2007/10/jqueryscrollto.html * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7/8, Opera 9.5/6, Safari 3, Chrome 1 on WinXP. * * @author Ariel Flesler * @version 1.4.2 * * @id jQuery.scrollTo * @id jQuery.fn.scrollTo * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements. * The different options for target are: * - A number position (will be applied to all axes). * - A string position ('44', '100px', '+=90', etc ) will be applied to all axes * - A jQuery/DOM element ( logically, child of the element to scroll ) * - A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc ) * - A hash { top:x, left:y }, x and y can be any kind of number/string like above. * - A percentage of the container's dimension/s, for example: 50% to go to the middle. * - The string 'max' for go-to-end. * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead. * @param {Object,Function} settings Optional set of settings or the onAfter callback. * @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'. * @option {Number} duration The OVERALL length of the animation. * @option {String} easing The easing method for the animation. * @option {Boolean} margin If true, the margin of the target element will be deducted from the final position. * @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }. * @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes. * @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends. * @option {Function} onAfter Function to be called after the scrolling ends. * @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends. * @return {jQuery} Returns the same jQuery object, for chaining. * * @desc Scroll to a fixed position * @example $('div').scrollTo( 340 ); * * @desc Scroll relatively to the actual position * @example $('div').scrollTo( '+=340px', { axis:'y' } ); * * @dec Scroll using a selector (relative to the scrolled element) * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } ); * * @ Scroll to a DOM element (same for jQuery object) * @example var second_child = document.getElementById('container').firstChild.nextSibling; * $('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){ * alert('scrolled!!'); * }}); * * @desc Scroll on both axes, to different values * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } ); */ ;(function( $ ){ var $scrollTo = $.scrollTo = function( target, duration, settings ){ $(window).scrollTo( target, duration, settings ); }; $scrollTo.defaults = { axis:'xy', duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1 }; // Returns the element that needs to be animated to scroll the window. // Kept for backwards compatibility (specially for localScroll & serialScroll) $scrollTo.window = function( scope ){ return $(window)._scrollable(); }; // Hack, hack, hack :) // Returns the real elements to scroll (supports window/iframes, documents and regular nodes) $.fn._scrollable = function(){ return this.map(function(){ var elem = this, isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1; if( !isWin ) return elem; var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem; return $.browser.safari || doc.compatMode == 'BackCompat' ? doc.body : doc.documentElement; }); }; $.fn.scrollTo = function( target, duration, settings ){ if( typeof duration == 'object' ){ settings = duration; duration = 0; } if( typeof settings == 'function' ) settings = { onAfter:settings }; if( target == 'max' ) target = 9e9; settings = $.extend( {}, $scrollTo.defaults, settings ); // Speed is still recognized for backwards compatibility duration = duration || settings.speed || settings.duration; // Make sure the settings are given right settings.queue = settings.queue && settings.axis.length > 1; if( settings.queue ) // Let's keep the overall duration duration /= 2; settings.offset = both( settings.offset ); settings.over = both( settings.over ); return this._scrollable().each(function(){ var elem = this, $elem = $(elem), targ = target, toff, attr = {}, win = $elem.is('html,body'); switch( typeof targ ){ // A number will pass the regex case 'number': case 'string': if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){ targ = both( targ ); // We are done break; } // Relative selector, no break! targ = $(targ,this); case 'object': // DOMElement / jQuery if( targ.is || targ.style ) // Get the real position of the target toff = (targ = $(targ)).offset(); } $.each( settings.axis.split(''), function( i, axis ){ var Pos = axis == 'x' ? 'Left' : 'Top', pos = Pos.toLowerCase(), key = 'scroll' + Pos, old = elem[key], max = $scrollTo.max(elem, axis); if( toff ){// jQuery / DOMElement attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] ); // If it's a dom element, reduce the margin if( settings.margin ){ attr[key] -= parseInt(targ.css('margin'+Pos)) || 0; attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0; } attr[key] += settings.offset[pos] || 0; if( settings.over[pos] ) // Scroll to a fraction of its width/height attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos]; }else{ var val = targ[pos]; // Handle percentage values attr[key] = val.slice && val.slice(-1) == '%' ? parseFloat(val) / 100 * max : val; } // Number or 'number' if( /^\d+$/.test(attr[key]) ) // Check the limits attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max ); // Queueing axes if( !i && settings.queue ){ // Don't waste time animating, if there's no need. if( old != attr[key] ) // Intermediate animation animate( settings.onAfterFirst ); // Don't animate this axis again in the next iteration. delete attr[key]; } }); animate( settings.onAfter ); function animate( callback ){ $elem.animate( attr, duration, settings.easing, callback && function(){ callback.call(this, target, settings); }); }; }).end(); }; // Max scrolling position, works on quirks mode // It only fails (not too badly) on IE, quirks mode. $scrollTo.max = function( elem, axis ){ var Dim = axis == 'x' ? 'Width' : 'Height', scroll = 'scroll'+Dim; if( !$(elem).is('html,body') ) return elem[scroll] - $(elem)[Dim.toLowerCase()](); var size = 'client' + Dim, html = elem.ownerDocument.documentElement, body = elem.ownerDocument.body; return Math.max( html[scroll], body[scroll] ) - Math.min( html[size] , body[size] ); }; function both( val ){ return typeof val == 'object' ? val : { top:val, left:val }; }; })( jQuery );
JavaScript
$(document).ready function() { $("#foo4").carouFredSel({ circular : false, infinite : true, auto: {pauseDuration: 3000, delay: 750}, scroll: {fx: "fade"}, items: { pauseOnHover: true }, prev : { button : "#foo4_prev", key : "left", items : 4, easing : "easeInOutCubic", duration : 2500, pauseOnHover: true }, next : { button : "#foo4_next", key : "right", items : 4, easing : "easeInQuart", duration : 1500, pauseOnHover: true }, pagination : { container : "#foo4_pag", keys : true, easing : "easeOutBounce", duration : 3000, pauseOnHover: true } }); $('.preview-fade').each(function() { $(this).hover( function() { $(this).stop().animate({ opacity: 0.5 }, 400); }, function() { $(this).stop().animate({ opacity: 1.0 }, 400); }) }); }); $(document).ready(function() { //search toggle $("#search-toggle").click(function () { if ($("#adv-search-wrap").is(":hidden")) { $("#adv-search-wrap").fadeIn("normal"); } else { $("#adv-search-wrap").fadeOut("normal"); } return false; }); $('#adv-search-wrap').click(function(e) { e.stopPropagation(); }); $(document).click(function() { $('#adv-search-wrap').animate({ opacity: 'hide' }, 400); }); //search functions $("#adv-search-post").click(function () { $("#search-filter").val('post'); if ($("#adv-search-input").val() == 'search galleries...' || $("#adv-search-input").val() == '') { $("#adv-search-input").val('search posts...'); } $("#adv-search-post").addClass('active'); $("#adv-search-image").removeClass('active'); return false; }); $("#adv-search-image").click(function () { $("#search-filter").val('gallery'); if ($("#adv-search-input").val() == 'search posts...' || $("#adv-search-input").val() == '') { $("#adv-search-input").val('search gallery...'); } $("#adv-search-image").addClass('active'); $("#adv-search-post").removeClass('active'); return false; }); $("#adv-search-input").click(function () { $("#adv-search-input").val(''); }); }); $(document).ready function() { $('#social-01').tipsy({gravity: 'n'}); $('#social-02').tipsy({gravity: 'n'}); $('#social-03').tipsy({gravity: 'n'}); $('#social-04').tipsy({gravity: 'n'}); $('#social-05').tipsy({gravity: 'n'}); $('#social-06').tipsy({gravity: 'n'}); $('#logoff').tipsy({gravity: 'n'}); $('#tip-1').tipsy({gravity: 's'}); $('#tip-2').tipsy({gravity: 's'}); $('#tip-3').tipsy({gravity: 's'}); $('#tip-4').tipsy({gravity: 's'}); $('#tip-5').tipsy({gravity: 's'}); });
JavaScript
$(document).ready(function() { /// wrap inner content of each anchor with first layer and append background layer $("#BMenu li a").wrapInner( '<span class="out"></span>' ).append( '<span class="bg"></span>' ); // loop each anchor and add copy of text content $("#BMenu li a").each(function() { $( '<span class="over">' + $(this).text() + '</span>' ).appendTo( this ); }); $("#BMenu li a").hover(function() { // this function is fired when the mouse is moved over $(".out", this).stop().animate({'top': '28px'}, 250); // move down - hide $(".over", this).stop().animate({'top': '0px'}, 250); // move down - show $(".bg", this).stop().animate({'top': '0px'}, 120); // move down - show }, function() { // this function is fired when the mouse is moved off $(".out", this).stop().animate({'top': '0px'}, 250); // move up - show $(".over", this).stop().animate({'top': '-28px'}, 250); // move up - hide $(".bg", this).stop().animate({'top': '-28px'}, 120); // move up - hide }); }); $(document).ready(function(){ $('#fulldate').load('date.php', function() { }); }); $(function() { $(".tab_content").hide(); $("ul.tabs li:first").addClass("sel").show(); $(".tab_content:first").show(); $("ul.tabs li").click(function() { $("ul.tabs li").removeClass("sel"); $(this).addClass("sel"); $(".tab_content").hide(); var activeTab = $(this).find("a").attr("href"); $(activeTab).fadeIn('slow'); return false; }); });
JavaScript
//** Tab Content script v2.0- ? Dynamic Drive DHTML code library (http://www.dynamicdrive.com) //** Updated Oct 7th, 07 to version 2.0. Contains numerous improvements: // -Added Auto Mode: Script auto rotates the tabs based on an interval, until a tab is explicitly selected // -Ability to expand/contract arbitrary DIVs on the page as the tabbed content is expanded/ contracted // -Ability to dynamically select a tab either based on its position within its peers, or its ID attribute (give the target tab one 1st) // -Ability to set where the CSS classname "selected" get assigned- either to the target tab's link ("A"), or its parent container //** Updated Feb 18th, 08 to version 2.1: Adds a "tabinstance.cycleit(dir)" method to cycle forward or backward between tabs dynamically //** Updated April 8th, 08 to version 2.2: Adds support for expanding a tab using a URL parameter (ie: http://mysite.com/tabcontent.htm?tabinterfaceid=0) ////NO NEED TO EDIT BELOW//////////////////////// function ddtabcontent(tabinterfaceid){ this.tabinterfaceid=tabinterfaceid //ID of Tab Menu main container this.tabs=document.getElementById(tabinterfaceid).getElementsByTagName("a") //Get all tab links within container this.enabletabpersistence=true this.hottabspositions=[] //Array to store position of tabs that have a "rel" attr defined, relative to all tab links, within container this.currentTabIndex=0 //Index of currently selected hot tab (tab with sub content) within hottabspositions[] array this.subcontentids=[] //Array to store ids of the sub contents ("rel" attr values) this.revcontentids=[] //Array to store ids of arbitrary contents to expand/contact as well ("rev" attr values) this.selectedClassTarget="link" //keyword to indicate which target element to assign "selected" CSS class ("linkparent" or "link") } ddtabcontent.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 "" } ddtabcontent.setCookie=function(name, value){ document.cookie = name+"="+value+";path=/" //cookie value is domain wide (path=/) } ddtabcontent.prototype={ expandit:function(tabid_or_position){ //PUBLIC function to select a tab either by its ID or position(int) within its peers this.cancelautorun() //stop auto cycling of tabs (if running) var tabref="" try{ if (typeof tabid_or_position=="string" && document.getElementById(tabid_or_position).getAttribute("rel")) //if specified tab contains "rel" attr tabref=document.getElementById(tabid_or_position) else if (parseInt(tabid_or_position)!=NaN && this.tabs[tabid_or_position].getAttribute("rel")) //if specified tab contains "rel" attr tabref=this.tabs[tabid_or_position] } catch(err){alert("Invalid Tab ID or position entered!")} if (tabref!="") //if a valid tab is found based on function parameter this.expandtab(tabref) //expand this tab }, cycleit:function(dir, autorun){ //PUBLIC function to move foward or backwards through each hot tab (tabinstance.cycleit('foward/back') ) if (dir=="next"){ var currentTabIndex=(this.currentTabIndex<this.hottabspositions.length-1)? this.currentTabIndex+1 : 0 } else if (dir=="prev"){ var currentTabIndex=(this.currentTabIndex>0)? this.currentTabIndex-1 : this.hottabspositions.length-1 } if (typeof autorun=="undefined") //if cycleit() is being called by user, versus autorun() function this.cancelautorun() //stop auto cycling of tabs (if running) this.expandtab(this.tabs[this.hottabspositions[currentTabIndex]]) }, setpersist:function(bool){ //PUBLIC function to toggle persistence feature this.enabletabpersistence=bool }, setselectedClassTarget:function(objstr){ //PUBLIC function to set which target element to assign "selected" CSS class ("linkparent" or "link") this.selectedClassTarget=objstr || "link" }, getselectedClassTarget:function(tabref){ //Returns target element to assign "selected" CSS class to return (this.selectedClassTarget==("linkparent".toLowerCase()))? tabref.parentNode : tabref }, urlparamselect:function(tabinterfaceid){ var result=window.location.search.match(new RegExp(tabinterfaceid+"=(\\d+)", "i")) //check for "?tabinterfaceid=2" in URL return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index }, expandtab:function(tabref){ var subcontentid=tabref.getAttribute("rel") //Get id of subcontent to expand //Get "rev" attr as a string of IDs in the format ",john,george,trey,etc," to easily search through var associatedrevids=(tabref.getAttribute("rev"))? ","+tabref.getAttribute("rev").replace(/\s+/, "")+"," : "" this.expandsubcontent(subcontentid) this.expandrevcontent(associatedrevids) for (var i=0; i<this.tabs.length; i++){ //Loop through all tabs, and assign only the selected tab the CSS class "selected" this.getselectedClassTarget(this.tabs[i]).className=(this.tabs[i].getAttribute("rel")==subcontentid)? "selected" : "" } if (this.enabletabpersistence) //if persistence enabled, save selected tab position(int) relative to its peers ddtabcontent.setCookie(this.tabinterfaceid, tabref.tabposition) this.setcurrenttabindex(tabref.tabposition) //remember position of selected tab within hottabspositions[] array }, expandsubcontent:function(subcontentid){ for (var i=0; i<this.subcontentids.length; i++){ var subcontent=document.getElementById(this.subcontentids[i]) //cache current subcontent obj (in for loop) subcontent.style.display=(subcontent.id==subcontentid)? "block" : "none" //"show" or hide sub content based on matching id attr value } }, expandrevcontent:function(associatedrevids){ var allrevids=this.revcontentids for (var i=0; i<allrevids.length; i++){ //Loop through rev attributes for all tabs in this tab interface //if any values stored within associatedrevids matches one within allrevids, expand that DIV, otherwise, contract it document.getElementById(allrevids[i]).style.display=(associatedrevids.indexOf(","+allrevids[i]+",")!=-1)? "block" : "none" } }, setcurrenttabindex:function(tabposition){ //store current position of tab (within hottabspositions[] array) for (var i=0; i<this.hottabspositions.length; i++){ if (tabposition==this.hottabspositions[i]){ this.currentTabIndex=i break } } }, autorun:function(){ //function to auto cycle through and select tabs based on a set interval this.cycleit('next', true) }, cancelautorun:function(){ if (typeof this.autoruntimer!="undefined") clearInterval(this.autoruntimer) }, init:function(automodeperiod){ var persistedtab=ddtabcontent.getCookie(this.tabinterfaceid) //get position of persisted tab (applicable if persistence is enabled) var selectedtab=-1 //Currently selected tab index (-1 meaning none) var selectedtabfromurl=this.urlparamselect(this.tabinterfaceid) //returns null or index from: tabcontent.htm?tabinterfaceid=index this.automodeperiod=automodeperiod || 0 for (var i=0; i<this.tabs.length; i++){ this.tabs[i].tabposition=i //remember position of tab relative to its peers if (this.tabs[i].getAttribute("rel")){ var tabinstance=this this.hottabspositions[this.hottabspositions.length]=i //store position of "hot" tab ("rel" attr defined) relative to its peers this.subcontentids[this.subcontentids.length]=this.tabs[i].getAttribute("rel") //store id of sub content ("rel" attr value) this.tabs[i].onclick=function(){ tabinstance.expandtab(this) tabinstance.cancelautorun() //stop auto cycling of tabs (if running) return false } if (this.tabs[i].getAttribute("rev")){ //if "rev" attr defined, store each value within "rev" as an array element this.revcontentids=this.revcontentids.concat(this.tabs[i].getAttribute("rev").split(/\s*,\s*/)) } if (selectedtabfromurl==i || this.enabletabpersistence && selectedtab==-1 && parseInt(persistedtab)==i || !this.enabletabpersistence && selectedtab==-1 && this.getselectedClassTarget(this.tabs[i]).className=="selected"){ selectedtab=i //Selected tab index, if found } } } //END for loop if (selectedtab!=-1) //if a valid default selected tab index is found this.expandtab(this.tabs[selectedtab]) //expand selected tab (either from URL parameter, persistent feature, or class="selected" class) else //if no valid default selected index found this.expandtab(this.tabs[this.hottabspositions[0]]) //Just select first tab that contains a "rel" attr if (parseInt(this.automodeperiod)>500 && this.hottabspositions.length>1){ this.autoruntimer=setInterval(function(){tabinstance.autorun()}, this.automodeperiod) } } //END int() function } //END Prototype assignment
JavaScript
//Style Sheet Switcher version 1.1 Oct 10th, 2006 //Author: Dynamic Drive: http://www.dynamicdrive.com //Usage terms: http://www.dynamicdrive.com/notice.htm var manual_or_random="manual" //"manual" or "random" var randomsetting="3 days" //"eachtime", "sessiononly", or "x days (replace x with desired integer)". Only applicable if mode is random. //////No need to edit beyond here////////////// function getCookie(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 } function setCookie(name, value, days) { var expireDate = new Date() //set "expstring" to either future or past date, to set or delete cookie, respectively var expstring=(typeof days!="undefined")? expireDate.setDate(expireDate.getDate()+parseInt(days)) : expireDate.setDate(expireDate.getDate()-5) document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/"; } function deleteCookie(name){ setCookie(name, "moot") } function setStylesheet(title, randomize){ //Main stylesheet switcher function. Second parameter if defined causes a random alternate stylesheet (including none) to be enabled var i, cacheobj, altsheets=[""] for(i=0; (cacheobj=document.getElementsByTagName("link")[i]); i++) { if(cacheobj.getAttribute("rel").toLowerCase()=="alternate stylesheet" && cacheobj.getAttribute("title")) { //if this is an alternate stylesheet with title cacheobj.disabled = true altsheets.push(cacheobj) //store reference to alt stylesheets inside array if(cacheobj.getAttribute("title") == title) //enable alternate stylesheet with title that matches parameter cacheobj.disabled = false //enable chosen style sheet } } if (typeof randomize!="undefined"){ //if second paramter is defined, randomly enable an alt style sheet (includes non) var randomnumber=Math.floor(Math.random()*altsheets.length) altsheets[randomnumber].disabled=false } return (typeof randomize!="undefined" && altsheets[randomnumber]!="")? altsheets[randomnumber].getAttribute("title") : "" //if in "random" mode, return "title" of randomly enabled alt stylesheet } function chooseStyle(styletitle, days){ //Interface function to switch style sheets plus save "title" attr of selected stylesheet to cookie if (document.getElementById){ setStylesheet(styletitle) setCookie("mysheet", styletitle, days) } } function indicateSelected(element){ //Optional function that shows which style sheet is currently selected within group of radio buttons or select menu if (selectedtitle!=null && (element.type==undefined || element.type=="select-one")){ //if element is a radio button or select menu var element=(element.type=="select-one") ? element.options : element for (var i=0; i<element.length; i++){ if (element[i].value==selectedtitle){ //if match found between form element value and cookie value if (element[i].tagName=="OPTION") //if this is a select menu element[i].selected=true else //else if it's a radio button element[i].checked=true break } } } } if (manual_or_random=="manual"){ //IF MANUAL MODE var selectedtitle=getCookie("mysheet") if (document.getElementById && selectedtitle!=null) //load user chosen style sheet from cookie if there is one stored setStylesheet(selectedtitle) } else if (manual_or_random=="random"){ //IF AUTO RANDOM MODE if (randomsetting=="eachtime") setStylesheet("", "random") else if (randomsetting=="sessiononly"){ //if "sessiononly" setting if (getCookie("mysheet_s")==null) //if "mysheet_s" session cookie is empty document.cookie="mysheet_s="+setStylesheet("", "random")+"; path=/" //activate random alt stylesheet while remembering its "title" value else setStylesheet(getCookie("mysheet_s")) //just activate random alt stylesheet stored in cookie } else if (randomsetting.search(/^[1-9]+ days/i)!=-1){ //if "x days" setting if (getCookie("mysheet_r")==null || parseInt(getCookie("mysheet_r_days"))!=parseInt(randomsetting)){ //if "mysheet_r" cookie is empty or admin has changed number of days to persist in "x days" variable setCookie("mysheet_r", setStylesheet("", "random"), parseInt(randomsetting)) //activate random alt stylesheet while remembering its "title" value setCookie("mysheet_r_days", randomsetting, parseInt(randomsetting)) //Also remember the number of days to persist per the "x days" variable } else setStylesheet(getCookie("mysheet_r")) //just activate random alt stylesheet stored in cookie } }
JavaScript
//Style Sheet Switcher version 1.1 Oct 10th, 2006 //Author: Dynamic Drive: http://www.3zfaldmo3.com //Usage terms: http://www.dynamicdrive.com/notice.htm var manual_or_random="manual" //"manual" or "random" var randomsetting="3 days" //"eachtime", "sessiononly", or "x days (replace x with desired integer)". Only applicable if mode is random. //////No need to edit beyond here////////////// function getCookie(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 } function setCookie(name, value, days) { var expireDate = new Date() //set "expstring" to either future or past date, to set or delete cookie, respectively var expstring=(typeof days!="undefined")? expireDate.setDate(expireDate.getDate()+parseInt(days)) : expireDate.setDate(expireDate.getDate()-5) document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/"; } function deleteCookie(name){ setCookie(name, "moot") } function setStylesheet(title, randomize){ //Main stylesheet switcher function. Second parameter if defined causes a random alternate stylesheet (including none) to be enabled var i, cacheobj, altsheets=[""] for(i=0; (cacheobj=document.getElementsByTagName("link")[i]); i++) { if(cacheobj.getAttribute("rel").toLowerCase()=="alternate stylesheet" && cacheobj.getAttribute("title")) { //if this is an alternate stylesheet with title cacheobj.disabled = true altsheets.push(cacheobj) //store reference to alt stylesheets inside array if(cacheobj.getAttribute("title") == title) //enable alternate stylesheet with title that matches parameter cacheobj.disabled = false //enable chosen style sheet } } if (typeof randomize!="undefined"){ //if second paramter is defined, randomly enable an alt style sheet (includes non) var randomnumber=Math.floor(Math.random()*altsheets.length) altsheets[randomnumber].disabled=false } return (typeof randomize!="undefined" && altsheets[randomnumber]!="")? altsheets[randomnumber].getAttribute("title") : "" //if in "random" mode, return "title" of randomly enabled alt stylesheet } function chooseStyle(styletitle, days){ //Interface function to switch style sheets plus save "title" attr of selected stylesheet to cookie if (document.getElementById){ setStylesheet(styletitle) setCookie("mysheet", styletitle, days) } } function indicateSelected(element){ //Optional function that shows which style sheet is currently selected within group of radio buttons or select menu if (selectedtitle!=null && (element.type==undefined || element.type=="select-one")){ //if element is a radio button or select menu var element=(element.type=="select-one") ? element.options : element for (var i=0; i<element.length; i++){ if (element[i].value==selectedtitle){ //if match found between form element value and cookie value if (element[i].tagName=="OPTION") //if this is a select menu element[i].selected=true else //else if it's a radio button element[i].checked=true break } } } } if (manual_or_random=="manual"){ //IF MANUAL MODE var selectedtitle=getCookie("mysheet") if (document.getElementById && selectedtitle!=null) //load user chosen style sheet from cookie if there is one stored setStylesheet(selectedtitle) } else if (manual_or_random=="random"){ //IF AUTO RANDOM MODE if (randomsetting=="eachtime") setStylesheet("", "random") else if (randomsetting=="sessiononly"){ //if "sessiononly" setting if (getCookie("mysheet_s")==null) //if "mysheet_s" session cookie is empty document.cookie="mysheet_s="+setStylesheet("", "random")+"; path=/" //activate random alt stylesheet while remembering its "title" value else setStylesheet(getCookie("mysheet_s")) //just activate random alt stylesheet stored in cookie } else if (randomsetting.search(/^[1-9]+ days/i)!=-1){ //if "x days" setting if (getCookie("mysheet_r")==null || parseInt(getCookie("mysheet_r_days"))!=parseInt(randomsetting)){ //if "mysheet_r" cookie is empty or admin has changed number of days to persist in "x days" variable setCookie("mysheet_r", setStylesheet("", "random"), parseInt(randomsetting)) //activate random alt stylesheet while remembering its "title" value setCookie("mysheet_r_days", randomsetting, parseInt(randomsetting)) //Also remember the number of days to persist per the "x days" variable } else setStylesheet(getCookie("mysheet_r")) //just activate random alt stylesheet stored in cookie } }
JavaScript
/* * jQuery carouFredSel 5.5.0 * Demo's and documentation: * caroufredsel.frebsite.nl * * Copyright (c) 2012 Fred Heusschen * www.frebsite.nl * * Dual licensed under the MIT and GPL licenses. * http://en.wikipedia.org/wiki/MIT_License * http://en.wikipedia.org/wiki/GNU_General_Public_License */ (function($) { // LOCAL if ($.fn.carouFredSel) return; $.fn.carouFredSel = function(options, configs) { if (this.length == 0) { debug(true, 'No element found for "'+this.selector+'".'); return this; } if (this.length > 1) { return this.each(function() { $(this).carouFredSel(options, configs); }); } var $cfs = this, $tt0 = this[0]; if ($cfs.data('cfs_isCarousel')) { var starting_position = $cfs.triggerHandler('_cfs_currentPosition'); $cfs.trigger('_cfs_destroy', true); } else { var starting_position = false; } $cfs._cfs_init = function(o, setOrig, start) { o = go_getObject($tt0, o); // DEPRECATED if (o.debug) { conf.debug = o.debug; debug(conf, 'The "debug" option should be moved to the second configuration-object.'); } // /DEPRECATED var obs = ['items', 'scroll', 'auto', 'prev', 'next', 'pagination']; for (var a = 0, l = obs.length; a < l; a++) { o[obs[a]] = go_getObject($tt0, o[obs[a]]); } if (typeof o.scroll == 'number') { if (o.scroll <= 50) o.scroll = { 'items' : o.scroll }; else o.scroll = { 'duration' : o.scroll }; } else { if (typeof o.scroll == 'string') o.scroll = { 'easing' : o.scroll }; } if (typeof o.items == 'number') o.items = { 'visible' : o.items }; else if ( o.items == 'variable') o.items = { 'visible' : o.items, 'width' : o.items, 'height' : o.items }; if (typeof o.items != 'object') o.items = {}; if (setOrig) opts_orig = $.extend(true, {}, $.fn.carouFredSel.defaults, o); opts = $.extend(true, {}, $.fn.carouFredSel.defaults, o); if (typeof opts.items.visibleConf != 'object') opts.items.visibleConf = {}; if (opts.items.start == 0 && typeof start == 'number') { opts.items.start = start; } crsl.upDateOnWindowResize = (opts.responsive); crsl.direction = (opts.direction == 'up' || opts.direction == 'left') ? 'next' : 'prev'; var dims = [ ['width' , 'innerWidth' , 'outerWidth' , 'height' , 'innerHeight' , 'outerHeight' , 'left', 'top' , 'marginRight' , 0, 1, 2, 3], ['height' , 'innerHeight' , 'outerHeight' , 'width' , 'innerWidth' , 'outerWidth' , 'top' , 'left', 'marginBottom', 3, 2, 1, 0] ]; var dn = dims[0].length, dx = (opts.direction == 'right' || opts.direction == 'left') ? 0 : 1; opts.d = {}; for (var d = 0; d < dn; d++) { opts.d[dims[0][d]] = dims[dx][d]; } var all_itm = $cfs.children(); // check visible items switch (typeof opts.items.visible) { // min and max visible items case 'object': opts.items.visibleConf.min = opts.items.visible.min; opts.items.visibleConf.max = opts.items.visible.max; opts.items.visible = false; break; case 'string': // variable visible items if (opts.items.visible == 'variable') { opts.items.visibleConf.variable = true; // adjust string visible items } else { opts.items.visibleConf.adjust = opts.items.visible; } opts.items.visible = false; break; // function visible items case 'function': opts.items.visibleConf.adjust = opts.items.visible; opts.items.visible = false; break; } // set items filter if (typeof opts.items.filter == 'undefined') { opts.items.filter = (all_itm.filter(':hidden').length > 0) ? ':visible' : '*'; } // primary size set to auto -> measure largest size and set it if (opts[opts.d['width']] == 'auto') { opts[opts.d['width']] = ms_getTrueLargestSize(all_itm, opts, 'outerWidth'); } // primary size percentage if (ms_isPercentage(opts[opts.d['width']]) && !opts.responsive) { opts[opts.d['width']] = ms_getPercentage(ms_getTrueInnerSize($wrp.parent(), opts, 'innerWidth'), opts[opts.d['width']]); crsl.upDateOnWindowResize = true; } // secondary size set to auto -> measure largest size and set it if (opts[opts.d['height']] == 'auto') { opts[opts.d['height']] = ms_getTrueLargestSize(all_itm, opts, 'outerHeight'); } // primary item-size not set if (!opts.items[opts.d['width']]) { // responsive carousel -> set to largest if (opts.responsive) { debug(true, 'Set a '+opts.d['width']+' for the items!'); opts.items[opts.d['width']] = ms_getTrueLargestSize(all_itm, opts, 'outerWidth'); // non-responsive -> measure it or set to "variable" } else { opts.items[opts.d['width']] = (ms_hasVariableSizes(all_itm, opts, 'outerWidth')) ? 'variable' : all_itm[opts.d['outerWidth']](true); } } // secondary item-size not set -> measure it or set to "variable" if (!opts.items[opts.d['height']]) { opts.items[opts.d['height']] = (ms_hasVariableSizes(all_itm, opts, 'outerHeight')) ? 'variable' : all_itm[opts.d['outerHeight']](true); } // secondary size not set -> set to secondary item-size if (!opts[opts.d['height']]) { opts[opts.d['height']] = opts.items[opts.d['height']]; } // visible-items not set if (!opts.items.visible && !opts.responsive) { // primary item-size variable -> set visible items variable if (opts.items[opts.d['width']] == 'variable') { opts.items.visibleConf.variable = true; } if (!opts.items.visibleConf.variable) { // primary size is number -> calculate visible-items if (typeof opts[opts.d['width']] == 'number') { opts.items.visible = Math.floor(opts[opts.d['width']] / opts.items[opts.d['width']]); } else { // measure and calculate primary size and visible-items var maxS = ms_getTrueInnerSize($wrp.parent(), opts, 'innerWidth'); opts.items.visible = Math.floor(maxS / opts.items[opts.d['width']]); opts[opts.d['width']] = opts.items.visible * opts.items[opts.d['width']]; if (!opts.items.visibleConf.adjust) opts.align = false; } if (opts.items.visible == 'Infinity' || opts.items.visible < 1) { debug(true, 'Not a valid number of visible items: Set to "variable".'); opts.items.visibleConf.variable = true; } } } // primary size not set -> calculate it or set to "variable" if (!opts[opts.d['width']]) { opts[opts.d['width']] = 'variable'; if (!opts.responsive && opts.items.filter == '*' && !opts.items.visibleConf.variable && opts.items[opts.d['width']] != 'variable') { opts[opts.d['width']] = opts.items.visible * opts.items[opts.d['width']]; opts.align = false; } } // variable primary item-sizes with variabe visible-items if (opts.items.visibleConf.variable) { opts.maxDimention = (opts[opts.d['width']] == 'variable') ? ms_getTrueInnerSize($wrp.parent(), opts, 'innerWidth') : opts[opts.d['width']]; if (opts.align === false) { opts[opts.d['width']] = 'variable'; } opts.items.visible = gn_getVisibleItemsNext(all_itm, opts, 0); // set visible items by filter } else if (opts.items.filter != '*') { opts.items.visibleConf.org = opts.items.visible; opts.items.visible = gn_getVisibleItemsNextFilter(all_itm, opts, 0); } // align not set -> set to center if primary size is number if (typeof opts.align == 'undefined') { opts.align = (opts[opts.d['width']] == 'variable') ? false : 'center'; } opts.items.visible = cf_getItemsAdjust(opts.items.visible, opts, opts.items.visibleConf.adjust, $tt0); opts.items.visibleConf.old = opts.items.visible; opts.usePadding = false; if (opts.responsive) { if (!opts.items.visibleConf.min) opts.items.visibleConf.min = opts.items.visible; if (!opts.items.visibleConf.max) opts.items.visibleConf.max = opts.items.visible; opts.align = false; opts.padding = [0, 0, 0, 0]; var isVisible = $wrp.is(':visible'); if (isVisible) $wrp.hide(); var fullS = ms_getPercentage(ms_getTrueInnerSize($wrp.parent(), opts, 'innerWidth'), opts[opts.d['width']]); if (typeof opts[opts.d['width']] == 'number' && fullS < opts[opts.d['width']]) { fullS = opts[opts.d['width']]; } if (isVisible) $wrp.show(); var visb = cf_getItemAdjustMinMax(Math.ceil(fullS / opts.items[opts.d['width']]), opts.items.visibleConf); if (visb > all_itm.length) { visb = all_itm.length; } var newS = Math.floor(fullS/visb), seco = opts[opts.d['height']], secp = ms_isPercentage(seco); all_itm.each(function() { var $t = $(this), nw = newS - ms_getPaddingBorderMargin($t, opts, 'Width'); $t[opts.d['width']](nw); if (secp) { $t[opts.d['height']](ms_getPercentage(nw, seco)); } }); opts.items.visible = visb; opts.items[opts.d['width']] = newS; opts[opts.d['width']] = visb * newS; } else { opts.padding = cf_getPadding(opts.padding); if (opts.align == 'top') opts.align = 'left'; if (opts.align == 'bottom') opts.align = 'right'; switch (opts.align) { // align: center, left or right case 'center': case 'left': case 'right': if (opts[opts.d['width']] != 'variable') { var p = cf_getAlignPadding(gi_getCurrentItems(all_itm, opts), opts); opts.usePadding = true; opts.padding[opts.d[1]] = p[1]; opts.padding[opts.d[3]] = p[0]; } break; // padding default: opts.align = false; opts.usePadding = ( opts.padding[0] == 0 && opts.padding[1] == 0 && opts.padding[2] == 0 && opts.padding[3] == 0 ) ? false : true; break; } } if (typeof opts.cookie == 'boolean' && opts.cookie) opts.cookie = 'caroufredsel_cookie_'+$cfs.attr('id'); if (typeof opts.items.minimum != 'number') opts.items.minimum = opts.items.visible; if (typeof opts.scroll.duration != 'number') opts.scroll.duration = 500; if (typeof opts.scroll.items == 'undefined') opts.scroll.items = (opts.items.visibleConf.variable || opts.items.filter != '*') ? 'visible' : opts.items.visible; opts.auto = go_getNaviObject($tt0, opts.auto, 'auto'); opts.prev = go_getNaviObject($tt0, opts.prev); opts.next = go_getNaviObject($tt0, opts.next); opts.pagination = go_getNaviObject($tt0, opts.pagination, 'pagination'); opts.auto = $.extend(true, {}, opts.scroll, opts.auto); opts.prev = $.extend(true, {}, opts.scroll, opts.prev); opts.next = $.extend(true, {}, opts.scroll, opts.next); opts.pagination = $.extend(true, {}, opts.scroll, opts.pagination); if (typeof opts.pagination.keys != 'boolean') opts.pagination.keys = false; if (typeof opts.pagination.anchorBuilder != 'function' && opts.pagination.anchorBuilder !== false) opts.pagination.anchorBuilder = $.fn.carouFredSel.pageAnchorBuilder; if (typeof opts.auto.play != 'boolean') opts.auto.play = true; if (typeof opts.auto.delay != 'number') opts.auto.delay = 0; if (typeof opts.auto.pauseOnEvent == 'undefined') opts.auto.pauseOnEvent = true; if (typeof opts.auto.pauseOnResize != 'boolean') opts.auto.pauseOnResize = true; if (typeof opts.auto.pauseDuration != 'number') opts.auto.pauseDuration = (opts.auto.duration < 10) ? 2500 : opts.auto.duration * 5; if (opts.synchronise) { opts.synchronise = cf_getSynchArr(opts.synchronise); } if (conf.debug) { debug(conf, 'Carousel width: '+opts.width); debug(conf, 'Carousel height: '+opts.height); if (opts.maxDimention) debug(conf, 'Available '+opts.d['width']+': '+opts.maxDimention); debug(conf, 'Item widths: '+opts.items.width); debug(conf, 'Item heights: '+opts.items.height); debug(conf, 'Number of items visible: '+opts.items.visible); if (opts.auto.play) debug(conf, 'Number of items scrolled automatically: '+opts.auto.items); if (opts.prev.button) debug(conf, 'Number of items scrolled backward: '+opts.prev.items); if (opts.next.button) debug(conf, 'Number of items scrolled forward: '+opts.next.items); } }; // /init $cfs._cfs_build = function() { $cfs.data('cfs_isCarousel', true); var orgCSS = { 'textAlign' : $cfs.css('textAlign'), 'float' : $cfs.css('float'), 'position' : $cfs.css('position'), 'top' : $cfs.css('top'), 'right' : $cfs.css('right'), 'bottom' : $cfs.css('bottom'), 'left' : $cfs.css('left'), 'width' : $cfs.css('width'), 'height' : $cfs.css('height'), 'marginTop' : $cfs.css('marginTop'), 'marginRight' : $cfs.css('marginRight'), 'marginBottom' : $cfs.css('marginBottom'), 'marginLeft' : $cfs.css('marginLeft') }; switch (orgCSS.position) { case 'absolute': var newPosition = 'absolute'; break; case 'fixed': var newPosition = 'fixed'; break; default: var newPosition = 'relative'; } $wrp.css(orgCSS).css({ 'overflow' : 'hidden', 'position' : newPosition }); $cfs.data('cfs_origCss', orgCSS).css({ 'textAlign' : 'left', 'float' : 'none', 'position' : 'absolute', 'top' : 0, 'left' : 0, 'marginTop' : 0, 'marginRight' : 0, 'marginBottom' : 0, 'marginLeft' : 0 }); if (opts.usePadding) { $cfs.children().each(function() { var m = parseInt($(this).css(opts.d['marginRight'])); if (isNaN(m)) m = 0; $(this).data('cfs_origCssMargin', m); }); } }; // /build $cfs._cfs_bind_events = function() { $cfs._cfs_unbind_events(); // stop event $cfs.bind(cf_e('stop', conf), function(e, imm) { e.stopPropagation(); // button if (!crsl.isStopped) { if (opts.auto.button) { opts.auto.button.addClass(cf_c('stopped', conf)); } } // set stopped crsl.isStopped = true; if (opts.auto.play) { opts.auto.play = false; $cfs.trigger(cf_e('pause', conf), imm); } return true; }); // finish event $cfs.bind(cf_e('finish', conf), function(e) { e.stopPropagation(); if (crsl.isScrolling) { sc_stopScroll(scrl); } return true; }); // pause event $cfs.bind(cf_e('pause', conf), function(e, imm, res) { e.stopPropagation(); tmrs = sc_clearTimers(tmrs); // immediately pause if (imm && crsl.isScrolling) { scrl.isStopped = true; var nst = getTime() - scrl.startTime; scrl.duration -= nst; if (scrl.pre) scrl.pre.duration -= nst; if (scrl.post) scrl.post.duration -= nst; sc_stopScroll(scrl, false); } // update remaining pause-time if (!crsl.isPaused && !crsl.isScrolling) { if (res) tmrs.timePassed += getTime() - tmrs.startTime; } // button if (!crsl.isPaused) { if (opts.auto.button) { opts.auto.button.addClass(cf_c('paused', conf)); } } // set paused crsl.isPaused = true; // pause pause callback if (opts.auto.onPausePause) { var dur1 = opts.auto.pauseDuration - tmrs.timePassed, perc = 100 - Math.ceil( dur1 * 100 / opts.auto.pauseDuration ); opts.auto.onPausePause.call($tt0, perc, dur1); } return true; }); // play event $cfs.bind(cf_e('play', conf), function(e, dir, del, res) { e.stopPropagation(); tmrs = sc_clearTimers(tmrs); // sort params var v = [dir, del, res], t = ['string', 'number', 'boolean'], a = cf_sortParams(v, t); var dir = a[0], del = a[1], res = a[2]; if (dir != 'prev' && dir != 'next') dir = crsl.direction; if (typeof del != 'number') del = 0; if (typeof res != 'boolean') res = false; // stopped? if (res) { crsl.isStopped = false; opts.auto.play = true; } if (!opts.auto.play) { e.stopImmediatePropagation(); return debug(conf, 'Carousel stopped: Not scrolling.'); } // button if (crsl.isPaused) { if (opts.auto.button) { opts.auto.button.removeClass(cf_c('stopped', conf)); opts.auto.button.removeClass(cf_c('paused', conf)); } } // set playing crsl.isPaused = false; tmrs.startTime = getTime(); // timeout the scrolling var dur1 = opts.auto.pauseDuration + del; dur2 = dur1 - tmrs.timePassed; perc = 100 - Math.ceil(dur2 * 100 / dur1); tmrs.auto = setTimeout(function() { if (opts.auto.onPauseEnd) { opts.auto.onPauseEnd.call($tt0, perc, dur2); } if (crsl.isScrolling) { $cfs.trigger(cf_e('play', conf), dir); } else { $cfs.trigger(cf_e(dir, conf), opts.auto); } }, dur2); // pause start callback if (opts.auto.onPauseStart) { opts.auto.onPauseStart.call($tt0, perc, dur2); } return true; }); // resume event $cfs.bind(cf_e('resume', conf), function(e) { e.stopPropagation(); if (scrl.isStopped) { scrl.isStopped = false; crsl.isPaused = false; crsl.isScrolling = true; scrl.startTime = getTime(); sc_startScroll(scrl); } else { $cfs.trigger(cf_e('play', conf)); } return true; }); // prev + next events $cfs.bind(cf_e('prev', conf)+' '+cf_e('next', conf), function(e, obj, num, clb) { e.stopPropagation(); // stopped or hidden carousel, don't scroll, don't queue if (crsl.isStopped || $cfs.is(':hidden')) { e.stopImmediatePropagation(); return debug(conf, 'Carousel stopped or hidden: Not scrolling.'); } // not enough items if (opts.items.minimum >= itms.total) { e.stopImmediatePropagation(); return debug(conf, 'Not enough items ('+itms.total+', '+opts.items.minimum+' needed): Not scrolling.'); } // get config var v = [obj, num, clb], t = ['object', 'number/string', 'function'], a = cf_sortParams(v, t); var obj = a[0], num = a[1], clb = a[2]; var eType = e.type.substr(conf.events.prefix.length); if (typeof obj != 'object' || obj == null) obj = opts[eType]; if (typeof clb == 'function') obj.onAfter = clb; if (typeof num != 'number') { if (opts.items.filter != '*') { num = 'visible'; } else { var arr = [num, obj.items, opts[eType].items]; for (var a = 0, l = arr.length; a < l; a++) { if (typeof arr[a] == 'number' || arr[a] == 'page' || arr[a] == 'visible') { num = arr[a]; break; } } } switch(num) { case 'page': e.stopImmediatePropagation(); return $cfs.triggerHandler(eType+'Page', [obj, clb]); break; case 'visible': if (!opts.items.visibleConf.variable && opts.items.filter == '*') { num = opts.items.visible; } break; } } // resume animation, add current to queue if (scrl.isStopped) { $cfs.trigger(cf_e('resume', conf)); $cfs.trigger(cf_e('queue', conf), [eType, [obj, num, clb]]); e.stopImmediatePropagation(); return debug(conf, 'Carousel resumed scrolling.'); } // queue if scrolling if (obj.duration > 0) { if (crsl.isScrolling) { if (obj.queue) $cfs.trigger(cf_e('queue', conf), [eType, [obj, num, clb]]); e.stopImmediatePropagation(); return debug(conf, 'Carousel currently scrolling.'); } } // test conditions callback if (obj.conditions && !obj.conditions.call($tt0)) { e.stopImmediatePropagation(); return debug(conf, 'Callback "conditions" returned false.'); } tmrs.timePassed = 0; $cfs.trigger('_cfs_slide_'+eType, [obj, num]); // synchronise if (opts.synchronise) { var s = opts.synchronise, c = [obj, num]; for (var j = 0, l = s.length; j < l; j++) { var d = eType; if (!s[j][1]) c[0] = s[j][0].triggerHandler('_cfs_configuration', eType); if (!s[j][2]) d = (d == 'prev') ? 'next' : 'prev'; c[1] = num + s[j][3]; s[j][0].trigger('_cfs_slide_'+d, c); } } return true; }); // prev event, accessible from outside $cfs.bind(cf_e('_cfs_slide_prev', conf, false), function(e, sO, nI) { e.stopPropagation(); var a_itm = $cfs.children(); // non-circular at start, scroll to end if (!opts.circular) { if (itms.first == 0) { if (opts.infinite) { $cfs.trigger(cf_e('next', conf), itms.total-1); } return e.stopImmediatePropagation(); } } if (opts.usePadding) sz_resetMargin(a_itm, opts); // find number of items to scroll if (typeof nI != 'number') { if (opts.items.visibleConf.variable) { nI = gn_getVisibleItemsPrev(a_itm, opts, itms.total-1); } else if (opts.items.filter != '*') { var xI = (typeof sO.items == 'number') ? sO.items : gn_getVisibleOrg($cfs, opts); nI = gn_getScrollItemsPrevFilter(a_itm, opts, itms.total-1, xI); } else { nI = opts.items.visible; } nI = cf_getAdjust(nI, opts, sO.items, $tt0); } // prevent non-circular from scrolling to far if (!opts.circular) { if (itms.total - nI < itms.first) { nI = itms.total - itms.first; } } // set new number of visible items opts.items.visibleConf.old = opts.items.visible; if (opts.items.visibleConf.variable) { var vI = gn_getVisibleItemsNext(a_itm, opts, itms.total-nI); if (opts.items.visible+nI <= vI && nI < itms.total) { nI++; vI = gn_getVisibleItemsNext(a_itm, opts, itms.total-nI); } opts.items.visible = cf_getItemsAdjust(vI, opts, opts.items.visibleConf.adjust, $tt0); } else if (opts.items.filter != '*') { var vI = gn_getVisibleItemsNextFilter(a_itm, opts, itms.total-nI); opts.items.visible = cf_getItemsAdjust(vI, opts, opts.items.visibleConf.adjust, $tt0); } if (opts.usePadding) sz_resetMargin(a_itm, opts, true); // scroll 0, don't scroll if (nI == 0) { e.stopImmediatePropagation(); return debug(conf, '0 items to scroll: Not scrolling.'); } debug(conf, 'Scrolling '+nI+' items backward.'); // save new config itms.first += nI; while (itms.first >= itms.total) { itms.first -= itms.total; } // non-circular callback if (!opts.circular) { if (itms.first == 0 && sO.onEnd) sO.onEnd.call($tt0); if (!opts.infinite) nv_enableNavi(opts, itms.first, conf); } // rearrange items $cfs.children().slice(itms.total-nI, itms.total).prependTo($cfs); if (itms.total < opts.items.visible + nI) { $cfs.children().slice(0, (opts.items.visible+nI)-itms.total).clone(true).appendTo($cfs); } // the needed items var a_itm = $cfs.children(), c_old = gi_getOldItemsPrev(a_itm, opts, nI), c_new = gi_getNewItemsPrev(a_itm, opts), l_cur = a_itm.eq(nI-1), l_old = c_old.last(), l_new = c_new.last(); if (opts.usePadding) sz_resetMargin(a_itm, opts); if (opts.align) { var p = cf_getAlignPadding(c_new, opts), pL = p[0], pR = p[1]; } else { var pL = 0, pR = 0; } var oL = (pL < 0) ? opts.padding[opts.d[3]] : 0; // hide items for fx directscroll if (sO.fx == 'directscroll' && opts.items.visible < nI) { var hiddenitems = a_itm.slice(opts.items.visibleConf.old, nI), orgW = opts.items[opts.d['width']]; hiddenitems.each(function() { var hi = $(this); hi.data('isHidden', hi.is(':hidden')).hide(); }); opts.items[opts.d['width']] = 'variable'; } else { var hiddenitems = false; } // save new sizes var i_siz = ms_getTotalSize(a_itm.slice(0, nI), opts, 'width'), w_siz = cf_mapWrapperSizes(ms_getSizes(c_new, opts, true), opts, !opts.usePadding); if (hiddenitems) opts.items[opts.d['width']] = orgW; if (opts.usePadding) { sz_resetMargin(a_itm, opts, true); if (pR >= 0) { sz_resetMargin(l_old, opts, opts.padding[opts.d[1]]); } sz_resetMargin(l_cur, opts, opts.padding[opts.d[3]]); } if (opts.align) { opts.padding[opts.d[1]] = pR; opts.padding[opts.d[3]] = pL; } // animation configuration var a_cfs = {}, a_dur = sO.duration; if (sO.fx == 'none') a_dur = 0; else if (a_dur == 'auto') a_dur = opts.scroll.duration / opts.scroll.items * nI; else if (a_dur <= 0) a_dur = 0; else if (a_dur < 10) a_dur = i_siz / a_dur; scrl = sc_setScroll(a_dur, sO.easing); // animate wrapper if (opts[opts.d['width']] == 'variable' || opts[opts.d['height']] == 'variable') { scrl.anims.push([$wrp, w_siz]); } // animate items if (opts.usePadding) { var new_m = opts.padding[opts.d[3]]; if (l_new.not(l_cur).length) { var a_cur = {}; a_cur[opts.d['marginRight']] = l_cur.data('cfs_origCssMargin'); if (pL < 0) l_cur.css(a_cur); else scrl.anims.push([l_cur, a_cur]); } if (l_new.not(l_old).length) { var a_old = {}; a_old[opts.d['marginRight']] = l_old.data('cfs_origCssMargin'); scrl.anims.push([l_old, a_old]); } if (pR >= 0) { var a_new = {}; a_new[opts.d['marginRight']] = l_new.data('cfs_origCssMargin') + opts.padding[opts.d[1]]; scrl.anims.push([l_new, a_new]); } } else { var new_m = 0; } // animate carousel a_cfs[opts.d['left']] = new_m; // onBefore callback var args = [c_old, c_new, w_siz, a_dur]; if (sO.onBefore) sO.onBefore.apply($tt0, args); clbk.onBefore = sc_callCallbacks(clbk.onBefore, $tt0, args); // ALTERNATIVE EFFECTS // extra animation arrays switch(sO.fx) { case 'fade': case 'crossfade': case 'cover': case 'uncover': scrl.pre = sc_setScroll(scrl.duration, scrl.easing); scrl.post = sc_setScroll(scrl.duration, scrl.easing); scrl.duration = 0; break; } // create copy switch(sO.fx) { case 'crossfade': case 'cover': case 'uncover': var $cf2 = $cfs.clone().appendTo($wrp); break; } switch(sO.fx) { case 'uncover': $cf2.children().slice(0, nI).remove(); case 'crossfade': case 'cover': $cf2.children().slice(opts.items.visible).remove(); break; } // animations switch(sO.fx) { case 'fade': scrl.pre.anims.push([$cfs, { 'opacity': 0 }]); break; case 'crossfade': $cf2.css({ 'opacity': 0 }); scrl.pre.anims.push([$cfs, { 'width': '+=0' }, function() { $cf2.remove(); }]); scrl.post.anims.push([$cf2, { 'opacity': 1 }]); break; case 'cover': scrl = fx_cover(scrl, $cfs, $cf2, opts, true); break; case 'uncover': scrl = fx_uncover(scrl, $cfs, $cf2, opts, true, nI); break; } // /ALTERNATIVE EFFECTS // complete callback var a_complete = function() { var overFill = opts.items.visible+nI-itms.total; if (overFill > 0) { $cfs.children().slice(itms.total).remove(); c_old = $cfs.children().slice(itms.total-(nI-overFill)).get().concat( $cfs.children().slice(0, overFill).get() ); } if (hiddenitems) { hiddenitems.each(function() { var hi = $(this); if (!hi.data('isHidden')) hi.show(); }); } if (opts.usePadding) { var l_itm = $cfs.children().eq(opts.items.visible+nI-1); l_itm.css(opts.d['marginRight'], l_itm.data('cfs_origCssMargin')); } scrl.anims = []; if (scrl.pre) scrl.pre = sc_setScroll(scrl.orgDuration, scrl.easing); var fn = function() { switch(sO.fx) { case 'fade': case 'crossfade': $cfs.css('filter', ''); break; } scrl.post = sc_setScroll(0, null); crsl.isScrolling = false; var args = [c_old, c_new, w_siz]; if (sO.onAfter) sO.onAfter.apply($tt0, args); clbk.onAfter = sc_callCallbacks(clbk.onAfter, $tt0, args); if (queu.length) { $cfs.trigger(cf_e(queu[0][0], conf), queu[0][1]); queu.shift(); } if (!crsl.isPaused) $cfs.trigger(cf_e('play', conf)); }; switch(sO.fx) { case 'fade': scrl.pre.anims.push([$cfs, { 'opacity': 1 }, fn]); sc_startScroll(scrl.pre); break; case 'uncover': scrl.pre.anims.push([$cfs, { 'width': '+=0' }, fn]); sc_startScroll(scrl.pre); break; default: fn(); break; } }; scrl.anims.push([$cfs, a_cfs, a_complete]); crsl.isScrolling = true; $cfs.css(opts.d['left'], -(i_siz-oL)); tmrs = sc_clearTimers(tmrs); sc_startScroll(scrl); cf_setCookie(opts.cookie, $cfs.triggerHandler(cf_e('currentPosition', conf))); $cfs.trigger(cf_e('updatePageStatus', conf), [false, w_siz]); return true; }); // next event, accessible from outside $cfs.bind(cf_e('_cfs_slide_next', conf, false), function(e, sO, nI) { e.stopPropagation(); var a_itm = $cfs.children(); // non-circular at end, scroll to start if (!opts.circular) { if (itms.first == opts.items.visible) { if (opts.infinite) { $cfs.trigger(cf_e('prev', conf), itms.total-1); } return e.stopImmediatePropagation(); } } if (opts.usePadding) sz_resetMargin(a_itm, opts); // find number of items to scroll if (typeof nI != 'number') { if (opts.items.filter != '*') { var xI = (typeof sO.items == 'number') ? sO.items : gn_getVisibleOrg($cfs, opts); nI = gn_getScrollItemsNextFilter(a_itm, opts, 0, xI); } else { nI = opts.items.visible; } nI = cf_getAdjust(nI, opts, sO.items, $tt0); } var lastItemNr = (itms.first == 0) ? itms.total : itms.first; // prevent non-circular from scrolling to far if (!opts.circular) { if (opts.items.visibleConf.variable) { var vI = gn_getVisibleItemsNext(a_itm, opts, nI), xI = gn_getVisibleItemsPrev(a_itm, opts, lastItemNr-1); } else { var vI = opts.items.visible, xI = opts.items.visible; } if (nI + vI > lastItemNr) { nI = lastItemNr - xI; } } // set new number of visible items opts.items.visibleConf.old = opts.items.visible; if (opts.items.visibleConf.variable) { var vI = gn_getVisibleItemsNextTestCircular(a_itm, opts, nI, lastItemNr); while (opts.items.visible-nI >= vI && nI < itms.total) { nI++; vI = gn_getVisibleItemsNextTestCircular(a_itm, opts, nI, lastItemNr); } opts.items.visible = cf_getItemsAdjust(vI, opts, opts.items.visibleConf.adjust, $tt0); } else if (opts.items.filter != '*') { var vI = gn_getVisibleItemsNextFilter(a_itm, opts, nI); opts.items.visible = cf_getItemsAdjust(vI, opts, opts.items.visibleConf.adjust, $tt0); } if (opts.usePadding) sz_resetMargin(a_itm, opts, true); // scroll 0, don't scroll if (nI == 0) { e.stopImmediatePropagation(); return debug(conf, '0 items to scroll: Not scrolling.'); } debug(conf, 'Scrolling '+nI+' items forward.'); // save new config itms.first -= nI; while (itms.first < 0) { itms.first += itms.total; } // non-circular callback if (!opts.circular) { if (itms.first == opts.items.visible && sO.onEnd) sO.onEnd.call($tt0); if (!opts.infinite) nv_enableNavi(opts, itms.first, conf); } // rearrange items if (itms.total < opts.items.visible+nI) { $cfs.children().slice(0, (opts.items.visible+nI)-itms.total).clone(true).appendTo($cfs); } // the needed items var a_itm = $cfs.children(), c_old = gi_getOldItemsNext(a_itm, opts), c_new = gi_getNewItemsNext(a_itm, opts, nI), l_cur = a_itm.eq(nI-1), l_old = c_old.last(), l_new = c_new.last(); if (opts.usePadding) sz_resetMargin(a_itm, opts); if (opts.align) { var p = cf_getAlignPadding(c_new, opts), pL = p[0], pR = p[1]; } else { var pL = 0, pR = 0; } // hide items for fx directscroll if (sO.fx == 'directscroll' && opts.items.visibleConf.old < nI) { var hiddenitems = a_itm.slice(opts.items.visibleConf.old, nI), orgW = opts.items[opts.d['width']]; hiddenitems.each(function() { var hi = $(this); hi.data('isHidden', hi.is(':hidden')).hide(); }); opts.items[opts.d['width']] = 'variable'; } else { var hiddenitems = false; } // save new sizes var i_siz = ms_getTotalSize(a_itm.slice(0, nI), opts, 'width'), w_siz = cf_mapWrapperSizes(ms_getSizes(c_new, opts, true), opts, !opts.usePadding); if (hiddenitems) opts.items[opts.d['width']] = orgW; if (opts.align) { if (opts.padding[opts.d[1]] < 0) { opts.padding[opts.d[1]] = 0; } } if (opts.usePadding) { sz_resetMargin(a_itm, opts, true); sz_resetMargin(l_old, opts, opts.padding[opts.d[1]]); } if (opts.align) { opts.padding[opts.d[1]] = pR; opts.padding[opts.d[3]] = pL; } // animation configuration var a_cfs = {}, a_dur = sO.duration; if (sO.fx == 'none') a_dur = 0; else if (a_dur == 'auto') a_dur = opts.scroll.duration / opts.scroll.items * nI; else if (a_dur <= 0) a_dur = 0; else if (a_dur < 10) a_dur = i_siz / a_dur; scrl = sc_setScroll(a_dur, sO.easing); // animate wrapper if (opts[opts.d['width']] == 'variable' || opts[opts.d['height']] == 'variable') { scrl.anims.push([$wrp, w_siz]); } // animate items if (opts.usePadding) { var l_new_m = l_new.data('cfs_origCssMargin'); if (pR >= 0) { l_new_m += opts.padding[opts.d[1]]; } l_new.css(opts.d['marginRight'], l_new_m); if (l_cur.not(l_old).length) { var a_old = {}; a_old[opts.d['marginRight']] = l_old.data('cfs_origCssMargin'); scrl.anims.push([l_old, a_old]); } var c_new_m = l_cur.data('cfs_origCssMargin'); if (pL >= 0) { c_new_m += opts.padding[opts.d[3]]; } var a_cur = {}; a_cur[opts.d['marginRight']] = c_new_m; scrl.anims.push([l_cur, a_cur]); } // animate carousel a_cfs[opts.d['left']] = -i_siz; if (pL < 0) { a_cfs[opts.d['left']] += pL; } // onBefore callback var args = [c_old, c_new, w_siz, a_dur]; if (sO.onBefore) sO.onBefore.apply($tt0, args); clbk.onBefore = sc_callCallbacks(clbk.onBefore, $tt0, args); // ALTERNATIVE EFFECTS // extra animation arrays switch(sO.fx) { case 'fade': case 'crossfade': case 'cover': case 'uncover': scrl.pre = sc_setScroll(scrl.duration, scrl.easing); scrl.post = sc_setScroll(scrl.duration, scrl.easing); scrl.duration = 0; break; } // create copy switch(sO.fx) { case 'crossfade': case 'cover': case 'uncover': var $cf2 = $cfs.clone().appendTo($wrp); break; } switch(sO.fx) { case 'uncover': $cf2.children().slice(opts.items.visibleConf.old).remove(); break; case 'crossfade': case 'cover': $cf2.children().slice(0, nI).remove(); $cf2.children().slice(opts.items.visible).remove(); break; } // animations switch(sO.fx) { case 'fade': scrl.pre.anims.push([$cfs, { 'opacity': 0 }]); break; case 'crossfade': $cf2.css({ 'opacity': 0 }); scrl.pre.anims.push([$cfs, { 'width': '+=0' }, function() { $cf2.remove(); }]); scrl.post.anims.push([$cf2, { 'opacity': 1 }]); break; case 'cover': scrl = fx_cover(scrl, $cfs, $cf2, opts, false); break; case 'uncover': scrl = fx_uncover(scrl, $cfs, $cf2, opts, false, nI); break; } // /ALTERNATIVE EFFECTS // complete callback var a_complete = function() { var overFill = opts.items.visible+nI-itms.total, new_m = (opts.usePadding) ? opts.padding[opts.d[3]] : 0; $cfs.css(opts.d['left'], new_m); if (overFill > 0) { $cfs.children().slice(itms.total).remove(); } var l_itm = $cfs.children().slice(0, nI).appendTo($cfs).last(); if (overFill > 0) { c_new = gi_getCurrentItems(a_itm, opts); } if (hiddenitems) { hiddenitems.each(function() { var hi = $(this); if (!hi.data('isHidden')) hi.show(); }); } if (opts.usePadding) { if (itms.total < opts.items.visible+nI) { var l_cur = $cfs.children().eq(opts.items.visible-1); l_cur.css(opts.d['marginRight'], l_cur.data('cfs_origCssMargin') + opts.padding[opts.d[3]]); } l_itm.css(opts.d['marginRight'], l_itm.data('cfs_origCssMargin')); } scrl.anims = []; if (scrl.pre) scrl.pre = sc_setScroll(scrl.orgDuration, scrl.easing); var fn = function() { switch(sO.fx) { case 'fade': case 'crossfade': $cfs.css('filter', ''); break; } scrl.post = sc_setScroll(0, null); crsl.isScrolling = false; var args = [c_old, c_new, w_siz]; if (sO.onAfter) sO.onAfter.apply($tt0, args); clbk.onAfter = sc_callCallbacks(clbk.onAfter, $tt0, args); if (queu.length) { $cfs.trigger(cf_e(queu[0][0], conf), queu[0][1]); queu.shift(); } if (!crsl.isPaused) $cfs.trigger(cf_e('play', conf)); }; switch(sO.fx) { case 'fade': scrl.pre.anims.push([$cfs, { 'opacity': 1 }, fn]); sc_startScroll(scrl.pre); break; case 'uncover': scrl.pre.anims.push([$cfs, { 'width': '+=0' }, fn]); sc_startScroll(scrl.pre); break; default: fn(); break; } }; scrl.anims.push([$cfs, a_cfs, a_complete]); crsl.isScrolling = true; tmrs = sc_clearTimers(tmrs); sc_startScroll(scrl); cf_setCookie(opts.cookie, $cfs.triggerHandler(cf_e('currentPosition', conf))); $cfs.trigger(cf_e('updatePageStatus', conf), [false, w_siz]); return true; }); // slideTo event $cfs.bind(cf_e('slideTo', conf), function(e, num, dev, org, obj, dir, clb) { e.stopPropagation(); var v = [num, dev, org, obj, dir, clb], t = ['string/number/object', 'number', 'boolean', 'object', 'string', 'function'], a = cf_sortParams(v, t); var obj = a[3], dir = a[4], clb = a[5]; num = gn_getItemIndex(a[0], a[1], a[2], itms, $cfs); if (num == 0) return; if (typeof obj != 'object') obj = false; if (crsl.isScrolling) { if (typeof obj != 'object' || obj.duration > 0) return false; } if (dir != 'prev' && dir != 'next') { if (opts.circular) { if (num <= itms.total / 2) dir = 'next'; else dir = 'prev'; } else { if (itms.first == 0 || itms.first > num) dir = 'next'; else dir = 'prev'; } } if (dir == 'prev') num = itms.total-num; $cfs.trigger(cf_e(dir, conf), [obj, num, clb]); return true; }); // prevPage event $cfs.bind(cf_e('prevPage', conf), function(e, obj, clb) { e.stopPropagation(); var cur = $cfs.triggerHandler(cf_e('currentPage', conf)); return $cfs.triggerHandler(cf_e('slideToPage', conf), [cur-1, obj, 'prev', clb]); }); // nextPage event $cfs.bind(cf_e('nextPage', conf), function(e, obj, clb) { e.stopPropagation(); var cur = $cfs.triggerHandler(cf_e('currentPage', conf)); return $cfs.triggerHandler(cf_e('slideToPage', conf), [cur+1, obj, 'next', clb]); }); // slideToPage event $cfs.bind(cf_e('slideToPage', conf), function(e, pag, obj, dir, clb) { e.stopPropagation(); if (typeof pag != 'number') pag = $cfs.triggerHandler(cf_e('currentPage', conf)); var ipp = opts.pagination.items || opts.items.visible, max = Math.floor(itms.total / ipp)-1; if (pag < 0) pag = max; if (pag > max) pag = 0; return $cfs.triggerHandler(cf_e('slideTo', conf), [pag*ipp, 0, true, obj, dir, clb]); }); // jumpToStart event $cfs.bind(cf_e('jumpToStart', conf), function(e, s) { e.stopPropagation(); if (s) s = gn_getItemIndex(s, 0, true, itms, $cfs); else s = 0; s += itms.first; if (s != 0) { while (s > itms.total) s -= itms.total; $cfs.prepend($cfs.children().slice(s, itms.total)); } return true; }); // synchronise event $cfs.bind(cf_e('synchronise', conf), function(e, s) { e.stopPropagation(); if (s) s = cf_getSynchArr(s); else if (opts.synchronise) s = opts.synchronise; else return debug(conf, 'No carousel to synchronise.'); var n = $cfs.triggerHandler(cf_e('currentPosition', conf)), x = true; for (var j = 0, l = s.length; j < l; j++) { if (!s[j][0].triggerHandler(cf_e('slideTo', conf), [n, s[j][3], true])) { x = false; } } return x; }); // queue event $cfs.bind(cf_e('queue', conf), function(e, dir, opt) { e.stopPropagation(); if (typeof dir == 'function') { dir.call($tt0, queu); } else if (is_array(dir)) { queu = dir; } else if (typeof dir != 'undefined') { queu.push([dir, opt]); } return queu; }); // insertItem event $cfs.bind(cf_e('insertItem', conf), function(e, itm, num, org, dev) { e.stopPropagation(); var v = [itm, num, org, dev], t = ['string/object', 'string/number/object', 'boolean', 'number'], a = cf_sortParams(v, t); var itm = a[0], num = a[1], org = a[2], dev = a[3]; if (typeof itm == 'object' && typeof itm.jquery == 'undefined') itm = $(itm); if (typeof itm == 'string') itm = $(itm); if (typeof itm != 'object' || typeof itm.jquery == 'undefined' || itm.length == 0) return debug(conf, 'Not a valid object.'); if (typeof num == 'undefined') num = 'end'; if (opts.usePadding) { itm.each(function() { var m = parseInt($(this).css(opts.d['marginRight'])); if (isNaN(m)) m = 0; $(this).data('cfs_origCssMargin', m); }); } var orgNum = num, before = 'before'; if (num == 'end') { if (org) { if (itms.first == 0) { num = itms.total-1; before = 'after'; } else { num = itms.first; itms.first += itm.length } if (num < 0) num = 0; } else { num = itms.total-1; before = 'after'; } } else { num = gn_getItemIndex(num, dev, org, itms, $cfs); } if (orgNum != 'end' && !org) { if (num < itms.first) itms.first += itm.length; } if (itms.first >= itms.total) itms.first -= itms.total; var $cit = $cfs.children().eq(num); if ($cit.length) { $cit[before](itm); } else { $cfs.append(itm); } itms.total = $cfs.children().length; var sz = $cfs.triggerHandler('updateSizes'); nv_showNavi(opts, itms.total, conf); nv_enableNavi(opts, itms.first, conf); $cfs.trigger(cf_e('linkAnchors', conf)); $cfs.trigger(cf_e('updatePageStatus', conf), [true, sz]); return true; }); // removeItem event $cfs.bind(cf_e('removeItem', conf), function(e, num, org, dev) { e.stopPropagation(); var v = [num, org, dev], t = ['string/number/object', 'boolean', 'number'], a = cf_sortParams(v, t); var num = a[0], org = a[1], dev = a[2]; if (typeof num == 'undefined' || num == 'end') { $cfs.children().last().remove(); } else { num = gn_getItemIndex(num, dev, org, itms, $cfs); var $cit = $cfs.children().eq(num); if ($cit.length){ if (num < itms.first) itms.first -= $cit.length; $cit.remove(); } } itms.total = $cfs.children().length; var sz = $cfs.triggerHandler('updateSizes'); nv_showNavi(opts, itms.total, conf); nv_enableNavi(opts, itms.first, conf); $cfs.trigger(cf_e('updatePageStatus', conf), [true, sz]); return true; }); // onBefore and onAfter event $cfs.bind(cf_e('onBefore', conf)+' '+cf_e('onAfter', conf), function(e, fn) { e.stopPropagation(); var eType = e.type.substr(conf.events.prefix.length); if (is_array(fn)) clbk[eType] = fn; if (typeof fn == 'function') clbk[eType].push(fn); return clbk[eType]; }); // currentPosition event, accessible from outside $cfs.bind(cf_e('_cfs_currentPosition', conf, false), function(e, fn) { e.stopPropagation(); return $cfs.triggerHandler(cf_e('currentPosition', conf), fn); }); $cfs.bind(cf_e('currentPosition', conf), function(e, fn) { e.stopPropagation(); if (itms.first == 0) var val = 0; else var val = itms.total - itms.first; if (typeof fn == 'function') fn.call($tt0, val); return val; }); // currentPage event $cfs.bind(cf_e('currentPage', conf), function(e, fn) { e.stopPropagation(); var ipp = opts.pagination.items || opts.items.visible; var max = Math.ceil(itms.total/ipp-1); if (itms.first == 0) var nr = 0; else if (itms.first < itms.total % ipp) var nr = 0; else if (itms.first == ipp && !opts.circular) var nr = max; else var nr = Math.round((itms.total-itms.first)/ipp); if (nr < 0) nr = 0; if (nr > max) nr = max; if (typeof fn == 'function') fn.call($tt0, nr); return nr; }); // currentVisible event $cfs.bind(cf_e('currentVisible', conf), function(e, fn) { e.stopPropagation(); $i = gi_getCurrentItems($cfs.children(), opts); if (typeof fn == 'function') fn.call($tt0, $i); return $i; }); // slice event $cfs.bind(cf_e('slice', conf), function(e, f, l, fn) { e.stopPropagation(); var v = [f, l, fn], t = ['number', 'number', 'function'], a = cf_sortParams(v, t); f = (typeof a[0] == 'number') ? a[0] : 0, l = (typeof a[1] == 'number') ? a[1] : itms.total, fn = a[2]; f += itms.first; l += itms.first; while (f > itms.total) { f -= itms.total } while (l > itms.total) { l -= itms.total } while (f < 0) { f += itms.total } while (l < 0) { l += itms.total } var $iA = $cfs.children(); if (l > f) { var $i = $iA.slice(f, l); } else { var $i = $iA.slice(f, itms.total).get().concat( $iA.slice(0, l).get() ); } if (typeof fn == 'function') fn.call($tt0, $i); return $i; }); // isPaused, isStopped and isScrolling events $cfs.bind(cf_e('isPaused', conf)+' '+cf_e('isStopped', conf)+' '+cf_e('isScrolling', conf), function(e, fn) { e.stopPropagation(); var eType = e.type.substr(conf.events.prefix.length); if (typeof fn == 'function') fn.call($tt0, crsl[eType]); return crsl[eType]; }); // configuration event, accessible from outside $cfs.bind(cf_e('_cfs_configuration', conf, false), function(e, a, b, c) { e.stopPropagation(); return $cfs.triggerHandler(cf_e('configuration', conf), [a, b, c]); }); $cfs.bind(cf_e('configuration', conf), function(e, a, b, c) { e.stopPropagation(); var reInit = false; // return entire configuration-object if (typeof a == 'function') { a.call($tt0, opts); // set multiple options via object } else if (typeof a == 'object') { opts_orig = $.extend(true, {}, opts_orig, a); if (b !== false) reInit = true; else opts = $.extend(true, {}, opts, a); } else if (typeof a != 'undefined') { // callback function for specific option if (typeof b == 'function') { var val = eval('opts.'+a); if (typeof val == 'undefined') val = ''; b.call($tt0, val); // set individual option } else if (typeof b != 'undefined') { if (typeof c !== 'boolean') c = true; eval('opts_orig.'+a+' = b'); if (c !== false) reInit = true; else eval('opts.'+a+' = b'); // return value for specific option } else { return eval('opts.'+a); } } if (reInit) { sz_resetMargin($cfs.children(), opts); $cfs._cfs_init(opts_orig); $cfs._cfs_bind_buttons(); var siz = sz_setSizes($cfs, opts, false); $cfs.trigger(cf_e('updatePageStatus', conf), [true, siz]); } return opts; }); // linkAnchors event $cfs.bind(cf_e('linkAnchors', conf), function(e, $con, sel) { e.stopPropagation(); if (typeof $con == 'undefined' || $con.length == 0) $con = $('body'); else if (typeof $con == 'string') $con = $($con); if (typeof $con != 'object') return debug(conf, 'Not a valid object.'); if (typeof sel != 'string' || sel.length == 0) sel = 'a.caroufredsel'; $con.find(sel).each(function() { var h = this.hash || ''; if (h.length > 0 && $cfs.children().index($(h)) != -1) { $(this).unbind('click').click(function(e) { e.preventDefault(); $cfs.trigger(cf_e('slideTo', conf), h); }); } }); return true; }); // updatePageStatus event $cfs.bind(cf_e('updatePageStatus', conf), function(e, build, sizes) { e.stopPropagation(); if (!opts.pagination.container) return; if (build) { var ipp = opts.pagination.items || opts.items.visible, l = Math.ceil(itms.total/ipp); if (opts.pagination.anchorBuilder) { opts.pagination.container.children().remove(); opts.pagination.container.each(function() { for (var a = 0; a < l; a++) { var i = $cfs.children().eq( gn_getItemIndex(a*ipp, 0, true, itms, $cfs) ); $(this).append(opts.pagination.anchorBuilder(a+1, i)); } }); } opts.pagination.container.each(function() { $(this).children().unbind(opts.pagination.event).each(function(a) { $(this).bind(opts.pagination.event, function(e) { e.preventDefault(); $cfs.trigger(cf_e('slideTo', conf), [a*ipp, 0, true, opts.pagination]); }); }); }); } opts.pagination.container.each(function() { $(this).children().removeClass(cf_c('selected', conf)).eq($cfs.triggerHandler(cf_e('currentPage', conf))).addClass(cf_c('selected', conf)); }); return true; }); // updateSizes event $cfs.bind(cf_e('updateSizes', conf), function(e) { var a_itm = $cfs.children(), vI = opts.items.visible; if (opts.items.visibleConf.variable) vI = gn_getVisibleItemsNext(a_itm, opts, 0); else if (opts.items.filter != '*') vI = gn_getVisibleItemsNextFilter(a_itm, opts, 0); if (!opts.circular && itms.first != 0 && vI > itms.first) { if (opts.items.visibleConf.variable) { var nI = gn_getVisibleItemsPrev(a_itm, opts, itms.first) - itms.first; } else if (opts.items.filter != '*') { var nI = gn_getVisibleItemsPrevFilter(a_itm, opts, itms.first) - itms.first; } else { nI = opts.items.visible - itms.first; } debug(conf, 'Preventing non-circular: sliding '+nI+' items backward.'); $cfs.trigger('prev', nI); } opts.items.visible = cf_getItemsAdjust(vI, opts, opts.items.visibleConf.adjust, $tt0); return sz_setSizes($cfs, opts); }); // destroy event, accessible from outside $cfs.bind(cf_e('_cfs_destroy', conf, false), function(e, orgOrder) { e.stopPropagation(); $cfs.trigger(cf_e('destroy', conf), orgOrder); return true; }); $cfs.bind(cf_e('destroy', conf), function(e, orgOrder) { e.stopPropagation(); tmrs = sc_clearTimers(tmrs); $cfs.data('cfs_isCarousel', false); $cfs.trigger(cf_e('finish', conf)); if (orgOrder) { $cfs.trigger(cf_e('jumpToStart', conf)); } if (opts.usePadding) { sz_resetMargin($cfs.children(), opts); } $cfs.css($cfs.data('cfs_origCss')); $cfs._cfs_unbind_events(); $cfs._cfs_unbind_buttons(); $wrp.replaceWith($cfs); return true; }); }; // /bind_events $cfs._cfs_unbind_events = function() { $cfs.unbind(cf_e('', conf)); $cfs.unbind(cf_e('', conf, false)); }; // /unbind_events $cfs._cfs_bind_buttons = function() { $cfs._cfs_unbind_buttons(); nv_showNavi(opts, itms.total, conf); nv_enableNavi(opts, itms.first, conf); if (opts.auto.pauseOnHover) { var pC = bt_pauseOnHoverConfig(opts.auto.pauseOnHover); $wrp.bind(cf_e('mouseenter', conf, false), function() { $cfs.trigger(cf_e('pause', conf), pC); }) .bind(cf_e('mouseleave', conf, false), function() { $cfs.trigger(cf_e('resume', conf)); }); } if (opts.auto.button) { opts.auto.button.bind(cf_e(opts.auto.event, conf, false), function(e) { e.preventDefault(); var ev = false, pC = null; if (crsl.isPaused) { ev = 'play'; } else if (opts.auto.pauseOnEvent) { ev = 'pause'; pC = bt_pauseOnHoverConfig(opts.auto.pauseOnEvent); } if (ev) { $cfs.trigger(cf_e(ev, conf), pC); } }); } if (opts.prev.button) { opts.prev.button.bind(cf_e(opts.prev.event, conf, false), function(e) { e.preventDefault(); $cfs.trigger(cf_e('prev', conf)); }); if (opts.prev.pauseOnHover) { var pC = bt_pauseOnHoverConfig(opts.prev.pauseOnHover); opts.prev.button.bind(cf_e('mouseenter', conf, false), function() { $cfs.trigger(cf_e('pause', conf), pC); }) .bind(cf_e('mouseleave', conf, false), function() { $cfs.trigger(cf_e('resume', conf)); }); } } if (opts.next.button) { opts.next.button.bind(cf_e(opts.next.event, conf, false), function(e) { e.preventDefault(); $cfs.trigger(cf_e('next', conf)); }); if (opts.next.pauseOnHover) { var pC = bt_pauseOnHoverConfig(opts.next.pauseOnHover); opts.next.button.bind(cf_e('mouseenter', conf, false), function() { $cfs.trigger(cf_e('pause', conf), pC); }) .bind(cf_e('mouseleave', conf, false), function() { $cfs.trigger(cf_e('resume', conf)); }); } } if ($.fn.mousewheel) { if (opts.prev.mousewheel) { if (!crsl.mousewheelPrev) { crsl.mousewheelPrev = true; $wrp.mousewheel(function(e, delta) { if (delta > 0) { e.preventDefault(); var num = bt_mousesheelNumber(opts.prev.mousewheel); $cfs.trigger(cf_e('prev', conf), num); } }); } } if (opts.next.mousewheel) { if (!crsl.mousewheelNext) { crsl.mousewheelNext = true; $wrp.mousewheel(function(e, delta) { if (delta < 0) { e.preventDefault(); var num = bt_mousesheelNumber(opts.next.mousewheel); $cfs.trigger(cf_e('next', conf), num); } }); } } } if ($.fn.touchwipe) { var wP = (opts.prev.wipe) ? function() { $cfs.trigger(cf_e('prev', conf)) } : null, wN = (opts.next.wipe) ? function() { $cfs.trigger(cf_e('next', conf)) } : null; if (wN || wN) { if (!crsl.touchwipe) { crsl.touchwipe = true; var twOps = { 'min_move_x': 30, 'min_move_y': 30, 'preventDefaultEvents': true }; switch (opts.direction) { case 'up': case 'down': twOps.wipeUp = wN; twOps.wipeDown = wP; break; default: twOps.wipeLeft = wN; twOps.wipeRight = wP; } $wrp.touchwipe(twOps); } } } if (opts.pagination.container) { if (opts.pagination.pauseOnHover) { var pC = bt_pauseOnHoverConfig(opts.pagination.pauseOnHover); opts.pagination.container.bind(cf_e('mouseenter', conf, false), function() { $cfs.trigger(cf_e('pause', conf), pC); }) .bind(cf_e('mouseleave', conf, false), function() { $cfs.trigger(cf_e('resume', conf)); }); } } if (opts.prev.key || opts.next.key) { $(document).bind(cf_e('keyup', conf, false, true, true), function(e) { var k = e.keyCode; if (k == opts.next.key) { e.preventDefault(); $cfs.trigger(cf_e('next', conf)); } if (k == opts.prev.key) { e.preventDefault(); $cfs.trigger(cf_e('prev', conf)); } }); } if (opts.pagination.keys) { $(document).bind(cf_e('keyup', conf, false, true, true), function(e) { var k = e.keyCode; if (k >= 49 && k < 58) { k = (k-49) * opts.items.visible; if (k <= itms.total) { e.preventDefault(); $cfs.trigger(cf_e('slideTo', conf), [k, 0, true, opts.pagination]); } } }); } if (opts.auto.play) { $cfs.trigger(cf_e('play', conf), opts.auto.delay); } if (crsl.upDateOnWindowResize) { $(window).bind(cf_e('resize', conf, false, true, true), function(e) { $cfs.trigger(cf_e('finish', conf)); if (opts.auto.pauseOnResize && !crsl.isPaused) { $cfs.trigger(cf_e('play', conf)); } sz_resetMargin($cfs.children(), opts); $cfs._cfs_init(opts_orig); var siz = sz_setSizes($cfs, opts, false); $cfs.trigger(cf_e('updatePageStatus', conf), [true, siz]); }); } }; // /bind_buttons $cfs._cfs_unbind_buttons = function() { var ns1 = cf_e('', conf), ns2 = cf_e('', conf, false); ns3 = cf_e('', conf, false, true, true); $(document).unbind(ns3); $(window).unbind(ns3); $wrp.unbind(ns2); if (opts.auto.button) opts.auto.button.unbind(ns2); if (opts.prev.button) opts.prev.button.unbind(ns2); if (opts.next.button) opts.next.button.unbind(ns2); if (opts.pagination.container) { opts.pagination.container.unbind(ns2); if (opts.pagination.anchorBuilder) { opts.pagination.container.children().remove(); } } nv_showNavi(opts, 'hide', conf); nv_enableNavi(opts, 'removeClass', conf); }; // /unbind_buttons // START var crsl = { 'direction' : 'next', 'isPaused' : true, 'isScrolling' : false, 'isStopped' : false, 'mousewheelNext': false, 'mousewheelPrev': false, 'touchwipe' : false }, itms = { 'total' : $cfs.children().length, 'first' : 0 }, tmrs = { 'timer' : null, 'auto' : null, 'queue' : null, 'startTime' : getTime(), 'timePassed' : 0 }, scrl = { 'isStopped' : false, 'duration' : 0, 'startTime' : 0, 'easing' : '', 'anims' : [] }, clbk = { 'onBefore' : [], 'onAfter' : [] }, queu = [], conf = $.extend(true, {}, $.fn.carouFredSel.configs, configs), opts = {}, opts_orig = options, $wrp = $cfs.wrap('<'+conf.wrapper.element+' class="'+conf.wrapper.classname+'" />').parent(); conf.selector = $cfs.selector; conf.serialNumber = $.fn.carouFredSel.serialNumber++; // create carousel $cfs._cfs_init(opts_orig, true, starting_position); $cfs._cfs_build(); $cfs._cfs_bind_events(); $cfs._cfs_bind_buttons(); // find item to start if (is_array(opts.items.start)) { var start_arr = opts.items.start; } else { var start_arr = []; if (opts.items.start != 0) { start_arr.push(opts.items.start); } } if (opts.cookie) { start_arr.unshift(cf_readCookie(opts.cookie)); } if (start_arr.length > 0) { for (var a = 0, l = start_arr.length; a < l; a++) { var s = start_arr[a]; if (s == 0) { continue; } if (s === true) { s = window.location.hash; if (s.length < 1) { continue; } } else if (s === 'random') { s = Math.floor(Math.random()*itms.total); } if ($cfs.triggerHandler(cf_e('slideTo', conf), [s, 0, true, { fx: 'none' }])) { break; } } } var siz = sz_setSizes($cfs, opts, false), itm = gi_getCurrentItems($cfs.children(), opts); if (opts.onCreate) { opts.onCreate.call($tt0, itm, siz); } $cfs.trigger(cf_e('updatePageStatus', conf), [true, siz]); $cfs.trigger(cf_e('linkAnchors', conf)); return $cfs; }; // GLOBAL PUBLIC $.fn.carouFredSel.serialNumber = 1; $.fn.carouFredSel.defaults = { 'synchronise' : false, 'infinite' : true, 'circular' : true, 'responsive' : false, 'direction' : 'left', 'items' : { 'start' : 0 }, 'scroll' : { 'easing' : 'swing', 'duration' : 500, 'pauseOnHover' : false, 'mousewheel' : false, 'wipe' : false, 'event' : 'click', 'queue' : false } }; $.fn.carouFredSel.configs = { 'debug' : false, 'events' : { 'prefix' : '', 'namespace' : 'cfs' }, 'wrapper' : { 'element' : 'div', 'classname' : 'caroufredsel_wrapper' }, 'classnames' : {} }; $.fn.carouFredSel.pageAnchorBuilder = function(nr, itm) { return '<a href="#"><span>'+nr+'</span></a>'; }; // GLOBAL PRIVATE // scrolling functions function sc_setScroll(d, e) { return { anims : [], duration : d, orgDuration : d, easing : e, startTime : getTime() }; } function sc_startScroll(s) { if (typeof s.pre == 'object') { sc_startScroll(s.pre); } for (var a = 0, l = s.anims.length; a < l; a++) { var b = s.anims[a]; if (!b) continue; if (b[3]) b[0].stop(); b[0].animate(b[1], { complete: b[2], duration: s.duration, easing: s.easing }); } if (typeof s.post == 'object') { sc_startScroll(s.post); } } function sc_stopScroll(s, finish) { if (typeof finish != 'boolean') finish = true; if (typeof s.pre == 'object') { sc_stopScroll(s.pre, finish); } for (var a = 0, l = s.anims.length; a < l; a++) { var b = s.anims[a]; b[0].stop(true); if (finish) { b[0].css(b[1]); if (typeof b[2] == 'function') b[2](); } } if (typeof s.post == 'object') { sc_stopScroll(s.post, finish); } } function sc_clearTimers(t) { if (t.auto) clearTimeout(t.auto); return t; } function sc_callCallbacks(cbs, t, args) { if (cbs.length) { for (var a = 0, l = cbs.length; a < l; a++) { cbs[a].apply(t, args); } } return []; } // fx functions function fx_fade(sO, c, x, d, f) { var o = { 'duration' : d, 'easing' : sO.easing }; if (typeof f == 'function') o.complete = f; c.animate({ opacity: x }, o); } function fx_cover(sc, c1, c2, o, prev) { var old_w = ms_getSizes(gi_getOldItemsNext(c1.children(), o), o, true)[0], new_w = ms_getSizes(c2.children(), o, true)[0], cur_l = (prev) ? -new_w : old_w, css_o = {}, ani_o = {}; css_o[o.d['width']] = new_w; css_o[o.d['left']] = cur_l; ani_o[o.d['left']] = 0; sc.pre.anims.push([c1, { 'opacity': 1 }]); sc.post.anims.push([c2, ani_o, function() { $(this).remove(); }]); c2.css(css_o); return sc; } function fx_uncover(sc, c1, c2, o, prev, n) { var new_w = ms_getSizes(gi_getNewItemsNext(c1.children(), o, n), o, true)[0], old_w = ms_getSizes(c2.children(), o, true)[0], cur_l = (prev) ? -old_w : new_w, css_o = {}, ani_o = {}; css_o[o.d['width']] = old_w; css_o[o.d['left']] = 0; ani_o[o.d['left']] = cur_l; sc.post.anims.push([c2, ani_o, function() { $(this).remove(); }]); c2.css(css_o); return sc; } // navigation functions function nv_showNavi(o, t, c) { if (t == 'show' || t == 'hide') { var f = t; } else if (o.items.minimum >= t) { debug(c, 'Not enough items: hiding navigation ('+t+' items, '+o.items.minimum+' needed).'); var f = 'hide'; } else { var f = 'show'; } var s = (f == 'show') ? 'removeClass' : 'addClass', h = cf_c('hidden', c); if (o.auto.button) o.auto.button[f]()[s](h); if (o.prev.button) o.prev.button[f]()[s](h); if (o.next.button) o.next.button[f]()[s](h); if (o.pagination.container) o.pagination.container[f]()[s](h); } function nv_enableNavi(o, f, c) { if (o.circular || o.infinite) return; var fx = (f == 'removeClass' || f == 'addClass') ? f : false, di = cf_c('disabled', c); if (o.auto.button && fx) { o.auto.button[fx](di); } if (o.prev.button) { var fn = fx || (f == 0) ? 'addClass' : 'removeClass'; o.prev.button[fn](di); } if (o.next.button) { var fn = fx || (f == o.items.visible) ? 'addClass' : 'removeClass'; o.next.button[fn](di); } } // get object functions function go_getObject($tt, obj) { if (typeof obj == 'function') obj = obj.call($tt); if (typeof obj == 'undefined') obj = {}; return obj; } function go_getNaviObject($tt, obj, type) { if (typeof type != 'string') type = ''; obj = go_getObject($tt, obj); if (typeof obj == 'string') { var temp = cf_getKeyCode(obj); if (temp == -1) obj = $(obj); else obj = temp; } // pagination if (type == 'pagination') { if (typeof obj == 'boolean') obj = { 'keys': obj }; if (typeof obj.jquery != 'undefined') obj = { 'container': obj }; if (typeof obj.container == 'function') obj.container = obj.container.call($tt); if (typeof obj.container == 'string') obj.container = $(obj.container); if (typeof obj.items != 'number') obj.items = false; // auto } else if (type == 'auto') { if (typeof obj.jquery != 'undefined') obj = { 'button': obj }; if (typeof obj == 'boolean') obj = { 'play': obj }; if (typeof obj == 'number') obj = { 'pauseDuration': obj }; if (typeof obj.button == 'function') obj.button = obj.button.call($tt); if (typeof obj.button == 'string') obj.button = $(obj.button); // prev + next } else { if (typeof obj.jquery != 'undefined') obj = { 'button': obj }; if (typeof obj == 'number') obj = { 'key': obj }; if (typeof obj.button == 'function') obj.button = obj.button.call($tt); if (typeof obj.button == 'string') obj.button = $(obj.button); if (typeof obj.key == 'string') obj.key = cf_getKeyCode(obj.key); } return obj; } // get number functions function gn_getItemIndex(num, dev, org, items, $cfs) { if (typeof num == 'string') { if (isNaN(num)) num = $(num); else num = parseInt(num); } if (typeof num == 'object') { if (typeof num.jquery == 'undefined') num = $(num); num = $cfs.children().index(num); if (num == -1) num = 0; if (typeof org != 'boolean') org = false; } else { if (typeof org != 'boolean') org = true; } if (isNaN(num)) num = 0; else num = parseInt(num); if (isNaN(dev)) dev = 0; else dev = parseInt(dev); if (org) { num += items.first; } num += dev; if (items.total > 0) { while (num >= items.total) { num -= items.total; } while (num < 0) { num += items.total; } } return num; } // items prev function gn_getVisibleItemsPrev(i, o, s) { var t = 0, x = 0; for (var a = s; a >= 0; a--) { var j = i.eq(a); t += (j.is(':visible')) ? j[o.d['outerWidth']](true) : 0; if (t > o.maxDimention) return x; if (a == 0) a = i.length; x++; } } function gn_getVisibleItemsPrevFilter(i, o, s) { return gn_getItemsPrevFilter(i, o.items.filter, o.items.visibleConf.org, s); } function gn_getScrollItemsPrevFilter(i, o, s, m) { return gn_getItemsPrevFilter(i, o.items.filter, m, s); } function gn_getItemsPrevFilter(i, f, m, s) { var t = 0, x = 0; for (var a = s, l = i.length-1; a >= 0; a--) { x++; if (x == l) return x; var j = i.eq(a); if (j.is(f)) { t++; if (t == m) return x; } if (a == 0) a = i.length; } } function gn_getVisibleOrg($c, o) { return o.items.visibleConf.org || $c.children().slice(0, o.items.visible).filter(o.items.filter).length; } // items next function gn_getVisibleItemsNext(i, o, s) { var t = 0, x = 0; for (var a = s, l = i.length-1; a <= l; a++) { var j = i.eq(a); t += (j.is(':visible')) ? j[o.d['outerWidth']](true) : 0; if (t > o.maxDimention) return x; x++; if (x == l) return x; if (a == l) a = -1; } } function gn_getVisibleItemsNextTestCircular(i, o, s, l) { var v = gn_getVisibleItemsNext(i, o, s); if (!o.circular) { if (s + v > l) v = l - s; } return v; } function gn_getVisibleItemsNextFilter(i, o, s) { return gn_getItemsNextFilter(i, o.items.filter, o.items.visibleConf.org, s, o.circular); } function gn_getScrollItemsNextFilter(i, o, s, m) { return gn_getItemsNextFilter(i, o.items.filter, m+1, s, o.circular) - 1; } function gn_getItemsNextFilter(i, f, m, s, c) { var t = 0, x = 0; for (var a = s, l = i.length-1; a <= l; a++) { x++; if (x == l) return x; var j = i.eq(a); if (j.is(f)) { t++; if (t == m) return x; } if (a == l) a = -1; } } // get items functions function gi_getCurrentItems(i, o) { return i.slice(0, o.items.visible); } function gi_getOldItemsPrev(i, o, n) { return i.slice(n, o.items.visibleConf.old+n); } function gi_getNewItemsPrev(i, o) { return i.slice(0, o.items.visible); } function gi_getOldItemsNext(i, o) { return i.slice(0, o.items.visibleConf.old); } function gi_getNewItemsNext(i, o, n) { return i.slice(n, o.items.visible+n); } // sizes functions function sz_resetMargin(i, o, m) { var x = (typeof m == 'boolean') ? m : false; if (typeof m != 'number') m = 0; i.each(function() { var j = $(this); var t = parseInt(j.css(o.d['marginRight'])); if (isNaN(t)) t = 0; j.data('cfs_tempCssMargin', t); j.css(o.d['marginRight'], ((x) ? j.data('cfs_tempCssMargin') : m + j.data('cfs_origCssMargin'))); }); } function sz_setSizes($c, o, p) { var $w = $c.parent(), $i = $c.children(), $v = gi_getCurrentItems($i, o), sz = cf_mapWrapperSizes(ms_getSizes($v, o, true), o, p); $w.css(sz); if (o.usePadding) { var p = o.padding, r = p[o.d[1]]; if (o.align) { if (r < 0) r = 0; } var $l = $v.last(); $l.css(o.d['marginRight'], $l.data('cfs_origCssMargin') + r); $c.css(o.d['top'], p[o.d[0]]); $c.css(o.d['left'], p[o.d[3]]); } $c.css(o.d['width'], sz[o.d['width']]+(ms_getTotalSize($i, o, 'width')*2)); $c.css(o.d['height'], ms_getLargestSize($i, o, 'height')); return sz; } // measuring functions function ms_getSizes(i, o, wrapper) { var s1 = ms_getTotalSize(i, o, 'width', wrapper), s2 = ms_getLargestSize(i, o, 'height', wrapper); return [s1, s2]; } function ms_getLargestSize(i, o, dim, wrapper) { if (typeof wrapper != 'boolean') wrapper = false; if (typeof o[o.d[dim]] == 'number' && wrapper) return o[o.d[dim]]; if (typeof o.items[o.d[dim]] == 'number') return o.items[o.d[dim]]; var di2 = (dim.toLowerCase().indexOf('width') > -1) ? 'outerWidth' : 'outerHeight'; return ms_getTrueLargestSize(i, o, di2); } function ms_getTrueLargestSize(i, o, dim) { var s = 0; for (var a = 0, l = i.length; a < l; a++) { var j = i.eq(a); var m = (j.is(':visible')) ? j[o.d[dim]](true) : 0; if (s < m) s = m; } return s; } function ms_getTrueInnerSize($el, o, dim) { if (!$el.is(':visible')) return 0; var siz = $el[o.d[dim]](), arr = (o.d[dim].toLowerCase().indexOf('width') > -1) ? ['paddingLeft', 'paddingRight'] : ['paddingTop', 'paddingBottom']; for (var a = 0, l = arr.length; a < l; a++) { var m = parseInt($el.css(arr[a])); siz -= (isNaN(m)) ? 0 : m; } return siz; } function ms_getTotalSize(i, o, dim, wrapper) { if (typeof wrapper != 'boolean') wrapper = false; if (typeof o[o.d[dim]] == 'number' && wrapper) return o[o.d[dim]]; if (typeof o.items[o.d[dim]] == 'number') return o.items[o.d[dim]] * i.length; var d = (dim.toLowerCase().indexOf('width') > -1) ? 'outerWidth' : 'outerHeight', s = 0; for (var a = 0, l = i.length; a < l; a++) { var j = i.eq(a); s += (j.is(':visible')) ? j[o.d[d]](true) : 0; } return s; } function ms_hasVariableSizes(i, o, dim) { var s = false, v = false; for (var a = 0, l = i.length; a < l; a++) { var j = i.eq(a); var c = (j.is(':visible')) ? j[o.d[dim]](true) : 0; if (s === false) s = c; else if (s != c) v = true; if (s == 0) v = true; } return v; } function ms_getPaddingBorderMargin(i, o, d) { return i[o.d['outer'+d]](true) - ms_getTrueInnerSize(i, o, 'inner'+d); } function ms_isPercentage(x) { return (typeof x == 'string' && x.substr(-1) == '%'); } function ms_getPercentage(s, o) { if (ms_isPercentage(o)) { o = o.substring(0, o.length-1); if (isNaN(o)) return s; s *= o/100; } return s; } // config functions function cf_e(n, c, pf, ns, rd) { if (typeof pf != 'boolean') pf = true; if (typeof ns != 'boolean') ns = true; if (typeof rd != 'boolean') rd = false; if (pf) n = c.events.prefix + n; if (ns) n = n +'.'+ c.events.namespace; if (ns && rd) n += c.serialNumber; return n; } function cf_c(n, c) { return (typeof c.classnames[n] == 'string') ? c.classnames[n] : n; } function cf_mapWrapperSizes(ws, o, p) { if (typeof p != 'boolean') p = true; var pad = (o.usePadding && p) ? o.padding : [0, 0, 0, 0]; var wra = {}; wra[o.d['width']] = ws[0] + pad[1] + pad[3]; wra[o.d['height']] = ws[1] + pad[0] + pad[2]; return wra; } function cf_sortParams(vals, typs) { var arr = []; for (var a = 0, l1 = vals.length; a < l1; a++) { for (var b = 0, l2 = typs.length; b < l2; b++) { if (typs[b].indexOf(typeof vals[a]) > -1 && typeof arr[b] == 'undefined') { arr[b] = vals[a]; break; } } } return arr; } function cf_getPadding(p) { if (typeof p == 'undefined') return [0, 0, 0, 0]; if (typeof p == 'number') return [p, p, p, p]; else if (typeof p == 'string') p = p.split('px').join('').split('em').join('').split(' '); if (!is_array(p)) { return [0, 0, 0, 0]; } for (var i = 0; i < 4; i++) { p[i] = parseInt(p[i]); } switch (p.length) { case 0: return [0, 0, 0, 0]; case 1: return [p[0], p[0], p[0], p[0]]; case 2: return [p[0], p[1], p[0], p[1]]; case 3: return [p[0], p[1], p[2], p[1]]; default: return [p[0], p[1], p[2], p[3]]; } } function cf_getAlignPadding(itm, o) { var x = (typeof o[o.d['width']] == 'number') ? Math.ceil(o[o.d['width']] - ms_getTotalSize(itm, o, 'width')) : 0; switch (o.align) { case 'left': return [0, x]; case 'right': return [x, 0]; case 'center': default: return [Math.ceil(x/2), Math.floor(x/2)]; } } function cf_getAdjust(x, o, a, $t) { var v = x; if (typeof a == 'function') { v = a.call($t, v); } else if (typeof a == 'string') { var p = a.split('+'), m = a.split('-'); if (m.length > p.length) { var neg = true, sta = m[0], adj = m[1]; } else { var neg = false, sta = p[0], adj = p[1]; } switch(sta) { case 'even': v = (x % 2 == 1) ? x-1 : x; break; case 'odd': v = (x % 2 == 0) ? x-1 : x; break; default: v = x; break; } adj = parseInt(adj); if (!isNaN(adj)) { if (neg) adj = -adj; v += adj; } } if (typeof v != 'number') v = 1; if (v < 1) v = 1; return v; } function cf_getItemsAdjust(x, o, a, $t) { return cf_getItemAdjustMinMax(cf_getAdjust(x, o, a, $t), o.items.visibleConf); } function cf_getItemAdjustMinMax(v, i) { if (typeof i.min == 'number' && v < i.min) v = i.min; if (typeof i.max == 'number' && v > i.max) v = i.max; if (v < 1) v = 1; return v; } function cf_getSynchArr(s) { if (!is_array(s)) s = [[s]]; if (!is_array(s[0])) s = [s]; for (var j = 0, l = s.length; j < l; j++) { if (typeof s[j][0] == 'string') s[j][0] = $(s[j][0]); if (typeof s[j][1] != 'boolean') s[j][1] = true; if (typeof s[j][2] != 'boolean') s[j][2] = true; if (typeof s[j][3] != 'number') s[j][3] = 0; } return s; } function cf_getKeyCode(k) { if (k == 'right') return 39; if (k == 'left') return 37; if (k == 'up') return 38; if (k == 'down') return 40; return -1; } function cf_setCookie(n, v) { if (n) document.cookie = n+'='+v+'; path=/'; } function cf_readCookie(n) { n += '='; var ca = document.cookie.split(';'); for (var a = 0, l = ca.length; a < l; a++) { var c = ca[a]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(n) == 0) { return c.substring(n.length, c.length); } } return 0; } // buttons functions function bt_pauseOnHoverConfig(p) { if (p && typeof p == 'string') { var i = (p.indexOf('immediate') > -1) ? true : false, r = (p.indexOf('resume') > -1) ? true : false; } else { var i = r = false; } return [i, r]; } function bt_mousesheelNumber(mw) { return (typeof mw == 'number') ? mw : null } // helper functions function is_array(a) { return typeof(a) == 'object' && (a instanceof Array); } function getTime() { return new Date().getTime(); } function debug(d, m) { if (typeof d == 'object') { var s = ' ('+d.selector+')'; d = d.debug; } else { var s = ''; } if (!d) return false; if (typeof m == 'string') m = 'carouFredSel'+s+': ' + m; else m = ['carouFredSel'+s+':', m]; if (window.console && window.console.log) window.console.log(m); return false; } // CAROUFREDSEL ALL LOWERCASE $.fn.caroufredsel = function(o, c) { return this.carouFredSel(o, c); }; // EASING FUNCTIONS $.extend($.easing, { 'quadratic' : function(t) { var t2 = t * t; return t * (-t2 * t + 4 * t2 - 6 * t + 4); }, 'cubic' : function(t) { return t * (4 * t * t - 9 * t + 6); }, 'elastic' : function(t) { var t2 = t * t; return t * (33 * t2 * t2 - 106 * t2 * t + 126 * t2 - 67 * t + 15); } }); })(jQuery);
JavaScript