var timeOut = 3000;
var unPause = false;

$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length,
      blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
      
  elems.bind('load',function(){
      if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }  
  }); 

  return this;
};

jQuery(document).ready(function($) {
    // browser detection
    var isMobile = navigator.userAgent.toLowerCase().match(/android|iphone|ipod|ipad|series60|symbian|windows ce|blackberry|palm/);
	var isSlidePreloaded = false;

	// load images that need to be loaded
	$(window).load( function() {
		$('img').each(function() {
			$this = $(this);
			var src = $this.attr('rel');
			if (src) {
				$this.attr('src', src);
			}
		});
	});
	
	// Slideshow
	$("#sshow").click(function(event) {
		event.preventDefault();
		toggleSlideshow();
	});

	$(".slide").first().addClass("active");
	
	var slideshowTimer;
	var slideshowInterval = 4000;
	var slideshowToggleElements = $("#slideshow, #main-area > div:visible, #ifloorplan-navigation-options");
	function toggleSlideshow() {
		slideshowToggleElements.toggle();
                var slide = $(".slide.active");
		slide.parent().width(slide.width())
                              .height(slide.height());

		var marginTop =($('#main-area').height() - $('#slideshow').height()) / 2;
                $("#slideshow").css("margin-top", marginTop);

		if (!isSlidePreloaded) {
			slide.first().imagesLoaded(function() {
				$(this).next().imagesLoaded(function() {
					isSlidePreloaded = true;
					toggleAutoSlide(true);
				});
			});
		}
	}
    
    $("#ifloorplan-images img").first().imagesLoaded(function() {
        $(this).next().imagesLoaded(function() {
            // Start rotation
            ifloorplanRotationTimeout = setTimeout("rotate()", timeOut);
        });
    });
	
	function toggleAutoSlide(on) {
		if (slideshowTimer != null || on == false) {
			clearInterval(slideshowTimer);
			$("#sshow-pause").text("play");
			slideshowTimer = null;
		} else {
			slideshowTimer = setInterval(goToNextSlide, slideshowInterval);
			$("#sshow-pause").text("pause");
		}
	}
	
	var goToNextSlide = function(force) {
		return goToSlide("next", force);
	};
	var goToPreviousSlide = function(force) {
		return goToSlide("previous", force);
	};
	
	var goToSlide = function(direction, force) {
		if ("undefined" == typeof(direction)) {
			direction = "next";
		}
		if ("undefined" == typeof(force)) {
			force = false;
		}
		var slide;
		var activeSlide = slides.siblings(".active");
		
		if ("next" == direction) {
			if (activeSlide.is(":last-child")) {
				slide = slides.first();
			} else {
				slide = activeSlide.next();
			}
		} else {
			if (activeSlide.is(":first-child")) {
				slide = slides.last();
			} else {
				slide = activeSlide.prev();
			}
		}
		slides.removeClass("active").hide();

		var marginTop =($('#main-area').height() - $('#slideshow').height()) / 2;
		$("#slideshow").css("margin-top", marginTop);

		if (force) {
			slide.show().addClass("active");
			slide.parent().width(slide.width())
			              .height(slide.height());
			toggleAutoSlide(false);
		} else {
			slide.fadeIn("fast", function() {
				$(this).addClass("active");
			});
			slide.parent().animate({
				width: slide.width(),
				height: slide.height()
			}, "fast");
		}
	};
	
	var slides = $("#sshow-images .slide");
	slides.first().addClass("active");
	slides.add("#sshow-next").click(function(event) {
		event.preventDefault();
		clearInterval(slideshowTimer);
		goToNextSlide(true);
	});
	
	// Slideshow controls
	// Previous
	$("#sshow-prev").click(function(event) {
		event.preventDefault();
		goToPreviousSlide(true);
	});
	// Play/Pause
	$("#sshow-pause").click(function(event) {
		event.preventDefault();
		toggleAutoSlide();
	});
	// Exit
	$("#sshow-exit").click(function(event) {
		event.preventDefault();
		toggleSlideshow();
	});
	// Show/hide with mouse/idle actions
	$("#slideshow").mouseenter(function () {
		$("#sshow-controls-wrapper").show();
	}).mouseleave(function() {
		idleTimer = setTimeout(hideControls, 4000);
	});
	function hideControls() {
		$("#sshow-controls-wrapper").fadeOut("slow");
	}
	var idleTimer;
	$("#slideshow").mousemove(function() {
		if (idleTimer) {
			clearTimeout(idleTimer);
			timer = null;
		}

		$('#sshow-controls-wrapper').show();
		idleTimer = setTimeout(hideControls, 4000);
	});
    
    // 'Share This' box
    var caption = $("#caption");
    var captionDefault = caption.text();
    $("#shareThis").click(function(event) {
        event.preventDefault();
        $("#share ul").toggle();
    });
    $("#share ul a").mouseover(function() {
        caption.text($(this).text());
    }).each(function() {
        $(this).attr("href", $(this).attr("href").replace("%5Burl%5D", location.href));
    }).mouseout(function() {
        caption.text(captionDefault);
    }).click(function(event) {
        event.preventDefault();
        window.open($(this).attr("href"));
    });
    
    // lightbox effect on media links & google maps
    $(".video a, #floatbox-close, #map a").click(function(event) {
        event.preventDefault();
        
        var href = $(this).attr("href");
        
        // Do not open external links in a floatbox on mobiles
        // As they cannot scroll iframes properly
        // Only allow Google Maps to be shown in the floatbox
        var floatbox = $("#floatbox");
        if ("map" != $(this).parent().attr("id") && !floatbox.hasClass("map") && isMobile) {
            return window.open(href);
        }
        
        var iframe = floatbox.find("#iframe");
        
        if ("#" == href) {
            href = "about:blank";
        }

        iframe.attr("src", href);
        //iframe.attr("data", href);
        
        if ("map" == $(this).parent().attr("id")) {
            floatbox.addClass("map");
        }
        
        // Show/hide floatbox
        floatbox.slideToggle(500, function() {
            // Show or hide the iframe
            if (!floatbox.is(":visible")) {
                iframe.attr("src", "about:blank");
                //iframe.attr("data", "about:blank");
                floatbox.removeClass("map");
            }
        });

        // Hide the more info box
        $("#more-info-box").hide();
        
        // Pause/unpause
        togglePause();
    });
    
    // Called when a box comes up
    // Pause if not currently paused
    // Unpause if paused by the box when the box closes
    function togglePause() {
		if ($("#pause-play-cameras a").text() == "Pause") {
			stopIfloorplanRotation();
            unPause = true;
		} else if (unPause) {
			$(this).text('Pause');
			ifloorplanRotationTimeout = setTimeout("rotate()", timeOut);
            unPause = false;
		}
	}
	
	// setup our variables so jquery runs faster when needing to traverse the dom
	$ifloorplanFloorplan = $('#ifloorplan-floorplan');
	$ifloorplanCameras = $('#ifloorplan-cameras');
	if ($('#ifloorplan-navigation-levels-vertical').length > 0) {
		$ifloorplanNavigationLevels = $('#ifloorplan-navigation-levels-vertical');
	} else {
		$ifloorplanNavigationLevels = $('#ifloorplan-navigation-levels');
	}
	$ifloorplanImages = $('#ifloorplan-images');

	// rotate cameras
	/*
	$ifloorplanCameras.find('img').each(function() {
		var $this = $(this);
		var angle = parseInt($this.attr('alt'));
		$this.rotate(angle);
	});*/

	// drop shadow on images and floorplans
	//$ifloorplanImages.find('img.active').dropShadow();
	//$ifloorplanFloorplan.find('img.active').dropShadow();

	// center container div vertically
    
    var resize = function() {
        var windowHeight = $(window).height();
        var containerHeight = $('#ifloorplan-container').height();
        if (containerHeight < windowHeight) {
            var marginTop = parseInt((windowHeight - containerHeight) / 2);
            $('#ifloorplan-container').css('margin-top', marginTop + 'px');
        }
    };
    
    
    $(window).resize(resize)
    .bind("orientationchange", resize);
    resize();

	// more info box
	$('#more-info a, #more-info-close').click(function(event) {
		event.preventDefault();
		$('#more-info-box').slideToggle();
        $("#floatbox").hide();
        togglePause();
	});
    
	// hover effect for cameras
	$ifloorplanCameras.find('img').hover(function() {
		$this = $(this);
		if (!$this.parent().hasClass('active')) {
			var newImage = $this.attr('src').replace(/normal/, 'hover');
			$this.attr('src', newImage);
		}
	}, function() {
		$this = $(this);
		if (!$this.parent().hasClass('active')) {
			var newImage = $this.attr('src').replace(/hover/, 'normal');
			$this.attr('src', newImage);
		}
	});

	// toggle cameras on and off
	$('#hide-cameras').click(function(event) {
		event.preventDefault();
		if ($ifloorplanCameras.find('a').is(':visible')) {
			stopIfloorplanRotation();
			$ifloorplanCameras.find('a').css('display', 'none');
			$(this).css('opacity', '0.5');
		} else {
			$ifloorplanCameras.find('a').css('display', 'block');
			$(this).css('opacity', '1');
		}
	});

	// change floorplans when level navigation item clicked
	$ifloorplanNavigationLevels.find('li:visible').click(function(event) {
		event.preventDefault();
		$this = $(this);
		if (!$this.hasClass('active')) {
			var level = $this.attr('id').replace(/level-/, '');
			showIfloorplanImage(level, 1);
		}
	});

	// show the image if a camera is clicked
	$ifloorplanCameras.find('a').click(function(event) {
		event.preventDefault();
	});
	$ifloorplanCameras.find('a').hover(function(event) {
		event.preventDefault();
		$this = $(this);
		if (!$this.hasClass('active')) {
			stopIfloorplanRotation();
			var level = $this.parent().attr('id').replace(/camera-level-/, '');
			var imageNumber = $this.attr('id').replace('camera-' + level + '-', '');
			showIfloorplanImage(level, imageNumber);
		}
	});

	// next camera shot
	$('#next-camera').click(function(event) {
		event.preventDefault();
		if ($ifloorplanCameras.find('> div.active a').length > 1) {
			stopIfloorplanRotation();
			nextImage();
		}
	});

	// previous camera shot
	$('#previous-camera').click(function(event) {
		event.preventDefault();
		if ($ifloorplanCameras.find('> div.active a').length > 1) {
			stopIfloorplanRotation();
			var level = $ifloorplanCameras.find('> div.active').attr('id').replace(/camera-level-/, '');
			var $currentCamera = $ifloorplanCameras.find('> div.active').find('a.active');
			if ($currentCamera.is(':first-child')) {
				imageNumber = $ifloorplanCameras.find('> div.active a:last-child').attr('id').replace('camera-' + level + '-', '');
			} else {
				imageNumber = $currentCamera.prev().attr('id').replace('camera-' + level + '-', '');
			}
			showIfloorplanImage(level, imageNumber);
		}
	});

	// play pause rotating images
	$('#pause-play-cameras a').click(function(event) {
        unPause = false;
		event.preventDefault();
		if ($(this).text() == 'Pause') {
			stopIfloorplanRotation();
		} else {
			$(this).text('Pause');
			ifloorplanRotationTimeout = setTimeout("rotate()", timeOut);
		}
	});
});

function stopIfloorplanRotation() {
	clearTimeout(ifloorplanRotationTimeout);
	$('#pause-play-cameras a').text('Play');
}

function nextImage() {
	if ($ifloorplanCameras.find('> div.active a').length > 1) {
		var level = $ifloorplanCameras.find('> div.active').attr('id').replace(/camera-level-/, '');
		var $currentCamera = $ifloorplanCameras.find('> div.active').find('a.active');
		if ($currentCamera.is(':last-child')) {
			imageNumber = 1;
		} else {
			imageNumber = $currentCamera.next().attr('id').replace('camera-' + level + '-', '');
		}
		showIfloorplanImage(level, imageNumber);
	}
}

function nextImageRotation() {
	if ($ifloorplanCameras.find('> div.active a').length > 1 || $ifloorplanNavigationLevels.find('ul li:visible').length > 1) {
		var level = $ifloorplanCameras.find('> div.active').attr('id').replace(/camera-level-/, '');
		var $currentCamera = $ifloorplanCameras.find('> div.active a.active');
		if ($currentCamera.is(':last-child') && $ifloorplanNavigationLevels.find('ul li:visible').length == 1) {
			imageNumber = 1;
		} else if ($currentCamera.is(':last-child')) {
			imageNumber = 1;
			if ($ifloorplanNavigationLevels.find('ul li.active').is(':first-child')) {
				level = $ifloorplanNavigationLevels.find('ul li:last-child').attr('id').replace('level-', '');
			} else {
				var li = $ifloorplanNavigationLevels.find('ul li.active').prev().filter(function() {
                    return $(this).css('visibility') != 'hidden';
                });
                
                if (li.attr('id')) {
                    level = li.attr('id').replace('level-', '');
                } else {
                    level = 0;
                }
			}
		} else {
			if ($currentCamera.next().length) {
				imageNumber = $currentCamera.next().attr('id').replace('camera-' + level + '-', '');
			} else {
				imageNumber = 0;
			}
		}
		level = level == 'facade' ? '0' : level; //hack fix to stop facade rotating in, fix properly later
		showIfloorplanImage(level, imageNumber);
	}
}

function rotate() {
	nextImageRotation();
	clearTimeout(ifloorplanRotationTimeout);
	ifloorplanRotationTimeout = setTimeout("rotate()", timeOut);
}

function showIfloorplanImage(level, imageNumber) {

	// show the current floor plan
	$ifloorplanFloorplan.find('img.active').removeClass('active');
	if ($('#floorplan-' + level).length) {
		$('#floorplan-' + level).addClass('active');
	}
	//$ifloorplanFloorplan.find('img.active').dropShadow();

	// show the current cameras from the current level
	$ifloorplanCameras.find('> div.active').removeClass('active');
	if ($('#camera-level-' + level).length) {
		$('#camera-level-' + level).addClass('active');
	}

	// make the current level have the active class
	$ifloorplanNavigationLevels.find('li.active').removeClass('active');
	if ($('#level-' + level).length) {
		$('#level-' + level).addClass('active');
	}
    
    // hide the media icons
    $(".video").hide();
    $(".vLevel" + level).show();

	// show the current image
	$ifloorplanImages.find('img.active').removeClass('active');
	var $image = $('#image-' + level + '-' + imageNumber);
	if ($image) {
		$image.addClass('active');
		// load the image if it hasn't been loaded
		if ($image.attr('src') && $image.attr('src').search(/loading/) != -1) {
			$image.attr('src', $image.attr('rel'));
		}
	}
	
	// create the shadow on the new image
	//$image.dropShadow();

	// remove the on image from the old camera
	var $currentCamera = $ifloorplanCameras.find('> div > a.active img');
	if ($currentCamera.length) {
		var offImage = $currentCamera.attr('src').replace(/hover/, 'normal');
		$currentCamera.attr('src', offImage);
	}

	// make the current camera active
	$ifloorplanCameras.find('> div > a.active').removeClass('active');
	if ($('#camera-' + level + '-' + imageNumber)) {
		$('#camera-' + level + '-' + imageNumber).addClass('active');
	}

	//show the on image for the current camera
	var $currentCamera = $ifloorplanCameras.find('> div > a.active img');
	if ($currentCamera.length) {
		var onImage = $currentCamera.attr('src').replace(/normal/, 'hover');
		$currentCamera.attr('src', onImage);
	}

}

