/* USF Javascript Effects (requires jQuery and jQuery UI effects) */
/* by White Whale Web Services */

$(function() { // on DOM ready

	/**
	 * 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);


    if ($.browser.mobile) {    
   	$('#blocks').hide();
	$('.column.fixed').css('display', 'none');
	$('#sidebar').css('padding-top', '0');
	$('#main').css('width', '730px');
	$('#main').css('padding-top', '0');
	$('#main').css('margin-left', '0');
    }	
    
    $.easing.def = 'easeInOutSine';
    // 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 img = $(this).find('img'),
			imgWidth = img.width(),
			imgHeight = img.height(),
			block = $(this).parents('.block'),
			blockWidth = block.width(),
			blockHeight = block.height();
        img.wrap('<div style="margin-left:-' + (imgWidth - blockWidth) + 'px;margin-top:-' + (imgHeight - blockHeight) + 'px;width:' + ((imgWidth * 2) - blockWidth) + 'px;height:' + ((imgHeight * 2) - blockHeight) + 'px;"/>'); // this container keeps the draggable image inside the block
        img.draggable({ cursor: 'move', containment: 'parent' }); // activate the draggable
    });

  	setTimeout(function(){
		$('.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
    	})
	}, 3000);

    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) || $.browser.mobile) 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) || $.browser.mobile) 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
            })
        });
    }
    // Quickaccess (on gateway pages)
    if ($('.quickaccess').length) { // if quickaccess and quickaccess.js are present
        $.ajaxSetup({ cache: true });
        $.getScript('/law/scripts/quickaccess.js', function() {
            $('.quickaccess input').quickaccess({ selector: '.lawlinks a', sort: true, duplicates: true, maxResults: 10, inlineLabel: 'Search this page...' });
        });
    }
    
        // 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;
    });
    
    // Dropdown menus
    $('.dropdown>a').click(function() { return false; }); // cancel all click events
    $('.dropdown,#navigation.horizontal li,.horiz_ql_drop 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
    });
    // Switchers
    $('.switcher>h4>a').click(function() { // when clicking a switcher
        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
            $('#whiteout').remove(); // remove the whiteout overlay
        }
        return false; // cancel the original click
    });
    // Tables with alternating rows
    $('table tr:odd').addClass('odd');
    // Prepopulate USF Connect boxes
    $('.usfconnect_username').inlineLabel('Username');
    $('.usfconnect_password').inlineLabel('Password');
});

$.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.addClass('paused') // the slideshow starts paused
				.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
                    }
                }, 4000);
            }
        } 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();
}

