/*** exif data -- toggler ***/

$(function () {
	var open = false;
	
	$('div.camera-info').hide();
	$('div.camera-info-short').show();
	$('div.camera-info-toggle a').click(function(e) {
		
		stop(e);
		
		this.blur();
		
		if (!open) {
			$(this).attr('title', LESS).html(LESS).addClass('open');
			$('div.camera-info').fadeIn('fast');
			$('div.camera-info-short').hide();
		}
		else {
			$(this).attr('title', MORE).html(MORE).removeClass('open');
			$('div.camera-info').hide();
			$('div.camera-info-short').fadeIn('fast');
		}
		
		
		open = !open;
	});
});

/*** embed controls ***/

$(function () {
	var controls = $('.embed-controls');
	var small = controls.find('input.small');
	var medium = controls.find('input.medium');
	var large = controls.find('input.large');
	var embed = $('.embed-code').find('textarea');
	
	function setEmbedCode(mediaId, size) {
		var url = DYNAMIC_BASE+'/ajax/media/embed-code';
		$.getJSON(url, { mediaId: mediaId, size: size }, function (d) {			
			embed.val(d);
		});
	}
	
	small.click(function (e) {
		setEmbedCode(MEDIA_ID, 'small');
	});
	
	medium.click(function (e) {
		setEmbedCode(MEDIA_ID, 'medium');
	});

	large.click(function (e) {
		setEmbedCode(MEDIA_ID, 'large');
	});
});

/*** ajax comments ***/

$(function () {
	if (AJAX_COMMENTS) {
		
		var ajaxUrl = DYNAMIC_BASE+'/ajax/media/comment';
		
		var commentSubmit = $('div.comment-form input.submit');
		var commentBody = $('div.comment-form textarea');
		var commentsUl = $('div.media-comments ul:first');
		
		function buildLi(result, last) {
			var li = $('<li/>').addClass('clearfix');
			if (last) {
				li.addClass('last');
			}
			li.html(result.html);
			/*
			var commentDiv = $('<div/>').addClass('comment');			
			var anchor = $('<a/>').attr('name', 'comment-'+result.id);
			var postedSpan = $('<span/>').addClass('posted');
			postedSpan.html(result.posted);
			var dateSpan = $('<span/>').addClass('date');
			dateSpan.html('now');
			var bodyDiv = $('<div/>').addClass('body');
			bodyDiv.html(result.body);
			var avatarA = $('<a/>').addClass('avatar');
			var avatar = $('<img/>').attr('src', DYNAMIC_BASE+result.avatar).attr('alt', result.username);
			avatarA.append(avatar);
			bodyDiv.prepend(avatarA);
			var actionsDiv = $('<div/>').addClass('actions');
			var reply = $('<a/>').addClass('reply').addClass('link').attr('href', '#').attr('title', 'Reply').html('Reply');
			actionsDiv.append(reply);
			bodyDiv.append(actionsDiv);
			commentDiv.append(anchor).append(postedSpan).append(dateSpan).append(bodyDiv);
			li.append(commentDiv);*/
			return li;
		}
		
		function buildReplyPopup() {
			var popupDiv = $('<div/>').addClass('reply-popup');			
			var form = $('<form/>');
			var fieldset = $('<fieldset/>');
			var dl = $('<dl/>').addClass('clearfix');
			var commentDt = $('<dt/>');
			var commentLabel = $('<label/>').html('Comment');
			var commentDd = $('<dd/>');
			var commentTextarea = $('<textarea/>').attr('cols', '20').attr('rows', '5');
			var commentSubmit = $('<input/>').attr('type', 'submit').attr('value', 'Submit').addClass('submit');
			var closeA = $('<a/>').attr('href', '#').attr('title', '#').html('Close').addClass('link').addClass('close');
			dl.append(commentDt.append(commentLabel)).append(commentDd.append(commentTextarea));
			form.append(fieldset.append(dl).append(commentSubmit));
			popupDiv.append(form).append(closeA);			
			return popupDiv;
		}
		
		function buildCommentStyle() {
			var div = $('<div/>').addClass('comment-style').addClass('clearfix');

			if (COMMENT_STYLE == 'list') {
				div.append($('<span/>').addClass('comment-style-list').attr('title', 'Sort by date').append($('<span/>').html('list')));
			}
			else {
				div.append($('<a/>').attr('href', '/media/comment-style?style=list&return='+encodeURI(document.location.href)).attr('title', 'Sort by date').addClass('comment-style-list').html('list'));
			}

			if (COMMENT_STYLE == 'thread') {
				div.append($('<span/>').addClass('comment-style-thread').attr('title', 'Sort by thread').append($('<span/>').html('thread')));
			}
			else {
				div.append($('<a/>').attr('href', '/media/comment-style?style=thread&return='+encodeURI(document.location.href)).attr('title', 'Sort by thread').addClass('comment-style-thread').html('thread'));
			}
			
			return div;
		}
		
		commentSubmit.click(function (e) {
			stop(e);			
			commentSubmit.attr('disabled', true);
			var body = commentBody.attr('value');
			if (body == '') {
				return;
			}
			$.post(
				ajaxUrl,
				{ mediaId: MEDIA_ID, body: body, commentStyle: COMMENT_STYLE },
				function (r) {
					var result = eval('('+r+')');
					if (typeof result == 'string') {
						alert(result);
					}
					else {
						var commentsUl = $('div.media-comments ul:first');
						var li = buildLi(result, false);
						if (commentsUl.length == 0) {
							var h2 = $('<h2/>').addClass('comment-count').html('1 comment');
							commentsUl = $('<ul/>');
							$('div.media-comments').append(h2).append(buildCommentStyle()).append(commentsUl);
						}
						else {
							var parts = $('div.media-comments h2.comment-count').html().split(' ');
							var count = parts[0];
							count ++;
							$('div.media-comments h2.comment-count').html(count+' comments');							
						}
						commentsUl.prepend(li);
						$.scrollTo(li);
						commentBody.attr('value', '');
					}
					commentSubmit.attr('disabled', false);
				}
			);
		});
		var replies = $('div.media-comments div.actions a.reply');
		replies.live('click', function (e) {
			stop(e);			
			$(this).blur();		
			$('.reply-popup').remove();
			var replyDiv = buildReplyPopup();			
			$(this).parent().append(replyDiv);
			replyDiv.find('textarea').focus();
		});
		$('div.media-comments div.reply-popup a.close').live('click', function (e) {
			stop(e);
			$(this).parent('div.reply-popup').fadeOut('fast', function () {
				$(this).remove();
			});
		});
		$('div.media-comments div.reply-popup input.submit').live('click', function (e) {
			stop(e);
			var textarea = $(this).parent().find('textarea');
			var body = textarea.attr('value');
			var replyDiv = $(this).parent().parent().parent();
			var commentDiv = textarea.parent().parent().parent().parent().parent().parent().parent().parent();
			var anchor = commentDiv.find('a:first');
			var parentId = anchor.attr('name').replace('comment-', '');			
			$.post(
				ajaxUrl,
				{ mediaId: MEDIA_ID, body: body, parentId: parentId, commentStyle: COMMENT_STYLE },
				function (r) {
					var result = eval('('+r+')');
					if (typeof result == 'string') {
						alert(result);
					}
					else {
						replyDiv.fadeOut('fast', function () {
							$(this).remove();
						});
						
						var parts = $('div.media-comments h2.comment-count').html().split(' ');
						var count = parts[0];
						count ++;
						$('div.media-comments h2.comment-count').html(count+' comments');
						
						if (COMMENT_STYLE == 'list') {						
							var li = buildLi(result, false);
							var ul = $('div.media-comments ul:first');
							ul.prepend(li);
							$.scrollTo(li);
						}
						else {
							var li = buildLi(result, true);
							var ul = commentDiv.find('ul.replies');
							if (ul.length == 0) {
								var repliesUl = $('<ul/>').addClass('replies');
								repliesUl.append(li);
								commentDiv.append(repliesUl);	
							}
							else {
								ul.children('li').removeClass('last');
								ul.append(li);							
							}
						}
					}
				}			
			);
			//var anchor = $(this).parent('li').length;//.find('a:first').length;
			//alert(anchor);
			//var id = anchor.attr('name').replace('comment-');
			//alert(id);
			/*$.post(
				ajaxUrl,
				{ mediaId: MEDIA_ID, body: body, 
			
			);*/
		});
	} // if
});

/*** ratings ***/

$(function() {
	var span = $('div.rate div.ratings span.interactive');
	span.append($('<a/>').addClass('link').attr('href', '#').attr('title', 'Details').html('Details'));	
	var a = $('div.ratings a');
	var breakdown = $('div.rate div.breakdown');
	var startClass = span.attr('class');
	var startRatings = span.html();
	var open = false;	
	a.live('click', function (e) {		
		stop(e);
		breakdown.fadeIn();
		$(this).remove();
		startRatings = span.html();
		open = true;
	});
	span.mousemove(
		function (e) {
			if (RATED) {
				return;
			}					
			if (document.body.clientWidth >= 960) {
				var x = e.pageX - ((document.body.clientWidth - 960) / 2 + 617);	
			}
			else {
				var x = e.pageX - 617;					
			}				
			if (x > 80) {
				$(this).attr('class', startClass);
				$(this).html(startRatings);				
			}
			else {
				var star = Math.round(x / 18) + 1;
				$(this).attr('class', 'hover interactive star'+star);		
				$(this).html('Give this item a rating of <strong>'+star+' star'+(star == 1 ? '' : 's')+'</strong>');
			}
		}
	);
	span.mouseout(function (e) {
		if (!RATED) {
			$(this).attr('class', startClass);
			$(this).html(startRatings);
		}
	});
	span.click(function (e) {		
		if (document.body.clientWidth >= 960) {
			var x = e.pageX - ((document.body.clientWidth - 960) / 2 + 617);	
		}
		else {
			var x = e.pageX - 617;					
		}				
		if (x < 81) {
			if (USER_ID == 0) { // need to go to login
				document.location.href = DYNAMIC_BASE+'/login?return='+URL;
			}
			else {
				var star = Math.round(x / 18) + 1;
				$.post(
					DYNAMIC_BASE+'/ajax/media/rate',
					{ mediaId: MEDIA_ID, rating: star },
					function (r) {
						var result = eval('('+r+')');
						if (result == null) { // error
							alert('There was an error processing your rating');
						}
						else {
							var stars = ''+(Math.round(result.newRating * 2) / 2);
							stars = stars.replace('.', '');
							span.attr('class', 'star'+stars);
							span.html(result.newRatingCount+' rating'+(result.newRatingCount == 1 ? '' : 's')+' (including yours)'+(open ? '' : ' <a href="#" title="Details" class="link">Details</a>'));
							span.hide().fadeIn();
							RATED = true;
							
							// rebuild breakdown
							
							breakdown.html('');
							
							for (i = 5; i > 0; i --) {
								var starspan = $('<span/>').addClass('star'+i);
								if (result.newRatingBreakdown[i - 1] == '0') {
									starspan.addClass('empty');
								}
								starspan.html(result.newRatingBreakdown[i - 1]+' rating'+(result.newRatingBreakdown[i - 1] == '1' ? '' : 's')+(star == i ? ' (including yours)' : ''));
								breakdown.append(starspan);
							}
							
							$('div.rate h4').html('Ratings');
						}
					}			
				);
			}
		}		
	});
});

/*** timestamp ***/

$(function () {
	
	function secondsToTimestamp(seconds) {
		function pad (value) {
			if (value < 10) {
				return '0' + value;
			}
			return value;
		}
		var timestamp = '';
		if (seconds >= 3600) {
			timestamp = pad(Math.floor(seconds / 3600))+':';
			seconds -= Math.floor(seconds / 3600) * 3600;
		}
		timestamp += pad(Math.floor(seconds / 60))+':'+pad(seconds % 60);
		return timestamp;
	}
	
	if (START_TIME > 0 && MEDIA_ID >= 53622) {
		setTimeout(function () {
			if (navigator.appName.indexOf('Microsoft') != -1) {
				var flash = window.video_player;
			}
			else {
				var flash = window.document.video_player;
			}
			try {
				flash.seek_v(secondsToTimestamp(START_TIME));
			}
			catch (e) {  }
		}, 2500);
	}
	
	var slider;
	var init = false;
	var quickUrl = $('#quick-url').val();
	$('#quick-url-slider').css({display: 'none'});
	$('#quick-url').click(function (e) {
		this.select();
	});
	$('#quick-url-timestamp').click(function (e) {		
		if (this.checked) {
			$('#carpe-slider-panel-quick-url-slider').css({display: 'block'});
			$('#quick-url-slider').css({display: 'block'});
			if (!init) {
				slider = new CARPE.Slider('quick-url-slider', {
					'orientation': 'horizontal',
					'size': 140,
					'position': 0,
					'stops': 10,
					onUpdate: function (value) {
						
						var seconds = Math.round(DURATION * value);
						var timestamp = secondsToTimestamp(seconds);
						
						$('#quick-url').val(quickUrl+'?t='+timestamp);
					}
				});
				init = true;
			}
			else {
				slider.onUpdate(slider.value);
			}
		}
		else {
			$('#quick-url').val(quickUrl);
			$('#carpe-slider-panel-quick-url-slider').css({display: 'none'});
		}
	});
});