// +-------------------------------------------------------------+
// | Zaplife Slideshow javascript file
// | All rights reserved. Copyright 2005-2008 Zaplife
// |
// +-------------------------------------------------------------+

var photoCommentReplyMessage = '';
var photoCommentReplyToUserId = '';

var zapSlideshow = new Class({

	Extends: Slideshow,
	
	//Same as default but fixed freezing bug on line 200 in original js, fixed now
	/*
	preload: function(fast){
		if (this.preloader.complete && $time() > this.delay && $time() > this.transition){
			if (this.stopped){
				if (this.options.captions)
					this.slideshow.retrieve('captions').get('morph').cancel().start(this.classes.get('captions', 'hidden'));
				this.pause(1);
				return;				
			}					
			this.image = (this.counter % 2) ? this.b : this.a;
			this.image.set({
				'src': this.preloader.get('src'),
				'styles': {'height': 'auto', 'visibility': 'hidden', 'width': 'auto', 'zIndex': this.counter}
			});	
			this._resize(this.image, this.preloader.width, this.preloader.height);
			var anchor = this.image.getParent();
			if (this.data.hrefs[this.slide])
				anchor.set('href', this.data.hrefs[this.slide]);			
			else
				anchor.erase('href');	
			if (this.options.loader)
				this.slideshow.retrieve('loader').fireEvent('hide');
			if (this.options.captions)
				this.slideshow.retrieve('captions').fireEvent('update', fast);				
			if (this.options.thumbnails)
				this.slideshow.retrieve('thumbnails').fireEvent('update', fast); 			
			this.show(fast);
			this.loaded();
		} 
		else {
			if ($time() > this.delay && this.options.loader)
				this.slideshow.retrieve('loader').fireEvent('show');
			//this.timer = (this.paused) ? null : this.preload.delay(100, this, fast);
			this.timer = this.preload.delay(100, this, fast);
			
		}
	},
	*/
	
	//Same as default but remove centering when Safari gives img size = 0, need to solve this
	
	_center: function(img){
		if (this.options.center){
			var size = img.getSize();
			if (Browser.Engine.webkit && size.x == 0) {
				//alert(size.x);
			} else {
				img.set('styles', {'left': (size.x - this.width) / -2, 'top': (size.y - this.height) / -2});
			}
		}
	},

	//Same as default function except that I removed the fast mode on pause mode

	go: function(n, direction){
		if ((this.slide - 1 + this.data.images.length) % this.data.images.length == n || $time() < this.transition)
			return;		
		$clear(this.timer);
		this.delay = 0;		
		this.direction = (direction) ? direction : ((n < this.slide) ? 'right' : 'left');
		this.slide = n;
		if (this.preloader) 
			this.preloader = this.preloader.destroy();
		this._preload(this.options.fast);
	},
	
	//Same as default but moved the centering code to the morph to be able to center image when using absolute transition
	
	/*
	show: function(fast){
		if (!this.image.retrieve('morph')){
			var options = (this.options.overlap) ? {'duration': this.options.duration, 'link': 'cancel'} : {'duration': this.options.duration / 2, 'link': 'chain'};
			$$(this.a, this.b).set('morph', $merge(options, {'transition': this.options.transition}));
		}
		//this._center(this.image);
		var hidden = this.classes.get('images', ((this.direction == 'left') ? 'next' : 'prev'));
		var visible = this.classes.get('images', 'visible');
		if (fast)
			this.image.get('morph').cancel().set(visible); 			
		else {
			var img = (this.counter % 2) ? this.a : this.b;
			if (this.options.overlap){	
				img.get('morph').set(visible);
				this.image.get('morph').set(hidden).start(visible);
			} else {
				var size = this.image.getSize();
				var fn = function(hidden, visible){
					this.image.get('morph').set(hidden).start({left: (size.x - this.width) / -2, top: (size.y - this.height) / -2, opacity: 1});
				}.pass([hidden, visible], this);
				var hidden = this.classes.get('images', ((this.direction == 'left') ? 'prev' : 'next'));
				img.get('morph').set({left: (size.x - this.width) / -2, top: (size.y - this.height) / -2, opacity: 1}).start(hidden).chain(fn);
			}
		}
		if (activeSlideshowTabs.selected != null) {
			activeSlideshowTabs.select(activeSlideshowTabs.selected, this.slide);
		}
	},
	*/
	
	initialize: function(el, data, options){
		this.parent(el, data, options);
		
		/*
		//Do this to center image
		if (this.image.getSize().x != 0) {
			this._center(this.image);
		} else {
			//If not yet loaded, do CSS centering (maybe not needed, if so remove in show function)
			this.image.setStyles({ 'margin': '0 auto', 'float': 'none', 'position': 'relative'});
		}
		*/
		
		
		this.tagFrameSize = 142;
		this.taggingActive = false;
		this.currentPhoto = this.options.slide;
		
		//Create html element for viewing tags
		this.tagFrameContainer = new Element('div').set({'id': 'tagFrame'}).setStyles({
        	'display': 'none'
        }).inject(document.body);
        this.tagFrameContainerInside = new Element('div').set({'id': 'tagFrameInside'}).inject(this.tagFrameContainer);
		
		this.loadTags();
	},

	_show: function(fast){
		this.parent(fast);
		
		//Do this to remove centering on initialize
		//this.image.setStyles({ 'margin': '', 'float': 'left', 'position': 'absolute'});
		
		this.currentPhoto = this.slide;
		this.deActivateTagging('cancel');
		this.loadTags();
		if (startSlideshow.tabs.selected != null) {
			startSlideshow.tabs.select(startSlideshow.tabs.selected, this.currentPhoto);
		}
		
		//alert(this.slide);
	},
	
	loadTags: function() {
		/*
		//if (this.tagsVisible) {
		pars = 'action=loadtags&photo_id=' + this.props.photos[this.atScreen] + '&album_id=' + this.props.albumId[this.atScreen] + '&value=' + this.props.users[this.atScreen];
		var myAjax = new Ajax('ajax_photos.php', {method: 'post', data: pars, onComplete: function (response) {
					$('phototags_content').innerHTML = response;
				}
			}).request();
		}
		*/
		
		var pars = 'action=load_tags&' + 'id=' + startSlideshow.images[this.currentPhoto][0] + sessionVar;
		var myAjax = new Request.HTML({
			url: webPath + 'ajax_photos.php?' + pars, 
			evalScripts: false,
			//update: startSlideshow.tagsContainer,
			onComplete: function (responseTree, responseElements, responseHTML, responseJavaScript) {
				startSlideshow.tagsContainer.set('html', responseHTML);
			}
		}).get();
		
	},
	
	activateTagging: function(event) {
		
		this.taggingActive = true;
		//this.options.controller = false;
		
		//Hide controller and caption
		$$('div.slideshow-controller')[0].setStyle('display', 'none');
		$$('div.slideshow-captions')[0].setStyle('display', 'none');
				
		//$('phototags_button').setStyle('display', '');
		//tags.slideIn();
		//this.loadTags();
		
		//Load edit tags content
		/*
		if (this.props.users[this.atScreen] == this.props.sessUserId) {
			pars = 'action=loadedittags&photo_id=' + this.props.photos[this.atScreen] + '&album_id=' + this.props.albumId[this.atScreen] + '&value=' + this.props.users[this.atScreen];
				var myAjax = new Ajax('ajax_photos.php', { method: 'post', data: pars, onComplete: function (response) {
						$('phototags_content').innerHTML = response;
					}.bind(this)
				}).request();
		}
		*/
		
		//Create html elements for tagging
        //Add userlist div
		this.taggingList = new Element('div');
		this.taggingList.setStyles({ display: 'none', textAlign: 'center', position: 'absolute', left: '0px', top: '0px', border: 'solid 2px #00a7c2', backgroundColor: '#ffffff', zIndex: 999, width: '182px',  height: 'auto' });
		//this.taggingList.addClass('cardbackground');
		this.taggingList.injectAfter(this.tagFrameContainer);
		
    	//Activate cursor tagging
		this.image.setStyle('cursor', 'crosshair');
		this.image.addEvent("click", function(event) {
			event = new Event(event).stop(); 
			this.setTagFrame(event);
		}.bind(this));
		this.tagFrameContainerInside.addEvent("click", function(event) {
			event = new Event(event).stop(); 
			this.setTagFrame(event);
		}.bind(this));
			
		//Activate tooltip
		//showTooltip('photos',-(this.props.width-this.loader.width)/2 + 5,this.props.height/2);
		
		/*
		pars = 'action=load_tagable_users&photo_id=' + this.props.photos[this.atScreen] + '&album_id=' + this.props.albumId[this.atScreen] + '&value=' + this.props.users[this.atScreen];
    		var myAjax = new Ajax('ajax_photos.php', { method: 'post', data: pars, onComplete: function (response) {
    				this.taggingList.innerHTML = response;
    			}.bind(this)
    		}).request();
		*/
		
		var pars = 'action=load_tagable_users' + sessionVar;
		var myAjax = new Request.HTML({
			url: webPath + 'ajax_photos.php?' + pars, 
			evalScripts: false,
			//update: this.taggingList,
			onComplete: function (responseTree, responseElements, responseHTML, responseJavaScript) {
				this.taggingList.set('html', responseHTML);
				//Show tag frame
				startSlideshow.show.setTagFrame();
			}.bind(this)
		}).get();
		
				
		/*
		if (this.commentsVisible && this.props.albumComment == 1) {
			pars = 'action=showcomments&photo_id=' + this.props.photos[this.atScreen] + '&album_id=' + this.props.albumId + '&value=' + this.props.albumComment + '&value2=' + this.props.albumUser + '&value3=' + this.props.titles[this.atScreen];
    		var myAjax = new Ajax('ajax_photos.php', {method: 'post', data: pars, onComplete: function (response) {
    				$('comments').innerHTML = response;
    			}
    		}).request();
    	}
    	*/
    	//alert('tag');
	},
	
	setTagFrame: function(event) {
	
		var frameSize = this.tagFrameSize;
		//var containerCoord = startSlideshow.container.getPosition();
		//var imgCoord = this.image.getCoordinates(startSlideshow.container);
		var imgCoord = this.image.getCoordinates();
		var imgLeft = imgCoord['left'];
		var imgTop = imgCoord['top'];
		if (event == undefined) {
			var frameX = imgLeft + imgCoord['width']/2 - frameSize/2;
			var frameY = imgTop + imgCoord['height']/2 - frameSize/2;
		} else {
			var frameX = event.page.x - frameSize/2;
			var frameY = event.page.y - frameSize/2;
		}
		
		
		//Bug
		/*
		if (window.ie) {
			var imgLeft = imgCoord['left'] + 1;
			var imgTop = imgCoord['top'] + 1;
		} else if (window.gecko) {
			var imgLeft = imgCoord['left'] + 2;
			var imgTop = imgCoord['top'] + 2;
		} else {
			var imgLeft = imgCoord['left'];
			var imgTop = imgCoord['top'];
		}
		*/
		
		if(frameX < imgLeft) frameX = imgLeft;
		if(frameY < imgTop) frameY = imgTop;
		if(frameX > imgLeft + imgCoord['width'] - frameSize) frameX = imgLeft + imgCoord['width'] - frameSize;
		if(frameY > imgTop + imgCoord['height'] - frameSize) frameY = imgTop + imgCoord['height'] - frameSize;
		this.tagFrameContainer.setStyles({left: frameX + 'px', top: frameY + 'px', display: ''});
		if (window.getWidth() < frameX + frameSize + 13 + 190) {
			this.taggingList.setStyles({left: frameX - 199 + 'px', top: frameY + 'px', display: ''});
		} else {
			this.taggingList.setStyles({left: frameX + frameSize + 13 + 'px', top: frameY + 'px', display: ''});
		}
		
		//Set coordinates in form
		$('tagX').value = frameX - imgLeft + frameSize/2;
		$('tagY').value = frameY - imgTop + frameSize/2;
		
		//alert(window.getWidth());
		//alert(imgCoord['left']);
		
    	//alert('tag');
	},
	
	deActivateTagging: function(mode) {
		if (mode == 'cancel' && !this.taggingActive) {
			return false;
		}
		this.image.setStyle('cursor', 'cursor');
		this.image.removeEvents("click");
		/*
		this.tagFrameContainer.setStyles({display: 'none'});
		this.taggingList.setStyles({display: 'none'});
		this.taggingList.setHTML('');
		*/
		
		//$('phototags_button').setStyle('display', 'none');
		//hideTooltip('photos');
		//this.tagsVisible = true;
		//this.loadTags();
		
		
		//Save tags
		if (mode == 'save') {
			pars = 'photo_id=' + startSlideshow.images[this.currentPhoto][0] + '&' + $('usertaglist').toQueryString();
			var myAjax = new Request({url: 'ajax_photos.php?action=add_user_tags', method: 'post', data: pars, onComplete: this.loadTags.bind(this)}).send();
		}
		
		//Remove tag frames
		//this.tagFrameContainer.destroy(); We keep this one for tag viewing
		this.taggingList.destroy();
		this.tagFrameContainer.setStyles({display: 'none'});
		
		//Show controller and caption
		$$('div.slideshow-controller')[0].setStyle('display', '');
		$$('div.slideshow-captions')[0].setStyle('display', '');

		this.taggingActive = false;
	},
	
	toggleTagFrame: function(x, y, display) {
	
		var frameSize = this.tagFrameSize;
		var imgCoord = this.image.getCoordinates();
		var imgLeft = imgCoord['left'];
		var imgTop = imgCoord['top'];
		var frameX = x - frameSize/2;
		var frameY = y - frameSize/2;
		
		/*
		//Bug
		if (window.ie) {
			var imgLeft = imgCoord['left'] + 1;
			var imgTop = imgCoord['top'] + 1;
		} else if (window.gecko) {
			var imgLeft = imgCoord['left'] + 2;
			var imgTop = imgCoord['top'] + 2;
		} else {
			var imgLeft = imgCoord['left'];
			var imgTop = imgCoord['top'];
		}
		*/
		
		if (display) {
			display = '';
		} else {
			display = 'none';
		}
		
		this.tagFrameContainer.setStyles({left: frameX + imgLeft + 'px', top: frameY + imgTop + 'px', display: display});
		
	},
	
	removeUserTag: function(id) {
			
		pars = 'photo_id=' + startSlideshow.images[this.currentPhoto][0] + '&id=' + id + sessionVar;
		var myAjax = new Request({url: webPath + 'ajax_photos.php?action=remove_user_tag', method: 'get', data: pars, onComplete: this.loadTags.bind(this)}).send();

	},
	
	addComment: function() {
		if ($('photoCommentMessage').value == '' || langDefaultCommentMessage == $('photoCommentMessage').value || photoCommentReplyMessage == $('photoCommentMessage').value) {
			doError('photoCommentMessage', langCommentMessageError);
		} else {
			var pars = 'action=add_comment&photo_id=' + startSlideshow.images[this.currentPhoto][0] + '&' + $('newPhotoCommentForm').toQueryString() + '&reply_to_user_id=' + photoCommentReplyToUserId + sessionVar;
			var myAjax = new Request({ url: webPath + 'ajax_photos.php', method: 'post', data: pars, onComplete: function () {
					this.loadComments();
					if ($('smiliesTooltip')) {
						if ($('smiliesTooltip').style.display == 'block') {
							$('smiliesTooltip').style.display = 'none';
						}
					}
					newPhotoCommentEffect.toggle();
					$('photoCommentMessage').value = langDefaultCommentMessage;
					
					//Add events so that we can use slideshow again
					this.toggleEvents(true);
				}.bind(this)
			}).send();
		}
	},
	
	removeComment: function (commentId) {
		var pars = 'action=remove_comment&photo_id=' + startSlideshow.images[this.currentPhoto][0] + '&id=' + commentId + sessionVar;
		var myAjax = new Request({ url: webPath + 'ajax_photos.php', method: 'get', data: pars, onComplete: this.loadComments.bind(this) }).send();
	},
	
	replyComment: function (replyId, username) {
		photoCommentReplyMessage = langDefaultCommentReplyMessage + ' ' + username;
		$('photoCommentMessage').value = photoCommentReplyMessage;
		photoCommentReplyToUserId = replyId;
		newPhotoCommentEffect.toggle();
		this.toggleEvents(false);
	},
	
	loadComments: function () {
		if ($('photoComments')) {
			var pars = 'action=load_comments&id=' + startSlideshow.images[this.currentPhoto][0] + sessionVar;
			var myAjax = new Request.HTML({
				url: webPath + 'ajax_photos.php?' + pars, 
				evalScripts: false,
				onComplete: function (responseTree, responseElements, responseHTML, responseJavaScript) {
					$('photoComments').set('html', responseHTML);
				}
			}).get();
    	}	
	},
	
	toggleEvents: function (add) {
		if (add) {
			this.events.each(function(array, e){
				array.each(function(fn){ document.addEvent(e, fn); });
			});
		} else {
			this.events.each(function(array, e){
				array.each(function(fn){ document.removeEvent(e, fn); });
			});
		}
	
	}
	
});


var slideshowTabs = new Class({

	Extends: SimpleTabs,
	
	//Added containerFx to tab object
	
	addTab: function(text, title, content) {
		var grab = $(content);
		var container = (grab || new Element('div'))
			.setStyle('display', 'none')
			.addClass(this.options.classContainer)
			.inject(this.wrapper);
		var pos = this.tabs.length;
		var evt = (this.options.hover) ? 'mouseenter' : 'click';
		var containerFx = new Fx.Slide(container, {
			mode: 'vertical',
			onComplete: function() {
				if(this.wrapper.offsetHeight != 0)
				this.wrapper.setStyle('height', 'auto');
			}
		}).hide();
		var tab = {
			containerFx: containerFx,
			container: container,
			toggle: new Element('li').grab(new Element('a', {
				href: '#',
				title: title
			}).grab(
				new Element('span', {html: text})
			)).addEvent(evt, this.onClick.bindWithEvent(this, [pos])).inject(this.menu)
		};
		if (!grab && $type(content) == 'string') tab.url = content;
		this.tabs.push(tab);
		return this.fireEvent('onAdded', [tab.toggle, tab.container, pos]);
	},
	
	
	//Same as original except for removing the check if already is selected
	//Added support for closing a tab if open
	//Added containerFx
	
	select: function(index, slide) {
		//if (this.selected === index || !this.tabs[index]) return this;
		if (this.selected === index && slide == undefined) { //When click to close tab	
			this.tabs[this.selected].containerFx.slideOut();
			this.fireEvent('onDeselect', [this.tabs[this.selected].toggle, this.tabs[this.selected].container, this.selected]);
			this.selected = null;
			return this;
		}
		if (this.ajax) this.ajax.cancel().removeEvents();
		var tab = this.tabs[index];
		var params = [tab.toggle, tab.container, index];
		if (this.selected !== null && slide == undefined) {
			var current = this.tabs[this.selected];
			if (this.ajax && this.ajax.running) this.ajax.cancel();
			params.extend([current.toggle, current.container, this.selected]);
			this.tabs[this.selected].containerFx.slideOut();
			this.fireEvent('onDeselect', [current.toggle, current.container, this.selected]);
		}
		this.fireEvent('onSelect', params);
		if (tab.url && (!tab.loaded || !this.options.cache)) {
			this.ajax = this.ajax || new Request.HTML();
			this.ajax.setOptions({
				url: tab.url,
				method: 'get',
				//evalScripts: true,
				//update: tab.container,
				onFailure: this.fireEvent.pass(['onFailure', params], this),
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
					tab.container.set('html', responseHTML);
					eval(responseJavaScript);
					tab.loaded = true;
					this.fireEvent('onComplete', params);
					tab.containerFx.slideIn();
				}.bind(this)
			}).setOptions(this.options.ajaxOptions);
			this.ajax.send();
			this.fireEvent('onRequest', params);
		}
		this.selected = index;
		return this;
	}

});

