$(document).ready(function() {
	
	//set selected tab & defaults
	//valid values
	var rexp = /^catalog$|^ebooks$|^ejournals$|^eresources$|^images$|sitesearch$/;
	//on page load, get which tab to select - first from URL hash, else from cookie, else default to 'catalog'
	var selectedTab = rexp.test(window.location.hash.substr(1)) ? window.location.hash.substr(1) : rexp.test(getCookie('tabCookie')) ? getCookie('tabCookie') : 'catalog';
  
  //catalog tab is set to display by default in css; if catalog is not supposed to be the selected tab on page load, then hide it
	if (selectedTab != 'catalog') {
		$('#tab-catalog').addClass('search-tab').removeClass('search-tab-sel');
		$('#catalog').hide();
	}
  
  //set selected tab state
	selectTab(selectedTab);
  
	//jQuery URL utils
	//this utility enables tab history -- when click back button, goes to previous tab clicked
	$.fragmentChange( true );
	//set tab clicks
	$(document).bind('fragmentChange', function(e) { 
		selectedTab = rexp.test(e.fragment) ? e.fragment : selectedTab;
		selectTab(selectedTab);
	});
});

//selectTab function
var selectedTabName = null;
function selectTab(tabName) {
  //remove selected state
	if (selectedTabName != null) {
		$('#tab-'+selectedTabName).addClass('search-tab').removeClass('search-tab-sel');
		$('#'+selectedTabName).hide();
	}
	//apply selected state
	selectedTabName = tabName;
	$('#tab-'+selectedTabName).addClass('search-tab-sel').removeClass('search-tab');
	$('#'+selectedTabName).show();
  //set cookie
	setCookie('tabCookie', selectedTabName, 365);
}

//cookie functions
function getCookie( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  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() : "" ) + //expires.toGMTString()
    ( ( 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-1970 00:00:01 GMT";
}

// Fix for IE background image flickering
try {
  document.execCommand('BackgroundImageCache', false, true);
}
catch(e) {}

