$(document).ready(function(){
	attachExpands();
});

function attachExpands() {
	$(".imagelist .item").click(function(event){
		var me = $(this),
			sibling = null;

		if (me.hasClass('right')) {
			sibling = me;
		} else {
			var siblings = me.nextAll('.right:first');
			if (siblings.length > 0) {
				sibling = siblings;
			} else {
				sibling = $('.item:last');
			}
		}
		sibling.caller = me;
		
		$.ajax({
			context: sibling,
			url: me.children('.details').attr('href'),
			data: { 'ajax': true },
			success: function(data) {
				$('#details-arrow').remove();
				$(this.caller).children('.details').after('<img id="details-arrow" src="images/details-arrow.png" alt="" />');
				var details = $('#details');
				if ($(this).next().attr('id') == 'spacefiller') {
					details.replaceWith(data);
					$('#details').fadeIn(400);
				} else {
					if (details.length != 0) {
						$('#spacefiller').remove();
					}
					$(this).after('<div id="spacefiller" style="height: 500px; width: 960px; float: left;">&nbsp;</div>');
					$('#spacefiller').html(data);
					$('#details').slideDown(400, function() {
						$('html, body').animate(
							{
								scrollTop: ($(this).offset().top+500) - $(window).height()
							},
							200
						);
					});
				}
			}
		});

		event.preventDefault();
		event.stopPropagation();
	});
}

function addToSelection(o, id, title) {
	trackAddToSelection(id, title);
	
	$.ajax({
		url: 'my-selections',
		type: 'post',
		data: { 'ajax': true, 'add': id },
		success: function(data) {
			$('#selection-count').text(data.length);
			$('#my-selection-tb-num').text(data.length);
			if (data.length == 0) {
				$('#selection-link').hide();
				$('#selection-empty').show();
				$('#my-selection-tb').hide();
			} else {
				$('#selection-link').show();
				$('#selection-empty').hide();
				$('#my-selection-tb').show();
			}
			$(o).parent().fadeOut(200, function(){
				$('#removefromselection').fadeIn();
			});
			
		}
	});
}
function removeFromSelection(o, id) {
	$.ajax({
		url: 'my-selections',
		type: 'post',
		data: { 'ajax': true, 'remove': id },
		success: function(data) {
			$('#selection-count').text(data.length);
			$('#my-selection-tb-num').text(data.length);
			if (data.length == 0) {
				$('#selection-link').hide();
				$('#selection-empty').show();
				$('#my-selection-tb').hide();
			} else {
				$('#selection-link').show();
				$('#selection-empty').hide();
				$('#my-selection-tb').show();
			}
			$(o).parent().fadeOut(200, function(){
				$('#addtoselection').fadeIn();
			});
			
		}
	});
}

function showTerms(lang, oid, type, embed) {
	$('#detailsterms .scroll').html($('#terms-'+lang).html());
	if (typeof oid !== 'undefined') {
		$('#termsdownloadbutton').unbind('click');
		$('#termsdownloadbutton').attr('href', '/download.php?oid='+oid+'&type='+type);
		$('#termsdownloadbutton').text('I accept - Download');
		$('#termsdownloadbutton').click(function(event) {
			var me = $(this),
				id = IBSImage.id,
				title = IBSImage.title,
				urlifiedtitle = IBSImage.urlifiedtitle,
				photographer = IBSImage.photographer,
				from = IBS.downloadLocation,
				format = type,
				href = me.attr('href');
			
			trackDownload(from, id, title, urlifiedtitle, format, photographer, href);
			
			try {
				event.preventDefault ? event.preventDefault() : event.returnValue = false;
				event.stopPropagation();
			} catch (e) {}
			return false;
		});
		
		$('#termscancelbutton').unbind('click');
		$('#termscancelbutton').click(function() {
			trackDeniedDownload();
		});
		
		$('#termslanguage option').attr('selected', '');
		$('#termslanguage option').first().attr('selected', 'selected');
		$('#details a.share + ul').hide();
		$('#detailsterms').fadeIn();
	}
	if (typeof embed !== 'undefined') {
		$('#termsdownloadbutton').unbind('click');
		$('#termsdownloadbutton').click(function(event) {
			if ($(embed).next().css('display') == 'none') {
				trackAcceptEmbed(IBSImage.id, IBSImage.urlifiedtitle);
				
				$('#detailsterms').hide();
				$('#share-email-dialog-details').hide();
				$('#details a.share + ul').hide();
				$('#update-embed-details').click();
				$(embed).next().slideDown(200, 'swing');
				
			    $('input#copy-embed-details').zclip({
			        path:'flash/ZeroClipboard.swf',
			        copy:function(){return $('textarea#embed-code').val();}
			    });
			}
			event.preventDefault();
		});
		$('#termsdownloadbutton').text('I accept');
		
		$('#termscancelbutton').unbind('click');
		$('#termscancelbutton').click(function() {
			trackDeniedEmbed();
		});
		
		$('#termslanguage option').attr('selected', '');
		$('#termslanguage option').first().attr('selected', 'selected');
		$('#details a.share + ul').hide();
		$('#detailsterms').fadeIn();
	}
}

$('#details a.share').live('click', function(event){
	if ($(this).next().css('display') == 'none') {
		$('#detailsterms').hide();
		$('#share-email-dialog-details').hide();
		$('#embed-dialog-details').hide();
		$(this).children('img').css({'clip': 'rect(0px 20px 20px 0px)', 'left': '4px'});
		$(this).next().slideDown(200, 'swing');
	} else {
		$(this).next().slideUp(200, 'swing');
		$('#share-email-dialog-details').slideUp(200, 'swing');
	}
	event.preventDefault();
});

$('#share-email-details').live('click', function(event) {
	//$('#details a.share').next().hide();
	$('#share-email-dialog-details').show();
	event.preventDefault();
});
$('#cancel-email-details').live('click', function(event) {
	$('#details a.share').children('img').css({'clip': '', 'left': ''});
	$('#details a.share').css('background', 'none');
	$('#details .toolbar-drop').hide();
	$('#share-email-dialog-details').slideUp(200, 'swing');
});
$('#share-email-dialog-details').live('submit', function(event) {
	$.ajax({
		'url': 'share.php?from='+IBS.downloadLocation,
		'data': $(this).serialize(),
		'type': 'post',
		'beforeSend': function() {
			$(this).children('img').show();
		},
		'error': function(data) {
			$('#share-email-dialog-details img').hide();
			$('#share-email-dialog-details p').text(data.responseText);
		},
		'success': function(data) {
			trackShare('e-mail', IBSImage.id, IBSImage.urlifiedtitle);
			$('#share-email-dialog-details div').first().fadeOut(200, 'swing', function() {
				$(this).hide();
				$('#details-thanks').fadeIn(200, 'swing');
			});
		}
	});
	event.preventDefault();
});
$('#details-thanks input[type="button"]').live('click', function() {
	$('#share-email-dialog-details').children('img').hide();
	$('#details a.share').children('img').css({'clip': '', 'left': ''});
	$('#details a.share').css('background', 'none');
	$('#details a.share ul').slideUp(200, 'swing');
	$('#share-email-dialog-details').slideUp(200, 'swing', function() {
		$('#details-thanks').hide();
		$('#share-email-dialog-details div').first().show();
		$('#email-details').val('');
		$('#message-details').val('');
		$('#sender-details').val('');
	});
});
$('#message-details').live('focus', function() {
	if ($(this).val() == 'Your message here...') {
		$(this).val('');
	}
});

$('#details .short-description a.toggledescr').live('click', function(event){
	$(this).parents('#detailsinfo').children('.short-description, dl').fadeOut(200, function(){
		$(this).parents('#detailsinfo').children('.long-description').fadeIn(200);
	});
	event.preventDefault();
});
$('#details .long-description a.toggledescr').live('click', function(event){
	$(this).parents('#detailsinfo').children('.long-description').fadeOut(200, function() {
		$(this).parents('#detailsinfo').children('.short-description, dl').fadeIn(200);
	});
	event.preventDefault();
});

$('#show-on-map').live('click', function(event){
	var img = $(this).siblings('img');
	var url = $(this).attr('href');
	img.fadeOut(200, function(){
		img.attr('src', url);
		$('#show-on-map').hide();
		$('#show-image').show();
		img.fadeIn(200);
	});
	event.preventDefault();
});
$('#show-image').live('click', function(event){
	var img = $(this).siblings('img');
	img.fadeOut(200, function(){
		img.attr('src', 'images/blank.gif');
		$('#show-on-map').show();
		$('#show-image').hide();
		img.fadeIn(200);
	});
	event.preventDefault();
});


var embedTpl = '<iframe width="{width}" height="{height}" src="{source}/{width}" frameborder="0"></iframe>';
function updateEmbedCode(source, newwidth, width, height) {
	var ratio = width > height ? (width / height) : (height / width),
		newheight = Math.ceil((newwidth / ratio) + 30);
		embed = embedTpl.replace(/\{width\}/g, newwidth).replace(/\{height\}/g, newheight).replace('{source}', source);
	$('#embed-code').val(embed);
}

$('#details li#embed a').live('click', function(event){
	showTerms('english', null, null, this);
	event.preventDefault();
});

function updateEvent(event) {
	var source = $('[name=source]').val(),
		width = $('[name=width]').val(),
		height = $('[name=height]').val(),
		newwidth = $('[name=embed-width]').val();
	
	updateEmbedCode(source, newwidth, height, width);
	
	event.preventDefault();
}

$('#update-embed-details').live('click', updateEvent);
$('#embed-dialog-details').live('submit', updateEvent);

$('#close-embed-details').live('click', function(event) { $('#embed-dialog-details').slideUp(); });

$('a[rel="terms"]').live('click', function(event) {
	window.open($(this).attr('href')+'?popup=1', 'termswindow', 'width=1000,height=800,scrollbars=yes,resizable=yes');
	event.preventDefault();
});


