
google.load("jquery", "1.4.2");
google.setOnLoadCallback(init);
//
var currentPath = location.href;
var	hostPath = (currentPath.indexOf('localhost') != -1)? '/americanfederal/' : '/';
//
function init() {
   	if(typeof jQuery == 'undefined') {
		alert('menu error: jquery has not loaded.');	
	}
	else {
		/* Stop IE flicker */
		if ($.browser.msie == true) document.execCommand('BackgroundImageCache', false, true);
		//
		$('#page .mainColumn .postContainer:last').css("border","0px solid transparent");
		$('#page .mainColumn .staff:last').css("border","0px solid transparent");
		$('#page .mainColumn .coinContainer:last').css("border","0px solid transparent");
		$('#page .mainColumn table tr:odd').addClass("alt");
	 	menuInit();
	  	$('#tickerContainer #ticker').fadeIn();
		/*//
		$('#tickerContainer #ticker').load(hostPath + 'assets/php/marketTicker.php', function() {
		  $(this).fadeIn();
		});
		//*/
		contactFormInit();
		mediaPlayerInit();
		mapInit();
		slideShowInit();
		pollsInit();
	}
}
function pollsInit () {
	//if ($('#playlistContainer').length) {
		pollsL10n = {
			ajax_url: hostPath +"wp/wp-content/plugins/wp-polls/wp-polls.php",
			text_wait: "Your last request is still being processed. Please wait a while ...",
			text_valid: "Please choose a valid poll answer.",
			text_multiple: "Maximum number of choices allowed: ",
			show_loading: "1",
			show_fading: "1"
		};
		$.getScript(hostPath + 'wp/wp-content/plugins/wp-polls/polls-js.js?ver=2.50', pollsLoaded);
	//}
}
function pollsLoaded () {

}
//////////////////// main menu ajax logic
function menuInit() {
	var Menu = {
		// object level variables
		timeout: 250,
		closeTimer: null,
		currentSubmenu: null,

		initEvents: function () {
			$('#menu > li').each(function(index) {
				var item = this;		
				$(item).hover(
				  function () {
				    $(this).addClass("hoverClass");
				  },
				  function () {
				    $(this).removeClass("hoverClass");
				  }
				);
				// has submenu
				if($(item).has('ul').length) { 
					$(item).bind('mouseover', Menu.submenuOpen);
					//$(item).bind('mouseout',  Menu.submenuStartCloseTimer);
					$(item).bind('mouseout',  Menu.submenuCloseAndCancelTimer);
				}
				else {
					$(item).bind('mouseover', Menu.submenuCloseAndCancelTimer);
				}
			});
			document.onclick = Menu.submenuCloseAndCancelTimer;
		},
		
		submenuOpen: function () {
			Menu.submenuCloseAndCancelTimer();
			// find the submenu in the current item and get reference to it
			Menu.currentSubmenu = $(this).find('ul').eq(0);
			// get the x of the menu as a whole relative to the page
			var menuOffset = $('#wrapper').offset();
			var menuHeight = $('#menuContainer').height();
			//
			var menuItemOffset = $(this).offset();
			// position the submenu below and left aligned to the parent item
			Menu.currentSubmenu.css('left', menuItemOffset.left - menuOffset.left);
			Menu.currentSubmenu.css('top', menuItemOffset.top + menuHeight);
			// show the menu
			Menu.currentSubmenu.css('visibility', 'visible');
		},
		
		submenuClose: function () {  
			if(Menu.currentSubmenu) {
				Menu.currentSubmenu.css('visibility', 'hidden');
				Menu.currentSubmenu = null;
			}
		},
		
		submenuStartCloseTimer: function () {
			Menu.closeTimer = window.setTimeout(Menu.submenuClose, Menu.timeout);
		},
		
		submenuCancelTimer: function() {  
			if(Menu.closeTimer) {  
				window.clearTimeout(Menu.closeTimer);
				Menu.closeTimer = null;
			}
		},
		
		submenuCloseAndCancelTimer: function () {
			Menu.submenuClose();
			Menu.submenuCancelTimer();
		},
		
		init: function () {
			Menu.initEvents();
		}
	}
	Menu.init();
}
var player = null;
var mediaPlayerCurrentState = null;
var mediaPlayerPlaylistTrackIndex = null;
function mediaPlayerInit () {
	if ($('#playlistContainer').length) {
		$.getScript(hostPath + 'assets/js/objects/jwplayer-js.js', mediaPlayerLoaded);
	}
}
function mediaPlayerLoaded (){
	jwPlayerInit ();
	$('#mediaPlayerContainer').show();
	$('#playlistContainer').fadeIn('slow');
	mediaPlayerPlaylistInit();
}
function mediaPlayerPlaylistInit () {
	$('#playlistContainer .playlistItemContainer a.playlistItem').click(
		function () { 
			var index =  $('#playlistContainer .playlistItemContainer').index($(this).parent().parent());
			mediaPlayerPlayPlaylistItem(index);
			return false;
		}
	);
	$('#playlistContainer .playlistItemContainer').click(
		function () { 
			var index =  $('#playlistContainer .playlistItemContainer').index(this);
			mediaPlayerPlayPlaylistItem(index);
			return false; 
		}
	);
}
function mediaPlayerPlayPlaylistItem (index) {
	// have to increment the index since the nth-child selector is a 1 based list instead of 0 based
	index++;
	mediaPlayerPlaylistTrackIndex = index;
	var link = $('#playlistContainer .playlistItemContainer:nth-child(' + index +') .title a.playlistItem');
	var url = link.attr("href");
	// check to see if that same index already is playing or a  new track
	if(!$('#playlistContainer .playlistItemContainer:nth-child(' + index +')').hasClass('playlistItemContainerCurrentTrack')) {
		$('#playlistContainer .playlistItemContainer').removeClass('playlistItemContainerCurrentTrack');
		$('#playlistContainer .playlistItemContainer .playPauseContainer').removeClass('playing');
		$('#playlistContainer .playlistItemContainer .playPauseContainer').removeClass('paused');
		$('#playlistContainer .playlistItemContainer:nth-child(' + index +')').addClass('playlistItemContainerCurrentTrack');
		$('#playlistContainer .playlistItemContainer:nth-child(' + index +') .playPauseContainer').addClass('playing');
		// in the future we will reference the player and change the track
		mediaPlayerCreateInstance(url);
	}
	else {
		// toggle the current track
		player.sendEvent('PLAY');
	}
}
function mediaPlayerCreateInstance(url) {
	var html = '<video height="20" id="mediaPlayer" src="' + url + '" width="580">';
	$('#mediaPlayerContainer').html(html);
	$('#mediaPlayer').jwplayer({
		//autostart:true,
		flashplayer: hostPath + 'assets/mediaplayer/player.swf',
		skin: hostPath + 'assets/mediaplayer/stormtrooper/stormtrooper.xml',
		volume: 50
    });
}
function playerReady(thePlayer) { 
	player = window.document[thePlayer.id];
	//alert("playerReady " + thePlayer.id); 
	player.sendEvent('PLAY');
	mediaPlayerAddListeners();
};
function mediaPlayerAddListeners() {
	if (player) { 
		player.addModelListener("STATE", "mediaPlayerStateListener");
	} else {
		setTimeout("mediaPlayerAddListeners()",100);
	}
}
function mediaPlayerStateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	mediaPlayerCurrentState = obj.newstate; 
	mediaPlayerPreviousState = obj.oldstate; 
	if ((mediaPlayerCurrentState == "PLAYING")) {
		var o = $('#playlistContainer .playlistItemContainer:nth-child(' + mediaPlayerPlaylistTrackIndex +') .playPauseContainer');
		$('#playlistContainer .playlistItemContainer:nth-child(' + mediaPlayerPlaylistTrackIndex +') .playPauseContainer').addClass('playing');
	}
	else if ((mediaPlayerCurrentState == "PAUSED")) {
		$('#playlistContainer .playlistItemContainer .playPauseContainer').removeClass('playing');
	}
}var RecaptchaOptions = {
   theme : 'clean'
};
function contactFormInit () {
	if($("#contactForm").length){
		$('form#contactForm').submit(function() {
			$('form#contactForm .error').remove();
			var hasError = false;
			$('.requiredField').each(function() {
				var labelText = $(this).attr("id");
				switch(labelText){
					case "contactName":
						labelText = "name";
					break;
			
					case "commentsText":
						labelText = "comments";
					break;
				}
				if(jQuery.trim($(this).val()) == '') {
					$(this).parent().append('<div class="error">Please enter your '+labelText+'.</div>');
					hasError = true;
				} 
				if($(this).hasClass('email')) {
					var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
					//var emailReg = "^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$";
					if(!emailReg.test(jQuery.trim($(this).val()))) {
						$(this).parent().append('<div class="error">You entered an invalid '+ labelText + '.</div>');
						hasError = true;
					}
				}
				/*//
				if($(this).hasClass('phone')) {
				
					var phone = jQuery.trim($(this).val()));
					phone = phone.replace(/\s+/g, ""); 
					var phoneReg = '/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/';
					if(!phoneReg.test(phone) {
						$(this).parent().append('<div class="error">You entered an invalid '+ labelText + '.</div>');
						hasError = true;
					}
				}
				//*/
			});
			if(!$("input#recaptcha_response_field").val()){
				$('#recaptchaRow').append('<div id="recaptchaError" class="error">Please enter the value for the reCAPTCHA field above. If your stuck, click the blue button that has a white circular logo with two arrows for a new word.</div>');
				hasError = true;
			}
			if(!hasError) {
				// show a sending form dialog
				$('#contactFormErrorContainer').html("");
				$('form#contactForm').hide();
				$('form#contactForm').submit();
			}
			else {
				$('#contactFormErrorContainer').html('<div id="contactFormError" class="error">There was an error submitting the form.</div>'); 
			}
			return false;
		});
	}
}
function mapInit() {
	if ($('#mapContainer').length) {
		mapLoadGoogleJs();
    }
}
function mapLoadGoogleJs () {
	$.getScript('http://maps.google.com/maps/api/js?v=3.1&sensor=false&callback=mapGoogleJsLoaded', mapGoogleJsLoaded);
}
function mapGoogleJsLoaded () {
	mapLoadJs();
}
function mapLoadJs () {
	$.getScript(hostPath + 'assets/js/objects/googleMap.js', mapJsLoaded);
	// load css next ??
}
function mapJsLoaded () { 
	mapRender();
}
function slideShowInit (){
	SlideShow = {
		
		timer: null,
		path: ".slideshow",
		
		init: function () {
			if($('.slideshow').length){
				$('.slideshow .images').show();
				var $active = $(SlideShow.path + ' .images IMG.active');
				if ($active.length == 0) $active = $(SlideShow.path + ' .images IMG:first');
				SlideShow.controlsInit();
				SlideShow.play();
			}
		},
		
		controlsInit: function () {
			if($('.slideshowControls').length) {
				$('.slideshow .images').mouseover(function () { $('.slideshowControls').show(); });
				$('.slideshowControls').mouseleave(function () { $('.slideshowControls').hide(); });
				$('.slideshow .images').click(function () { location.href = "http://www.americanfederal.com/about/memberships/"; });
				//
				$('.slideshowControls .pause').bind("click", SlideShow.pause);
				$('.slideshowControls .play').bind("click", SlideShow.play);
				$('.slideshowControls .next').bind("click", SlideShow.nextImage);
				$('.slideshowControls .previous').bind("click", SlideShow.previousImage);
				$('.slideshowControls .pause').hide(); 
				$('.slideshowControls .play').show();
				$('.slideshowControls').hide(); 
			}
		},
		
		isPlaying: function (){
			return (SlideShow.timer)? true : false;
		},
		
		play: function () {
			SlideShow.timer = setInterval("SlideShow.switchImage()", 4000);
			$('.slideshowControls .pause').show(); 
			$('.slideshowControls .play').hide();
			SlideShow.switchImage ();
		},
		
		pause: function (){
			clearInterval(SlideShow.timer);
			$('.slideshowControls .pause').hide(); 
			$('.slideshowControls .play').show();
		},
		
		goToImage: function (num) {
			var next =  $(SlideShow.path + ' .images IMG:eq(' + num + ')');
		    SlideShow.switchImage (next);	
		},
		
		previousImage: function (){
			if(SlideShow.isPlaying()) SlideShow.pause();
			var active = $(SlideShow.path + ' .images IMG.active');
			var next =  (active.prev().length) ? active.prev() : $(SlideShow.path + ' .images IMG:last');
		    SlideShow.switchImage (next);
		},
		
		nextImage: function (){
			if(SlideShow.isPlaying()) SlideShow.pause();
			var active = $(SlideShow.path + ' .images IMG.active');
			var next =  (active.next().length) ? active.next() : $(SlideShow.path + ' .images IMG:first');
		    SlideShow.switchImage (next);
		},
		
		switchImage: function (next){
			var active = $(SlideShow.path + ' .images IMG.active');
				active.addClass('last-active');
		    if (!next) var next =  (active.next().length) ? active.next() : $(SlideShow.path + ' .images IMG:first');
			var index =  $(SlideShow.path + ' .images IMG').index(next);
			//var title = $('ul#thumbnailController li:eq(' + index + ') a').text();
			//$('.mainColumn .post h2.dark').text(title);
			//$('ul#thumbnailController li.current_page_item').removeClass("current_page_item");
			//$('ul#thumbnailController li:eq(' + index + ')').addClass("current_page_item");
			//alert('nextIMage is: ' + index);
			//console.log('nextIMage is: ' + index);
		    next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() { active.removeClass('active last-active'); });
		}
	};
	SlideShow.init();
}
