/**************************************************
 * ready.js
 **************************************************/

var minheight = 400;
var wpdir = '/cms';
var themedir = wpdir+'/wp-content/themes/BMC12/';

jQuery(document).ready(function($) {

	$.fn.preload = function() {
		this.each(function(){
			$('<img/>')[0].src = this;
		});
	}

	// add all images to preload here
	$([themedir+'images/main-nav/about-us_on.gif',
	   themedir+'images/main-nav/who-we-are_on.gif',
	   themedir+'images/main-nav/our-roots_on.gif',
	   themedir+'images/main-nav/ethos_on.gif',
	   themedir+'images/main-nav/our-team_on.gif',
	   themedir+'images/main-nav/about-you_on.gif',
	   themedir+'images/main-nav/who-we-work-with_on.gif',
	   themedir+'images/main-nav/testimonials_on.gif',
	   themedir+'images/main-nav/what-we-do-together_on.gif',
	   themedir+'images/main-nav/capabilities_on.gif',
	   themedir+'images/main-nav/our-approach_on.gif',
	   themedir+'images/main-nav/portfolio_on.gif',
	   themedir+'images/subnav-buttons/roots-on.jpg',
	   themedir+'images/subnav-buttons/ethos-on.jpg',
	   themedir+'images/subnav-buttons/team-on.jpg',
	   themedir+'images/_blank.png'
	   ]).preload();


	$(".nav img").hover(function() {
	 $(this).attr("src",$(this).attr("src").replace("_off","_on"));
	}, function() {
	 $(this).attr("src",$(this).attr("src").replace("_on","_off"));
	});
	
	$(".nav .toggler img").unbind('mouseenter').unbind('mouseleave');
 
	$(".multi").hover(function() {
	 $(this).find("ul.close").removeClass("close").addClass("open");
	 $(this).find(".toggler img").attr("src",$(this).find(".toggler img").attr("src").replace("_off","_on"));
	}, function() {
	 $(this).find("ul.open").removeClass("open").addClass("close");
	 $(this).find(".toggler img").attr("src",$(this).find(".toggler img").attr("src").replace("_on","_off"));
	});
	
	$(".nav .snazzy.dead img").unbind('mouseenter').unbind('mouseleave');
	

	$('.textlinks a.toggler').click(function() {
	
		var toggler = this;
		var txt = '';
		var target = '#' + $(toggler).attr('id').replace('to_','');
		if($(target).hasClass('open')) {
		  $(target).removeClass('open').addClass('closed');
		  $(toggler).removeClass('open').addClass('closed');
		  txt = $(toggler).html();
		  $(toggler).html($(toggler).attr('alt'));
		  $(toggler).attr('alt',txt);
		} else {
		  $(toggler).siblings().each(function() {
		    if($(this).hasClass('open')) {
		      $(this).removeClass('open').addClass('closed');
			  txt = $(this).html();
			  $(this).html($(this).attr('alt'));
			  $(this).attr('alt',txt);
			}
		  });
		  $(toggler).parent().parent().find('.extended').removeClass('open').addClass('closed');
		  $(target).removeClass('closed').addClass('open');
		  $(toggler).removeClass('closed').addClass('open');
		  txt = $(toggler).html();
		  $(toggler).html($(toggler).attr('alt'));
		  $(toggler).attr('alt',txt);
		}
		
	});


	//////////////////////////////////////////////////////////
	// FAQ functionality
	$(".answer").addClass("ghost");
	
	$(".answer").each(function() {
	 if ($(this).find("p").length<=0) $(this).wrapInner("<p></p>"); 
	});
	
	$(".question").click(function() {
	  if($(this).next().hasClass("ghost")) {
		$(".answer").addClass("ghost");
		$(this).next().removeClass("ghost");
		 freshChest();
	  } else {
	    $(this).next().addClass("ghost");
		freshChest();
	  }
	});	
	
	
	if($('.jscroll').length) {
		// makes that little scroll bar thingy
		$('.dropdown').jScrollPane();
		$('.container').addClass('ghost');
		// make the dropdown menus work
		$('.select').hover(function() {
		  $(this).find('.container').removeClass('ghost');
		}, function() {
		  $(this).find('.container').addClass('ghost');
		});
	}
	
	
	
	////////////////////////////////////////////////////////
	// portfolio page thumb action
	$('.thumbframe').click(function(){
	
		var theID = $(this).parent().attr('id').replace('ss_','');
	
		$(this).parent().find('.thumbcurrent').removeClass('thumbcurrent');
		$(this).addClass('thumbcurrent');

		var src = $(this).find('.thumbimage').attr('src').replace('__thumbs/','');
		var blank = '/cms/wp-content/themes/BMC12/images/_blank.png';
		var link = $(this).find('.thumbimage').attr('link');
		var caption = $(this).find('.thumbimage').attr('alt');
		var title = $(this).find('.thumbimage').attr('title');
		var embed = $(this).find('.thumbimage').attr('embed');

		//$('#ss_<?php echo($pro->slug); ?> .featuredimage').animate({
		//  opacity: 0.0
		//}, 200, function() {
		//  $(this).attr('src',src);
		//  $(this).animate({
		//   opacity: 1.0
		//  }, 1000, function() {
		//   //done
		//  });
		//});

		if(link!="") {
		  $(this).parent().find('.featuredlink').attr('href',link);
		  $(this).parent().find('.featuredlink').attr('title',"Click to visit the website.");
		} else {
		  $(this).parent().find('.featuredlink').removeAttr('href');
		  $(this).parent().find('.featuredlink').removeAttr('title');
		}
		$(this).parent().find('.featuredimage').attr('src',blank);
		$(this).parent().find('.caption').html('<strong>'+title+'</strong>&nbsp;'+ caption);
		if(embed!="") {
			swfobject.embedSWF(embed, "embed_"+theID, "520", "400", "9.0.0");
		} else {
			$(this).parent().find('.featuredimage').attr('src',src);
		}
	
	});
   






	
	if($('#rotator').length) {
	
		// get the id of all slides into an array
		$('.slide').each(function() {
		  trimTarget($(this).attr('id'),210);
		});

		$('#rotator').before('<ul id="rotator-nav">').cycle({ 
			fx:     'scrollUp', 
			speed:   900, 
			timeout: 4500, 
			pause:   1,
			pager:	'#rotator-nav', 
			pagerAnchorBuilder: function(idx, slide) { 
				// return selector string for existing anchor 
				return '<li><a href="#">&bull;</a></li>';
			} 
		});
	
	}
	
	
	
	
	/////////////////////////////////////////////////////
	// form submissions

	$('#to-info-button').click(function() {
	  var errors = 0;
	  $(this).addClass('ghost');
	  $('#x-message').html('processing...');
	  $('input.email').each(function() { if(!isValidEmail($(this).val())) errors++; $('#x-message').html('Please provide a valid email address.'); });
	  $('input.required').each(function() { if(!$(this).val()) { errors++; $('#x-message').html('Please fill out all required fields.'); } });
	  if(errors>0) {
		$(this).removeClass('ghost');
	  } else {
	    $('#to-info').attr('action',$('#to-info').attr('action').replace('cgi/formmail.pl','processors/to-info.php'));
		$('#to-info').ajaxSubmit({ success: processContact });
	  }		  
	});

	$('#to-emma-button').click(function() {
	  //$('#x-message').html('processing...');
	  //$(this).ajaxSubmit({ success: processNewsletter });
	  if($('input#emma_member_name_first').val()&&$('input#emma_member_name_last').val()&&$('input#emma_member_email').val()) {
		if(isValidEmail($('input#emma_member_email').val())) $('#to-emma').submit();
		else $('#x-message').html('Please provide a valid email address.');
	  } else {
		$('#x-message').html('Please fill out all required fields.');
	  }		  
	});

	
	///////////////////////////////////////////////////////////
	// easy way to tell if javascript is enabled :)
	$('#javascript-message').remove();
	
	
	
	
}); // end on ready


/////////////////////////////////
// the name says it all
function isValidEmail(email) {
  var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
  return pattern.test(email);
}

///////////////////////////////////////////////////////////////////
// makes sure the sidebar and the content are the
// same height and at least whatever minheight is set to
function freshChest() {

  var $ = jQuery;

  // if this is the homepage, we should decrease the minheight variable
  if ($("#chester.home").length) minheight = 200;

  $("#left").height('auto'); // reset heights
  $("#right").height('auto'); // reset heights

  if($("#left").height() > $("#right").height())
	$("#right").height($("#left").height());
  else $("#left").height($("#right").height());
  
  if($("#left").height()<minheight) {
	$("#left").height(minheight);
	$("#right").height(minheight);
  }

}


//////////////////////////////////////////////////
// runs after EVERYTHING is loaded
jQuery(window).load(function($){

 freshChest();
 trimTarget('.testimony',100);
 if(window.location.hash=="#expanded") {
   $('#to_study_<?php echo($pro->ID); ?>').click();
   $('#to_process_<?php echo($pro->ID); ?>').click();
   $('#to_banda_<?php echo($pro->ID); ?>').click();
 }
 
});

function trimTarget(target,maxheight) {

	var $ = jQuery;

	// do something crazy to limit the lines of text
	
	var ztop = 0;
	var zheight = 0;
	var position;
	var gtop = 0;
	var found = false;
	var lineheight = 0;

	$('#'+target+' .content').children().each(function() {
		
		  position = $(this).position();
		  ztop = parseInt(position.top);
		  zheight = parseInt($(this).height());
		  lineheight = parseInt($(this).css('line-height'));
		
		if(this.tagName!="IMG") {
		
		  if(!found&&ztop+zheight>=maxheight) { 
			while(ztop<maxheight) { ztop+= lineheight; }
			gtop=ztop;
			found=true;
			$(this).html('<span>'+$(this).text()+'</span>');
			$('#'+target+' .content a.more').appendTo(this);
			$('#'+target+' .content > a.more').remove();
			
			// removes the last character (and orphaned spaces) on each click
			var lastelement = $(this).children('span');
			var i = 0;
			while((position.top+$(this).height())>=(maxheight+lineheight)) {
			  lastelement.html(lastelement.text().substring(0, lastelement.text().length-12));
			  i++;
			  if(i>200) {
				break;
			  }
			} lastelement.html(lastelement.text().substring(0, lastelement.text().length-6));//do it one more time for good measure
			lastelement.append('...');
			
		  } else if(found && !$(this).hasClass('more')) {
		    $(this).remove();
		  }
		}
			
	});
	
}

function processContact(msg) {
  var $ = jQuery;
  $('#x-message').html(msg);
}

