/*******************************************************************************
	SPEAKING OF FAITH - Default Javascript
	Site-wide javascript functions for speakingoffaith.org
	
	DEVELOPERS
	Andy Dayton - adayton@americanpublicmedia.org
	Trent Gilliss - tgilliss@aamericanpublicmedia.org
	
	Last Updated: March 24, 2010
	
*******************************************************************************/


/*******************************************************************************
	JQUERY CODE
*******************************************************************************/

// Using the $jq variable to avoid conflict with
// Prototype javascript library
var $jq = jQuery.noConflict();

// These are all activated when the page loads
$jq(function() {
 
// -----------------------------------------------------------------------------
// SOF HEADER SEARCHBOX
// This script handles the searchbox beviours for the new SOF header, including
// auto-replacing the search prompt with empty text when the searchbox is
// clicked
// 
// -----------------------------------------------------------------------------

  var DEFAULT_SEARCHBOX_TEXT = "Search onBeing&hellip;";
 	var page_searchbox_text = $jq('#searchbox input.text').attr('value');
	
	// If there is no default text defined in markup, use the javascript-assigned default
  if( page_searchbox_text == (''||null)) { 
		page_searchbox_text = DEFAULT_SEARCHBOX_TEXT;
		$jq('#searchbox input.text').attr('value', page_searchbox_text);
	}
	// otherwise, save the value defined in markup for later 
	else page_searchbox_text = $jq('#searchbox input.text').attr('value'); 
		
	$jq('#searchbox input.text').focus(function(e) {
		// console.log("Focus!");
		$jq(this).addClass("active");
		if($jq(this).attr("value") == page_searchbox_text) $jq(this).attr("value", "");
	}); 
  
	$jq('#searchbox input.text').blur(function(e) {   
		// if no query has been entered, replace default text and deactivate
		if($jq(this).attr("value") == "") {
			$jq(this).attr("value", page_searchbox_text);
			$jq(this).removeClass("active");  
		} 
	});
 
// -----------------------------------------------------------------------------
// IMAGE CAPTIONS
//
// DEPENDENCIES:
// jQuery v1.2.6
// jquery.dimensions.js (v1.2)
// jquery.tooltip.js (v1.3)
// -----------------------------------------------------------------------------
  

	
	/* SAMPLE HTML CODE:
	
	<!-- IMAGE CAPTION start -->
	<div id="imageCaption" class="main">
		<div id="imageCaptionContent">
		<h4>About the Image</h4>
			<p>Giancarlo Neri's public sculpture "The Writer" on Hampstead Heath, London.</p>
		</div>
		<a id="imageCaptionButton" href="http://flickr.com/photos/acb/32077684/" title="Click the link to view Andrew Bulhak's photo on flickr."><cite>+ (photo: Andrew Bulhak/Flickr)</cite></a>
	</div>
	<!-- IMAGE CAPTION end -->
	
	END SAMPLE HTML CODE */
  if(jQuery.tooltip) {
		var append = ''; 
	
		// If the image caption link has an href attribute, use the pointer cursor
		// and link to that url.
		if($jq("a#imageCaptionButton").attr("href") != undefined) {
			$jq("a#imageCaptionButton").css("cursor", "pointer");
			// Set the link's title attribute to be appended to the image caption.
			append = '<p class="note">('+$jq("a#imageCaptionButton").attr("title")+')</p>'
		}
	
		// Assign tooltip class to caption button
		$jq("a#imageCaptionButton").tooltip({
			bodyHandler: function() {
				// Add the caption content, append the link title attribute if
				// applicable
				return $jq("#imageCaptionContent").html()+append;
			},
			showURL: false,
			delay: 100
		}); 
	}
// -----------------------------------------------------------------------------
// ADDTHIS FUNCTIONS
//
// DEPENDENCIES:
// Must import the adthis widget library:
// <script type="text/javascript" src="http://s7.addthis.com/js/200/addthis_widget.js"></script>
// Also must set the page var "addthis_pub" to "speakingoffaith" before
// loading the widget library
// -----------------------------------------------------------------------------

	/* SAMPLE HTML CODE:
	
  	<!-- ADDTHIS LINK SHARING start -->
  	<div class="nav_box">
      <h3>Spread the Word</h3>
      <img style="display:none;" src="images/thumb.jpg" alt="The Novelist as God" />
      <a href="http://www.addthis.com/bookmark.php" id="addthis_email">&raquo; <strong>Email</strong></a>
      &nbsp;&brvbar;
      <a href="http://www.addthis.com/bookmark.php?v=20" id="addthis_share">+ <strong>Share</strong></a>
	</div>
  	<!-- ADDTHIS LINK SHARING end -->
	
	END SAMPLE HTML CODE */

	// Set the program title from the page's title element
	// 	"Program Title [Speaking of Faith&#174; from American Public Media]"
	// 	---> "SOF: Program Title"
	var addthis_prog_title = "Being: " + $jq('title').html().match(/(.+)\s\[(.+)\]/)[1];
	
	// Email button
	$jq("a#addthis_email").click(function(event) {
		event.preventDefault();
		addthis_open(this, 'email', '[URL]', addthis_prog_title);	
	});
	
	// Print button
	// (doing this the old school way until addthis supports print only)
	$jq("a#addthis_print").click(function(event) {
		event.preventDefault();
		// addthis_open(this, 'print', '[URL]', addthis_prog_title);
		window.print()	
	});
	
	// Share button
	$jq("a#addthis_share").hover(
		function() {
			addthis_open(this, '', '[URL]', addthis_prog_title);	
		},
		function() { addthis_close() }
	);	
	$jq("a#addthis_share").click( function(event) {
		event.preventDefault();
		addthis_sendto();
	});

// -----------------------------------------------------------------------------
// BASIC POPUP
// This isn't really completed yet, but the idea is to have a simple,
// non-obtrusive popup function for the site
// -----------------------------------------------------------------------------
	
	/* SAMPLE HTML CODE:
	
  	<a href="http://speakingoffaith.org" title="Speaking of Faith" rel="popup[300, 600]">Speaking of Faith</a>
	
	END SAMPLE HTML CODE */	
	$jq("a[rel^='popup']").click(function(event) {
		event.preventDefault();
		var window_attr = $jq(this).attr('rel').match(/(\w+)(?:\[(\d+)(?:\,\s*)(\d+)\])?/);
		var title = $jq(this).attr('title');
		// console.log(window_attr);
		if(window_attr.length > 2) {
			var attr_str = "width="+window_attr[2]+",height="+window_attr[3];
			// console.log(attr_str);
			window.open( $jq(this).attr('href'), title, attr_str);			
		} else {
			window.open( $jq(this).attr('href'), title);
		}           
		
	}); 
	
	// -----------------------------------------------------------------------------
	// JQUERY MASONRY
	// If masonry plugin is loaded, apply default settings
	// http://desandro.com/resources/jquery-masonry
	// -----------------------------------------------------------------------------		
	if(jQuery.masonry) {
		$jq('.masonry').masonry({ columnWidth: 123 });
	}
	

	// -----------------------------------------------------------------------------
	// PROGRAM INDEX PAGE REFLECTION COUNT
	// This script finds any link with the class "fp_read_others" and appends a
	// a reflections count to the end of that link. It pulls from the Your Voices,
	// Your Stories application xml.
	//
	// If there is a 'config_name' global variable set, this will be used to build
	// the query string for the XML (the name of the your_stories configuration .ini)
	// is needed to pull the necessary data). Otherwise, the script will attempt to
	// use the name of the program directory.  
	//
	// Added a javascript section on the show's index page to set the config_name variable.  This is not needed if the .ini file name matches the program directory.  However, if it does not, you need to set it.
	// Probably faster to set it anyway so that the regex doesn't need to process before displaying.
	//
	//-----------------------------------------------------------------------------	
	
	if($jq("a.fp_read-others").size() > 0) {
		// if the "config_name" variable wasn't manually set,
		// try and grab it from the program folder name
		if (typeof(config_name) == 'undefined') { 
			// This RegEx pattern looks for the directory name for
			// in the document's path. The pattern it searches for
			// is: [...]/programs/YYYY/program-name/[...]    
		 	var pattern = /^.*\/programs\/\d{4}\/([A-z0-9-_]+)\/.*$/;
			var match = window.location.pathname.match(pattern);
			// console.log("Match: "+match);
			if (match != null) { config_name = match[1]; }      
		}
		
		// if the match worked, or the variable was already set
		if (typeof(config_name) != 'undefined' && config_name != null) { 
		  var map_data_path = '/www_publicradio/applications/formbuilder/projects/your_story/category.php?format=xml&name='+config_name;
		 	$jq.ajax({
				type: 'GET',
				url: map_data_path,
				dataType: 'xml',
				success: function(xml) {
					var n = $jq(xml).find('response').size();   
					$jq("a.fp_read-others").append(' ('+n+')');
				}
			}); 
		}
	}
	
});


 

/*******************************************************************************
	LEGACY FUNCTIONS (DEPRECATED)
	These are included to avoid breaking old sites, but shouldn't be used.
*******************************************************************************/

// print this page script
function print_me() {
	if (window.print) { 
		window.print()
	} else {
		var platform = navigator.platform.toUpperCase()
		var browser = navigator.appName.toUpperCase()
		if (platform == "MACPPC" && browser == "NETSCAPE") {
			alert('Please use command-p to print.')
		} else {
			alert('Please use control-p to print.')
		}
	}
}

// size slideshow window
function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=700');");
}

// size player window
var popUpWin=0;
function popUpWindow(URLStr, left, top, width, height)
{
  if(popUpWin)
  {
    if(!popUpWin.closed) popUpWin.close();
  }
  popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}
//

