// Globals
var donateText;
var subscribeText;
var donateIsOpen = false;
var subscribeIsOpen = false;


// Autostart on DOM ready
	$(document).ready( function()
	{
		$('.slideshow').cycle({timeout:  6000});
		
		var donateButtonTop = $("#donate-box-top .donate-button");
		if (donateButtonTop[0]) {
			console.log(donateButtonTop[0]);
			$("#donate-box-top .donate-button")[0].closeImage = '/wp-content/themes/sakyong2/images/btn-support2-close.gif';
		}
		var donateButtonBottom = $("#donate-box-bottom .donate-button");
		if (donateButtonBottom[0]) {
			$("#donate-box-bottom .donate-button")[0].closeImage = '/wp-content/themes/sakyong2/images/btn-support-close.gif';
		}
		
		jQuery.each($(".donate-button"), function () {
			this.oldHtml = this.innerHTML;
		});
		jQuery.each($(".donate-box"), function () {
			this.oldWidth = $(this).width();
			this.oldHeight = $(this).height();
		});
		
		
		$(".donate-button").click(function() {
			donateToggle(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);
			return false;
		});		
		
		
		subscribeText = $("#subscribe-button").html();
		$("#subscribe-button").click(function() {
			subscribeToggle();
			return false;
		});	
		
		
		$(".donate-box").hoverIntent({
			 interval: 400,
			 sensitivity: 7,
			 over: function() {
				donateOpen(this.parentNode);
			},
			 timeout: 2000,
			 out: function() {
				donateClose(this.parentNode);
			}
		});	
		
		$("#subscribe-box").hoverIntent({
			 interval: 400,
			 sensitivity: 7,
			 over: subscribeOpen,
			 timeout: 2000,
			 out: subscribeClose
		});	
		
		
		$(".paypal-link").click(function(event) {
			if (!$(this).attr('href').match(/^#.*$/)) { // if isn't an anchor link
				event.preventDefault();
			}
			//console.log(this);
			$(".donate-text").hide();
			$(".donate-paypal").show();
		});
		
		
		if(jQuery.browser.safari) {
			$(".donate-nosafari").hide();
			$(".donate-safari").show();
		}
		
		/*
		document.getElementById('cf2_field_2').defaultValue = "Your Email";
		document.getElementById('cf2_field_2').value = "Your Email";
		$("#cf2_field_2").search();
		*/
		PEPS.rollover.init();
		
		
		$("#accordion").accordion({autoHeight: false});
		
		
		
	    ////// Home Page Code
		if ($('#home-container').length) {
			$('.slide-text').addClass('hidden');
			var slideButtons = document.getElementById('slide-buttons').getElementsByTagName('li');
			var slides = document.getElementById('slides').getElementsByTagName('li');
			for (var i=0; i< slideButtons.length; i++) {
				slideButtons[i].number = i;
				$(slideButtons[i]).hover( function() {
					if (!$(this).hasClass('active')) {
						$(slideButtons).each( function() {
							$(this).removeClass("active");
						});
						$(this).addClass("active");
						
						$(slides).each( function() {
							$(this).removeClass("active");
						});
						$(slides[this.number]).addClass("active");
						$(slides[this.number]).trigger("slideShown", slides[this.number]);
					}
				},
				function() {
					//$(this).removeClass("active");
					
				});
				$(slideButtons[i]).dropShadow({opacity:0.7});
			}
			
			// Tooltips
			$.fn.qtip.styles.tsf = {
					width: 400,
					border: { width: 4, radius: 4, color: '#BB0042' },
					background: '#FFFFFF',
					padding: 8,
					tip : 'leftMiddle',
					name: 'light'
			}
			$('a.tooltip').qtip({
				position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle' }},
				style: { name: 'tsf', tip : 'leftMiddle' },
				content: { prerender: true, text: false }
			});
			
			$('a.tooltip-left').qtip({
				position: { corner: { target: 'leftMiddle', tooltip: 'rightMiddle' }},
				style: { name: 'tsf', tip: 'rightMiddle' },
				content: { prerender: true, text: false }
			});
			
			
			$('marquee').marquee('marquee');
			
			$("#slide-buttons li a").click(function(event) {
				//event.preventDefault();
			});
			
			/*
			$('#voices').before('<div id="voices-pager">') 
			$('#voices').cycle({ 
				//speed:  'slow', 
				timeout: 7000, 
				pager:  '#voices-pager',
				pause: 1
				
			});
			*/
			
			$('.voice-box .thumb').css('opacity', 0.3); 
			$('.voice-box').hoverIntent({
				 interval: 100,
				 sensitivity: 7,
				 over: function() {
					voicesOpen(this);
				},
				 timeout: 200,
				 out: function() {
					voicesClose(this);
				}
			});
			// Event listener for actions when a slide is displayed
			$('#slides li').bind('slideShown', function(e, data) {
				// fade in slide text
				if ($('.slide-text',data)[0] != undefined) {
					$('.slide-text').hide();
					setTimeout("$('.slide-text').fadeIn('slow');", 200);
				}
				// display a default voice (11th) when voice tab is shown
				if ($('.voice-box',data)[0] != undefined) {
					voicesOpen($('.voice-box')[11], true);
				}
				
			});
			$('#slides li.active').trigger("slideShown", $('#slides li.active')[0]);
			
			
			$('#donate-home-link').click(function(event) {
				event.preventDefault();
				donateOpen();
			});
		}
		///// End Home Page Code
		
		$('a.button').wrapInner('<div class="button-wrap"></div>');
		
	}); // end autostart
	


////// DONATION BOX 

function donateOpen(ele) {
	donateToggle(ele, 'open');
}
function donateClose(ele) {
	donateToggle(ele, 'close');
}

function donateToggle(ele, toggleCmd) {
	if (toggleCmd == 'open') {
		donateIsOpen = false;
	} else {
		if (toggleCmd == 'close') {
			donateIsOpen = true;
		}
	}
	
	if (donateIsOpen) { 
		// Close
		var oldHeight = $(".donate-box", ele)[0].oldHeight;
		var oldWidth = $(".donate-box", ele)[0].oldWidth;
		$(".donate-paypal", ele).hide();		
		$(".donate-text", ele).show();
		$(".donate-box", ele).animate({ height: oldHeight, width: oldWidth }, 700, 'linear', function(){ $(".donate-box", ele).addClass('closed');});
		$(".donate-button", ele).html( $(".donate-button", ele)[0].oldHtml );
		donateIsOpen = false;
	} else {
		// Open
		var closeImage = $(".donate-box", ele)[0].closeImage;
		$(".donate-button img", ele).src = closeImage;
		$(".donate-box", ele).removeClass('closed');
		$(".donate-box", ele).animate({ height: "250px", width: "686px" }, 700);
		donateIsOpen = true;
	}
	PEPS.rollover.bindHover();
	return false;
}
////// END DONATION BOX 

////// SUBSCRIBE BOX
function subscribeOpen() {
	subscribeToggle('open');
}
function subscribeClose() {
	subscribeToggle('close');
}

function subscribeToggle(toggleCmd) {
	if (toggleCmd == 'open') {
		subscribeIsOpen = false;
	} else {
		if (toggleCmd == 'close') {
			subscribeIsOpen = true;
		}
	}
	
	if (subscribeIsOpen) { 
		// Close
		$("#subscribe-box").animate({ height: "26px", width: "206px" }, 700, 'linear', function(){ $("#subscribe-box").addClass('closed');});
		$("#subscribe-button").html(subscribeText);
		subscribeIsOpen = false;
	} else {
		// Open
		var h = $("#subscribe-contents").height();
		$("#subscribe-button").html('<img src="/wp-content/themes/sakyong2/images/btn-support-close.gif" class="rollover" alt="Close" />');
		$("#subscribe-box").removeClass('closed');
		$("#subscribe-box").animate({ height: h, width: "370px" }, 700);
		subscribeIsOpen = true;
	}
	PEPS.rollover.bindHover();
	return false;
}
//////// END SUBSCRIBE BOX


//////// VOICES GRID
function voicesOpen(parent, quick) {
	//First, close all open voices
	$('.voice-box').each( function() {
		voicesClose(this);
	});
	
	
	var em = false;
	// substitute large image
	if ($(parent).hasClass("em")) {
		var em = true;
		$(".large-thumb", parent).show();
		//$('.quote', parent).position().left = $(".large-thumb", parent).width();
	}
	var imageSize  = $(".thumb", parent).width();
	var marginSize = parseInt($(parent).css('padding-right').replace("px", ""));
	var thumbSize = imageSize + 2 * marginSize;
	var cols = Math.floor($('.voices-grid').outerWidth() / thumbSize);
	var rows = Math.floor($('.voices-grid').outerHeight() / thumbSize);
	var gridWidth  = cols * thumbSize;
	var gridHeight = rows * thumbSize;
	var col = ($(parent).position().left - $('.voices-grid').position().left + thumbSize) / thumbSize;
	var row = ($(parent).position().top - $('.voices-grid').position().top + thumbSize) / thumbSize;
	
	if (em) {
		var lgThumbBottomEdge = $('.large-thumb', parent).height() + $(parent).position().top - $('.voices-grid').position().top + marginSize;
		if (lgThumbBottomEdge > gridHeight) {
			$('.large-thumb', parent).css({'top': 'auto', 'bottom': 0});
		}
		
		$('.quote', parent).width(imageSize*4 + marginSize*6 - 20 +1);
	} else {
		$('.quote', parent).width(imageSize*4 + marginSize*6 - 20 +1);
	}

	// If quote goes over right edge, shift it to be on left of photo
	var quoteRightEdge = $('.quote', parent).width() + $(parent).position().left + thumbSize;
	if (em) {
		quoteRightEdge = quoteRightEdge + thumbSize;
	}
	if (quoteRightEdge > gridWidth) {
		$('.quote', parent).css('left', 'auto');
		$('.quote', parent).css('right', thumbSize +'px');
	} else {
		$('.quote', parent).css('right', 'auto');
		if (em) {
			$('.quote', parent).css('left', $(".large-thumb", parent).width() + 2 * marginSize + 'px');
		} else {
			$('.quote', parent).css('left', thumbSize+'px');
		}
	}
	
	// If in rightmost column, shift large thumb & quote a column to the left
	if ( em && col == cols) {
		$('.large-thumb',parent).css('left', (-1) * thumbSize +'px');
		$('.quote',parent).css('right', 2 * thumbSize +'px');
	}

	// If on bottom row make quote unfurl from bottom
	if (row == rows && $('.quote',parent).outerHeight() <= gridHeight) {
		$('.quote', parent).css('top', 'auto');
		$('.quote', parent).css('bottom', '0');
	} else {
		// Shift the quote a row up until it either fits or reaches the top of grid (or 20 rows)
		var i=0;
		var quoteBottomEdge = $('.quote', parent).outerHeight() + $(parent).position().top - $('.voices-grid').position().top + marginSize;
		while ( 
				quoteBottomEdge + parseInt($('.quote', parent).css('top').replace("px", "")) > gridHeight
				&& parseInt($('.quote',parent).css('top').replace('px',''))*(-1) < row*thumbSize-thumbSize 
				&& i < 20 
			) 
		{
			$('.quote', parent).css('top', parseInt($('.quote', parent).css('top').replace("px", "")) - thumbSize +'px');
			$('.large-thumb',parent).css('top', (-1) * thumbSize +'px');
			i++;
		}
	}

	$(parent).addClass('active');
	$(".thumb", parent).css('opacity', 1);
	if (!quick) {
		$('.quote', parent).slideDown('fast', function() {
			//$(this).dropShadow();
		});
	} else {
		$('.quote', parent).show();
		//$('.quote', parent).dropShadow();
	}
}

function voicesClose(parent) {
	//return true;
	if ($(parent).hasClass("em")) {
		$(".large-thumb", parent).hide();
	}

	$(parent).removeClass('active');
	//$('.quote', parent).removeShadow();
	$(".thumb", parent).css('opacity', 0.3);
	//$('.quote', parent).slideUp('fast');
	$('.quote', parent).hide();
}



/////// Clear input field function
$.fn.search = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
};






// Image rollover function: uses class ".rollover" and rollover image filename ending in "_o".  Start with PEPS.rollover.init();
// from: http://peps.ca/blog/easy-image-rollover-script-with-jquery/
PEPS = {};
PEPS.rollover =
{
   init: function()
   {
      this.preload();
     
	  this.bindHover();
   },

   bindHover: function()
   {
      $(".rollover").hover(
         function () { $(this).attr( 'src', PEPS.rollover.newimage($(this).attr('src')) ); },
         function () { $(this).attr( 'src', PEPS.rollover.oldimage($(this).attr('src')) ); }
      );
   },
   
   preload: function()
   {
      $(window).bind('load', function() {
         $('.rollover').each( function( key, elm ) { $('<img>').attr( 'src', PEPS.rollover.newimage( $(this).attr('src') ) ); });
      });
   },
   
   newimage: function( src )
   {  
      if ( src.search(/(_o\.[a-z]+)$/) == -1 ) {
		return src.substring( 0, src.search(/(\.[a-z]+)$/) ) + '_o' + src.match(/(\.[a-z]+)$/)[0];
	  } else {
		return src;
	  }
   },

   oldimage: function( src )
   {
      return src.replace(/_o\./, '.');
   }
};






/*
//Create your sharelet with desired properties and set button element to false
var object = SHARETHIS.addEntry({
title:'share',
summary: 'Sharing is good for the soul.'},
{button:false});
//Output your customized button
document.write('<span id="share"><img src="http://www.iamelephant.com/assets/share1.gif" />Share!</span>');
//Tie customized button to ShareThis button functionality.
var element = document.getElementById("share");
object.attachButton(element);
*/