$(document).ready(function(){

	//set shadowbox up
	Shadowbox.init({
	    skipSetup: true
	});	

	fixPng();
	replaceFonts();
	setUpButtons();
	setUpTooltips();
	setUpHeader();
	setUpLikeLinks();
	setUpFlagLinks();
	setUpPaginationLinks();
	setUpPostISHRedirectLink();
	setUpFedFinderLink();
	setUpRequiredFields();
	setUpFedFinderInterstitial();
	setUpTwitterPostLightbox();
	setUpISHofTheDay();
	setUpPostISHForm();
	setUpISHTabs();
	setUpPostToFacebookWindow();
	setUpDatePicker();
	setUpJewishFederationLogoLinks();
	setUpVideoPaginationLinks();
	

	//***BDF
	setUpYoutubeSlider();
	setUpValidateMapPC(); 
	setUpClueTooltips(); 
	autoStartVideo();

	
	function fixPng(){
		//$(document).pngFix(); 

	}
	
	
	function replaceFonts(){
		Cufon.replace("h1.jFont, h2.jFont, h3.jFont, h4.jFont, span.jFont");
	}
	
	
	function setUpButtons(){
			
		$("a.btn-find-fed, a.btn-vote").css("text-indent", "-999px");
	}
	
	
	//sets up the ish and ish fund tooltips
	function setUpTooltips(){
		var ishText = "What's a #? - It's a hash tag, which makes sure your ish appears here, and counts towards the #ish fund.";
		$(".ish_tooltip").each( function(i){
			$(this).attr("title", ishText);
		});
/*		
		var fundText = "What's the #ish fund? - Copy explaining #ish fund";
		$(".fund_tooltip").each( function(i){
			$(this).attr("title", fundText);
		});
*/		
		$(".ish_tooltip").tooltip({
			showURL: false,
			extraClass: "wordbox",
			fixPNG: true, 
			showBody: " - ",
			top: -131,
			left: -10
		});
	}
	
	
	//set up the insane header 
	function setUpHeader(){	
		$("#menuMap area.menuItem").mouseover( function(e){
				$("#siteHeader .menu_hover_"+$(this).attr("title")).addClass("menu_hover_hovered");
		});
		$("#siteHeader .menu_hover").mouseout(function(e){
				$(this).removeClass("menu_hover_hovered");	
		});
		
		//now for ie6 png fix...
		$("#siteHeader .menu_hover").pngFix(); 
	}
	
	
	
	//sets up the datepicker on the ish of the day page
	function setUpDatePicker(){
		if( $("#IOTDdateChooser").length < 1 ){	return false; }
		
		$("#IOTDdateChooser .calendar").datepicker({
		   onSelect: function(dateText, inst) {
				window.location = "ish_of_the_day.php?date="+dateText;
			},
			dateFormat: 'yy-mm-dd'
		});
		$("#IOTDdateChooser .calendar").hide();
		
		$("#IOTDdateChooser a.link").mouseover( function(e){
			$("#IOTDdateChooser .calendar").show();
		});
		
		$("#IOTDdateChooser .calendar").mouseleave( function(e){
			$("#IOTDdateChooser .calendar").hide();
		});

	}
	
	
	
	//sets up the like link service ajaxiness
	function setUpLikeLinks(){
		$("a.like, a.unlike").live("click", function(e){
			e.preventDefault();
			
			//don't let them click it more than once per page load
			if($(this).hasClass("clicked")){
				return false;
			}
			
			$(this).addClass("clicked");
			var updateElement = $(this).siblings(".count");
			var likeFunc = 'like';
			var ish_id = $(this).attr("rel");
			if($(this).hasClass('unlike')){	likeFunc = 'unlike';}
			
			
			$(this).parents(".likeButtons").find(".count").show();
			//update the element now - assume the ajax works for snappiness
			//original = parseInt(updateElement.html());
			//updateElement.html(original+1);
			
			$.ajax({
				type: "POST",
				url: LIKE_SERVICE_URL,
				dataType: 'json',
				data: {
					id : ish_id,
					like: likeFunc
				},
				success: function(json){
					if(json.status == 'success'){
						original = parseInt(updateElement.html());
						updateElement.html(original+1);
					}
				}
			});
		});
	}
	
	
	//sets up the flag link service ajaxiness
	function setUpFlagLinks(){
		$("a.flag").live( "click", function(e){
			e.preventDefault();
			
			var updateElement = $(this).parents(".flagLink");
			var ish_id = $(this).attr("rel");
			
			//we're just going to update quickly for snappiness and assume that everything is a-ok
			//updateElement.html("<span class='flagged'>flagged</span>");
			
			$.ajax({
				type: "POST",
				url: FLAG_SERVICE_URL,
				dataType: 'json',
				data: {
					id : ish_id
				},
				success: function(json){
					if(json.status == 'success'){
						updateElement.html("<span class='flagged'>flagged</span>");
					} else {
						updateElement.html("already flagged");
					}
				}
			});
		});
	}
	
	
	//sets up the pagination ajaxiness
	function setUpPaginationLinks(){
		$("a.lastLink, a.nextLink").live("click", function(e){
			e.preventDefault();
			
			var num = 10;
			
			//vars for updating elements
			var updateElement = $($(this).attr("rel"));
			var updateLink = $(this).attr("href");
			var el = $(this);
			var otherEl = $(this).siblings(".paginationLink");
			var firstElement = $(this).siblings(".first");
			var lastElement = $(this).siblings(".last");
			
			//vars for page numbering
			var firstIsh = 0;
			var total = parseInt($(this).siblings(".total").html().replace(",", ""));
			
			if( $(this).hasClass('lastLink') ){
				firstIsh = parseInt( firstElement.html().replace(",", "") )-num;
				if(firstIsh < 1){	firstIsh=1 }
			} else {
				firstIsh = parseInt( lastElement.html().replace(",", "") )+1;
				if(firstIsh>total){ return false;	}
			}
			
			$.ajax({
				type: "POST",
				url: PAGINATION_SERVICE_URL,
				dataType: 'json',
				data: {
					link: updateLink
				},
				success: function(json){
					//update list
					updateElement.html(json.ishList);
					
					//update links
					if(el.hasClass("lastLink")){
						el.attr("href", json.prev);
						otherEl.attr("href", json.next);
					} else {
						el.attr("href", json.next);
						otherEl.attr("href", json.prev);
					}
					
					//uypdate counts		
					var lastIsh = firstIsh+num-1;			
					if(lastIsh>total){
						lastIsh = total;
					}
					firstElement.html(firstIsh);
					lastElement.html(lastIsh);
					
					//remove pagination links if we don't need them
					if( parseInt(lastElement.html())==total ){
						el.add(otherEl).filter(".nextLink").hide();
					} else {
						el.add(otherEl).filter(".nextLink").show();
					}

					if( firstIsh==1 ){
						el.add(otherEl).filter(".lastLink").hide();
					} else {
						el.add(otherEl).filter(".lastLink").show();
					}
					
					//if this is popular ishes, update the numbers
					if(updateElement.attr("id")=="popularISHList" || updateElement.attr("id")=="popularWeekISHList"){
						updateElement.find("li.ish").each( function(i){
							$(this).find(".num").html(firstIsh+i);
						});
					}
				}
			});
			
		});
		
		//hide prev links at first
		$("a.lastLink").hide();
	}
	
	
	function setUpPostISHRedirectLink(){
		$("a.postISHredirect").click( function(e){
			
			//if we hve the post ish widget on this page, just scroll to it and open it oop!
			if( $("#postISH").length > 0 ){
				e.preventDefault();
				
				$.scrollTo( "#postISH", 1000, {
					offset: -100,
					onAfter: function(){
						$("#postISH .postISHCTA a.post_ish_cta").click();
					}
				});
			} 
			
			//if not, just let the link go where it wants =p
			
		});
	}
	
	
	function setUpFedFinderLink(){
		$("a.fedFinderLink").click( function(e){
			
			//if we hve the post ish widget on this page, just scroll to it and open it oop!
			if( $("#federationFinder").length > 0 ){
				e.preventDefault();
				
				$.scrollTo( "#federationFinder", 1000, {
					offset: -10
				});
			} 
			
			//if not, just let the link go where it wants =p
			
		});
	}
	
	
	function setUpISHofTheDay(){
		//only run this if the ISH of the day widget is on the page
		if( $("#ISHOfTheDay").length < 1 ){	return false; }
	}


	function setUpPostISHForm(){
		//only run this if the postISH widget is on the page
		if( $("#postISH").length < 1 ){	return false; }
		
		
		//set up the facebook posting functionality
		$("input.fb-post").hide();
		
		//set up the twitter posting functionality
		$("input.twit-post").hide();
			
		//set up the open animation
		$("#postISH .postISHCTA a.post_ish_cta").click( function(e){
			e.preventDefault();
			
			//ie sucks shit...
			if (jQuery.browser.msie && parseFloat(jQuery.browser.version) < 8 ){	$("#ISHpostForm .col2").hide();	}
			
			$("#postISH .postISHCTA").fadeOut(
				function(){
					$("#postISH .postISHForm").slideDown( function(){
						if (jQuery.browser.msie && parseFloat(jQuery.browser.version) < 8 ){	$("#ISHpostForm .col2").show();	}
					});
				}
			);
		});
		
		//set up the close animation
		$("#ISHpostForm a.close_button, #ISHpostForm a.close_link").click( function(e){
			e.preventDefault();
			
			//ie sucks shit...
			if (jQuery.browser.msie && parseFloat(jQuery.browser.version) < 8 ){	$("#ISHpostForm .col2").hide();	}
			
			$("#postISH .postISHForm").slideUp(
				function(){
					$("#postISH .postISHCTA").fadeIn();
					if (jQuery.browser.msie && parseFloat(jQuery.browser.version) < 8 ){	$("#ISHpostForm .col2").show();	}
				}
			);
		});
		
		//cufon the titles that need em
		Cufon.replace('#ISHpostForm .col2 label.text, #ISHpostForm .col2 .close_button');
		
		//helper function for anabling/disabling the form
		function checkISHRequirements(){

			//check that we have all required info
			if( $("#first_name").length < 1 || $("#first_name").attr("value")==REQ_FIELD_DEFAULT ){
				$("#site_submit").attr("disabled", "disabled");
				$("#site_submit").attr("src", "img/btn-submit-disabled.jpg");
				return false;
			}else if( $("#last_name").length < 1 || $("#last_name").attr("value")==REQ_FIELD_DEFAULT ){
				$("#site_submit").attr("disabled", "disabled");
				$("#site_submit").attr("src", "img/btn-submit-disabled.jpg");
				return false;
			}else if( $("#email").length < 1 || $("#email").attr("value")==REQ_FIELD_DEFAULT ){
				$("#site_submit").attr("disabled", "disabled");
				$("#site_submit").attr("src", "img/btn-submit-disabled.jpg");
				return false;
			}else if( $("#zip").length < 1 || $("#zip").attr("value")==REQ_FIELD_DEFAULT ){
				$("#site_submit").attr("disabled", "disabled");
				$("#site_submit").attr("src", "img/btn-submit-disabled.jpg");
				return false;
			}else if( $("#ishText").length < 1 || $("#ishText").attr("value")==REQ_FIELD_DEFAULT || $("#ishText").attr("value")==ISHTEXT_FIELD_DEFAULT || $("#ishText").attr("value")==" #ish " ){
				$("#site_submit").attr("disabled", "disabled");
				$("#site_submit").attr("src", "img/btn-submit-disabled.jpg");
				return false;
			}

			//if we get to this point, enable the submit
			$("#site_submit").removeAttr("disabled");
			$("#site_submit").attr("src", "img/btn-submit.jpg");
			
			return true;
		}
		
		//set up the req checking
		$("input.required, textarea.required").bind( "keypress", function(e){	checkISHRequirements();	});
		checkISHRequirements();
		
		//set up thank you message post ish link
		$("#showIshPostFormAgain").click( function(e){
			e.preventDefault();
			
			$(".thankYouMessage").fadeOut( function(){
				$(".postForm").fadeIn();
			});
			
		});
	}



	function setUpRequiredFields(){
		
		//on focus, remove the required text and change the css style
		$("input.required, textarea.required").bind( "focus", function(e){
			if( $(this).attr("value")==REQ_FIELD_DEFAULT || $(this).attr("value")==ISHTEXT_FIELD_DEFAULT){
				if( $(this).attr("id")=="ishText" || $(this).attr("id")=="ishText2" ){
					$(this).attr("value", " #ish ");
					var inputEl = $(this).get(0);
					if (inputEl.setSelectionRange) { 
						inputEl.focus(); 
						inputEl.setSelectionRange(0, 0); 
					} else if (inputEl.createTextRange) { 
						var range = inputEl.createTextRange(); 
						range.collapse(true); 
						range.moveEnd('character', 0); 
						range.moveStart('character', 0); 
						range.select(); 
					}
				} else {
					$(this).attr("value", "");
				}
				$(this).css({	color: "#000"});
			}else if( $(this).html()==REQ_FIELD_DEFAULT ){
				$(this).html("#ish ");
				$(this).css({	color: "#000"});
			}
		});
		
		$("input.required, textarea.required").bind( "blur", function(e){
			if( $(this).attr("value")=="" ){
				$(this).attr("value", REQ_FIELD_DEFAULT);
				$(this).css({	color: "#292929"	});
			}else if( $(this).hasClass("textarea") && $(this).html()=="" ){
				$(this).html(ISHTEXT_FIELD_DEFAULT);
				$(this).css({	color: "#292929"	});
			}else if( $(this).hasClass("textarea") && $(this).val()==" #ish " ){
				$(this).html(ISHTEXT_FIELD_DEFAULT);
				$(this).val(ISHTEXT_FIELD_DEFAULT);
				$(this).css({	color: "#292929"	});
			}
		});
		
	}
	
	
	function setUpFedFinderInterstitial(){
		$("a.fedLink").each( function(i){
			
			var content = $(this).siblings(".description").html();
			Shadowbox.setup(this, {
				content: "<h1>hi</h1>",
				player: "inline",
				title: 	"Hello world",
				height: 480,
				width: 640
			});
		
		});
	}

	
	function setUpTwitterPostLightbox(){
		$("#postISH .postConnectOptions .twitConnect a.twitter_post").each( function(i){
			Shadowbox.setup(this, {
				title: 	"twitter post",
				height: 480,
				width: 640
			});
		});
	}
	
	
	function setUpISHTabs(){
		//only run if we have the ish tabs on the page
		if( $("#ISHTabs").length < 1 ){	return false; }
		
		//hide the content panes we don't need
		$("#ISHTabs .contentPane").hide();
		$("#ISHTabs .paneSelected").show();
		
		//set up the tab functionality
		$("#ISHTabs ul.ishTabs li a.tab").click( function(e){
			e.preventDefault();
			
			//if the tab is already selected, do nothing
			var parentLi = $(this).parents("li");
			if(parentLi.hasClass("selected")){	return false;	}
			
			//set the selected li and show the target pane
			$("#ISHTabs .contentPane").removeClass("paneSelected").hide();
			$("#ISHTabs ul.ishTabs li.selected").removeClass("selected");
			
			parentLi.addClass("selected");
			$("#ISHTabs ."+$(this).attr("href")).addClass("paneSelected").show();
		});
		
		//set up the this week/all time popular switcher
		$("#popularSwitcher a.sortLink").click( function(e){
			e.preventDefault();
			
			$("#popularISHListContainer, #popularWeekISHListContainer").hide();
			$($(this).attr("href")).show();
			
			$("#popularSwitcher a.sortLink").removeClass("selected");
			$(this).addClass("selected");
		});
		
		
		//cufon the tag cloud
		Cufon.replace(".tagCloud a.word");
		
		//set up the search again link
		$("#ISHTabs .pane_search .searchResults .searchHeader a.searchAgain").click( function(e){
			e.preventDefault();
			
			$("#ISHTabs .pane_search .searchResults").hide();
			$("#ISHTabs .pane_search .searchFunction").show();
		})
	}
	
	
	function setUpPostToFacebookWindow(){
		//only run if we're in the post to facebook window
		if( $("#facebookPostingWidget").length < 1 ){	return false; }
		
		//set up the close link
		$("#facebookPostingWidget a.close_button").click( function(e){
			window.close();
		});
	}
	
});

//global scope items
var intervalID = 0;

function setTitles(){
	if($(".youTubeSlider table.resultTable_gsvb").length > 0){
		clearInterval(intervalID);
		$(".youTubeSlider table.resultTable_gsvb .resultDiv_gsvb").each( function(i){
			$(this).append("<span class='title'>"+$(this).attr("title")+"</span>");
		});
	}
}


function facebook_onlogin(session_key, uid) {
   
	$.ajax({
		type: "POST",
		url: "facebook_connect.php",
		dataType: 'json',
		data: {
			//session_id : FB.Facebook.apiClient._session.session_key,
			//user_id: FB.Facebook.apiClient._session.uid
			session_id : session_key,
			user_id: uid
		},
		success: function(json){
			//open the post ish page
			if ($("#ishText2").attr("value")!=REQ_FIELD_DEFAULT && $("#ishText2").attr("value")!=ISHTEXT_FIELD_DEFAULT && $("#ishText2").attr("value")!=" #ish ") {
				$("input.fb-post").click();																	
			}
		}
	});
}

function updateSessionKey(session_key, uid){
	$.ajax({
		type: "POST",
		url: "services/facebook_session_service.php",
		dataType: 'json',
		data: {
			session_id : session_key,
			user_id: uid
		},
		success: function(json){
			
		}
	});
}


function setUpJewishFederationLogoLinks(){
	$("img.divot, #site-footer img.logo").css("cursor", "pointer").click( function(e){
		window.location = "http://www.jewishfederations.org";
	});
}


//________________ BDF _____________________


//***  Validates the PostalCode on the What you can do page
function setUpValidateMapPC()
{
if( $("#federationFinder").length < 1 ){	return false; }

    $("#MapSearchForm").validate({
						 success: function(label) {
						 		  enableFind();
						 },
						 showErrors: function(errorMap, errorList) {
									 disableFind();  
									 this.defaultShowErrors();
								     }
								});

//*** takes 98101, 98101-1234, v7j2w4 or v7j 2w4. Does not take v7j-2w4
$.validator.addMethod('postalCode', function (value) { 
		value=jQuery.trim(value);
		if(/^[0-9]{5}-[0-9]{4}$|^[0-9]{5}$|^[A-Z][0-9][A-Z]\s?[0-9][A-Z][0-9]$/.test(value) || /^[a-zA-Z][0-9][a-zA-Z]\s?[0-9][a-zA-Z][0-9]$/.test(value)){return true}else{return false;}
	}, 'Please enter a valid US or Canadian postal code.');
}

//*** enables the submit button
function enableSubmit()
{
	document.getElementById("submitButImage").src = "img/btn-submit.jpg";
	document.getElementById("submitBut").disabled=false;
}

//*** disables the submit button
function disableSubmit()
{
	document.getElementById("submitButImage").src = "img/btn-submit-disabled.jpg";
	document.getElementById("submitBut").disabled=true;
}

//*** enables the submit button
function enableFind()
{
	document.getElementById("submitButImage").src = "img/btn-find.jpg";
	document.getElementById("submitBut").disabled=false;
}

//*** disables the submit button
function disableFind()
{
	document.getElementById("submitButImage").src = "img/btn-find-disabled.jpg";
	document.getElementById("submitBut").disabled=true;
}


//*** Procesess the state map click
function getState(state)
{
	getSearchResults("state=" + state);
}

//*** AJAX function for getting the Foundation search results
function getSearchResults(getStr) {
            $.ajax({
                url: "fed_finder_results.php",
                type: "GET",
                data: getStr,
                cache: false,
                async: false,
                dataType: "text",
                success: function(rec) {
                  $("#resultContainer").empty().append(rec);
				  	setUpClueTooltips();
                },
                error: function() {
                    alert("Sorry, there was a problem connecting to the server");
                }
            });
        }

//*** Reloads the Finder search page
function redoSearch() {
            $.ajax({
                url: "widgets/fed_finder_map.php",
                type: "GET",
                cache: false,
                async: false,
                dataType: "text",
                success: function(rec) {
                  $("#resultContainer").empty().append(rec);
				  $(document).trigger('hideCluetip');
				  setUpValidateMapPC();
                },
                error: function() {
                    alert("Sorry, there was a problem connecting to the server");
                }
            });
        }


	// *** Sets up the tooltips on the what you can do federation list.
	function setUpClueTooltips()
	{
		$(".fed_tooltip").cluetip({
		  splitTitle: '|',
		  sticky: true,
		  titleAttribute: 'rel',
		  closePosition: 'top',
		  closeText: '<img src="img/clueTip-Close.png" alt="" />',
		  cluetipClass: 'custom',
		  dropShadow: false,
		  positionBy: 'fixed',
		  activation: 'click',
		  cluezIndex: 1000,
		  height: 225,
		  topOffset: -220,
		  leftOffset: -50,
		  width: 377
		  });

	}

//*** Simple image replace for the map
function replaceImg(imgName)
{
	document.getElementById("overlay").src="img/map/" + imgName + ".gif";
}


//*** Starts the first video on the What We Do Page
function autoStartVideo()
{
	if( $("#movieViewer").length < 1 ){	return false; }
	
	var movie_info = $($("#theTalent .youtubePromo").get(0)).find(".movie_info");	
	playYouTubeVideoByVideoID(movie_info.find(".video_id").html(), 'what\'s your #ish', 'with '+movie_info.find(".talent_name").html())

}


function setUpVideoPaginationLinks(){
	if( $(".video_list").length < 1 ){	return false; }
	
	//for each paginator
	$(".video_pagination").each( function(i){		
		var targetList = $($(this).attr("rel"));
		var pageLinks = $(this).find("a.pageLink");
		var curPage = $(this).find(".pageNumber .curPage");
		
		if( pageLinks.length < 2 ){
			$(this).find(".pageSelector").remove();
			return true;
		}
		
		//set up direct click links
		pageLinks.click( function(e){
			e.preventDefault();
			scrollToPage(targetList, parseInt($(this).attr("href")), pageLinks, curPage );
		});
		
		//set up first and last page links
		$(this).find("a.firstPage").click( function(e){
			e.preventDefault();
			scrollToPage(targetList, 1, pageLinks, curPage );
		});
		
		$(this).find("a.lastPage").click( function(e){
			e.preventDefault();
			var lastPage = pageLinks.length;
			scrollToPage(targetList, lastPage, pageLinks, curPage );
		});
		
		//set up next and prev page links
		$(this).find("a.prevPage").click( function(e){
			e.preventDefault();
			var prevPage = parseInt(curPage.html())-1;
			if(prevPage < 1){
				return false;
			}
			scrollToPage(targetList, prevPage, pageLinks, curPage );
		});
		
		$(this).find("a.nextPage").click( function(e){
			e.preventDefault();
			var nextPage = parseInt(curPage.html())+1;
			if(nextPage > pageLinks.length){
				return false;
			}
			scrollToPage(targetList, nextPage, pageLinks, curPage );
		});
	});
}


function scrollToPage(target, pageNum, pageLinks, curPage ){
	
	var pageSize = parseInt(target.parent().css("width"));
	var newLeft = (pageNum-1)*pageSize*-1;
	
	target.animate( { left: newLeft } );
	
	pageLinks.removeClass("selected");
	pageLinks.filter(".page_"+pageNum).addClass("selected");
	
	curPage.html(pageNum);
}


//*** Plays the youtube video from the What Do We Do Page
function playYouTubeVideoByVideoID(videoID, title, subtext){
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/'+videoID+'&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+videoID+'&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+title+"</h4><span>"+subtext+"</span>");
}


function playYouTubeVideo(talentId)
{
	if(talentId==1)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/5yAiP55b2aY&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/5yAiP55b2aY&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle1 h4").text()+"</h4><span>"+$("#movieTitle1 span").text()+"</span>");
	}
	
	if(talentId==2)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/ev6YqiS1moM&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/ev6YqiS1moM&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle2 h4").text()+"</h4><span>"+$("#movieTitle2 span").text()+"</span>");
	}
	
	if(talentId==3)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/m8z9zlnx29E&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/m8z9zlnx29E&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle3 h4").text()+"</h4><span>"+$("#movieTitle3 span").text()+"</span>");
	}
	
	if(talentId==4)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/BSYnftCS7ZQ&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/BSYnftCS7ZQ&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle4 h4").text()+"</h4><span>"+$("#movieTitle4 span").text()+"</span>");
	}
	
	if(talentId==5)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/P807DshJ1nM&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/P807DshJ1nM&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle5 h4").text()+"</h4><span>"+$("#movieTitle5 span").text()+"</span>");
	}
	
	if(talentId==6)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/hZ3jM3BzTVw&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/hZ3jM3BzTVw&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle6 h4").text()+"</h4><span>"+$("#movieTitle6 span").text()+"</span>");
	}
	
	if(talentId==7)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/cA4fN6Jr-Dc&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/cA4fN6Jr-Dc&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle7 h4").text()+"</h4><span>"+$("#movieTitle7 span").text()+"</span>");
	}
	
	if(talentId==8)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/c_CNczgUwkk&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/c_CNczgUwkk&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle8 h4").text()+"</h4><span>"+$("#movieTitle8 span").text()+"</span>");
	}
	
	if(talentId==9)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/5DrziGZxJ0U&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/5DrziGZxJ0U&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle9 h4").text()+"</h4><span>"+$("#movieTitle9 span").text()+"</span>");
	}
	
	if(talentId==10)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/hd79mqRW3K8&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/hd79mqRW3K8&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle10 h4").text()+"</h4><span>"+$("#movieTitle10 span").text()+"</span>");
	}
	
	if(talentId==11)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/ZcAex4VKCf8&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/ZcAex4VKCf8&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle11 h4").text()+"</h4><span>"+$("#movieTitle11 span").text()+"</span>");
	}
	
	if(talentId==12)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/_RNjg3u_Qqk&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/_RNjg3u_Qqk&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle12 h4").text()+"</h4><span>"+$("#movieTitle12 span").text()+"</span>");
	}
	
	if(talentId==13)
	{
	document.getElementById("movieDiv").innerHTML = ie6EmbedFix('<object width="718" height="356"><param name="movie" value="http://www.youtube.com/v/igj-buAHySQ&hl=en_US&fs=1&rel=0&hd=1&autoplay=1"></param><param name="allowFullScreen" value="false"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/igj-buAHySQ&hl=en_US&fs=1&rel=0&hd=1&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="false" width="718" height="356"></embed></object>');
	$("#secTitle").html("<h4 class=\"jFont\">"+$("#movieTitle13 h4").text()+"</h4><span>"+$("#movieTitle13 span").text()+"</span>");
	}
	
	Cufon.replace("#secTitle h4.jFont");
}

//*** sigh ***
function ie6EmbedFix(embedCode)
{
   if(embedCode && embedCode.toLowerCase().indexOf('classid') == -1) {
      var objPos = embedCode.toLowerCase().indexOf('object ') + 'object '.length;
      return embedCode.substr(0, objPos) + 'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' + embedCode.substr(objPos);
   } else {
      return embedCode;
   }
}

//*** Sets up the youtube sliders at the bottom of the What We Do Page
function setUpYoutubeSlider(){
		//set up titles
		intervalID = setInterval("setTitles()", 1000);
		
		
		//bind next and prev links
		$(".youTubeSlider a.prev").bind("click", function(e){
			e.preventDefault();
			
			var table = $(this).siblings(".videoThumbs").find("table.resultTable_gsvb");
			if( parseInt(table.css("left")) < 0 ){
				var newLeft = parseInt(table.css("left"))+106;
				
				table.animate({
					left: newLeft+"px"
				}, "fast");
			}
		});
		
		$(".youTubeSlider a.next").bind("click", function(e){
			e.preventDefault();
			
			var table = $(this).siblings(".videoThumbs").find("table.resultTable_gsvb");
			
			if( parseInt(table.css("left")) > -(table.width()-106)){
				var newLeft = parseInt(table.css("left"))-106;
				
				table.animate({
					left: newLeft+"px"
				}, "fast");
			}
		});
	}
    
//*** Loops through and sets up the movie slider to do stuff on click
function setTitles(){
	if($(".youTubeSlider table.resultTable_gsvb").length > 0){
		clearInterval(intervalID);
		
		$(".youTubeSlider table.resultTable_gsvb .resultDiv_gsvb img").each( function(i){
			$(this).click(function() { openYouTubeMovie($(this).attr("src")); });	
		});
	}
}

//*** Gets the movie id from the image src and opens it up in a new window.
function openYouTubeMovie(src)
{
	sndLast = src.lastIndexOf("/");
	sndStart = (src.lastIndexOf("/", sndLast-1)+1);
	movieId = src.substring(sndStart,sndLast);
	window.open('http://www.youtube.com/watch?v='+movieId,'mywindow');
}

var validator;

//***  Validates the comment form
function setUpValidateCommentForm()
{

    validator = $("#commentForm").validate({
		rules: {
			firstname: "required",
			lastname: "required",
			email: "required",
			comment: "required"
		},
		messages: {
			firstname: "Enter your first name",
			lastname: "Enter your last name",
			email: {
				required: "Please enter a valid email address",
				minlength: "Please enter a valid email address"
			},
			comment: "Please enter your comment"
		},
	 	success: function(label) {
				 checkForm();
		 },
		 showErrors: function(errorMap, errorList) {
				 
			disableSubmit();  
			this.defaultShowErrors();
		}
	});

	//*** takes 98101, 98101-1234, v7j2w4 or v7j 2w4. Does not take v7j-2w4
	$.validator.addMethod('postalCode', function (value) { 
			value=jQuery.trim(value);
			if(/^[0-9]{5}-[0-9]{4}$|^[0-9]{5}$|^[A-Z][0-9][A-Z]\s?[0-9][A-Z][0-9]$/.test(value) || /^[a-zA-Z][0-9][a-zA-Z]\s?[0-9][a-zA-Z][0-9]$/.test(value)){return true}else{return false;}
		}, 'Please enter a valid US or Canadian postal code.'),

	$.validator.addMethod('customRequired', function (value) { 
			value=jQuery.trim(value);
			if(value.length>0){return true}else{return false;}
		}, 'Please enter a value');

}



//*** AJAX function for viewing all the comments
function getCommentsResults(itemPos) {
            $.ajax({
                url: "comments.php",
                type: "GET",
                data: "itemPos="+itemPos,
                cache: false,
                async: false,
                dataType: "text",
                success: function(rec) {
                  $("#ajaxContainer").empty().append(rec);
                },
                error: function() {
                    alert("Sorry, there was a problem connecting to the server");
                }
            });
        }
		
		
//*** AJAX function for getting showing the add comment page
function addComment(ish_of_day_id) {
            $.ajax({
                url: "addComment.php?ish_id="+ish_of_day_id,
                type: "GET",
                cache: false,
                async: false,
                dataType: "text",
                success: function(rec) {
                  $("#ajaxContainer").empty().append(rec);
				  setUpValidateCommentForm();
                },
                error: function() {
                    alert("Sorry, there was a problem connecting to the server");
                }
            });
        }
		
		//*** AJAX function for posting comments
function postComment() {
            email=document.getElementById("email").value;
			updates=document.getElementById("contactCheck").checked;
			firstname=document.getElementById("firstname").value;
			lastname=document.getElementById("lastname").value;
			zip=document.getElementById("zip").value;
			ishText=document.getElementById("comment").value;
			ishId=document.getElementById("ish_of_day_id").value;
			
			$.ajax({
			   type: "POST",
			   url: "addComment.php?ish_id="+ishId,
			   data: "email="+email+"&updates="+updates+"&first_name="+firstname+"&last_name="+lastname+"&zip="+zip+"&ishText="+ishText+"&submit=CommentPostForm",
                success: function(rec) {
                  $("#ajaxContainer").empty().append(rec);
				  setUpValidateCommentForm();
                },
                error: function() {
                    alert("Sorry, there was a problem connecting to the server");
                }
            });
        }
		

function checkForm()
{
	if(validator.numberOfInvalids()==0 && document.getElementById("email").value.length>0 && document.getElementById("email").value!="[required]" && document.getElementById("firstname").value.length>0 && document.getElementById("firstname").value!="[required]" && document.getElementById("lastname").value.length>0 && document.getElementById("lastname").value!="[required]" && document.getElementById("zip").value.length>0 && document.getElementById("zip").value!="[required]" && document.getElementById("comment").value.length>0 && document.getElementById("comment").value!="[required]")
	{							  
		enableSubmit();
	}else{
		disableSubmit();  
	}
	return true;
}

/*MASON'S SADASS LIGHTBOX*/

$(document).ready(function() {

	/* This is basic - uses default settings */
	
	$("a#single_image").fancybox();
	
	/* Using custom settings */
	
	$("a#inline").fancybox({ 
		scrolling: "no",
		padding: 0,
		margin: 0,
		titleShow: false,
		onStart: function(){
			$("#ishText").val($("#ishText2").val());
		}
	});


	
});




