document.observe("dom:loaded", function() {
	externalLinks();
	navigation();
	contactUs();
	changeLanguage();
	uploadSelectForm();
	selectOption('lang-change', selectChange);
});

Event.observe(window, 'load', function() {
	var spinner = $('spinner');
	if (spinner) {
		spinner.fade();
	}
	
	var homepage = $('homepage');
	if (homepage) {
		homepageImageRotate();
	}
});

fbPageOptions = {
	showHints: 'never'
};


/**
 * Make external links open new window/tab
 */
function externalLinks() {
	var hostname = window.location.hostname;
	hostname = hostname.replace("www.","").toLowerCase();
	var a = document.getElementsByTagName("a");
	this.check = function(obj){
		var href = obj.href.toLowerCase();
		if ( href.indexOf("http://") != -1 &&
			 href.indexOf("zzmomments.com") == -1 &&
			 href.indexOf(hostname)==-1 )
			 return true ;
		else
			return false;
	};
	this.set = function(obj){
		obj.target = "_blank";
	};
	for (var i=0;i<a.length;i++){
		if(check(a[i])) set(a[i]);
	};
}


/**
 * When you mouseover a navigation item remove the on class from its siblings and hide and the subnav (span)
 * On mouseout restore the original navigation item
 */
function navigation() {
	var navigation = $('menu');
	var originalNavItem = navigation.down('.on');
	
	navigation.observe('mouseover',
		function(event) {
			var navItem = Event.findElement(event,'a');
			if (navItem) {
				var li = navItem.up().siblings();
				li.each(
					function(liItem) {
						liItem.down().removeClassName('on');
						var span = liItem.down('span');
						if (typeof span !== 'undefined') {
							span.addClassName('hide');
						}
					}
				);
				
				var span = navItem.down();
				if (span) {
					span.removeClassName('hide');
				}
			}
		}
	).observe('mouseout',
		function(event) {
			var navItem = Event.findElement(event,'a');
			if (navItem) {				
				navigation.down('.hide').removeClassName('hide');
				originalNavItem.addClassName('on');
				
				var span = originalNavItem.down();
				if (span) {
					span.removeClassName('hide');
				}
				
				originalNavItem.up().siblings().each(
					function(old) {
						var span = old.down('span');
						if (span) {
							span.addClassName('hide');
						}
					}
				);
			}
		}
	);
}


/**
 * Show the contact us info div when contact us is clicked
 */
function contactUs() {
	var contactUsInfo = $('contact-us-info');	
	$('footer').observe('click',
		function(event) {			
			var contactUs = Event.findElement(event,'#contact-us a');
			if (contactUs) {
				event.stop();
				contactUsInfo.appear();
			}
			
			var closeContact = Event.findElement(event,'#close-contact');
			if (closeContact) {
				contactUsInfo.fade();
			}
		}
	);
}


/**
 * Cycle the images on the homepage through a set of 12 images, going clockwise
 * Wait 3 seconds before each image swap
 */
function homepageImageRotate() {
	var timer = null;
	
	// wait 3 seconds between each effect
	timer = setTimeout(fadeImage,3000);
	
	var images = $('images');
	images.on('click', 'img',
		function(event, element) {
			window.location = 'photos/';
		}
	);
	
	function fadeImage() {
		clearTimeout(timer);
		
		var imageTofade = images.down('img.active');		
		if (imageTofade) {
			var numberOfSiblings = imageTofade.nextSiblings().size();	
			
			// there are 12 images to cycle through, if we're at number 8 then the image to swap to falls back to 1, if image 9 then image to swap to is the second etc
			if (numberOfSiblings > 3) {
				var nextImageToShow = imageTofade.next(3);
			} else {
				// when you get to the last set of 4 images (e.g. 9 to 12) map the next image to show as one of the first 4 images
			    var nextImageToShowIndex = Math.abs(numberOfSiblings - 3);
			    var nextImageToShow = images.childElements()[nextImageToShowIndex];
			}
			
			imageTofade.fade({duration: 2.0}).removeClassName('active');
			
			
			new Effect.Appear(nextImageToShow, {
				duration: 2.0,
				afterFinish: function() {
					// after the appear is finished set the appropriate active class and run the homepageImageRotate function again
					var imageTofade2 = imageTofade.next();
					if (imageTofade2) {
						imageTofade.next().addClassName('active');
					} else {
						var firstImage = images.down();
						firstImage.addClassName('active');
					}
					
					homepageImageRotate();
				}
			});
		
		}
				
	}

}


/**
 * When you select a language from the drop down go the relevant page
 * and add selected="selected" when you're in a language
 */
var currentPath = new String(document.location.pathname);
var urlArray = currentPath.split('/');
var splitUrl = (urlArray[1]);
var selectChange = '/' + splitUrl + '/';

function changeLanguage() {
	var langSection = (urlArray[2]);
	
	$("lang-change").observe('change',
		function(event) {
			var langValue = this.options[this.selectedIndex].value;
			
			if (langSection == '') {
				window.location = langValue
			} else {
				window.location = langValue + langSection + '/';
			}
		}
	);	
	
}

selectOption = function(select, optionValue) {
	var index = 0; 
	
	$(select).childElements().each( 
		function(option) { 
			if (option.value == optionValue) { 
				option.writeAttribute( { selected: 'selected' } ); 
				/* below line is needed for Webkit browsers */ 
				$(select).selectedIndex = index; 
				throw $break; 
			} 
		index++; 
		} 
	);       
}


/**
 * Get the previous/next link urls for the fullsize image and pass to ajax request
 */
var initFullsizeImage = function() {
	var nextPreviousLinks = $$('#image-container a');
	if (nextPreviousLinks) {
		nextPreviousLinks.each(
			function(getNextPreviousLink) {
				getNextPreviousLink.observe('mouseover', function(event) {
					this.fade({
						duration: 0.3,
						from: 1,
						to: 0.7
					});
				}).observe('mouseout', function(event) {
					this.appear({
						duration: 0.3,
						from: 0.7,
						to: 1
					});
				}).observe('click', function(event) {
					event.stop();
					
					// If you click the next arrow on fullsize image and the next image is the 16th, also change the thumbs container
					var numberOfThumbs = $$('.thumbs img').size();
					
					var imageNumber = event.element().up().down('#fullsize-image').readAttribute('imagenumber');

					if (this.hasClassName('next-image')) {
						var nextThumb = $('next-thumb');
						if (nextThumb && (imageNumber % numberOfThumbs == '0')) {
							var url = nextThumb.href;
							updateGallery(url);
						}
					} else if (this.hasClassName('previous-image')) {
						var previousThumb = $('previous-thumb');
						if (previousThumb && ((imageNumber - 1) % numberOfThumbs == '0')) {
							var url = previousThumb.href;
							updateGallery(url);
						}
					}
					
					updateFullsizeImage(this.href);
					
				});
			}
		)
	};
	
}


/**
 * Replace fullsize photo image with thumbnail from gallery
 */
var updateFullsizeImage = function(url) {
	var imageContainer = $('image-container');
	var spinner = $('spinner');
	
	new Ajax.Request(url,
		{
			onComplete: function(transport) {
				spinner.show();
				
				/*var cloned = document.createElement('div');
				Element.extend(cloned);
				cloned.writeAttribute('id','cloned');
				
				imageContainer.setOpacity(0.5).insert({'before' : cloned});
				
				cloned.hide().update(transport.responseText);
				
				var fullsizeImage = $$('#cloned img')[0];
				
				// check if image has loaded, when done show the image and hide the spinner
				new PeriodicalExecuter(function(pe) {
					var hasImageLoaded = fullsizeImage.complete;						
					if (hasImageLoaded === true) {
						spinner.hide();
						imageContainer.remove();
						cloned.writeAttribute('id','image-container').appear();
						pe.stop();
					}
				}, 0.2);*/
				
				imageContainer.addClassName('hidden').update(transport.responseText);
				
				var fullsizeImage = $('fullsize-image');
				fullsizeImage.hide();
				
				// check if image has loaded, when done show the image and hide the spinner
				new PeriodicalExecuter(function(pe) {
					var hasImageLoaded = fullsizeImage.complete;						
					if (hasImageLoaded === true) {
						imageContainer.removeClassName('hidden');
						spinner.hide();
						fullsizeImage.appear();
						pe.stop();
					}
				}, 0.2);
				
				initFullsizeImage();
				setSelectedThumb();
			}
		}
	);
}


/**
 * Add selected class to current thumb image
 */
function setSelectedThumb() {
	var imageFullsizeNumber = $('fullsize-image').readAttribute('imagenumber');
	$$('#thumbs-container img').each(
		function(image) {
			image.removeClassName('selected');
			var imageNumber = image.readAttribute('imagenumber');
			if (imageNumber == imageFullsizeNumber) {
				image.addClassName('selected');
			}
		}
	);
}


/**
 * Get the href of page for thumbs and pass to ajax request
 * and on mouseover of thumbs set opacity
 */
var initImages = function() {
	var thumbs = $$('.thumbs img');
	if (thumbs) {
		thumbs.each(
			function(thumbLink) {
				thumbLink.observe('click',function(event) {
					event.stop();
					var imageNumber = this.readAttribute('imagenumber');
					var fullsizeHref = '/' + splitUrl + '/image-fullsize/page_' + imageNumber + '/';
					updateFullsizeImage(fullsizeHref);
				});
			}
		)
	};						
	
	// Load new page when you choose your page number and hit enter
	var galleryForm = $("gallery-pagination");
		
	galleryForm.observe('submit', function(event) {
		event.stop();
		
		var pageError = $("page-error");
		var getPageNumber = galleryForm["page-number"];
		var pageNumberResult = $F(getPageNumber);	
		var totalPagesNumber = $("total-pages-number").innerHTML;
       
	   	pageNumberResult = pageNumberResult.replace(/[^0-9]/, '');
		
		var totalPagesNumber2 = parseInt(totalPagesNumber);
		var pageNumberResult2 = parseInt(pageNumberResult);
		
		
		if (pageNumberResult == '' || pageNumberResult < 1) {
			pageError.appear();
		} else if (pageNumberResult2 > totalPagesNumber2) {
			pageError.appear();
		} else {
			var langSection = $("gallery-pagination").up(2).down("li").readAttribute("rel");
			var thumbHref = '/' + langSection + '/photo-thumbs/page_' + pageNumberResult2 + '/';
			updateGallery(thumbHref);
			pageError.hide();
		}
		
    });  
		
}

/**
 * Update sidebar thumbs
 */
var updateGallery = function(url) {
	var thumbsContainer = $('thumbs-container');
	var spinner = $('spinner-sidebar');
	
	new Ajax.Request(url,
		{
			onComplete: function(transport) {
				spinner.show();
				
				thumbsContainer.addClassName('hidden');
				thumbsContainer.update(transport.responseText);
				
				var thumbs = $$('.thumbs')[0];
				thumbs.hide();
				
				// check if images have loaded, when done show the images and hide the spinner
				new PeriodicalExecuter(function(pe) {
					var thumbsHaveLoaded = true;
					$$('.thumbs img').each(
						function(image) {
							if (!image.complete) {
								thumbsHaveLoaded = false;
							}
						}
					);
						
					if (thumbsHaveLoaded === true) {
						thumbsContainer.removeClassName('hidden');
						spinner.hide();
						thumbs.appear();
						pe.stop();
					}
						
				}, 0.2);
				
				updateLinks();
				initImages();
				setSelectedThumb();
			}
		}
	);
}


/**
 * Ajax pagination of photo thumbs
 */
var updateLinks = function() {
	var links = $$('.pagination a');
	if (links) {
		links.each(
			function(getLink) {
				getLink.observe('click',
					function(event) {
						event.stop();
						updateGallery(this.href);
						$('page-error').hide();
					}
				);
			}
		)
	}
}





/* NEED TO CONDENSE THIS + MERGE WITH ABOVE if there is time (which if you're reading this there wasn't) */


// Update sidebar video thumbs
var updateVideoGallery = function(url) {	
	new Ajax.Request(url,
		{
			onComplete: function(transport) {
				$("thumbs-container").update(transport.responseText);
				updateVideoLinks();
				initVideoImages();
			}
		}
	);
}

// Ajax pagination of video thumbs
var updateVideoLinks = function() {
	var videolinks = $$(".pagination a");
	if (videolinks) {
		videolinks.each(
			function(getVideoLink) {
				getVideoLink.observe('click', function(event) {
					Event.stop(event);
					updateVideoGallery(this.href);
					$('page-error').hide();
				});
			}
		)
	}
}

// Get the href of page for thumbs and pass to ajax request
// and on mouseover of thumbs set opacity
var initVideoImages = function() {
	
	var langSection2 = $("gallery-pagination").up(2).down("li").readAttribute("rel");
	
	var videoThumbs = $$(".video a img");
	
	if (videoThumbs) {
		videoThumbs.each(
			function(videoThumbLink) {
				videoThumbLink.observe('mouseover', function(event) {
					this.fade({
						duration: 0.3,
						from: 1,
						to: 0.7
					});
				}).observe('mouseout', function(event) {
					this.appear({
						duration: 0.3,
						from: 0.7,
						to: 1
					});
				}).observe('click',function(event) {
					event.stop();
					var videoThumbRel = this.up(0).readAttribute('rel');
					var fullsizeVideoHref = '/' + langSection2 + '/video-pages/' + videoThumbRel;
					updateFullsizeVideo(fullsizeVideoHref);					
				});
			}
		)
	};
		
	
	var videoHeadline = $$(".video h3 a");
	
	if (videoHeadline) {
		videoHeadline.each(
			function(videoHeadlineLink) {
				videoHeadlineLink.observe('click',function(event) {
					event.stop();
					var videoThumbRel2 = this.up(0).previous(0).readAttribute('rel');
					var fullsizeVideoHref2 = '/' + langSection2 + '/video-pages/' + videoThumbRel2;
					updateFullsizeVideo(fullsizeVideoHref2);					
				});
			}
		)
	};
	
	// Load new page when you choose your page number and hit enter
	var videoGalleryForm = $("gallery-pagination");
		
	videoGalleryForm.observe('submit', function(event) {
		event.stop();
		

		var pageError = $("page-error");
		var getVideoPageNumber = videoGalleryForm["video-page-number"];
		var videoPageNumberResult = $F(getVideoPageNumber);
		var totalVideoPagesNumber = $("total-pages-number").innerHTML;
		
		
		
		var getLang = videoGalleryForm["lang"];
		var theLang = $F(getLang);	
       
	   	videoPageNumberResult = videoPageNumberResult.replace(/[^0-9]/, '');
		
		var totalVideoPagesNumber2 = parseInt(totalVideoPagesNumber);
		var videoPageNumberResult2 = parseInt(videoPageNumberResult);
		
		if (videoPageNumberResult == '' || videoPageNumberResult < 1) {
			pageError.appear();
		} else if (videoPageNumberResult2 > totalVideoPagesNumber2) {
			pageError.appear();
		} else {
			var thumbVideoHref = '/' + theLang + '/video-pages/page_' + videoPageNumberResult + '/'
			updateVideoGallery(thumbVideoHref);
			pageError.hide();
		}
				
		
    });  
	
	
}

// Replace fullsize video with thumbnail from gallery
var updateFullsizeVideo = function(url) {
	new Ajax.Request(url,
		{
			onComplete: function(transport) {
				$("video-container").update(transport.responseText);
			}
		}
	);
}



/**
 * When other option is selected on upload page shrink the select menu and add
 * an input box so user can type their custom country
 */
function uploadSelectForm() {
	var uploadSelect = $$('#form-upload select')[0];
	if (uploadSelect) {
		uploadSelect.observe('change',
			function(event) {
				var other = this.options[this.selectedIndex].value;
				// en, fr, de, nl, es, it, thai
				if (other == 'Other' || other == 'Autre' || other == 'Anderes' || other == 'Andere' || other == 'Otro' || other == 'Altro' || other == 'อื่น') {
					this.removeClassName("expand").addClassName("shrink").up().setStyle({ 'width': '55px' }).insert ({
						'after' : '<input type="text" id="other-option" name="Nationality_Other"/>'
					});
					
					// only run if less than IE9
					if (document.documentMode < 9 || typeof document.body.style.maxHeight == 'undefined') {
						this.observe('mousedown',function(event) {
							event.element().setStyle({ 'width': 'auto' });
						}).observe('blur',function(event) {
							event.element().setStyle({ 'width': '55px' });
						}).observe('change',function(event) {
							event.element().setStyle({ 'width': '55px' });
						});
					}

				} else {
					if($('other-option')) {
						this.removeClassName("shrink").addClassName("expand").up().setStyle({ 'width': '297px' }).next().remove();
					}
				}
			}
		);
	}
}
