var teasers = new Array;
var fadedLeft = new Array;
var teaser = {
	init: function(ids) {
		for(var i=0; i<ids.length; i++) {
			var id = ids[i];
			teasers.push({
				tid: parseInt(id),
				marginright: jQuery('#teaser'+ids[i]).css('margin-left'),
				zindex: parseInt(jQuery('#teaser'+ids[i]).css('z-index')),
				twidth: jQuery('#teaser'+ids[i]).css('width')
			});
		}
		this.slide(ids)
	},
	slide: function(ids) {
		for(var i=0; i < ids.length; i++) {
			var c1 = i;
			jQuery("#overlayer"+ids[c1]).click(function() {
				for(var j=0; j < teasers.length; j++) {
					var c2 = j;
					if(fadedLeft.inArray(this.id) && typeof teasers[c2+1] !== 'undefined' 
					&& teasers[c2+1].zindex < parseInt(jQuery(this).css('z-index'))) {
						teaser.fadeRight(this.id, c2, teasers[c2+1].tid, teasers[c2].tid);
					}
					if(!fadedLeft.inArray(this.id) 
					&& teasers[c2].zindex > parseInt(jQuery(this).css('z-index'))) {
						teaser.fadeLeft(this.id, c2, teasers[c2-1].tid, teasers[c2].tid)
					} 
				}
			})
		}
	},
	fadeRight: function(thisid, index, tid, olid) {
		jQuery('#overlayer'+olid).animate({
			width: teasers[index].twidth
		}, 500, 'swing', function() {
			jQuery('#'+thisid).animate({
				width: teasers[index].twidth
			}, 500, 'swing', function() {
				jQuery('#teaser'+tid).animate({
					width: teasers[index].twidth
				}, 500, 'swing', function() {
					jQuery('#'+thisid).fadeOut(300, function() {
						if('overlayer'+olid !== this.id) {
							jQuery('#overlayer'+olid).fadeIn(300);
						}
						if(fadedLeft.inArray('overlayer'+tid)) {
							fadedLeft = fadedLeft.remove('overlayer'+tid);
						}
					})
				})
			})
		})
	},
	fadeLeft: function(thisid, index, tid, olid) {
		jQuery('#overlayer'+olid).fadeIn(300, function() {
			jQuery('#teaser'+olid).animate({
				width: '30px'
			}, 500, 'swing', function() {
				jQuery('#overlayer'+olid).animate({
					width: '30px'
				}, 500, 'swing', function() {
					if('overlayer'+tid === thisid) {
						jQuery('#overlayer'+tid).fadeOut(300)
//						jQuery('#overlayer'+tid).animate({ width: '0px' }, 300)
					}
					if(!fadedLeft.inArray('overlayer'+olid)) {
						fadedLeft.push('overlayer'+olid)
					}
				})
			})
		})
	}
}

// IE doesn't like indexOf applied on numerical arrays ...
// and I don't like jQuery's inArray() method
Array.prototype.inArray = function(needle) {
	for(var i=0; i<this.length; i++) {
		if(needle === this[i]) return true;
	} 
	return false;
}

// array.remove returns a new array
// use array = array.remove(needle) 
// rather than array.remove(needle)
Array.prototype.remove = function(needle) {
	var tmpArr = new Array;
	if(this.inArray(needle)) {
		for(var i=0; i<this.length; i++) {
			if(this[i] !== needle) {
				tmpArr.push(this[i])
			}
		}
		return tmpArr;
	}
	return this;
}

