const MMM_IMAGE_WIDGET_SIZE = 500;

function getImageUrl(img, idx) {
	return $(img).attr("src");
}

function resizeImage() {
	var thisImg = $(this);
	//reset size
	thisImg.css('width', 'auto');
	thisImg.css('height', 'auto');
	var w = thisImg.width();
	var h = thisImg.height();
	if (w > h) {
		thisImg.width(MMM_IMAGE_WIDGET_SIZE);
		thisImg.height((MMM_IMAGE_WIDGET_SIZE / w) * h);
	} else if (h > w) {
		thisImg.width((MMM_IMAGE_WIDGET_SIZE / h) * w);
		thisImg.height(MMM_IMAGE_WIDGET_SIZE);
	} else {
		thisImg.width(MMM_IMAGE_WIDGET_SIZE);
		thisImg.height(MMM_IMAGE_WIDGET_SIZE);
	}
}

$(function () {
	$("a[rel=facybox]").facybox();
	$(".secondary-image-list").each(function () {
		/* grab all the images in this articles image list */
		var imageObjs = $(this).find("img");
		
		/* make the click for each of this images just change the main image */
		imageObjs.bind('click', function () {
			var imgSrc = $(this).attr("src");
			$(this).parent().parent().parent().find("li").removeClass("selected");
			$(this).parent().parent().addClass("selected");
			var articleImagesDiv = $(this).parent().parent().parent().parent();
			articleImagesDiv.find(".main-image a").attr("href", imgSrc);
			articleImagesDiv.find(".main-image img").attr("src", imgSrc);
			return false;
		});
		
		/* get the array of image urls for constructing the facybox gallery */
		var imgUrls = $.map(imageObjs, getImageUrl);
		
		var articleImagesDiv = $(this).parent();
		articleImagesDiv.find("a.expand-link").bind("click", function () {
			/* generate facybox gallery for this article */
			$.facybox({images: imgUrls});
			return false;
		});
	});
	
	$('.article-images .main-image img').load(resizeImage);
	
	$(".comment-form div.input input, .comment-form div.input textarea").focus(function () {
		$(this).css("border-color", "#de5370");
	}).blur(function() {
		var curInput = $(this);
		if (curInput.val() == "") {
			curInput.css("border-color", "#9f9f9f");
		}
	});
});
$(window).load(function () {
	$.map($('.article-images .main-image img'), resizeImage);
});