/*
	SuperCampStaff.com main javascript functions
	Author: Ryan Oglesby
	Date: 10-29-2010
*/

/******** Document ready handler ***********/
$(document).ready(function(){
	// Set up sub menu
	$("#sub_menu ul").hide();
	$("#sub_menu ul li").hide();
	
	$("#main_menu ul li a").mouseenter( function() {
		$("#sub_menu ul").hide();
		$("#sub_menu ul li").hide();
	});
	
	$("#positions").mouseenter( function() {
		$("#sub_menu ul").show();
		$("#sub_menu ul li.positions").show();
	});
	
	// Initialize slider
	if( $("#slider").length ) {
		initSlider();
	}	
	
	// Initialze fader slideshows on role pages
	if( $("#slideshows_container .slideshow").length ) {
		initRoleSlideshows();
	}
	
	// Initialze fader slideshows on contact us
	if( $("#scpd").length ) {
		initContactUsSlideshows();
	}
	
	// Initialize Locations and Dates page
	if( $("#location_container").length && $("#calendar").length ) {
		initLocations();
	}
	
	// Initialize application page
	if( $(".form_row").length ) {
		initApplication();
	}
	
	// Initialize FAQ
	if( $(".faq_toc").length ) {
		initFAQ();
	}
});


/************************ Image slider ************************/

var youtubePlayer = null;

function initSlider() {
	// Insert left and right arrow controls and play/pause controls in the DOM
	$('#slider_container').prepend('<span class="slide_nav" id="nav_prev">Move left</span>')
						  .append('<span class="slide_nav" id="nav_next">Move right</span>')
						  .append('<div id="slider_controls_container"><div id="slider_controls"><span id="slider_play">play</span><span id="slider_pause">pause</span></div></div>');
	
	// Get a reference to the video
	// Need access to the video to ensure video does not keep playing while the slider is sliding
	var params = { allowScriptAccess: "always" };
    var atts = { id: "youtube_video" };
    swfobject.embedSWF("http://www.youtube.com/v/-0j6x6WBkCE?enablejsapi=1&playerapiid=ytplayer", 
                       "youtube_container", "395", "295", "8", null, null, params, atts);
                       
    $('#slider').cycle({ 
    	fx:			"scrollHorz",
    	speed:		1000, 
   		timeout:	6000,
   		manualTrump: false,
   		next: 		"#nav_next",
   		prev:		"#nav_prev",
   		prevNextClick:	function() {
   			// Pause when clicking next/prev
   			$('#slider').cycle('pause');
   		}
	});
	
	$("#slider_play").click(function() { $('#slider').cycle('resume'); });
	$("#slider_pause").click(function() { $('#slider').cycle('pause'); });
}
function onYouTubePlayerReady(playerId) {
	youtubePlayer = document.getElementById("youtube_video");
	youtubePlayer.addEventListener("onStateChange","onYouTubePlayerStateChange");
}
function onYouTubePlayerStateChange(newState) {	
	// Pause the slider while watching the video
	if( newState == 1 || newState == 3 ) {  // Playing or buffering
		$('#slider').cycle('pause');
	}
}


/************************ Role Page Image Faders ************************/
/**
	Preload the images so that if the user has javscript turned off, then they just see the 1st image
	With javascript, this will ensure all images are loaded before starting any faders
*/
var slideshow1_images = [];
var slideshow2_images = [];
var slideshow3_images = [];
var slideshow1_image_count = 25;
var slideshow2_image_count = 24;
var slideshow3_image_count = 24;

function initRoleSlideshows() {
	preloadIntoArray(slideshow1_images, 1, slideshow1_image_count, "../images/role_slideshows/slideshow_1/", "", 200, 175, "Camp Picture");
	preloadIntoArray(slideshow2_images, 1, slideshow2_image_count, "../images/role_slideshows/slideshow_2/", "", 200, 175, "Camp Picture");
	preloadIntoArray(slideshow3_images, 1, slideshow3_image_count, "../images/role_slideshows/slideshow_3/", "", 200, 175, "Camp Picture");
	
	setTimeout("startRoleSlideshows()",200);
}

function startRoleSlideshows() {
	if( slideshow1_images.length == slideshow1_image_count && 
		slideshow2_images.length == slideshow2_image_count && 
		slideshow3_images.length == slideshow3_image_count ) { // All images have loaded

		for( var i = 0; i < slideshow1_images.length; i++ ) {
			$('#slideshow_1').append( createHTMLImg_hidden(slideshow1_images[i]) );
		}
		for( var i = 0; i < slideshow2_images.length; i++ ) {
			$('#slideshow_2').append( createHTMLImg_hidden(slideshow2_images[i]) );
		}
		for( var i = 0; i < slideshow3_images.length; i++ ) {
			$('#slideshow_3').append( createHTMLImg_hidden(slideshow3_images[i]) );
		}

		// Random timeouts, but make sure they are not too close together
		var timeout1 = 4000 + Math.floor(Math.random()*2500);
		var timeout2 = 4000 + Math.floor(Math.random()*2500);
		var timeout3 = 4000 + Math.floor(Math.random()*2500);
	    
	 	// Start the faders
	    $('#slideshow_1').cycle({
	        timeout:  timeout1,
	        random:	  1
	    }); 
	    $('#slideshow_2').cycle({ 
	        timeout:  timeout2,
	        random:	  1
	    });
	    $('#slideshow_3').cycle({ 
	        timeout:  timeout3,
	        random:	  1
	    });
	    
	    // Fade in the first image
	     $(".slideshow img").css({
	        opacity: 0
	     });
	    
	    // Hide the absolutely positioned images right after the first image fades in
	    // Use 7 seconds because the max timeout above is 6.5 seconds
	    setTimeout( function() { $(".initial_role_slideshow").remove(); }, 7000 );
	}
	else {
		setTimeout("startRoleSlideshows()",200);
	}
}

/************************ Who We Are Image Faders ************************/
/**
	Preload the images so that if the user has javscript turned off, then they just see the 1st image
	With javascript, this will ensure all images are loaded before starting any faders and that they are synced
*/
var katie_images = [];
var marina_images = [];
var chicka_images = [];
var jake_images = [];

function initContactUsSlideshows() {
    preloadIntoArray(katie_images, 2, 4, "images/", "katie_", 197, 148, "Katie");
    preloadIntoArray(marina_images, 2, 4, "images/", "marina_", 197, 148, "Marina");
    preloadIntoArray(chicka_images, 2, 4, "images/", "chicka_", 197, 148, "Chicka");
    preloadIntoArray(jake_images, 2, 4, "images/", "jake_", 197, 148, "Jake");
	
	setTimeout("startContactUsSlideshows()",200);
}

function startContactUsSlideshows() {
	if( katie_images.length	== 3 && 
		chicka_images.length == 3 && 
		marina_images.length == 3 && 
		jake_images.length== 3) { // All images have loaded
		
		for( var i = 0; i < katie_images.length; i++ ) {
			$('#katie_slideshow').append( createHTMLImg(katie_images[i]) );
		}
		for( var i = 0; i < chicka_images.length; i++ ) {
			$('#chicka_slideshow').append( createHTMLImg(chicka_images[i]) );
		}
		for( var i = 0; i < marina_images.length; i++ ) {
			$('#marina_slideshow').append( createHTMLImg(marina_images[i]) );
		}
		for( var i = 0; i < jake_images.length; i++ ) {
			$('#jake_slideshow').append( createHTMLImg(jake_images[i]) );
		}
		
		$('.slideshow').cycle();
	}
	else {
		setTimeout("startContactUsSlideshows()",200);
	}
}

/************************ Image Fader Preloading Utility Functions ************************/

function preloadIntoArray(array, start_index, end_index, path, image_prefix, width, height, alt_text) {
    for (var i = start_index; i <= end_index; i++) { 
        var myImg = new Image(width,height); 
        myImg.src = path + image_prefix + i + '.jpg?random=' + (new Date()).getTime();  // This fixes an IE image caching issue
        myImg.alt = alt_text; 
        $(myImg).bind('load', function() { 
            array.push(this); 
        }); 
    }
}

function createHTMLImg(myImg) {
	return '<img src="'+myImg.src+'" width="'+myImg.width+'" height="'+myImg.height+'" alt="'+myImg.alt+'" />';
}
function createHTMLImg_hidden(myImg) {
	return '<img src="'+myImg.src+'" width="'+myImg.width+'" height="'+myImg.height+'" alt="'+myImg.alt+'" style="display:none;opacity:0;-ms-filter:\'progid:DXImageTransform.Microsoft.Alpha(Opacity=0)\';filter:alpha(opacity=0);" />';
}

/************************ Locations Calendar and Tabs ************************/

var defaultLocation = "stanford";
// 0 = January, 1 = February, ...
var defaultMonths = {"brown":		6,
					"loyola":		6,
					"stanford":		5,
					"berkeley":		6,
					"florida":		6,
					"wakeforest": 	5,
					"kentstate":	6,
					"ucla":			6};
					
var currentYear = 2012;
					
function initLocations() {
	// Hide all details initially
	$(".details_container").hide();
	
	// Show the default
	$("#"+defaultLocation).addClass("active"); // List item
	$("#"+defaultLocation+"_details").show().addClass("active"); // Details div
	
	// Initialize the calendar and show the default
	$('#calendar').fullCalendar({
		year: currentYear,
		month: defaultMonths[defaultLocation],
		header: {
			left: 'title',
			center:'',
			right: 'prev,next'
		},
		events: "javascripts/camp_dates_json/"+defaultLocation+".js"
	});
	
	// Add the click handlers for the tabs
	$("#locations_list li").click( function() {
		var new_elt = $(this);
		
		if( !new_elt.hasClass("active") ) {
			// Get the ids (the site name) to unload and reload the events calendar
			var new_loc = new_elt.attr("id");
			
			var old_elt = $("#locations_list li.active");
			var old_loc = old_elt.attr("id");
		
			// Change the active list item
			old_elt.removeClass("active");
			new_elt.removeClass("hover").addClass("active");
		
			// Change the details
			$("#"+old_loc+"_details").hide();
			$("#"+new_loc+"_details").show();
			
			// Load the calendar events
			$('#calendar').fullCalendar( 'removeEventSource',	"javascripts/camp_dates_json/"+old_loc+".js" )
					  	  .fullCalendar( 'addEventSource',		"javascripts/camp_dates_json/"+new_loc+".js" )
					  	  .fullCalendar( 'gotoDate', currentYear, defaultMonths[new_loc] );
		}
		
	}).hover(
		function () {
			if( !$(this).hasClass("active") ) {
				$(this).addClass("hover");
			}
		}, 
		function () {
			$(this).removeClass("hover");
  		});
}

/************************ Applications Datepicker and Text Counter ************************/

function initApplication() {
	var default_start_date = "6/1/2012";
	var default_end_end = "8/31/2012";
	
	// Datepicker
	$("input[id$='StartDate']").datepicker({ 
		defaultDate: "6/1/2012",
		minDate: default_start_date, 
		maxDate: default_end_end
	});
	$("input[id$='EndDate']").datepicker({ 
		defaultDate: "8/1/2012",
		minDate: default_start_date, 
		maxDate: default_end_end 
	});
	
	// Text counter
	// Don't limit the amount of text, just count it for the user
	var textarea_ids = new Array("TLNotes", "FacilitatorNotes", "WellnessNotes", 
								"OMNotes", "LMNotes", "WPCertifications", 
								"AccomplishThisYear", "LFacDependOn");
						
	for(var i = 0; i < textarea_ids.length; i++) {
		$("textarea[id$='"+textarea_ids[i]+"']").NobleCount("#"+textarea_ids[i]+"_chars_remain", {
			max_chars: 		500,
			on_negative:	"over_limit",
			on_positive:	"under_limit"
		});
	}
}

/************************ FAQ Answer Highlighter ************************/

function initFAQ() {
	$(".question").click( function() {
		var target = $(this).attr("href").substr(1); // Remove the #
		
		$("a[name='"+target+"']").closest("li").effect("highlight", {}, 5000)
	});
}
