var galleries;

$(function() {
	// wait for safari - (timing problems onload)
	if (jQuery.browser.safari && document.readyState != "complete"){
		setTimeout( arguments.callee, 100 );
		return;
	} 
	// init gallery
	galleries = $('.ad-gallery').adGallery();
	init_resize_gallery();
});

$(document).ready(function() {
	var isIE6 = !$.support.opacity && !window.XMLHttpRequest;
	var overlay;
	var contact_details;

	$('div.contact-html').hide();
	$('a.contact').click(function() {
		// ajax request to load contact data, easy fallback w/o javascript to standard anchor
		if(contact_details == undefined) {
			$.get('./contact.html', function(data) {
				contact_details = data;
				$('div.contact-html').html(contact_details);
				// close anchor
				$('div.contact-html a#close').click(function() {
					hideContact();
				});
				showContact();
			});
		} else {
			showContact();
		}
		return false;
	});

	
	showContact = function() {
		if(overlay == undefined) {
			$('body').append(
				overlay = $('<div id="fancybox-overlay"></div>')
			);
		}
		if (isIE6) {
			$('select:not(#fancybox-tmp select)').filter(function() {
				return this.style.visibility !== 'hidden';
			}).css({'visibility':'hidden'}).one('fancybox-cleanup', function() {
				this.style.visibility = 'inherit';
			});
		}

		overlay.css({
			'background-color'	: "#000",
			'opacity'			: "0.8"
		}).unbind().fadeIn('fast');
		$('div.contact-html').fadeIn(300);
		
		overlay.click(function() {
			hideContact();
		});
	}
	
	hideContact = function() {
		overlay.fadeOut('fast');
		$('div.contact-html').hide();
	}
	
	// handle touch events	
	initTouchEvents();
	
	function initTouchEvents() {
	    $('div.ad-next').each(function() {
			this.addEventListener("touchend", adGalleryNext, true);
		});
		
		$('ul.ad-thumb-list li a').each(function(index) {
			this.addEventListener("touchend", function (event) {
				galleries[0].showImage(index);
				}, true
			);
		});
	}
	
	function adGalleryNext(event) {
		galleries[0].showImage(galleries[0].nextIndex());
	}

	
});

