/*
Copyright (c) 2007 - Fabien Udriot fabien.udriot (at) ecodev.ch
- script improvement :
	* navigation in the gallery with right left arrow.
	* colored thumbnail background 
	* jquery + typo3 integration
	* cross browser improvement 
	* other miscellaneous improvements...

Original script gallery : 
Copyright (c) 2005 - Alf Magne Kalleland post@dhtmlgoodies.com
Get this and other scripts at www.dhtmlgoodies.com	
You can use this script freely as long as this copyright message is kept intact.
*/

var imageGalleryLeftPos = false;
var imageGalleryWidth = false;
var imageGalleryObj = false;
var maxGalleryXPos = false;
var slideSpeed = 0;
var imgPadding = 3;
var imageGalleryCaptions = new Array();
//variable added by Fabien 23.09.06
var imgLastNo = -1;
var imgNo = 1;
var speed = 20; 
var slideOrigin = 39 // the slide show origin
var limit = 0 + slideOrigin; // == the slide width
var doTranslate = false; 

// slideWidth = {SLIDE_WIDTH} // the slide width
// imagePath = {PATH} defined in the html page


$(document).ready(function() {
	$('#theImages a').click(showPreview);
	if($('#theImages').size() > 0){ //init the first time only if it is the player alone
		initSlideShow();
	}
	$(document).keyup(keyNavigation);
});

function keyNavigation(e){
	var keycode = e.keyCode;
	
	if(keycode == 39){ //right
		if(imgNo < galleryImgs.length){
			showPreview($('#theImages a:eq('+ imgNo +')'),true);
		}
	}
	else if(keycode == 37){ //left
		if((imgNo -2) >= 0){
			showPreview($('#theImages a:eq('+ (imgNo - 2) +')'),true);
		}
	}
}
/**
 * When the mouse goes OVER a ARROW
 */
function overSlide(){
	if(this.id == 'arrow_left'){
		var side = 'left-';
	}
	else{
		var side = 'right-';
	}
	
	var arrow = 'arr-' + side + thumbSize
	if($.browser.msie){
		$('#'+arrow).attr("src",imagePath + arrow + '-over.gif');
	}
	else{
		$('#'+arrow).attr("src",imagePath + arrow + '-over.png');
	}
}

/**
 * When the mouse goes OUT a ARROW
 */
function outSlide(){
	if(this.id == 'arrow_left'){
		var side = 'left-';
	}
	else{
		var side = 'right-';
	}
	
	var arrow = 'arr-' + side + thumbSize
	if($.browser.msie){
		$('#'+arrow).attr("src",imagePath + arrow + '.gif');
	}
	else{
		$('#'+arrow).attr("src",imagePath + arrow + '.png');
	}
}

/**
 * When the user clicks on the slider right or left
 * @param {Object} e
 */
function startSlide(e){
	doTranslate = true;
	if(document.all)e = event;
	var id = this.id;
	if(this.id=='arrow_right'){
		var direction = 'right';
		var stopPosition = imageGalleryObj.offsetLeft - slideWidth;
	}
	else{
		var direction = 'left';
		var stopPosition = imageGalleryObj.offsetLeft + slideWidth;
	}
	translate(stopPosition,direction); //tells the limit
}

/**
 * When the mouse is OVER a THUMBNAIL
 * @param {Object} e
 */
function showImage(){
	if($.browser.msie){
		this.style.filter = 'alpha(opacity=99)';
	}
	else{
		$(this).attr('style','opacity:0.99');
	}
}


/**
 * When the mouse goes OUT a THUMBNAIL
 * @param {Object} e
 */
function releaseImage(){
	$(this).removeAttr('style');
}

/* TRANSLATE THE THUMBNAIL */
function translate(stopPosition,direction){
	//wait one click before going forward
	if(doTranslate){ 
		var increment = speed;
		if(direction == 'right') //change the direction
			increment = -increment;
		var leftPos = imageGalleryObj.offsetLeft/1 + increment; //new position
		
		if(maxGalleryXPos >= leftPos && minGalleryXPos <= leftPos){ //check the end of the gallery
			imageGalleryObj.style.left = leftPos + 'px';
			//stop recursive condition		
			if(direction == 'right'){
				if(stopPosition < imageGalleryObj.offsetLeft){
					setTimeout("translate("+ stopPosition +",'"+ direction +"')",20);
				}
			}
			else{
				if(stopPosition > imageGalleryObj.offsetLeft){
					setTimeout("translate("+ stopPosition +",'"+ direction +"')",20);
				}
			}
		}	
	}
	else{
		doTranslate = true;
	}
}

/* MAIN METHOD */
function initSlideShow(){
	$('#arrow_left').mouseover(overSlide);
	$('#arrow_left').click(startSlide);
	$('#arrow_left').mouseout(outSlide);
	
	$('#arrow_right').mouseover(overSlide);
	$('#arrow_right').click(startSlide);
	$('#arrow_right').mouseout(outSlide);
	$('#theImages img').mouseout(releaseImage);
	
	imageGalleryObj = document.getElementById('theImages');
	
	imageGalleryLeftPos = imageGalleryObj.offsetLeft;
	imageGalleryWidth = $('#galleryContainer').get(0).offsetWidth - 80;
	
	maxGalleryXPos = imageGalleryObj.offsetLeft 
	minGalleryXPos = imageGalleryWidth - $('#slideEnd').get(0).offsetLeft
	
	$('#theImages IMG').mouseover(showImage); //over a thumbnail
	$('#theImages IMG').mousemove(showImage);
	
	//prepare the image caption
	var divs = $('#theImages .imageCaption');
	for(var no=0;no<divs.size();no++){
		imageGalleryCaptions[no] = $(divs).get(no).innerHTML;
	}
	
	echo('Gallery express inited');
}

function showPreview(el,keyEvent){
	if(typeof(keyEvent) == 'undefined'){
		el = this;
	}
	
	$('#theImages a').removeClass('selected');
	$(el).addClass('selected'); // make a nice colored background
	var uid = $(el).find('IMG').attr('id'); //the id looks like thumbNo[0-9]
	imgNo = uid.substr(7,uid.length) - 0; //extract the last numero
	
	//do something ONLY if it is NOT the same picture
	if(imgLastNo != imgNo){
			
		var imgElWidth = $(el).find('IMG').attr('width') - 0;
		
		//correct the padding. IE is too stupid !!
		if(!$.browser.msie){
			imgElWidth += imgPadding;
		}
		else{
			imgElWidth += imgPadding - 8; //TODO : check this value
		}
		
		if(imgLastNo < imgNo){ //avoid a second click on the same image
			var direction = 'right';
			var stopPosition = imageGalleryObj.offsetLeft - imgElWidth;
		}
		else{
			var direction = 'left';
			var stopPosition = imageGalleryObj.offsetLeft + imgElWidth;
		}
		translate(stopPosition,direction); //tells the limit
		
		//for the firstImage don't move the slider
		if(imgNo == 1 && direction == 'left') {
			setTimeout('doTranslate = false;',500);
		}
		imgLastNo = imgNo;
		$('#waitMessage').removeClass('hidden');
		
		var img = $('#previewPane IMG:eq(0)'); //take the first which is the gallery image, the second is the loading...
		var curImg = getCurImg(imgNo)
		$(img).bind('load',{uid:curImg},hideWaitMessageAndShowCaption)		
		//reslve a SAFARI bug. (for the last image which the same)
		if($(img).attr('src') == galleryImgs[curImg]){
			$(img).attr('src','');
		}
		$(img).attr('src',galleryImgs[curImg]);
	}
	return false;	
}

/* hide the wait message */	
function hideWaitMessageAndShowCaption(e){
	$('#waitMessage').addClass('hidden');
	$('#largeImageCaption').html(imageGalleryCaptions[e.data.uid]);
	$('#imageSrc').attr('href',originalImgs[e.data.uid]);
}

/**
 * return the real image to display. Handle the last image exception
 */
function getCurImg(imgNo){
	if(typeof(galleryImgs[imgNo]) != 'undefined'){ //check if there is one more image OR if it is the last image
		var curImg = imgNo - 1;
	}
	else{
		var curImg = imgNo-2;
	}
	return curImg;
}

/* UTIL */
function echo(data){
	try{
		dump(data+"\n");
		console.log(data);
	}
	catch(e){
		e = null;
	}
}

/* URL PARSER */
if (typeof Poly9 == 'undefined')
 var Poly9 = {};

Poly9.URLParser = function(url) {
 this._fields = {'Username' : 4, 'Password' : 5, 'Port' : 7, 'Protocol' : 2, 'Host' : 6, 'Pathname' : 8, 'URL' : 0, 'Querystring' : 9, 'Fragment' : 10};
 this._values = {};
 this._regex = null;
 this.version = 0.1;
 this._regex = /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/;
 for(var f in this._fields)
  this['get' + f] = this._makeGetter(f);
 if (typeof url != 'undefined')
  this._parse(url);
}

Poly9.URLParser.prototype.setURL = function(url) {
  this._parse(url);
}

Poly9.URLParser.prototype._initValues = function() {
   for(var f in this._fields)
   this._values[f] = '';
}

Poly9.URLParser.prototype._parse = function(url) {
  this._initValues();
  var r = this._regex.exec(url);
  if (!r) throw "DPURLParser::_parse -> Invalid URL"
  for(var f in this._fields) if (typeof r[this._fields[f]] != 'undefined')
   this._values[f] = r[this._fields[f]];
}

Poly9.URLParser.prototype._makeGetter = function(field) {
 return function() {
  return this._values[field];
 }
}


