var imageTimeoutWait = 1000 * 60; // every minute

function resetWebcamsPage() {
	// remove the class from noscript tags (fix IE issue)
	$("noscript").removeClass();

	// add mouseover/mouseout/click effects to the webcam images
	$("#webcams img").bind('mouseover', function() {
		document.body.style.cursor = 'pointer';
	});
	$("#webcams img").bind('mouseout', function() {
		document.body.style.cursor = 'default';
	});
	$("#webcams img").bind(
			'click',
			function() {
				window.open($(this).parents("form").find("input:hidden[name='location_image']").attr("value"), "webcam_location",
						"location=0,status=0,menubar=0,directories=0,resizable=0,scrollbars=0,width=400,height=600");
			});

	// setup each of the webcam forms
	$("#webcams form").each(function(i) {
		var id = $(this).attr("id");
		// set timeout to update the webcam_update_time forms
		setTimeout('updateImage("' + id + '")', imageTimeoutWait);

		// make form resizable (if not using IE)
		if (!$.browser.msie) {
			$(this).resizable({
				alsoResize : "#" + id + " img",
				aspectRatio : true,
				minWidth : 220,
				maxWidth : 515,
				minHeight : 180,
				maxHeight : 425,
				// reset the main scroll bar after a short delay
				stop : function() {
					if (typeof resetMainScrollPane == 'function') {
						setTimeout("resetMainScrollPane()", 100);
					}
				}
			});
		}
	});

	// reset the main scroll bar after picture loaded
	$("#webcams img").bind("load", function() {
		if (typeof resetMainScrollPane == 'function') {
			resetMainScrollPane();
		}
	});
}

/**
 * Update the Webcam Image in the specified form element
 * 
 * @param formId
 *            String id of the form to be updated
 */
function updateImage(formId) {
	// add the JavaScript enabled flag and cache disrupt values to the form
	addJsEnabledFlag(formId);
	addCacheDisrupt(formId);

	var formElem = $('#' + formId);

	// first update the image by adding unique query-string part of image source
	// to force image reload
	var img = formElem.find("img");
	var src = img.attr("src");
	src = src.indexOf("?") == -1 ? src : src.substring(0, src.indexOf("?"));
	img.attr("src", src + '?' + (new Date()).getTime());

	// perform the AJAX request and replace the current webcam_update_time form
	$.post(formElem.attr('action'), formElem.serialize(), function(data, textStatus) {
		// set the returned span HTML on the page
		formElem.find("span").replaceWith(data);

		// loop the details fetch...
		setTimeout('updateImage("' + formId + '")', imageTimeoutWait);
	}, "html");

	// prevent post-back of form
	return false;
}
