//On DOM ready
window.addEvent('domready', function() {
	addEventPrimary();
	//load and count sets...
	countSets();
	//navigation bar
	loadThumbnailNavigation();
	//sure gallery is stoped
	stopGalleryShow();
	//prepare Slideshow big photos...
	prepareSlideShow();
});


//On load... when everything is loaded...
window.addEvent('load',function() {
	// Hide the load banner
	hideLoading();
	//begin the Galleryshow...
	GalleryShowPhotos();
});

//slideshow...
var prepareSlideShow = function() { //prepare and create elementes for slideshow
	var backgroundGrey = new Element('div', {
		'id' : 'slideShowBackground',
		'styles': {
			'height': winH,
			'width': winW
		}
	}).inject($('footer'), 'after');
	var myDrag = $('slideShowBackground').makeDraggable();
	
	//close the slideshow button
	var showclose = new Element('div', {
		'id' : 'showClose',
		'class' : 'showClose'
	}).inject($('slideShowBackground'));
	$('showClose').set('text', 'Close X');
	$('showClose').addEvent('click', function() {
		hideSlideShow();
		GalleryShowPhotos();
	});
	//photo container
	var photoContainer = new Element('div', {
		'id' : 'photoContainer',
		'class' : 'photoContainer'
	}).inject('slideShowBackground');
		var nPoto = new Element('img', {
			'id' : 'loading_slideshow',
			'src' : '/pages/images/ajax-loader.gif',
			'width' : 100,
			'height' : 100,
			'alt' : 'loading...'
		}).inject('photoContainer');
		var Caption = new Element('div', {
			'id' : 'captionSlideShow',
			'class' : 'caption'
		}).inject($('photoContainer'));
	//play controls
	var playControlView = new Element('div', {
		'id' : 'playControlView'
	}).inject('slideShowBackground');
	var playControl = new Element('div', {
		'id' : 'playControl'
	}).inject('slideShowBackground');
		var playControlPrev = new Element('div', {
			'id' : 'ControlPrev'
		}).inject('playControl');
			$('ControlPrev').addEvent('click', function() {
				previousPhotoSlideShow();
			});
		var playControlPlay = new Element('div', {
			'id' : 'ControlPlayPause'
		}).inject('playControl');
			$('ControlPlayPause').addEvent('click', function() {
				playpauseSlideShow();
			});
		var playControlNext = new Element('div', {
			'id' : 'ControlNext'
		}).inject('playControl');
			$('ControlNext').addEvent('click', function() {
				nextPhotoSlideShow();
			});
		checkplaypauseControl();

	//banner over primPhoto showing click to slideshow
	var controlRun = new Element('div', {
		'id' : 'showSlideShowContainer'
	}).inject('showPhotos');
	var control = new Element('div', {
		'id' : 'showSlideShow'
	}).inject('showSlideShowContainer');
	$('showSlideShow').set('text', 'Click to view bigger photos');
	var myHorizontalSlide = new Fx.Slide('showSlideShow', {mode: 'horizontal'});
	$('primPhoto').addEvent('mouseover', function(e){
		myHorizontalSlide.slideIn();
	});
	$('primPhoto').addEvent('mouseout', function(e){
		myHorizontalSlide.slideOut();
	});
	$('primPhoto').fireEvent('mouseout');
	//preload first photo...
	preLoadPhotos(0, false);
	return true;
};
var preLoadPhotos = function(n, loadIn) { //preload big photos for slideshow, ajax async.
	if($('BP_'+n) || n >= numPics) { // check if it exits
		if(loadIn) {
			loadPhotoInSlideShow();
		}
		return true;
	} else { // else loads it
		var urlRequest = '/IncludeFunctions/thumbnails.php';
		var jsonRequest = new Request.JSON({
			url: urlRequest,
			onComplete: function(photo){
				var nPoto = new Element('img', {
					'id' : 'BP_'+photo.n,
					'src' : photo.src,
					'width' : photo.width,
					'height' : photo.height,
					'alt' : photo.alt,
					'class' : 'bigPhoto'
				}).inject('photoContainer', 'top');
				if(loadIn) {
					loadPhotoInSlideShow();
					return true;
				}
			}
		}).get({
			'yachtId':yachtId,
			'Op' : 'photos',
			'Sec':section,
			'n':n
		});
	}
};
var loadPhotoInSlideShow = function() {//take the photo active and showed it in the slideshow
	//recheck window size...
	winW = window.getSize().x;
	winH = window.getSize().y;
	//checks in each iteration
	slideShowActive = true;
	showhideSlideShowControl(); //slideshow controls next-previuos
	if(stateSlideShow!=true) { //running or stop
		stopGalleryShow();
	}
	checkplaypauseControl(); //play-pause control
	//take the active photo
	var n = getThumbNum(getPhotoActive());
	var newPhoto = $('BP_'+n);

	//try with the action
	try {
		//preload nextphoto
		nextPhoto = $clear(nextPhoto);//clear timer
		if(n < numPics) {
			nextPhoto = function(){
					nn = n + 1
					preLoadPhotos(nn, false);
			}.delay(500);
		}
		//preload previous photo
		prevPhoto = $clear(prevPhoto);//clear timer
		if(n > 0) {
			prevPhoto = function(){
				np = n - 1;
				preLoadPhotos(np, false);
			}.delay(1000);
		}
		//define animations
		var PhotoAnimN = new Fx.Morph(newPhoto, {duration: 300, transition: Fx.Transitions.linear});
		var PhotoCAnim = new Fx.Morph('photoContainer', {duration: 800, transition: Fx.Transitions.linear});
		var slideAnim = new Fx.Morph('slideShowBackground', {duration: 800, transition: Fx.Transitions.linear});
		var CaptionAnim = new Fx.Morph('captionSlideShow', {duration: 900, transition: Fx.Transitions.linear});
		//get photo size
		var imageW = parseInt(newPhoto.getProperty('width'));
		var imageH = parseInt(newPhoto.getProperty('height'));
		//if this fails... for IE only another method...
		if(imageW==0 && imageH==0){
			var re = /(\d+)[\s*]?(px)$/;
			imageW = parseInt(re.exec(newPhoto.getStyle('width'))[1]);
			imageH = parseInt(re.exec(newPhoto.getStyle('height'))[1]);
		}
		//check the size
		//if the photo is too big then resize it
		if(imageW>(winW-150) || imageH>(winH-150)){
			if((imageW/winW) > (imageH/winH)) {
				nimageW = winW - 100;
				p = nimageW / imageW;
				nimageH = imageH * p;
			} else {
				nimageH = winH - 100;
				p = nimageH / imageH;
				nimageW = imageW * p;
			}
			
			imageW = nimageW;
			imageH = nimageH;
			$('BP_'+n).setProperties({
				'width': imageW,
				'height': imageH
			});
		}
		if($$('.photoActive').length > 0) { //hide the old photo if it exists
			var oldPhoto = $$('.photoActive')[0];
			oldPhoto.setStyles({
				'opacity':0,
				'display':'none'
			});
			oldPhoto.removeProperty('style');
			oldPhoto.removeClass('photoActive');
		}
		//start animations
		PhotoAnimN.start({
			'opacity':[0,1]
		});
		//put the img alt in the caption
		$('captionSlideShow').set('text', newPhoto.get('alt'));
		//show photo active and start animations
		newPhoto.addClass('photoActive');
		slideAnim.start ({
			'display': 'block',
			'top': 20,
			'left' : 20,
			'width': (imageW+2),
			'height': (imageH+2),
			'top': ((winH/2) - (imageH/2)-15),
			'left':((winW/2)-(imageW/2)-15),
			'opacity':1,
			'padding': 30
		});
		if(Browser.Engine.trident) {
			PhotoCAnim.start ({
				'display': 'block',
				'opacity':1,
				'width': 'auto',
				'height':'auto'
			});
		} else {
			PhotoCAnim.start ({
				'display': 'block',
				'opacity':1,
				'width': [0,imageW],
				'height':'auto'
			});
		}
		//continue with the animation
		PhotoAnimN.start ({
			'opacity':[0,1]
		});
		//this prevent the problem in Safari that the photo is not showed
		if(Browser.Engine.webkit) {
			newPhoto.setStyles({
				display: 'block',
				visibility: 'visible'
			});
		}
	} catch(e) {
		preLoadPhotos(n, true); //load the photo
	}
};
var playpauseSlideShow = function() {//change the status play/pause in the slideshow
	stateSlideShow = !stateSlideShow;
	checkplaypauseControl();
};
var checkplaypauseControl = function() {//check and show status of the slideshow
	if(stateSlideShow) {//show playing
		$('ControlPlayPause').addClass('Play');
		GalleryShowPhotos();
		$('playControlView').set('text', 'Playing >>');
	} else {//show paused
		$('ControlPlayPause').removeClass('Play');
		stopGalleryShow();
		$('playControlView').set('text', 'Paused ||');
	}
};
var previousPhotoSlideShow = function() {//move one photo back in the slideshow
	//check status
	stateSlideShow = false;
	checkplaypauseControl();
	//stop the animation
	stopGalleryShow();
	//check the photo where we have to go
	var last = false;
	var n = getThumbNum(getPhotoActive());
	if(n > 0) {
		if(n % 9 == 0)//we are in the first photo in next set
			last = true;
		n = n - 1;
		if(last) { //if we have to change the set...
			set = parseInt(n/9);
			changeSetThumbnails(set, n);
		} else { //else only move on in this set
			changePhoto($('Th_'+n));
		}
		stopGalleryShow(); //stop movement
	}
	showhideSlideShowControl(); //check controls
};
var nextPhotoSlideShow = function() {//move one photo forward in the slideshow
	//check status
	stateSlideShow = false;
	checkplaypauseControl();
	//stop animation
	stopGalleryShow();
	//check the photo where we have to go
	var last = false;
	var n = getThumbNum(getPhotoActive());
	if(n < numPics-1) { //if we don't finish
		n = n + 1;
		if(n % 9 == 0) { //we are in the first photo in next set
			set = parseInt(n/9);
			changeSetThumbnails(set, n);
		} else { //else only move on in this set
			changePhoto($('Th_'+n));
		}
		stopGalleryShow(); //stop movement
	} else { //else go to the first
		changeSetThumbnails(0,0);
	}
	showhideSlideShowControl(); //check controls
};
var showhideSlideShowControl = function(){//show/hide controls in the slideshow
	//where we are
	var n = getThumbNum(getPhotoActive());
	if(numPics <= 1) { //if we have one photo we don't show the controls
		$('playControlView').setStyle('display','none');
		$('playControl').setStyle('display','none');
	} else {
		//if we are in the first photo we cannot go backwards
		if(n <=0) {
			$('ControlPrev').addClass('hide');
		} else {
			$('ControlPrev').removeClass('hide');
		}
/*
		if(n >= maxN) {
			$('ControlNext').addClass('hide');
		} else {
			$('ControlNext').removeClass('hide');
		}
*/
	}
};
var hideSlideShow = function() {//hide slideshow
	//reset variables
	slideShowActive = false;
	stateSlideShow = false;
	//animations
	var PhotoAnim = new Fx.Morph('photoContainer', {duration: 500, transition: Fx.Transitions.linear});
	var slideAnim = new Fx.Morph('slideShowBackground', {duration: 500, transition: Fx.Transitions.linear});
	PhotoAnim.start({
		'opacity': 0
	})
	slideAnim.start({
		'opacity': 0
	});
	//reset styles and hide
	$('photoContainer').removeProperty('style');
	$('slideShowBackground').removeProperty('style');
	$$('.bigPhoto').removeClass('photoActive');
	$$('.bigPhoto').removeProperty('style');
};
var showLoading =function() {//show loading banner, this avoid someone thinks is frozen
	var loadingOn = new Fx.Morph('loading', {duration: 300, transition: Fx.Transitions.linear});
	loadingOn.start({
		'opacity': [0.8]
	});
};
var hideLoading =function() {//hide loading banner
	var loadingOff = new Fx.Morph('loading', {duration: 300, transition: Fx.Transitions.linear});
	loadingOff.start({
		'opacity': [0]
	});
};
var showPhotoGallery = function(thum) {//fired when click on thumbnail, show photo and wait to move on...
	changePhoto(thum);
	stopGalleryShow();
	if(stateSlideShow) {//if the slideshow is active, whe we click on a thumb the photo is loaded and slide show continues
		GalleryShowPhotos();
	} else {//else we show the photo and stop the gallery animation for a while
		GalleryShowPhotos.delay(delayPeriodicalGallery);//restart the slideshow with delay...
	}
};
var changePhoto = function(thum) {//change photo in normal preview, and launch photo in slideshow if it is active
	//stop the Galleryshow...
	stopGalleryShow();
	//remove the class active
	$$('#thumbPhotos ul.thum li.active').removeClass('active');
	//Put the picture to view
	var imageMed = takeMediumSizePhoto(thum);
	var photoSrc = imageMed.getProperty('src');
	//resize the image showed...
	//normal browsers
	var photoW=0;//340
	var photoH=240;
	var imageMedwidth = imageMed.getProperty('width');
	var imageMedheight = imageMed.getProperty('height');
	//and for IE only
	if(imageMedwidth==0 && imageMedheight==0){
		var re = /(\d+)[\s*]?(px)$/;
		imageMedwidth = re.exec(imageMed.getStyle('width'))[1];
		imageMedheight = re.exec(imageMed.getStyle('height'))[1];
	}
	//new size...
	if(imageMedwidth>1 && imageMedheight>1){
		if(imageMedwidth > imageMedheight) {
			nW = (imageMedwidth>=340)? 340 : imageMedwidth;
			photoP = nW / imageMedwidth;
			photoW = nW;
			photoH = imageMedheight * photoP;
		} else {
			nH = (imageMedheight>=240)? 240 : imageMedheight;
			photoP = nH / imageMedheight;
			photoH = nH;
			photoW = imageMedwidth * photoP;
		}
	}
	var photoTitle = imageMed.getProperty('title');
	//efects
	var primPhotoOpacityFx = new Fx.Morph('primPhoto', {
			duration: 500, 
			transition: Fx.Transitions.linear
		});
	//add class active
	thum.parentNode.addClass('active');
	//if the SlideShow is active
	if(slideShowActive)
		loadPhotoInSlideShow();
	//start Fx hide...
	primPhotoOpacityFx.start({
		'opacity': [0]
	}).chain(
		function(){
			$('photoShowed').setProperty('src', photoSrc);
			//put the caption
			$('captionPhoto').set('html', photoTitle);
			if(photoW>0) {
				$('photoShowed').setProperty('width', photoW);
				$('photoShowed').setProperty('height', photoH);
				this.start({
					'opacity': [1]
				});
			} else {
				$('photoShowed').setProperty('height', photoH);
				this.start({
					'opacity': [1]
				});
			}
		}
	);
	if(slideShowActive && !stateSlideShow) {
		stopGalleryShow();
	} else {
		//relaunch Galleryshow
		GalleryShowPhotos();
	}
	return true;
};
var changeSetThumbnails = function(set,n) {//change and/or load the new set of thumbnails
	showLoading();

	n = (n)? n : 0;
	if(!navBar) { //navBar not ready
		if(fails<100) { //try 100 times... if it fails... ops... 
			fails++;
			changeSetThumbnails(set, n).delay(100);
			return false;
		} else {
			//refresh the page...
			window.location.reload( true );
		}
	} else {
		fails = 0;
	}
	//stop the Galleryshow...
	stopGalleryShow();

	var maxSet = numSets-1;
	if(set=='P' || set=='N') {//Previous or Next
		nset = getSetNum(getPageActive());
		if(set=='P' && nset>0)
			set = nset-1;
		if(set=='N' && nset<maxSet)
			set = nset+1;
	}

	if(!setThumbnails.contains(set)) {
		$('set_'+set).empty(); //remove elements inside because is incomplete...
		loadSetThumbnail(set);
		return false;
	}

	if(set==0)
		$('page_Prev').addClass('hide');
	else if(maxSet>0)
		$('page_Prev').removeClass('hide');
	if(set==maxSet)
		$('page_Next').addClass('hide');
	else if(maxSet>0)
		$('page_Next').removeClass('hide');

	//change the texts
	oldSet = getSetNum($$('#navThumb li.active')[0]);
	$('page_'+oldSet).getFirst().set('text', oldSet+1);
	$('page_'+set).getFirst().set('text','Set '+(set+1));

	//change the clasess
	$$('#navThumb li').removeClass('active');
	$$('.setThumbnail').removeClass('active');//This is for all browsers
	$('set_'+oldSet).removeClass('active');//this line is only for IE 5.5
	$('set_'+set).addClass('active');
	$('page_'+set).addClass('active');

	// and put first photo as active...
	if(n==0)
		changePhoto(getFirstPhotoInSet($('set_'+set)));
	else // what we want... 
		changePhoto($('Th_'+n));

	//relaunch Galleryshow
	hideLoading();
	GalleryShowPhotos();
	
	return true;
};
var GalleryShowPhotos = function() {//automatic play of photos... preview and slideshow
	//stop the Galleryshow...
	stopGalleryShow();
	if(setThumbnails.length>0 && ((slideShowActive && stateSlideShow) || !slideShowActive)) {
		if($('loading').getProperty('opacity')!=0) //avoid frozen loading banner...
			hideLoading();
	
		var setActive = getSetNum(getPageActive());
		var set = $('set_'+setActive);
		var numTh = getNumberThumbsInSet(set);
		//if we want the slickshow not continues
		//var first = (slideShowActive)? 0 : getThumbNum(getFirstPhotoInSet(set));
		//var last = (slideShowActive)? numPics-1 : first+numTh-1;
		//slickshow continues
		var first = 0;
		var last = numPics-1;
	
		if(numTh>1 || (slideShowActive && numTh >= 1) || (setActive>0 && numTh >= 1)) {
			var runGalleryShow = function() {
				i = getThumbNum(getPhotoActive());
				i = (i<last)? i+1 : first;
				//if(slideShowActive && i % 9 == 0) { //slickshow not continues
				if(i % 9 == 0) { //slideshow and slickshow continues
					setPhoto = parseInt(i/9);
					changeSetThumbnails(setPhoto, i);
				} else {
					changePhoto($('Th_'+i));
				}
			};
			var t = (slideShowActive)? periodicalSlideShow : periodicalGallery;
			timer = runGalleryShow.periodical(t);
		}
	}
};
var stopGalleryShow = function() { //stops photo playing
	if(timer) {
		timer = $clear(timer);
		return true;
	} else {
		return false;
	}
};
var addEventsThumbnails = function() {//events in thumbanils
	//add efects to thumbnails
	$$('.Thumbnails').addEvent('click', function(){
		showPhotoGallery(this);
	});
};
var addEventPrimary = function() {//event in preview photo
	//add efects to thumbnails
	$('primPhoto').addEvent('click', function(){
		if(slideShowActive) {//this fix the bug in dobleclick in primPhoto
			return true;
		} else {
			stopGalleryShow();
			loadPhotoInSlideShow();
		}
	});
};
var addTipsThumbnails = function() {//adds tip to thumbnails
	$$('.Thumbnails').each(function(el)	{
		var full_title = el.getProperty('title');
		if(full_title) {
			var dual = full_title.split('::');
			var tip_title = dual[0].trim();
			var tip_text	= dual[1].trim();
			el.store('tip:title', tip_title);
			el.store('tip:text', tip_text);
		}
	});

	// Tips
	var myTips = new Tips('.Thumbnails', {
		className: 'Thumbnails',
		showDelay: 50,
		hideDelay: 0,
		onShow: function(toolTip) {
 			toolTip.set('tween', {duration: 250}).fade('in');
		},
		onHide: function(toolTip) {
			toolTip.set('tween', {duration: 250}).fade('out');
		}

	});
};
var getPageActive = function() {//gets thumbnail set active, returns element
	return $$('#navThumb li.active')[0];
};
var getPhotoActive = function() { //gets photo thumb active, returns element
	var ph = $$('#thumbPhotos ul.thum li.active');
	if(ph.length>0)
		return ph[0].getFirst();
	else
		return getFirstPhotoInSet($('set_'+getSetNum(getPageActive())));
};
var getThumbNum = function(photo) {//gets thumbnail number, given element
	var re = /Th_(\d+)$/;
	var m = re.exec(photo.id);
	return parseInt(m[1]);
};
var getSetNum = function(r) {//gets set number, given element
	if(r) {
		var re = /page_(\d+)$/;
		var m = re.exec(r.id);
		return parseInt(m[1]);
	} else {
		return 0;
	}
};
var getLastSet = function() {//gets last set, returns element
	return $('navThumb').getLast();
};
var getNumberThumbsInSet = function(set) {//gets number of thumbs in a given set, given element
	var th = set.getFirst().getChildren()
	return th.length;
};
var getFirstPhotoInSet = function(set) {//gets first thumb in a given set, given element and returns element
	var th = set.getFirst().getChildren();
	return th[0].getFirst();
};
var takeMediumSizePhoto = function(th) {//gets medium size photo of a given thumb, given element and returns element
	return $('MedPhoto_'+getThumbNum(th));
};
var loadSetThumbnail = function(set) {//loads thumbnail set and show first photo. ajax async
	var urlRequest = '/IncludeFunctions/thumbnails.php';
	var v = 'yachtId='+yachtId+'&Op=TakeSet&Sec='+section+'&set='+set;
	var ajax = new Request({
			url: urlRequest,
			method: 'get',
			onSuccess: function() {
				$('set_'+set).set('html', this.response.text);
				setThumbnails.include(set);
				addEventsThumbnails();
				addTipsThumbnails();
				changeSetThumbnails(set, 0);
			}
	}).send(v);
};
var loadThumbnailNavigation = function() {//loads navigation Thumbnails bar
	var urlRequest = '/IncludeFunctions/thumbnails.php';
	var v = 'yachtId='+yachtId+'&Op=PutNav&Sec='+section;
	var ajax = new Request({
			url: urlRequest,
			method: 'get',
			onSuccess: function() {
				$('navigationThumbnails').set('html', this.response.text);
				navBar = true;
				loadSets();
			}
	}).send(v);
};
var loadSets = function() {//loads empty containers for set
	$('thumbPhotos').empty();
	var urlRequest = '/IncludeFunctions/thumbnails.php';
	var v = 'yachtId='+yachtId+'&Op=PutSets&Sec='+section;
	var ajax = new Request({
			url: urlRequest,
			method: 'get',
			onSuccess: function(r) {
				$('thumbPhotos').set('html',r);
				loadSetThumbnail(0);
				return true;
			}
	}).send(v);
};
var countSets = function() {//gets num of sets
	var urlRequest = '/IncludeFunctions/thumbnails.php';
	var v = 'yachtId='+yachtId+'&Op=count&Sec='+section;
	var ajax = new Request({
			url: urlRequest,
			method: 'get',
			onSuccess: function(r) {
				numPics = parseInt(r);
				numSets = (numPics % 9 == 0)? parseInt(numPics/(9+1))+1 : parseInt(numPics/9)+1;
				//if we don't have photos we hide the thumb space
				if(numPics==0)
					$('showPhotos').setStyle('display', 'none');
			}
	}).send(v);
};

