document.observe("dom:loaded", function() {									
	sentBy();
	uploadForm();
	getContactPage();
	externalLinks();
	langChange();
	uploadSelectForm();
	
	selectOption('lang-change', selectChange);	
});


// Get the language from the url and then add a selected="selected" to 
// the option when you choose one
var currentPath = new String(document.location.pathname); 
var urlArray = currentPath.split('/'); 
var splitUrl = (urlArray[1]);
var selectChange = '/' + splitUrl + '/';

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++; 
    	} 
   	);       
}

// When you choose a language go to that page
function langChange() {
	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 + '/';
		}
		
	});
}

// Cookie functions to create/read/delete cookies for sent by/icon fade/show
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+escape(value)+expires+"; path=/";
	// alert('createCookie '+value) ;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {
			// alert('readCookie '+name+ ' ' + ' cookie = ' + c + ' value = ' + c.substring(nameEQ.length,c.length)) ;
			return unescape(c.substring(nameEQ.length,c.length));
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



// Ajax pagination of photo thumbs
var updateLinks = function() {
	var links = $$("ul.pagination li a");
	if (links) {
		links.each(
			function(getLink) {
				getLink.observe('click', function(event) {
					Event.stop(event);
					updateGallery(this.href);
				});
			}
		)
	}
}

// Get the href of page for thumbs and pass to ajax request
// and on mouseover of thumbs set opacity
var initImages = function() {
	
	var thumbs = $$("div.thumbs a img");
	
	if (thumbs) {
		thumbs.each(
			function(thumbLink) {
				thumbLink.observe('mouseover', function(event) {
					this.fade({
						duration: 0.3,
						from: 1,
						to: 0.7
					});
				});
				thumbLink.observe('mouseout', function(event) {
					this.appear({
						duration: 0.3,
						from: 0.7,
						to: 1
					});
				});
				thumbLink.observe('click',function(event) {
					Event.stop(event);
					var thumbRel = this.up(0).readAttribute('rel');
					var fullsizeHref = '/' + splitUrl + '/image-fullsize/page_' + thumbRel + '/';
					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(event);	
		
		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 > totalPagesNumber) {
			$("page-error").appear();
		} else if (pageNumberResult2 > totalPagesNumber2) {
			$("page-error").appear();
		} else {
			var langSection = $("gallery-pagination").up(2).down("li").readAttribute("rel");
			var thumbHref = '/' + langSection + '/photo-thumbs/page_' + pageNumberResult2 + '/'
			updateGallery(thumbHref);
		}
		
    });  
		
}

// Update sidebar thumbs
var updateGallery = function(url) {	
	new Ajax.Request(url,
		{
			onComplete: function(transport) {
				$("sidebar-container").update(transport.responseText);
				updateLinks();
				initImages();
			}
		}
	);
}


// Get the previous/next links for the fullsize image
var initFullsizeImage = function() {
	var nextPreviousLinks = $$("div#image-fullsize a");
	if (nextPreviousLinks) {
		nextPreviousLinks.each(
			function(getnextPreviousLink) {
				getnextPreviousLink.observe('mouseover', function(event) {
					this.fade({
						duration: 0.3,
						from: 1,
						to: 0.7
					});
				});
				getnextPreviousLink.observe('mouseout', function(event) {
					this.appear({
						duration: 0.3,
						from: 0.7,
						to: 1
					});
				});
				getnextPreviousLink.observe('click', function(event) {
					Event.stop(event);
					updateFullsizeImage(this.href);
				});
			}
		)
	};
	
	sentBy();
}

// Replace fullsize photo image with thumbnail from gallery
var updateFullsizeImage = function(url) {
	new Ajax.Request(url,
		{
			onComplete: function(transport) {
				$("image-fullsize").update(transport.responseText);
				initFullsizeImage();
				showAllPhotoInfo();
			}
		}
	);
}


// Fade in/out sent by icon/box	
function sentBy() {
	var iconSend = $$("div#content div.icon-sent-by");
	if (iconSend) {
		iconSend.each (
			function(closeIconSend) {
				closeIconSend.observe('click',iconFade);
			}
		)
	};

		
	var sentByBox = $$("div#content div.sent-by-close");
	if (sentByBox) {
		sentByBox.each (
			function(sentByBoxClose) {
				sentByBoxClose.observe('click',iconAppear);
			}
		)
	}
}

function iconFade(event) {
	var iconFadeAll = $$("div#content div.icon-sent-by");
	iconFadeAll.each (
		function(icon) {
			icon.fade();
			icon.next().appear();
		}
	);

	createCookie('zoomzoom_sentby','show',365);
}

function iconAppear(event) {
	var iconAppearAll = $$("div#content div.sent-by-close");
	iconAppearAll.each (
		function(iconShow) {
			iconShow.up(0).fade();
			iconShow.up(0).previous().appear();
		}
	);
	
	eraseCookie('zoomzoom_sentby');
	
}

// If zoomzoom cookie is set to show show all sent by boxes and hide all icons
function showAllPhotoInfo() {
	if (readCookie('zoomzoom_sentby') == 'show') {
		$$("div.icon-sent-by").each(
			function(showAllPhotoInfos) {
				showAllPhotoInfos.hide();
				showAllPhotoInfos.next(0).show();
			}
		)
	}
}


// Update sidebar video thumbs
var updateVideoGallery = function(url) {	
	new Ajax.Request(url,
		{
			onComplete: function(transport) {
				$("sidebar-video-container").update(transport.responseText);
				updateVideoLinks();
				initVideoImages();
			}
		}
	);
}

// Ajax pagination of video thumbs
var updateVideoLinks = function() {
	var videolinks = $$("ul.pagination li a");
	if (videolinks) {
		videolinks.each(
			function(getVideoLink) {
				getVideoLink.observe('click', function(event) {
					Event.stop(event);
					updateVideoGallery(this.href);
				});
			}
		)
	}
}

// Get the href of page for thumbs and pass to ajax request
// and on mouseover of thumbs set opacity
var initVideoImages = function() {
	
	var langSection2 = $("video-gallery-pagination").up(2).down("li").readAttribute("rel");
	
	var videoThumbs = $$("div.video-thumbs a img");
	
	if (videoThumbs) {
		videoThumbs.each(
			function(videoThumbLink) {
				videoThumbLink.observe('mouseover', function(event) {
					this.fade({
						duration: 0.3,
						from: 1,
						to: 0.7
					});
				});
				videoThumbLink.observe('mouseout', function(event) {
					this.appear({
						duration: 0.3,
						from: 0.7,
						to: 1
					});
				});
				videoThumbLink.observe('click',function(event) {
					Event.stop(event);
					var videoThumbRel = this.up(0).readAttribute('rel');
					var fullsizeVideoHref = '/' + langSection2 + '/video-pages/' + videoThumbRel;
					updateFullsizeVideo(fullsizeVideoHref);					
				});
			}
		)
	};
		
	
	var videoHeadline = $$("div.video-thumbs h3 a");
	
	if (videoHeadline) {
		videoHeadline.each(
			function(videoHeadlineLink) {
				videoHeadlineLink.observe('click',function(event) {
					Event.stop(event);
					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 = $("video-gallery-pagination");
		
	videoGalleryForm.observe('submit', function(event) {
		Event.stop(event);
				
		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 > totalVideoPagesNumber) {
			$("page-error").appear();
		} else if (videoPageNumberResult2 > totalVideoPagesNumber2) {
			$("page-error").appear();
		} else {
			var thumbVideoHref = '/' + theLang + '/video-pages/page_' + videoPageNumberResult + '/'
			updateVideoGallery(thumbVideoHref);
		}
				
		
    });  
	
	
}

// Replace fullsize video with thumbnail from gallery
var updateFullsizeVideo = function(url) {
	new Ajax.Request(url,
		{
			onComplete: function(transport) {
				$("video-container").update(transport.responseText);
			}
		}
	);
}


// Add the second bg image to upload page
function uploadForm() {
	var form = $("form-upload");
	if (form) {
		form.down(3).next(2).addClassName("about").insert ({
        	'bottom' : '<div id="bg-about-your-video"><!-- x --></div>'
  		});
	}
}


// Contact Popup
function getContactPage() {
	
	var getContactLink = $("contact-us").down(0);

	new Ajax.Request(getContactLink.href,
		{
			onComplete: function(transport) {
				$("contact-us-info").update(transport.responseText);
				closeContactLink();
			}
		}
	)
	
	getContactLink.observe('click',function(event) {
		Event.stop(event);
		$("contact-us-info").appear();
	});
	
	function closeContactLink() {		
		$("close-contact").observe('click',function(event) {
			$("contact-us-info").fade();
		});
	}	

}



// 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";
		//obj.className = "external";
	};
	for (var i=0;i<a.length;i++){
		if(check(a[i])) set(a[i]);
	};
}

// 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#form-upload select");
	if (uploadSelect) {
		uploadSelect.each(
			function(uploadSelectOther) {
				uploadSelectOther.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(0).setStyle({ 'width': '55px' }).insert ({
        					'after' : '<input type="text" id="other-option" name="Nationality_Other"/>'
  						});
						
						
						this.observe('mousedown',function(event) {
							event.element().setStyle({ 'width': 'auto' });
						});
						this.observe('blur',function(event) {
							event.element().setStyle({ 'width': '55px' });
						});
						this.observe('change',function(event) {
							event.element().setStyle({ 'width': '55px' });
						});
						
						
					}
					else {
						if($("other-option")) {
							this.removeClassName("shrink").addClassName("expand").up(0).setStyle({ 'width': '297px' }).next().remove();
						}
					}
				});
			}
		)
	}
}