/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
;
(function(document, $) {
	$(document).ready(init);
	function init() {	
		var program_detail = $('#program-detail'),
		popup_component = $('#popup-component');
		if (program_detail) {
			addProgramTabsEvent(program_detail);
		}
		if (popup_component) {
			enablePopups(popup_component);
		}
		
		addNavigationArrows();
		addSearchFormEvents();
		addPrintEvents();
		addFormEvents();
		moveToToolbar('#block-workbench-block');
		moveToToolbar('#primary-local-tasks');
		
		$("#stateList").change(function(){
	          if ($("option:selected").attr("value") != "") window.location.href = "#" + $("option:selected").attr("value");
	     });
	
		addSupplementalAnalytics();
	}

	function addSupplementalAnalytics() {
		$('a[href$=pdf]').each(function() {
			$(this).click(function() {
					var href = $(this).attr('href'),
					url_splits = window.location.href.split('/'),
					program = url_splits[3];
										
					if (_gaq) {
						_gaq.push(['_trackEvent', 'PDF', program + ' ' + href]);
					}
			});
		});

		$('a[href^=http]').each(function() {
		    var href = $(this).attr('href');
		    if (href.substr(0, 5) == 'http:' || href.substr(0, 6) == 'https:') {
		        if (href.search("/^http[s]?:\/\/www\.interexchange\.org\/") == -1) {
        			$(this).click(function() {
    					var url_splits = window.location.href.split('/'),
    					program = url_splits[3];
									
    					if (_gaq) {
    						_gaq.push(['_trackEvent', 'External', program + ' ' + href]);
    					}
        			});
    			}
			}
		});
		
		// track when the user clicks on the email link
		$('.popups-form-noupdate').click(function() {
			pageTracker._trackPageview('/v/contact-popup');
		});
	
		$(document).bind('popups_form_success', function() {
			pageTracker._trackPageview('/v/contact/thank-you-popup');
		});

	}
	
	function addNavigationArrows() {
		$('#program-menu .menu .active').parent('li').addClass('active-li');
	}
	
	function moveToToolbar(selector) {
		if ($(selector).length && $('#toolbar').length) {
			$(selector + ' .contextual-links-wrapper').remove();
			$(selector)
			    .removeClass()
			    .addClass('clearfix, toolbar-menu');

			$('#toolbar').append($(selector));
			$('#toolbar').append('<div class="toolbar-drawer clearfix"></div>');
			$(selector).show();
			$('body').css('padding-top', $('#toolbar').height() + 'px');
		}
  }
    
	function addFormEvents() {
		if ($('#qforms-submit-form, .custom-form').length) {
		  $(':input').focus( function() {
		    $('#qforms-submit-form div.active, .custom-form div.active').removeClass('active');
		    $(this).parent('div').addClass('active');
		  });
		  $(':input').blur(function() {
		    $(this).parent('div').removeClass('active');
		  });
		}
	}
	
	function addPrintEvents() {
		$('#print-button').click(function() {
			$('body').printElement({printMode: 'popups', overrideElementCSS: ['/' + Drupal.settings.path_to_theme + '/css/print.css']});
			return false;
		})
	}
	
	
	function addProgramTabsEvent(detail) {
		// check if there is a cookie of the last tab
		var index = 0;
		if (window.location.href == $.cookie('last_page') && $.cookie('last_tab')) {
			index = $.cookie('last_tab');
		}
				
		var items = detail.find('#tabs li'),
		tab_contents = detail.find('.tab-content-container'),
		previous_content = $(tab_contents[index]),
		previous_item = $(items[index]); // default the previous item to the first list item
		
		previous_item.addClass('selected');
		previous_content.show();
		
		items.each(function () {
			$(this).click(function (event) {
				var item = $(event.currentTarget),
				item_id = item.attr('id');

				// set the clicked tab as selected and the previous one as not
				if (previous_item) {
					previous_item.removeClass('selected');
				}

				previous_item = item;
				previous_item.addClass('selected');
				
				var index_value = item_id == 'first-tab' ? 0 : 1;
				$.cookie('last_tab', index_value);
				$.cookie('last_page', window.location.href);
				
				// Show the new content and hide the old one	
				if (previous_content) {
					previous_content.hide();
				}

				previous_content = $('#' + item_id + '-content-container');
				previous_content.show();
								
				return false;
			});
		});
	}
	
	function addSearchFormEvents() {
		$('input[name=keys]').focus(function() {
			var value = $(this).val();
			
			if (value == 'Search') {				
				$(this).val('');
			}
		});
	}
	
	function enablePopups(popup_component) {
		var selected_popup;
		popup_component.find('ul a').each(function() {
			var anchor = $(this);
			anchor.hover(
				function(event) {
					var popup_type = anchor.parent().attr('class');
					if (selected_popup && selected_popup.hasClass(popup_type)) {
						return;
					}

					// hide the previous popup
					if (selected_popup) {
						selected_popup.fadeOut(300);
					}

					// find the correct popup
					// when one is clicked then make the corresponding popup appear
					selected_popup = popup_component.find('.popup.' + popup_type);
					selected_popup.fadeIn(300);
				
					// look for the close button click
					// if it's clicked hide the current popup
					selected_popup.find('.close-button').click(close_popup);
				
					return false;
				},
				function (event) {}
			);
			
			function close_popup(event) {
					// if ($(event.toElement).attr('id') != 'popup-component') {
					// 	return;
					// }
					
					selected_popup.fadeOut(300);
					selected_popup = null;
					return false;
			}
		});
	}
})(document, jQuery)
;
/// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.2
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
*  Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.printElement 
*  Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement
*  jQuery plugin page : http://plugins.jquery.com/project/printElement 
*  
*  Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100)
*  For their great contributions!
* 
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*   
*   Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead
*/
;(function(g){function k(c){c&&c.printPage?c.printPage():setTimeout(function(){k(c)},50)}function l(c){c=a(c);a(":checked",c).each(function(){this.setAttribute("checked","checked")});a("input[type='text']",c).each(function(){this.setAttribute("value",a(this).val())});a("select",c).each(function(){var b=a(this);a("option",b).each(function(){b.val()==a(this).val()&&this.setAttribute("selected","selected")})});a("textarea",c).each(function(){var b=a(this).attr("value");if(a.browser.b&&this.firstChild)this.firstChild.textContent=
b;else this.innerHTML=b});return a("<div></div>").append(c.clone()).html()}function m(c,b){var i=a(c);c=l(c);var d=[];d.push("<html><head><title>"+b.pageTitle+"</title>");if(b.overrideElementCSS){if(b.overrideElementCSS.length>0)for(var f=0;f<b.overrideElementCSS.length;f++){var e=b.overrideElementCSS[f];typeof e=="string"?d.push('<link type="text/css" rel="stylesheet" href="'+e+'" >'):d.push('<link type="text/css" rel="stylesheet" href="'+e.href+'" media="'+e.media+'" >')}}else a("link",j).filter(function(){return a(this).attr("rel").toLowerCase()==
"stylesheet"}).each(function(){d.push('<link type="text/css" rel="stylesheet" href="'+a(this).attr("href")+'" media="'+a(this).attr("media")+'" >')});d.push('<base href="'+(g.location.protocol+"//"+g.location.hostname+(g.location.port?":"+g.location.port:"")+g.location.pathname)+'" />');d.push('</head><body style="'+b.printBodyOptions.styleToAdd+'" class="'+b.printBodyOptions.classNameToAdd+'">');d.push('<div class="'+i.attr("class")+'">'+c+"</div>");d.push('<script type="text/javascript">function printPage(){focus();print();'+
(!a.browser.opera&&!b.leaveOpen&&b.printMode.toLowerCase()=="popup"?"close();":"")+"}<\/script>");d.push("</body></html>");return d.join("")}var j=g.document,a=g.jQuery;a.fn.printElement=function(c){var b=a.extend({},a.fn.printElement.defaults,c);if(b.printMode=="iframe")if(a.browser.opera||/chrome/.test(navigator.userAgent.toLowerCase()))b.printMode="popup";a("[id^='printElement_']").remove();return this.each(function(){var i=a.a?a.extend({},b,a(this).data()):b,d=a(this);d=m(d,i);var f=null,e=null;
if(i.printMode.toLowerCase()=="popup"){f=g.open("about:blank","printElementWindow","width=650,height=440,scrollbars=yes");e=f.document}else{f="printElement_"+Math.round(Math.random()*99999).toString();var h=j.createElement("IFRAME");a(h).attr({style:i.iframeElementOptions.styleToAdd,id:f,className:i.iframeElementOptions.classNameToAdd,frameBorder:0,scrolling:"no",src:"about:blank"});j.body.appendChild(h);e=h.contentWindow||h.contentDocument;if(e.document)e=e.document;h=j.frames?j.frames[f]:j.getElementById(f);
f=h.contentWindow||h}focus();e.open();e.write(d);e.close();k(f)})};a.fn.printElement.defaults={printMode:"iframe",pageTitle:"",overrideElementCSS:null,printBodyOptions:{styleToAdd:"padding:10px;margin:10px;",classNameToAdd:""},leaveOpen:false,iframeElementOptions:{styleToAdd:"border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;",classNameToAdd:""}};a.fn.printElement.cssElement={href:"",media:""}})(window);
;

