/**********************************************
 Blackbaud Design Custom JavaScript
***********************************************
 Site:		Dian Fossey Gorilla Fund International
 Author: 	Chris Wolf
 Created:	2/2/10
 BBNC:		6.10
 
 
*********** CHANGE LOG ************************



**********************************************/


/************* global definitions ************/

//var bbpage = $(document);	//offline
var bbpage = Sys.WebForms.PageRequestManager.getInstance(); //BBNC

var isEditView = window.location.href.match('edit=');

/************* core design global functions *************/

function bbGlobal()
{

	// replace copyright with current year
	function currentYear()
	{
		$("#currentYear").text((new Date).getFullYear());
	};
	
	function fixPositioning()
	{
		$('div[id$=_panelPopup]').appendTo('body');
		$('div[id$=_panelPopup_DropShadow]').appendTo('body');
	};
	
	function hideMenuItem()
	{
		$('a[title=hide]').each(function(){						  
		
			var ul = $(this).parent().parent();
			var li = $(this).parent();
			var parent = $(this).parent().parent().parent();
			var a = ul.prev();
			
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
			a.addClass('selected');
		}

		if (li.siblings().length > 0) {
				li.remove();
			} else {
				ul.remove();
				parent.removeClass('parent');
			}
		});
		
		$('ul.menu ul').each(function(){
		 if ($(this).children().length == 0) {
		  $(this).parent().removeClass('parent');
		  $(this).remove();
		 }
		});
		
		$('#contentSecondary ul.menu').wrap('<div class="contentBox" />');
		$('ul.menu').css('visibility','visible');
	
	};	
	
	function DisableKeyPress(){
      $('input:text').keypress(function(e){ 
	   if(e.keyCode==13){
		return false;
	   }
	  });
	};
		
	function photoBox()
	{
		$('.photo').each(function(){
			
			var src = $(this).attr('src');	
			var cap = $(this).attr('alt');
			var aln = $(this).attr('align');
			var w = $(this).outerWidth();
			
			if ($(this).attr('align')) {
				var float = ' float'+aln;
			} else if ($(this).hasClass('floatRight')) {
				var float = ' floatRight';
			} else if ($(this).hasClass('floatLeft')) {
				var float = ' floatLeft';
			} else {
				var float = '';
			};
			
			if ($(this).width() > 449) {
				
				$(this).wrap('<div class="photoBox" />');
				$(this).addClass(float);
				$(this).removeClass('photo');
				$(this).after(cap+'<div class="clear"></div>');
			
			} else {
			
				$(this).wrap('<div class="photoBox'+float+'" style="width: '+w+'px" />');
				$(this).removeClass('photo'+float);
				$(this).after(cap);
			
			};
			
		});
		
	};
	
	 $.extend({
  	  getUrlVars: function(){
       var vars = [], hash;
       var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
       for(var i = 0; i < hashes.length; i++)
       {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
       }
       return vars;
      },
      getUrlVar: function(name){
       return $.getUrlVars()[name];
      }
     });	
	
	
/** execute **********/
	fixPositioning();
	currentYear();
	hideMenuItem();
    DisableKeyPress();
    photoBox();

};


/************* site specific global functions *************/

function siteGlobal()
{

	function showSubMenu()
	{
		if ($('#ArchiveHeader').length > 0) {
			
			var group = $('#ArchiveHeader').text();
			var section = $('.menu a:contains("'+group+'")').parent().parent().parent();

			section.addClass('section');
			$('.menu a:contains("'+group+'")').addClass('group');

			$('.menu .section .group').addClass('selected').parent().addClass('selected');

			$.each($('li.selected'),function(){		
             //if ($(this).parent().parent().is('li') {
              $('li.selected').parent().parent().addClass('selected');		
			 //}
			});
			$.each($('li.selected'),function(){		
             //if ($(this).parent().parent().is('li') {
              $('li.selected').parent().parent().addClass('selected');		
			 //}
			});
	
		};
	
	};	
	
     function NewUserRegistrationForm()
     { 
      if ($('tr[id$=_trRegistrationRequest]').length > 0) {
       $('.LoginFormCheckList input').each(function(){
        $(this).attr("checked", "checked");
       });
      };
     };


/** execute **********/
showSubMenu();
NewUserRegistrationForm();
};


/************* page specific functions *************/

function newsPhotos()
{
	if ($('#landingPhoto').length > 0) {
		$('.landing .photoBox').appendTo('#landingPhoto');
		$('.photoBox img').wrap('<div class="photoWrap" />');
	};
	
	if ($('.NewsChannelListingTable').length > 0) {
		$('.NewsChannelListingTable').addClass('summary');
		$('.NewsChannelItem').each(function(i){
			var i = i+1;
			$(this).addClass('article-'+i);
			var photoBox = $('.article-'+i+' .photoBox');
			if (photoBox) {
				photoBox.css('margin-top','.5em');
				$(this).parent().prepend(photoBox);
			}
			$(this).css('width','auto').after('<hr class="clear" />');
		});
	};
	
	if ($('.NewsReaderFormTable').length > 0) {
			var column = $('.column');
		$('.NewsReaderResultsList tr').each(function(i){
			var i = i+1;
			$(this).addClass('article-'+i);
			var url = $('.article-'+i+' .NewsReaderItemLink').attr('href');
			$('.article-'+i+' .NewsReaderItemDesc').append(' <a class="readmore" href="'+url+'">Full Story</a>');

			if ($('.landing').length == 0) {
			 $('.NewsReaderFormTable').addClass('NewsChannelListingTable summary');
			 var photoBox = $('.article-'+i+' .photoBox');
			 if (photoBox) {
				photoBox.css('margin-top','.5em');
				$('.article-'+i+' .NewsReaderItemLink').before(photoBox);
			 }
			 var dateSplit = $('.article-'+i+' .NewsReaderItemDate').html().split(' ');
			 $('.article-'+i+' .NewsReaderItemDate').html(dateSplit[0]+' '+dateSplit[1]+' '+dateSplit[2]+' '+dateSplit[3]);
			 $('.article-'+i+' .NewsReaderItemLink').parent().append('<hr class="clear" />');			 	
			}

			if ($('.landing.main').length > 0) {
				var article = $('.article-'+i+' td').html();
				var num = i-1;
				column.eq(num).append(article).addClass('column-'+i);
			    var photoBox = $('.column-'+i+' .photoBox');
				var articleContent = photoBox.parent();
				photoBox.prependTo(articleContent);
				$(this).remove();		
				$('.column br').hide();
				var columnImg = $('.column-'+i+' img');
				var imgHeight = columnImg.height();
				if (imgHeight > 140) {
					diff = imgHeight-140;
					margin = diff/2;
					columnImg.css('margin-top','-'+margin+'px');
				};				
			};		
			if ($('#landingPhoto').length > 0) {
				$('.NewsReaderFormTable').addClass('landing-2');
			}
		});	
		if ($('.landing.main').length > 0) {
			$('.photoBox img').wrap('<div class="photoWrap" />');
			$('.photoBox').removeClass('floatright');
			$('div[id$=_panelNewsReader]').remove();
		};
		if ($('.landing').length > 0) {
			$('.photoBox').removeClass('floatright');
		};
	};
	
};

function BBGlobalTranslations() {
	
	// membership form
	if ($('td[id$=_SummaryDues]').length > 0) {
	 $('td[id$=_SummaryDues] span').html('Adoption Cost:');
	};
	
}

function EmailPreferencesForm() {

 if ($('.SubscriptionFormTable').length > 0) {
  $('.ProfileFormSubmitButton').val('Update My Newsletter Preferences');
  $('.BBFormButtonCell').css('text-align','left');
  $('.ProfileFieldCaption').hide();
  
  $('.ProfileFormCheckBoxList tr:last').after('<tr><td style="padding: 1em 0"><input type="checkbox" id="checkAll"><label for="checkAll" style="font-style: italic">Check All Subscriptions</label></td></tr>');
  
  $('#checkAll').change(function(){
	  var _state = $(this).attr('checked');
	  $('.ProfileFormCheckBoxList input').each(function(){
		  $(this).attr('checked',_state);
	  });
	  if ($(this).is(':checked')) {
		$('label[for=checkAll]').html('Uncheck All Subscriptions');  
	  } else {
		$('label[for=checkAll]').html('Check All Subscriptions');  
	  }
	  
  });

  /*function toggleButton() {
   if ($('input[id$=_chkOpting]').is(':checked')) {
    $('.SubscriptionFormSubmitButton').val('Opt Out of Receiving Email');
   } else {
    $('.SubscriptionFormSubmitButton').val('Opt In to Receiving Email');
   }
  }
  
  toggleButton();
  
  $('input[id$=_chkOpting]').change(function(){
   toggleButton();
  });*/
  

 }
}


function vimeoPlayer(dID) {

function changeMOV(movID,title){
// build video src
var url_1 = 'http://vimeo.com/moogaloop.swf?clip_id=';
var url_2 = '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=c9ff23';
var movSRC = url_1+movID+url_2;

 flashembed('vimeoplayer', movSRC, {});
 $('#title').text(title);

}

if (window.location.href.match('movID=')) {
 var movID = $.getUrlVar('movID');
 var title = $('.clip a[href$='+movID+']').next().text();
 changeMOV(movID,title);
} else {
 var movID = dID;
 var title = $('.clip a[href$='+dID+']').next().text();
 changeMOV(movID,title);	
}
$('.clip a').each(function(){
	var thisURL = $(this).attr('href');
	var thisID = thisURL.split('com/')[1];
	var thisCaption = $(this).next().text();
	$(this).click(function(){
	 var movID = thisID;
	 var title = thisCaption;
	 //changeMOV(movID,title);
	 
	 var currentHref = window.location.href;
	 if (currentHref.match('&')) {
	  window.location.href = currentHref.substr(0, currentHref.lastIndexOf("&")) + "&movID=" + movID;
	 } else {
	  window.location.href = currentHref+"&movID="+movID;
	 }

	 return false;
	});
});

}


function eCardLoggedOut()
{
 if (window.location.href.match('CardViewKey=')) {
  $('input[id$=_btnSendAnECard]').click(function(){ window.location = "/Page.aspx?pid=714" });
 } else {
  window.location = "/Page.aspx?pid=714";
 }
}

function eCardLoggedIn()
{
	
}



function AdoptionForm()
{
Relabel('Name on card:','Name to appear on certificate:','label');
Relabel('I wish to give a gift of membership','I wish to give a gift of adoption','label');
Relabel('Special Message:','Name to appear on certificate:','label');
$('label[for$=_rdoRenewalOption_0]').html('Gift Recipient&nbsp;&nbsp;');
$('label[for$=_rdoRenewalOption_1]').html('Purchaser&nbsp;&nbsp;');
$('label[for$=_rdoBenefitsOption_0]').html('Gift Recipient&nbsp;&nbsp;');
$('label[for$=_rdoBenefitsOption_1]').html('Purchaser&nbsp;&nbsp;');
$('label[id$=_lblTxtNumCards]').parent().parent().hide();
$('label[id$=_lblTxtCardName]').parent().css('padding-left','0');
$('input[id=MemCat_0]').attr('checked','checked');
$('input[value="Join Now"]').val('Adopt Now');
$('span[id$=_lblThanks]').css('font-size','12px').text('Thank you for adopting! Your transaction is complete.');
}

function MembershipForm()
{
Relabel('Name on card:','Name to appear on certificate:','label');
Relabel('Name on card:','Name to appear on certificate:','span');
Relabel('Special Message:','Name to appear on certificate:','label');
$('label[for$=_rdoRenewalOption_0]').html('Gift Recipient&nbsp;&nbsp;');
$('label[for$=_rdoRenewalOption_1]').html('Purchaser&nbsp;&nbsp;');
$('label[for$=_rdoBenefitsOption_0]').html('Gift Recipient&nbsp;&nbsp;');
$('label[for$=_rdoBenefitsOption_1]').html('Purchaser&nbsp;&nbsp;');
$('label[id$=_lblTxtNumCards]').parent().parent().hide();
$('span[id$=_lblTxtNumCards]').parent().parent().hide();
$('label[id$=_lblTxtCardName]').parent().css('padding-left','0');
$('span[id$=_lblTxtNameOnCard]').parent().css('padding-left','0');
$('input[id=MemCat_0]').attr('checked','checked');
$('input[value="Join Now"]').val('Join Now');
$('span[id$=_lblThanks]').css('font-size','12px').text('Thank you for joining! Your transaction is complete.');
$('tr[id$=_trGuestPassInfo]').parent().parent().addClass('BBMembershipFormTable');
}


// run pre-load functions
document.write('<style type="text/css">.menu{visibility:hidden;}</style>');

// run page load functions
bbpage.add_pageLoaded(function(){
  bbGlobal();
  siteGlobal();
EmailPreferencesForm();
});









/*********** Execute Plugins **********/

// Relabel a Form Element // Author: Chris Wolf // BBNC: 6.10 // Created 5/25/2010 //
// Tested on: New User Registration
function Relabel(_old,_new,_element){
 var selector = $(_element+':contains("'+_old+'")');
 selector.each(function(){
  if ($(this).html() == _old) {
    // replace text in element
   var selHTML = $(this).html().replace(_old,_new);
   $(this).html(selHTML);
   

   // replace validation text
   
   // registration form
   if ($('tr[id$=_trRegistrationRequest]').length > 0) {
    var thisRow = $(this).parent().parent();
    if (thisRow.children('.BBFormRequiredFieldMarker').length > 0) {
     var span = $(this).parent().next().children('input').next();
     var alertID = span.attr('id'); 
     $('body').append('<script>'+alertID+'.errormessage = "'+_new+' Required";</script>');
    }
   }

  }
 });  
}

/*
 * tools.flashembed 1.0.4 - The future of Flash embedding.
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/flash-embed.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : March 2008
 * Date: ${date}
 * Revision: ${revision} 
 */
(function(){var e=typeof jQuery=="function";var i={width:"100%",height:"100%",allowfullscreen:true,allowscriptaccess:"always",quality:"high",wmode:"transparent",version:null,onFail:null,expressInstall:null,w3c:false,cachebusting:false};if(e){jQuery.tools=jQuery.tools||{};jQuery.tools.flashembed={version:"1.0.4",conf:i}}function j(){if(c.done){return false}var l=document;if(l&&l.getElementsByTagName&&l.getElementById&&l.body){clearInterval(c.timer);c.timer=null;for(var k=0;k<c.ready.length;k++){c.ready[k].call()}c.ready=null;c.done=true}}var c=e?jQuery:function(k){if(c.done){return k()}if(c.timer){c.ready.push(k)}else{c.ready=[k];c.timer=setInterval(j,13)}};function f(l,k){if(k){for(key in k){if(k.hasOwnProperty(key)){l[key]=k[key]}}}return l}function g(k){switch(h(k)){case"string":k=k.replace(new RegExp('(["\\\\])',"g"),"\\$1");k=k.replace(/^\s?(\d+)%/,"$1pct");return'"'+k+'"';case"array":return"["+b(k,function(n){return g(n)}).join(",")+"]";case"function":return'"function()"';case"object":var l=[];for(var m in k){if(k.hasOwnProperty(m)){l.push('"'+m+'":'+g(k[m]))}}return"{"+l.join(",")+"}"}return String(k).replace(/\s/g," ").replace(/\'/g,'"')}function h(l){if(l===null||l===undefined){return false}var k=typeof l;return(k=="object"&&l.push)?"array":k}if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}})}function b(k,n){var m=[];for(var l in k){if(k.hasOwnProperty(l)){m[l]=n(k[l])}}return m}function a(r,t){var q=f({},r);var s=document.all;var n='<object width="'+q.width+'" height="'+q.height+'"';if(s&&!q.id){q.id="_"+(""+Math.random()).substring(9)}if(q.id){n+=' id="'+q.id+'"'}if(q.cachebusting){q.src+=((q.src.indexOf("?")!=-1?"&":"?")+Math.random())}if(q.w3c||!s){n+=' data="'+q.src+'" type="application/x-shockwave-flash"'}else{n+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'}n+=">";if(q.w3c||s){n+='<param name="movie" value="'+q.src+'" />'}q.width=q.height=q.id=q.w3c=q.src=null;for(var l in q){if(q[l]!==null){n+='<param name="'+l+'" value="'+q[l]+'" />'}}var o="";if(t){for(var m in t){if(t[m]!==null){o+=m+"="+(typeof t[m]=="object"?g(t[m]):t[m])+"&"}}o=o.substring(0,o.length-1);n+='<param name="flashvars" value=\''+o+"' />"}n+="</object>";return n}function d(m,p,l){var k=flashembed.getVersion();f(this,{getContainer:function(){return m},getConf:function(){return p},getVersion:function(){return k},getFlashvars:function(){return l},getApi:function(){return m.firstChild},getHTML:function(){return a(p,l)}});var q=p.version;var r=p.expressInstall;var o=!q||flashembed.isSupported(q);if(o){p.onFail=p.version=p.expressInstall=null;m.innerHTML=a(p,l)}else{if(q&&r&&flashembed.isSupported([6,65])){f(p,{src:r});l={MMredirectURL:location.href,MMplayerType:"PlugIn",MMdoctitle:document.title};m.innerHTML=a(p,l)}else{if(m.innerHTML.replace(/\s/g,"")!==""){}else{m.innerHTML="<h2>Flash version "+q+" or greater is required</h2><h3>"+(k[0]>0?"Your version is "+k:"You have no flash plugin installed")+"</h3>"+(m.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='http://www.adobe.com/go/getflashplayer'>here</a></p>");if(m.tagName=="A"){m.onclick=function(){location.href="http://www.adobe.com/go/getflashplayer"}}}}}if(!o&&p.onFail){var n=p.onFail.call(this);if(typeof n=="string"){m.innerHTML=n}}if(document.all){window[p.id]=document.getElementById(p.id)}}window.flashembed=function(l,m,k){if(typeof l=="string"){var n=document.getElementById(l);if(n){l=n}else{c(function(){flashembed(l,m,k)});return}}if(!l){return}if(typeof m=="string"){m={src:m}}var o=f({},i);f(o,m);return new d(l,o,k)};f(window.flashembed,{getVersion:function(){var m=[0,0];if(navigator.plugins&&typeof navigator.plugins["Shockwave Flash"]=="object"){var l=navigator.plugins["Shockwave Flash"].description;if(typeof l!="undefined"){l=l.replace(/^.*\s+(\S+\s+\S+$)/,"$1");var n=parseInt(l.replace(/^(.*)\..*$/,"$1"),10);var r=/r/.test(l)?parseInt(l.replace(/^.*r(.*)$/,"$1"),10):0;m=[n,r]}}else{if(window.ActiveXObject){try{var p=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")}catch(q){try{p=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");m=[6,0];p.AllowScriptAccess="always"}catch(k){if(m[0]==6){return m}}try{p=new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(o){}}if(typeof p=="object"){l=p.GetVariable("$version");if(typeof l!="undefined"){l=l.replace(/^\S+\s+(.*)$/,"$1").split(",");m=[parseInt(l[0],10),parseInt(l[2],10)]}}}}return m},isSupported:function(k){var m=flashembed.getVersion();var l=(m[0]>k[0])||(m[0]==k[0]&&m[1]>=k[1]);return l},domReady:c,asString:g,getHTML:a});if(e){jQuery.fn.flashembed=function(l,k){var m=null;this.each(function(){m=flashembed(this,l,k)});return l.api===false?this:m}}})();