var ImageTeaser = Class.extend({ // *** URL_REGEXP : /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/, _domElement : null, _changeMs : 0, _changeTimer : null, _streams : {currentIndex : 0, pools : []}, init : function(config){ if( $.isPlainObject(config) && (typeof config.id === 'string') && (typeof config.changeMs === 'number') && $.isArray(config.streams) ){ this._domElement = $('#' + config.id); this._changeMs = config.changeMs; for( var i = 0; i < config.streams.length; i++ ){ if( $.isArray(config.streams[i]) ){ this._streams.pools[i] = {currentIndex : 0, urls : []}; for( var j = 0; j < config.streams[i].length; j++ ){ if( this.URL_REGEXP.test(config.streams[i][j]) ){ this._streams.pools[i].urls[j] = config.streams[i][j]; } else { throw 'one of the streams contains a non-url'; } } } else { throw 'one of the given streams is not an array'; } } this._changeTimer = window.setInterval($.proxy(this.change, this), this._changeMs); } else { throw 'cannot initialize imageteaser, missing params or wrong param type(s)'; } }, // *** // xxx destroy : function(){ window.clearInterval(this._changeTimer); this.changeMs = 0; this._streams = {}; }, // xxx //--|FUNCTIONALITY---------- change : function(){ var that = this; var nextStreamIndex = this.getRandomIndex(this._streams.pools.length); while( nextStreamIndex == this._streams.currentIndex ){ nextStreamIndex = this.getRandomIndex(this._streams.pools.length); } var nextImageIndex = this.getRandomIndex(this._streams.pools[nextStreamIndex].urls.length); while( nextImageIndex == this._streams.pools[nextStreamIndex].currentIndex ){ nextImageIndex = this.getRandomIndex(this._streams.pools[nextStreamIndex].urls.length); } var nextEntry = this._domElement.find('li').eq(nextStreamIndex); var nextImage = new Image(); nextImage.onload = function(){ that.switchImages(nextEntry, nextImage); }; nextImage.src = this._streams.pools[nextStreamIndex].urls[nextImageIndex]; this._streams.currentIndex = nextStreamIndex; this._streams.pools[nextStreamIndex].currentIndex = nextImageIndex; }, getRandomIndex : function(firstNot){ return Math.floor(Math.random() * firstNot); }, switchImages : function(targetEntry, targetImage){ oldImg = targetEntry.children('a:first'); newImg = oldImg.clone().hide(); newImg.css('background-image', 'url(' + targetImage.src + ')'); targetEntry.append(newImg); execute = function(){ oldImg.remove(); }; oldImg.fadeOut('1500'); newImg.fadeIn('1500', execute); } });