// 
//  gallery.js
//  The Hot Hits Party Gallery
//  
//  Created by Victor Nguyen on 2009-02-24.
//  Copyright 2009 igloo. All rights reserved.
// 

var gallery = {
	
	ids: {
		photo: {
			wrap: 'gallery-holder',
			replace: 'gallery-photo-area',
			full: 'gallery-photo-full'
		},
		thumbs: {
			wrap: 'gallery-thumbs-holder',
			area: 'gallery-thumbs',
			classname: 'gallery-thumb'
		},
		vote: {
			popupwrap: 'gallery-vote-bg',
			popup: 'gallery-vote'
		},
		comp: {
			wrap: 'gallery-vote-comp',
			form: 'gallery-vote-form',
			loading: 'gallery-vote-comp-loading',
			complete: 'gallery-vote-comp-complete'
		},
		controls: {
			vote: 'gallery-controls-vote',
			zoom: 'gallery-zoom-link',
			prev: 'gallery-controls-prev',
			next: 'gallery-controls-next',
			share: 'gallery-controls-share',
			slideshow: 'gallery-controls-slideshow'
		},
		share: {
			menu: 'gallery-share',
			wrap: 'gallery-controls-share-holder',
			facebook: 'gallery-share-facebook',
			myspace: 'gallery-share-myspace',
			send: {
				link: 'gallery-share-send',
				popupwrap: 'gallery-send-bg',
				popup: 'gallery-send'
			}
		},
		ad: {
			iframe: 'gallery-ad-iframe'
		},
		preroll: {
			wrap: 'gallery-preroll',
			start: 'gallery-preroll-start',
			count: 'gallery-preroll-counter'
		}
	},
	
	settings: {
		thumbnailwidth: 120, // width of a thumbnail container in px
		scrollz: null,
		slideshowdelay: 4000,
		adRefreshInterval: 20000,
		prerollLength: 10000
	},
	
	thumbs: {
		holder: null,
		els: null,
		count: null
	},
	
	activeRequest: null,
	
	init: function() {
		gallery.preroll.init();
		
		gallery.getThumbs();
		gallery.setThumbHolderWidth();
		// gallery.comp.init();
		// gallery.ad.init();
		
		$(gallery.ids.photo.wrap).addEvent('click', gallery.clickHandler);
		$(gallery.ids.controls.share).addEvent('mouseover', gallery.shareMouseOverHandler);
		$(gallery.ids.share.wrap).addEvent('mouseleave', gallery.shareMouseOutHandler);
	},
	
	clickHandler: function(e) {
		var event = new Event(e);
		var target = gallery.getTarget(event);
		// console.log('click logger', target); // click logger
		
		// thumbnail or next/prev buttons
		if ((target.hasClass('gallery-thumb-link')) || (target == $(gallery.ids.controls.prev)) || (target == $(gallery.ids.controls.next))) {
			event.stop();
			if (gallery.slideshowActive) gallery.slideshowStop();
			gallery.updateFullPhoto(target);
			gallery.sendtofriend.close();
			gallery.vote.close();
		}
		
		// slideshow button
		if (target == $(gallery.ids.controls.slideshow)) {
			event.stop();
			gallery.slideshowToggle();
			gallery.sendtofriend.close();
			gallery.vote.close();
		}
		
		// send to friend buttons
		if ((target == $(gallery.ids.share.send.link)) || (target == $('gallery-send-complete-init'))) {
			event.stop();
			gallery.sendtofriend.open();
		}
		
		// close dialogs
		if (((gallery.sendtofriend.active) || (gallery.vote.active)) && ((target == $('gallery-send-close')) || (target == $('gallery-vote-close')) || target == $(gallery.ids.photo.full) || (target == $('gallery-photo-desc')) || (target == $(gallery.ids.controls.zoom)))) {
			event.stop();
			gallery.sendtofriend.close();
			gallery.vote.close();
		}
		
		// vote button
		if (target == $(gallery.ids.controls.vote)) {
			event.stop();
			gallery.vote.open();
		}
		
		// share button
		if (target == $(gallery.ids.controls.share)) {
			event.stop();
		}
		
	},
		
	getTarget: function(event) {
		var target = $(event.target);
		if (target.getTag() == 'img') target = target.getParent();
		return target;
	},
	
	getThumbs: function() {
		gallery.thumbs.holder = $(gallery.ids.thumbs.area);
		gallery.thumbs.els = $$('.'+gallery.ids.thumbs.classname);
		gallery.thumbs.count = gallery.thumbs.els.length;
	},
	
	setThumbHolderWidth: function() {
		var w = gallery.settings.thumbnailwidth * gallery.thumbs.count;
		gallery.thumbs.holder.style.width = w+'px';
		// console.log('thumbs width', gallery.thumbs.holder.style.width);
		var relindex = $(gallery.ids.photo.full).getElement('img').getProperty('rel');
		// console.log(relindex);
		gallery.scrollToThumb(relindex-1);
	},
	
	updateCurrentThumb: function(url) {
		// clear current class from thumbs
		for (var i=0; i < gallery.thumbs.els.length; i++) {
			gallery.thumbs.els[i].removeClass('current');
		};
		// set current class to current thumb
		var currentindex = gallery.getPhotoIndex(url);
		gallery.thumbs.els[currentindex-1].addClass('current');
		// scroll to current thumb
		gallery.scrollToThumb(currentindex-1);
	},
	
	updateFullPhoto: function(target) {
		if (gallery.activeRequest) gallery.activeRequest.cancel();
		
		var url = target.href;
		gallery.updateCurrentThumb(url);
		gallery.updateNextPrev(url);
		gallery.updateShareLinks(url);
		gallery.vote.close();
		// gallery.vote.reset();
		if (!(Lightbox.step < 0)) Lightbox.close();
		
		url = url + '?ajax=true'; // add ajax=true to call
		gallery.activeRequest = new Ajax(url, {
			method: 'get',
			update: $(gallery.ids.photo.replace),
			onRequest: _displayLoading,
			onComplete: function() {
				Lightbox.init(); // re init lightbox
				gallery.activeRequest = null;
			}
		});
		
		function _displayLoading() {
			var photo = $(gallery.ids.photo.full).getFirst();
			if (photo) photo.remove();
		}
		
		gallery.activeRequest.request();
	},
	
	updateNextPrev: function(url) {
		var currentindex = gallery.getPhotoIndex(url);
		var previndex = _getPrevIndex(currentindex);
		var nextindex = _getNextIndex(currentindex);

		// console.log('indexessssssss', currentindex, previndex, nextindex);
		
		_updateNavLink($(gallery.ids.controls.prev), /(photo-galleries\/\d{1,}\/\d{1,})/, previndex);
		_updateNavLink($(gallery.ids.controls.next), /(photo-galleries\/\d{1,}\/\d{1,})/, nextindex);
		
		function _updateNavLink(navlink, regex, newindex) {
			var url = navlink.href;
			var galleryid = gallery.getGalleryId(url);
			// console.log('gallery id', galleryid);
			url = url.replace(regex, 'photo-galleries/'+galleryid+'/'+newindex);
			// console.log('***NAV NEW***', url, newindex);
			navlink.href = url;
		}
		
		function _getPrevIndex(currentindex) {
			if (currentindex > 1) {
				var previndex = currentindex - 1;
			} else if (currentindex < 2) {
				// var previndex = 1; // stay at start
				var previndex = gallery.thumbs.count; // loop back to end
			}
			return previndex;
		}
		
		function _getNextIndex(currentindex) {
			if (currentindex < gallery.thumbs.count) {
				var nextindex = currentindex + 1;
			} else if (currentindex >= gallery.thumbs.count) {
				// var nextindex = gallery.thumbs.count; // stay at end
				var nextindex = 1; // loop back to start
			}
			return nextindex; 
		}
		
	},
	
	updateShareLinks: function(url) {
		var currentindex = gallery.getPhotoIndex(url);
		var facebook = $(gallery.ids.share.facebook);
		var myspace = $(gallery.ids.share.myspace);
		
		_updateShareLink(facebook, /(photo-galleries\/\d{1,}\/\d{1,})/, currentindex);
		_updateShareLink(myspace, /(photo-galleries\/\d{1,}\/\d{1,})/, currentindex);
		_updateSendUrl(currentindex);
		// _updateVoteUrl(currentindex);
		
		function _updateShareLink(sharelink, regex, newindex) {
			var url = sharelink.href;
			var galleryid = gallery.getGalleryId(url);
			// console.log('old', url, url.search(regex));
			url = url.replace(regex, 'photo-galleries/'+galleryid+'/'+newindex);
			// console.log('new', url, newindex);
			sharelink.href = url;
		}
		
		function _updateSendUrl(newindex) {
			var sendurl = $(gallery.ids.share.send.link);
			var url = sendurl.getProperty('rel');
			var galleryid = gallery.getGalleryId(url);
			url = url.replace(/(photo-galleries\/\d{1,}\/\d{1,})/, 'photo-galleries/'+galleryid+'/'+newindex);
			sendurl.setProperty('rel', url);
		}
		
		function _updateVoteUrl(newindex) {
			var votebtn = $(gallery.ids.controls.vote);
			var voteurl = votebtn.href;
			voteurl = voteurl.replace(/(&photo=\d{1,})/, '&photo='+newindex);
			votebtn.href = voteurl;
		}
	},
	
	getPhotoIndex: function(url) {
		var pieces = url.split('/');
		var currentindex = pieces[pieces.length-2];
		currentindex = currentindex * 1; // convert to integer
		// console.log('current index', currentindex);
		return currentindex;
	},
	
	getGalleryId: function(url) {
		var pieces = url.split('/');				
		var galleryid = pieces[pieces.length-3];
		return galleryid;
	},
	
	scrollToThumb: function(currentindex) {
		// function this shit off
		var totalwidth = gallery.thumbs.holder.style.width;
		var posthumb = gallery.thumbs.els[currentindex].getPosition().x;
		var posholder = $('gallery-thumbs').getPosition().x;
		// console.log(totalwidth, posholder, posthumb);
		var posoffset = 14; // padding on edge of holder
		var posfinal = posthumb - posholder - posoffset;
		// console.log('final position', posfinal);
		
		if (gallery.settings.scrollz) {
			// console.log('STOP EXISTING SCROLLZZZZZZ AND REUSE');
			gallery.settings.scrollz.stop();
		} else {
			// console.log('CREATE NEW SCROLLLLLZZZZ');
			gallery.settings.scrollz = new Fx.Scroll($(gallery.ids.thumbs.wrap),{
				wait: false,
				duration: 500,
				wheelStops: false,
				transition: Fx.Transitions.Quad.easeInOut
			});
		}
		
		// gallery.settings.scrollz.toElement(gallery.thumbs.els[currentindex]);
		// console.log('scrolling to',posfinal-240);
		gallery.settings.scrollz.scrollTo(posfinal-240);
	},
	
	
	shareMouseOverHandler: function(e) {
		var event = new Event(e);
		$(gallery.ids.share.menu).style.display = 'block';
		$(gallery.ids.controls.share).addClass('current');
	},
	
	shareMouseOutHandler: function() {
		$(gallery.ids.share.menu).style.display = 'none';
		$(gallery.ids.controls.share).removeClass('current');
	},
	
	slideshowActive: null,
	
	slideshowToggle: function() {
		if (gallery.slideshowActive) {
			// turn off slideshow
			gallery.slideshowStop();
		} else {
			// turn on slideshow
			gallery.slideshowStart();
		}
	},
	
	slideshowStop: function() {
			$clear(gallery.slideshowActive);
			gallery.slideshowActive = null;
			$(gallery.ids.controls.slideshow).removeClass('on');
	},
	
	slideshowStart: function() {
			$(gallery.ids.controls.slideshow).addClass('on');
			var nextbutton = $(gallery.ids.controls.next);
			gallery.slideshowActive = gallery.updateFullPhoto.periodical(gallery.settings.slideshowdelay, gallery, nextbutton);
	},
	
	
	// ==================
	// = SEND TO FRIEND =
	// ==================
	// Actual form submission is handled by submitSendToFriend() in global.js
	sendtofriend: {
		
		active: null,
		
		init: function() {
			url = 'http://'+servername+'/send-to-friend?pageName='+_getTitle();
			stf = new Ajax(url, {
				method: 'get',
				update: $('gallery-form-holder'),
				// onRequest: _displayLoading,
				onComplete: function() { gallery.sendtofriend.set(); }
			});
			stf.request();
			// stf.request.delay(500, stf);
			
			function _getTitle() {
				var title = document.getElement('h1');
				var pagetitle = title.getText();
				// console.log(pagetitle);
				return pagetitle;
			}
		},
		
		set: function() {
			$('sendForm').removeProperty('onsubmit');			
			$('sendForm').onsubmit = null;
			
			$('sendForm').addEvent('submit', function (e) {
				var event = new Event(e);
				event.stop();
				submitSendToFriend('photo');
			});
			
			$('sendPLButton').setProperty('src','/images/galleries/btn-send.gif');
			$('send-name').focus();
			
		},
		
		open: function() {
			// if (!gallery.sendtofriend.active) {
				gallery.vote.close();
				$(gallery.ids.share.send.popup).style.display = 'block';
				$(gallery.ids.share.send.popupwrap).style.display = 'block';
				gallery.sendtofriend.init();
				gallery.sendtofriend.active = true;
			// }
		},
		
		close: function() {
			if (gallery.sendtofriend.active) {
				$(gallery.ids.share.send.popup).style.display = 'none';
				$(gallery.ids.share.send.popupwrap).style.display = 'none';
				gallery.sendtofriend.active = null;
			}
		}
		
	},
	
	// ==========
	// = VOTING =
	// ==========	
	vote: {
		
		active: null,
		
		voted: null,
		
		request: function(voteurl) {
			if (gallery.vote.activeRequest) gallery.vote.activeRequest.cancel();
			var params = _getVoteParams(voteurl);
			var url = 'http://'+servername+'/gallery/vote'+params;
			
			gallery.vote.activeRequest = new Ajax(url, {
				method: 'get',
				onComplete: function() {
					gallery.vote.activeRequest = null;
					// gallery.vote.displaymsg.delay(500);
					gallery.vote.displaymsg();
				}
			});
			gallery.vote.activeRequest.request();
			
			function _getVoteParams(voteurl) {
				var voteparamsposition = voteurl.search(/(\?gallery=\d{1,}&photo=\d{1,})/);
				var voteparams = voteurl.substr(voteparamsposition);
				return voteparams;
			}
		},
		
		displaymsg: function() {
			$(gallery.ids.vote.popup).removeClass('loading');
			$('gallery-vote-thanks').style.display = 'block';
			$('gallery-vote-comp').style.display = 'block';
		},
		
		open: function() {
			// console.log('open', gallery.vote.voted);
			if (gallery.vote.voted == null) {
				gallery.sendtofriend.close();
				gallery.vote.active = true;
				gallery.vote.voted = true;
				$(gallery.ids.controls.vote).addClass('voted');
				$(gallery.ids.vote.popupwrap).style.display = 'block';
				$(gallery.ids.vote.popup).style.display = 'block';
				var voteurl = $(gallery.ids.controls.vote).href;
				gallery.vote.request(voteurl);
			}
		},
		
		close: function() {
			gallery.vote.active = null;
			$(gallery.ids.vote.popupwrap).style.display = 'none';
			$(gallery.ids.vote.popup).style.display = 'none';
			$(gallery.ids.vote.popup).addClass('loading');
			$('gallery-vote-thanks').style.display = 'none';
			$('gallery-vote-comp').style.display = 'none';
			$(gallery.ids.comp.form).style.display = 'block';
			$(gallery.ids.comp.loading).style.display = 'none';
			$(gallery.ids.comp.complete).style.display = 'none';
		},
		
		reset: function() { // resets vote button
			$(gallery.ids.controls.vote).removeClass('voted');
			gallery.vote.voted = null;
		}
		
	},
	
	
	// ===============
	// = VOTING COMP =
	// ===============	
	comp: {
		
		activeRequest: null,
		
		init: function() {
			var compform = $(gallery.ids.comp.form);
			compform.addEvent('submit', function(e) {
				gallery.comp.submit();
				return false;
			});
		},
		
		submit: function() {
			// define form vars
			var compform = $(gallery.ids.comp.form);
			var firstname = $(compform.firstName);
			var lastname = $(compform.lastName);
			var email = $(compform.email);
			var phone = $(compform.phone);
			var formfields = [firstname, lastname, email, phone];
			
			// if valid, submit form
			if (gallery.comp.validate([[firstname,'req'], [lastname,'req'], [email,'email'], [phone,'req']])) {
				// console.log('form is valid!!!!');
				var compaction = compform.getProperty('action');
				var url = 'http://'+servername+compaction+'?firstName='+firstname.value+'&lastName='+lastname.value+'&email='+email.value+'&phone='+phone.value;
				
				if (gallery.comp.activeRequest) gallery.comp.activeRequest.cancel();
				gallery.comp.activeRequest = new Ajax (url, {
					method: 'get',
					onRequest: _displayLoading,
					onComplete: function() {
						gallery.comp.activeRequest = null;
						// _displayThanks.delay(500);
						_displayThanks();
					}
				});
				
				gallery.comp.activeRequest.request();
				
			} else { // else validate on keyup
				// console.log('FORM IS NOT VALID BIATCH');
				for (var i=0; i < formfields.length; i++) {
					formfields[i].addEvent('keyup', function() {
						gallery.comp.validate([[firstname,'req'], [lastname,'req'], [email,'email'], [phone,'req']]);
					});
				};
			}
			
			function _displayLoading() {
				// console.log('sending comp entry');
				compform.style.display = 'none';
				$(gallery.ids.comp.loading).style.display = 'block';
			}
			
			function _displayThanks() {
				// console.log('display thanks msg!');
				$(gallery.ids.comp.loading).style.display = 'none';
				$(gallery.ids.comp.complete).style.display = 'block';
			}
			
			
		},
		
		validate: function(field) {
			var isitvalid = true; // valid until proven false
			
			for (var i=0; i < field.length; i++) {
				var value = field[i][0].value;
				var validation = field[i][1];
				
				if (validation == 'req') {
					if (!_validRequired(value)) {
						isitvalid = false;
						_displayError(field[i][0]);
					} else {
						_removeError(field[i][0]);
					}
				} else if (validation == 'email') {
					if (!_validEmail(value)) {
						isitvalid = false;
						_displayError(field[i][0]);
					} else {
						_removeError(field[i][0]);
					}
				}
				
			};
			
			function _validEmail(fielddata) {
				if (fielddata.test(/^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i)) return true;
			}
			
			function _validRequired(fielddata) {
				if (fielddata.test(/[^.*]/)) return true;
			}
			
			function _displayError(field) {
				field.addClass('error');
				var errorimg = field.getPrevious();
				var label = errorimg.getPrevious();
				errorimg.addClass('on');
				label.addClass('error');
			}
			
			function _removeError(field) {
				field.removeClass('error');
				var errorimg = field.getPrevious();
				var label = errorimg.getPrevious();
				errorimg.removeClass('on');
				label.removeClass('error');
			}
			
			if (isitvalid == true) {
				return true;
			} else {
				return false;
			}
		}
		
	},
	
	// =============
	// = ISLAND AD =
	// =============
	ad: {
			
		init: function() {
			gallery.ad.active = gallery.ad.refresh.periodical(gallery.settings.adRefreshInterval);
		},
		
		active: null,
		
		refresh: function() {
			// console.log('***REFRESHING AD***', gallery.settings.adRefreshInterval);
			$(gallery.ids.ad.iframe).src = $(gallery.ids.ad.iframe).src;
		}
		
	},
	
	// ==================
	// = ISLAND PREROLL =
	// ==================
	preroll: {
				
		active: null,
		counting: null,
		
		init: function() {
			if (!(_isActive())) { return; }
			// console.log('INITING PREROLL BIATCH');
			
			gallery.preroll.hide.delay(gallery.settings.prerollLength);
			gallery.preroll.counting = gallery.preroll.countdown.periodical(1000);
			
			$(gallery.ids.preroll.start).addEvent('click', function(e) {
				var event = new Event(e);
				event.stop();
				gallery.preroll.hide();
			});
			
			function _isActive() {
				if ($(gallery.ids.preroll.wrap)) {
					// console.log('BLING BLING!!!!!!!!!');
					return true;
				} else {
					// console.log('no ad');
					return false;
				}
			}
		},
		
		hide: function() {
			if (!(gallery.preroll.active == true)) {
				$(gallery.ids.preroll.wrap).style.display = 'none';
				$(gallery.ids.photo.wrap).style.visibility = 'visible';
				$(gallery.ids.photo.wrap).style.height = 'auto';
				$(gallery.ids.photo.wrap).style.overflow = 'auto';
				$(gallery.ids.photo.wrap).style.position = 'relative';
				$('adIsland').style.display = 'block';
				gallery.preroll.active = false;
				$clear(gallery.preroll.counting);
			}
		},
		
		initCountdown: function() {
			gallery.preroll.countdown.delay(1000);
			gallery.preroll.length = gallery.preroll.length - 1;
		},
		
		countdown: function() {
			var count = $(gallery.ids.preroll.count).getText();
			if (count > 0) {
				var count = $(gallery.ids.preroll.count).getText();
				count = (count * 1) - 1;
				$(gallery.ids.preroll.count).setText(count);
			} else {
				$clear(gallery.preroll.counting);
			}
		}
		
	}
	
	
};

window.addEvent('domready', function() { gallery.init(); });