/* USF Javascript Effects (requires jQuery and jQuery UI effects) */
/* by White Whale Web Services */

$(function() { // on DOM ready
    // searchform
    var doSearch = function() {
        var searchquery = $('#search_query').val();
        window.location = '/results.html?cx=009000563526072549411%3Abmq5fndvvr8&cof=FORID%3A11&q=' + searchquery;
    }
    $('#search_go').click(function() { doSearch(); });
    $('#search_query').keyup(function(e) {
        if (e.keyCode == 13) { doSearch(); }
    });
	$('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 - 10) + 'px')
			.css('left',(e.pageX + 10) + 'px');
	});
    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') }); // initialize the slideshow with the auto-advance flag
    });
    if ($('.block .video').length) { // if there are video blocks
        $.ajaxSetup({ cache: true });
        $.getScript('http://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) 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
                            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)
                    video.find('a').append('<span/>');
                    if ($.browser.msie && $.browser.version < 7) 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
            })
        });
    }

    // 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() {
        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');
    // 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');
    // Tables with alternating rows
    $('table tr:odd').addClass('odd');
    // 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 });
        }
    }
});


$.fn.extend({
    slideshow: function(options) {
        var self = this;
        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 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
                    }
                }, 5000);
            }
        } 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();
}

