$(document).ready(function() {

	$(window).resize(function () {

		// get the page width
		if(window.innerWidth) ww = window.innerWidth;
		else ww = (document.documentElement.clientWidth>0) ? document.documentElement.clientWidth : document.body.clientWidth;

		//get the margins
		var pg_w =  $("#pagebox").width();
		var mrgn_rt = $("#pagebox").css("margin-right");
		mrgn_rt = Number(mrgn_rt.substr(0, (mrgn_rt.length -2)));

		//set the right - margin
		mrgn_rt = (ww - pg_w)/3;
		if(mrgn_rt < 0) {
			mrgn_rt = 10;
		} else if (mrgn_rt > 68) {
			mrgn_rt = 68;
		}
		$("#pagebox").css({"margin":"0px 0px 0px " + mrgn_rt+"px"});

	});

	/*
	 * open links in new window
	*/
	$(function(){
		$("a:not( [href*=http://www.good.is/],[href^=#],[rel=nofollow] )")
		.addClass("external-link")
	 	.click(function(){
	 		window.open(this.href); // open new window
	 		return false;
		});
	});

    $(window).resize();

	// handle the top nav links --
	var global_nav_items = $("a", ".global_tier1");
	global_nav_items.removeAttr("target");

	for (var i=0; i < global_nav_items.length; i++){
		var my_attr = $(global_nav_items[i]).attr("href");

		$(global_nav_items[i]).attr("index", i);

		$(global_nav_items[i]).bind("click", function(){ loadExtUrl(this) });

		$(global_nav_items[i]).attr("href", ("#" + my_attr.substr(0, my_attr.indexOf(".") ) ) );
		//("#"+my_attr.substr(0,  (my_attr.length -4) ))
		$("body").prepend('<a name="' + my_attr.substr(0, my_attr.indexOf(".") ) +'">');
	}

	/** any link that opens "Join GOOD" **/
	var join_items = $("a", ".join_good_link");
	join_items.removeAttr("target");
	for (var i=0; i < join_items.length; i++){
		var my_attr = $(join_items[i]).attr("href");

		$(join_items[i]).attr("index", i);

		$(join_items[i]).bind("click", function(){ loadExtUrl(this) });

		$(join_items[i]).attr("href", ("#" + my_attr.substr(0, my_attr.indexOf(".") ) ) );

		$("body").prepend('<a name="' + my_attr.substr(0, my_attr.indexOf(".") ) +'">');
	}



	//only do this 1x
	$("#pagebox").prepend('<div class="column colx6-edge tier tier1 last shadow_rl" id="global_tier1"><a href="#"><div class="close"></div></a><ul id="msg"/><div class="tcontent"><div class="loading">LOADING</div></div><div class="global_tier_marker"/></div>');
	$(".close", "#global_tier1").bind("click", function(){ closeGlobalTier() });


	$.fn.x = function(n) {
		 var result = null;
		 this.each(function() {
			 var o = this;
			 if (n === undefined) {
				 var x = 0;
				 if (o.offsetParent) {
					 while (o.offsetParent) {
						 x += o.offsetLeft;
						 o = o.offsetParent;
					 }
				 }
				 if (result === null) {
					 result = x;
				 } else {
					 result = Math.min(result, x);
				 }
			 } else {
				 o.style.left = n + 'px';
			 }
		 });
		 return result;
	};

	$.fn.y = function(n) {
		 var result = null;
		 this.each(function() {
			 var o = this;
			 if (n === undefined) {
				 var y = 0;
				 if (o.offsetParent) {
					 while (o.offsetParent) {
						 y += o.offsetTop;
						 o = o.offsetParent;
					 }
				 }
				 if (result === null) {
					 result = y;
				 } else {
					 result = Math.min(result, y);
				 }
			 } else {
				 o.style.top = n + 'px';
			 }
		 });
		 return result;
	};


});

	var currentRel = "";
	// handle the external page request
	function loadExtUrl(my_obj){

		var globalTierPrefix=		"global-tier-name-";
		var count = $(my_obj).attr(	"name" );
		var contentPrefix=			".tcontent";
		var sizeOfOptions=			3;
		var indx = $(my_obj).attr(	"index");
		var rel = $(my_obj).attr(	"rel");
		var req_url = $(my_obj).attr("href") + ".php";
		req_url = req_url.substr(1, req_url.length);

		if(document.getElementById(currentRel)) document.getElementById(currentRel).className = currentRel;
		if(document.getElementById(rel)) document.getElementById(rel).className = rel + " selected";
		currentRel = rel;

		if ($("#global_tier1").find("." + globalTierPrefix + count).is(":visible"))
		{
			//current tier is visible
			$("#global_tier1").find("." + globalTierPrefix + count).removeClass( globalTierPrefix + count );
			closeGlobalTier()
			return;
		}
		else
		{
			//change contents

			//clear classes
			for ( var i = 1; i <= sizeOfOptions; ++i )
			{
				$("#global_tier1").find("." + globalTierPrefix + i).removeClass( globalTierPrefix + i );
			}

			$.ajax({
			  url: req_url,
			  cache: false,
			  success: function(html){
				$(contentPrefix,"#global_tier1").html(html);
				window.scrollBy(0,-1000);

				//add selected state

			  }
			});
	 		if(count == "2") pad = 4;
			else pad = 12;
			var my_x = $(my_obj).x() - ($(my_obj).width()/ 2) + (count*pad);
			$(".global_tier_marker").css({"left": my_x+"px"});
			$("#global_tier1").find(".tcontent").addClass( globalTierPrefix + count );
			$("#global_tier1").show();
		}
	}

	function closeGlobalTier(){
		//stop all ajax requests
		$(".tcontent","#global_tier1").html("")
		$("#global_tier1").hide();
		//remove selected state
		if(document.getElementById(currentRel)) document.getElementById(currentRel).className = currentRel;
		currentRel = "";
	}

	function loadJoin(){
		if(document.getElementById(currentRel)) document.getElementById(currentRel).className = currentRel;
		if(document.getElementById('join_good')) document.getElementById('join_good').className = "join_good selected";
		currentRel = 'join_good';
		req_url = "/about/join_good.php";
		$.ajax({
		  url: req_url,
		  cache: false,
		  success: function(html){
			$(".tcontent","#global_tier1").html(html);
			window.scrollTo(0,0);
			//add selected state

		  }
		});
		var my_x = "849";
		$(".global_tier_marker").css({"left": my_x+"px"});
		$("#global_tier1").show();
	}

// +---------------------+
// | Used for pagination |
// +---------------------+
function do_scroll_top(thisid) {
	$(thisid).css({'visibility':'hidden'});
	$(thisid).before("<img src='/wp-content/themes/goodv1/images/loading.gif' id='loading_anim_"+thisid.substr(1)+"' class='loadanim'/>");
	if(document.getElementById('scrollTop')) {
		if(document.getElementById('scrollTop').offsetTop) window.scroll(0,(document.getElementById('scrollTop').offsetTop-30));
		else window.scroll(0,(document.getElementById('scrollTop').offsetParent.offsetTop));


	} else {
		window.scroll(0,0);
	}
}

function return_scroll_content(thisid) {
	$(thisid).css({'visibility':'visible'});
	$('#loading_anim_'+thisid.substr(1)).remove();
}


/******************************************************************/
/// choose good drop down
var curSelect = false;
	/* ####### TO PUT BACK WHEN THESE PAGES ARE CREATED
	var partnerValue = Array(
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42694">Help Ashoka</a> support leading social entrepreneurs worldwide.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42701">Help Room to Read</a> build a library in the developing world.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42704">Help Teach for America</a> enlist our nation\'s most promising leaders in the movement to eliminate educational inequity.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42710">Help 862 National</a> give teachers and students the tools they need to stimulate youth literacy.',
		'<a href="https://admin.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Acumen Fund</a> support enterprises  that are bringing essential goods and services to the poor.',
		'<a href="https://admin.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Malaria No More</a> make malaria deaths a thing of the past.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42702">Help Slow Food USA</a> change the way America eats by creating a food system that is good, clean, and fair.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42700">Help NRDC</a> implement solutions to the problems in our environment and in our lives.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42697">Help Kiva</a> distribute microloans directly to the people who need them.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42696">Help IAVA</a> protect the rights of American soldiers.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42695">Help Hands</a> On Network mobilize volunteers wherever they are needed.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=42705">Help YouthAIDS</a> curb the spread of AIDS through pop culture and education.'
	);
	###### */

	var partnerValue = Array(
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Ashoka</a> support leading social entrepreneurs worldwide.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Room to Read</a> build a library in the developing world.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Teach for America</a> enlist our nation\'s most promising leaders in the movement to eliminate educational inequity.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help 862 National</a> give teachers and students the tools they need to stimulate youth literacy.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Acumen Fund</a> support enterprises  that are bringing essential goods and services to the poor.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Malaria No More</a> make malaria deaths a thing of the past.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Slow Food USA</a> change the way America eats by creating a food system that is good, clean, and fair.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help NRDC</a> implement solutions to the problems in our environment and in our lives.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Kiva</a> distribute microloans directly to the people who need them.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help IAVA</a> protect the rights of American soldiers.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help Hands</a> On Network mobilize volunteers wherever they are needed.',
		'<a href="https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=GDM&cds_page_id=52173">Help YouthAIDS</a> curb the spread of AIDS through pop culture and education.'
	);

	var urlValue = Array(
		'/sections/nonprofit/ashoka.php',
		'/sections/nonprofit/room_read.php',
		'/sections/nonprofit/teach_america.php',
		'/sections/nonprofit/826.php',
		'/sections/nonprofit/acumen.php',
		'/sections/nonprofit/malaria.php',
		'/sections/nonprofit/slowfood.php',
		'/sections/nonprofit/nrdc.php',
		'/sections/nonprofit/kiva.php',
		'/sections/nonprofit/iava.php',
		'/sections/nonprofit/handson.php',
		'/sections/nonprofit/youthaids.php'
	);

	var partnerKey = Array('choose_ashoka','choose_room_to_read','choose_teach','choose_826','choose_acumen','choose_malaria','choose_slow_food','choose_nrdc','choose_kiva','choose_iava','choose_hands','choose_youth_aids');

	function in_array(arr,valeur) {
		for (var i in arr) { if (arr[i] === valeur) return i; }
		return false;
	}

	function nonprofitInfo(which) {
		key = in_array(partnerKey,which);
		value = partnerValue[key];
		url = urlValue[key];
		document.getElementById('learn_more').innerHTML = value+' <a href="'+url+'" class="more">Learn more</a>';

		if(curSelect) document.getElementById(curSelect).className = "choose_partner "+curSelect;
		document.getElementById(which).className = "choose_partner selected "+which+"_s";

		curSelect = which;
	}
/******************************************************************/

//
// +-------------------+
// | Generic Utilities |
// +-------------------+
//

/**
 * Safer replacement for document.getElementById.
 */
function get_object(obj)
{
    if (typeof obj == "object")
    {
        return obj;
    }

    if (document.all)
    {
        return document.all(obj);
    }
    else if (document.getElementById)
    {
        return document.getElementById(obj);
    }

    return null;
}

//
// The following code declares three functions and adds them to the
// HTMLElement prototype class: insertAdjacentElement, insertAdjacentHTML, and
// insertAdjacentText. These functions are available in MSIE 4+ and are not
// redefined if they already exist. You can find documentation for these
// functions on the internet.
//

if (typeof HTMLElement != "undefined" &&
    !HTMLElement.prototype.insertAdjacentElement)
{
	HTMLElement.prototype.insertAdjacentElement = function (where, node)
	{
		switch (where){
		case 'beforeBegin':
            this.parentNode.insertBefore(node, this);
			break;
		case 'afterBegin':
			this.insertBefore(node, this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(node);
			break;
		case 'afterEnd':
			if (this.nextSibling)
            {
                this.parentNode.insertBefore(node, this.nextSibling);
            }
			else
            {
                this.parentNode.appendChild(node);
            }
			break;
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function (where, html)
	{
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		this.insertAdjacentElement(where, r.createContextualFragment(html));
	}

	HTMLElement.prototype.insertAdjacentText = function (where, text)
	{
		this.insertAdjacentElement(where, document.createTextNode(text));
	}
}



/**
 * Similar to the PHP built-in number_format function, but more limited in
 * scope. This function only adds thousands separators.
 */
function number_format(n)
{
    n += '';  // convert n to a string

    var answer = '';
    var i = n.length-1;

    for (; i >= 3; i -= 3)
    {
        answer = ',' + n.substr(i-2, 3) + answer;
    }
    if (i >= 0)
    {
        answer = n.substr(0, i + 1) + answer;
    }
    else
    {
        answer = answer.substr(1);
    }

    return answer;
}

/**
 * Given an associative array, returns a list containing the array's keys.
 */
function array_keys(a)
{
    var keys = new Array();
    for (var k in a)
    {
        keys.push(k);
    }
    return keys;
}



function redirect(url)
{
    window.location=url;
}





/**
 * Returns f.g if f is a function, else returns g.
 */
function append_function(g, f)
{
    if (f && (typeof(f)).toUpperCase() == 'FUNCTION')
    {
        return function() { f(); g(); };
    }
    return g;
}

/**
 * Creates an XMLHTTPRequest object in a portable way.
 */
function create_xml_http_request()
{
    try
    {
        return new ActiveXObject('Microsoft.XMLHTTP');
    }
    catch (e)
    {
        return new XMLHttpRequest();
    }
}





/**
 * Adds a unique request variable to the url to thwart web browsers that cache
 * pages too aggressively (shame on you IE).
 */
function add_cache_burster_to_url(url)
{
    return url_adjoin_qs(url, { _ctk_cache_burst : Math.random() });
}


function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : ""); }

function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

// this is to show a loading animation in the time-space between
// asking for facebook connect and getting the dialogs (blair 10/09)
function tb_wait()
{
	$('#TB_window').css('width',208)
	.css('margin-top',0)
	.css('margin-left',-100)
	.html("<img src='"+tb_pathToImage+"' >");
	
}