//BarkleyREI Searchbox Clear/Restore 1.0
$.fn.searchclear=function(){
	return this
	.focus(function(){if(this.value==this.defaultValue){this.value=""};})
	.blur(function(){if(!this.value.length){this.value=this.defaultValue};})
};

// BarkleyREI Searchbox Validate 1.0
$.fn.validsearch=function(status, textbox){
	return this.submit(function(){
		var dvalue = $(textbox).attr("defaultValue");var value = $(textbox).attr("value");var error = "Please enter a query before submitting.";
		if(dvalue==value){$(status).html(error).fadeIn(300);setTimeout('$("' + status + '").fadeOut()', 2000);return false;};
	});
};

//BarkleyREI Div Swapper 1.0
$.fn.div_swap=function(click_swap){
	$(this).children('div').addClass('pane');
	$(this).children('div:not(:first)').hide()
	$(click_swap).click(function(){
		var to_show = $(this).attr('href');
		var to_hide = "#" + $(this).parents('div.pane').attr('id');
		$(to_show).show();
		$(to_hide).hide();
		return false;
	});
};

// BarkleyREI Gallery 1.0 
$.fn.rei_gallery=function(container){
	//populate container with image object
	var init_display = $(this).parent().children("li").get(0);
	var the_img = '<img src="' + $(init_display).find("a").attr("href") + '" alt="' + $(init_display).find("a").attr("title") + '" title="' + $(init_display).find("a").attr("title") + '" />'
	$(container).prepend(the_img);
	$(init_display).addClass('active');	
	//on li click
	return this.click(function(){
		//source and target attributes
		var target = $(container + " img").attr("src");
		var source =  $(this).find("a").attr("href");
		var alt_text = $(this).find("a").attr("title");
		//active class
		$(this).siblings().removeClass('active');
		$(this).addClass('active');
		//swap images
		if (target != source) {
			$(container + " img").fadeOut(250, function() {$(container + " img").attr({src: source, title: alt_text, alt: alt_text}).fadeIn(250);});
		};
		return false;
	});
};

//BarkleyREI AJAX Click function 1.0
$.fn.rei_ajax_click=function(templateId, targetId, loadingId){
	return this.click(function(){
		$(loadingId).fadeIn(100);
		var datasource = "/TemplateMarkupCallbackHandler.ashx?templateId=" + templateId + "&amp;",
			datasource = datasource.replace("amp;", ""),
			href = $(this).attr("href").split("?");
			//set cookie, expires in 4:30min
			$.cookie('results_url', datasource + href[1], {expires:.003});
		$.ajax({
			type: "GET",
			url: datasource + href[1],
			dataType: "html",
			success: function(html){
				$(targetId).html(html);
				$(loadingId).hide();
			}
		});
		return false;
	});
};

//BarkleyREI AJAX Flash function 1.0
function rei_ajax_flash(theCat, templateId, targetId, loadingId){
	//return this.click(function(){
		$(loadingId).fadeIn(100);
		var datasource = "/TemplateMarkupCallbackHandler.ashx?templateId=" + templateId + "&amp;",
			datasource = datasource.replace("amp;", ""),
			href = "industry=" + theCat;
			//set cookie, expires in 4:30min
			//$.cookie('results_url', datasource + href[1], {expires:.003});
			//console.log(datasource + href);
		$.ajax({
			type: "GET",
			url: datasource + href,
			dataType: "html",
			success: function(html){
				$(targetId).html(html);
				$(loadingId).hide();
			}
		});
		//return false;
	//});
};

//BarkleyREI AJAX Submit function 1.0
$.fn.rei_ajax_submit=function(templateId, targetId, loadingId){
	return this.submit(function(){
		$(loadingId).fadeIn(100);
		var datasource = "/TemplateMarkupCallbackHandler.ashx?templateId=" + templateId + "&amp;",
			datasource = datasource.replace("amp;", ""),
			formdata = $(this).serialize();
			//set cookie, expires in 4:30min
			$.cookie('results_url', datasource + formdata, {expires:.003});
		$.ajax({
			type: "GET",
			url: datasource + formdata,
			dataType: "html",
			success: function(html){
				$(targetId).html(html);
				$(loadingId).hide();
			}
		});
		return false;
	});
};

//BarkleyREI AJAX State Restore 1.0
function restore_ajax_state(targetId, loadingId) {
	if ($.cookie('results_url') != null) {
		$(loadingId).fadeIn(100);
		$.ajax({
			type: "GET",
			url: $.cookie('results_url'),
			dataType: "html",
			success: function(html){$(targetId).html(html);$(loadingId).hide();}
		});
	};
};

//REI AJAX Seondary Form Set Cookie
$.fn.rei_ajax_second_form=function(templateId, cookiePath){
	return this.submit(function(){
		var datasource = "/TemplateMarkupCallbackHandler.ashx?templateId=" + templateId + "&amp;",
			datasource = datasource.replace("amp;", ""),
			formdata = $(this).serialize();
		//set cookie, expires in 4:30min
		$.cookie('results_url', datasource + formdata, {path:cookiePath, expires:.003});
		return true;
	});
};

//BarkleyREI Bookmark Dropdown 1.0
$.fn.bm_slider=function(){
	return this.hoverIntent(
		function () {if ($(this).is(":has(ul)")) {$(this).children('ul').slideDown(300);}},
		function () {$(this).children('ul').slideUp(300)}
	);
};

//not logged in message for MyContent SAVE button
	$(function() {
		$('a.not_logged_in').click(function() {
			$('p.signup_to_save').fadeIn(500);
			setTimeout('$(\'p.signup_to_save\').fadeOut(500)', 5500 );return false;
		})
	});
	
	
// Barkley REI Simple Tooltip 1.0
this.tooltip = function(){	
		offset_x = 10;
		offset_y = 20;		
	$(".tooltip").hover(function(e){											  
		titleo = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ titleo +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - offset_x) + "px")
			.css("left",(e.pageX + offset_y) + "px")
			.fadeIn("fast");		
    },
	function(){
		$("#tooltip").remove(); 
		this.title = titleo;		
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - offset_x) + "px")
			.css("left",(e.pageX + offset_y) + "px");
	});			
};



// hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+ <http://cherne.net/brian/resources/jquery.hoverIntent.html | author Brian Cherne <brian@cherne.net>
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:200,timeout:500};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);


//Modified jQuery Easing - (gsgd.co.uk/sandbox/jquery.easing.php) - Copyright (c) 2007 George Smith - Licensed under the MIT License
jQuery.extend(jQuery.easing,{easeinout:function(x,t,b,c,d){if(t<d/2)return 2*c*t*t/(d*d)+b;var ts=t-d/2;return-2*c*ts*ts/(d*d)+2*c*ts/d+c/2+b}});

// jQuery UI Accordion 1.6 -  Copyright (c) 2007 Jörn Zaefferer - http://docs.jquery.com/UI/Accordion -  Dual licensed under the MIT and GPL licenses
(function($){$.ui=$.ui||{};$.fn.extend({accordion:function(options,data){var args=Array.prototype.slice.call(arguments,1);return this.each(function(){if(typeof options=="string"){var accordion=$.data(this,"ui-accordion");accordion[options].apply(accordion,args)}else if(!$(this).is(".ui-accordion"))$.data(this,"ui-accordion",new $.ui.accordion(this,options))})},activate:function(index){return this.accordion("activate",index)}});$.ui.accordion=function(container,options){this.options=options=$.extend({},$.ui.accordion.defaults,options);this.element=container;$(container).addClass("ui-accordion");if(options.navigation){var current=$(container).find("a").filter(options.navigationFilter);if(current.length){if(current.filter(options.header).length){options.active=current}else{options.active=current.parent().parent().prev();current.addClass("current")}}};options.headers=$(container).find(options.header);options.active=findActive(options.headers,options.active);if(options.fillSpace){var maxHeight=$(container).parent().height();options.headers.each(function(){maxHeight-=$(this).outerHeight()});var maxPadding=0;options.headers.next().each(function(){maxPadding=Math.max(maxPadding,$(this).innerHeight()-$(this).height())}).height(maxHeight-maxPadding)}else if(options.autoheight){var maxHeight=0;options.headers.next().each(function(){maxHeight=Math.max(maxHeight,$(this).outerHeight())}).height(maxHeight)};options.headers.not(options.active||"").next().hide();options.active.parent().andSelf().addClass(options.selectedClass);if(options.event)$(container).bind((options.event)+".ui-accordion",clickHandler)};$.ui.accordion.prototype={activate:function(index){clickHandler.call(this.element,{target:findActive(this.options.headers,index)[0]})},enable:function(){this.options.disabled=false},disable:function(){this.options.disabled=true},destroy:function(){this.options.headers.next().css("display","");if(this.options.fillSpace||this.options.autoheight){this.options.headers.next().css("height","")}$.removeData(this.element,"ui-accordion");$(this.element).removeClass("ui-accordion").unbind(".ui-accordion")}};function scopeCallback(callback,scope){return function(){return callback.apply(scope,arguments)}};function completed(cancel){if(!$.data(this,"ui-accordion"))return;var instance=$.data(this,"ui-accordion");var options=instance.options;options.running=cancel?0:--options.running;if(options.running)return;if(options.clearStyle){options.toShow.add(options.toHide).css({height:"",overflow:""})}$(this).triggerHandler("change.ui-accordion",[options.data],options.change)};function toggle(toShow,toHide,data,clickedActive,down){var options=$.data(this,"ui-accordion").options;options.toShow=toShow;options.toHide=toHide;options.data=data;var complete=scopeCallback(completed,this);options.running=toHide.size()==0?toShow.size():toHide.size();if(options.animated){if(!options.alwaysOpen&&clickedActive){$.ui.accordion.animations[options.animated]({toShow:jQuery([]),toHide:toHide,complete:complete,down:down,autoheight:options.autoheight})}else{$.ui.accordion.animations[options.animated]({toShow:toShow,toHide:toHide,complete:complete,down:down,autoheight:options.autoheight})}}else{if(!options.alwaysOpen&&clickedActive){toShow.toggle()}else{toHide.hide();toShow.show()}complete(true)}};function clickHandler(event){var options=$.data(this,"ui-accordion").options;if(options.disabled)return false;if(!event.target&&!options.alwaysOpen){options.active.parent().andSelf().toggleClass(options.selectedClass);var toHide=options.active.next(),data={instance:this,options:options,newHeader:jQuery([]),oldHeader:options.active,newContent:jQuery([]),oldContent:toHide},toShow=options.active=$([]);toggle.call(this,toShow,toHide,data);return false}var clicked=$(event.target);if(clicked.parents(options.header).length)while(!clicked.is(options.header))clicked=clicked.parent();var clickedActive=clicked[0]==options.active[0];if(options.running||(options.alwaysOpen&&clickedActive))return false;if(!clicked.is(options.header))return;options.active.parent().andSelf().toggleClass(options.selectedClass);if(!clickedActive){clicked.parent().andSelf().addClass(options.selectedClass)}var toShow=clicked.next(),toHide=options.active.next(),data={instance:this,options:options,newHeader:clicked,oldHeader:options.active,newContent:toShow,oldContent:toHide},down=options.headers.index(options.active[0])>options.headers.index(clicked[0]);options.active=clickedActive?$([]):clicked;toggle.call(this,toShow,toHide,data,clickedActive,down);return false};function findActive(headers,selector){return selector!=undefined?typeof selector=="number"?headers.filter(":eq("+selector+")"):headers.not(headers.not(selector)):selector===false?$([]):headers.filter(":eq(0)")};$.extend($.ui.accordion,{defaults:{selectedClass:"selected",alwaysOpen:true,animated:'slide',event:"click",header:"a",autoheight:true,running:0,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase()}},animations:{slide:function(options,additions){options=$.extend({easing:"swing",duration:300},options,additions);if(!options.toHide.size()){options.toShow.animate({height:"show"},options);return}var hideHeight=options.toHide.height(),showHeight=options.toShow.height(),difference=showHeight/hideHeight;options.toShow.css({height:0,overflow:'hidden'}).show();options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate({height:"hide"},{step:function(now){var current=(hideHeight-now)*difference;if($.browser.msie||$.browser.opera){current=Math.ceil(current)}options.toShow.height(current)},duration:options.duration,easing:options.easing,complete:function(){if(!options.autoheight){options.toShow.css("height","auto")}options.complete()}})},easeslide:function(options){this.slide(options,{easing:"easeinout",duration:700})}}})})(jQuery);

//cookies - credit: Klaus Hartl (stilbuero.de)
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

//COMMON INITIALIZE
$(document).ready(function() {
	//keyword validation
	$("#keywordform").validsearch(".tryagain", "#kwords");
	//navigation animate
	$('#nav_in').accordion({alwaysOpen: false,autoheight: false,active: '.active',selectedClass: 'active',header: "h3.title",animated:"easeslide"});		
	//create main background divs
	$("#main").append('<div id="main_right_bg"></div>').append('<div id="main_left_bg"></div>');
	//Seondary Form Cookie set
	$("#sidebar_ff_form").rei_ajax_second_form(12, "/find-and-apply-for-funding/funding-and-program-finder/");
	$("#keywordform").rei_ajax_second_form(6, "/site-search/");
	//page url to footer
	var this_url = document.location.href;
	$("p.this_url").html(this_url);

	tooltip();
});