////////////////////////////////////////////////////////
// GLOBAL VARIABLES
////////////////////////////////////////////////////////

var res_interval;
var field_focused = false;

var time_slide_transition = 1000;
var time_slide_transition_delay = 500;
var time_slide_interval = 6000;


var time_body_transition = 1000;
var time_body_transition_delay = 500;

var current_section;
var current_slide = 0;

var top_slide = "slide_1";
var bottom_slide = "slide_2";

var slide_interval;

var playlist = new Array(
  "/custom/audio/hip_jazz.mp3",
  "/custom/audio/ambience.mp3",
  "/custom/audio/vanilla_sky.mp3",
  "/custom/audio/where_to_now.mp3"
);

var shuffled_playlist = shuffle(playlist);
var current_audio_track = 0;

var scrollbar_content;
var sidebar_api;


jQuery(function($){	
	
  ////////////////////////////////////////////////////////
  // INITIALIZE
  ////////////////////////////////////////////////////////
	
	$("#curtain").css("opacity", "0");
	$("#footer_bg").css("opacity", ".8");
	
	//hide content data (seo)
	$(".content_data").hide();
	
	//load homepage
	$(document).ready(function(){	   
	  replace_hrefs();
	  slideshow_next("home");
		
	  $("#header").show();	
      $("#footer").show();
      		
		$("#jquery_jplayer").jPlayer({
			ready: function () {
				$(this).jPlayer("setMedia", {
				    mp3: shuffled_playlist[current_audio_track]
				});
				$(this).jPlayer("play");
				
				if(current_audio_track < (playlist.length - 1)){
				    current_audio_track++;
				}
				else {
				    current_audio_track = 0;
				}
			},
			ended: function() {			 
			  $(this).jPlayer("setMedia", {
			    mp3: shuffled_playlist[current_audio_track]
			  });
			  $(this).jPlayer("play");
			},
			swfPath: "/custom/js/jquery/plugins/jplayer/",
			supplied: "mp3",
			volume: .4,
			solution: "flash, html"
		});
	});
	
	
  ////////////////////////////////////////////////////////
  // SCROLLBAR
  ////////////////////////////////////////////////////////
  var scrollbar_settings = {
    showArrows: false
  };
  
  scrollbar_content = $('#content .content').jScrollPane(scrollbar_settings);
  sidebar_api = scrollbar_content.data('jsp');
	
	
  ////////////////////////////////////////////////////////
  // EVENT: Nav hovers
  ////////////////////////////////////////////////////////
	
	$("#header").hover(
		function () {
			slideshow_pause();
		},
		function () {
			slideshow_restart();
		}
	);
	
	$("#footer").hover(
		function () {
			slideshow_pause();
		},
		function () {
			slideshow_restart();
		}
	);
	
	$("#gallery").hover(
		function () {
			slideshow_pause();
		},
		function () {
			slideshow_restart();
		}
	);
	
	
  ////////////////////////////////////////////////////////
  // EVENT: Explore hover
  ////////////////////////////////////////////////////////	
	
	$("#property_tour").hover(
		function () {
			show_property_tour();
		},
		function (evt) {
			hide_property_tour(evt);
		}
	);
	
	$("#property_tour a.nav_primary").hover(
		function () {
			show_property_tour();
		},
		function (evt) {
			hide_property_tour(evt);
		}
	);
	
	$("#property_tour").click(function(){
		hide_property_tour(null);
		slideshow_restart();
	});
		
	
  ////////////////////////////////////////////////////////
  // EVENT: Email Signup
  ////////////////////////////////////////////////////////
  
  $("#email_form").submit(function(){
    var user_name = $("#email_form #name").val();
    var user_email = $("#email_form #mjtjjh-mjtjjh").val();
    
    switch(true){
      case (user_name == "") || (user_name.length < 3) || (user_name.indexOf(" ") == -1):
        alert("Please enter your full name.");
        return false;
        break;
        
      case (user_email == "") || (user_email.length < 6) || (user_email.indexOf("@") == -1) || (user_email.indexOf(".") == -1):
        alert("Email address does not appear to be correct. Please check again.");
        return false;
        break;
        
      default:
        return true;
    }
  });
	
	
  ////////////////////////////////////////////////////////
  // Additional Functionality
  ////////////////////////////////////////////////////////

	//footer AJAX
	$(".dynamic_url").click(function(evt){
	   //stop click event
	   evt.preventDefault();
	   
	   //retrieve data from expression engine
	   $.post(
	     "/ajax" + $(this).attr("href"),
         function(data) {
           $("#content .title").html(data.title);
           sidebar_api.getContentPane().html(data.content);
		   
		   if($("#content").css("display") == "none"){
		     $("#content").fadeIn();
		   }
		   
		   //fancybox
		   $("#content .iframe").fancybox({
      	     'overlayShow' : false,
      	     'hideOnOverlayClick' : false,
      	     'hideOnContentClick' : false,
      	     'enableEscapeButton' : false,
      	     'overlayShow' : true,
      	     'overlayColor' : '#000',
      	     'overlayOpacity' : 0.8
      	   });
		   
		   //ajust scrollbar
		   sidebar_api.reinitialise();
         },
         "json"
       );
       
       //track page
       _gaq.push(['_trackPageview', $(this).attr("href")]);
	});
	
	$("#audio_toggle a").click(function(){
		if($("#audio_toggle a").attr("class") == "off"){
			$("#jquery_jplayer").jPlayer("play");
			$("#audio_toggle a").removeClass("off");
		}
		else {
			$("#jquery_jplayer").jPlayer("pause");
			$("#audio_toggle a").addClass("off");
		}
	});
	
	//Opens footer if set in hash
	var hashtag = String(window.location.hash);
    if($(hashtag).length != 0){
      $(hashtag).click();
    }

});


function show_property_tour(){
	var wid = ($("#property_tour").width() + 40) + "px";
	$("#property_tour .bg").css("height", ($("#property_tour").height() + 16) + "px");
	$("#property_tour").addClass("active");
	
	$("#header #property_tour .bg").animate({
		width: wid
		}, 200, function() { 
			$("#header #property_tour ul").css("visibility", "visible");
	});
}

function hide_property_tour(evt){
	if((evt == null) || (check_rect_focus("property_tour", evt))){			
		$("#header #property_tour ul").css("visibility", "hidden");
		$("#property_tour").removeClass("active");
		
		$("#header #property_tour .bg").animate({
			width: 0
			}, 200, function() { 
				$("#header #property_tour ul").css("visibility", "hidden");
		});
	}
}


////////////////////////////////////////////////////////
// Pop-up
////////////////////////////////////////////////////////

function open_popup(page){
  //retrieve data from expression engine
  $.post(
    page,
    function(data) {
      $("#popup").html(data);
      
      $('#popup').reveal({
      animation: 'fade',
      animationspeed: 500,
      closeonbackgroundclick: false,
      dismissmodalclass: 'close-modal'  
      });
    }
  );
  
  //track page
  //_gaq.push(['_trackPageview', page]);
}


////////////////////////////////////////////////////////
// NAVIGATION REPLACEMENT
////////////////////////////////////////////////////////

function replace_hrefs(){
	$("a.dynamic_url").each(function (i) {
		var url = $(this).attr("href");
		
		if(url == "/"){
			var last_segment = "home";
		}
		else {
			var segments = url.split("/");
			var segment_length = segments.length;
			var last_segment = segments[segment_length - 2];
		}
		
		//$(this).attr("href", "javascript: void(0);");
						
		$(this).click(function(){
			slideshow_next(last_segment);
		});
		
	});
}


////////////////////////////////////////////////////////
// EVENT: Window Resize
////////////////////////////////////////////////////////

$(window).resize(function() {
	
	//BUG!!! Firefox won't give jQuery's height()
	var ua = $.browser;
	
	if(ua.mozilla){
	  var win_width = window.innerWidth;
	  var win_height = window.innerHeight;
	}
	else {
	  var win_width = $(window).width();
	  var win_height = $(window).height();
	}
	
	//resize background
	$('#background').css({'width': win_width, 'height': win_height});
	$("#nav_bg").css("height", (win_height - 25) + "px");
	resize_background();
	
	//resize sidebar
	$('#content .content').css({'height': win_height - 175 + "px"});
	sidebar_api.reinitialise();
});
	
	
////////////////////////////////////////////////////////
// FUNCTION: Resize Background
////////////////////////////////////////////////////////

function resize_background() {
	var item = "#background img";
	var elem = "#background";
	
	w = $(elem).width();
	h = $(elem).height();

	var ow = $(item).width();
	var oh = $(item).height();
	
	if (ow / oh > w / h) {
		var scale = h / oh;
		$(item).attr({'width':ow * scale,'height':oh * scale});
	} else {
		var scale = w / ow;
		$(item).attr({'width':ow * scale,'height':oh * scale});
	}
	$(item).css({'left':-(($(item).width()-w)/2),'top':-(($(item).height()-h)/2)});
}


////////////////////////////////////////////////////////
// FUNCTION: Show curtain
////////////////////////////////////////////////////////

function show_curtain(followup_function){
	$("#curtain").animate({
			opacity: 0.5
		}, 200, function() {
			eval(followup_function);
	});
}


////////////////////////////////////////////////////////
// FUNCTION: Hide curtain
////////////////////////////////////////////////////////

function hide_curtain(followup_function){
	$("#curtain").animate({
			opacity: 0
		}, 500, function() {
			eval(followup_function);
	});
}


////////////////////////////////////////////////////////
// FUNCTION: Check res focus
////////////////////////////////////////////////////////

function check_rect_focus(element, evt){
	var res_top = $("#" + element).offset().top;
	var res_left = $("#" + element).offset().left;
	var res_bottom = res_top + $("#" + element).height();
	var res_right = res_left + $("#" + element).width();
	
	if((evt.pageX < res_left) || (evt.pageX > res_right) || (evt.pageY < res_top) || (evt.pageY > res_bottom)){
		return true;
	}
	else {
		return false;
	}
}


////////////////////////////////////////////////////////
// FUNCTION: Stop animations
////////////////////////////////////////////////////////

function stop_animations(){
	$(".res_form").stop(true, true);
	$("#curtain").stop(true, true);
}



function swap_photo(img_src){
	$(".img_background").hide();
	
}


////////////////////////////////////////////////////////
// FUNCTION: Load section
////////////////////////////////////////////////////////

slideshow_restart();

function slideshow_next(section_id){	
	$("#background #" + top_slide).css("z-index", 9);
	$("#background #" + bottom_slide).css("z-index", 10);
	
	if(section_id != null){
	  current_section = section_id;
		current_slide = 0;
	}
	
	//$()
		$('#background #' + bottom_slide).append('<img style="display: none;" />');
		$('#background #' + bottom_slide + " img").load(function() {
			
			//resize background
			resize_background();
			$(window).resize();
			
			//fade in background
			$("#background #" + bottom_slide + " img").delay(time_slide_transition_delay).fadeIn(time_slide_transition, function(){
				
				//clean-up
				$('#background #' + bottom_slide + " img").remove();
				
				//if navigated to new section
				if(section_id != null){
					//set new section
					$("#slides .active").removeClass("active");
					
					//show section body
					/*if(section_id != "home"){
						$("#" + section_id).addClass("active");
						$("#page_content").hide();
						$("#gallery").delay(time_body_transition_delay).slideDown(time_body_transition);
					}
					else {
						$("#gallery").slideUp(time_body_transition);
					}*/
					
					//preload gallery
					preload(jQuery.makeArray($("#slides #" + section_id + " .gallery li a")));
				}
				
				//increament current slide
				var total_slides = $("#slides #" + current_section + " .gallery li a").length - 1;
				
				if(current_slide < total_slides){
				  current_slide++;
				}
				else {
					current_slide = 0;
				}
			});
			
			//update variables
			if(top_slide == "slide_1"){
				top_slide = "slide_2";
				bottom_slide = "slide_1";
			}
			else {
				top_slide = "slide_1";
				bottom_slide = "slide_2";
			}
		})
		//.attr('src', $("#slides #" + section_id + " .gallery li a").eq(0).attr("href"));
		.attr('src', $("#slides #" + current_section + " .gallery li a").eq(current_slide).attr("href"));
}


////////////////////////////////////////////////////////
// FUNCTION: Pause slideshow
////////////////////////////////////////////////////////

function slideshow_pause(){
	clearInterval(slide_interval);
}


////////////////////////////////////////////////////////
// FUNCTION: Restart slideshow
////////////////////////////////////////////////////////

function slideshow_restart(){
	clearInterval(slide_interval);
	slide_interval = setInterval(slideshow_next, time_slide_interval, null);
}


////////////////////////////////////////////////////////
// FUNCTION: Image preloader
////////////////////////////////////////////////////////

function preload(images) {
	var img_array = new Array();
	for(i = 0; i < images.length; i++){
		img_array[i] = new Image();
    img_array[i].src = images[i];
		img_array[i].onload = function(){
			//alert("Loaded!");
		}
	}
}


////////////////////////////////////////////////////////
// FUNCTION: Shuffle array
////////////////////////////////////////////////////////

function shuffle(array) {
  return array.sort(function(){ 
    return .5 - Math.random(); 
  });
}


////////////////////////////////////////////////////////
// GOOGLE ANALYTICS
////////////////////////////////////////////////////////

function outbound_link(link, category, action) {
	_gat._getTrackerByName()._trackEvent(category, action);
	setTimeout('document.location = "' + link.href + '"', 100);
}
