if (typeof window.AutoCMS == "undefined") {
	var AutoCMS = {};
}
// Add default photos to slideshow
if (typeof AutoCMS.photos == "undefined") {
	AutoCMS.photos = [
		"/uploads/img_6193.jpg", "/uploads/img_5781.jpg", "/uploads/img_9345.jpg"
	];
}

// Static utility functions
jQuery.extend({
	/**
	 * Substitutes keywords in a string with values from an object. The keywords
	 * are properties of the object, wrapped in curly braces inside the string (ie. {prop}).
	 *
	 * @param String str The string to perform substitions on.
	 * @param Object obj The object with values to inject into the string.
	 * @return String String with all properties existing in the object replaced with the respective values.
	 */
	substitute: function (str, obj, fallback) {
		jQuery.each(obj, function (key, value) {
			// We only use fallback for actual NULL values, not any 'falsy' value
			if (value == null) {
				value = fallback || '';
			}
			str = str.replace(new RegExp('\\{' + key + '\\}', 'g'), value);
		});
		return str;
	}
});

jQuery(function ($) {
	var
		// Contants for the slideshows
		IMAGE_URL = AutoCMS.url + "/image/2/{width}/{height}/5/1{imagefile}",
		SLIDESHOW_DELAY = 5000,
		SLIDESHOW_FADETIME = 1500,
		SLIDESHOW_USER_FADETIME = 1000,
		IMG_WIDTH = 758,
		IMG_HEIGHT = 464,
		// Core containers
		$win = $(window),
		$slideshow = $("#slideshow"),
		// Status flags
		numPhotosLoading,
		slideshowTimer,
		slideshowIsPlaying;

	function isPhotoLoaded (img) {
		return ((typeof img.complete !== 'undefined' && img.complete)
				|| (typeof img.naturalWidth !== 'undefined' && img.naturalWidth != 0));
	}

	function swapPhotos ($currentPhoto, $newPhoto, fadeTime) {
		fadeTime = fadeTime || SLIDESHOW_FADETIME;

		if ($newPhoto[0] == $currentPhoto[0]) return;

		// Wait a bit longer for image to load
		if (!isPhotoLoaded($newPhoto[0])) {
			slideshowTimer = setTimeout(nextPhoto, SLIDESHOW_DELAY);
			return;
		}

		$currentPhoto.css("zIndex", 10).fadeOut(fadeTime, function () {
			$currentPhoto.hide();
		});
		$newPhoto.css("zIndex", 1).fadeIn(fadeTime, function () {
			if (slideshowIsPlaying) {
				slideshowTimer = setTimeout(nextPhoto, SLIDESHOW_DELAY);
			}

			$("#slideshow-nav .status").text(function (i, text) {
				return text.replace(/\d+\//, ($newPhoto.index() + 1) + "/");
			});
		});
	}

	function prevPhoto (userAction) {
		userAction = userAction || false;

		var $current = $slideshow.find("img:visible"),
			$prev = $current.prev("img");

		if ($prev.length == 0) {
			$prev = $slideshow.find("img:last");
		}

		swapPhotos($current, $prev, userAction ? SLIDESHOW_USER_FADETIME : SLIDESHOW_FADETIME);
	}

	function nextPhoto (userAction) {
		userAction = userAction || false;

		var $current = $slideshow.find("img:visible"),
			$next = $current.next("img");

		if ($next.length == 0) {
			$next = $slideshow.find("img:eq(0)");
		}

		swapPhotos($current, $next, userAction ? SLIDESHOW_USER_FADETIME : SLIDESHOW_FADETIME);
	}

	/*
	 * Initialiser slideshow hvis foto finnes for siden.
	 */
	if (AutoCMS.photos && AutoCMS.photos.length > 0) {
		$("style#default-slideshow").remove();
		// Fjern kun bakgrunnsbildet, IE7 har trøbbel om vi skjuler DIV helt her…
		$slideshow.css('backgroundImage', 'none !important'); //.hide();

		var
			i = 0, len = AutoCMS.photos.length,
			params = {
				"width": IMG_WIDTH,
				"height": IMG_HEIGHT
			},
			attrs;

		numPhotosLoading = len;

		for (i = 0; i < len; i++) {
			params.imagefile = AutoCMS.photos[i];
			attrs = {
				"src": $.substitute(IMAGE_URL, params)
			};

			$("<img />", attrs)
				.load(function () {
					if (!slideshowIsPlaying && this.src.indexOf(AutoCMS.photos[i]) !== false) {
						// Start slideshow!
						$slideshow.show();
						slideshowTimer = setTimeout(nextPhoto, SLIDESHOW_DELAY);
						slideshowIsPlaying = true;
					}
				})
				.data("slideshow.originalSize", params)
				.appendTo($slideshow);
		}
		// Skjul alle foto unntatt det første
		$slideshow.find("img:gt(0)").hide();

		$("#slideshow-nav")
			.change(function (e) {
				window.location = e.target.value;
			})
			.click(function (e) {
				var $target = $(e.target),
					action;
				if ($target.is("a")) {
					e.preventDefault();

					action = $target.attr("href").split("#")[1];
					switch (action) {
						case "prev":
							clearTimeout(slideshowTimer);
							prevPhoto(true);
							break;

						case "next":
							clearTimeout(slideshowTimer);
							nextPhoto(true);
							break;

						case "pause":
							clearTimeout(slideshowTimer);
							slideshowIsPlaying = false;
							$target.hide()
								.closest("ul").find("a[href*=play]").show();
							break;

						case "play":
							slideshowTimer = setTimeout(nextPhoto, SLIDESHOW_DELAY);
							slideshowIsPlaying = true;
							$target.hide()
								.closest("ul").find("a[href*=pause]").show();
							break;
					}
				}
			})
			.find("a[href*=play]").hide();
	}

	var
		cars = {
			left: $('#cars .first .preview-cars'),
			right: $('#cars .last .preview-cars')
		},
		currentCar = 0,
		totalCars = cars.left.length < cars.right.length ? cars.left.length : cars.right.length;
	
	if (totalCars <= 1) {
		$("#cars a.prev, #cars a.next").css('visibility', 'hidden');
	}

	$("#cars a.prev").click(function (e) {
		e.preventDefault();
		if (currentCar == 0) return;
		else toggleCars(false);
	});
	
	$("#cars a.next").click(function (e) {
		e.preventDefault();
		if (currentCar == (totalCars -1)) return;
		else toggleCars(true);
	});
	
	function toggleCars (up) {
		$(cars.left[currentCar]).animate({width: 'toggle'}, 360);
		$(cars.right[currentCar]).animate({width: 'toggle'}, 360);
		$(cars.left[currentCar]).find('p span').hide();
		$(cars.right[currentCar]).find('p span').hide();
		if (up) currentCar++;
		else currentCar--;
		setTimeout(function () {
			$(cars.left[currentCar]).animate({width: 'toggle'}, 360);
			$(cars.right[currentCar]).animate({width: 'toggle'}, 360);
			$(cars.left[currentCar]).find('p span').show();
			$(cars.right[currentCar]).find('p span').show();
		}, 370);
	}
});

