dimScreenFinishedCallback = '';
function dimScreen(finishedCallback) {
	if (typeof(finishedCallback) == 'undefined') {
		dimScreenFinishedCallback = '';
	} else {
		dimScreenFinishedCallback = finishedCallback;
	}
	$('body').append('<div id="dimming"></div>');
	$('div#dimming').css({
		'backgroundColor': '#000',
		'opacity': '0',
		'height': $(document).height(),
		'width': '100%',
		'background-repeat': 'repeat',
		'position': 'absolute',
		'top': '0px',
		'left': '0px'
	}).animate({
		'opacity': '0.7'
	}, function() {
		if (dimScreenFinishedCallback != '') {
			dimScreenFinishedCallback();
			dimScreenFinishedCallback = '';
		}
	});
}
function undimScreen() {
	$('div#dimming').animate({'opacity': '0'}, 400, function(){
		$(this).remove();
	});
}

enlargedImgCloseFunction = '';
function enlargeImg($img, closeFunction) {

	if (typeof(closeFunction) == 'undefined') {
		enlargedImgCloseFunction = '';
	} else {
		enlargedImgCloseFunction = closeFunction;
	}

	dimScreen(function() {

		imgSet = new Array();
		$('img', $img.closest('.enlargedimageset')).each(function() {
			if ($(this).width() > 20) {
				imgSet.push($(this).attr('src'));
			}
		});

		$("body").append('<div id="enlargedFrame1" style="position: absolute; left:-2000; top:-2000"><div id="enlargedFrame2"><div id="enlargedFrame3"><div id="enlargedFrame4"><img src="' + $img.attr('src') + '" data_imgset="' + imgSet.join(' ') + '" id="enlarged" style="width:' + $img.width() + '; height:' + $img.height() + ';" /></div></div></div></div><img src="close.gif" id="enlargedClose" width="15" height="15" />');
		if (imgSet.length > 1) {
			$('body').append('<div id="enlargedPrev"><a href="#' + getHash() + '">Back</a></div><div id="enlargedNext"><a href="#' + getHash() + '">Next</a></div>');
		}
		if (getHash() == 'arbetsmarknaden') {
			$('body').append('<div id="dlpdf"><a href="http://www.cuf.se/press/Presskit/Tabloider/Arbetsmarknaden.pdf">Spara</a></div>');
		}
		if (getHash() == 'handlingsprogram') {
			$('body').append('<div id="dlpdf"><a href="http://www.cuf.se/press/Presskit/Tabloider/Handlingsprogrammet.pdf">Spara</a></div>');
		}
		$('div#enlargedPrev a, div#enlargedNext a').each(function() {
			$(this).click(function() {
				var imgSet = $('img#enlarged').attr('data_imgset').split(' ');
				var currentSrc = $('img#enlarged').attr('src');
				var currentIndex = -1;
				for (var i = 0; i < imgSet.length; i++) {

					var re = new RegExp('^.*/([^/]+)$')
					var jmfr1 = imgSet[i];
					var jmfr2 = currentSrc;
					if (jmfr1.match(re)) {
						jmfr1 = jmfr1.replace(re, '$1');
					}
					if (jmfr2.match(re)) {
						jmfr2 = jmfr2.replace(re, '$1');
					}
					if (jmfr1 == jmfr2) {
						currentIndex = i;
					}

				}
				if (currentIndex != -1) {
					if ($(this).parent().attr('id') == 'enlargedPrev') {
						currentIndex = currentIndex - 1;
					} else {
						currentIndex = currentIndex + 1;
					}
					if (currentIndex == -1) {
						currentIndex = imgSet.length - 1;
					} else if (currentIndex == imgSet.length) {
						currentIndex = 0;
					}
					$oldEnlarged = $('img#enlarged');
					$newEnlarged = $('<img src="' + imgSet[currentIndex] + '" border="0" id="enlarged" style="display:none" data_imgset="' + $oldEnlarged.attr('data_imgset') + '" />');
					$oldEnlarged.after($newEnlarged);
					$oldEnlarged.remove();
					$newEnlarged.css('display', 'block');
					positionEnlargedImg(true);
				}
				return false;
			});
		});

		positionEnlargedImg(true);

		$(window).resize(function() {
			positionEnlargedImg(true);
		});
		$(window).scroll(function() {
			/* removeEnlargedImage(); */
			positionEnlargedImg(true);
		});
		$('div#dimming').css('cursor', 'pointer').click(function() {
			removeEnlargedImage();
		});
		$('img#enlargedClose').css('cursor', 'pointer').click(function() {
			removeEnlargedImage();
		});

	});

}

function positionEnlargedImg(resize) {
	$('img#enlarged').each(function() {

		borderheight = $('div#enlargedFrame1').outerHeight() - $('div#enlargedFrame4').innerHeight();
		borderwidth = $('div#enlargedFrame1').outerWidth() - $('div#enlargedFrame4').innerWidth();

		viewportheight = $(window).height() - 20 - borderheight;
		viewportwidth = $(window).width() - 20 - borderwidth;
		viewportprops = viewportwidth / viewportheight;
		imgprops = $(this).width() / $(this).height();
		imgheight = viewportheight;
		imgwidth = imgprops * imgheight;
		if (imgwidth > viewportwidth) {
			imgwidth = viewportwidth;
			imgheight = imgwidth / imgprops;
		}
		if (imgwidth > 725) {
			imgwidth = 725;
			imgheight = imgwidth / imgprops;
		}
		imgwidth = parseInt(imgwidth);
		imgheight = parseInt(imgheight);

		imgstyle = {
			'width': parseInt(imgwidth),
			'height': parseInt(imgheight)
		};
		borderstyle = {
			'left': parseInt(((viewportwidth + 20 + borderheight) / 2) - ((imgwidth + borderwidth) / 2)) + $(window).scrollLeft(),
			'top': parseInt(((viewportheight + 20 + borderheight) / 2) - ((imgheight + borderheight) / 2)) + $(window).scrollTop()
		}
		if (resize) {
			$(this).css(imgstyle)
			$('div#enlargedFrame1').css(borderstyle);
			$('img#enlargedClose').css({
				'position': 'absolute',
				'top': $('img#enlarged').offset().top + 5,
				'left': $('img#enlarged').offset().left + $('img#enlarged').width() - $('img#enlargedClose').width() - 5
			});
			$('div#dlpdf').css({
				'position': 'absolute',
				'top': $('img#enlargedClose').position().top,
				'left': $('img#enlargedClose').position().left - $('div#dlpdf').width() - 6
			});
			$('div#enlargedPrev').css({
				'position': 'absolute',
				'top': $('img#enlarged').offset().top + parseInt($('img#enlarged').height() * 0.4) - parseInt($('div#enlargedPrev').outerHeight() / 2),
				'left': $('img#enlarged').offset().left
			});
			$('div#enlargedNext').css({
				'position': 'absolute',
				'top': $('img#enlarged').offset().top + parseInt($('img#enlarged').height() * 0.4) - parseInt($('div#enlargedNext').outerHeight() / 2),
				'left': $('img#enlarged').offset().left + $('img#enlarged').width() - $('div#enlargedNext').outerWidth()
			});
		} else {
			$(this).animate(imgstyle);
			$('div#enlargedFrame1').animate(borderstyle, function() {
				$('img#enlargedClose').css({
					'position': 'absolute',
					'top': $('img#enlarged').offset().top + 5,
					'left': $('img#enlarged').offset().left + $('img#enlarged').innerWidth() - $('img#enlargedClose').width() - 5
				});
				$('div#enlargedPrev').css({
					'position': 'absolute',
					'top': $('img#enlargedClose').position().top,
					'left': $('img#enlargedClose').position().left - $('div#dlpdf').width() - 6
				});
				$('div#enlargedPrev').css({
					'position': 'absolute',
					'top': $('img#enlarged').offset().top + parseInt($('img#enlarged').height() * 0.4) - parseInt($('div#enlargedPrev').outerHeight() / 2),
					'left': $('img#enlarged').offset().left
				});
				$('div#enlargedNext').css({
					'position': 'absolute',
					'top': $('img#enlarged').offset().top + parseInt($('img#enlarged').height() * 0.4) - parseInt($('div#enlargedNext').outerHeight() / 2),
					'left': $('img#enlarged').offset().left + $('img#enlarged').width() - $('div#enlargedNext').outerWidth()
				});
			});
		}
	});
}

function removeEnlargedImage(callback) {
	$('img#enlargedClose, div#enlargedPrev, div#enlargedNext, div#dlpdf').remove();
	$('div#enlargedFrame1').each(function() {
		undimScreen();
		$(this).fadeOut('fast', function() {
			$(this).remove();
			if (enlargedImgCloseFunction != '') {
				enlargedImgCloseFunction();
				enlargedImgCloseFunction = '';
			}
			if (typeof(callback) != 'undefined') {
				callback();
			}
		});
	});
}

function makeImgEnlargable(img) {
	$(img).css('cursor', 'pointer').click(function() {
		enlargeImg($(this));
	});
	if (getHash() != 'vinn') { //if (!$.browser.msie) {
		$emb = $('<div style="width:' + $(img).width() + 'px; height:' + $(img).height() + 'px; overflow: hidden" />');
		$(img).after($emb);
		$emb.append($(img))
		$(img).after('<img align="top" src="enlarge.png" width="15" height="15" style="position: relative; height:15px; width:15px; padding: 0 0 0 0; margin: 5px 0px 0px -20px; cursor: pointer; top: 0; left: 0" />').next('img').click(function() {
			enlargeImg($(this).prev('img'));
		});
		$(img).hover(function() {
			if ($(this).next('img').attr('data_blinked') != 'done') {
				$(this).next('img').attr('data_blinked', 'done').animate({opacity: 0}, 100, function() {
					$(this).animate({opacity: 1}, 100, function() {
						$(this).animate({opacity: 0}, 100, function() {
							$(this).animate({opacity: 1}, 100, function() {
								$(this).animate({opacity: 0}, 100, function() {
									$(this).animate({opacity: 1}, 100, function() {
									});
								});
							});
						});
					});
				});
			}
		});
	}
}

function positionAlbumImgOnLoad(img) {
	if ((img.complete) && ($(img).width() != 0) && ($(img).height() != 0)) {
		prop = $(img).width() / $(img).height();
		width = 140;
		height = width / prop;
		if (height > 150) {
			height = 150;
			width = height * prop;
		}
		$(img).width(parseInt(width));
		$(img).height(parseInt(height));
		$(img).css({'opacity': 0, 'position': 'static'}).animate({'opacity': 1}, 'slow', function() {
			makeImgEnlargable(this);
		});
	} else {
		setTimeout(function() { positionAlbumImgOnLoad(img) }, 500);
	}
}

function chlike(nr, dislike) {
	if (((dislike == false) && ($.cookie('opinion-' + nr) != 'like')) || ((dislike == true) && ($.cookie('opinion-' + nr) != 'dislike'))) {
		likes = parseInt($('div.likes span.likes span.number', $('div.entry[data_klajax_content_id="' + nr + '"]')).html());
		dislikes = parseInt($('div.likes span.dislikes span.number', $('div.entry[data_klajax_content_id="' + nr + '"]')).html());
		if (dislike == false) {
			if ($.cookie('opinion-' + nr) == 'dislike') {
				dislikes = dislikes - 1;
				if (dislikes < 0) dislikes = 0;
				ch = 1;
			} else {
				ch = 0;
			}
			likes = likes + 1;
		} else {
			if ($.cookie('opinion-' + nr) == 'like') {
				likes = likes - 1;
				if (likes < 0) likes = 0;
				ch = 1;
			} else {
				ch = 0;
			}
			dislikes = dislikes + 1;
		}
		if (likes < 10) likes = '0' + likes;
		if (dislikes < 10) dislikes = '0' + dislikes;

		$('div.likes span.likes span.number', $('div.entry[data_klajax_content_id="' + nr + '"]')).html(likes);
		$('div.likes span.dislikes span.number', $('div.entry[data_klajax_content_id="' + nr + '"]')).html(dislikes);
		$('div.meta span.likecounter', $('div.entry[data_klajax_content_id="' + nr + '"]')).html(' (' + parseInt(likes) + ')');
		$('div.meta span.dislikecounter', $('div.entry[data_klajax_content_id="' + nr + '"]')).html(' (' + parseInt(dislikes) + ')');

		if (dislike == false) {
			cookieValue = 'like';
		} else {
			cookieValue = 'dislike';
		}
		$.cookie('opinion-' + nr, cookieValue, {
			path: '/',
			expires: 365
		});
		$.ajax({
			type: "POST",
			url: "like.php",
			async: true,
			data: {
				'nr': nr,
				'ch': ch
			},
			dataType: 'html'
		});
		/*
		$('span.likes', $('div.interaction[data_entryid="' + nr + '"]').prev('div.likes')).addClass('selected');
		$('span.dislikes', $('div.interaction[data_entryid="' + nr + '"]').prev('div.likes')).removeClass('selected');
		*/
		if (dislike == false) {
			$('a.like', $('div.entry[data_klajax_content_id="' + nr + '"]')).addClass('selected').html('Du gillar detta').css('background-color', '#7bc673').animate({'backgroundColor': '#fff'}, 'slow');
			$('a.dislike', $('div.entry[data_klajax_content_id="' + nr + '"]')).removeClass('selected').html('Ogilla');
		} else {
			$('a.dislike', $('div.entry[data_klajax_content_id="' + nr + '"]')).addClass('selected').html('Du ogillar detta').css('background-color', '#7bc673').animate({'backgroundColor': '#fff'}, 'slow');
			$('a.like', $('div.entry[data_klajax_content_id="' + nr + '"]')).removeClass('selected').html('Gilla');
		}
	}
}

function like(nr) {
	chlike(nr, false);
}

function dislike(nr) {
	chlike(nr, true);
}

$(document).ready(function() {
	addKlajaxHashChangeHook(function(hash) {
		removeEnlargedImage();
		$('div.comments, div.likes').hide(400);
	});

	addKlajaxOnHashHideHook('feed', function(element) {
		$('object', element).each(function() {
			$(element).remove(); // Plocka bort alla entries med en inladdad YouTube.
			// Här borde vi kanske begära att skiten ska laddas in igen, så det inte måste ajaxas när man klickar tillbaka.
		});
	});

	addKlajaxPostInsertHook('feed', function(element) {

		addKlajaxPostInsertHook('comments/' + $(element).attr('data_klajax_content_id'), function(element) {
			$entry = $(element).closest('div.entry');
			$('div.meta a.comment', $entry).html('Kommentarer (' + $('div.comments ul li', $entry).length + ')');
			$('div.meta span.likecounter', $entry).html(' (' + parseInt($('div.likes span.likes span.number', $entry).html()) + ')').show();
			if ($('div.cirkusen').length == 0) {
				$('div.meta span.dislikecounter', $entry).html(' (' + parseInt($('div.likes span.dislikes span.number', $entry).html()) + ')').show();
			}
		});

		$('input[data_default],textarea[data_default]', element).each (function () {
			if (this.value == '') {
				this.value = $(this).attr ('data_default');
			}
			$(this)
				.focus (function () {
					if (this.value == $(this).attr ('data_default')) {
						this.value = '';
					}
				})
				.blur (function () {
					if (this.value == '') {
						this.value = $(this).attr ('data_default');
					}
				});
		});

		// ALBUM
		$('div.album', element).each(function() {
			$(this).css('position', 'static').fadeIn();
			$('img', this).each(function() {
				positionAlbumImgOnLoad($(this)[0]);
			});
		});

		// TEXT
		$('span.moreinfo', $(element)).click(function() {
			$('div.text', $(this).closest('div.entry')).show(400, function() {
				$(this).children('div.textimages').fadeIn(function() {
					$('img', this).each(function() {
						makeImgEnlargable(this);
					});
				});
			});
			$(this).remove();
		});

		// CUF SPECIFIC
		$('div.statusleftimg img', $(element)).load(function() {
			makeImgEnlargable(this);
		});

		// YOUTUBE
		$('img.youtube, img.playbutton', element).click(function() {
			$(this).parent().each(function() {
				$(this).children('img.playbutton').fadeOut(200, function() {
					$(this).remove();
				});
				$(this).children('img.youtube').animate({width: 476, height: 300, opacity: 0, 'padding-right': 0, 'padding-bottom': 9}, 400, function(){
					$(this).after('<div style="padding: 0px 0px 9px 0px; width: 476px; height:300px;"><object width="476" height="300"><param name="wmode" value="opaque"></param><param name="movie" value="http://www.youtube.com/v/' + $(this).parent().attr('data_youtube') + '?autoplay=1"></param><param name="autoplay" value="1"></param><embed wmode="opaque" src="http://www.youtube.com/v/' + $(this).parent().attr('data_youtube') + '?autoplay=1" type="application/x-shockwave-flash" width="476" height="300" autoplay="1"></embed></object></div>');
					$(this).remove();
				});
			});
		});

		// LIKES/DISLIKES/COMMENTS
		$('a.like,a.dislike,a.comment', element).click(function() {
			$('div.likes,div.comments', $(this).closest('div.entry')).each(function() {
				$(this).show('normal');
			});
			if ($(this).hasClass('like')) {
				like($(this).closest('div.entry').attr('data_klajax_content_id'));
			} else if ($(this).hasClass('dislike')) {
				dislike($(this).closest('div.entry').attr('data_klajax_content_id'));
			}
			return false;
		});
		$('div.likes span.likes span.number', element).click(function() {
			like($(this).closest('div.entry').attr('data_klajax_content_id'));
			return false;
		});
		$('div.likes span.dislikes span.number', element).click(function() {
			dislike($(this).closest('div.entry').attr('data_klajax_content_id'));
			return false;
		});

		// COMMENTS
		$('form input.button', element).click(function() {
			name = trim($(this).parent().children('input.name').val());
			email = trim($(this).parent().children('input.email').val());
			comment = trim($(this).parent().children('textarea').val());
			var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
			if (!filter.test(email)) {
				alert('Felaktig e-postadress, försök igen!');
				$(this).parent().children('input.email').focus();
			} else if ((comment == '') || (comment == 'Skriv en kommentar')) {
				alert('Skriv en kommentar först!');
				$(this).parent().children('textarea').focus();
			} else {
				$(this).parent('form').children('input, textarea').each(function() {
					$(this)[0].disabled = true;
				});
				$.cookie('myemail', email, {
					path: '/',
					expires: 365
				});
				$.ajax({
					type: "POST",
					url: "comment.php",
					async: true,
					data: {
						'name': name,
						'email': email,
						'comment': comment,
						'entryid': $(this).closest('div.entry').attr('data_klajax_content_id')
					},
					dataType: 'html',
					success: function(data) {
						$('input, textarea', 'div#feed').each(function() {
							if ($(this).attr('data_default')) {
								$(this).val($(this).attr('data_default'));
							}
							$(this)[0].disabled = false;
						});
						runKlajaxLoader = true;
					},
					error: function(data) {
						alert('Ett fel uppstod när du skulle posta en kommentar.');
						$('input, textarea', 'div#feed').each(function() {
							$(this)[0].disabled = false;
						});
					}
				});
			}
			return false
		});
	
	});

});

