/* USF Javascript Effects (requires jQuery and jQuery UI effects) */
/* by White Whale Web Services */

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){jQuery.browser.mobile=/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

function setCookie(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=/;domain=usfca.edu";
}

function getCookie(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 deleteCookie(name) {
    setCookie(name,"",-1);
}
/*
  Changed function names from readCookie(), createCookie()
  and eraseCookie() to getCookie(), setCookie() and deleteCookie().
*/
   
   if ($.browser.mobile) {
    if (getCookie('mobile') == null) {      
    	var mobile_setting = 'enable';
        // if (confirm('Would you like to go mobile?')) { mobile_setting = 'enable'; }
	setCookie('mobile', mobile_setting, 1);  
    }
      if (document.referrer.substring(0, 8) == "http://m") { 
      	setCookie('mobile', 'disable', 1);  
      }
      if (window.parent.frames.length>0) { 
      	setCookie('mobile', 'disable', 1);  
      }      
   }  
$(function() { // on DOM ready

    if ($.browser.mobile) {    
   	$('#mobile_float').show();
    }
    
    $('#mobile_on').click(function() { 
    	setCookie('mobile', 'enable', 14);  
    	location.replace("http://m.usfca.edu/");
    });
    
    if ($.browser.safari || $.browser.chrome) {
        $(".navigation li").css( "margin-bottom",".64em" );
    }    

    $('#homepage .usfconnect_username').mouseup(function() { $('#password_hide').show(); $('#socialmedia').hide(); });
    $('#homepage .usfconnect_username').keypress(function() { $('#password_hide').show(); $('#socialmedia').hide(); });
    $('#homepage .usfconnect').mouseleave(function() { 
    	setTimeout( function()
          {
             $('#password_hide').hide(); $('#socialmedia').show();
    	  }, 20000); });
         
    // searchform
    var doSearch = function() {
	var searchquery = '';
    	if ($("#ctl00_ContentPlaceHolder1_search_query").length > 0){
	       	searchquery = $('#ctl00_ContentPlaceHolder1_search_query').val();
	}
    	if ($("#ctl00_search_query").length > 0){
	       	searchquery = $('#ctl00_search_query').val();
	}
        window.location = 'http://www.usfca.edu/results.html?cx=009000563526072549411%3Abmq5fndvvr8&cof=FORID%3A11&q=' + searchquery;
    }
    $('#search_go').click(function() { doSearch(); });
    $('#ctl00_ContentPlaceHolder1_search_query').keyup(function(e) {
        if (e.keyCode == 13) { doSearch(); }
    });
    $('#ctl00_search_query').keyup(function(e) {
        if (e.keyCode == 13) { doSearch(); }
    });    
    $('.captioned').hover(function(e){
	this.t = this.title;
	this.title = "";	
	var c = (this.t != "") ? this.t : "";
	var l = c.length;
	$(this).append("<span class='tooltip'>" + c + "</span>");
	tipsize = $(this).find("img").width();
	$(this).find('.tooltip').css('width', tipsize - 20).show();
        if (l > 50) {
	   $(this).find('.tooltip').css('height', 40);
	   $(this).find('.tooltip').css('margin-top', -50);
        }
    },
	function(){
		this.title = this.t;	
		$(this).find('.tooltip').remove();        
    });	

    $('.captionedon').each(function(){
	this.t = this.title;
	this.title = "";	
	var c = (this.t != "") ? this.t : "";
	var l = c.length;
	$(this).append("<span class='tooltip'>" + c + "</span>");
        if (l > 50) {
	   $(this).find('.tooltip').css('height', 40);
	   $(this).find('.tooltip').css('margin-top', -50);
        }
    });	
    	
    $('.thumbviewer').prepend("<div id='previewpane'><img src='' alt='Image preview' /></div>");	
    	firstThumb = $('.thumbviewer>img:first').attr("src");
    	$('#previewpane>img').attr("src", firstThumb);
    	$('#previewpane').append("<div>" + "Roll over thumbnails to see larger images." + "</div>");
    	
    $('.thumbviewer>img').hover(function(e){
    	$("#previewpane>div").remove();
    	this.t = this.title;
    	this.title = "";	
    	var c = (this.t != "") ? this.t : "";
	if (c !='') {
	$('#previewpane').append("<div>" + c + "</div>");
	}
	$('#previewpane>img').attr("src", this.src);
	$('#previewpane>img').fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
    });	  
    
    if ($('.rightview').length) {    
    $('.rightview').prepend("<div id='previewpane'><img src='' alt='Image preview' /></div>");	
    	firstThumb = $('.rightview>img:first').attr("src");
    	firstThumb = firstThumb.substring(0, firstThumb.length-10) + ".jpg";
    	$('#previewpane>img').attr("src", firstThumb);
    	$('#previewpane').append("<div>" + "Click on thumbnails to see larger images." + "</div>");
    }	
    $('.rightview>img').click(function(e){
    	$("#previewpane>div").remove();
    	newPreview = this.src;
    	newPreview = newPreview.substring(0, newPreview.length-10) + ".jpg";
    	this.t = this.title;
    	// this.title = "";	
    	var c = (this.t != "") ? this.t : "";
	if (c !='') {
	$('#previewpane').append("<div>" + c + "</div>");
	}
	$('#previewpane>img').attr("src", newPreview);
	$('#previewpane>img').fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
    });	   
    	
    
    $('img.preview').hover(function(e){
	this.t = this.title;
	this.title = "";	
	var c = (this.t != "") ? "<br/>" + this.t : "";
	$('body').append("<p id='preview'><img src='"+ this.src +"' alt='Image preview' />"+ c +"</p>");								 
	$('#preview')
		.css("top",(e.pageY - 10) + 'px')
		.css("left",(e.pageX + 10) + 'px')
		.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$('img.preview').mousemove(function(e){
		$("#preview")
			.css('top',(e.pageY - (this.height * 2)) + 'px')
			.css('left',(e.pageX + 10) + 'px');
			// alert (this.height);
	});

    $('.videolist').prepend("<div id='videopane'><iframe frameborder='0' id='ifrm' name='ifrm'>Your browser doesn't support iframes.</iframe></div>");	
    	firstThumb = $('.videolist>ul>li>a:first').attr('href');
    	$('#videopane>iframe').attr('src', firstThumb);
	$("#videopane>iframe")
			.css('width','640px')
			.css('height','500px')
			.css('float','right');    	
    	
    $('.videolist>ul>li>a').click(function(e){
    	this.t = this.title;
    	this.title = "";	
    	var c = (this.t != "") ? this.t : "";
	$('#videopane>iframe').attr('src', this.href);
	return false;
    },
	function(){
		this.title = this.t;	
    });	  
    

    var doSearchVA = function() {
        var query = $('#vasearch').val();
        window.location = 'http://emt.askadmissions.net/usfca/ask.aspx?did=2&cid=9&quser=' + query + '&submit=Ask';
    }
    if ($('#vasearch')) {
        $('#btnask').click(function() { doSearchVA(); });
        $('#vasearch').keyup(function(e) {
            if (e.keyCode == 13) { doSearchVA(); }
        });
    }
    $.easing.def = 'easeInOutSine';
    // Collapsing menus
    $('.collapse>div>a').toggle(function() {
        if (!$(this).parent().parent().is('.open')) {
            $(this).parent().parent().addClass('open');
            $(this).html("Close All");
            $(this).parent().parent().find('h4').css('background-image', 'url(/images/navigation/arrow_step_dn.gif)');
            $(this).parent().parent().find('h4').next('span').slideDown('fast');
        }
        else {
            $(this).parent().parent().removeClass('open');
            $(this).html("Show All");
            $(this).parent().parent().find('h4').css('background-image', 'url(/images/navigation/arrow_step_rt.gif)');
            $(this).parent().parent().find('h4').next('span').slideUp('fast');
        }
    }, function() {
        if (!$(this).parent().parent().is('.open')) {
            $(this).html("Close All");
            $(this).parent().parent().addClass('open');
            $(this).parent().parent().find('h4').css('background-image', 'url(/images/navigation/arrow_step_dn.gif)');
            $(this).parent().parent().find('h4').next('span').slideDown('fast');
        }
        else {
            $(this).html("Show All");
            $(this).parent().parent().removeClass('open');
            $(this).parent().parent().find('h4').css('background-image', 'url(/images/navigation/arrow_step_rt.gif)');
            $(this).parent().parent().find('h4').next('span').slideUp('fast');
        }
        return false;
    });
    $('.collapse>h4>a').toggle(function() {
        if ($(this).parent().is('.opened')) {
            $(this).parent().removeClass('opened');
            $(this).parent().next('span').removeClass('opened');
            return true;
        }
        if (!$(this).parent().parent().is('.open')) {
            $(this).parent().css('background-image', 'url(/images/navigation/arrow_step_dn.gif)');
            $(this).parent().next('span').slideDown('fast');
        }
        else {
            $(this).parent().css('background-image', 'url(/images/navigation/arrow_step_rt.gif)');
            $(this).parent().next('span').slideUp('fast');
        }
    }, function() {
        if (!$(this).parent().parent().is('.open')) {
            $(this).parent().css('background-image', 'url(/images/navigation/arrow_step_rt.gif)');
            $(this).parent().next('span').slideUp('fast');
        }
        else {
            $(this).parent().css('background-image', 'url(/images/navigation/arrow_step_dn.gif)');
            $(this).parent().next('span').slideDown('fast');
        }
        return true;
    });

    // Blocks
    $('.block').each(function() { // find each image in a block
        if (!$(this).is('.long,.extra-long,.full-width,.double-plus')) { // skip this for wide blocks
            $(this).find('.caption').css('opacity', 0).show();
            $(this).hover(function() { // on mouse enter
                var link_more = $(this).find('.link_more').show();
                var caption = $(this).find('.caption,.link_more'); // store the caption
                clearTimeout(caption.data('timer')); // clear any timer
                caption.stop().fadeTo(300, 1, 'easeOutSine'); // fade in the caption
            }, function() { // on mouse leave
                var caption = $(this).find('.caption,.link_more'); // store the caption
                caption.data('timer', setTimeout(function() { // set (and store) the timeout before
                    caption.stop().fadeTo(600, 0, 'easeInSine'); // hiding the caption
                }, 200));
            });
        }
    });
    $('.block .draggable.image').each(function() { // draggable images
        var draggable = $(this),
			map = draggable.find('.map'),
			img = map.find('img'),
			imgWidth = img.width(),
			imgHeight = img.height(),
			block = draggable.parents('.block'),
			blockWidth = block.width(),
			blockHeight = block.height(),
			maxHeight = 490,
			currentZoom = 1,
			minZoom = Math.max((blockWidth + 20) / imgWidth, (maxHeight + 20) / imgHeight),
			info = $('<div class="pin_info"/>').prependTo(draggable);
        map.css({ width: imgWidth, height: imgHeight });
        img.css({ width: '100%', height: '100%' });
        map.wrap('<div class="map_wrapper"></div>'); // this container keeps the draggable image inside the block
        var wrapper = draggable.find('.map_wrapper');
        draggable
			.prepend('<div class="zoom_controls"><a class="zoom_in" href="#">+</a><a class="zoom_out" href="#">-</a></div>')
			.find('.caption').append('<div class="expand"><a href="#">Click to expand</a></div>');
        var zoomTimer,
			zoomIn = draggable.find('.zoom_in'),
			zoomOut = draggable.find('.zoom_out'),
			zoomTo = function(zoom) {
			    var width = map.width(),
					height = map.height(),
					targetHeight = Math.floor(imgHeight * zoom),
					targetWidth = Math.floor(imgWidth * zoom),
					areaHeight = draggable.height();
			    if (zoom < minZoom) {
			        zoomOut.addClass('disabled');
			        return;
			    } else if (zoom > 1) {
			        zoomIn.addClass('disabled');
			        return;
			    } else {
			        var deltaZoom = currentZoom - zoom;
			        currentZoom = zoom;
			        zoomIn.add(zoomOut).removeClass('disabled');
			        var position = map.position(),
						targetTop = Math.floor(position.top + ((height - targetHeight) / 2)),
						targetLeft = Math.floor(position.left + ((width - targetWidth) / 2));
			        // IN IE, what are the targetTop and targetLeft here? are they always negative?!
			        if (targetLeft > 0) targetLeft = 0; // if we're off the left edge, set the position to the left edge
			        else if (targetLeft + targetWidth < blockWidth) targetLeft = blockWidth - targetWidth; // or, if we're off the right edge, set the position to the right edge 
			        if (targetTop > 0) targetTop = 0; // if we're off the left edge, set the position to the left edge
			        else if (targetTop + targetHeight < areaHeight) targetTop = areaHeight - targetHeight; // or, if we're off the bottom edge, set the position to the top edge 
			        map.css({ width: targetWidth, height: targetHeight, left: targetLeft, top: targetTop }); // resize and reposition the map
			        wrapper.css({ marginLeft: '-' + (targetWidth - blockWidth) + 'px', marginTop: '-' + (targetHeight - areaHeight) + 'px', width: ((targetWidth * 2) - blockWidth) + 'px', height: ((targetHeight * 2) - areaHeight) + 'px' }); // resize the container
			        if ($.browser.msie && $.browser.version < 8) {
			            wrapper.css({ marginTop: 0, top: '-' + (targetHeight - areaHeight) + 'px', marginLeft: 0, left: '-' + (targetWidth - blockWidth) + 'px' });
			            map.css({ marginTop: (targetHeight - areaHeight), marginLeft: (targetWidth - blockWidth) });
			        }
			    }
			};
        draggable.find('.zoom_controls a').click(function() {
            map.trigger('mousedown.draggable', event);
            return false;
        })
			.mousedown(function(e) {
			    var scale = $(this).is('.zoom_in') ? 0.05 : -0.05;
			    zoomTo(currentZoom + scale);
			    zoomTimer = setInterval(function() { zoomTo(currentZoom + scale); }, 50);
			    return false;
			})
			.bind('mouseup mouseout', function() {
			    clearInterval(zoomTimer);
			});
        draggable.find('.expand a').toggle(function() {
            var self = $(this);
            draggable.animate({ height: maxHeight }, { duration: 1000, step: function() { zoomTo(currentZoom); }, complete: function() { self.text('Click to collapse'); } });
            $('#main').animate({ paddingTop: maxHeight + 20 }, 1000);
            return false;
        }, function() {
            var self = $(this);
            draggable.animate({ height: blockHeight }, { duration: 1000, step: function() { zoomTo(currentZoom); }, complete: function() { self.text('Click to expand'); } });
            $('#main').animate({ paddingTop: blockHeight + 20 }, 1000);
            return false;
        }
		);
        draggable.find('.pin').click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            info.html($(this).children().eq(0).html() + '<a class="close" href="#"></a>').show();
            info.find('a.close').click(function() { $(this).parent().hide(); draggable.find('.active').removeClass('active'); return false; });
        });
        if ($.browser.msie && $.browser.version < 8) {
            wrapper.css({ position: 'relative' });
        }
        map.draggable({ cursor: 'move', containment: 'parent' }); // activate the draggable
        zoomTo(0.40); // default a little zoomed out
        zoomTo(0.50); // default a little zoomed out
    });

    $('.block .slideshow').each(function() { // find each slideshow in a block

        var slideshow = $(this);
        slideshow.slideshow({ auto: slideshow.is('.auto'),slower:slideshow.is('.slower') }); // initialize the slideshow with the auto-advance flag
    });
    if ($('.block .video').length) { // if there are video blocks
        $.ajaxSetup({ cache: true });
        $.getScript('https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js', function() { // grab swfObject, then
            $('.block .video').each(function() { // find blocks
                var video = $(this),
					url = $(this).find('a').attr('href'),
					swf = (url.indexOf('/v/') > -1 ? url : url.replace(/[^?].*?v=([^&]*)/i, 'http://www.youtube.com/v/$1&hl=en&fs=1')) + '&enablejsapi=1&hd=1'; // parse out the linked SWF, force-enabling the JS api and the HD quality
                if (video.parent().is('.long')) { // if it's a long block (i.e. on the homepage)
                    if (($.browser.msie && $.browser.version < 7) || (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) return; // IE6 will just be links directly to the Youtube page
                    var blocks = video.parent().parent(),
					 	teaser = video.find('a'),
						grayout = $('<div class="grayout"/>').appendTo(video).fadeTo(0, 0); // add a grayout div at 0% opacity
                    teaser.click(function() { // attach a click event which
                        $('<div class="player"><div id="youtube_embed">Flash Player 8 or above is required to view this video.</div></div>').appendTo(video); // adds the player div
                        swfobject.embedSWF(swf, // embed the linked SWF
							'youtube_embed', // replacing the item with this ID
							'560', '320', // width&height
							'8', null, null,
							{ allowScriptAccess: 'always', wmode: 'transparent', allowFullScreen: 'true' }, // needed for JS api
							{id: 'youtube_embed' }
						);
                        grayout.show().stop().fadeTo(500, 1, function() { // fade out the grayout and then
	                    video.find('.close').remove(); // remove the close button
                            teaser.hide(); // hide the teaser
                            blocks.animate({ height: '320px' }, 800, 'easeOutSine', function() { // grow the block div					
                                grayout.stop().fadeTo(500, 0, function() { grayout.hide(); }); // fadeout and hide the grayout
                            }).css('overflow', 'visible'); // make sure the overflow is visible during the animation
                        });
                        return false;
                    });
                    if ($('div').is('#homepage')) { // if we're on the homepage
                        $('#collapse').click(function() { // attach a click event to the collapse link
                            $(this).blur();
                            try { document.getElementById('youtube_embed').pauseVideo(); } catch (e) { }
                            grayout.show().stop().fadeTo(500, 1, function() { // fade in the grayout and then
                                teaser.show(); // show the teaser
                                blocks.animate({ height: '150px' }, 800, 'easeOutSine', function() { // shrink the block
                                    video.find('.player').remove(); // remove the player
                                    grayout.stop().fadeTo(500, 0, function() { grayout.hide(); }); // fadeout and hide the grayout
                                }).css('overflow', 'visible'); // make sure the overflow is visible during the animation
                            });
                            return false;
                        });
                    }
                } else { // for square blocks (pop-up player)
                    var thisTitle = '';
                    if ($('div').is('#homepage')) { thisTitle = $(this).find("img").attr('title') }
                    video.find('a').append('<span><div>' + thisTitle + '</div></span>');
                    if (($.browser.msie && $.browser.version < 7) || (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) return; // IE6 will just be links directly to the Youtube page
                    video.find('a').click(function() { // add the "Click to play" overlay and attach a click event which
                        $('.block .video .player').remove(); // stop&remove any other videos
                        var player = $('<div class="player"><div id="youtube_embed">Flash Player 8 or above is required to view this video.</div><a class="close" href="#"></a></div>').appendTo(video),
							leftEdge = player.offset().left, // offset from the lefthand side of the page
							rightEdge = leftEdge + player.width(), // the right edge
							pageWidth = $('body').width(); // page width (with 20 pixel buffer)
                        if ($.browser.msie) player.parents().css('z-index', '500'); // for IE (we need to create a new, high stacking context)
                        if (rightEdge > pageWidth) player.css('left', -85 - (rightEdge - pageWidth) - 20); // if the right edge is off the window width
                        if (leftEdge < 0) player.css('left', -85 - leftEdge);
                        swfobject.embedSWF(swf, // embed the linked SWF
							'youtube_embed', // replacing the item with this ID
							'100%', '100%', // width&height
							'8', null, null,
							{ allowScriptAccess: 'always', wmode: 'transparent', allowFullScreen: 'true' }, // needed for JS api
							{id: 'youtube_embed' }
						);
                        return false; // cancel the original click
                    });
                }
            });
            $('.block .video .player .close').live('click', function() { // close links
                $(this).parent().remove(); // remove the video
                if ($.browser.msie) $(this).parents().css('z-index', '');
                return false; // cancel the original click
            })
        });
    }

    $('.catalog h1:empty').addClass('nomargin');
    $('.ekflexmenu_submenu_items:empty').addClass('nomargin');
    
    // Dropdown menus
    $('.dropdown>a').click(function() { return false; }); // cancel all click events
    $('.dropdown,#navigation.horizontal li').hover(function() { // when the mouse enters a dropdown
        //	if($(this).is('#navigation li ul li')) return false;
        var self = $(this);
        clearTimeout(self.data('closeTimer')); // cancel the closing
        self.data('openTimer', setTimeout(function() { // set a timer to show the dropdown
            self.addClass('active') // add the active class, which shows the contents
				.siblings().removeClass('active'); // and remove the active class from any siblings
        }, 200));
    }, function() {
        var self = $(this);
        clearTimeout(self.data('openTimer')); // cancel the opening
        if (!self.data('sticky')) {
            self.data('closeTimer', setTimeout(function() { // set a timer to hide the dropdown if the mouse doesn't re-enter
                self.removeClass('active'); // remove the active class
            }, 500));
        }
    });
    $('.dropdown input').focus(function() { // when focusing on an input element inside a dropdown
        var dropdown = $(this).parents('.dropdown'); // find the dropdown
        dropdown.data('sticky', true); // set the flag to stick it open
    }).blur(function() { // when blurring
        var dropdown = $(this).parents('.dropdown'); // find the dropdown
        dropdown.data('sticky', false); // and remove the sticky flag
    });
    $('#nav_meta_search a').click(function() { // if clicking the search link
        $('#search_query').focus(); // focus the query box
    });
    // Quick link dropdowns
    $('.expand_ql_drop').hover(function() { // when the mouse enters a dropdown
        var self = $(this);
        clearTimeout(self.data('closeTimer')); // cancel the closing
        self.find('.ekflexmenu_submenu_items_hidden').show();
    }, function() {
        var self = $(this);
        self.data('closeTimer', setTimeout(function() { // set a timer to show the dropdown
            self.find('.ekflexmenu_submenu_items_hidden').hide();
        }, 500));
    }).find('.ekflexmenu_submenu_items_hidden').hide();

    $('.expand_dept').find('.ekflexmenu_menu_level_1').find('.ekflexmenu_submenu_items').hide();
    $('.expand_dept').find('.ekflexmenu_button_selected').siblings('ul').show();

    $('.expand_inside').find('.ekflexmenu_menu_level_1').find('.ekflexmenu_submenu_items').hide();
    $('.expand_inside').find('.ekflexmenu_button_selected').siblings('ul').show();


    // Switchers
    $('.switcher>h4>a').click(function() { // when clicking a switcher
        $('#sidebar').hide();
        var switcher = $(this).parent().parent();
        switcher.toggleClass('active') // toggle the active class
			.find('.contents').toggle(200); // and show the contents
        if (switcher.is('.active')) { // if activating
            $('<div id="whiteout"/>').prependTo('body') // add a whiteout overlay
				.one('click', function() { // which, when clicked
				    switcher.find('>h4>a').click(); // is the same as clicking the switcher
				});
        } else { // if deactivating
        $('#sidebar').show();
            $('#whiteout').remove(); // remove the whiteout overlay
        }
        return false; // cancel the original click
    });
    // Tabs
    $('.tabs .tabs_menu li a').click(function() {
    	$('.tabs div').show();
        var tab = $(this).parent(),
    		content = $('#' + tab.attr('id') + '_content');
        tab.addClass('active').siblings().removeClass('active');
        content.show().siblings('.tab').hide();
        return false;
    }).eq(0).click();
    // Tables with alternating rows
    $('table tr:odd').addClass('odd');
    $('table.columned tr:odd').removeClass('odd');
    $('table.columned tr').addClass('columned');
    $('table.columned td:nth-child(1)').addClass('half');
    $('table.columned td:nth-child(2)').addClass('columned');
    // Prepopulate USF Connect boxes
    $('.usfconnect_username').inlineLabel('Username');
    $('.usfconnect_password').inlineLabel('Password');
    // Prepopulate Gleeson boxes
    $('#books_query').inlineLabel('Ignacio: Library Catalog');
    $('#proQuestSearchInput').inlineLabel('ProQuest');
    $('#gvrlx_search').inlineLabel('Gale Virtual Reference Library');
    $('#queryword').inlineLabel('Oxford English Dictionary');
    $('#ebscohostsearchtext');
    $('#journals_query').inlineLabel('Journal Title Begins with...');
    $('#reserves_query').inlineLabel('Instructor (Last Name)');
    $('#collections_query').inlineLabel('example: St Ignatius Church');
    $('#qa_input').inlineLabel('Enter Search Here');
    $('#qa_input_library').inlineLabel('Enter Subject or Database Name');
    
    
    // Prepopulate USF Connect boxes
    $('.usfconnect_username').inlineLabel('Username');
    $('.usfconnect_password').inlineLabel('Password');

    // Prepopulate Gleeson boxes
    $('#books_query').inlineLabel('Ignacio: Library Catalog');
    $('#proQuestSearchInput').inlineLabel('ProQuest');
    $('#gvrlx_search').inlineLabel('Gale Virtual Reference Library');
    $('#findword2').inlineLabel('Oxford English Dictionary');
    $('#tab_books_content .radios input').change(function() {
        var value = $('.radios input[name=searchtype_option]:checked').val();
        $(this).parents('.tab').find('form').attr('action', 'http://ignacio.usfca.edu/search/' + value);
    });
    $('#books_form').submit(function() { // keyword search override!
        var value = $('.radios input[name=searchtype_option]:checked').val();
        if (value == 'X') {
            var query = $('#books_query').val();
            window.location = 'http://ignacio.usfca.edu/search/X?SEARCH=' + query + '&SORT=D';
            return false;
        }
    });

    // Quickaccess (on gateway pages)
    if ($('.template-gateway .quickaccess').length) { // if quickaccess is present
        $.ajaxSetup({ cache: true });
        $.getScript('/scripts/quickaccess.js', function() {
            $('.quickaccess input').quickaccess({ links: '.navigation a,#nav_meta ul a', sort: true, removeDuplicates: true, maxResults: 10 });
        });
    }

    // Quickaccess (library database search)
    if ($('#library_qa .quickaccess').length) { // if quickaccess and quickaccess.js are present
        if (typeof $.fn.quickaccess == 'function') {
            $('.quickaccess input').quickaccess({ links: [{ selector: '#qa_subject a', title: 'Subjects:' }, { selector: '#qa_atoz a', title: 'Databases:'}], focus: false, inlineLabel: 'Search databases by subject or name', sort: true, removeDuplicates: true, maxResults: 20 });
        }
    }

	// BEGIN Tracking code
	$('a').click(function() {
	  var $a = $(this);
	  var href = $a.attr('href');
		if (href.match(/\.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)$/i)) {
		    var category = 'download';
		    var event = 'click';
		    var label = href;  	
		    pageTracker._trackEvent(category, event, href);				    
		    if (window.console)	{window.console.log(href + " was tracked. ");}
		}
		
	});
	// END Tracking Code

if ($('.catalog').length) {
	var el = $('.catalog');
	el.html(el.html().replace(/Level restricted to Graduate./ig, ""));
	el.html(el.html().replace(/College restricted to School of Nursing./ig, ""));			   
	el.html(el.html().replace(/College restricted to School of Education./ig, ""));
	el.html(el.html().replace(/Prerequisite: /ig, "&bull; Prerequisite: "));
	el.html(el.html().replace(/Prerequisites: /ig, "&bull; Prerequisites: "));
	el.html(el.html().replace(/Degree restricted to/ig, "<br />&bull; Degree restricted to"));
	el.html(el.html().replace(/Majors restricted to/ig, "<br />&bull; Majors restricted to"));
}

});

$.fn.extend({
    slideshow: function(options) {
        var self = this;
        var frameRate = 1000;
        if (this.is('.slower')) { frameRate = 8000; }
        options = options || {};
        if (typeof options == 'object') { // if options is unset or the options object, we create a new slideshow
            s = {
                auto: options.auto || false // CSS selector for elements which should destroy the overlay onclick
            };
            self.data('current', self.children(':first').addClass('slideshow_current')); // store the first image as the current image
           		self.before('<div class="slideshow_controls"><a class="slideshow_prev" href="#"></a><a class="slideshow_next" href="#"></a></div>') // attach the control panel
            self.prev().find('.slideshow_prev').click(function() { // find the previous-image link and attach its click
                self.slideshow('prev'); // show the previous image
                return false; // cancel the original click
            }).next().click(function() { // and the next link
                self.slideshow('next'); // show the next image
                return false; // cancel the original click
            });
            if (s.auto) { // if this slideshow is auto-advancing
               var frameRate = 5000;
               if (this.is('.slower')) { frameRate = 8000; }
                var controls = self.prev().stop().fadeTo(0, 0); // fade the controls to 0
                self.parent().hover(function() {
                    self.addClass('paused');
                    controls.stop().fadeTo(300, 1); // fade in the controls
                }, function() {
                    self.removeClass('paused');
                    controls.stop().fadeTo(600, 0); // fade in the controls					
                });
                setInterval(function() { // on a timer
                    if (!self.is('.paused')) { // if the slideshow isn't currently paused
                        self.slideshow('next'); // show the next image
                    }
                }, frameRate);
            }
        } else { // otherwise, the user has sent a command			
            var current = self.data('current'),
				next;
            if (!current.is(':animated')) { // if we're not currently transitioning
                if (options == 'next') { // if showing the next image
                    next = current.next(); // get it
                    if (!next.length) { // if there isn't a next image
                        next = self.children(':first'); // go back to the first image
                    }
                } else { // if showing the previous image
                    next = current.prev(); // get it
                    if (!next.length) { // if there isn't a next image
                        next = self.children(':last'); // go back to the last image
                    }
                }
                next.show(); // show the next image
                current.fadeOut(1000, function() { // fade out the current image
                    current.hide().fadeTo(0, 1).removeClass('slideshow_current'); // hide the current image, then reset its opacity
                    self.data('current', next.addClass('slideshow_current')); // and store the next image as the current
                });
            }
        }
        return self;
    },
    inlineLabel: function(text, style) {
        if (typeof style != 'string') { // if no style is specified (including empty strings)
            style = 'inline_label'; // the default CSS class for placeholder text	
        }
        var self = $(this),
			blur = function() { // a blur function that doesn't fire the browser blur event
			    var val = $.trim(self.val());
			    if (!val || val == text) { // if this input has no contents or the contents are identical to the placeholder text
			        self.addClass(style) // add the inline_label class
						.val(text) // set the appropriate text
						.one('focus', function() { // and, on the first focus
						    self.val('') // remove that text
								.removeClass(style); // and the inline_label class
						});
			    }
			};
        self.blur(blur);
        blur();
        return this; // return original element for chaining
    }
});

function onYouTubePlayerReady() { // called when YouTube embeds are ready for interaction
    var yt = document.getElementById('youtube_embed');
    yt.playVideo();
}

