//Setup two different servers for URLs
//var staticServer = 'http://methproject.org';
var dynamicServer = "http://origin.methproject.org";
var staticServer = (dynamicServer.indexOf(window.location.hostname) != -1) ? 'http://www.methproject.org' : 'http://' + window.location.hostname;

// disable dynamicServer, all previously dynamic pages are static and in svn now
dynamicServer = staticServer;

// State Array: contains data for link behavior
var stateList = [
		["arizona","AZ","http://www.facebook.com/pages/Arizona-Meth-Project/114096508629626?sk=wall","MethProject",""],
		["colorado","CO","http://www.facebook.com/coloradomethproject?sk=wall","coloradomethproject","http://twitter.com/COMethProject"],
		["georgia","GA","http://www.facebook.com/GeorgiaMethProject","GeorgiaMethProject","http://www.twitter.com/gamethproject"],
		["hawaii","HI","http://www.facebook.com/hawaiimethproject?sk=wall","hawaiimethproject","http://twitter.com/HawaiiMeth"],
		["idaho","ID","http://www.facebook.com/IdahoMethProject","IdahoMethProject","https://twitter.com/IDMethProject"],
		["montana","MT","http://www.facebook.com/MontanaMethProject","MontanaMethProject",""],
		["wyoming","WY","http://www.facebook.com/WyomingMethProject","WyomingMethProject",""],
		["national","MI","http://www.facebook.com/MethProject","MethProject",""]
	];

//populate a reset with ["flash_object_id",injectionFunction,jQueryObject_before_swfobject]
var flashResets = [null,null,null,null,null,null,null];
var textNumbers = {"one":1,"two":2,"three":3,"four":4,"five":5,"six":6};

function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

var isIE8 = (getInternetExplorerVersion() == 8);
var isIE7 = (getInternetExplorerVersion() == 7);

function navClick(obj) {
	if(isiDevice()) {
		touchClear();
	}
	$('.subnav li img').removeClass("active");
	$('.nextStepNav').hide();
	for (i = 0; i < $('.subnav li img').length; i++) {
		//$($('.subnav li img')[i]).attr("src",$($('.subnav li img')[i]).attr("src").replace("over","off"));
		$($('.subnav li img')[i]).parent().fadeTo(1, .5);
		$('.subnav li img').removeClass("on");
		$('.subnav li img').addClass("off");
	}
	//$(obj).attr("src",$(obj).attr("src").replace("off","over"));
	$(obj).parent().fadeTo(1, 1);
	$(obj).removeClass("on");
	$(obj).addClass("active");
	
	$(".question .subnav ul li img.off").parent().hover(
		function () { $(this).css("opacity","1"); },
		function () { $(this).css("opacity",".5");}
	);

	$(".question .subnav ul li img.off.active").parent().hover(
		function () { $(this).css("opacity","1"); }
	);


	//Show Content
	$('.answer').hide();
	$('.answer').removeClass('currentAnswer')

	$('.' + obj.id.replace("nav_", "")).show();
	
	//Pause all HTML5 Video and Audio
	try {
		var allVids = $('video');
		for (i=0; i<allVids.length;i++) {
			vidObj = allVids.get(i);
			vidObj.pause();	
			if(isiDevice()) { // hide video after pausing on ipad to hide flash
				$(vidObj).css({"display":"none"});
			}
		}
	} catch(e) {}
	try {
		var allAuds = $('audio');
		for (i=0; i<allAuds.length;i++) {
			audObj = allAuds.get(i);
			audObj.pause();	
		}
	} catch(e) {}
	
	
	$('.' + obj.id.replace("nav_", "")).addClass("currentAnswer");
	$('.' + obj.id.replace("nav_", "")).trigger('madeActive');
	
	//Used by The Look of Meth - DO NOT REMOVE
	if(isiDevice()) {
		$(window).trigger('madeActive');
	}
	
	$(window).unbind('hashchange');
	
	//Set Deeplink
	if(window.location.hash != "") {
		if(window.location.hash.toLowerCase() != ("#" + obj.title.replace(/[ ]/g, '-').replace(/['";:,.\/?\\]/g, '')).toLowerCase()) {
			//Do not rewrite if there is simply a case difference
			window.location.hash = "#" + obj.title.replace(/[ ]/g, '-').replace(/['";:,.\/?\\]/g, '');
		}
	} else {
		window.location.replace(window.location.href + "#" + obj.title.replace(/[ ]/g, '-').replace(/['";:,.\/?\\]/g, ''));
	}

	$(window).bind('hashchange', function() {
	  checkDeeplink();
	});

	
	fireAnswerPageView();
	
	//Unload Flash
	for(i=1; i<7; i++) {
		//Reset has been set by page
		if(flashResets[i] != null) {
			//Flash has already replaced the div
			if($('div#'+flashResets[i][0]).length == 0) {
				//Return original content
				$('#'+flashResets[i][0]).replaceWith(flashResets[i][2]);
			}
		}
	}
	
	//Load Flash
	if (flashResets[textNumbers[obj.id.replace("nav_", "")]] != null) {
		swfObjectCall = flashResets[textNumbers[obj.id.replace("nav_", "")]][1].replace(");", ", swfObjectCallback);");
		eval(swfObjectCall);
	}

	//Show sharing in case video nav hide has hidden it.
	showShare();
	//Play Current HTML5 Video or Audio
	if(isiDevice()) {
		try {
			var vidObj = $('.' + obj.id.replace("nav_", "") + ' video').get(0);
			var vidItemParent = $(vidObj).parent();
			var vidSRC = vidObj.currentSrc;
			$("source",vidItemParent).remove();
			$(vidItemParent).append($("source",vidObj));
			vidObj.src = vidSRC; 
			vidObj.play(); 
			var playvideoWait = setTimeout(function () {
				//hide blink during new load
				$(vidObj).css({"display":""});
				clearInterval(playvideoWait);
			}, 1000);
			/*var vidObj = $('.' + obj.id.replace("nav_", "") + ' video').get(0);
			vidObj.play(); */
			
		} catch(e) { }
			
		try {
			var audObj = $('.' + obj.id.replace("nav_", "") + ' audio').get(0);
			audObj.play();
		} catch(e) { }
	}
}

function swfObjectCallback(e) {
	document.title = initialTitle;

	if (!e.success && !isiDevice()) {
		resetDivClass = $('.currentAnswer').attr('class').replace("answer","").replace("currentAnswer","").replace(" ","").replace(" ","")
		resetDivID = flashResets[textNumbers[resetDivClass]][0];
		$('#'+resetDivID).html('<a href="http://get.adobe.com/flashplayer/" style="text-decoration:none" target="getFlash"><img src="/img/get_flash_player_button.gif"/></a><br/><br/>You need <a href="http://get.adobe.com/flashplayer/" style="text-decoration:underline;color:#fff" target="getFlash">Flash</a> to view this video content.');
		//$('.currentAnswer').html('You need <a href="http://get.adobe.com/flashplayer/">Flash</a> to view this video content.');
	}
}

function swfObjectCallbackRadio(e) {
	if (!e.success && !isiDevice()) {
		$('#'+e.id).html('<a href="http://get.adobe.com/flashplayer/" style="text-decoration:none" target="getFlash"><img src="/img/get_flash_player_button.gif"/></a><br/>You need <a href="http://get.adobe.com/flashplayer/" style="text-decoration:underline;color:#fff" target="getFlash">Flash</a><br/>to listen to this content.');
	}
}

function swfObjectCallbackOnline(e) {
	if (!e.success && !isiDevice()) {
		$('#'+e.id).html('<a href="http://get.adobe.com/flashplayer/" style="text-decoration:none" target="getFlash"><img src="/img/get_flash_player_button.gif"/></a><br/><br/>You need <a href="http://get.adobe.com/flashplayer/" style="text-decoration:underline;color:#fff" target="getFlash">Flash</a><br/>to view this content.');
	}
}



function MM_preloadImages() { //v3.0
	var d = document;
	if (d.images) {
		if (!d.MM_p) d.MM_p = new Array();
		var i, j = d.MM_p.length,
			a = MM_preloadImages.arguments;
		for (i = 0; i < a.length; i++)
		if (a[i].indexOf("#") != 0) {
			d.MM_p[j] = new Image;
			d.MM_p[j++].src = a[i];
		}
	}
}

function Get_Cookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split(';');
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	for (i = 0; i < a_all_cookies.length; i++) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split('=');


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if (cookie_name == check_name) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if (a_temp_cookie.length > 1) {
				cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found) {
		return null;
	}
}

function Set_Cookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + (";path=/" );
	//document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");
}


function setStateCookie(c_name, value, exdays) {
/*
	var exdate = new Date();
	//	var c_name= google.loader.ClientLocation.address.region + "meth";
	var c_name = "sitestate";
	exdate.setDate(exdate.getDate() + exdays);
	try {
		c_value = escape(google.loader.ClientLocation.address.region) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
		Set_Cookie("sitestate", c_value, 80, "/");	
	} catch (e) {

		c_value = "CA" + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
		Set_Cookie("sitestate", c_value, 80, "/");	
	}
	//document.cookie = c_name + "=" + c_value;
	*/
}
                   
//Navigation for Idaho [ID]
var navID = [
	["Get Answers", staticServer + "/answers/", "answers"],
	["Take Action", staticServer + "/action/idaho/", "takeaction"],
	["Speak Up", dynamicServer + "/speak/", "speak"]
],
	dropDownID = [
		["News", staticServer + "/action/idaho/news.html"],
		["Events", staticServer + "/action/idaho/events.html"],
		["Teen Advisory Council", staticServer + "/action/idaho/teen-council.html"],
		["Paint the State", staticServer + "/action/paintthestate.html"],
		["Get Involved", staticServer + "/action/idaho/volunteer.html"],
		["Get Help", staticServer + "/action/idaho/get-help.html"]
	],
	topNavID = [
		["About the Meth Project", "http://idaho.methproject.org"],
		["View Ads", staticServer + "/ads/tv"]
	];

//Navigation for Colorado [CO]
var navCO = [
	["Get Answers", staticServer + "/answers/", "answers"],
	["Take Action", staticServer + "/action/colorado/", "takeaction"],
	["Speak Up", dynamicServer + "/speak/", "speak"]
],
	dropDownCO = [
		["News", staticServer + "/action/colorado/news.html"],
		["Events", staticServer + "/action/colorado/events.html"],
		["Teen Advisory Council", staticServer + "/action/colorado/teen-council.html"],
		["Paint the State", staticServer + "/action/paintthestate.html"],
		["Get Involved", staticServer + "/action/colorado/volunteer.html"],
		["Get Help", staticServer + "/action/colorado/get-help.html"]
	],
	topNavCO = [
		["About the Meth Project", "http://colorado.methproject.org"],
		["View Ads", staticServer + "/ads/tv"]
	];

//Navigation for Georgia [GA]
var navGA = [
	["Get Answers", staticServer + "/answers/", "answers"],
	["Take Action", staticServer + "/action/georgia/", "takeaction"],
	["Speak Up", dynamicServer + "/speak/", "speak"]
],
	dropDownGA = [
		["News", staticServer + "/action/georgia/news.html"],
		["Events", staticServer + "/action/georgia/events.html"],
		["Paint the State", staticServer + "/action/paintthestate.html"],
		["Get Involved", staticServer + "/action/georgia/volunteer.html"],
		["Get Help", staticServer + "/action/georgia/get-help.html"]
	],
	topNavGA = [
		["About the Meth Project", "http://georgia.methproject.org"],
		["View Ads", staticServer + "/ads/tv"]
	];

//Navigation for Montana [MT]
var navMT = [
	["Get Answers", staticServer + "/answers/", "answers"],
	["Take Action", staticServer + "/action/montana/", "takeaction"],
	["Speak Up", dynamicServer + "/speak/", "speak"]
],
	dropDownMT = [
		["News", staticServer + "/action/montana/news.html"],
		["Events", staticServer + "/action/montana/events.html"],
		["Teen Advisory Council", staticServer + "/action/montana/teen-council.html"],
		["Paint the State", staticServer + "/action/paintthestate.html"],
		["March Against Meth", staticServer + "/action/montana/march.html"],
		["Get Involved", staticServer + "/action/montana/volunteer.html"],
		["Get Help", staticServer + "/action/montana/get-help.html"]
	],
	topNavMT = [
		["About the Meth Project", "http://montana.methproject.org"],
		["View Ads", staticServer + "/ads/tv"]
	];

//Navigation for Arizona [AZ]
var navAZ = [
	["Get Answers", staticServer + "/answers/", "answers"],
	["Take Action", staticServer + "/action/arizona/", "takeaction"],
	["Speak Up", dynamicServer + "/speak/", "speak"]
],
	dropDownAZ = [
		["News", staticServer + "/action/arizona/news.html"],
		["Events", staticServer + "/action/arizona/events.html"],
		["Paint the State", staticServer + "/action/paintthestate.html"],
		["Get Involved", staticServer + "/action/arizona/volunteer.html"],
		["Get Help", staticServer + "/action/arizona/get-help.html"]
	],
	topNavAZ = [
		["About the Meth Project", "http://arizona.methproject.org"],
		["View Ads", staticServer + "/ads/tv"]
	];

//Navigation for Wyoming [WY]
var navWY = [
	["Get Answers", staticServer + "/answers/", "answers"],
	["Take Action", staticServer + "/action/wyoming/", "takeaction"],
	["Speak Up", dynamicServer + "/speak/", "speak"]
],
	dropDownWY = [
		["News", staticServer + "/action/wyoming/news.html"],
		["Events", staticServer + "/action/wyoming/events.html"],
		["Paint the State", staticServer + "/action/paintthestate.html"],
		["Get Involved", staticServer + "/action/wyoming/volunteer.html"],
		["Get Help", staticServer + "/action/wyoming/get-help.html"]
	],
	topNavWY = [
		["About the Meth Project", "http://wyoming.methproject.org"],
		["View Ads", staticServer + "/ads/tv?state=WY"]
	];

//Navigation for Hawaii [HI]
var navHI = [
	["Get Answers", staticServer + "/answers/", "answers"],
	["Take Action", staticServer + "/action/hawaii/", "takeaction"],
	["Speak Up", dynamicServer + "/speak/", "speak"]
],
	dropDownHI = [
		["News", staticServer + "/action/hawaii/news.html"],
		["Events", staticServer + "/action/hawaii/events.html"],
		["Teen Advisory Council", staticServer + "/action/hawaii/teen-council.html"],
		["Paint the State", staticServer + "/action/paintthestate.html"],
		["Mobilize", staticServer + "/action/hawaii/mobilize.html"],
		["Get Involved", staticServer + "/action/hawaii/volunteer.html"],
		["Get Help", staticServer + "/action/hawaii/get-help.html"]
	],
	topNavHI = [
		["About the Meth Project", "http://hawaii.methproject.org"],
		["View Ads", staticServer + "/ads/tv"]
	];

//Navigation for MI (Test)
var navMI = [
	["Get Answers", staticServer + "/answers/", "answers"],
	["Take Action", staticServer + "/action/", "takeaction"],
	["Speak Up", dynamicServer + "/speak/", "speak"]
],
	dropDownMI = [
		["News", staticServer + "/action/news.html"],
		["Events", staticServer + "/action/events.html"],
		["Paint the State", staticServer + "/action/paintthestate.html"],
		["March Against Meth", staticServer + "/action/montana/march.html"],
		["Icons &amp; Wallpapers", staticServer + "/action/icons-wallpaper.html"],
		["Get Involved", staticServer + "/action/volunteer.html"],
		["Recognition", staticServer + "/action/recognition.html"],
		["Get Help", staticServer + "/action/get-help.html"]
	],
	topNavMI = [
		["About the Meth Project", "http://michigan.methproject.org"],
		["View Ads", staticServer + "/ads/tv"]
	];

function writeNav() {
	//var regState= getStateCookie();
	var stateCookieValue = Get_Cookie("sitestate");
	var navObj, topNavObj, dropDownObj;
	var primaryNav = $(".primaryNav");
	var dropdownNav = $(".takeaction");
	var topNav = $(".topNav");
	var path = window.location.pathname;
	var pathParts = path.split('/');
	var currentPageClass = 'currentPage';

	switch (stateCookieValue) {
	case "AZ":
	case "CO":
	case "GA":
	case "HI":
	case "ID":
	case "MT":
	case "WY":
		navObj = eval("nav" + stateCookieValue);
		dropDownObj = eval("dropDown" + stateCookieValue);
		topNavObj = eval("topNav" + stateCookieValue);

		primaryNav.empty();
		//topNav.empty();
		
		
		$.each(navObj, function (i, navItem) {
			var cssClasses = navItem[2];
			var urlParts = navItem[1].split('/');
			if(urlParts[3] == pathParts[1]) {
				cssClasses +=' '+currentPageClass;
			} else if (navItem[2] == 'answers' && pathParts[1] == '') {
				cssClasses +=' '+currentPageClass;
			}
			primaryNav.append("<li class='" + cssClasses + "'><a href='" + navItem[1] + "'>" + navItem[0] + "</a></li>");
		});
		$.each(dropDownObj, function (i, navItem) {
			var cssClasses = '';
			var targetWindow = '';			
			var urlParts = navItem[1].split('/');
			if(pathParts.length == 4 && pathParts[3] == urlParts[5]){
				cssClasses +=' '+currentPageClass;
			}
			if( 2 in navItem ){
				var targetWindow = "target='" + navItem[2] + "'";
			}
			$(".takeaction").append("<li class='" + cssClasses + "'><a href='" + navItem[1] + "' "+ targetWindow +">" + navItem[0] + "</a></li>");
		});


		//This wraps our Dropdown
		$('.takeaction li').wrapAll('<ul />');

		break;
	default:
		break;

	}

	if(isiDevice()) {
		// touch device hover menu
		var hoverIntent;
		$('.takeaction').attr("clicked",0);
		$('li.takeaction a').eq(0).unbind('click');
		$('li.takeaction').click(function (event) {
			if($('.takeaction').attr("clicked") < 1){
				clearInterval(hoverIntent);
				$this = $(this)
				hoverIntent = setTimeout(function () {
					$(".takeaction").addClass("dropdown");
					$(".takeaction ul").slideDown(300);
				}, 200);
				$('.takeaction').attr("clicked",1);
				$('.content').bind('click.offMenu', function () {
					clearInterval(hoverIntent);
					$this = $(this)
					hoverIntent = setTimeout(function () {
						$(".takeaction").delay(1000).removeClass("dropdown");
						$(".takeaction ul").slideUp(200);
					}, 200);
					$('.takeaction').attr("clicked",0);
					$('.content').unbind('click.offMenu');
					return false;
				});
				event.preventDefault();
				event.stopPropagation();
				event.stopImmediatePropagation();
				return false;
			}else{
				clearInterval(hoverIntent);
				$this = $(this)
				hoverIntent = setTimeout(function () {
					$(".takeaction").delay(1000).removeClass("dropdown");
					$(".takeaction ul").slideUp(200);
				}, 200);
				$('.takeaction').attr("clicked",0);
				return true;
			}
		});
	}else{
	//Dropdown Specifics
		var hoverIntent;
		$('.takeaction').live('mouseover', function () {
			clearInterval(hoverIntent);
			$this = $(this)
			hoverIntent = setTimeout(function () {
				$(".takeaction").addClass("dropdown");
				$(".takeaction ul").slideDown(300);
			}, 200);
		});
	
		$('.takeaction').live('mouseout', function () {
			clearInterval(hoverIntent);
			$this = $(this)
			hoverIntent = setTimeout(function () {
				$(".takeaction").delay(1000).removeClass("dropdown");
				$(".takeaction ul").slideUp(200);
			}, 200);
		});
	}
	
}



//Query String function
var qsParm = new Array();
qsParm['state'] = null;

function qs() {
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i = 0; i < parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0, pos);
			var val = parms[i].substring(pos + 1);
			qsParm[key] = val;
		}
	}

}

//Set cookie based on QS


function qsSet_Cookie() {
	qs();

	if (qsParm['state']) {
		qsValue = qsParm['state'];
		//Set_Cookie("state", qsValue, null, location.pathname)
		return qsValue;
	}
return null;
}



var lastTitle;

function setTooltips() {

	//Select all anchor tag with rel set to tooltip
	$('li[rel=tooltip]').mousemove(function (e) {
		if($('#tooltip').length == 0) {
			//Grab the title attribute's value and assign it to a variable
			var tip = $(this).attr('title');
	
			lastTitle = tip;
			//Remove the title attribute's to avoid the native tooltip from the browser
			$(this).attr('title', '');

			//Append the tooltip template and its value
			$(this).append('<div id="tooltip"><div class="tipBody">' + tip + '</div></div>');
	
			//Show the tooltip with faceIn effect
			$('#tooltip').fadeIn('500');
			$('#tooltip').fadeTo('10', 1);
			$('#tooltip').css('top', mouseY(e) + 10);
			$('#tooltip').css('left', mouseX(e) + 20);
		}
		//Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
		$('#tooltip').css('top', mouseY(e) + 10);
		$('#tooltip').css('left', mouseX(e) + 20);

	}).mouseout(function () {

		//Put back the title attribute's value
		$(this).attr('title', lastTitle);

		//Remove the appended tooltip template
		$(this).children('div#tooltip').remove();

	});

}

function mouseX(evt) {
if (evt.pageX) return evt.pageX;
else if (evt.clientX)
   return evt.clientX + (document.documentElement.scrollLeft ?
   document.documentElement.scrollLeft :
   document.body.scrollLeft);
else return null;
}
function mouseY(evt) {
if (evt.pageY) return evt.pageY;
else if (evt.clientY)
   return evt.clientY + (document.documentElement.scrollTop ?
   document.documentElement.scrollTop :
   document.body.scrollTop);
else return null;
}

var gaDocTypes = new RegExp(/\.(zip|pdf|jpg|swf)$/i);

$.expr[':'].external = function (obj) {
	if (obj.hostname.indexOf("methproject.org") != -1 || obj.hostname.indexOf("organic.com") != -1 || obj.href.indexOf("javascript:") != -1 || obj.href == "#" || obj.href == "") {
		return false;
	} else {
		return true;
	}
};

$.expr[':'].asset = function (obj) {
	return gaDocTypes.test(obj.href);
};


//Tracking Vars
var meth_UA_ID = "UA-2551111-1";
var meth_UA_Domain = "methproject.org";

function getMethUAID(){
	return meth_UA_ID;
}

var addthis_config = {
	data_track_clickback: true,
	data_ga_property: meth_UA_ID,
	ui_use_css: false,
	ui_delay: 1500,
//	services_compact: 'facebook, gmail, stumbleupon, yahoomail, myspace, email, twitter, blogger, print'
    services_compact:"facebook,twitter,stumbleupon,email,google,favorites,blogger,more"

}

function addthis_listener(event) {
	if(event.data.service != "facebook_like"){
	_gaq.push(['_trackSocial', 'addthis', event.data.service, event.data.url]);
	}
}


function linkupSocialMedia() {
	getFaceBookCounts();
}

function stripFilenameFromUrl(completeURLString) {
	var myString = String(completeURLString);
	return myString.substring(0, myString.lastIndexOf('/') + 1);
}

function getFaceBookCounts() {
	var siteURL = document.location;
	//var baseURL = stripFilenameFromUrl(siteURL);
	$("#fb_count").each(function () {
		$(this).attr("href", "http://www.facebook.com/sharer.php?u=" + siteURL);
		$(this).attr("target", "facebookwindow");
	});

	if (jQuery.fn.fbLikes !== undefined) {
		$('.content .adGrid,.content .adList').fbLikes();
	}
}

function injectFBLikes() {
	var answerDivs = $('.content .answer');
	if (answerDivs.length == 0) {
		$('.content .share_this').prepend('<fb:like href="http://' + document.location.host + document.location.pathname + '" layout="button_count" show_faces="false" width="90" action="like" colorscheme="dark" />');
		//$('.content .share_this').prepend('<fb:like-box href="http://' + document.location.host + document.location.pathname + '" show_faces="false" width="90" stream="false" border_color="" header="false" colorscheme="dark" />');

		if (typeof FB != "undefined") {
			FB.XFBML.parse($('.content .' + curCount + ' .share_this').get(0))
		}
	} else {
		//Answer Page
		for (i = 0; i < answerDivs.length; i++) {
			try {
				var curCount = answerDivs[i].className.replace("answer", '').replace("currentAnswer", '').replace(" ", '').replace(" ", '');
				var curHash = $('#nav_' + curCount).attr('title').replace(/[ ]/g, '-').replace(/['";:,.\/?\\]/g, '');

				$('.content .' + curCount + ' .share_this').prepend('<fb:like href="http://' + document.location.host + document.location.pathname + '#' + curHash + '" layout="button_count" show_faces="false" width="90" action="like" colorscheme="dark" />');
				//$('.content .' + curCount + ' .share_this').prepend('<fb:like-box href="http://' + document.location.host + document.location.pathname + '#' + curHash + '" show_faces="false" width="90" stream="false" border_color="" header="false" colorscheme="dark" />');

				if (typeof FB != "undefined") {
					FB.XFBML.parse($('.content .' + curCount + ' .share_this').get(0))
				}
			} catch (e) {

			}
		}
	}

}


// Usage:
//$(['img1.jpg','img2.jpg','img3.jpg']).preload();
$.fn.preload = function () {
	var items = new Array();
	for(i = 0; i < this.length; i++) {
		items[i] = new Image;
		items[i].src = this[i];
	}
}

//Spotlight Tagging


function drawSpotlightTags() {

	var axel = Math.random() + "";
	var a = axel * 10000000000000;
	switch (true) {
	case (document.location.pathname.indexOf("/answers") == 0):
		//Answers section
		$('body').append('<iframe src="http://fls.doubleclick.net/activityi;src=3021782;type=natio976;cat=nat-g196;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
		break;
	case (document.location.pathname.indexOf("/ads") == 0):
		//View Ads section
		$('body').append('<iframe src="http://fls.doubleclick.net/activityi;src=3021782;type=natio976;cat=nat-a488;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
		break;
	case (document.location.pathname.indexOf("/action") == 0):
		//Take Action section
		$('body').append('<iframe src="http://fls.doubleclick.net/activityi;src=3021782;type=natio976;cat=nat-t347;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
		break;
	case (document.location.pathname.indexOf("/speak") == 0):
		//Speak Up section
		$('body').append('<iframe src="http://fls.doubleclick.net/activityi;src=3021782;type=natio976;cat=nat-s378;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
		break;
	default:
		//All other pages
		$('body').append('<iframe src="http://fls.doubleclick.net/activityi;src=3021782;type=natio976;cat=nat-u210;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
	}
}

function wireupFooterElements(){
	//other copy links
	$("a.twitter").each(function(){
		var stateCookieValue = Get_Cookie("sitestate");
		for (i=0; i<stateList.length; i++) {
			if(stateList[i][1] == stateCookieValue && stateList[i][4] != "") {
				$(this).attr("href",stateList[i][4]);
			}
		}		
		$(this).attr("target","twitterwindow");
	});
	// Facebook text link.
		//Set Like FB link

	$("a.fb_like").each(function(){
		$(this).attr("target","facebookwindow");
		var stateCookieValue = Get_Cookie("sitestate");
		for (i=0; i<stateList.length; i++) {
			if(stateList[i][1] == stateCookieValue) {
				$(this).attr("href",stateList[i][2]);
				return false;
			} 
		} 
		$(this).attr("href",stateList[7][2]);
		
	});
	// Facebook text link.
	$("a.nl_signup").each(function(){
		$(this).attr("href","http://www.foundation.methproject.org/subscribe.php");
		$(this).attr("target","smwin");
	});
	$("span.footerMethsite").each(function(){
		$(this).wrap("<a href='http://foundation.methproject.org' target='smwin'></a>");
	});
}
function changeStateCookie(){
	$("ul.StateSelector a").click( function(){
		var stateChoice = $(this).attr("href");
		for(var x=0; x<stateList.length; x++){		
			if(stateChoice.indexOf(String(stateList[x][0])) > -1){
				Set_Cookie("sitestate", stateList[x][1], 80, "/");	
				return;
			}
		}
		if(stateChoice.indexOf("/action") > -1){
			//alert(stateChoice);	
			Set_Cookie("sitestate", "MI", 80, "/");
		}
	});
}
function isTouchDevice() {
	try {
		document.createEvent("TouchEvent");
		return true;
	} catch (e) {
		return false;
	}
}

//Password Protection Hack
function subPost() {
	var value = $('#foo').val();
	if(value == "porcupine") {
		Set_Cookie("validated",true);	
		location.reload();
	} else {
		javascript:alert("Bad Password");
	}
}

$(document).ready(function () {
	//Password Protection Hack
	/*
	var passwordCookie = Get_Cookie("validated");
	if (passwordCookie == null && document.location.href.indexOf('origin.methproject.org/story/form.htm') == -1) {
		$('body').html("<div style='width:300px;margin: 50px auto'><input id='foo'/> <a href='javascript:subPost()'>Submit</a></div>");
		$(document).unbind('ready');
		return;
	}
	*/
	//Rewriting Mailtos
	rewriteEmail();
	
	//Top Nav Tracking
	attachTopNavTracking();

	$('.adGrid.radio li').click(function() {
		location.href = $('.linkListen', this).attr('href');    
	});


	var isQueryString = qsSet_Cookie();
	if(isQueryString==null){
		var stateCookieValue = Get_Cookie("sitestate");
		if(stateCookieValue==null){
			setStateCookie();	
		}
	}else{
		Set_Cookie("sitestate", isQueryString, 80, "/");			
	}
	var stateCookieValue = Get_Cookie("sitestate");
	changeStateCookie();
	Set_Cookie("state", stateCookieValue);
	//qsSet_Cookie();
	writeNav();
	injectFBLikes();
	setTooltips();
/*
	if (typeof FB  != "undefined"){
		FB.Event.subscribe('edge.create', function(response) {
			_gaq.push(['_trackSocial', 'facebook', 'like_content', document.location.href]);
		});
	}
*/
	$('a:asset').click(

	function ($e) {
		_gaq.push(['_trackEvent', 'download', this.pathname, document.location.href]);
	});

	$('a:external').click(

	function ($e) {
		_gaq.push(['_trackEvent', 'Outbound', document.location.href, this.href]);
	});

	//$('.fb span').html("0");
	//addthis.addEventListener('addthis.menu.share', addthis_listener); 
	linkupSocialMedia();
	drawSpotlightTags();
	wireupFooterElements();
	
	//IE7 Reset for Speak Up
	if(isIE7 && $('body.speak').length == 1) {
		var overlays = $('.overlay');
		for (i = 0; i < overlays.length; i++) {
			obj = $(overlays[i]);
			obj.detach();
			$('body').append(obj);
		}
	}
	
	
});

//Array Randomizing Utility
Array.prototype.shuffle = function() {
	for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
	return this;
}
//Array Unique Values Utility
Array.prototype.unique = function() {
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l;i+=1) o[this[i]] = this[i];
    for(i in o) r.push(o[i]);
    return r;
};

//Delayed GA Event Tag
var delayedGAEvent

function callDelayedEvent(category, action, label) {
	delayedGAEvent = setTimeout("_gaq.push(['_trackEvent', '"+category+"', '"+action+"', '"+label+"'])",1500);
}

// Utility function to decode entity-encoded html back into html.
// Used by several ajax submissions to prepare rendered html
// results for insertion back into page
function htmlEntityDecode(str)
{
    try
	{
		var  tarea=document.createElement('textarea');
		tarea.innerHTML = str; return tarea.value;
		tarea.parentNode.removeChild(tarea);
	}
	catch(e)
	{
		//for IE add <div id="htmlconverter" style="display:none;"></div> to the page
		document.getElementById("htmlconverter").innerHTML = '<textarea id="innerConverter">' + str + '</textarea>';
		var content = document.getElementById("innerConverter").value;
		document.getElementById("htmlconverter").innerHTML = "";
		return content;
	}
}

function isiDevice(){
    return (
        //Detect iPhone
        (navigator.platform.indexOf("iPhone") != -1) ||
        //Detect iPod
        (navigator.platform.indexOf("iPod") != -1) ||
		//Detect iPad
		(navigator.platform.indexOf("iPad") != -1) 
    );
}

// *****************************
// START Media Player related JS >>
// *****************************

/**
 * HIDE SHOW SHARE ICONS
 */

function hideShare() {
	$(".share_this iframe").hide();
	$(".share_this").stop(true,true).fadeTo(100,0);	
}

function showShare() {
	$(".share_this iframe").show();
	$(".share_this").stop(true,true).fadeTo(500,1);	
}

/**
 * GOOGLE ANALYTICS TRACKING
 */

var trackEventTags = {
	// example (important: no trailing comma in array)
	// "manual_id": { categoryId:"this_category_id", actionId:"this_action_id", labelId:"this_label_id" }
	
	// inside ad video (no actionID)
	"answers_inside_ad_video_0": { categoryId:"inside_the_ads_video", actionId:"play", labelId:"answer" },
	"answers_inside_ad_video_50": { categoryId:"inside_the_ads_video", actionId:"mid", labelId:"answer" },
	"answers_inside_ad_video_100": { categoryId:"inside_the_ads_video", actionId:"complete", labelId:"answer" },
	
	// inside ad video overlay (actionID provided in call)
	"answers_inside_ad_video_overlay": { categoryId:"inside_the_ads_video", actionId:null, labelId:"answer" },
	
	// answer video (no actionID)
	"answers_video_0": { categoryId:"answers_video", actionId:"play", labelId:"answer" },
	"answers_video_50": { categoryId:"answers_video", actionId:"mid", labelId:"answer" },
	"answers_video_100": { categoryId:"answers_video", actionId:"complete", labelId:"answer" },
	
	// answer audio (no actionID)
	"answers_audio_0": { categoryId:"answers_audio", actionId:"play", labelId:"answer" },
	"answers_audio_50": { categoryId:"answers_audio", actionId:"mid", labelId:"answer" },
	"answers_audio_100": { categoryId:"answers_audio", actionId:"complete", labelId:"answer" },
	
	// speak up video (no actionID)
	"speak_up_video_0": { categoryId:"speakup_video", actionId:"play", labelId:"speak_up" },
	"speak_up_video_50": { categoryId:"speakup_video", actionId:"mid", labelId:"speak_up" },
	"speak_up_video_100": { categoryId:"speakup_video", actionId:"complete", labelId:"speak_up" },
	
	// speak up audio (no actionID)
	"speak_up_audio_0": { categoryId:"speakup_audio", actionId:"play", labelId:"speak_up" },
	"speak_up_audio_50": { categoryId:"speakup_audio", actionId:"mid", labelId:"speak_up" },
	"speak_up_audio_100": { categoryId:"speakup_audio", actionId:"complete", labelId:"speak_up" },

	// answer audio (no actionID)
	"view_ads_audio_0": { categoryId:"view_ads_audio", actionId:"play", labelId:"view_ads" },
	"view_ads_audio_50": { categoryId:"view_ads_audio", actionId:"mid", labelId:"view_ads" },
	"view_ads_audio_100": { categoryId:"view_ads_audio", actionId:"complete", labelId:"view_ads" }
}

// return location
function returnLocation() {
	return( document.location.href );
}

// return answers label
function labelAnswers() {
	return( (window.location.pathname + window.location.hash).replace(".html#","/") );
}

// return speak_up label
function labelSpeakUp() {
	return( returnLocation() );
}

// call a track event tag
function callTrackEventTag(manualID, actionID) {
	//alert("manualID " + manualID + "actionID " + actionID);
	if(manualID != null && manualID != "" && manualID != undefined) {
		// fully define manualID based on area
		var url = returnLocation();
		var returnValue;
		if (url.indexOf('/answers/') > -1) {
			returnValue = 'answers';
		} else if (url.indexOf('/ads/') > -1) {
			returnValue = 'view_ads';
		} else {
			
			returnValue = 'speak_up';
		}
		manualID = returnValue + manualID;
		// get related values based on manualID

		try {
			// get categoryId
			var categoryID = trackEventTags[manualID]['categoryId']
			// get actionId (only define actionID if the value is null)
			if (actionID == null) actionID = trackEventTags[manualID]['actionId'];
			// get labelId (special handling for 'answer' and 'speak_up' labels)
			var labelID = trackEventTags[manualID]['labelId'];
			if (labelID == 'answer') labelID = labelAnswers();
			else if (labelID == 'speak_up') labelID = labelSpeakUp();
			else labelID = labelSpeakUp();
		} catch (e) { 
			//alert("tracking error");
			return false;
		}
    	//alert("no errors " + manualID + " - " + categoryID + " - " + actionID  + " - " + labelID);
		// google analytics function call
		_gaq.push(['_trackEvent', categoryID, actionID, labelID]);
	}
}

// ***************************
// END Media Player related JS <<
// ***************************

function rewriteEmail() {
	$("a.email_link").each(function(){
		address = $(this).html().replace("/AT/","@").replace("/DOT/",".");
		$(this).attr("href","mailto:"+address);
		$(this).html(address);
	});
}

function attachTopNavTracking() {
	//categoryID = "top_nav";
	$('#head a.logo').click(function(e) {
			e.preventDefault();
			fireNavTracking("top_nav","methproject_logo")
			setTimeout("window.location = '"+this.href+"'", 100);
	});
	$('.primaryNav .answers > a').click(function(e) {
			e.preventDefault();
			fireNavTracking("top_nav","answers_link")
			setTimeout("window.location = '"+this.href+"'", 100);
	});
	$('.primaryNav .takeaction > a').click(function(e) {
				e.preventDefault();
				fireNavTracking("top_nav","takeaction_link")
				setTimeout("window.location = '"+this.href+"'", 100);
	});
	$('.primaryNav .speak > a').click(function(e) {
			e.preventDefault();
			fireNavTracking("top_nav","speakup_link")
			setTimeout("window.location = '"+this.href+"'", 100);
	});
	$('.topNav li:nth-child(1)  a').click(function(e) {
			e.preventDefault();
			fireNavTracking("top_nav","aboutmethproject_link")
			setTimeout("window.location = '"+this.href+"'", 100);
	});
	$('.topNav li:nth-child(2)  a').click(function(e) {
			e.preventDefault();
			fireNavTracking("top_nav","viewads_link")
			setTimeout("window.location = '"+this.href+"'", 100);
	});

	//Footer
	//categoryID = "bottom_nav";
	$('#footerNav a[href|="/common/contact-us.html"]').click(function(e) {
			e.preventDefault();
			fireNavTracking("bottom_nav","contactus_link")
			setTimeout("window.location = '"+this.href+"'", 100);
	});
	$('#footerNav a.nl_signup').click(function(e) {
			//e.preventDefault();
			fireNavTracking("bottom_nav","newsletterrsignup_link")
			//setTimeout("window.location = '"+this.href+"'", 100);
			//alert($(this).attr("target"));
	});
	
	$('#footerNav a.fb_like').click(function(e) {
			e.preventDefault();
			_gaq.push(['_trackSocial','facebook','like_us_facebook_page',$('#footerNav a.fb_like').attr("href")]);
			setTimeout("window.open('"+this.href+"')", 100);
	});
	
	

}

function fireNavTracking(categoryID,actionID) {
	if (document.location.toString().indexOf("/answers/") != -1) {
		labelID = (window.location.pathname + window.location.hash).replace(".html#", "/");
	} else {
		labelID = document.location.toString();	
	}

	_gaq.push(['_trackEvent', categoryID, actionID, labelID]);	
	
}


function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = "";

         switch(event.type)
    {
        case "touchstart": type= "mousedown"; break;
        case "touchmove":  type="mousemove"; break;        
        case "touchend":   type="click"; break;
        default: return;
    }

    //initMouseEvent(type, canBubble, cancelable, view, clickCount,
    //           screenX, screenY, clientX, clientY, ctrlKey,
    //           altKey, shiftKey, metaKey, button, relatedTarget);
    
    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1,
                              first.screenX, first.screenY,
                              first.clientX, first.clientY, false,
                              false, false, false, 0/*left*/, null);

    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function touchInit()
{
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);    
}
function touchClear()
{
    document.removeEventListener("touchstart", touchHandler, true);
    document.removeEventListener("touchmove", touchHandler, true);
    document.removeEventListener("touchend", touchHandler, true);
    document.removeEventListener("touchcancel", touchHandler, true);    
}

