﻿
/**
 * Galleria (http://monc.se/kitchen)
 *
 * Galleria is a javascript image gallery written in jQuery. 
 * It loads the images one by one from an unordered list and displays thumbnails when each image is loaded. 
 * It will create thumbnails for you if you choose so, scaled or unscaled, 
 * centered and cropped inside a fixed thumbnail box defined by CSS.
 * 
 * The core of Galleria lies in it's smart preloading behaviour, snappiness and the fresh absence 
 * of obtrusive design elements. Use it as a foundation for your custom styled image gallery.
 *
 * MAJOR CHANGES v.FROM 0.9
 * Galleria now features a useful history extension, enabling back button and bookmarking for each image.
 * The main image is no longer stored inside each list item, instead it is placed inside a container
 * onImage and onThumb functions lets you customize the behaviours of the images on the site
 *
 * Tested in Safari 3, Firefox 2, MSIE 6, MSIE 7, Opera 9
 * 
 * Version 1.0
 * Februari 21, 2008
 *
 * Copyright (c) 2008 David Hellsing (http://monc.se)
 * Licensed under the GPL licenses.
 * http://www.gnu.org/licenses/gpl.txt
 **/

(function ($) {
    $.browser.chrome = $.browser.safari && navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    $.browser.safari = $.browser.safari && !$.browser.chrome;
    $.easing.easeInOutExpo = function (x, t, b, c, d) { return t === 0 ? b : t === d ? b + c : (t /= d / 2) < 1 ? c / 2 * Math.pow(2, 10 * --t) + b : c / 2 * (-Math.pow(2, -10 * --t) + 2) + b; };
    var $$;


    /**
    * 
    * @desc Convert images from a simple html <ul> into a thumbnail gallery
    * @author David Hellsing
    * @version 1.0
    *
    * @name Galleria
    * @type jQuery
    *
    * @cat plugins/Media
    * 
    * @example $('ul.gallery').galleria({options});
    * @desc Create a a gallery from an unordered list of images with thumbnails
    * @options
    *   insert:   (selector string) by default, Galleria will create a container div before your ul that holds the image.
    *             You can, however, specify a selector where the image will be placed instead (f.ex '#main_img')
    *   history:  Boolean for setting the history object in action with enabled back button, bookmarking etc.
    *   onImage:  (function) a function that gets fired when the image is displayed and brings the jQuery image object.
    *             You can use it to add click functionality and effects.
    *             f.ex onImage(image) { image.css('display','none').fadeIn(); } will fadeIn each image that is displayed
    *   onThumb:  (function) a function that gets fired when the thumbnail is displayed and brings the jQuery thumb object.
    *             Works the same as onImage except it targets the thumbnail after it's loaded.
    *
    **/

    var paused = true;
    var count = 3;
    $$ = $.fn.galleria = function ($options) {

        // check for basic CSS support
        if (!$$.hasCSS()) { return false; }

        // init the modified history object
        $.historyInit($$.onPageLoad);

        // set default options
        var $defaults = {
            insert: '.galleria_container',
            history: true,
            clickNext: true,
            onImage: function (image, caption, thumb, description) { },
            onThumb: function (thumb) { }
        };


        // extend the options
        var $opts = $.extend($defaults, $options);

        // bring the options to the galleria object
        for (var i in $opts) {
            if (i) {
                $.galleria[i] = $opts[i];
            }
        }

        // if no insert selector, create a new division and insert it before the ul
        var _insert = ($($opts.insert).is($opts.insert)) ?
		$($opts.insert) :
		jQuery(document.createElement('div')).insertBefore(this);

        // create a wrapping div for the image
        var _div = $(document.createElement('div')).addClass('galleria_wrapper').html("<span>loading...</span>");

        // create a caption span
        var _span = $(document.createElement('span')).addClass('caption');

        // create a description span
        var _descDiv = $(document.createElement('div')).addClass('description').append("<span></span><a href='#' title='Close Description'>Close</a>");
        _descDiv.find("a").click(function () {
            _descDiv.fadeOut($.browser.msie ? 0 : 300);
            return false;
        });
        // create a link span
        var _linkDiv = $(document.createElement('div')).addClass('link').append("<span></span><a href='#' title='Close Link Dialogue'>Close</a>");
        _linkDiv.find("a").click(function () {
            _linkDiv.fadeOut($.browser.msie ? 0 : 300);
            return false;
        });

        // create the links div
        var _linksDiv = $(document.createElement('div')).addClass('links').append("<a href='#' title='View Photo Description'>Description</a> | <a href='#' title='Get Link to Photo'>Link</a> <a title='Hide Thumbnails' class='openClose'>Hide Thumbnails &#9660;</a>");
        _linksDiv.find("a:first").click(function () {
            _descDiv.fadeIn($.browser.msie ? 0 : 300);
            return false;
        });
        _linksDiv.find("a:eq(1)").click(function () {
            // stop the slideshow...
            paused = true;
            $(".controls").find("a:eq(1)").attr("title", "Play").html("&#9658;");
            _linkDiv.fadeIn($.browser.msie ? 0 : 300);
            _linkDiv.find("input").each(function () {
                this.focus();
                this.select();
            });
            return false;
        });
        _linksDiv.find("a:last").click(function () {
            var self = this,
	        containers = $("#thumbsBG,.thumbsArrow"),
	        l = parseInt(containers.eq(0).css("bottom") || 0) !== 0 ? 0 : -86;
            if (self.innerHTML.indexOf("Hide Thumbnails") === 0) {
                var removed = "",
	                text = "Hide Thumbnails",
	                countLetters = 0;
                (function () {
                    countLetters++;
                    var html = self.innerHTML;
                    if (html.length > 2 && removed !== "Hide Thumbnails" && html.indexOf("&#9650;") === -1) {
                        var textLength = text.length - (countLetters === 7 ? 2 : 1);
                        removed += text.substring(textLength);
                        text = text.substring(0, textLength);
                        self.innerHTML = text + " &#9660;";
                        setTimeout(arguments.callee, 5);
                    }
                })();
            }
            $("#thumbsContainer").stop().css("visibility", "visible").animate({ "bottom": l }, 1000, "easeInOutExpo", function () {
                if (l) {
                    self.innerHTML = "&#9650;";
                    self.title = "Show Thumbnails";
                    this.style.visibility = "hidden";
                }
                else {
                    self.innerHTML = "&#9660;";
                    self.title = "Hide Thumbnails";
                }
            });
            $(".thumbsArrow").stop().animate({ "bottom": l }, 1000, "easeInOutExpo");
            $("#thumbsBG").stop().css("background", "#000").animate({ "bottom": l }, 1000, "easeInOutExpo", function () {
                if (l) {
                    this.style.background = "transparent";
                }
            });
            return false;
        });

        // create the playback controls
        var controlTimer = null;
        function controlsOver() {
            clearTimeout(controlTimer);
            $("#state").html(this.title);
        }
        function controlsOut() {
            controlTimer = setTimeout(function () {
                $("#state").html($("#state").attr("rel"));
            }, 150);
        }
        var _playCount = $("<div id='playCount'></div>");
        var _controlsDiv = $(document.createElement('div')).addClass('controls').append("<a href='#' title='View Previous Image'>&#9668;&#9668;</a> <a href='#' title='Play Slideshow'>&#9658;</a> <a href='#' title='View Next Image'>&#9658;&#9658;</a> <span id='state' rel='Paused'>Paused</span>");
        _controlsDiv.find("a:eq(0)").click(function () {
            $.galleria.prev();
            return false;
        }).mouseover(controlsOver).mouseout(controlsOut);
        _controlsDiv.find("a:eq(1)").click(function () {
            var self = this;
            clearTimeout(controlTimer);
            if (paused) {
                $("#state").html("Playing").attr("rel", "Playing");
                _linkDiv.fadeOut($.browser.msie ? 0 : 300);
                self.innerHTML = "||";
                self.title = "Pause Slideshow";
                paused = false;
                $.galleria.next();
                _playCount.text(count);
                setTimeout(function () {
                    if (!paused) {
                        if (--count < 0) {
                            $.galleria.next();
                        }
                        _playCount.text(count);
                        setTimeout(arguments.callee, 1000);
                    }
                    else {
                        _playCount.text("");
                    }
                }, 1000);
            }
            else {
                $("#state").html("Playing").attr("rel", "Paused");
                self.title = "Play Slideshow";
                self.innerHTML = "&#9658;";
                _playCount.text("");
                paused = true;
            }
            return false;
        }).mouseover(controlsOver).mouseout(controlsOut); ;
        _controlsDiv.find("a:eq(2)").click(function () {
            $.galleria.next();
            return false;
        }).mouseover(controlsOver).mouseout(controlsOut); ;

        // inject the wrapper in in the insert selector
        _insert.addClass('galleria_container').append(_div).append(_span).append(_linkDiv).append(_playCount).append("<div id='thumbsBG'></div>").parent().append(_controlsDiv).append(_linksDiv).append(_descDiv);

        //-------------
        var timer2 = null;
        return this.each(function () {

            // add the Galleria class
            $(this).addClass('galleria');

            // loop through list
            $(this).children('li').mouseover(function () {
                $(this).stop().animate({ "opacity": 1 }, 150);
            }).mouseout(function () {
                if (this.className.indexOf("active") === -1) {
                    $(this).stop().animate({ "opacity": 0.5 }, 150);
                }
            }).children("div").end().each(function (i) {

                // bring the scope
                var _container = $(this);

                // build element specific options
                var _o = $.meta ? $.extend({}, $opts, _container.data()) : $opts;

                // remove the clickNext if image is only child
                _o.clickNext = _container.is(':only-child') ? false : _o.clickNext;

                // try to fetch an anchor
                var _a = _container.find('a').is('a') ? _container.find('a') : false;

                // reference the original image as a variable and hide it
                var _img = _container.children('img').css('display', 'none');

                // extract the original source
                var _src = _a ? _a.attr('href') : _img.attr('src');

                // find a title
                var _title = _a ? _a.attr('title') : _img.attr('title');

                // find a title
                var _description = _container.find("span").html();

                // create loader image            
                var _loader = new Image();

                // check url and activate container if match
                if (_o.history && (window.location.hash && window.location.hash.replace(/\#/, '') == _src)) {
                    _container.siblings('.active').removeClass('active').mouseout();
                    _container.addClass('active').mouseover();
                }
                var done = false;
                // begin loader
                var load = function () {
                    if (done) { return; }
                    done = true;

                    //-----------------------------------------------------------------
                    // the image is loaded, let's create the thumbnail

                    var _thumb = _a ?
					    _a.find('img').addClass('thumb noscale') :
					    _img.clone(true).addClass('thumb');
                    _thumb.css("display", "none");

                    if (!_thumb.hasClass('noscale')) { // scaled tumbnails!
                        var w = Math.ceil(_img.width() / _img.height() * _container.height());
                        var h = Math.ceil(_img.height() / _img.width() * _container.width());
                        if (w < h) {
                            _thumb.css({ height: 'auto', width: _container.width(), marginTop: -(h - _container.height()) / 2 });
                        } else {
                            _thumb.css({ width: 'auto', height: _container.height(), marginLeft: -(w - _container.width()) / 2 });
                        }
                    } else { // Center thumbnails.
                        // a tiny timer fixed the width/height
                        window.setTimeout(function () {
                            _thumb.css({
                                marginLeft: -(_thumb.width() - _container.width()) / 2,
                                marginTop: -(_thumb.height() - _container.height()) / 2
                            });
                        }, 1);
                    }

                    // wrap it up...

                    // add the rel attribute
                    _thumb.attr('rel', _src);

                    // add the title attribute
                    _thumb.attr('title', _title);

                    // add the title attribute
                    _thumb.attr('description', _description);

                    // add the click functionality to the _thumb
                    _thumb.click(function () {
                        $.galleria.activate(_src);
                        return false;
                    });
                    _container.click(function () {
                        $.galleria.activate(_src);
                        return false;
                    });

                    // hover classes for IE6
                    _thumb.hover(
					    function () { $(this).addClass('hover'); },
					    function () { $(this).removeClass('hover'); }
				    );
                    _container.hover(
					    function () { _container.addClass('hover'); },
					    function () { _container.removeClass('hover'); }
				    );

                    // prepend the thumbnail in the container
                    _container.prepend(_thumb);

                    // show the thumbnail
                    _thumb.css('display', 'block');
                    _container.css("background-image", "url(" + _thumb.attr("src") + ")");

                    // call the onThumb function
                    _o.onThumb(jQuery(_thumb));

                    // check active class and activate image if match
                    if (_container.hasClass('active')) {
                        _container.click();
                    }

                    //-----------------------------------------------------------------

                    // finally delete the original image
                    _img.remove();

                };
                var error = function () {
                    alert('error');
                    // check active class and activate image if match
                    if (_container.hasClass('active')) {
                        $.galleria.activate(_src);
                    }
                };
                _loader.onload = load;
                _loader.onerror = error;
                _loader.src = _src;
                if (_loader.complete) {
                    load();
                }
            });
        });
    };

    /**
    *
    * @name NextSelector
    *
    * @desc Returns the sibling sibling, or the first one
    *
    **/

    $$.nextSelector = function (selector) {
        return $(selector).is(':last-child') ?
		   $(selector).siblings(':first-child') :
    	   $(selector).next();

    };

    /**
    *
    * @name previousSelector
    *
    * @desc Returns the previous sibling, or the last one
    *
    **/

    $$.previousSelector = function (selector) {
        return $(selector).is(':first-child') ?
		   $(selector).siblings(':last-child') :
    	   $(selector).prev();

    };

    /**
    *
    * @name hasCSS
    *
    * @desc Checks for CSS support and returns a boolean value
    *
    **/

    $$.hasCSS = function () {
        $('body').append(
		$(document.createElement('div')).attr('id', 'css_test').css({ width: '1px', height: '1px', display: 'none' })
	);
        var _v = ($('#css_test').width() != 1) ? false : true;
        $('#css_test').remove();
        return _v;
    };

    /**
    *
    * @name onPageLoad
    *
    * @desc The function that displays the image and alters the active classes
    *
    * Note: This function gets called when:
    * 1. after calling $.historyInit();
    * 2. after calling $.historyLoad();
    * 3. after pushing "Go Back" button of a browser
    *
    **/

    var failCount = 0,
        first = true,
        largePrefix = document.location.href.indexOf("stellalucaboutique.") === -1 ? "" : "bx";
    $$.onPageLoad = function (_src) {
        count = 4;
        // get the wrapper
        var _wrapper = $('.galleria_wrapper');


        if (_src) {

            // new hash location
            if ($.galleria.history) {
                //window.location = window.location.href.replace(/\#.*/,'') + '#' + _src.replace(/\/resources\/img\/feedImages\/(bx)?large\//,"");
            }
            var _thumb;
            $(".thumbWrapper a").each(function () {
                var rel = $(this).attr("href");

                if (rel && rel.indexOf(_src) >= 0) {
                    _src = rel;
                    _thumb = $(this).parent();
                    return false;
                }
            });


            // alter the active classes
            _thumb.parents('li').siblings('.active').removeClass('active').mouseout();
            _thumb.parents('li').addClass('active').mouseover();

            // define a new image
            var _img = $(new Image()).attr('src', _src).addClass('replaced');

            // empty the wrapper and insert the new image
            _wrapper.empty().append(_img).append("<img style='position:absolute;top:0;left:0;z-index:1;opacity:0;filter:alpha(opacity=0);' src='/resources/img/blank.gif' height='100%' width='100%' />");

            // insert the caption
            var caption = _thumb.attr('title'),
		    captionEl = _wrapper.siblings('.caption')
            if (!caption) {
                captionEl.fadeOut($.browser.msie ? 0 : 300);
            }
            else {
                captionEl.text(caption).fadeIn($.browser.msie ? 0 : 300);
            }
            // insert the description
            var descriptionEl = $('.description');
            descriptionEl.find("span").html(_thumb.attr('description') || "<em>no description</em>");

            _wrapper.siblings('.link').find("span").html("<span class='linkk'>Link:</span> <input type='text' value='" + document.location.toString() + "' />");

            // fire the onImage function to customize the loaded image's features
            $.galleria.onImage(_img, captionEl, _thumb, descriptionEl);

            // add clickable image helper
            if ($.galleria.clickNext) {
                _wrapper.find("img:last").css('cursor', 'pointer').click(function () { $.galleria.next(); return false; });
            }

            if (_thumb.parent()[0]) {
                centerImage(_thumb.parent()[0], $('ul.galleria'), $('ul.galleria').parent().parent());
            }


        } else {

            // remove active classes
            $('.galleria li.active').click();
        }

        if (first) {
            setTimeout(function () {
                $('.description').show();
            }, 200);
            first = false;
        }

        // place the source in the galleria.current variable
        $.galleria.current = _src;
    };

    /**
    *
    * @name jQuery.galleria
    *
    * @desc The global galleria object holds four constant variables and four public methods:
    *       $.galleria.history = a boolean for setting the history object in action with named URLs
    *       $.galleria.current = is the current source that's being viewed.
    *       $.galleria.clickNext = boolean helper for adding a clickable image that leads to the next one in line
    *       $.galleria.next() = displays the next image in line, returns to first image after the last.
    *       $.galleria.prev() = displays the previous image in line, returns to last image after the first.
    *       $.galleria.activate(_src) = displays an image from _src in the galleria container.
    *       $.galleria.onImage(image,caption) = gets fired when the image is displayed.
    *
    **/

    $.extend({ galleria: {
        current: '',
        onImage: function () { },
        activate: function (_src) {
            if ($.galleria.history) {
                $.historyLoad(_src);
            } else {
                $$.onPageLoad(_src);
            }
        },
        next: function () {
            var _next = $($$.nextSelector($('.galleria img[rel="' + $.galleria.current + '"]').parents('li'))).find('img').attr('rel');
            $.galleria.activate(_next);
        },
        prev: function () {
            var _prev = $($$.previousSelector($('.galleria img[rel="' + $.galleria.current + '"]').parents('li'))).find('img').attr('rel');
            $.galleria.activate(_prev);
        }
    }
    });
    var timer1 = null;
    function centerImage(self, galleryThumbsUL, galleryThumbs) {
        var ulWidth = galleryThumbsUL.width(),
        viewPort = galleryThumbs.width(),
        // ie doesn't do the offset correctly and returns 0, this "||" fixes it.
        offset = (self.offsetLeft !== 1 && self.offsetLeft !== 2) ? self.offsetLeft : self.parentNode.offsetLeft + self.offsetLeft,
        thisMinLeft = viewPort / 2 - offset - (self.offsetWidth / 2),
        ov = galleryThumbsUL.css("overflow"),
        move = (viewPort < ulWidth && thisMinLeft < 0 ? thisMinLeft < viewPort - ulWidth ? viewPort - ulWidth : thisMinLeft : 0);

        if (move != parseInt(galleryThumbsUL.css("left"), 10)) {
            clearInterval(timer1)
            if (parseInt($("#thumbsBG").css("bottom")) !== -86) {
                timer1 = customAnimate(galleryThumbsUL[0], move, 500, "left", timer1, "px");
            }
            else {
                galleryThumbsUL.css("left", move + "px");
            }
        }
    }
})(jQuery);


/**
 *
 * History extension for jQuery
 * Credits to http://www.mikage.to/
 *
**/


/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
    historyCurrentHash: undefined,

    historyCallback: undefined,

    historyInit: function (callback) {
        jQuery.historyCallback = callback;
        var current_hash = location.hash;

        jQuery.historyCurrentHash = current_hash;
        if (jQuery.browser.msie && jQuery.browser.version < 8) {
            // To stop the callback firing twice during initilization if no hash present
            if (jQuery.historyCurrentHash === '') {
                jQuery.historyCurrentHash = '#';
            }

            // add hidden iframe for IE
            $("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
            var ihistory = $("#jQuery_history")[0],
			    iframe = ihistory.contentWindow.document;
            iframe.open();
            iframe.close();
            iframe.location.hash = current_hash;
        }
        else if ($.browser.safari) {
            // etablish back/forward stacks
            jQuery.historyBackStack = [];
            jQuery.historyBackStack.length = history.length;
            jQuery.historyForwardStack = [];

            jQuery.isFirst = true;
        }

        //jQuery.historyCallback(current_hash.replace(/^#/, ''));
        setInterval(jQuery.historyCheck, 500);
    },

    historyAddHistory: function (hash) {
        // This makes the looping function do something
        jQuery.historyBackStack.push(hash);

        jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
        this.isFirst = true;
    },

    historyCheck: function () {
        var current_hash;
        if (jQuery.browser.msie && jQuery.browser.version < 8) {
            // On IE, check for location.hash of iframe
            var ihistory = $("#jQuery_history")[0],
			    iframe = ihistory.contentDocument || ihistory.contentWindow.document,
			    current_hash = iframe.location.hash;
            if (current_hash != jQuery.historyCurrentHash) {
                location.hash = current_hash;
                jQuery.historyCurrentHash = current_hash;
                jQuery.historyCallback(current_hash.replace(/^#/, ''));
            }
        } else if ($.browser.safari) {
            if (!jQuery.dontCheck) {
                var historyDelta = history.length - jQuery.historyBackStack.length;

                if (historyDelta) { // back or forward button has been pushed
                    jQuery.isFirst = false;
                    var i;
                    if (historyDelta < 0) { // back button has been pushed
                        // move items to forward stack
                        for (i = 0; i < Math.abs(historyDelta); i++) {
                            jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
                        }
                    } else { // forward button has been pushed
                        // move items to back stack
                        for (i = 0; i < historyDelta; i++) {
                            jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
                        }
                    }
                    var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
                    if (cachedHash !== undefined) {
                        jQuery.historyCurrentHash = location.hash;
                        jQuery.historyCallback(cachedHash);
                    }
                } else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] === undefined && !jQuery.isFirst) {
                    // back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
                    // document.URL doesn't change in Safari
                    if (document.URL.indexOf('#') >= 0) {
                        jQuery.historyCallback(document.URL.split('#')[1]);
                    } else {
                        current_hash = location.hash;
                        jQuery.historyCallback('');
                    }
                    jQuery.isFirst = true;
                }
            }
        } else {
            // otherwise, check for location.hash
            current_hash = location.hash;
            if (current_hash != jQuery.historyCurrentHash) {
                jQuery.historyCurrentHash = current_hash;
                jQuery.historyCallback(current_hash.replace(/^#/, ''));
            }
        }
    },
    historyLoad: function (hash) {
        if (!hash) { return; }
        var newhash;


        if (jQuery.browser.safari) {
            newhash = hash;
        }
        else {

            newhash = '#' + hash;
            if(jQuery.historyCurrentHash){
                location.hash = newhash;
            }
        }
        jQuery.historyCurrentHash = newhash;
        if (jQuery.browser.msie && jQuery.browser.version < 8) {
            var ihistory = $("#jQuery_history")[0];
            var iframe = ihistory.contentWindow.document;
            iframe.open();
            iframe.close();
            iframe.location.hash = newhash;
            jQuery.historyCallback(hash);
        }
        else if (jQuery.browser.safari) {
            jQuery.dontCheck = true;
            // Manually keep track of the history values for Safari
            this.historyAddHistory(hash);

            // Wait a while before allowing checking so that Safari has time to update the "history" object
            // correctly (otherwise the check loop would detect a false change in hash).
            var fn = function () { jQuery.dontCheck = false; };
            window.setTimeout(fn, 200);
            jQuery.historyCallback(hash);
            // N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
            //      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
            //      URL in the browser and the "history" object are both updated correctly.
            location.hash = newhash;
        }
        else {
            jQuery.historyCallback(hash);
        }
    }
});


var minTimeout=1,
    customAnimate = function(who,destination,duration,prop,timer,unit){
    var duration=duration,
        startTime=+new Date,
        style=who.style,
        last=0,
        startValue=parseInt(style[prop]||0),
        diff=destination-startValue,
        durate=duration,
        // >> 1 divides by 2...(then lops off any decimals)...
        halfTime=durate >> 1,
        halfDistance=unit=="px" ? diff >> 1 : diff / 2 ,
        step = function(){
            var timeDiff=new Date-startTime;
            // if the difference between now and when we started is larger or equal to the the duration stop everything!
            if(timeDiff>=duration){
                // time is up...we need to be done now...
                // make sure we are where we need to be...
                // stop the timer...
                clearInterval(timer);
                who.style[prop]=destination+unit;
            }
            else{
                // animate...
                var n=easeInOutExpo(timeDiff);
                // don't update unless we have to...
                if(n!==last){
                    style[prop]=(last=n)+unit;
                }
            }
        },
        // taken from robert penners easing equations port to javascript. Its been cleaned up for maximum performance...
        easeInOutExpo=unit==="px"?function(t){return ~~(halfDistance*((t/=halfTime)<1?Math.pow(2,10*(t-1)):-Math.pow(2,-10*(t-1))+2)+startValue);} :
            function(t){return (halfDistance*((t/=halfTime)<1?Math.pow(2,10*(t-1)):-Math.pow(2,-10*(t-1))+2)+startValue);}
    step();
    return setInterval(step,minTimeout);
}