var lastOpenedEntry = null;
var lastOpenedPanel = null;
var kMode = false;
var flashEnabled = true;
var entry_form = null;
var ajaxFileUpload = null;
if (!subdir) {
	var subdir = "";
}
var timeoutID = null;
var shortURL = null;
var checkForURLShortener = null;

$(document).ready(function(){
	//alert('domready!');		
	hiJackSpecialLinkTypes();
	checkForToolTips();
	
	if($('#connectory').size()) {
		connectorySearchBoxes();
		connectoryAccordian();
		connectoryShowOpportunities();
	
				FB.XFBML.parse();
		
	}
	
	if($('#search_small_form').size()) {
		connectorySearchSmallBoxes();
	}
	
	//apply home page functions
	if($("#swf_replace").size()) {
		if(flashEnabled) {
			$("#footer").hide(0);
			if($('#user_bar').size()) {
				$("#user_bar").animate({"opacity":"0"}, 0, "linear");
			} else if($('#profile').size()) {
				$("#profile").animate({"opacity":"0"}, 0, "linear");
			}
		}
	}
	
	if($('#button_sign-in').size() == 1) {
		hiJackSignInLink();
	} 
	
	if($('#signin_form').size() == 1) {
		hiJackSignInForm();
	}
	
	if($('#button_sign-out').size() == 1) {
		hiJackSignOutLink();
	}
	
	if($("#preferences").size() == 1) {
		hiJackPreferencesForm();
	}
	
	if($("#saved_opportunities").size() == 1) {
		shareEmailFormBoxes();
	}
	
	if($("#invite_form").size() == 1) {
		hiJackInviteForm();
	}
	
	if($("#pledge_form").size() == 1) {
		hiJackPledgeForm();
	}
	
	if($("#contact_form").size() == 1) {
		hiJackContactForm();
	}
	
	if($("#btn_get_a_badge").size() == 1 && $("#btn_get_the_widget").size() == 1) {
		hiJackShareDownloadLinks();
	}
	
	if($("#search_small_form").size() == 1 && $("#btn_get_the_widget").size() == 1) {
		hiJackShareDownloadLinks();
	}
		
	if($("#share_opportunities_form").size() == 1) {
		hiJackSaveOpporunitiesForm();
	}
	
	if (jQuery.browser.msie) {
		if(parseInt(jQuery.browser.version) == 6) {
			$(".sprite_button, button.sprite").mouseover(function(event){
				//$(this).addClass("ie6_hover");
				$(this).css({"background-position" : "bottom left", "cursor" : "pointer"});
					
			});

			$(".sprite_button, button.sprite").mouseout(function(event){
				//$(this).removeClass("ie6_hover");
				$(this).css({"background-position" : "top left", "cursor" : "default"});
			});
		}
	}
	
	$("input#am_employee").click(function() {
		if ($('input#am_employee').is(':checked')) {
			$("p#pledge_employee").show();
		} else {
			$("p#pledge_employee").hide();
		}
	});

pledgePublish();
});

/* GLOBAL */

function isFlashEnabled(e) {
	if(!e.success) {
		//alert(e.success)
		flashEnabled = false;
		$("#footer").show(0);
		if($('#user_bar').size() == 1) {
			$("#user_bar").animate({"opacity":"1"}, 0, "linear");
		} else if($('#profile').size() == 1) {
			$("#profile").animate({"opacity":"1"}, 0, "linear");
		}
	}
}

function hiJackSpecialLinkTypes(parentElement) {
	if(parentElement == undefined) {
		parentElement = 'body';
	}
	
	//links to external sites
	var externals = $(parentElement+' a.external');
	
	externals.click(function(event) {
		event.preventDefault();
		if(kMode) {
			var msg = "I'MMA LET YOU FINISH GOING TO THAT LINK, BUT LIGHTBOX IS THE BEST JAVASCRIPT CODE OF ALL TIME!";
		} else {
			var msg = "You are about to leave the Connect a Million Minds website. Do you wish to continue?";
		}
		createPromptBox(msg, this.href);
	})
	
	//links to show error boxes
	var errors = $(parentElement+' a.error');
	
	errors.click(function(event) {
		event.preventDefault();
		var errors = ["Bad name", "Bad Email", "Bad Zip Code", "Did not agree to terms."];
		createErrorBox(errors);
	})
	
	//links that delete something
	var deleteLinks = $(parentElement+' a.delete_link');
	deleteLinks.click(function(event) {
		event.preventDefault();
		if(kMode) {
			var msg = "I'MMA LET YOU DELETE THAT ITEM, BUT WINDOWS RECYCLE BIN IS THE BEST DELETE OF ALL TIME!";
		} else {
			var msg = "Are you sure you want to delete this item?";
		}
		createPromptBox(msg, this.href);
	})
	
	//links to show post story box
	var postStorylinks = $(parentElement+' a.post_story_link');
	postStorylinks.click(function(event) {
		event.preventDefault();
		if(isLoggedIn) {
			createPostStoryBox();
		} else {
			createSignInForm();
		}

	})

	var shareOpplinks = $(parentElement+' a.share_opp');
	shareOpplinks.click(function(event) {
		event.preventDefault();
		createShareOppBox(this.href);
	})
	
	//links to display the href into a modal box
	var lightBoxLinks = $(parentElement+' a.href_modal_link');
	lightBoxLinks.click(function(event) {
		event.preventDefault();
		createHREFLightBox(this.href);
	})
		
	//links to display general lightbox
	var lightBoxLinks = $(parentElement+' a.lightbox_link');
	lightBoxLinks.click(function(event) {
		event.preventDefault();
		createHiJackLightBox(this);
	})
	
	//link to display send to a friend box
	var sendToFriendLinks = $(parentElement+' a.send_to_friend_link');
	sendToFriendLinks.click(function(event) {
		event.preventDefault();
		createSendToFriendBox(this.href);
	})

	var badgeDownloadLinks = $(parentElement+' a.badge_download_link');
	
	badgeDownloadLinks.click(function(event) {
		event.preventDefault();
		$("body").append('<div id="lightbox_wrapper" class="lightbox"></div>');
		$("#lightbox_wrapper").append('<div id="get_badges_box"></div>');
		
		//set HTML for the sign in box
		$("#get_badges_box").load(this.href, null, function() {
			//siteOverlay();	
			showLightBox($("#get_badges_box"));
		});
		
		//omniture
		if(s != undefined) {
			s.eVar5 = "get badges";
			trackLinkClick("event6");
		}

	});
	
	var widgetDownloadLinks = $(parentElement+' a.widget_download_link');
	widgetDownloadLinks.click(function(event) {
		event.preventDefault();
		$("body").append('<div id="lightbox_wrapper" class="lightbox"></div>');
		$("#lightbox_wrapper").append('<div id="get_widgets_box"></div>');
		
		//set HTML for the sign in box
		$("#get_widgets_box").load(this.href, null, function() {
			//siteOverlay();
			//hijack the embed code to select all onfocus
			$(".embed_code_box").focus(function(event){
				$(this).select();
			})
			
			$(".embed_code_box").click(function(event){
				//event.preventDefault();
				$(this).focus();
				$(this).select();
			})
			
			$(".embed_code_box").bind('cut copy paste', function(e) {
				//alert(e.type + ' text!');
				if(e.type == "copy" || e.type == "cut") {
					trackLinkClick("event7");
				}
			});

			showLightBox($("#get_widgets_box"));
		});

		//omniture
		if(s != undefined) {
			s.eVar5 = "get widgets";
			trackLinkClick("event6");
		}
		
	});
	
	//share links
	var shareLinks = $(parentElement+' a.share_link');
	shareLinks.click(function(event) {
		event.preventDefault();
		var service = $(this).attr("id");
		if(service == "favorites" || service == "bookmark") {
			//bookMarkLink(this);
		} else {
			shareURL(service, this.href, "Connect a Million Minds: Take The Pledge!");
		}
	})
	
	//all bookmark links, apply jFav to it
	var shareLinks = $(parentElement+' a.bookmark_link');
	shareLinks.jFav();
}

function bookMarkLink(url) {
	//alert("hello")
	$(url).jFav();
}

function checkForToolTips(parentElement) {
	//alert("checkForToolTips");
	if(parentElement == undefined) {
		parentElement = 'body';
	}
	if($(parentElement+' .tooltip').size() > 0) {
		//alert("there are tooltip buttons on page!")
		$(parentElement+' .tooltip').each(function(idx, item) {
			$(item).click(function(event){
				event.preventDefault();
			})
			addToolTip(item);
		});
	}
}

function thisMovie(movieName) {
     if (navigator.appName.indexOf("Microsoft") != -1) {
         return window[movieName];
     } else {
         return document[movieName];
     }
}

function startTimeOut(msg, timeoutlength) {
	//alert("startTimeOut");
	timeoutID = setTimeout("showTimeOutError('"+msg+"')", timeoutlength);
}

function endTimeOut() {
	clearTimeout(timeoutID);
}

function showTimeOutError(msg) {
	//alert("showTimeOutError");
	endTimeOut();
	var msg = msg;
	$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
		$("#loading_wrapper").remove();
		msg = new Array(msg);
		createErrorBox(msg, false)
	});
}

/* LIGHTBOX FUNCTIONS */
function siteOverlay(hasCloseButton) {
	//alert("siteOverlay "+hasCloseButton)
	hasCloseButton = typeof(hasCloseButton) != 'undefined' ? hasCloseButton : true;
	//remove overlay on click
	if(hasCloseButton) {
		$(".overlay").click(function(event){
			event.preventDefault();
			closeLightBox(event);
		});	
		$(".overlay").css("cursor","pointer");
	}
	
	if($('.overlay').size() > 0) {
		return false;
	}
	
	$("body").append('<div class="overlay"></div>');
	if(hasCloseButton) {
		$(".overlay").click(function(event){
			event.preventDefault();
			closeLightBox(event);
		});
		
		$(".overlay").css("cursor","pointer");	
	}
	
	if (jQuery.browser.msie) {
		if(parseInt(jQuery.browser.version) == 6) {
			//alert("overlay height: "+$("body").height())
			$(".overlay").css({
				"position":"absolute"//,
				// "height":$("wrapper").height()
			})
						
			$("#wrapper select[class!=hide][class!=hidden]").css({
				"display":"none"
			})
			
		}	
	} 
	$(".overlay").animate({"opacity":"0.7"}, 200, "linear");

}

function showLightBox(innerBox, hideAll, hasCloseButton) {
	//alert("showLightBox")
	
	hideAll = typeof(hideAll) != 'undefined' ? hideAll : true;
	hasCloseButton = typeof(hasCloseButton) != 'undefined' ? hasCloseButton : true;
	var box = innerBox.parent();
	//alert(box.attr("id"))
	if(hasCloseButton) {
		box.append('<a id="btn_close_lightbox" class="btn_close sprite_button" href="#">Close</a>')
	}
	//set the css for positioning to center on screen
	var boxWidth = box.width();
	var boxHeight = box.height();
	var windowHeight = $(window).height();
	
	//clip off lightbox if it's too tall still
	if(boxHeight > windowHeight) {
		boxHeight = windowHeight - 200;
	}
	
	// if (innerBox.attr("id") == "href_modal_box") {
	// 	innerBox.css({"min-width":"425px"});
	// 	innerBox.css({"width":"auto !important"});
	// 	innerBox.css({"width":"425px"});
	// }
	
	//set close button(s)
	if(hasCloseButton) {	
		$(".btn_close").click(function(event){
			closeLightBox(event, hideAll);
		});

		// Escape closes lightbox
		$(document).keydown(function (event) {
			if (event.keyCode == '27')  {
				event.preventDefault();
				window.location = '#all';
				closeLightBox(event, hideAll);
			}
		});
/*
		$(".btn_close").click(function(event){
			closeLightBox(event, hideAll);
		});*/
		
		//get width and height of close button
		var closeBtnWidth = $("#btn_close_lightbox").width();
		var closeBtnHeight = $("#btn_close_lightbox").width();
		//move the inner box down and right to shift for close button
		innerBox.css({
				"margin-top": closeBtnHeight/2,
				"margin-left":closeBtnWidth/2
			})
	} else {
		var closeBtnWidth = 0;
		var closeBtnHeight = 0;
	}
		
	//for IE6
	if (jQuery.browser.msie) {
		if(parseInt(jQuery.browser.version) == 6) {
			
			$(".sprite_button, button.sprite").mouseover(function(event){
				//$(this).addClass("ie6_hover");
				$(this).css({"background-position" : "bottom left", "cursor" : "pointer"});
					
			});

			$(".sprite_button, button.sprite").mouseout(function(event){
				//$(this).removeClass("ie6_hover");
				$(this).css({"background-position" : "top left", "cursor" : "default"});
			});
			
			box.css({
					"position": "absolute"
			})
			pngfix();
			move_box();
			scrollInterval = window.setInterval("move_box()", 100);
		} else {
			box.css({
					"width": boxWidth,
					"height": boxHeight,
					"margin-top": -(boxHeight/2)-20,
					"margin-left":-(boxWidth/2)-(closeBtnWidth/4) //to position it in the middle (using offset for closebutton)
			})
		}
	} else {
		box.css({
				"width": boxWidth,
				"height": boxHeight,
				"margin-top": -(boxHeight/2)-50,
				"margin-left":-(boxWidth/2)-(closeBtnWidth/4) //to position it in the middle (using offset for closebutton)
		})
	}
	
	//fade form in
	siteOverlay(hasCloseButton);
	box.animate({"opacity":"1"}, 200, "linear");
	
	if($("#swf_replace").size() == 1) {
		thisMovie("swf_replace").deactivateFlash();
	}
	
	if($("#discuss").size() == 1) {
		thisMovie("discuss").deactivateFlash();
	}
}

function closeLightBox(event, hideAll) {
	//alert("closeLightbox")
	if(event != undefined) {
		if(event.preventDefault() != undefined) {
			event.preventDefault();
		}
	}

	hideAll = typeof(hideAll) != 'undefined' ? hideAll : true;
	//hide all boxes with class of lightbox and the overlay
	if(hideAll) {
		$(".lightbox").animate({"opacity":"0"}, 200, "linear");
		$(".overlay").animate({"opacity":"0"}, 200, "linear", function(){
			$(".overlay").remove();
			$(".lightbox").remove();

			//for IE6 to kill scroll interval for lightbox overlay div
			if (jQuery.browser.msie) {
				if(parseInt(jQuery.browser.version) == 6) {
					//alert("i am IE6 and closing the lightbox")
					$("#wrapper select[class!=hide][class!=hidden]").css({
						"display":"block"
					})
					
					clearInterval(scrollInterval)
					//alert(scrollInterval);
				}				
			}

			if($("#swf_replace").size() == 1) {
				thisMovie("swf_replace").activateFlash();
			}
			
			if($("#discuss").size() == 1) {
				thisMovie("discuss").activateFlash();
			}
		
		});
	} else {
		//will fade and remove only itself
		//drill back up to the first parent div with the class of 'lightbox'
		var currentLightBox = $(event.target).parents('.lightbox');
		currentLightBox.animate({"opacity":"0"}, 200, "linear", function(){
			currentLightBox.remove();
			//bring back any other boxes with lightbox class
			$(".lightbox").animate({"opacity":"1"}, 200, "linear", function() {
				//re-enable any submit buttons after fade in
				var submitButton = $(".lightbox button[type='submit']")
				submitButton.attr("disabled","");
				if (jQuery.browser.msie) {
					if(parseInt(jQuery.browser.version) == 6) {
						$(".lightbox select").each(function(idx,item){
							$(item).removeClass("hide");
						})
					}
				}
				
			});
		});
		
	}
}

function createPromptBox(msg, url) {
	$("body").append('<div id="promptBox_wrapper" class="lightbox"></div>');

	var html = '<div id="externalLink_box" class="acct_lightbox">';
	html += '<div class="lightbox_inner">';
	html += '<h2 id="title_attention">Attention</h2>'
	html += '<p class="message">'+msg+'</p>';
	html += '<div class="modal_buttons">';
	html += '<p><a id="btn_no" class="sprite_button" href="#">No</a></p>';
	html += '<p><a id="btn_ok" class="sprite_button" href="'+url+'">OK</a></p>';
	// html +=	'<div class="clear"></div>';
	html += '</div>';
	html += '</div>';
	html += '</div>';
	$("#promptBox_wrapper").append(html);
	
	$("#btn_no").click(function(event) {
		closeLightBox(event);
	})
	//siteOverlay();
	showLightBox($("#externalLink_box"));
}

function createErrorBox(errors, hideAll) {
	hideAll = typeof(hideAll) != 'undefined' ? hideAll : true;
	
	var html = "<h2 id=\"title_error\">Oops!</h2>";
	html += "<p>We’ve found an issue with your entry:</p>";
	if(typeof(errors) == "object") {
		var totalErrors = errors.length;
		html += "<ul>";
		for(var i=0;i<totalErrors;i++) {
			html+="<li>"+errors[i]+"</li>";
		}
		html += "</ul>";
	} else {
		html += errors;
	}
	
	html += '<p><a id="btn_return_to_form" type="submit" class="btn_close sprite_button" href="#">Return To Form</a></p>';
	
	$("body").append('<div id="error_wrapper" class="lightbox"></div>');
	$("#error_wrapper").append('<div id="error_msg_box" class="acct_lightbox"></div>');
	$("#error_msg_box").append('<div class="lightbox_inner">'+html+'</div>');
	//siteOverlay();
	
	//put mouse focus on the return to form button.
	$('#btn_return_to_form').focus();
	
	showLightBox($("#error_msg_box"), hideAll);	
} 

function createSuccessLightBox(html) {
	//alert("createSuccessLightBox")
	var boxTitle = "<h2 id=\"title_success\">Thank You!</h2>";
	var returnToPage = '<p><a id="btn_return_to_page" type="submit" class="btn_close sprite_button" href="#">Return To Page</a></p>';
	
	$("body").append('<div id="generic_wrapper" class="lightbox"></div>');
	$("#generic_wrapper").append('<div id="generic_box" class="acct_lightbox"></div>');
	$("#generic_box").append('<div class="lightbox_inner">'+boxTitle+html+returnToPage+'</div>');
	//siteOverlay();
	
	//put mouse focus on the return to form button.
	$('#btn_return_to_form').focus();
	
	showLightBox($("#generic_box"));
}

function createGenericLightBox(html) {
	//alert("createGenericLightBox")
	$("body").append('<div id="generic_wrapper" class="lightbox"></div>');
	$("#generic_wrapper").append('<div id="generic_box" class="acct_lightbox"></div>');
	$("#generic_box").append('<div class="lightbox_inner">'+html+'</div>');
	//siteOverlay();
	showLightBox($("#generic_box"));
}

function createTermsLightBox() {
	//alert("createGenericLightBox")
	showLoadingBox("<p>Loading Terms</p>");
	
	var boxTitle = "<h2 id=\"title_terms_conditions\">Policies and Terms of Use</h2>";
	var returnToPage = '<p><a id="btn_return_to_page" type="submit" class="btn_close sprite_button" href="#">Return To Page</a></p>';

	
	$("body").append('<div id="generic_wrapper" class="lightbox"></div>');
	$("#generic_wrapper").append('<div id="generic_box" class="acct_lightbox"></div>');
	$("#generic_box").append('<div class="lightbox_inner">'+boxTitle+'</div>');
	$("#generic_box div").append('<div id="scrollBox"></div>');
	$("#generic_box div").append(returnToPage);
	$("#generic_box").css("width","400px");
	
	$("#scrollBox").load('/_includes/terms_conditions.php', null, function() {
		// $("#scrollBox").css("border","1px solid #cecabc");
		// $("#scrollBox").css("background-color","#fff");
		// $("#scrollBox").css("padding","10px");
		// $("#scrollBox").css("height","225px");
		// $("#scrollBox").css("overflow","auto");
		$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
			$("#loading_wrapper").remove();
			//fade back in the form box and re-enabled the submit button after fade in
			showLightBox($("#generic_box"));
		});
		
	});
	
}

function createThankYouLightBox() {
	//alert("createThankYouLightBox")
	
	var boxTitle = "<h2 id=\"title_thank_you_pledge\">Thank you for pledging!</h2>";
	var html = '<p>Now taking you to <em>The Connectory...</em></p>';
	
	$("body").append('<div id="loading_wrapper" class="lightbox"></div>');
	$("#loading_wrapper").append('<div id="loading_box" class="acct_lightbox"></div>');
	$("#loading_box").append('<div class="lightbox_inner">'+boxTitle+html+'</div>');
	//siteOverlay();
	$("#loading_box").css("text-align","left");
	$("#loading_box").css("width","250px");
	showLightBox($("#loading_box"), false, false);
}

function showLoadingBox(msg) {
	//alert("showLoadingBox");
	// var html = '<div class="loading_wrapper">';
	var html = '<img src="/_media/ajax-loader.gif" alt="loading bar" class="loading_image" />';
	html += '<h3>'+msg+'</h3>';
	// html += '</div>';
	
	$("body").append('<div id="loading_wrapper" class="lightbox"></div>');
	$("#loading_wrapper").append('<div id="loading_box" class="acct_lightbox"></div>');
	$("#loading_box").append('<div class="lightbox_inner">'+html+'</div>');
	
	var innerBox = $("#loading_box");
	var box = innerBox.parent();//$('#lightbox_wrapper');

	//set the css for positioning to center on screen
	var boxWidth = box.width();
	var boxHeight = box.height();
	var windowHeight = $(window).height();
	
	//clip off lightbox if it's too tall still
	if(boxHeight > windowHeight) {
		boxHeight = windowHeight - 200;
	}
	
	//for IE6
	if (jQuery.browser.msie) {
		if(parseInt(jQuery.browser.version) == 6) {
			box.css({
					"position": "absolute"
			})
			pngfix();
			move_box();
			scrollInterval = window.setInterval("move_box()", 100);
		} else {
			box.css({
					"width": boxWidth,
					"height": boxHeight,
					"margin-top": -(boxHeight/2)-50,
					"margin-left":-(boxWidth/2) //to position it in the middle (using offset for closebutton)
			})
		}
	} else {
		box.css({
				"width": boxWidth,
				"height": boxHeight,
				"margin-top": -(boxHeight/2)-50,
				"margin-left":-(boxWidth/2) //to position it in the middle (using offset for closebutton)
		})
	}
	
	if($("#swf_replace").size() == 1) {
		thisMovie("swf_replace").deactivateFlash();
	}
	
	if($("#discuss").size() == 1) {
		thisMovie("discuss").deactivateFlash();
	}

	siteOverlay(false);
	//fade form in
	box.animate({"opacity":"1"}, 200, "linear");
	
}

//this takes certain content from the HTML and displays it inside an lightbox
function createHiJackLightBox(item) {
	var jQueryItem = $(item);
	//get its id and remove "lightbox_" prefix from it
	var id = jQueryItem.attr("id").substring(9);
	//find any element that has the same id but with lightbox_content_ prefix to use as the lightbox content
	var lightBoxContent = $('#lightbox_content_'+id);
	if(lightBoxContent.size() == 1) {
		var html = lightBoxContent.html();
	} else {
		var html = "<p>There is no content available.</p>";
	}
	createGenericLightBox(html);
}

function createHREFLightBox(url) {
	//url = typeof(url) != 'undefined' ? url : "http://www.connectamillionminds.com";
	showLoadingBox("Loading content...");
	$("body").append('<div id="generic_wrapper" class="lightbox"></div>');
	$("#generic_wrapper").append('<div id="href_modal_box" class="acct_lightbox"></div>');
	$("#href_modal_box").load(url, null, function() {
		$("#loading_wrapper").animate({"opacity":"1"}, 200, "linear", function() {
			$("#loading_wrapper").remove();
		});
		//alert("loaded!");
		showLightBox($("#href_modal_box"));
		HREFcallback();
	});	
}


function createSendToFriendBox(url) {
	url = typeof(url) != 'undefined' ? url : "http://www.connectamillionminds.com";
	$("body").append('<div id="send_to_friend_wrapper" class="lightbox"></div>');
	$("#send_to_friend_wrapper").load("/send_to_friend.php", null, function() {
		$("#send_to_friend_form fieldset:first").append('<p><a id="btn_cancel" type="submit" class="btn_close sprite_button" href="#">Cancel</a></p>');
		$("#send_to_friend_form").append('<input id="url" name="url" type="hidden" value="'+url+'" />');
		$("#send_to_friend_form").append('<input id="isModal" name="isModal" type="hidden" value="true" />');
		$("#send_to_friend_form").append('<input id="action" name="action" type="hidden" value="invite" />');
		checkForToolTips("#send_to_friend");
		
		shareEmailFormBoxes();
		hiJackSendToFriendForm();
		showLightBox($("#send_to_friend"));
	});
}

function hiJackSendToFriendForm() {
	$("#send_to_friend_form").submit(function(event){
		
		event.preventDefault();
		//alert("submitted!");
		//disable submit button
		
		var form = $(this);
		
		//disable submit button
		var submitButton = $("#send_to_friend_form button[type='submit']")
		submitButton.attr("disabled","disabled");
		
		//fade out form
		$("#send_to_friend_wrapper").animate({"opacity":"0"}, 200, "linear");
		
		if(form.attr("errors") != undefined) {
			if(form.attr("errors").length > 0) {
				// $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
				// 	$("#loading_wrapper").remove();
				// 	//createErrorBox(errors, false);
				// });
				return false;
			}
		}
		
		//fade out box
		$("#send_to_friend_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
			showLoadingBox("Sending message. Please wait...");
			//grab the url from the action attribute
			var action_url = $("#send_to_friend_form").attr("action");
			//alert("action url: "+action_url);
			$.ajax({
			   	type: "POST",
			   	url: action_url,
			   	data: $("#send_to_friend_form").serialize(),
				dataType: "json",
			   	success: function(json){
			    	//alert( "Data Saved: " + msg );
					//remove send to friend box
					if(json.success == "true") {
						$("#send_to_friend_wrapper").remove();
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							//fade back in the form box and re-enabled the submit button after fade in
							var msg = json.message;
							createSuccessLightBox("<p>"+msg+"</p>");

						});
						
					} else {
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							var msg = new Array(json.message);
							createErrorBox(msg, false)
						});
					}
					
					//omniture
					if(s != undefined) {
						s.eVar5 = "send email to friend";
						trackLinkClick("event6");
					}
				},
				error: function(json) {
					//alert('error!');
					//fade out the loading box and remove it after fade out
					$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
						$("#loading_wrapper").remove();
						var msg = new Array("There was a problem connecting to the server. Please try again.");
						createErrorBox(msg, false)
					});
				}
			});
		});
	});
}

function createShareOppBox(url) {
	url = typeof(url) != 'undefined' ? url : "http://www.connectamillionminds.com";
	$("body").append('<div id="send_to_friend_wrapper" class="lightbox"></div>');

	$("#send_to_friend_wrapper").load("/share_opportunity.php", null, function() {
		$("#send_to_friend_form").append('<p><a id="btn_cancel" type="submit" class="btn_close sprite_button" href="#">Cancel</a></p>');
		$("#send_to_friend_form").append('<input id="url" name="url" type="hidden" value="'+url+'" />');
		$("#send_to_friend_form").append('<input id="isModal" name="isModal" type="hidden" value="true" />');
		$("#send_to_friend_form").append('<input id="isAjax" name="isAjax" type="hidden" value="true" />');	
		$("#send_to_friend_form").append('<input id="invite" name="action" type="hidden" value="invite" />');	
		
		shareEmailFormBoxes();
		checkForToolTips("#send_to_friend");
		hiJackShareOppForm();
		showLightBox($("#send_to_friend"));
	});
}

function hiJackShareOppForm() {
	$("#send_to_friend_form").submit(function(event){
		event.preventDefault();
		//alert("submitted!");
		
		var form = $(this);
		$("#send_to_friend_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
			//showLoadingBox("Sending message. Please wait...");
		});
		
		
		if(form.attr("errors") != undefined) {
			if(form.attr("errors").length > 0) {
				// $("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
				// 	$("#loading_wrapper").remove();
				// 	//createErrorBox(errors, false);
				// });
				return false;
			}
		}

		//disable submit button
		var submitButton = $("#send_to_friend_form button[type='submit']")
		submitButton.attr("disabled","disabled");
		//fade out box
		$("#send_to_friend_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
			showLoadingBox("Sending message. Please wait...");
			//grab the url from the action attribute
			var action_url = $("#send_to_friend_form").attr("action");
			$.ajax({
			   	type: "POST",
			   	url: action_url,
			   	data: $("#send_to_friend_form").serialize(),
				dataType: "json",
			   	success: function(json){
			    	//alert( "Data Saved: " + json );
					//remove send opp box
					if(json.success == "true") {
						$("#send_to_friend_wrapper").remove();
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							//fade back in the form box and re-enabled the submit button after fade in
							var msg = json.message;
							createSuccessLightBox("<p>"+msg+"</p>");

						});
						
					} else {
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							var msg = new Array(json.message);
							createErrorBox(msg, false)
						});
					}
				},
				error: function(msg) {
					//alert('error!');
					//fade out the loading box and remove it after fade out
					$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
						$("#loading_wrapper").remove();
						var msg = new Array("There was a problem connecting to the server. Please try again.");
						createErrorBox(msg, false)
					});
				}
			});
		});
	});
}

/* HOME PAGE */
function introComplete() {
	//alert("introComplete");
	$("#footer").slideToggle(500);
	if($("#user_bar").size() == 1) {
		$("#user_bar").animate({"opacity":"1"}, 500, "linear");
	} else if($('#profile').size() == 1) {
		$("#profile").animate({"opacity":"1"}, 500, "linear");
	}
}

/* SIGN IN */
function hiJackSignInLink() {
	var sign_in = $('#button_sign-in');
	
	sign_in.click(function(event) {
		event.preventDefault();
		//siteOverlay();
		createSignInForm();
	})
}

function createSignInForm() {
	$("body").append('<div id="lightbox_wrapper" class="lightbox"></div>');
	$("#lightbox_wrapper").append('<div id="signin_box" class="acct_lightbox"></div>');
	//set HTML for the sign in box via Ajax call
	$("#signin_box").load("/form_login.php", null, function() {
		//add special ajax hidden input in the form
		var isAjax = '<input id="isAjax" name="isAjax" type="hidden" value="true" />';
		$('#signin_form > fieldset:first').prepend(isAjax);

		hiJackSignInForm();
		hiJackLostPasswordLink();
		signInFormBoxes();
		
		showLightBox($("#signin_box"));
		
		$('button.sign_in').click(function (){
			form = $('#signin_form')[0];
			form.fb_id.value = '';
		});
	});
}

function hiJackSignInForm() {
	$('#signin_form').submit(function(event){
		event.preventDefault();
		signInAjax();
	})
	$('a#button_facebook_login').click(function () {
		facebookLogin(loginCallback); 
	});
}

function signInAjax() {
	var submitButton = $("#signin_form button[type='submit']")
	submitButton.attr("disabled", "disabled");
	
	if($("#isAjax").size() > 0) {
		//fade out box
		$("#lightbox_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
			showLoadingBox("Signing in. Please wait...");
			//grab the url from the action attribute
			var action_url = $("#signin_form").attr("action");
			//var action_url = "test_login.php";
			$.ajax({
			   	type: "POST",
			   	url: action_url,
			   	data: $("#signin_form").serialize(),
				dataType: "json",
			   	success: function(json){
			    	//alert( "Data Saved: " + json.success );
					if(json.success == "true") {
						//remove sign in box
						$("#lightbox_wrapper").remove();
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							
							if (window.location.href = '#share-pledge') { // Prevent pledge sharing for re-opening
								window.location = window.location.protocol+'//'+window.location.hostname+window.location.pathname+window.location.search;
							} else {
								window.location.reload();
							}
						});
					} else {
						//alert('error!');
						//fade out the loading box and remove it after fade out
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							var msg = new Array(json.message);
							createErrorBox(msg, false);
						});
					}
				},
				error: function(msg) {
					//alert('error!');
					//fade out the loading box and remove it after fade out
					$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
						$("#loading_wrapper").remove();
						var msg = new Array("There was a problem connecting to the server. Please try again.");
						createErrorBox(msg, false);
					});
				}
			});
		});
	} else {
		//if normal form
		showLoadingBox("Signing in. Please wait...");
		//grab the url from the action attribute
		var action_url = $("#signin_form").attr("action");
		
		$.ajax({
		   	type: "POST",
		   	url: action_url,
		   	data: $("#signin_form").serialize(),
			dataType: "json",
		   	success: function(json){
		    	//alert( "Data Saved: " + json.success );
				if(json.success == "true") {
					$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
						$("#loading_wrapper").remove();
						window.location = subdir+"/connectory.php";
					});
				} else {
					//alert('error!');
					//fade out the loading box and remove it after fade out
					$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
						$("#loading_wrapper").remove();
						var msg = new Array(json.message);
						createErrorBox(msg, true);
						var submitButton = $("#signin_form button[type='submit']")
						submitButton.attr("disabled","");
					});
				}
			},
			error: function(msg) {
				//alert('error!');
				//fade out the loading box and remove it after fade out
				$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
					$("#loading_wrapper").remove();
					var msg = new Array("There was a problem connecting to the server. Please try again.");
					createErrorBox(msg, true);
					var submitButton = $("#signin_form button[type='submit']")
					submitButton.attr("disabled","");
				});
			}
		});
	}

	
	return false;
}

function signInFormBoxes() {
	var zipLabel = "Email";
	var keywordLabel = "Password";
	
	var zipInput = $("input[name='email']");
	zipInput.val(zipLabel);
	
	zipInput.focus(function() {
		if(this.value == zipLabel) {
			this.value = "";
		}
	});
	
	zipInput.blur(function() {
		if(this.value == "") {
			this.value = zipLabel;
		}
	});
	
	var keywordsInput = $("#signin_box input[name='password']:first");
	//alert(keywordsInput.attr("type"))
	// rename element to simple HTML element (non jQuery so I can change the type to text)
	// not working using the jQuery attr() method;
	if(keywordsInput.size() > 0) {
		var newkeywordsInput = keywordsInput[0];
		//ie browser die when you try to change an
		//input from password to text
		if (!jQuery.browser.msie) {
			newkeywordsInput.type = "text";
			newkeywordsInput.value = keywordLabel;
		}
	}
	
	//reselect element as jQuery object to apply focus and blurs
	keywordsInput = $("#signin_box input[name='password']:first");
	//keywordsInput = keywordsInput[0];
	
	keywordsInput.focus(function() {
		if(this.value == keywordLabel) {
			if (!jQuery.browser.msie) {
				this.value = "";
				this.type = "password";
			}
		}
		//alert(this.type)
	});
	
	keywordsInput.blur(function() {
		//alert(this.type)
		if(this.value == "") {
			if (!jQuery.browser.msie) {
				this.type = "text";
				this.value = keywordLabel;
			}
		}
	});
}

/* SIGN OUT */
function hiJackSignOutLink() {
	var sign_out = $('#button_sign-out');
	
	sign_out.click(function(event) {
		event.preventDefault();
		signOutAjax();
	})
}

function signOutAjax() {
	//siteOverlay();
	showLoadingBox("Signing out. Please wait...");
	//grab the url from the action attribute
	var action_url = "/actions/logout.php";
	//var action_url = "test_login.php";
	$.ajax({
	   	type: "GET",
	   	url: action_url,
		dataType: "json",
	   	success: function(json){
	    	//alert( "Data Saved: " + json.success );
			if(json.success == "true") {
				$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
					$("#loading_wrapper").remove();
					//fade back in the form box and re-enabled the submit button after fade in
					//
							if (window.location.href = '#share-pledge') { // Prevent pledge sharing for re-opening
								window.location = window.location.protocol+'//'+window.location.hostname+window.location.pathname+window.location.search;
							} else {
								window.location.reload();
							}
				});
			} else {
				//alert('error!');
				//fade out the loading box and remove it after fade out
				$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
					$("#loading_wrapper").remove();
					var msg = new Array(json.message);
					createErrorBox(msg, false);
				});
			}
		},
		error: function(msg) {
			//alert('error!');
			//fade out the loading box and remove it after fade out
			$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
				$("#loading_wrapper").remove();
				var msg = new Array("There was a problem connecting to the server.. Please try again.");
				createErrorBox(msg, false);
			});
		}
	});
	
}

/* LOST PASSWORD */
function hiJackLostPasswordLink() {
	var forgot_pass_link = $('#forgot_password_link');
	
	forgot_pass_link.click(function(event) {
		event.preventDefault();
		$("#signin_box").animate({"opacity":"0"}, 200, "linear", function(){
			$(".lightbox").remove();
			createForgotPasswordBox();
		});
	})
}

function createForgotPasswordBox() {
	$("body").append('<div id="lightbox_wrapper" class="lightbox"></div>');
	$("#lightbox_wrapper").append('<div id="forgot_password_box" class="acct_lightbox"></div>');
	//set HTML for the sign in box
	$("#forgot_password_box").load("/form_forgot_password.php", null, function() {
		forgotPassworkFormBoxes();
		hiJackBackToLogin();
		hiJackForgotPasswordForm();
		
		//add special ajax hidden input in the form
		var isAjax = '<input id="isAjax" name="isAjax" type="hidden" value="true" />';
		$('#lost_password_form > fieldset:first').prepend(isAjax);
		
		showLightBox($("#forgot_password_box"));
	});
}

function hiJackForgotPasswordForm() {
	//alert("hiJackForgotPasswordForm")
	
	$('#lost_password_form').submit(function(event){
		event.preventDefault();
				
		var submitButton = $("#lost_password_form button[type='submit']")
		submitButton.attr("disabled","disabled");
		
		//if modal box
		if($("#isAjax").size() > 0) {
			//fade out box
			$("#lightbox_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
				showLoadingBox("Looking up account. Please wait...");
				//grab the url from the action attribute
				var action_url = $("#lost_password_form").attr("action");
				//var action_url = "test_login.php";
				$.ajax({
				   	type: "POST",
				   	url: action_url,
				   	data: $("#lost_password_form").serialize(),
					dataType: "json",
				   	success: function(json){
				    	//alert( "Data Saved: " + json.success );
						if(json.success == "true") {
							//remove forgot password box
							$("#lightbox_wrapper").remove();
							$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
								$("#loading_wrapper").remove();
								createSuccessLightBox("<p>"+json.message+"</p>");
							});
						} else {
							//alert('error!');
							//fade out the loading box and remove it after fade out
							$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
								$("#loading_wrapper").remove();
								var msg = new Array(json.message);
								createErrorBox(msg, false);
							});
						}
					},
					error: function(msg) {
						//alert('error!');
						//fade out the loading box and remove it after fade out
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							var msg = new Array("There was a problem connecting to the server. Please try again.");
							createErrorBox(msg, false);
						});
					}
				});
			});

		} else {
			//if normal form
			showLoadingBox("Looking up account. Please wait...");
			//grab the url from the action attribute
			var action_url = $("#lost_password_form").attr("action");
			
			$.ajax({
			   	type: "POST",
			   	url: action_url,
			   	data: $("#lost_password_form").serialize(),
				dataType: "json",
			   	success: function(json){
			    	//alert( "Data Saved: " + json.success );
					if(json.success == "true") {
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							createSuccessLightBox("<p>"+json.message+"</p>");
						});
					} else {
						//alert('error!');
						//fade out the loading box and remove it after fade out
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							var msg = new Array(json.message);
							createErrorBox(msg, true);
							var submitButton = $("#lost_password_form button[type='submit']")
							submitButton.attr("disabled","");
						});
					}
				},
				error: function(msg) {
					//alert('error!');
					//fade out the loading box and remove it after fade out
					$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
						$("#loading_wrapper").remove();
						var msg = new Array("There was a problem connecting to the server. Please try again.");
						createErrorBox(msg, true);
						var submitButton = $("#lost_password_form button[type='submit']")
						submitButton.attr("disabled","");
					});
				}
			});
		}

	});
}

function forgotPassworkFormBoxes() {
	var label = "E-mail Address";
	
	var input = $("input[name='email']");
	input.val(label);
	
	input.focus(function() {
		if(this.value == label) {
			this.value = "";
		}
	});
	
	input.blur(function() {
		if(this.value == "") {
			this.value = label;
		}
	});
}

function hiJackBackToLogin() {	
	var sign_in = $('#back_to_login');
	
	sign_in.click(function(event) {
		event.preventDefault();
		$("#forgot_password_box").animate({"opacity":"0"}, 200, "linear", function(){
			$(".lightbox").remove();
			createSignInForm();
		});
	})
}

/* PLEDGE */
function hiJackPledgeForm() {
	//apply blur/focus labels
	validateForm("pledge_form");
	
	//return true;
	
	// $("#pledge_form input[type=text]").each(function(idx, item) {
	// 
	// 	var input = $(item);
	// 	var label = input.attr("value");
	// 	//var label = $("label[for="+input.attr("id")+"]").text();
	// 	input.attr("origValue",label);
	// 	
	// 	if(label != "") {
	// 		input.val(label);
	// 
	// 		input.focus(function() {
	// 			if(this.value == label) {
	// 				this.value = "";
	// 			}
	// 		});
	// 
	// 		input.blur(function() {
	// 			if(this.value == "") {
	// 				this.value = label;
	// 			}
	// 		});
	// 	}
	// })
	// 
	// $("#pledge_form").submit(function(){
	// 	//event.preventDefault();
	// 	
	// 	var errors = new Array();
	// 	
	// 	//check if anything is required
	// 	$("#pledge_form input.required").each(function(idx, item){
	// 		if(!isRequired(item)) {
	// 			//alert("I am blank")
	// 			var input = $(item);
	// 			//alert(input.attr("id"))
	// 			var label = $("label[for="+input.attr("id")+"]");
	// 			//alert(label)
	// 			var msg = label.text()+" is required.";
	// 			//alert(msg)
	// 			errors.push(msg);
	// 		};
	// 		
	// 	});
	// 	
	// 	$("#pledge_form input.isNumeric").each(function(idx, item){
	// 		if(!isNumeric(item)) {
	// 			var input = $(item);
	// 			//alert(input.attr("id"))
	// 			var label = $("label[for="+input.attr("id")+"]");
	// 			//alert(label)
	// 			var msg = label.text()+" must be a number.";
	// 			//alert(msg)
	// 			errors.push(msg);
	// 		};
	// 	});
	// 	
	// 	$("#pledge_form input.isAlphabetical").each(function(idx, item){
	// 		if(!isAlphabetical(item)) {
	// 			var input = $(item);
	// 			//alert(input.attr("id"))
	// 			var label = $("label[for="+input.attr("id")+"]");
	// 			//alert(label)
	// 			var msg = label.text()+" can not have any numbers.";
	// 			//alert(msg)
	// 			errors.push(msg);
	// 		};
	// 	});
	// 	
	// 	$("#pledge_form input.email").each(function(idx, item){
	// 		if(!isValidEmail(item)) {
	// 			var input = $(item);
	// 			//alert(input.attr("id"))
	// 			var label = $("label[for="+input.attr("id")+"]");
	// 			//alert(label)
	// 			var msg = label.text()+" is not an valid email format.";
	// 			//alert(msg)
	// 			errors.push(msg);
	// 		};
	// 		
	// 	});
	// 	
	// 	//birth date
	// 	//month
	// 	var month = $("#pledge_form input.isMonthNumber")[0];
	// 	//day
	// 	var day = $("#pledge_form input.isDayNumber")[0];
	// 	//year		
	// 	var year = $("#pledge_form input.isFullYearNumber")[0];
	// 	
	// 	if(month != undefined && day != undefined && year != undefined) {
	// 		if(!isMonthNumber(month) || !isDayNumber(day) || !isFullYearNumber(year)) {
	// 			var msg = "Birthdate is not valid.";
	// 			errors.push(msg);
	// 		} else {
	// 			//check if user is at least age required
	// 			var ageRequired = 13;
	// 			var dateToday = new Date();
	// 			var dob = new Date();
	// 			dob.setFullYear(parseInt($(year).attr("value")), parseInt($(month).attr("value"))-1, parseInt($(day).attr("value")));
	// 			var age = Math.floor((dateToday - dob) / (365.25 * 24 * 60 * 60 * 1000))
	// 			if (age < ageRequired) {
	// 				var msg = "You must be "+ageRequired+" years of age to pledge.";
	// 				errors.push(msg);
	// 			}
	// 		}
	// 	}
	// 			
	// 	$("#pledge_form input.hasAgreed").each(function(idx, item){
	// 		if(!isRequired(item)) {
	// 			var input = $(item);
	// 			//alert(input.attr("id"))
	// 			var label = $("label[for="+input.attr("id")+"]");
	// 			//alert(label)
	// 			var msg = "You must agree with the Terms and Conditions.";
	// 			//alert(msg)
	// 			errors.push(msg);
	// 		};
	// 	});
	// 	
	// 
	// 
	// 	//var errors = new Array("hello","whats","up");
	// 	if(errors.length > 0) {
	// 		createErrorBox(errors);
	// 		return false;
	// 	} else {
	// 		return true;
	// 	}
	// 	return true;
	// });
}

/* CONNECTORY FUNCTIONS */
function connectorySearchBoxes() {
	//sets both zip and keyword boxes to have
	//gray text labels ("Zip" and "Keyword(s)") but removes them when focused
	//and puts them back only if left blank when blurred
	
	var zipLabel = "Zip";
	var keywordLabel = "Keyword(s)";
	
	var zipInput = $('.zip');

	zipInput.each(function(idx,item){
		var item = $(item);
		if(item.val() == "") {
			item.val(zipLabel);
		} 
	})
	//alert(zipInput.val())
	
	zipInput.focus(function() {
		if(this.value == zipLabel) {
			this.value = "";
		}
	});
	
	zipInput.blur(function() {
		if(this.value == "") {
			this.value = zipLabel;
		}
	});
	
	var keywordsInput = $('.keywords');

	keywordsInput.each(function(idx,item){
		var item = $(item);
		if(item.val() == "") {
			item.val(keywordLabel);
		} 
	})
	
	keywordsInput.focus(function() {
		if(this.value == keywordLabel) {
			this.value = "";
		}
	});
	
	keywordsInput.blur(function() {
		if(this.value == "") {
			this.value = keywordLabel;
		}
	});
}

function connectoryAccordian() {
	$('[class^=save_checkbox]').click(function (event) {
		event.stopPropagation();
		var input = $(this);
		var value = $(input).attr("value");
		var isChecked = $(input).attr("checked");
		if(isChecked) {
			//alert("checked!")
			var action = "add";
		} else {
			var action = "delete";
			//alert("unchecked!");
		}
		
		var action_url = "/actions/opportunity.php?id="+value+"&action="+action;
		//alert(action_url)
		$.ajax({
		   	type: "GET",
		   	url: action_url,
			dataType: "json",
		   	success: function(json){
		    	//alert( "Data Saved: " +json.success);
				if(json.success == "true") {
					//alert("saved/unsaved!");
					var panel = input.parent().parent();
					var panelSibling = $("#"+panel.attr("id").replace("entry","more_detail"));
					panel.effect("highlight", {color:"#F3AD13"}, 1000);
					panelSibling.effect("highlight", {color:"#F3AD13"}, 1000);
				} else {
					//alert('not saved!');
					var msg = new Array(json.message);
					createErrorBox(msg, true)
				}
			},
			error: function(msg) {
				//alert('problem contacting server!');
				if(isChecked) {
					input.attr("checked", "");
				} else {
					input.attr("checked", "checked");
				}

				var msg = new Array("There was a problem connecting to the server. Please try again.");
				createErrorBox(msg, true)
			}
		});
	});
	
	//hide all entry details
	if($('[class^=opp_details]').size() == 0) {
		return false;
	} else {
		$('[class^=opp_description]').each(function(idx,item){
			//alert($(item).height())
			if($(item).height() > 115) {
				$(item).parent().css({"height":$(item).height()+10});
			}
		})
		$('.more_details').each(function(idx,item){
			
			$(item).click(function(event){
				//event.preventDefault();
				event.stopPropagation();
				
				var panel = $("#"+this.id.replace("more_detail","detail_entry"));
				//change the +/- graphic
				if(panel.is(":hidden")) {
					$("#entry"+this.id.replace("more_detail","")+ " p.opportunity_name").css({"background-image" : "url('/_media/btn_contract.gif')"});
				} else {
					$("#entry"+this.id.replace("more_detail","")+ " p.opportunity_name").css({"background-image" : "url('/_media/btn_expand.gif')"});
				}

				lastOpenedPanel = panel;
				lastOpenedEntry = this;
				
				panel.slideToggle(300);
			})
			$(item).mouseover(function(event){
				$(this).css({"cursor":"pointer"});
			})
			$(item).mouseout(function(event){
				$(this).css({"cursor":"default"});
			})
		})
		
		$('.opp_description a').each(function(idx,item){
			$(item).click(function(event){
				//event.preventDefault();
				event.stopPropagation();
			})
		})
		
		$('.opp_description p').each(function(idx,item){
			$(item).mouseover(function(event){
				$(this).css({"cursor":"text"});

			})
			$(item).mouseout(function(event){
				$(this).css({"cursor":"default"});
			})
			$(item).click(function(event){
				event.stopPropagation();
			})

		})
	}
	
	$('[class^=opp_details]').hide();
	

	$('[class^=opp_link]').click(function (event) {
		event.stopPropagation();
		//determine which panel to toggle based on id of element that was clicked
		var panel = $("#detail_"+this.id);
				
		if(lastOpenedPanel != null && lastOpenedEntry != null) {
			if(lastOpenedPanel.attr("id") != panel.attr("id")) {
				//change the +/- graphic
				//$("#"+lastOpenedEntry.id+ " p.opportunity_name").css({"background-image" : "url('_media/btn_expand.gif')"});
				//lastOpenedPanel.hide(300);
			}
		}
		
		//change the +/- graphic
		if(panel.is(":hidden")) {
			$("#"+this.id+ " p.opportunity_name").css({"background-image" : "url('/_media/btn_contract.gif')"});
		} else {
			$("#"+this.id+ " p.opportunity_name").css({"background-image" : "url('/_media/btn_expand.gif')"});
		}

		lastOpenedPanel = panel;
		lastOpenedEntry = this;

		//toggle the panel
	    panel.slideToggle(300);
	
	});
}

function connectoryShowOpportunities() {
	// $('#btn_my_share_saved').click(function(event){
	// 	event.preventDefault();
	// 	//siteOverlay();
	// 	
	// 	$("body").append('<div id="lightbox_wrapper" class="lightbox"></div>');
	// 	$("#lightbox_wrapper").append('<div id="saved_opportunities"></div>');
	// 	
	// 	//set HTML for the sign in box
	// 	//$("#signin_box").html('<form id="signin_form" name="signin_form" action="signin.php" method="post"><h1>Login</h1><input id="username_" name="username" type="text" class="text" value="" /><input name="password" type="text" class="text" value="" /><button name="sign_in" type="submit" class="sprite sign_in"><span>Search</span></button><p><a href="forgot_password.php">Forgot Password</a></p></form><p>Don\'t have a username and password? <a id="form_pledge_link" href="pledge.php">Take the Pledge!</a></p>');
	// 	$("#saved_opportunities").load("_includes/saved_opportunities.php", null, function() {
	// 		var opporunities_table = $("#saved_opportunities > table:first");
	// 		opporunities_table.wrap('<div class="lightbox_scroll"></div>')
	// 		$("#share_opportunities_form").append('<p><a id="btn_cancel" type="submit" class="btn_close sprite_button" href="#">Cancel</a></p>');
	// 		shareEmailFormBoxes();
	// 		hiJackSpecialLinkTypes("#saved_opportunities");
	// 		checkForToolTips("#saved_opportunities");
	// 		showLightBox($("#saved_opportunities"));
	// 	});
	// 	
	// })
}

function connectorySearchSmallBoxes() {
	var zipLabel = "Zip";
	var keywordLabel = "Keyword(s)";
	
	var zipInput = $('#search_small_form .zip');
	zipInput.val(zipLabel);
	
	zipInput.focus(function() {
		if(this.value == zipLabel) {
			this.value = "";
		}
	});
	
	zipInput.blur(function() {
		if(this.value == "") {
			this.value = zipLabel;
		}
	});
	
	var keywordsInput = $('#search_small_form .keywords');
	keywordsInput.val(keywordLabel);
	
	keywordsInput.focus(function() {
		if(this.value == keywordLabel) {
			this.value = "";
		}
	});
	
	keywordsInput.blur(function() {
		if(this.value == "") {
			this.value = keywordLabel;
		}
	});
}

/* PREFERENCES */
function shareEmailFormBoxes() {
	//shareEmailFormBoxes
	validateForm("send_to_friend_form");
}

function hiJackPreferencesForm() {
	
	//PERSONAL INFO
	//hide employee info if not checked
	var isEmployeeCheckBox = $("input[id='twc_employee']:first");
	if(!isEmployeeCheckBox.attr("checked")) {
		$("label[for=employee_id]:first").animate({"opacity":"0"}, 0);
		$("input[id='employee_id']:first").animate({"opacity":"0"}, 0);
		$("label[for*=twc_region]:first").animate({"opacity":"0"}, 0);
		$("select[id*='twc_region']:first").animate({"opacity":"0"}, 0);
		$("select[id*='twc_region']:first").val("");
		$("input[id='employee_id']:first").val("");
		$("#employee_info").hide();

	} else {
		$("input[id='employee_id']:first").addClass("notBlank");
		$("select[id*='twc_region']:first").addClass("notBlank");
	}

	//apply click event to the TWC employee check box
	//to disable/enable certain fields
	isEmployeeCheckBox.click(function(event) {
		//event.preventDefault();
		var input = $(this);
		if(input.attr("checked")) {
			// $("input[name='employee_id']:first").removeClass("disabled");
			// $("input[name='employee_id']:first").attr("disabled", "");
			// $("select[name='region']:first").attr("disabled", "");
			$("#employee_info").slideToggle(300, function() {
				$("input[id='employee_id']:first").addClass("notBlank");
				$("select[id*='twc_region']:first").addClass("notBlank");
				$("label[for=employee_id]:first").animate({"opacity":"1"}, 250);
				$("input[id='employee_id']:first").animate({"opacity":"1"}, 250);
				$("label[for*=twc_region]:first").animate({"opacity":"1"}, 250);
				$("select[id*='twc_region']:first").animate({"opacity":"1"}, 250);
				//

			});
		} else {
			$("input[id='employee_id']:first").removeClass("notBlank");
			$("select[id*='twc_region']:first").removeClass("notBlank");
			$("label[for=employee_id]:first").animate({"opacity":"0"}, 250);
			$("input[id='employee_id']:first").animate({"opacity":"0"}, 250);
			$("label[for*=twc_region]:first").animate({"opacity":"0"}, 250);
			$("select[id*='twc_region']:first").animate({"opacity":"0"}, 250, function() {
				$("#employee_info").slideToggle(300);
				$(this).val("");
				$("input[id='employee_id']:first").val("");
			});
			
			// $("input[name='employee_id']:first").addClass("disabled");
			// $("input[name='employee_id']:first").attr("disabled", "disabled");
			// $("select[name='region']:first").attr("disabled", "disabled");
		};
	});
	
	validateForm("personal_form");

	//LOGIN FORM
	if($("#crediential_form").size() == 1) {
		validateForm("crediential_form");
	}


	//FULFILLMENT WALL FORM
	validateForm("pledge_wall_form");
	
	//apply Delete Entry function to button(s)	
	$('.delete_entry').click(function(event) {
		event.preventDefault();
		
		var entry = $(this).parent().parent();
		
		if(kMode) {
			var msg = "I'MMA LET YOU DELETE THAT ITEM, BUT WINDOWS RECYCLE BIN IS THE BEST DELETE OF ALL TIME!";
		} else {
			var msg = "Are you sure you want to delete this story?";
		}
		createPromptBox(msg, this.href);
		hiJackDeletePostPromptBox(entry);
		
		return true;
	})
	
	//entry_form = $('.pledge_entry:first').clone(true);


	//NEWSLETTER FORM
	var checkbox = $("#subscribe");
	if(checkbox.attr("checked")) {
		$("#interests").addClass("notBlank");
	} 
	
	checkbox.click(function(event) {
		//event.preventDefault();
		var input = $(this);
		if(input.attr("checked")) {
			$("#interests").addClass("notBlank");
		} else {
			$("#interests").removeClass("notBlank");
		};
	});
	
	validateForm("newsletter_form");
}

function hiJackDeletePostPromptBox(entry) {
	$("#btn_ok").click(function(event) {
		var action_url = this.href;
		event.preventDefault();
		var clickEvent = event;
		//alert("clicked");
		//fade out box
		$("#promptBox_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
			showLoadingBox("Deleting story. Please wait...");
			//grab the url from the action attribute
			$.ajax({
			   	type: "GET",
			   	url: action_url,
				dataType: "json",
			   	success: function(json){
			    	//alert( "Data Saved: " + msg );
					if(json.success == "true") {
						//alert("true");
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							$("#promptBox_wrapper").remove();
							//if successful, do the following:
							//var entry = $(this).parent().parent();
							//alert($(this).attr("id"));
							//alert($(this).parent().attr("id"));
							//closeLightBox(event);
							entry.animate({"opacity":"0"}, 500, "linear", function(){
								entry.remove();
								if($(".pledge_entry").size() == 0) {
									var no_stories = '<div id="no_stories"><p>You currently do not have any stories.</p></div>';
									$('#pledge_wall_form > fieldset:first').prepend(no_stories);
								}
								closeLightBox();

							});
						});
					} else {
						//alert('returned error!');
						//fade out the loading box and remove it after fade out
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							var msg = new Array(json.message);
							createErrorBox(msg, true)
						});
					}
				},
				error: function(msg) {
					// alert('error!');
	//				fade out the loading box and remove it after fade out
					$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
						$("#loading_wrapper").remove();
						var msg = new Array("There was a problem connecting to the server. Please try again.");
						createErrorBox(msg, true)
					});
				}
			});
		});
	});	
}

/* SHARE */
function hiJackShareDownloadLinks() {
	//alert("hiJackShareDownloadLinks");
}

function hiJackSaveOpporunitiesForm() {
	//alert("hiJackSaveOpporunitiesForm");
	//links that delete an opp
	var deleteLinks = $('a.delete_opp');
	deleteLinks.click(function(event) {
		event.preventDefault();
		if(kMode) {
			var msg = "I'MMA LET YOU DELETE THAT ITEM, BUT WINDOWS RECYCLE BIN IS THE BEST DELETE OF ALL TIME!";
		} else {
			var msg = "Are you sure you want to delete this opportunity?";
		}
		createPromptBox(msg, this.href);
		hiJackOpportunityPromptBox();
	})
	
	//validate form
	validateForm("share_opportunities_form");
	
}

function hiJackOpportunityPromptBox() {
	//alert("hiJackOpportunityPromptBox");
	$("#btn_ok").click(function(event) {
		var action_url = this.href;
		event.preventDefault();
		//alert("clicked");
		//fade out box
		$("#promptBox_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
			showLoadingBox("Deleting opportunity. Please wait...");
			//grab the url from the action attribute
			$.ajax({
			   	type: "GET",
			   	url: action_url,
				dataType: "json",
			   	success: function(json){
			    	//alert( "Data Saved: " + json.success );
					if(json.success == "true") {
						$("#promptBox_wrapper").remove();
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							//fade back in the form box and re-enabled the submit button after fade in
							//
							if (window.location.href = '#share-pledge') { // Prevent pledge sharing for re-opening
								window.location = window.location.protocol+'//'+window.location.hostname+window.location.pathname+window.location.search;
							} else {
								window.location.reload();
							}
						});
					} else {
						//alert('error!');
						//fade out the loading box and remove it after fade out
						$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
							$("#loading_wrapper").remove();
							var msg = new Array(json.message);
							createErrorBox(msg, false);
						});
					}
				},
				error: function(msg) {
					//alert('error!');
					//fade out the loading box and remove it after fade out
					$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
						$("#loading_wrapper").remove();
						var msg = new Array("There was a problem connecting to the server. Please try again.");
						createErrorBox(msg, false);
					});
				}
			});
		});
	});
}

function hiJackInviteForm() {
	validateForm("invite_form");
}

/* DISCUSS / THE WALL */
function createPostStoryBox() {
	//siteOverlay();
	$("body").append('<div id="post_story_wrapper" class="lightbox"></div>');
	$("#post_story_wrapper").append('<div id="post_story_box"></div>');
	
	//set HTML for the sign in box
	$("#post_story_box").load("/form_post_story.php", null, function() {
		$("#post_your_story_form fieldset:first").append('<p><a id="btn_cancel" type="submit" class="btn_close sprite_button" href="#">Cancel</a></p>');
		checkForToolTips("#post_story_box");
		hijackPostStoryForm();
		showLightBox($("#post_story_box"));
	});
	
	//omniture
	if(s != undefined) {
		trackLinkClick("event4");
	}
	
	
}

function hijackPostStoryForm() {
	//alert("hijackPostStoryForm")
	//replace the entry button with something else
	//so we can make a faux upload button to display the file the user selected
		
	var newFileEntry = '<button id="entry_photo" name="entry_photo" type="button" class="file">Choose File</button>';
	newFileEntry += '<span id="file_name">no file selected</span>';
	newFileEntry += '<label for="hiddenFile" class="hide">An image</label>';
	newFileEntry += '<input id="hiddenFile" name="hiddenFile" type="hidden" value="" class="required" />';

	$("#entry_photo").replaceWith(newFileEntry);
	
	var action_url = $("#post_your_story_form").attr("action");	
	var form_data = $("#post_your_story_form").serialize();
	ajaxFileUpload = new AjaxUpload('#entry_photo', {
		// Location of the server-side upload script
		// NOTE: You are not allowed to upload files to another domain
		action: action_url,
		// File upload name
		name: 'entry_photo',
		// Additional data to send
		data: form_data,
		// Submit file after selection
		autoSubmit: false,
		// The type of data that you're expecting back from the server.
		// HTML (text) and XML are detected automatically.
		// Useful when you are using JSON data as a response, set to "json" in that case.
		// Also set server response type to text/html, otherwise it will not work in IE6
		responseType: 'json',
		// Fired after the file is selected
		// Useful when autoSubmit is disabled
		// You can return false to cancel upload
		// @param file basename of uploaded file
		// @param extension of that file
		onChange: function(file, extension){
			//update the filename element to show
			//alert("ajax upload file change!");
			$("#file_name").text(file);
			$("#hiddenFile").attr("value",file);
		},
		// Fired before the file is uploaded
		// You can return false to cancel upload
		// @param file basename of uploaded file
		// @param extension of that file
	  	onSubmit: function(file, extension) {
			//alert("ajax upload submit!");
			$("#post_story_wrapper").animate({"opacity":"0"}, 200, "linear");
			
			//this.disable();
			//check file extension			
			if (!(extension && /^(jpg|png|jpeg|gif)$/.test(extension))){
                  // extension is not allowed
                  //alert('Error: invalid file extension');
                  // cancel upload
                  return false;
			} else {
				var form_data = {
					your_story: $('#your_story').val(),
					city: $('#city').val(),
					state: $('#state').val(),
					MAX_FILE_SIZE: $('#MAX_FILE_SIZE').val()
				}
				this.setData(form_data);
			}
		},
		 // Fired when file upload is completed
		 // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
		 // @param file basename of uploaded file
		 // @param response server response
		 onComplete: function(file, response) {
			//alert("ajax upload complete!");
			endTimeOut();
			if(response.success == "true") {
				//remove post_story box
				//alert("true");
				$("#post_story_wrapper").remove();
				this.destroy();
				$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
					$("#loading_wrapper").remove();
					//fade back in the form box and re-enabled the submit button after fade in
					var msg = new Array(response.message);
					createSuccessLightBox("<p>"+msg+"</p>");

					trackLinkClick("event5");
			
				});
			} else {
				//alert('error!');
				//fade out the loading box and remove it after fade out
				$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
					$("#loading_wrapper").remove();
					var msg = new Array(response.message);
					createErrorBox(msg, false)
				});
			}
		}
	});
	
	$("#post_your_story_form").submit(function(event){
		//alert("submit button!");
		event.preventDefault();
		//alert("submitted!");
		
		//disable submit button
		var submitButton = $("#post_your_story_form button[type='submit']")
		submitButton.attr("disabled","disabled");
						
		//fade out box
		if (jQuery.browser.msie) {
			if(parseInt(jQuery.browser.version) == 6) {
				$("#post_story_wrapper select").each(function(idx,item){
					$(item).addClass("hide");
				})
			}
		}
		$("#post_story_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
			showLoadingBox("Submitting your story. Please wait...");
			var errors = new Array();

			$("#post_your_story_form textarea.required").each(function(idx, item){
				if(!isNotBlank(item)) {
					//alert("I am blank")
					var input = $(item);
					//alert(input.attr("id"))
					var label = $("label[for="+input.attr("id")+"]");
					//alert(label)
					var msg = label.text()+" is required.";
					//alert(msg)
					errors.push(msg);
				};

			});
			
			//check for length
			var maxLength = 400;
			$("#post_your_story_form textarea.hasMaxlength").each(function(idx, item){
				if(!isUnderMaxLength(item, maxLength)) {
					var msg = getLabel(item)+" must be under "+maxLength+" characters.";
					//alert(msg)
					errors.push(msg);
				}
			});
			
			//check if anything is required
			$("#post_your_story_form input.required").each(function(idx, item){
				if(!isNotBlank(item)) {
					//alert("I am blank")
					var input = $(item);
					//alert(input.attr("id"))
					var label = $("label[for="+input.attr("id")+"]");
					//alert(label)
					var msg = label.text()+" is required.";
					//alert(msg)
					errors.push(msg);
				};

			});
			
			// //user the properly selected a file
			// //check its extension
			var file = $("#hiddenFile").val();
			if(file != "") {
				var regex = /^.*\.(jpg|png|jpeg|gif)$/i;
				var isValid = regex.test(file);
				if(!isValid) {
					var msg = "That is not a valid image file or that file does not have the proper extension. Please choose a GIF, JPG, or PNG.";
					errors.push(msg);
					//alert(msg)
				}
			}
			
			if(errors.length > 0) {
				$("#loading_wrapper").animate({"opacity":"0"}, 200, "linear", function(){
					$("#loading_wrapper").remove();
					createErrorBox(errors, false);
				});
				return false;
			}
			
			ajaxFileUpload.submit();
			startTimeOut("There was a problem connecting to the server. Please try again.", 60000);
			
			return true;
		});
	});
}

/* ABOUT */
function hiJackContactForm() {
	//alert("hiJackContactForm");
	
	$("#contact_form select[id=reason]").change(function(event){
		//show/hide location dropdown depending on reason drop down
		var selected = $("#contact_form select[id=reason] option:selected");
		var locationBox = $("#contact_form select[id=state]");
		var locationLabel = $("#contact_form label[for=state]");
		if(selected.hasClass("needsLocation")) {
			locationBox.fadeIn(250);
			locationLabel.fadeIn(250);
			locationBox.addClass("notBlank");
		} else {
			locationLabel.fadeOut(250);
			locationBox.removeClass("notBlank");
			locationBox.fadeOut(250, function(){
				locationBox.val("");
			});
			
		}
	})
	
	validateForm("contact_form");
}

/* SHARING TO SOCIAL NETWORKS */
function shareURL(service, url, title) {
	//alert("share")
	url = typeof(url) != 'undefined' ? url : window.location.href;

	//alert("url "+url+" | title "+title+ " | service "+service);
	var encodedURL = encodeURIComponent(url+"&fb=share");
	var encodedTitle = encodeURIComponent("Watching '"+title+"' on Connect a Million Minds. Science rocks.");
	var encodedDesc = encodeURIComponent("Watching '"+title+"' on Connect a Million Minds. Science rocks.");
	shortURL = url;
	switch(service) {
		case "twitter":
			//this is being done since browser block popups that are
			//not called directly from a click
			//calling a window.open from Ajax blocks the pop up, so this
			//timer is the best to try
			//checkForURLShortener = window.setInterval("receivedShortened('"+title+"')", 100);
			//shorten URL via bit.ly api.
			//alert(shortURL.length)
			var tempTitle = "Watching '"+title+"' on Connect a Million Minds. "+shortURL;
			//alert(tempTitle.length)
			if(tempTitle.length > 140) {
				var changedURL = url.replace("http://www.","");
				shortURL = changedURL;
				encodedTitle = encodeURIComponent("Watching '"+title+"' on Connect a Million Minds. "+shortURL);
			} else {
				encodedTitle = encodeURIComponent("Watching '"+title+"' on Connect a Million Minds. "+shortURL);
			}
			// $.ajax({
			//    	type: "POST",
			//    	url: "_includes/shortenURL.php",
			// 	data: "long_url="+url,
			// 	dataType: "text",
			//    	success: function(msg){
			//     	//alert( "URL shortened: " + msg);
			// 		shortURL = msg;
			// 		//alert(changedURL)
			// 		var encodedTitle = encodeURIComponent("Watching '"+title+"' on Connect a Million Minds. "+shortURL);					
			// 		var shareURL = "http://twitter.com/home?status="+encodedTitle;
			// 		window.open(shareURL, "shareWindow","menubar=0,resizable=0,scrollbars=1");
			// 	},
			// 	error: function() {
			// 		//alert( "URL NOT shortened: " + msg);
			// 		shortURL = changedURL;
			// 		var encodedTitle = encodeURIComponent("Watching '"+title+"' on Connect a Million Minds. "+shortURL);
			// 		var shareURL = "http://twitter.com/home?status="+encodedTitle;
			// 		window.open(shareURL, "shareWindow","menubar=0,resizable=0,scrollbars=1");
			// 	}
			// });
			
			//setTimeout("receivedShortened('"+title+"')", 1000);

			var shareURL = "http://twitter.com/home?status="+encodedTitle;
			window.open(shareURL, "shareWindow","menubar=0,resizable=0,scrollbars=1");
		break;
		case "facebook":
			var shareURL = "http://www.facebook.com/sharer.php?u="+encodedURL+"&t="+encodedTitle;
			//alert(shareURL)
			var width = 625;
			var height = 425;
			var top = ($(window).height()/2) - (height/2);
			var left = ($(window).width()/2) - (width/2);
			window.open(shareURL, "shareWindow","width="+width+",height="+height+",top="+top+",left="+left+",menubar=0,resizable=0");			
		break;
		case "digg":
			//overwrite the title
			encodedTitle = encodeURIComponent("Connect a Million Minds Video");
			var shareURL = "http://digg.com/submit?url="+encodedURL+"&title="+encodedTitle+"&bodytext="+encodedDesc+"&media=video&topic=general_sciences";
			//alert(shareURL)
			window.open(shareURL, "shareWindow","menubar=0,resizable=0,scrollbars=1");
		break;
		default:
		break;
	}
	
	//var addThisURL ="http://www.addthis.com/bookmark.php?v=250&pub=connectamillionminds&s="+ service + "&url=" + url + "&title=" + title;
	//window.open(addThisURL, "shareWindow","menubar=0,resizable=0");
}

function receivedShortened(title) {
	if(shortURL != null) {
		//alert("shortened!")
		//clear timer
		clearInterval(checkForURLShortener);
		//launch twitter
		var encodedTitle = encodeURIComponent("Watching '"+title+"' on Connect a Million Minds. "+shortURL);
		var shareURL = "http://twitter.com/home?status="+encodedTitle;
		window.open(shareURL, "shareWindow","menubar=0,resizable=0,scrollbars=1");
	}
}

/* OMNITURE */
function trackLinkClick(eventID) {
	if(s != undefined) {
		//alert("trackLinkClick: "+eventID+" - "+s.eVar5+" - "+s.eVar6)
		s.events=eventID;
		s.tl();
		//clear out variable names after track link call
		s.events="";
		s.prop1="";
		s.prop2="";
		s.eVar5="";
		s.eVar6="";
	}
}

function trackVideoStart(mediaName, mediaLength, mediaOffset, mediaPlayerName) {
	//alert("trackVideoStart");
	if(s != undefined) {
		if(s.Media != undefined) {
			s.Media.open(mediaName, mediaLength, mediaPlayerName)
			s.Media.play(mediaName, mediaOffset)
		}
	}
}

function trackVideoEnd(mediaName, mediaLength, mediaOffset, mediaPlayerName) {
	//alert("trackVideoEnd");
	if(s != undefined) {
		if(s.Media != undefined) {
			s.Media.stop(mediaName,mediaOffset)
			s.Media.close(mediaName)
		}
	}
}

function trackVideoPause(mediaName, mediaOffset) {
	//alert("trackVideoPause");
	if(s != undefined) {
		if(s.Media != undefined) {
			s.Media.stop(mediaName,mediaOffset)
		}
	}
}

function trackVideoResume(mediaName, mediaOffset) {
	//alert("trackVideoResume");
	if(s != undefined) {
		if(s.Media != undefined) {
			s.Media.play(mediaName,mediaOffset)
		}
	}
}

/* TOOLTIPS */
function addToolTip(item) {
	//alert("addToolTip");
	//make item a jQuery item
	var jQueryItem = $(item);
	//get its id and remove "tooltip_" prefix from it
	var id = jQueryItem.attr("id").substring(8);
	//find any element that has the same id but with tooltip_text_ prefix to use as the tooltip text
	var tooltipTextElement = $('#tooltip_text_'+id);
	if(tooltipTextElement.size() == 1) {
		var toolTipText = tooltipTextElement.html();
	} else {
		var toolTipText = "Help is currently unavailable.";
	}
	if(jQueryItem.hasClass("pledge")) {
		jQueryItem.qtip({
		   content: toolTipText,
		   show: 'mouseover',
		   hide: 'mouseout',
		   position: {
		      corner: {
		         target: 'leftMiddle',
		         tooltip: 'topRight'
		      }
		   },
			style: { 
				width: 267,
				padding: 5,
				background: '#246c84',
				color: '#fff',
				textAlign: 'center',
				border: {
				   width: 1,
				   radius: 0,
				   color: '#618b96'
				}
			}
		});
	} else if (jQueryItem.hasClass("connectory")) {
		jQueryItem.qtip({
		   content: toolTipText,
		   show: 'mouseover',
		   hide: 'mouseout',
		   position: {
		      corner: {
		         target: 'leftMiddle',
		         tooltip: 'topRight'
		      }
		   },
			style: { 
				width: 267,
				padding: 5,
				background: '#d6565a',
				color: '#fff',
				textAlign: 'center',
				border: {
				   width: 1,
				   radius: 0,
				   color: '#ea8589'
				}
			}
		});
	} else if (jQueryItem.hasClass("connectory_small")) {
		jQueryItem.qtip({
		   content: toolTipText,
		   show: 'mouseover',
		   hide: 'mouseout',
		   position: {
		      corner: {
		         target: 'bottomRight',
		         tooltip: 'topLeft'
		      }
		   },
			style: { 
				width: 267,
				padding: 5,
				background: '#d6565a',
				color: '#fff',
				textAlign: 'center',
				border: {
				   width: 1,
				   radius: 0,
				   color: '#ea8589'
				}
			}
		});
	} else {
		jQueryItem.qtip({
		   content: toolTipText,
		   show: 'mouseover',
		   hide: 'mouseout',
		   position: {
		      corner: {
		         target: 'leftMiddle',
		         tooltip: 'topRight'
		      }
		   },
			style: { 
				width: 267,
				padding: 5,
				background: '#f8f3ea',
				color: '#f16618',
				textAlign: 'center',
				border: {
				   width: 1,
				   radius: 0,
				   color: '#dad4b7'
				}
			}
		});
	}
}

// Additional functionality to social media buttons on the video modal dialog if applicable
function HREFcallback() {
		
	FB.XFBML.parse(); // render like button
	
	var href = $('#video_distribution #url').val();
	var name = $('#video_details h1').text();
	var thumb = $('#video_thumb').val();
	var desc = $('#video_description').text();
	
	// Force the width of the share box to the same with as the embed code
	var video_width = $('#video object').width();
	$('#video_share_items').css({width : video_width});	
	
	// Additional hooks into close events to change window location
	$(".btn_close").click(function(event){
		window.location = '#all';
	});
	
	$(".overlay").click(function(event){
		window.location = '#all';
	});
}

// Publish to Social Media
function pledgePublish() {
	// User just pledged 
	if(window.location.hash == '#share-pledge') {
		$.get('/_includes/pledge.php', function(data) {
			$("body").append('<div id="pledgeBox_wrapper" class="lightbox"></div>');
			$("#pledgeBox_wrapper").append(data);
			
			// Twitter
			$("#pledge_sharing_twitter a").click(function(event) {
				window.open(this.href);
				return false;
			});
			
			// Facebook
			$("#pledge_sharing_facebook a").click(function(event) {
				FB.ui( {
					method: 'stream.publish',
					message: $('#pledge_message').attr('value')
				});
				return false;
			});
			
			// No Thanks (Close)
			$("#pledge_sharing_close a").click(function(event) {
				closeLightBox(event);
				return false;
			})
			showLightBox($('#pledge_sharing_box'), true, true);
		});	
	}
}

/* Facebook Integration */
// Initialize Facebook API
window.fbAsyncInit = function() {
	FB.init({appId: '131865326851256', xfbml : true}); // needs to parse xfbml tags on FB ready
};


function showLoadingLightbox() {
	var boxTitle = "<h2 id=\"logging_into_facebook\">Facebook Login</h2>";
	var html = '<p>Waiting for Facebook...</em></p>';
	
	$("body").append('<div id="loading_wrapper" class="lightbox"></div>');
	$("#loading_wrapper").append('<div id="loading_box" class="acct_lightbox"></div>');
	$("#loading_box").append('<div class="lightbox_inner">'+boxTitle+html+'</div>');
	//siteOverlay();
	$("#loading_box").css("text-align","left");
	$("#loading_box").css("width","250px");
	showLightBox($("#loading_box"), true, true);
}

// Log into facebook
function facebookLogin(callback) {
	FB.getLoginStatus(function (response) {
		//console.log('facebookLogin: ' + response.status);
		// User is already logged in
		if (response.session) {
			callback();
		
		// Prompt user to login
		} else {
			FB.login(function (response) {
			// close prompt window
			//closeLightBox(); No.
			if (response.session) {
				callback();
			}
			},{perms:'user_birthday,email,user_location'});
		}
	});
}

function loginCallback() {
	FB.getLoginStatus(function (response) {	
		if(response.session) {
			// Get facebook ID of user and redirect site. 
			FB.api('/me', function(response) {
				form = $('#signin_form')[0];
				form.fb_id.value = response.id;
				$(form).submit();
			});
		} else {
			facebookLogin(loginCallback);
		}
	});
}

// Post message to user's wall
function facebookPost(body) {
	FB.api('/me/feed', 'post', { message: body }, function(response) {
		if (!response || response.error) {
			alert('Error occured');
		} else {
			alert('Post ID: ' + response.id);
		}
	});
}
$(function () {
	$('button.sign_in').click(function (){
		form = $('#signin_form')[0];
		form.fb_id.value = '';
	});
});
$(function () {
	// Load Facebook Code
	(function() {
		var e = document.createElement('script');
		e.type = 'text/javascript';
		e.src = document.location.protocol +
		'//connect.facebook.net/en_US/all.js';
		e.async = true;
		$('body').append('<div id="fb-root"></div>');
		$('div#fb-root').append(e);
		//alert('fb loaded');
	}());
});
