// 
//  bs_ready.js
//  Brookside Resort
//  
//  Created by Jesse Bunch on 2010-04-13.
//  Copyright 2010 Paramore|Redd Online Marketing. All rights reserved.
// 

// Images to Preload
var arrImages = new Array(
	
	"/images/site/img-resort-feature.jpg",
	"/images/site/img-waterhole-feature.jpg",
	"/images/site/img-eventscenter-feature.jpg",
	"/images/site/img-hikingfishing-feature.jpg",
	"/images/site/img-thepool-feature.jpg"
	
);


$(document).ready(function(){
	/* jquery commands here */
	
	// Let IE know about HTML 5 Elements
	document.createElement("figure");
	
	// Open external links in new window
	$('a[rel="external"]').click(function(){
	  this.target = "_blank";
	});
	
	// Make featured package block clickable
	$('#current-package').click(function(){
		window.location=$(this).find("a").attr("href");
		return false;
	});
	
	$('#current-package').css('cursor','pointer');
	$('#current-package').mouseover(function(){
		$('#current-package a').css('color','#333333');
	}).mouseout(function(){
		$('#current-package a').css('color','#8F3700');
	});

	
	
	// Preload header image
	var strImgSrc = $('#interior-frame img#header-image').attr('src');
		if (strImgSrc != undefined) {
			var imgObj = new Image();		
			imgObj.src = strImgSrc + "?&random=" + Math.round(Math.random()*9999999);
			$(imgObj).load(function() {
				$('#interior-frame img#header-image').attr('src', imgObj.src);
				setTimeout(function() {
					$('#interior-frame img#header-image').fadeIn('2000');
				}, 5000);
				
			});
		}
	$('#interior-frame img#header-image').load(function() { $(this).fadeIn('slow'); $('#interior-frame div#loader-image').fadeOut('slow'); });
	
	// Replace fonts with acclamation on page
	Cufon.replace('h1, h2, #explore li a');
	
	// Initialize Google Map on Directions Page
	if ($("#map_canvas").length == 1) {
		
		var script = document.createElement("script");
		  script.type = "text/javascript";
		  script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initDirectionsMap";
		  document.body.appendChild(script);
		
	}
	

	// Load fancybox for cool modals.
	$("a.inline").fancybox({
		'transitionIn'	:	'fade',
		'transitionOut'	:	'fade',
		'margin'		:   0,
		'padding'		:   0,
		'speedIn'		:	500, 
		'speedOut'		:	500, 
		'overlayShow'	:	true,
		'overlayOpacity':   0.4,
		'overlayColor'	:   '#3e2b23',
		'centerOnScroll':   true,
		'autoScale': 	false,
		'scrolling': 	'no',
		'titleShow': 	false,
		onComplete			: 	function() {
			$(".fancy-bg").hide();
		}
		
		
	});
	
	
	// Expandable p's
	// Cool idea, but AM's said no
	// $('p.expandable span').expander({
	//   slicePoint:       50,      // the number of characters at which the contents will be sliced into two parts. 
	//                               // Note: any tag names in the HTML that appear inside the sliced element before 
	//                               // the slicePoint will be counted along with the text characters.
	//   widow:            4,        // a threshold of sorts for whether to initially hide/collapse part of the element's contents. 
	//                               // If after slicing the contents in two there are fewer words in the second part than 
	//                               // the value set by widow, we won't bother hiding/collapsing anything.
	//   expandText:       'read more...',   // text displayed in a link instead of the hidden part of the element. 
	//                               // clicking this will expand/show the hidden/collapsed text
	//   expandPrefix:     ' -- ', // text to come before the expand link                              
	//   collapseTimer:    0,        // number of milliseconds after text has been expanded at which to collapse the text again
	//   expandEffect:     'fadeIn',
	//   expandSpeed:      '',       // speed in milliseconds of the animation effect for expanding the text
	//   userCollapse:     true,     // allow the user to re-collapse the expanded text.
	//   userCollapseText: 'read less...',  // text to use for the link to re-collapse the text
	//   userCollapsePrefix: ' -- ' // text to come before the re-collapse link
	// 
	//   });
	
	
	
	// Contact form validation
	$('#contactForm').validate({
		rules: {
			name: "required",
			email: {
				required: true,
				email: true
			},
			comment: "required",
			captcha: "required"
		},
		messages: {
			name: " Required",
			email: {
				required: " Required",
				email: " Invalid"
			},
			comment: " Required",
			captcha: " Required"
		},
		errorElement: "em",
		errorPlacement: function(error, element) {
			var id_is = element.attr("id");
			//alert(id_is);
			error.appendTo( $('#fs-'+id_is+' label') );
		}
	});
	
	$('#directionsForm').validate({
		rules: {
			saddr: "required"
		},
		messages: {
			saddr: "<br><br>Required"
		},
		errorElement: "em",
		errorPlacement: function(error, element) {
			var id_is = element.attr("id");
			//alert(id_is);
			error.appendTo( $('#fs-'+id_is+' label') );
		}
	});

	// Animate the rollover of the explore images on the home page
	$('#explore ul li').hover(
		
		function() {
			
			// Fade out the black and white image to reveal the colored image
			var objLink = $(this).find('a:first');
			forceAnimationFinish(objLink);
			objLink.fadeTo(1250, 0.0);		
			
		},
		
		function() {
			
			// Fade in the black and white image to hide the colored image
			var objLink = $(this).find('a:first');
			forceAnimationFinish(objLink);
			objLink.fadeTo(250, 1.0);
			
		}
		
	);
	
	$('#explore ul li a:first-child').click(function() {
		
		// Stop the automatic scrolling
		clearInterval(objCycleInterval);
		
		// Swap Image
		swapFeatureImage($(this));
		
		// Prevent link
		return false;
		
	});
	
	// Cycle Images on Home Page
	var objCycleInterval;
	if ($('div#gallery').length == 1) {
		objCycleInterval = setInterval(function() {
			
			// Get currently selected image
			var objSelectedImage = $('#explore ul li a.active');
			var nextIndex = objSelectedImage.parent().index() + 1;
			if (nextIndex > ($('#explore ul li').length - 1)) { nextIndex = 0; }
			var nextItem = $('#explore ul li:eq('+nextIndex+') a');
			swapFeatureImage(nextItem);
			
		}, 5000);
	}
	

	
	
	// Make sure big images are preloaded
	preloadImages();
	
	

});


/*

forceAnimationFinish()
If object is currently animating, this function finishes the animation early. Used to create fluidity when another animation is pending.

Parameters:
(object) - "jqObj" - A jQuery Object to iterate over

Returns: nothing

*/
function forceAnimationFinish(jqObj) {
	
	if (jqObj.is(':animated')) { jqObj.stop(false, true); }
	
}



/*

initDirectionsMap()
Iniitializes the google map used on the directions page.

Parameters: none
Returns: nothing
Author: Jesse Bunch


*/
function initDirectionsMap() {
	
    var latlng = new google.maps.LatLng(35.716583, -83.502885); // LL for 463 E Parkwwasy
    var myOptions = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	var image = '/images/site/ico-map.png';
	  var beachMarker = new google.maps.Marker({
	      position: latlng,
	      map: map,
	      icon: image
	  });

  }

/**
 * Loops through image array to preload neccessary images
 *
 * @return void
 * @author Jesse Bunch
 **/
function preloadImages() {
	
	for(intIndex in arrImages) {
		
		var objImg = new Image();
		objImg.src = arrImages[intIndex];
		
	}
	
}

/**
 * Swaps the featured image on the home page
 *
 * @return void
 * @author Jesse Bunch
 **/
function swapFeatureImage(objClickedItem) {
	
	// Check to see if the user clicked on the currently selected item, uncomment once we get separate images in there
	if ($('#gallery img').attr('src') == objClickedItem.attr('href')) { return; }
	
	// Switch the active item
	$('#explore ul li a.active').removeAttr("class");
	objClickedItem.parent().find('a:first').attr("class", "active");
	
	// Swap out the main image
	$('#gallery img').fadeOut("fast", function() {
		$('#gallery img').attr('src', objClickedItem.attr('href'));
		$('#gallery img').fadeIn("fast");
	});
	
}
