var HELPERS =
{    
    // Smart Text Input (e.g. search fields)
    memorizeTextInput : function(id, val){
        var input = $(id)[0];
        if(!input) return false;
		  input.value = val
        input.oldval = input.value;
        input.onfocus = function(){
			if(this.value == this.oldval)
            this.value = "";
        }
        input.onblur = function(){
            if(this.value == "")
            this.value = this.oldval;
        }
    }
};

function bookmark(){
	loc = document.location.href;
	title = document.title.replace(' (www.toigofoundation.org)', '');
	if (document.all)window.external.AddFavorite(loc,title);
	else window.sidebar.addPanel(title,loc,'');
	return false;
}

function featureCycle(){
	$("#featuredcontent .images").cycle({
		speed: 'slow',
		next: '#featuredcontent .next',
		prev: '#featuredcontent .prev'
	})  
	$("#featuredcontent ul a.pause").bind("click", function(){
		var me = $(this)
		if(me.hasClass("pause")){
			me.removeClass("pause").addClass("play")
			$("#featuredcontent .images").cycle('pause')
		} else {
			me.removeClass("play").addClass("pause")
			$("#featuredcontent .images").cycle('resume')
		}
		return false;
	})
}

function hoverSearch(){
	$("#search_field").bind("click focus", function(e){
	    if (!e) var e = window.event;
		e.cancelBubble = true;  
		if (e.stopPropagation) e.stopPropagation();
		$("#search").addClass("sticky")
	});
	$("body").bind("click", function(){
		$("#search").removeClass("sticky")
	})  
}

var PROFILE = {
	overlaid: false,
	init: function(){
		$("#profiles").removeClass("inactive");
		
		PROFILE.prepOverlay();
		
		$("#profiles .profile ul").each(function(ul){
			var cns = $(this).children('li').length;
			$(this).css("width", cns*86-22+"px");
		});
		
	   $("#profiles .profile ul a").bind("click", PROFILE.picClick);
		
		$("#profiles .profile ul a:first").trigger("click");
		
		$("#profilecontrols .next a").bind("click", PROFILE.nextClick);
		
		$("#profilecontrols .back a").bind("click", PROFILE.backClick);
		
		$("#profiledesc a").bind("click", PROFILE.profileClick)
		
	  // $("#overlay").bind("click", PROFILE.closeOverlay)
	},   
	
	prepOverlay: function(){
		if(PROFILE.overlaid) return;
		PROFILE.overlaid = true;
		// Create holder for popup div
		var holderdiv = document.createElement("div");
		$(holderdiv).attr("id", "popupholder");
		$("#wrapper").append(holderdiv);
		// Create overlay div to darken background
		var overlaydiv = document.createElement("div")
		$(overlaydiv).attr("id", "overlay")
		$("body").append(overlaydiv)
		overlaydiv = $(overlaydiv);
		overlaydiv.hide();
		overlaydiv.fadeTo(10, 0.75);
		overlaydiv.width($("body").width());
		overlaydiv.height($("body").height());   
		overlaydiv.bind("click", PROFILE.closeOverlay)
	},
	
	closeOverlay: function(){
		$("#popupholder").empty();
		$("#overlay").hide();
		return false;
	},
	
	nextClick : function(){
		if($(this).hasClass("disabled")) return false;
		$("#profilecontrols .back a").removeClass("disabled");
		hwidth = $("#profiles .profile").width();
		pu = $("#profiles .profile ul");
		pwidth = pu.width()-86
		pleft = pu.css("marginLeft").replace("px", "")*-1; // we always want a positive number
		overlap = pwidth - pleft - hwidth;
		if(overlap > hwidth){
			newleft = ((pleft + 430) * -1)+"px";
		} else {
			newleft = ((pleft + overlap) * -1)+"px";
			$(this).addClass("disabled");
		}
		pu.animate({marginLeft: newleft}, { duration: 500, queue: false });
		return false
	},
	
	backClick : function(){
		if($(this).hasClass("disabled")) return false;
		$("#profilecontrols .next a").removeClass("disabled");
		hwidth = $("#profiles .profile").width();
		pu = $("#profiles .profile ul");
		pwidth = pu.width();
		pleft = pu.css("marginLeft").replace("px", "")*-1;
		if(pleft > hwidth){
			newleft = ((pleft - 430) * -1)+"px";
		} else {
			newleft = 0;
			$(this).addClass("disabled");
		}
		pu.animate({marginLeft: newleft}, { duration: 500, queue: false });
		return false
	},
	
	picClick : function(){
		$("#profiles a.selected").toggleClass("selected")
		me = $(this)
		$("#profilepic").css("background-image", "url('"+me.attr("href")+"')")
		$("#profiledesc p.desc").html(me.children("span.desc").html())
		$("#profiledesc a.viewfellowshipprofile").attr("href", me.children("span.url").text())
		me.addClass("selected")         
		return false;
	},
	
	profileClick : function(){
		$("#overlay").css("display", "block").addClass("loading");
		$("#popupholder").load($(this).attr("href"), function(s){
			$("#overlay").removeClass("loading");
			popup = $("#profilepop");
			popup.css("marginTop", "110px");
			popup.css("marginLeft", $("body").width()/2-popup.width()/2+"px")
			$('html,body').animate({scrollTop: 100});
			$("#close").bind("click", PROFILE.closeOverlay)
			// Render sIFR
		// Object detection?! Firefox on Mac can't render sifr above the PNG  :(
		// if(!(navigator.appVersion.indexOf("Mac") != -1 && $.browser.mozilla)){
		// 	sIFR.replace(garamonds, {
		// 		selector: '#popupholder blockquote '
		// 		,css: ['.sIFR-root {color:#FFFFFF; font-style: italic;}']
		// 		,wmode: 'transparent'
		// 	})
		// }
			$('.scroll-pane').jScrollPane();
			
		});
		return false
	}
}

function donorOverlay(){
	PROFILE.prepOverlay();
	
	$("a.viewdiagram").bind("click", function(){
		$("#overlay").css("display", "block").addClass("loading");
		$("#popupholder").load("/donors/diagram.php", function(s){
			$("#overlay").removeClass("loading")
			popup = $("#donorDiagram");
			popup.css("marginTop", "110px");
			popup.css("marginLeft", $("body").width()/2-popup.width()/2+"px");
			popup.children("#close a").bind("click", PROFILE.closeOverlay);
		});
		return false;
	}) 
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
function emailPage(){
	var mail_str = "mailto:?subject=Link to website of Robert Toigo Foundation - (http://toigofoundation.org)"
	mail_str += "&body=Below is a link to the Robert Toigo Foundation website that I wanted to share with you.";
	mail_str += "%0A%0ATo view the page, visit: "+location.href;
	mail_str += "%0A%0A";
	// mail_str += "-------------------------------------------";
	// mail_str += "%0AAbout Robert Toigo Foudnation";
	location.href = mail_str;
	return false; 
}

textSizes = Array("small", "medium", "large");
function resizeText(){
	current = $("#wrapper").attr("class");
	next = current;
	if($(this).hasClass("larger")){
		if(current == "" || current == "small")
		next = "medium";
		if (current == "medium")
		next = "large";
	} else {
		if(current == "large")
		next = "medium";
		if(current == "medium")
		next = "small";
	}
	$("#wrapper").attr("class", next)
	createCookie("bodyclass", next, 365);
	
	return false;	
}

function checkSubscriptionForm(){
	retval = true;
	email = true;
	input = true;
	if($("#mb-pthhj-pthhj").val().match(/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/) == null){
		retval = false;
		email = false;
	} 
	if($("#eu input:checked").length == 0){
		retval = false;
		input = false;	
	}
	$("#eu p.error").remove();
	if(!email && !input){
		$("p.submit").after("<p class='error'>Please check you have entered your email address correctly and selected at least one area of interest.</p>");
	} else if(email && !input){
		$("p.submit").after("<p class='error'>Please select at least one area of interest.</p>");
	} else if (!email && input){
		$("p.submit").after("<p class='error'>Please check you have entered your email address correctly.</p>");
	}
	
	return retval;
}


/* Adthis Config*/
addthis_pub             = 'rtf';
addthis_logo            = 'http://rtf.activeingredients.com/images/interface/logo.gif';
addthis_logo_background = 'FFFFFF';
addthis_logo_color      = 'FFFFFF';
addthis_brand           = 'Robert Toigo Foundation';
addthis_options         = 'favorites, email, digg, delicious, myspace, facebook, google, live, more';

/* Page Loads*/
$(document).ready(function(){

	if($("#featuredcontent .images").length)
	featureCycle();
	
	if($("#backtotop").length)
	$("#backtotop a").bind("click", function(){
		$('html,body').animate({scrollTop: 0});
		return false;
	})
	
	if($("#search_field").length)
	hoverSearch()
	
	if($("#universityflash").length){
	   ufheight = (Math.floor(24/4)*109)+1;
		swfobject.embedSWF("/swfs/infounit_v1.swf", "universityflash", "501", ufheight, "9.0.0", "", {xmlPath: "/flashmedia/universities.xml"}, {salign: "tl", wmode: "transparent"})
	}
		
	$("#events").cycle({
		fx: 	'fade',
		timeout: 4000,
		speed: 'medium',
		next: "#eventcontrols .next",
		prev: "#eventcontrols .back"
	})
	  
	
	$("#eventcontrols .pause a").bind("click", function(){
		$(this).toggleClass("paused")
		if($(this).hasClass("paused"))
		$("#events").cycle("pause");
		else
		$("#events").cycle("resume");
		return false		
	})
	
	if($("#profiles").length)
	PROFILE.init();
	
	$("#tabcontent").before('<ul id="tabs">').cycle({
		fx:    'fade',
		timeout: 4000,
		speed: 'slow',	    
		//height: 169,
		cleartype: true,
		pager: '#tabs',
		pagerAnchorBuilder: function(idx, slide) { 
        	return '<li class="'+$(slide).attr("title")+'"><a href="#">'+$(slide).attr("title")+'</a></li>'; 
    	} 
	});	
	$('#tabcontent').cycle('pause'); 
	
	$("#pagetools .print a").bind("click", function(){
		window.print();
		return false;
	});
	
	$("#pagetools .email a").bind("click", emailPage)
	
	$("#pagetools a.larger, #pagetools a.smaller").bind("click", resizeText)
	
	$("#pagetools .bookmark a").bind("click", bookmark)
	
	HELPERS.memorizeTextInput("#emailupdates", "Enter email address")
	
	if ($("a.viewdiagram").length)
	donorOverlay();
	
	
	$("#bookmark a").bind("mouseout", function(){
		addthis_close();
	})
	$("#bookmark a").bind("click", function(){
		return addthis_sendto();
	})
	
	$("#global a.ext, #content a.ext, #content a.pdf, #content a.drivingdirections").attr("target", "_blank");
	
	$("#eu").bind("submit", checkSubscriptionForm);

}) 


/* sIFR setup */

if(typeof(sIFR) == "object" && typeof(homepage) == "undefined"){
	var garamond = {
		src: '/swfs/garamond.swf'
		,ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01]
	};
	// var garamond_italic = {
	// 	src: '/swfs/garamond-italic.swf'
	// 	,ratios: [6, 1.24, 8, 1.21, 10, 1.14, 12, 1.12, 13, 1.11, 14, 1.1, 16, 1.09, 18, 1.08, 21, 1.07, 41, 1.06, 47, 1.04, 66, 1.03, 111, 1.02, 1.01]
	// };
	var univers57cond = {
		src: '/swfs/univers57cond.swf'
		,ratios: [9, 1.27, 14, 1.19, 21, 1.16, 28, 1.13, 38, 1.12, 53, 1.11, 60, 1.1, 61, 1.11, 94, 1.1, 96, 1.09, 101, 1.1, 102, 1.09, 103, 1.1, 108, 1.09, 110, 1.1, 1.09]
	};
	sIFR.fitExactly = true;

	//sIFR.delayCSS  = true;
	//sIFR.domains = ['novemberborn.net'] // Don't check for domains in this demo
	

	sIFR.activate(garamond, univers57cond);
	sIFR.replace(garamond, {
		selector: 'h2#title'
		,css: ['.sIFR-root {color:#487184;}']
		,wmode: 'transparent'
	}) 
	sIFR.replace(garamond, {
		selector: '#content h1'
		,css: ['.sIFR-root {color:#576f21;}']
		,wmode: 'transparent'
	})
	sIFR.replace(univers57cond, {
		selector: '#content h2'
		,css: ['.sIFR-root {color:#443e38;}']
		,wmode: 'transparent'
	})    
	sIFR.replace(garamond, {
		selector: '#content blockquote p'
		,css: ['.sIFR-root {color:#4a4a4a; font-weight:bold; leading: 3;}']
		,wmode: 'transparent'
	})
}
