﻿$(document).ready(function(){
	editMode();
	//heroRotator(10000,500);  -Removed by Katie Gilcrease on 6/15/2011 to address factoid jitter by setting transtionduration to zero seconds
	heroRotator(10000,0);
	headlineTitleAttr('#newsAndEventsResults','#newsAndEventsLink');
	headlineTitleAttr('#expertsCornerResults','#expertsCornerLink');
	$('.factoid_text').marquee('factoid_text');
	archiveToggle();
});


// Checks to see if the page is in edit mode
function editMode() {
	// If there is a web part zone on the page...
	if($('.ms-SPZone').length > 0){
		// ...add the editMode class to the body tag.
		$('body').addClass('editMode');
	}
}

// Handles the display and rotation of hero images
var interval = 0;
function heroRotator(showDuration,transitionDuration) {
	//$("#heroRotator .dfwp-item").css({opacity: 0.0}).css("display","block");  --Katie Gilcrease 6/15/2011 - Set fadeout transition to be opaque (not transparent)
	$("#heroRotator .dfwp-item").css({opacity: 1.0}).css("display","block");
	$("#heroRotator .dfwp-item:first").animate({opacity: 1.0}, transitionDuration).addClass("show");
	startHeroRotate(showDuration,transitionDuration);
}
function heroRotate(transitionDuration,dir) {
	var current = $("#heroRotator .dfwp-item.show");
	var next;
	if(dir){
		if(dir=="prev"){
			next = ((current.prev("#heroRotator .dfwp-item").length) ? ((current.prev("#heroRotator .dfwp-item").hasClass("show")) ? $("#heroRotator .dfwp-item:last") : current.prev()) : $("#heroRotator .dfwp-item:last"));
		}
		else if(dir=="next"){
			next = ((current.next("#heroRotator .dfwp-item").length) ? ((current.next("#heroRotator .dfwp-item").hasClass("show")) ? $("#heroRotator .dfwp-item:first") : current.next()) : $("#heroRotator .dfwp-item:first"));
		}
		stopHeroRotate();
	}
	else {
		next = (current.next("#heroRotator .dfwp-item").length) ? current.next("#heroRotator .dfwp-item") : $("#heroRotator .dfwp-item:first");
	}
	current.animate({opacity: 0.0}, transitionDuration).removeClass("show");
	next.css({opacity: 0.0}).addClass("show").animate({opacity: 1.0}, transitionDuration);
}
function startHeroRotate(showDuration,transitionDuration) {
	if($("#heroRotator .dfwp-item").length>1){
		interval = setInterval('heroRotate('+transitionDuration+')',showDuration);
	}
}
function stopHeroRotate() {
	clearInterval(interval);
}

// Handles the display of headlines in the title attribute of the link on hover
function headlineTitleAttr(results,link) {
	// Instantiate variable
	var t = "";
	
	// For each item in the result set...
	$(results).find('.link-item a').each(function(i){
		// ...if this is the first result...
		if(i==0){
			// ...get the text value
			t = '('+(i+1)+') '+$(this).text();
		}
		else {
			// ...get the text value preceeded by an ellipsis separator
			t = t+'... ('+(i+1)+') '+$(this).text();
		}
	});
		
	// Set the result string as the link title attribute
	$(link).attr('title',t);
	
	// If not in edit mode, remove the query results block from the page.
	if($('body.editMode').length < 1){
		$(results).remove();
	}
}

// Handles the toggle display of archived items on News & Events page
function archiveToggle() {
	if($('body.editMode').length < 1){
		$('.ms-WPBody:hidden').each(function(){
			$(this).wrapInner('<div class="toggleBody"></div>').prepend('<a class="toggleLink">Show Archived</a>').show();
		});
		$('.toggleLink').click(function(){
			if($(this).parent('.ms-WPBody').hasClass('show')){
				$(this).text('Show Archived').parent('.ms-WPBody').removeClass('show');
			}
			else{
				$(this).text('Hide Archived').parent('.ms-WPBody').addClass('show');
			}
		});
	}
}


/* PLUGINS */
// jQuery Marquee
/**
* author Remy Sharp
* url http://remysharp.com/tag/marquee
*/
(function ($) {
    $.fn.marquee = function (klass) {
        var newMarquee = [],
            last = this.length;

        // works out the left or right hand reset position, based on scroll
        // behavior, current direction and new direction
        function getReset(newDir, marqueeRedux, marqueeState) {
            var behavior = marqueeState.behavior, width = marqueeState.width, dir = marqueeState.dir;
            var r = 0;
            if (behavior == 'alternate') {
                r = newDir == 1 ? marqueeRedux[marqueeState.widthAxis] - (width*2) : width;
            } else if (behavior == 'slide') {
                if (newDir == -1) {
                    r = dir == -1 ? marqueeRedux[marqueeState.widthAxis] : width;
                } else {
                    r = dir == -1 ? marqueeRedux[marqueeState.widthAxis] - (width*2) : 0;
                }
            } else {
                r = newDir == -1 ? marqueeRedux[marqueeState.widthAxis] : 0;
            }
            return r;
        }

        // single "thread" animation
        function animateMarquee() {
            var i = newMarquee.length,
                marqueeRedux = null,
                $marqueeRedux = null,
                marqueeState = {},
                newMarqueeList = [],
                hitedge = false;
                
            while (i--) {
                marqueeRedux = newMarquee[i];
                $marqueeRedux = $(marqueeRedux);
                marqueeState = $marqueeRedux.data('marqueeState');
                
                if ($marqueeRedux.data('paused') !== true) {
                    // TODO read scrollamount, dir, behavior, loops and last from data
                    marqueeRedux[marqueeState.axis] += (marqueeState.scrollamount * marqueeState.dir);

                    // only true if it's hit the end
                    hitedge = marqueeState.dir == -1 ? marqueeRedux[marqueeState.axis] <= getReset(marqueeState.dir * -1, marqueeRedux, marqueeState) : marqueeRedux[marqueeState.axis] >= getReset(marqueeState.dir * -1, marqueeRedux, marqueeState);
                    
                    if ((marqueeState.behavior == 'scroll' && marqueeState.last == marqueeRedux[marqueeState.axis]) || (marqueeState.behavior == 'alternate' && hitedge && marqueeState.last != -1) || (marqueeState.behavior == 'slide' && hitedge && marqueeState.last != -1)) {                        
                        if (marqueeState.behavior == 'alternate') {
                            marqueeState.dir *= -1; // flip
                        }
                        marqueeState.last = -1;

                        $marqueeRedux.trigger('stop');

                        marqueeState.loops--;
                        if (marqueeState.loops === 0) {
                            if (marqueeState.behavior != 'slide') {
                                marqueeRedux[marqueeState.axis] = getReset(marqueeState.dir, marqueeRedux, marqueeState);
                            } else {
                                // corrects the position
                                marqueeRedux[marqueeState.axis] = getReset(marqueeState.dir * -1, marqueeRedux, marqueeState);
                            }

                            $marqueeRedux.trigger('end');
                        } else {
                            // keep this marquee going
                            newMarqueeList.push(marqueeRedux);
                            $marqueeRedux.trigger('start');
                            marqueeRedux[marqueeState.axis] = getReset(marqueeState.dir, marqueeRedux, marqueeState);
                        }
                    } else {
                        newMarqueeList.push(marqueeRedux);
                    }
                    marqueeState.last = marqueeRedux[marqueeState.axis];

                    // store updated state only if we ran an animation
                    $marqueeRedux.data('marqueeState', marqueeState);
                } else {
                    // even though it's paused, keep it in the list
                    newMarqueeList.push(marqueeRedux);                    
                }
            }

            newMarquee = newMarqueeList;
            
            if (newMarquee.length) {
                setTimeout(animateMarquee, 25);
            }            
        }
        
        // TODO consider whether using .html() in the wrapping process could lead to loosing predefined events...
        this.each(function (i) {
            var $marquee = $(this),
                width = $marquee.attr('width') || $marquee.width(),
                height = $marquee.attr('height') || $marquee.height(),
                $marqueeRedux = $marquee.after('<div ' + (klass ? 'class="' + klass + '" ' : '') + 'style="display: block-inline; width: ' + width + 'px; height: ' + height + 'px; overflow: hidden;"><div style="float: left; white-space: nowrap;">' + $marquee.html() + '</div></div>').next(),
                marqueeRedux = $marqueeRedux.get(0),
                hitedge = 0,
                direction = ($marquee.attr('direction') || 'left').toLowerCase(),
                marqueeState = {
                    dir : /down|right/.test(direction) ? -1 : 1,
                    axis : /left|right/.test(direction) ? 'scrollLeft' : 'scrollTop',
                    widthAxis : /left|right/.test(direction) ? 'scrollWidth' : 'scrollHeight',
                    last : -1,
                    loops : $marquee.attr('loop') || -1,
                    scrollamount : $marquee.attr('scrollamount') || this.scrollAmount || 2,
                    behavior : ($marquee.attr('behavior') || 'scroll').toLowerCase(),
                    width : /left|right/.test(direction) ? width : height
                };
            
            // corrects a bug in Firefox - the default loops for slide is -1
            if ($marquee.attr('loop') == -1 && marqueeState.behavior == 'slide') {
                marqueeState.loops = 1;
            }

            $marquee.remove();
            
            // add padding
            if (/left|right/.test(direction)) {
                $marqueeRedux.find('> div').css('padding', '0 ' + width + 'px');
            } else {
                $marqueeRedux.find('> div').css('padding', height + 'px 0');
            }
            
            // events
            $marqueeRedux.bind('stop', function () {
                $marqueeRedux.data('paused', true);
            }).bind('pause', function () {
                $marqueeRedux.data('paused', true);
            }).bind('start', function () {
                $marqueeRedux.data('paused', false);
            }).bind('unpause', function () {
                $marqueeRedux.data('paused', false);
            }).data('marqueeState', marqueeState); // finally: store the state
            
            // todo - rerender event allowing us to do an ajax hit and redraw the marquee

            newMarquee.push(marqueeRedux);

            marqueeRedux[marqueeState.axis] = getReset(marqueeState.dir, marqueeRedux, marqueeState);
            $marqueeRedux.trigger('start');
            
            // on the very last marquee, trigger the animation
            if (i+1 == last) {
                animateMarquee();
            }
        });            

        return $(newMarquee);
    };
}(jQuery));
/* end PLUGINS */
