/********************************************************
 Bridge Javascript
*********************************************************/

// Page Load
$(function() {

	// Setup Overlay/Dialogs 
	SetupOverlay("facebook");
	SetupOverlay("whoWeAre");
	SetupOverlay("media");
	
	// Hide the overlay for scriptures
	$(".scriptureOverlay").hide();
	
	// Hide Scripture Popups
	$(".scripturePopup").hide();
	
	// Hide the H1 (need an h1, but don't want it to show)
	$(".bridge_title").hide();
	
	// Need to reset vertical scroller on music
	$('a[rel="#music"]').overlay({
		effect: 'apple',
		mask: '#CCC',
		top: '5%',
		onLoad: function() {
			ResetVerticalNavigation("music");
		}
	});
	
	// Need to reset vertical scroller on message
	$('a[rel="#message"]').overlay({
		effect: 'apple',
		mask: '#CCC',
		top: '5%',
		onLoad: function() {
			ResetVerticalNavigation("message");
		}
	});
	
	// Visit overlay is special for the FAQ section
	$('a[rel="#visit"]').overlay({
		effect: 'apple',
		mask: '#CCC',
		top: '5%',
		onLoad: function() {
			// Get only setup the scrollbar on the first time to the overlay
			if(!($("#faqContent div.scrollbar-pane").length > 0)) {
				$("#faqContent").scrollbar();
			}
			ResetVerticalNavigation("visit");
		}
	});
	
	// Twitter Overlay is special, load separately (content loads when it is selected)
	$('a[rel="#twitter"]').overlay({
		effect: 'apple',
		mask: '#CCC',
		top: '5%',
		onLoad: function() {
			// Get twiiter feed
			GetTwitterFeed();
		}
	});

	// Setup the hover for each section
	SetupSiteHover("whoWeAre");
	SetupSiteHover("message");
	SetupSiteHover("music");
	SetupSiteHover("media");
	SetupSiteHover("visit");
	
	// Setup Main scrolling 
	SetupMainScrolling("music");
	SetupMainScrolling("message");
	SetupMainScrolling("visit");
	
	// Setup cycles (cycle through ministers, musicians, etc)
	SetupCycle("messageMinister");
	SetupCycle("messageThisWeek");

	// Setup Music bio so that the last page has scoller
	$('#musicBioCycle').cycle({
	    fx:     'fade',
	    speed:  'fast',
	    timeout: 0,
	    next:   '#musicBioNext',
	    prev:   '#musicBioPrevious',
		after: AddScrollbarToBandMembers
	});
		
	// Next/Previous
	SetupTieredNavs();
	$("#homeImage").css("opacity",1);
	
	// Setup Media Page Scrollable
	SetupMediaScroller();
	
	// Check if form was submitted
	if (GetURLParameter("p") == 'thankyou') {
		alert("Thank you for contacting us! We'll get back to you ASAP!");
	}
	
	// Contact form - hide the 'interest in' drop down
	$("#interestInLabel").hide();
	$("#interestIn").hide();
	/* On change of the dropdown on contact page, show/hide fields */
	$("#whatBringsYouHere").change(function() {
		if($(this + "option:selected").val() == 'Interest In Joining A Creative Team') {
			$("#interestInLabel").show();
			$("#interestIn").show();
		} else {
			$("#interestInLabel").hide();
			$("#interestIn").hide();
		}
	});
});

/* Sets up the overlay (modal dialog) for each section that doesn't require special reqs */
function SetupOverlay(item) {
	$('a[rel="#'+item+'"]').overlay({
		effect: 'apple', 
		mask: '#CCC',
		top: '5%'
	});
}

/* Sets up the hover div on the main image to reveal the spotlight image on hover (and hover text) */
function SetupSiteHover(item) {
	$("#"+item+"Image").css("opacity",0).fadeTo(200,0);
	$("#"+item+"Hover").hover(function() {
		$("#"+item+"Image").fadeTo(300,1);
		$("#"+item+"Link").addClass("imageHoverText");
		if (item != "media") {
			// only hide the media hover if media is not the item being passed
			// want the slide to always show
			$("#mediaHover img").fadeTo(200,0);
		}
	}, function() {
		$("#"+item+"Image").fadeTo(300,0);
		$("#"+item+"Link").removeClass("imageHoverText");
		if (item != "media") {
			// only hide the media hover if media is not the item being passed
			// want the slide to always show
			$("#mediaHover img").fadeTo(300,1);
		}
	});	
}

/* Retrieves and formats the JSON string returned from twitter for the bridge wcc account */
function GetTwitterFeed() {
	$.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=thebridgewcc&count=10&callback=?",
		function(data){
			$("#twitterFeed").html('');
			$.each(data, function(i,item){
				ct = item.text;
				ct = ct.replace(/http:\/\/\S+/g,'<a href="$&" target="_blank">$&</a>');
				ct = ct.replace(/\s(@)(\w+)/g,'@<a onclick="javascript:pageTracker._trackPageview("/outgoing/twitter.com/");" href="http://twitter.com/$2" target="_blank">$2</a>');
				ct = ct.replace(/\s(#)(\w+)/g,'#<a onclick="javascript:pageTracker._trackPageview("/outgoing/search.twitter.com/search?q=%23");" href="http://search.twitter.com/search?q=%23$2" target="_blank">$2</a>');
				
				// Conver time so its readable
				time = item.created_at;

				// date at this point is correct. On parse, it was set to the time zone on the browser
				var date = new Date(Date.parse(time));
				
				// get the hour and minute from the feed //
				var hour = date.getHours();
				var minute = date.getMinutes();
								
				// convert to AM or PM //
				var ampm = hour<12 ? ' AM' : ' PM';
				if (hour>12) hour-= 12;
				if (hour==0) hour = 12;
				
				// return the formatted string //
				date = date.toLocaleString().substr(0, 16);
				var minuteTime = minute.toString();
				if (minute < 10) {
					// put 0 in front of minute
					minuteTime = "0" + minute;
				}
				var finalDate = date.substr(0, 11) + " - " + hour + ":" + minuteTime + ampm + ": ";
				
				$("#twitterFeed").append('<div class="twitterPost"><p><span class="twitterDate">' + finalDate + '</span>'+ ct +'</p></div>');
			});
			// Add scrollbar if necessary
			$("#twitterFeed").scrollbar();
		}
	);
}

/* This setups up the vertical scrolling menus on overlays/dialogs */
function SetupMainScrolling(item) {
	// main vertical scroll
	$("#"+item+"Main").scrollable({
		// basic settings
		vertical: true,
		// up/down keys will always control this scrollable
		keyboard: 'static',
	// main navigator (thumbnail images)
	}).navigator("#"+item+"MainNavi");
}

/* This sets up the cycle used on the projector and bios */
function SetupCycle(item) {
	$('#'+item+'Cycle').cycle({
	    fx:     'fade',
	    speed:  'fast',
	    timeout: 0,
	    next:   '#'+item+'Next',
	    prev:   '#'+item+'Previous'
	});	
}

function SetupMediaScroller() {
	/* Setup the scrollable on the bottom (bar of selectable images) */
	$('#mediaScroller').scrollable();

	/* Setup the images 'click' action */
	$(".items img").click(function() {
		// see if same thumb is being clicked
		if ($(this).hasClass("active")) { return; }

		// get handle to element that wraps the image and make it semi-transparent
		var wrap = $("#image_wrap");

		// change the image
		var url = $(this).attr("src")
		// Sencha is a service that takes your image, caches it, then
		// serves it back to you in the size you need. It speeds things up by
		// caching the image
		var sencha_full_url = url.substring(url.indexOf("http://",2),url.length);
		sencha_full_url = "http://src.sencha.io/677/" + sencha_full_url;
		wrap.find("img").attr("src", sencha_full_url);

		// activate item
		$(".items img").removeClass("active");
		$(this).addClass("active");

	// when page loads simulate a "click" on the first image
	}).filter(":first").click();
}

function SetupTieredNavs() {
	// Setup Tiered Navs
	$(".firstTierNavRight, .secondTierNavRight").hover(function () {
	    $(this).animate({
		    left: '+=10'
		  }, 100, function() {});
	}, function () {
	    $(this).animate({
		    left: '-=10'
		  }, 100, function() {});
	});

	// Setup previous class so it moves out
	$(".firstTierNavLeft, .secondTierNavLeft").hover(function () {
	    $(this).animate({
		    left: '-=10'
		  }, 100, function() {});
	}, function () {
	    $(this).animate({
		    left: '+=10'
		  }, 100, function() {});
	});
}

function ResetVerticalNavigation(item) {
	// Remove all active from visit's navigation, reset to begin
	$("#"+item+"MainNavi li").removeClass("active");
	$("#"+item+"MainNavi li:eq(0)").addClass("active");
	// Reset the active item of the navigation
	$("#"+item+"Main").scrollable().seekTo(0,1);	
}

function AddScrollbarToBandMembers(currSlideElement, nextSlideElement, options, forwardFlag) {
	// Setup scrollbar on band members section
	// Get only setup the scrollbar on the first time to the overlay
	if(!($(nextSlideElement).find("div.scrollbar-pane").length > 0)) {
		// If the scrollbar doesn't exist and bandMember div is in this bio div, then add scrollbar
		if ($(nextSlideElement).find("#bandMembers").length > 0) {
			$(nextSlideElement).scrollbar();
		}
	}
}

/********************************************************
Form Validation (Contact Form)
*********************************************************/

function ValidateForm() {
	if ($("#firstName").val() == '') {
		alert("Please make sure to enter a first name.")
		return false;
	}
	if ($("#lastName").val() == '') {
		alert("Please make sure to enter a last name.")
		return false;
	}
	if ($("#email").val() == '') {
		alert("Please make sure to enter an email address.")
		return false;
	}
	return true;
}

/********************************************************
Get URL Parameter
*********************************************************/

function GetURLParameter(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/********************************************************
Scripture Popups
*********************************************************/
function OpenScripture (item){
	// Get only setup the scrollbar on the first time to the overlay
	$("#"+item).show();
	// Commenting out scrollbar
	//if(!($("#"+item+" div.scrollbar-pane").length > 0)) {
	//	$("#"+item).scrollbar();
	//}
	$(".scriptureOverlay").show();
}

function CloseScripture() {
	$(".scripturePopup").hide();
	$(".scriptureOverlay").hide();
}
