var $js = jQuery.noConflict();
$js(function(){
	
	$js('div.slideshow-container').each(function(i) {

		$js(this).children('img').each(function(i) {
			$(this).hide();
		});
		var imgLoader = document.createElement('img');
		imgLoader.src = '../images/loader.gif';
		imgLoader.className = 'loader';
		this.appendChild(imgLoader);
		$js(this).children('div').hide();

	});
	
});

$js(window).load(function() {
    var slideshows = [];
	$js('div.slideshow-container').each(function(i){
        slideshows.push(new SlideshowJS(this, $js(this).children('img').not('.loader'), $js(this).children('div.slideshow-title'), $js(this).children('div.filmstrip')));
    });
	$js(slideshows).each(function() {
		this.start();
	});
});

var SlideshowJS = function(container, images, titlebar, filmstrip) {

    this.container = container;
    this.images = images;
	this.titlebar = titlebar;
	this.controlContainer = null;
	this.filmstrip = filmstrip ? filmstrip : null;
	this.filmstripImages = this.filmstrip ? $js(filmstrip).children('img') : null;
	this.filmstripFrames = this.filmstrip ? [] : null;
    this.activeImage = null;
    this.nextImage = null;
    this.fade = false;
    this.fadeDuration = -1;
    this.maxWidth = -1;
    this.maxHeight = -1;
    this.slideshowDuration = -1;
	this.limitCounter = 1;
    this.limit = -1;
	this.hasTitle = false;
	this.titleHover = false;
	this.PE = null;
	this.id = Math.round(Math.random() * 1000);
    this._init();
    
}

SlideshowJS.prototype._init = function(){

    var This = this;
    var curParam = null;
	var params = null;

    $js(this.images).each(function(i){
    
        if (i === 0) {
            This.activeImage = this;
        }

        if (This.maxWidth < $js(this).width()) {
            This.maxWidth = $js(this).width();
        }
        if (This.maxHeight < $js(this).height()) {
            This.maxHeight = $js(this).height();
        }
        
    });

    params = this.container.className.split(' ').slice(1);
    for (var i = 0, len = params.length; i < len; ++i) {
    
        curParam = params[i].toLowerCase().split(':');
        switch (curParam[0]) {
			
            case 'auto':
				this.auto = true;
                this.slideshowDuration = curParam[1] > 0 ? curParam[1] : 1;
				this.PE = new PE(function() {
					This._nextImage();
				}, This.slideshowDuration);
                break;
                
            case 'manual':
				this.auto = false;
                $js(this.container).children('img').click(function(){
                    This._nextImage();
                });
                break;
                
            case 'fade':
                this.fade = true;
                this.fadeDuration = curParam[1] > 0 ? curParam[1] * 1000 : 1000;
                break;
                
            case 'random':
                this._randomize(this.images);
                break;
                
            case 'limit':
                this.limit = curParam[1] - 1;
                break;
                
			case 'title':
				if($js(this.titlebar).get(0) === undefined) {
					throw ('Slideshow JS - No titlebar division found')
				} else {
					this.hasTitle = true;
				}
				this.titleHover = true;
				if(curParam[1] === 'slide') {
					$js(this.container).hover(function() {
						$js(This.titlebar).slideDown();
					}, function() {
						$js(This.titlebar).slideUp();
					});	
				} else if(curParam[1] === 'fade') {
					$js(this.container).hover(function() {
						$js(This.titlebar).fadeIn();
					}, function() {
						$js(This.titlebar).fadeOut();
					});	
				} else {
					this.titleHover = false;
					$js(this.titlebar).show();
				}
				break;
			
			case 'control':
				this._configureControls();
				break;
			
            default:
                throw ('Slideshow JS - Unrecognized parameter.');
                break;
                
        }
        
    }
    
    $js(this.container).css({
        width: this.maxWidth,
        height: this.maxHeight,
        position: 'relative',
        textAlign: 'center',
        cursor: 'pointer'
    });
	
	if(this.filmstrip !== null) {
		this._configureFilmstrip();	
	}
	
    $js(this.images).each(function(i){
    
        var margin = -1;
        $js(this).css({
            position: 'relative',
            float: 'left',
            marginLeft: (This.maxWidth / 2) - ($js(this).outerWidth() / 2)
        });
        
        margin = '-' + $js(this).outerHeight() + 'px';
        if ($js(this).css('margin-bottom') !== margin) {
            $js(this).css({
                marginBottom: margin
            });
        }
        
    });
    
}

SlideshowJS.prototype.start = function() {	

	if($js(this.titlebar) !== null) {
		$js(this.titlebar).html(this.activeImage.alt);		
	}
	$js(this.activeImage).fadeIn();
	$js(this.filmstrip).fadeIn();
	
	if(this.auto === true) {
		this.PE.start();	
	}

	$js('img.loader').each(function(i) {
		$js(this).hide();
	}).remove();
	
}

SlideshowJS.prototype._nextImage = function(bShowPrevious){
	
	var This = this;
    var currentIndex = this.images.index(this.activeImage);
	var titlebar = null;
	var nextImage = null;
	
	if(this.limit != -1 && this.limit == this.limitCounter) {
		this.PE.stop();
	} else {
		this.limitCounter++;
	}
	
	if(bShowPrevious) {
		if(this.images.index(this.activeImage) === 0) {
			this._makeActive(this.images.length - 1);
		} else {
			this._makeActive(currentIndex - 1);
		} 
	} else {
		if (this.images.index(this.activeImage) === this.images.length - 1) {
			this._makeActive(0);
    	} else {
			this._makeActive(currentIndex + 1);
    	}
	} 
	
} 

SlideshowJS.prototype._makeActive = function(index, slideshow) {

	this.nextImage = this.images[index];

	var titlebar = this.titlebar;
	var nextImage = this.nextImage;
    if (this.fade === true) {
		
        $js(this.activeImage).fadeOut(this.fadeDuration);
		$js(this.nextImage).fadeIn(this.fadeDuration);
		
		if (this.titlebar.get(0) !== null && this.hasTitle === true && this.titleHover === false) {
			$js(titlebar).fadeOut(this.fadeDuration / 2, function() {
				$js(titlebar).html(nextImage.alt);			
			}).fadeIn(this.fadeDuration / 2);
		} else {
			$js(titlebar).html(nextImage.alt);	
		}
		
    } else {
        $js(this.activeImage).hide();
		$js(this.titlebar).html(this.nextImage.alt);
        $js(this.nextImage).show();
    }
    
	this.activeImage = this.nextImage;
    this.nextImage = null;

}

SlideshowJS.prototype._randomize = function(images){

    var n = images.length;
    var k = -1;
    var temp = -1;
    
    while (n > 1) {
    
        k = Math.round(Math.random(n * 1000));
        n--;
        temp = images[n]; 
        images[n] = images[k];
        images[k] = temp;
        
    }
    
} 
 
SlideshowJS.prototype._configureControls = function() {
	
	var This = this;
	var eLeft = document.createElement('div');
	var backImg = document.createElement('img');
	backImg.src = '../images/controls/back.png';
	eLeft.appendChild(backImg);
	
	var eRight = document.createElement('div');
	var rightImg = document.createElement('img');
	rightImg.src = '../images/controls/next.png';
	eRight.appendChild(rightImg);

	var eCenter = document.createElement('div');
	var pauseImg = document.createElement('img');
	pauseImg.src = '../images/controls/pause.png';
	eCenter.appendChild(pauseImg);
	
	$js(eLeft).css({
		color: 'rgb(255, 255, 255)',
		left: '0',
		top: (This.maxHeight / 2) - (backImg.height / 2),
		position: 'absolute',
		background: 'rgb(0 , 0, 0)'
	});
	$js(eLeft).click(function() {
		This._nextImage(true);
	});

	$js(eRight).css({
		color: 'rgb(255, 255, 255)',
		right: '0',
		top: (This.maxHeight / 2) - (rightImg.height / 2),
		position: 'absolute',
		background: 'rgb(0 , 0, 0)'
	});
	$js(eRight).click(function() {
		This._nextImage();
	});

	$js(eCenter).css({
		color: 'rgb(255, 255, 255)',
		top: (This.maxHeight / 2) - (pauseImg.height / 2),
		position: 'absolute',
		background: 'rgb(0, 0, 0)'
	});
	if(!$js.browser.msie) {
		$js(eCenter).css({
			marginLeft: (This.maxWidth / 2) - (pauseImg.width / 2)
		});
	}
	
	$js(eCenter).click(function() {
		if(This.PE === null) {
			This.PE = new PE(null, null);
		}
		This.PE.toggle(this);
	});
	
	this.controlContainer = document.createElement('div');
	this.controlContainer.appendChild(eLeft);
	this.controlContainer.appendChild(eCenter);
	this.controlContainer.appendChild(eRight);
	$js(this.controlContainer).css({
		width: This.maxWidth,
		left: 0,
		top: 0,
		position: 'absolute',
		display: 'none'
	});
	$js(this.controlContainer).hide();
	
	$js(this.container).hover(function() {
		$js(This.controlContainer).fadeIn();
	}, function() {
		$js(This.controlContainer).fadeOut();
	});

	this.container.appendChild(this.controlContainer);
	
}
 
SlideshowJS.prototype._configureFilmstrip = function() {
	
	var This = this;
	
	var runningSum = 0;
	var width = this.maxWidth;
	var ul = document.createElement('ul');
	ul.className = 'filmstrip';
	var li = document.createElement('li');

	for(var i = 0, len = this.filmstripImages.length; i < len; i++) {
		
		var curImage = this.filmstripImages[i];
		var curWidth = curImage.width + parseInt($js(curImage).css('margin-left'), 10) + parseInt($js(curImage).css('margin-right'), 10);;

		if((curWidth + runningSum) <= width) {
			li.appendChild(curImage);
			runningSum += curWidth;
		} else {
			ul.appendChild(li);
			this.filmstripFrames.push(li);
			li = document.createElement('li');
			li.appendChild(curImage);
			runningSum = curWidth;
		}

		if(i === len - 1) {
			li.appendChild(curImage);
			ul.appendChild(li);
			this.filmstripFrames.push(li);
		}
		$js(li).hide();
		
		$js(curImage).click(function(e) {
			This._makeActive(This.filmstripImages.index(this));
		});
		
	} 

	if(this.filmstripFrames.length !== 0) {
		//this.filmstripFrames[0].className = 'activeframeset';
		this.filmstripFrames[0].className = this.id;
		$js(this.filmstripFrames[0]).show();
		$js(this.filmstrip).get(0).appendChild(ul);
	}

	$js(this.filmstrip).css({
		left: 0,
		top: This.maxHeight,
		width: This.maxWidth,
		position: 'absolute'
	});
	
	if(this.filmstripFrames.length > 1) {
	
		var prevControl = document.createElement('div');
		$js(prevControl).css({
			color: 'rgb(255, 255, 255)',
			left: 0,
			bottom: 0,
			position: 'absolute'
		}).click(function() {
			This._updateFrameset(false);
		});
		var prevImg = document.createElement('img');
		prevImg.src = '../images/controls/filmstripPrevious.png';
		prevControl.appendChild(prevImg);
		this.filmstrip.get(0).appendChild(prevControl);
		
		var nextControl = document.createElement('div');
		$js(nextControl).css({
			color: 'rgb(255, 255, 255)',
			right: 0,
			bottom: 0,
			position: 'absolute'
		}).click(function() {
			This._updateFrameset(true);
		});
		var nextImg = document.createElement('img');
		nextImg.src = '../images/controls/filmstripNext.png';
		nextControl.appendChild(nextImg);
		this.filmstrip.get(0).appendChild(nextControl);
		
	}
	
}
 
SlideshowJS.prototype._updateFrameset = function(bGoForward) {
	
	//var currentIndex = $js(this.filmstripFrames).index($js('li.activeframeset'));//activeframeset'));
	var currentIndex = $js(this.filmstripFrames).index($js('li.' + this.id));//activeframeset'));
	var nextFrameset = null;
	var activeFrameset = this.filmstripFrames[currentIndex];
			var This = this;
	if(bGoForward === true) {
		
		if(currentIndex === this.filmstripFrames.length - 1) {
			nextFrameset = this.filmstripFrames[0]
		} else {
			nextFrameset = this.filmstripFrames[currentIndex + 1];
		}
		

		$js(activeFrameset).toggle('slide', {
			direction: 'right'
		}, 400, function() {
			//nextFrameset.className = 'activeframeset';
			nextFrameset.className = This.id;
			$js(nextFrameset).toggle('slide', {
				direction: 'left'
			}, 400);
			activeFrameset.className = '';
		});
		
	} else {
		
		if(currentIndex === this.filmstripFrames.length - 1) {
			nextFrameset = this.filmstripFrames[0]
		} else {
			if(currentIndex === 0) {
				currentIndex = this.filmstripFrames.length - 1;
			} else {
				currentIndex = currentIndex - 1;
			}
			nextFrameset = this.filmstripFrames[currentIndex];
		}
		
		//$js('li.activeframeset').toggle('slide', {
		$js('li.' + this.id).toggle('slide', {
			direction: 'left'
		}, 400, function() {
			//nextFrameset.className = 'activeframeset';
			nextFrameset.className = This.id;
			$js(nextFrameset).toggle('slide', {
				direction: 'right'
			}, 400);
			activeFrameset.className = '';
		});
		
	}
	
}

var PE = function(callback, frequency) {
	this.callback = callback;
	this.frequency = frequency;
	this.timer = null;
	this.isRunning = false;
}

PE.prototype.start = function() {
	this.timer = setInterval(this.callback, this.frequency * 1000);
	this.isRunning = true;
}

PE.prototype.stop = function() {
	clearInterval(this.timer);
	this.timer = null;
	this.isRunning = false;
}

PE.prototype.toggle = function(container) {
	if(this.isRunning === true) {
		this.stop();
		var resumeImg = document.createElement('img');
		resumeImg.src = '../images/controls/resume.png';
		$js(container).html(resumeImg);
	} else {
		this.start();
		var pauseImg = document.createElement('img');
		pauseImg.src = '../images/controls/pause.png';
		$js(container).html(pauseImg);
	}
}
var $ = jQuery.noConflict();
