// Javascript by Nathaniel Kerksick, Institute for Policy Studies unless otherwise noted
// E-mail address found on staff pages
// This code may be copied, attribution must be given. See:
// http://creativecommons.org/licenses/by/3.0/


//nyroModal YouTube Popup
$(function() {
  $.fn.nyroModal.settings.processHandler = function(settings) {
    var from = settings.from;
    if (from && from.href && from.href.indexOf('http://www.youtube.com/watch?v=') == 0) {
      $.nyroModalSettings({
        type: 'swf',
        height: 355,
        width: 425,
        url: from.href.replace(new RegExp("watch\\?v=", "i"), 'v/')
      });
    }
  };
});


// starting the script on page load
$(document).ready(function(){
	tooltip();

	// Add print functionality
         $('#print a').click(function() {
			window.print();
			return false;
		});

	$('#uwsignup-email').submit(function() {
		alert("Thanks for signing up. Please add info@ips-dc.org to your safe senders list. You can unsubscribe any time you wish from a link at the bottom of every Unconventional Wisdom.");
		return true;
	});
	//edl added 7/21/11 for ips email list subs & unsubs
	$('#ips-email').submit(function() {
	alert("Thanks for signing up. Please add info@ips-dc.org to your safe senders list. You can unsubscribe any time you wish from a link at the bottom of every email from IPS.");
		return true;
	});
	
	$('#ips-email-unsub').submit(function() {
	alert("Unsubscription successful. Sorry to see you go! Please let us know at info@ips-dc.org if there's anything we can be doing better.");
		return true;
	});
	
/*
	$('.project .media_hits li:odd').addClass('odd');
	$('.project .media_hits li:even').addClass('even');
	
	$('.tab_wrapper tr:odd').addClass('odd');
	$('.tab_wrapper tr:even').addClass('even');
*/

	// Automatically add captions to images marked with a captions class
	// See jQuery capty plugin below
	$('.img-left-caption').capty({ animation: 'fixed' });
	$('.img-right-caption').capty({ animation: 'fixed' });
	$('.img-center-caption').capty({ animation: 'fixed' });

	//added 8/11/11 edl: scripts for social share
	// Load Plus One Button
	jQuery.getScript('https://apis.google.com/js/plusone.js');
		
	// Load Tweet Button Script
	jQuery.getScript('http://platform.twitter.com/widgets.js');
		
	// Load LinkedIn button
	jQuery.getScript('http://platform.linkedin.com/in.js');

	// Load StumbleUpon button
	// jQuery.getScript('http://www.stumbleupon.com/hostedbadge.php?s=1&a=1&d=stumbleupon-button');

});



// Tooptip
this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = -130;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$("a.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};



// COMMON FORMS BEHAVIORS:

function searchDEselect() {
document.forms["sitesearch"].q.value = 'Search IPS';
}

function searchselect() {
document.forms["sitesearch"].q.focus();
document.forms["sitesearch"].q.value = 'Type & Press ENTER';
document.forms["sitesearch"].q.select();
setTimeout("searchDEselect();",10000);
}

function uwDEselect() {
document.forms["uwsignup-email"].Email.value = 'your@email.org';
}

function uwselect() {
document.forms["uwsignup-email"].Email.focus();
document.forms["uwsignup-email"].Email.value = 'Type e-mail & ENTER';
document.forms["uwsignup-email"].Email.select();
setTimeout("uwDEselect();",10000);
}

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}


// Smooth scroll

/* Smooth scrolling
   Changes links that link to other parts of this page to scroll
   smoothly to those links rather than jump to them directly, which
   can be a little disorienting.
   
   sil, http://www.kryogenix.org/
   
   v1.0 2003-11-11
   v1.1 2005-06-16 wrap it up in an object
*/

var ss = {
  fixAllLinks: function() {
    // Get a list of all links in the page
    var allLinks = document.getElementsByTagName('a');
    // Walk through the list
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if ((lnk.href && lnk.href.indexOf('#') != -1) && 
          ( (lnk.pathname == location.pathname) ||
	    ('/'+lnk.pathname == location.pathname) ) && 
          (lnk.search == location.search)) {
        // If the link is internal to the page (begins in #)
        // then attach the smoothScroll function as an onclick
        // event handler
        ss.addEvent(lnk,'click',ss.smoothScroll);
      }
    }
  },

  smoothScroll: function(e) {
    // This is an event handler; get the clicked on element,
    // in a cross-browser fashion
    if (window.event) {
      target = window.event.srcElement;
    } else if (e) {
      target = e.target;
    } else return;

    // Make sure that the target is an element, not a text node
    // within an element
    if (target.nodeName.toLowerCase() != 'a') {
      target = target.parentNode;
    }
  
    // Paranoia; check this is an A tag
    if (target.nodeName.toLowerCase() != 'a') return;
  
    // Find the <a name> tag corresponding to this href
    // First strip off the hash (first character)
    anchor = target.hash.substr(1);
    // Now loop all A tags until we find one with that name
    var allLinks = document.getElementsByTagName('a');
    var destinationLink = null;
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if (lnk.name && (lnk.name == anchor)) {
        destinationLink = lnk;
        break;
      }
    }
    if (!destinationLink) destinationLink = document.getElementById(anchor);

    // If we didn't find a destination, give up and let the browser do
    // its thing
    if (!destinationLink) return true;
  
    // Find the destination's position
    var destx = destinationLink.offsetLeft; 
    var desty = destinationLink.offsetTop;
    var thisNode = destinationLink;
    while (thisNode.offsetParent && 
          (thisNode.offsetParent != document.body)) {
      thisNode = thisNode.offsetParent;
      destx += thisNode.offsetLeft;
      desty += thisNode.offsetTop;
    }
  
    // Stop any current scrolling
    clearInterval(ss.INTERVAL);
  
    cypos = ss.getCurrentYPos();
  
    ss_stepsize = parseInt((desty-cypos)/ss.STEPS);
    ss.INTERVAL =
setInterval('ss.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);
  
    // And stop the actual click happening
    if (window.event) {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
    if (e && e.preventDefault && e.stopPropagation) {
      e.preventDefault();
      e.stopPropagation();
    }
  },

  scrollWindow: function(scramount,dest,anchor) {
    wascypos = ss.getCurrentYPos();
    isAbove = (wascypos < dest);
    window.scrollTo(0,wascypos + scramount);
    iscypos = ss.getCurrentYPos();
    isAboveNow = (iscypos < dest);
    if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
      // if we've just scrolled past the destination, or
      // we haven't moved from the last scroll (i.e., we're at the
      // bottom of the page) then scroll exactly to the link
      window.scrollTo(0,dest);
      // cancel the repeating timer
      clearInterval(ss.INTERVAL);
      // and jump to the link directly so the URL's right
      location.hash = anchor;
    }
  },

  getCurrentYPos: function() {
    if (document.body && document.body.scrollTop)
      return document.body.scrollTop;
    if (document.documentElement && document.documentElement.scrollTop)
      return document.documentElement.scrollTop;
    if (window.pageYOffset)
      return window.pageYOffset;
    return 0;
  },

  addEvent: function(elm, evType, fn, useCapture) {
    // addEvent and removeEvent
    // cross-browser event handling for IE5+,  NS6 and Mozilla
    // By Scott Andrew
    if (elm.addEventListener){
      elm.addEventListener(evType, fn, useCapture);
      return true;
    } else if (elm.attachEvent){
      var r = elm.attachEvent("on"+evType, fn);
      return r;
    } else {
      alert("Handler could not be removed");
    }
  } 
}

ss.STEPS = 25;

ss.addEvent(window,"load",ss.fixAllLinks);



// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}



/**
 * jQuery Capty - A Caption Plugin - http://wbotelhos.com/capty
 * ---------------------------------------------------------------------------------
 *
 * jQuery Capty is a plugin that creates captions over the images.
 *
 * Licensed under The MIT License
 *
 * @version         0.2.1
 * @since           12.18.2010
 * @author          Washington Botelho dos Santos
 * @documentation   wbotelhos.com/capty
 * @twitter         twitter.com/wbotelhos
 * @license         opensource.org/licenses/mit-license.php MIT
 * @package         jQuery Plugins
 *
 * Usage with default values:
 * ---------------------------------------------------------------------------------
 * $('#capty').capty();
 *
 * <img id="capty" src="image.jpg" alt="Super Mario Bros.&reg;" width="150" height="150"/>
 *
 * This plugin has been modified for the purposes of this website.
 *
 */

;(function($) {

	$.fn.capty = function(settings) {
		var options = $.extend({}, $.fn.capty.defaults, settings);

		if (this.length == 0) {
			debug('Selector invalid or missing!');
			return;
		} else if (this.length > 1) {
			return this.each(function() {
				$.fn.capty.apply($(this), [settings]);
			});
		}

		var $this		= $(this),
			name		= $this.attr('name'),
			$caption	= $('<div class="' + options.cCaption + '"/>'),
			$elem		= $this;

		if ($this.attr('alt').length == 0) { return; }

		if ($this.parent().is('a')) {
			$elem = $this.parent();
		}

		// class should be one of: 
		// img-left-caption, img-right-caption, img-center-caption
		var img_align;
		var pad_left = "8px";
		var pad_right = "8px";
		if ($this.hasClass('img-right-caption')) { 
			img_align = 'right'; 
			pad_right = "0";
		}
		else if ($this.hasClass('img-center-caption')) { 
			img_align = 'center'; 
		}
		else if ($this.hasClass('img-left-caption')) { 
			img_align = 'left'; 
			pad_left = '0'; 
		}

		var $image		= $elem.wrap('<div class="' + options.cImage + '"/>').parent(),
			$wrapper	= $image.wrap('<div style="float: '+img_align+'; padding-top: 0; padding-bottom: 0; padding-left: '+pad_left+'; padding-right: '+pad_right+'; border: none"><div class="' + options.cWrapper + '"/>').parent();

		// Take the CSS width of the image and add to it to give the
		// div a little space.
		var div_width = parseInt($this.css('width'));
		div_width = div_width + 24;
		div_width = div_width + "px";

		$wrapper.css({
			float:		'left',
			width:		div_width
		});


		$caption.css({
			padding:	'6px'
		})

		.click(function(evt) {
			evt.stopPropagation();
		})
		.appendTo($wrapper);

		if (name) {
			var $content = $(name);

			if ($content.length) {
				$content.appendTo($caption);
			} else {
				$caption.html('<span style="color: #F00;">Content invalid or missing!</span>');
			}
		} else {
			$caption.html($this.attr('alt'));
		}

		if (options.prefix) {
			$caption.prepend(options.prefix);
		}

		if (options.sufix) {
			$caption.append(options.sufix);
		}

		if (options.animation == 'slide') {
			$wrapper.hover(
				function() {
					$caption.animate({ top: (-1 * options.height) }, { duration: options.speed, queue: false });
				},
	    		function() {
					$caption.animate({ top: 0 }, { duration: options.speed, queue: false });
				}
	    	);
		} else if (options.animation == 'fade') {
			$caption.css({
				opacity:	0,
				top:		(-1 * options.height) + 'px'
			});

			$wrapper.hover(
				function() {
					$caption.stop().animate({ opacity: options.opacity }, options.speed);
				},
	    		function() {
					$caption.stop().animate({ opacity: 0 }, options.speed);
				}
	    	);
		} else if (options.animation == 'fixed') {
			$caption.css('top', (-1 * options.height) + 'px');
		} else {
			debug($this.attr('id') + ': invalid animation!');
		}

		return $this;
	};

	function debug(message) {
		if (window.console && window.console.log) {
			window.console.log(message);
		}
	};

	$.fn.capty.defaults = {
		animation:	'slide',
		cCaption:	'ips-caption',
		cImage:		'',
		cWrapper:	'capty-wrapper',
		height:		30,
		opacity:	.7,
		prefix:		'',
		speed:		200,
		sufix:		''
	};

})(jQuery);

