$(document).ready(function() {

$.fn.simpleTabs = function(){ 
    //Default Action
    $(this).find(".tab_content").hide(); //Hide all content
    $(this).find("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(this).find(".tab_content:first").show(); //Show first tab content
    
    //On Click Event
    $("ul.tabs li").click(function() {
        $(this).parent().parent().find("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(this).parent().parent().find(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).show(); //Fade in the active content
        return false;
    });
};//end function

$("div[class^='simpleTabs']").simpleTabs(); //Run function on any div with class name of "Simple Tabs"


});

/* --------------------------------------------------------------------------- */

/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);

/* --------------------------------------------------------------------------- */

$(document).ready(function() {
    

    function megaHoverOver(){
        $(this).find(".sub").stop().fadeTo('fast', 1).show();
            
        //Calculate width of all ul's
        (function($) { 
            jQuery.fn.calcSubWidth = function() {
                rowWidth = 0;
                //Calculate row
                $(this).find("ul").each(function() {                    
                    rowWidth += $(this).width(); 
                }); 
            };
        })(jQuery); 
        
        if ( $(this).find(".row").length > 0 ) { //If row exists...
            var biggestRow = 0; 
            //Calculate each row
            $(this).find(".row").each(function() {                             
                $(this).calcSubWidth();
                //Find biggest row
                if(rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });
            //Set width
            $(this).find(".sub").css({'width' :biggestRow});
            $(this).find(".row:last").css({'margin':'0'});
            
        } else { //If row does not exist...
            
            $(this).calcSubWidth();
            //Set Width
            $(this).find(".sub").css({'width' : rowWidth});
            
        }
    }
    
    function megaHoverOut(){ 
      $(this).find(".sub").stop().fadeTo('fast', 0, function() {
          $(this).hide(); 
      });
    }


    var config = {    
         sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
         interval: 100, // number = milliseconds for onMouseOver polling interval    
         over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
         timeout: 500, // number = milliseconds delay before onMouseOut    
         out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
    };

    $("#navigation ul#main-nav li .sub").css({'opacity':'0'});
    $("#navigation ul#main-nav li").hoverIntent(config);
    
/* --------------------------------------------------------------------------- */
    
    // Hide and show taxonomy words when the length is greater than 5
    $('ul#articleTaxonomyWords li:gt(4)').parent().append('<li class="show_button"><a href="#">Show more...</a></li>');
    $('ul#articleTaxonomyWords li:gt(4)').not('.show_button').hide();
    
    $('ul#articleTaxonomyWords li.show_button a, ul#articleTaxonomyWords li.hide_button a').click(function(e) {
        
        e.preventDefault();  
        
        if($(this).parent().hasClass('show_button')) {
            $(this).html('Hide list...').parent().removeClass('show_button').addClass('hide_button');
            
            $('ul#articleTaxonomyWords li:hidden').show();
        }
        else
        {
            $(this).html('Show more...').parent().removeClass('hide_button').addClass('show_button');
            
            $('ul#articleTaxonomyWords li:gt(4)').not('.show_button, .hide_button').hide();
        }
    });

});

/* --------------------------------------------------------------------------- */

$(function () {
	  $('.bubbleInfo').each(function () {
	    // options
	    var distance = 10;
	    var time = 250;
	    var hideDelay = 500;

	    var hideDelayTimer = null;

	    // tracker
	    var beingShown = false;
	    var shown = false;
	    
	    var trigger = $('.trigger', this);
	    var popup = $('.popup', this).css('opacity', 0);

	    // set the mouseover and mouseout on both element
	    $([trigger.get(0), popup.get(0)]).mouseover(function () {
	      // stops the hide event if we move from the trigger to the popup element
	      if (hideDelayTimer) clearTimeout(hideDelayTimer);

	      // don't trigger the animation again if we're being shown, or already visible
	      if (beingShown || shown) {
	        return;
	      } else {
	        beingShown = true;

	        // reset position of popup box
	        popup.css({
	          top: -100,
	          left: -33,
	          display: 'block' // brings the popup back in to view
	        })

	        // (we're using chaining on the popup) now animate it's opacity and position
	        .animate({
	          top: '-=' + distance + 'px',
	          opacity: 1
	        }, time, 'swing', function() {
	          // once the animation is complete, set the tracker variables
	          beingShown = false;
	          shown = true;
	        });
	      }
	    }).mouseout(function () {
	      // reset the timer if we get fired again - avoids double animations
	      if (hideDelayTimer) clearTimeout(hideDelayTimer);
	      
	      // store the timer so that it can be cleared in the mouseover if required
	      hideDelayTimer = setTimeout(function () {
	        hideDelayTimer = null;
	        popup.animate({
	          top: '-=' + distance + 'px',
	          opacity: 0
	        }, time, 'swing', function () {
	          // once the animate is complete, set the tracker variables
	          shown = false;
	          // hide the popup entirely after the effect (opacity alone doesn't do the job)
	          popup.css('display', 'none');
	        });
	      }, hideDelay);
	    });
	  });
	});

/* --------------------------------------------------------------------------- */

/************************************************************************************
** jQuery Placehold version 0.3
** (cc) Jason Garber (http://sixtwothree.org and http://www.viget.com)
** Licensed under the CC-GNU GPL (http://creativecommons.org/licenses/GPL/2.0/)
*************************************************************************************/

;(function($) {
	$.fn.placehold = function( placeholderClassName ) {
		var placeholderClassName = placeholderClassName || "placeholder",
			supported = $.fn.placehold.is_supported();

		function toggle() {
			for ( i = 0; i < arguments.length; i++ ) {
				arguments[i].toggle();
			}
		}

		return supported ? this : this.each( function() {
			var $elem = $( this ),
				placeholder_attr = $elem.attr( "placeholder" );

			if ( placeholder_attr ) {
				if ( !$elem.val() || $elem.val() == placeholder_attr ) {
					$elem.addClass( placeholderClassName ).val( placeholder_attr );
				}

				if ( $elem.attr( "type" ) == "password" ) {
					var $pwd_shiv = $( "<input />", {
						"class": $elem.attr( "class" ) + " " + placeholderClassName,
						"value": placeholder_attr
					});

					$pwd_shiv.bind( "focus.placehold", function() {
						toggle( $elem, $pwd_shiv );
						$elem.focus();
					});

					$elem.bind( "blur.placehold", function() {
						if ( !$elem.val() ) {
							toggle( $elem, $pwd_shiv );
						}
					});

					$elem.hide().after( $pwd_shiv );
				}

				$elem.bind({
					"focus.placehold": function() {
						if ( $elem.val() == placeholder_attr ) {
							$elem.removeClass( placeholderClassName ).val( "" );
						}
					},
					"blur.placehold": function() {
						if ( !$elem.val() ) {
							$elem.addClass( placeholderClassName ).val( placeholder_attr );
						}
					}
				});

				$elem.closest( "form" ).bind( "submit.placehold", function() {
					if ( $elem.val() == placeholder_attr ) {
						$elem.val( "" );
					}

					return true;
				});
			}
		});
	};

	$.fn.placehold.is_supported = function() {
		return "placeholder" in document.createElement( "input" );
	};	
})(jQuery);

// initialize function
$().ready( function() {
	$( "input, textarea" ).placehold({
		placeholderClassName: "holder"
	});
});

/* --------------------------------------------------------------------------- */

/*
AnythingSlider v1.6.2 minified using Google Closure Compiler
Original by Chris Coyier: http://css-tricks.com
Get the latest version: https://github.com/ProLoser/AnythingSlider
*/

(function(d){d.anythingSlider=function(i,j){var a=this,b;a.$el=d(i).addClass("anythingBase").wrap('<div class="anythingSlider"><div class="anythingWindow" /></div>');a.$el.data("AnythingSlider",a);a.init=function(){a.options=b=d.extend({},d.anythingSlider.defaults,j);a.initialized=!1;d.isFunction(b.onBeforeInitialize)&&a.$el.bind("before_initialize",b.onBeforeInitialize);a.$el.trigger("before_initialize",a);a.$wrapper=a.$el.parent().closest("div.anythingSlider").addClass("anythingSlider-"+b.theme); a.$window=a.$el.closest("div.anythingWindow");a.$controls=d('<div class="anythingControls"></div>').appendTo(b.appendControlsTo!==null&&d(b.appendControlsTo).length?d(b.appendControlsTo):a.$wrapper);a.win=window;a.$win=d(a.win);a.$nav=d('<ul class="thumbNav" />').appendTo(a.$controls);a.flag=!1;a.playing=!1;a.slideshow=!1;a.hovered=!1;a.panelSize=[];a.currentPage=b.startPanel=parseInt(b.startPanel,10)||1;a.adj=b.infiniteSlides?0:1;a.outerPad=[a.$wrapper.innerWidth()-a.$wrapper.width(),a.$wrapper.innerHeight()- a.$wrapper.height()];b.playRtl&&a.$wrapper.addClass("rtl");a.original=[b.autoPlay,b.buildNavigation,b.buildArrows];if(b.expand)a.$outer=a.$wrapper.parent(),a.$window.css({width:"100%",height:"100%"}),a.outerDim=[a.$outer.width(),a.$outer.height()],a.checkResize();a.updateSlider();a.$lastPage=a.$currentPage;a.runTimes=d("div.anythingSlider").index(a.$wrapper)+1;a.regex=RegExp("panel"+a.runTimes+"-(\\d+)","i");if(!d.isFunction(d.easing[b.easing]))b.easing="swing";b.pauseOnHover&&a.$wrapper.hover(function(){a.playing&& (a.$el.trigger("slideshow_paused",a),a.clearTimer(!0))},function(){a.playing&&(a.$el.trigger("slideshow_unpaused",a),a.startStop(a.playing,!0))});var c,e=b.hashTags?a.gotoHash()||b.startPanel:b.startPanel;a.setCurrentPage(e,!1);a.slideControls(!1);a.$wrapper.bind("mouseenter mouseleave",function(b){a.hovered=b.type==="mouseenter"?!0:!1;a.slideControls(a.hovered,!1)});d(document).keyup(function(c){var e;e=a.$wrapper.is(".activeSlider")&&!c.target.tagName.match("TEXTAREA|INPUT|SELECT")&&b.showMultiple=== !1;switch(c.which){case 9:c=d(":focus");e=c.closest(".anythingSlider");e[0]===a.$wrapper[0]&&(a.makeActive(),a.$window.scrollLeft(0),a.gotoPage(c.closest(".panel").index()+a.adj));break;case 39:e&&b.enableKeyboard&&a.goForward();break;case 37:e&&b.enableKeyboard&&a.goBack()}});c="slideshow_paused slideshow_unpaused slide_init slide_begin slideshow_stop slideshow_start initialized swf_completed".split(" ");d.each("onShowPause onShowUnpause onSlideInit onSlideBegin onShowStop onShowStart onInitialized onSWFComplete".split(" "), function(e,f){d.isFunction(b[f])&&a.$el.bind(c[e],b[f])});d.isFunction(b.onSlideComplete)&&a.$el.bind("slide_complete",function(){setTimeout(function(){b.onSlideComplete(a)},0)});a.initialized=!0;a.$el.trigger("initialized",a)};a.updateSlider=function(){a.$el.children(".cloned").remove();a.$nav.empty();a.$items=a.$el.children();a.pages=a.$items.length;b.showMultiple=parseInt(b.showMultiple,10)||1;if(b.showMultiple>1){if(b.showMultiple>a.pages)b.showMultiple=a.pages;a.adjustMultiple=b.infiniteSlides&& a.pages>1?0:parseInt(b.showMultiple,10)-1;a.pages=a.$items.length-a.adjustMultiple}if(a.pages<=1)b.autoPlay=!1,b.buildNavigation=!1,b.buildArrows=!1,a.$controls.hide(),a.$nav.hide(),a.$forward&&a.$forward.add(a.$back).hide();else{b.autoPlay=a.original[0];b.buildNavigation=a.original[1];b.buildArrows=a.original[2];a.$controls.show();a.$nav.show();a.$forward&&a.$forward.add(a.$back).show();a.buildNavigation();if(b.autoPlay)a.playing=!b.startStopped,a.buildAutoPlay();b.buildArrows&&a.buildNextBackButtons()}b.infiniteSlides&& a.pages>1&&(a.$el.prepend(a.$items.filter(":last").clone().addClass("cloned").removeAttr("id")),b.showMultiple>1?a.$el.append(a.$items.filter(":lt("+b.showMultiple+")").clone().addClass("cloned").addClass("multiple").removeAttr("id")):a.$el.append(a.$items.filter(":first").clone().addClass("cloned").removeAttr("id")),a.$el.find(".cloned").each(function(){d(this).find("a,input,textarea,select").attr("disabled","disabled");d(this).find("[id]").removeAttr("id")}));a.$items=a.$el.children().addClass("panel"); a.setDimensions();b.resizeContents?(b.width&&(a.$items.css("width",b.width),a.$wrapper.css("width",a.getDim(a.currentPage)[0])),b.height&&a.$wrapper.add(a.$items).css("height",b.height)):a.$win.load(function(){a.setDimensions()});if(a.currentPage>a.pages)a.currentPage=a.pages;a.setCurrentPage(a.currentPage,!1);a.$nav.find("a").eq(a.currentPage-1).addClass("cur")};a.buildNavigation=function(){var c,e,g;b.buildNavigation&&a.pages>1&&a.$items.filter(":not(.cloned)").each(function(f){var h=f+1;e=(h=== 1?"first":"")+(h===a.pages?"last":"");g=d('<a href="#"></a>').addClass("panel"+h).wrap('<li class="'+e+'" />');a.$nav.append(g.parent());d.isFunction(b.navigationFormatter)?(c=b.navigationFormatter(h,d(this)),g.html("<span>"+c+"</span>"),parseInt(g.find("span").css("text-indent"),10)<0&&g.addClass(b.tooltipClass).attr("title",c)):g.html("<span>"+h+"</span>");g.bind(b.clickControls,function(c){if(!a.flag&&b.enableNavigation)a.flag=!0,setTimeout(function(){a.flag=!1},100),a.gotoPage(h),b.hashTags&& a.setHash(h);c.preventDefault()})})};a.buildNextBackButtons=function(){if(!a.$forward)a.$forward=d('<span class="arrow forward"><a href="#"><span>'+b.forwardText+"</span></a></span>"),a.$back=d('<span class="arrow back"><a href="#"><span>'+b.backText+"</span></a></span>"),a.$back.bind(b.clickArrows,function(b){a.goBack();b.preventDefault()}),a.$forward.bind(b.clickArrows,function(b){a.goForward();b.preventDefault()}),a.$back.add(a.$forward).find("a").bind("focusin focusout",function(){d(this).toggleClass("hover")}), a.$wrapper.prepend(a.$forward).prepend(a.$back),a.$arrowWidth=a.$forward.width()};a.buildAutoPlay=function(){if(!(a.$startStop||a.pages<2))a.$startStop=d("<a href='#' class='start-stop'></a>").html("<span>"+(a.playing?b.stopText:b.startText)+"</span>"),a.$controls.prepend(a.$startStop),a.$startStop.bind(b.clickSlideshow,function(c){b.enablePlay&&(a.startStop(!a.playing),a.playing&&a.goForward(!0));c.preventDefault()}).bind("focusin focusout",function(){d(this).toggleClass("hover")}),a.startStop(a.playing)}; a.checkResize=function(b){clearTimeout(a.resizeTimer);a.resizeTimer=setTimeout(function(){var e=a.$outer.width(),d=a.$outer[0].tagName==="BODY"?a.$win.height():a.$outer.height(),f=a.outerDim;if(f[0]!==e||f[1]!==d)a.outerDim=[e,d],a.setDimensions(),a.gotoPage(a.currentPage,a.playing,null,1);typeof b==="undefined"&&a.checkResize()},500)};a.setDimensions=function(){var c,e,g,f,h,i=0,k=b.showMultiple>1?b.width||a.$window.width()/b.showMultiple:a.$window.width(),j=a.$win.width();b.expand&&(c=a.$outer.width()- a.outerPad[0],e=a.$outer.height()-a.outerPad[1],a.$wrapper.add(a.$window).add(a.$items).css({width:c,height:e}),k=b.showMultiple>1?c/b.showMultiple:c);a.$items.each(function(l){g=d(this).children("*");b.resizeContents?(c=parseInt(b.width,10)||k,e=parseInt(b.height,10)||a.$window.height(),d(this).css({width:c,height:e}),g.length&&g[0].tagName==="EMBED"&&g.attr({width:"100%",height:"100%"}),g.length===1&&g.css({width:"100%",height:"100%"})):(c=d(this).width(),h=c>=j?!0:!1,g.length===1&&h&&(f=g.width()>= j?k:g.width(),d(this).css("width",f),g.css("max-width",f),c=f),c=h?b.width||k:c,d(this).css("width",c),e=d(this).outerHeight(),d(this).css("height",e));a.panelSize[l]=[c,e,i];i+=c});a.$el.css("width",i<b.maxOverallWidth?i:b.maxOverallWidth)};a.getDim=function(c){var c=b.infiniteSlides&&a.pages>1?c:c-1,e,d=a.panelSize[c][0],f=a.panelSize[c][1];if(b.showMultiple>1)for(e=1;e<b.showMultiple;e++)d+=a.panelSize[(c+e)%b.showMultiple][0],f=Math.max(f,a.panelSize[c+e][1]);return[d,f]};a.goForward=function(c){a.gotoPage(a.currentPage+ parseInt(b.changeBy,10)*(b.playRtl?-1:1),c)};a.goBack=function(c){a.gotoPage(a.currentPage+parseInt(b.changeBy,10)*(b.playRtl?1:-1),c)};a.gotoPage=function(c,e,d,f){e!==!0&&(e=!1,a.startStop(!1));b.changeBy!==1&&(c<0&&(c+=a.pages),c>a.pages&&(c-=a.pages));if(!(a.pages<=1)){a.$lastPage=a.$currentPage;if(typeof c!=="number")c=b.startPanel,a.setCurrentPage(c);if(!e||!b.isVideoPlaying(a))c>a.pages+1-a.adj&&(c=!b.infiniteSlides&&!b.stopAtEnd?1:a.pages),c<a.adj&&(c=!b.infiniteSlides&&!b.stopAtEnd?a.pages: 1),a.currentPage=c>a.pages?a.pages:c<1?1:a.currentPage,a.$currentPage=a.$items.eq(a.currentPage-a.adj),a.exactPage=c,a.$targetPage=a.$items.eq(c===0?a.pages-a.adj:c>a.pages?1-a.adj:c-a.adj),a.$el.trigger("slide_init",a),a.slideControls(!0,!1),e!==!0&&(e=!1),(!e||b.stopAtEnd&&c===a.pages)&&a.startStop(!1),a.$el.trigger("slide_begin",a),b.resizeContents||(e=a.getDim(c),a.$wrapper.filter(":not(:animated)").animate({width:e[0],height:e[1]},{queue:!1,duration:f||b.animationTime,easing:b.easing})),a.$el.filter(":not(:animated)").animate({left:-a.panelSize[b.infiniteSlides&& a.pages>1?c:c-1][2]},{queue:!1,duration:f||b.animationTime,easing:b.easing,complete:function(){a.endAnimation(c,d)}})}};a.endAnimation=function(c,e){c===0?(a.$el.css("left",-a.panelSize[a.pages][2]),c=a.pages):c>a.pages&&(a.$el.css("left",-a.panelSize[1][2]),c=1);a.exactPage=c;a.setCurrentPage(c,!1);a.$items.removeClass("activePage").eq(c-a.adj).addClass("activePage");a.hovered||a.slideControls(!1);a.$el.trigger("slide_complete",a);typeof e==="function"&&e(a);b.autoPlayLocked&&!a.playing&&setTimeout(function(){a.startStop(!0)}, b.resumeDelay-b.delay)};a.setCurrentPage=function(c,e){c=parseInt(c,10);c>a.pages+1-a.adj&&(c=a.pages-a.adj);c<a.adj&&(c=1);b.buildNavigation&&a.$nav.find(".cur").removeClass("cur").end().find("a").eq(c-1).addClass("cur");!b.infiniteSlides&&b.stopAtEnd&&(a.$wrapper.find("span.forward")[c===a.pages?"addClass":"removeClass"]("disabled").end().find("span.back")[c===1?"addClass":"removeClass"]("disabled"),c===a.pages&&a.playing&&a.startStop());if(!e){var d=a.getDim(c);a.$wrapper.css({width:d[0],height:d[1]}).add(a.$window).scrollLeft(0); a.$el.css("left",-a.panelSize[b.infiniteSlides&&a.pages>1?c:c-1][2])}a.currentPage=c;a.$currentPage=a.$items.eq(c-a.adj).addClass("activePage");a.makeActive()};a.makeActive=function(){a.$wrapper.is(".activeSlider")||(d(".activeSlider").removeClass("activeSlider"),a.$wrapper.addClass("activeSlider"))};a.gotoHash=function(){var b=a.win.location.hash.match(a.regex);return b===null?"":parseInt(b[1],10)};a.setHash=function(b){var e="panel"+a.runTimes+"-",d=a.win.location.hash;if(typeof d!=="undefined")a.win.location.hash= d.indexOf(e)>0?d.replace(a.regex,e+b):d+"&"+e+b};a.slideControls=function(c){var d=c?0:b.animationTime,g=c?b.animationTime:0,f=c?1:0,h=c?0:1;b.toggleControls&&a.$controls.stop(!0,!0).delay(d)[c?"slideDown":"slideUp"](b.animationTime/2).delay(g);b.buildArrows&&b.toggleArrows&&(!a.hovered&&a.playing&&(h=1,f=0),a.$forward.stop(!0,!0).delay(d).animate({right:h*a.$arrowWidth,opacity:f},b.animationTime/2),a.$back.stop(!0,!0).delay(d).animate({left:h*a.$arrowWidth,opacity:f},b.animationTime/2))};a.clearTimer= function(b){if(a.timer&&(a.win.clearInterval(a.timer),!b&&a.slideshow))a.$el.trigger("slideshow_stop",a),a.slideshow=!1};a.startStop=function(c,d){c!==!0&&(c=!1);if(c&&!d)a.$el.trigger("slideshow_start",a),a.slideshow=!0;a.playing=c;b.autoPlay&&(a.$startStop.toggleClass("playing",c).html("<span>"+(c?b.stopText:b.startText)+"</span>"),parseInt(a.$startStop.find("span").css("text-indent"),10)<0&&a.$startStop.addClass(b.tooltipClass).attr("title",c?"Stop":"Start"));c&&b.resumeOnVideoEnd?(a.clearTimer(!0), a.timer=a.win.setInterval(function(){b.isVideoPlaying(a)||a.goForward(!0)},b.delay/2)):a.clearTimer()};a.init()};d.anythingSlider.defaults={width:null,height:null,expand:!1,resizeContents:!0,showMultiple:!1,tooltipClass:"tooltip",theme:"default",startPanel:1,changeBy:1,hashTags:!0,infiniteSlides:!0,enableKeyboard:!0,buildArrows:!0,toggleArrows:!1,buildNavigation:!0,enableNavigation:!0,toggleControls:!1,appendControlsTo:null,navigationFormatter:null,forwardText:"&raquo;",backText:"&laquo;",enablePlay:!0, autoPlay:!0,autoPlayLocked:!1,startStopped:!1,pauseOnHover:!0,stopAtEnd:!1,playRtl:!1,startText:"Start",stopText:"Stop",delay:3E3,resumeDelay:15E3,animationTime:600,easing:"swing",clickArrows:"click",clickControls:"click focusin",clickSlideshow:"click",resumeOnVideoEnd:!0,addWmodeToObject:"opaque",isVideoPlaying:function(){return!1},maxOverallWidth:32766};d.fn.anythingSlider=function(i,j){return this.each(function(){var a,b=d(this).data("AnythingSlider");(typeof i).match("object|undefined")?b?b.updateSlider(): new d.anythingSlider(this,i):/\d/.test(i)&&!isNaN(i)&&b&&(a=typeof i==="number"?i:parseInt(d.trim(i),10),a>=1&&a<=b.pages&&b.gotoPage(a,!1,j))})}})(jQuery);


/* --------------------------------------------------------------------------- */


(function($) {
    $.fn.extend({
        jsCarousel: function(options) {
            var settings = $.extend({
                scrollspeed: 1500,
                delay: 5000,
                itemstodisplay: 5,
                autoscroll: false,
                circular: false,
                masked: true,
                onthumbnailclick: null,
                orientation: 'h'
            }, options);
            return this.each(function() {
                var oclass = 'horizontal';
                if (settings.orientation == 'v')
                    oclass = 'vertical';
                var slidercontents = $(this).addClass('jscarousal-contents-' + oclass + '');
                var slider = $('<div/>').addClass('jscarousal-' + oclass + '').attr('id', slidercontents.attr('id'));
                var backbutton = $('<div/>').addClass('jscarousal-' + oclass + '-back');
                var forwardbutton = $('<div/>').addClass('jscarousal-' + oclass + '-forward');

                slidercontents.removeAttr('id');
                slidercontents.before(slider);
                slider.append(backbutton);
                slider.append(slidercontents);
                slider.append(forwardbutton);

                var total = $('> div', slidercontents).css('display', 'none').length;
                var index = 0;
                var start = 0;
                var current = $('<div/>');
                var noOfBlocks;
                var interval;
                var display = settings.itemstodisplay;
                var speed = settings.scrollspeed;
                var top;
                var left;
                var height;
                var containerHeight;
                var containerWidth;
                var direction = "forward";
                var scrolling = true;

                function initialize() {
                    index = -1;
                    noOfBlocks = parseInt(total / display);
                    if (total % display > 0) noOfBlocks++;
                    index = noOfBlocks - 1;
                    var startIndex = 0;
                    var endIndex = display;
                    var copy = false;
                    var allElements = $('> div', slidercontents);
                    $('> div', slidercontents).remove();
                    if (settings.masked)
                        allElements.addClass('thumbnail-inactive').hover(function() { $(this).removeClass('thumbnail-inactive').addClass('thumbnail-active'); }, function() { $(this).removeClass('thumbnail-active').addClass('thumbnail-inactive'); })
                    for (var i = 0; i < noOfBlocks; i++) {
                        if (total > display) {
                            startIndex = i * display;
                            endIndex = startIndex + display;
                            if (endIndex > total) {
                                startIndex -= (endIndex - total);
                                endIndex = startIndex + display;
                                copy = true;
                            }
                        }
                        else {
                            startIndex = 0;
                            endIndex = total;
                        }
                        var wrapper = $('<div/>')
                        allElements.slice(startIndex, endIndex).each(function(index, el) {
                            if (!copy)
                                wrapper.append(el);
                            else wrapper.append($(el).clone(true));
                        });
                        wrapper.find("img").click(
                         function() {
                             if (settings.onthumbnailclick != null) {
                                 settings.onthumbnailclick($(this).attr('src'));
                             }
                         });
                        slidercontents.append(wrapper);
                    }
                    if (settings.onthumbnailclick != null)
                        $('> div > div', slidercontents).css('cursor', 'pointer');

                    $('> div', slidercontents).addClass('hidden');
                    $('> div > div', slidercontents).css('display', '');

                    /*vertical*/
                    if (settings.orientation == 'v') {
                        top = $('> div:eq(' + index + ')', slidercontents).css('top');
                        if (top == 'auto') top = "0px";
                        containerHeight = slidercontents.height();
                        height = slidercontents.get(0).offsetHeight;
                        $('> div', slidercontents).css('top', '-' + containerHeight + 'px');
                        $('> div:eq(' + index + ')', slidercontents).stop(false, true).animate({ 'top': top }, speed, function() { scrolling = false; });
                    }
                    /*horizontal*/
                    if (settings.orientation == 'h') {
                        left = $('> div:eq(' + index + ')', slidercontents).css('left');
                        containerWidth = slidercontents.width();
                        height = slidercontents.get(0).offsetHeight;
                        $('> div', slidercontents).css('left', '-' + containerWidth + 'px');
                        $('> div:eq(' + index + ')', slidercontents).stop(false, true).animate({ left: 0 }, speed, function() { scrolling = false; });
                    }
                    $('> div:eq(' + index + ')', slidercontents).addClass('visible').removeClass('hidden');

                    slider.mouseenter(function() { if (settings.autoscroll) stopAnimate(); }).mouseleave(function() { if (settings.autoscroll) animate(); });
                    if (settings.autoscroll)
                        animate();
                    forwardbutton.click(function() {
                        if (!scrolling) {
                            direction = "forward";
                            if (settings.circular)
                                if (index <= 0) index = noOfBlocks;
                            showThumbs();
                        }
                    });
                    backbutton.click(function() {
                        if (!scrolling) {
                            direction = "backward";
                            if (settings.circular)
                                if (index >= noOfBlocks - 1) index = -1;
                            showThumbs();
                        }
                    });
                }
                initialize();
                function stopAnimate() {
                    scrolling = false;
                    clearTimeout(interval);
                    slider.children().clearQueue();
                    slider.children().stop(false, true);
                }
                function animate() {                    
                    clearTimeout(interval);
                    if (settings.autoscroll)
                        interval = setTimeout(changeSlide, settings.delay);
                }
                function changeSlide() {
                    if (direction == "forward") {
                        if (index <= 0) index = noOfBlocks;
                    } else {
                        if (index >= noOfBlocks - 1) { index = -1; }
                    }
                    showThumbs();
                    interval = setTimeout(changeSlide, settings.delay);
                }
                function getDimensions(value) {
                    return value + 'px';
                }
                function showThumbs() {
                    scrolling = true;
                    var current = $('.visible', slidercontents);
                    var scrollSpeed = speed;

                    if (direction == "forward") {
                        index--;
                        if (index >= 0) {
                            if (settings.orientation == 'v') {
                                $('>div:eq(' + index + ')', slidercontents).css('top', getDimensions(containerHeight)).removeClass('hidden').addClass('visible').stop(false, true).animate({ 'top': top }, scrollSpeed, function() { scrolling = false; });
                                current.stop(false, true).animate({ 'top': '-=' + getDimensions(containerHeight) }, scrollSpeed, function() {
                                    $(this).removeClass('visible').addClass('hidden');
                                    $(this).css('top', top);
                                    scrolling = false;
                                });
                            }
                            else {
                                $('>div:eq(' + index + ')', slidercontents).css('left', getDimensions(containerWidth)).removeClass('hidden').addClass('visible').stop(false, true).animate({ 'left': '-=' + getDimensions(containerWidth) }, scrollSpeed, function() { scrolling = false; });
                                current.stop(false, true).animate({ 'left': '-=' + getDimensions(containerWidth) }, scrollSpeed, function() {
                                    $(this).removeClass('visible').addClass('hidden');
                                    $(this).css('left', left);
                                    scrolling = false;
                                });
                            }
                        } else index = 0;

                    }
                    else if (direction == "backward") {
                        index++;
                        if (index < noOfBlocks) {
                            if (settings.orientation == 'v') {
                                $('>div:eq(' + index + ')', slidercontents).removeClass('hidden').addClass('visible').css({
                                    'top': getDimensions(-containerHeight)
                                }).stop(false, true).animate({ 'top': top }, scrollSpeed, function() { scrolling = false; });

                                current.stop(false, true).animate({ 'top': '+=' + getDimensions(containerHeight) }, scrollSpeed,
                            function() {
                                $(this).removeClass('visible').addClass('hidden');
                                $(this).css('top', getDimensions(-containerHeight));
                                scrolling = false;
                            });
                            }
                            else {
                                $('>div:eq(' + index + ')', slidercontents).removeClass('hidden').addClass('visible').css({
                                    'left': getDimensions(-containerWidth)
                                }).stop(false, true).animate({ 'left': '+=' + getDimensions(containerWidth) }, scrollSpeed, function() { scrolling = false; });

                                current.stop(false, true).animate({ 'left': '+=' + getDimensions(containerWidth) }, scrollSpeed,
                            function() {
                                $(this).removeClass('visible').addClass('hidden');
                                $(this).css('left', getDimensions(-containerWidth));
                                scrolling = false;
                            });
                            }

                        } else index = noOfBlocks - 1;
                    }

                }
            });
        }
    });
})(jQuery);


/* --------------------------------------------------------------------------- */

/*
    jQuery News Ticker is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, version 2 of the License.
 
    jQuery News Ticker is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with jQuery News Ticker.  If not, see <http://www.gnu.org/licenses/>.
*/
(function($){  
	$.fn.ticker = function(options) { 
		// Extend our default options with those provided.
		// Note that the first arg to extend is an empty object -
		// this is to keep from overriding our "defaults" object.
		var opts = $.extend({}, $.fn.ticker.defaults, options); 
		
		/* Get the id of the UL to get our news content from */
		var newsID = '#' + $(this).attr('id');

		/* Get the tag type - we will check this later to makde sure it is a UL tag */
		var tagType = $(this).get(0).tagName; 	

		return this.each(function() { 
			/* Internal vars */
			var settings = {				
				position: 0,
				time: 0,
				distance: 0,
				newsArr: {},
				play: true,
				paused: false,
				contentLoaded: false,
				dom: {
					contentID: '#ticker-content',
					titleID: '#ticker-title',
					titleElem: '#ticker-title SPAN',
					tickerID : '#ticker',
					wrapperID: '#latest-news',
					revealID: '#ticker-swipe',
					revealElem: '#ticker-swipe SPAN',
					controlsID: '#ticker-controls',
					prevID: '#prev',
					nextID: '#next',
					playPauseID: '#play-pause'
				}
			};

			// if we are not using a UL, display an error message and stop any further execution
			if (tagType != 'UL' && tagType != 'OL' && opts.htmlFeed === true) {
				debugError('Cannot use <' + tagType.toLowerCase() + '> type of element for this plugin - must of type <ul> or <ol>');
				return false;
			}

			// set the ticker direction
			opts.direction == 'rtl' ? opts.direction = 'right' : opts.direction = 'left';
			
			// lets go...
			initialisePage();
			/* Function to get the size of an Object*/
			function countSize(obj) {
			    var size = 0, key;
			    for (key in obj) {
			        if (obj.hasOwnProperty(key)) size++;
			    }
			    return size;
			};

			/* Function for handling debug and error messages */ 
			function debugError(obj) {
				if (opts.debugMode) {
					if (window.console && window.console.log) {
						window.console.log(obj);
					}
					else {
						alert(obj);			
					}
				}
			}	

			/* Function to setup the page */
			function initialisePage() {
				// add our HTML structure for the ticker to the DOM
				$(settings.dom.wrapperID).append('<div id="' + settings.dom.tickerID.replace('#', '') + '"><div id="' + settings.dom.titleID.replace('#', '') + '"><span><!-- --></span></div><p id="' + settings.dom.contentID.replace('#', '') + '"></p><div id="' + settings.dom.revealID.replace('#', '') + '"><span><!-- --></span></div></div>');
				$(settings.dom.wrapperID).removeClass('no-js').addClass('has-js ' + opts.direction);
				// hide the ticker
				$(settings.dom.tickerElem + ',' + settings.dom.contentID).hide();
				// add the controls to the DOM if required
				if (opts.controls) {
					// add related events - set functions to run on given event
					$(settings.dom.controlsID).live('click mouseover mousedown mouseout mouseup', function (e) {
						var button = e.target.id;
						if (e.type == 'click') {	
							switch (button) {
								case settings.dom.prevID.replace('#', ''):
									// show previous item
									settings.paused = true;
									$(settings.dom.playPauseID).addClass('paused');
									manualChangeContent(button);
									break;
								case settings.dom.nextID.replace('#', ''):
									// show next item
									settings.paused = true;
									$(settings.dom.playPauseID).addClass('paused');
									manualChangeContent(button);
									break;
								case settings.dom.playPauseID.replace('#', ''):
									// play or pause the ticker
									if (settings.play == true) {
										settings.paused = true;
										$(settings.dom.playPauseID).addClass('paused');
										pauseTicker();
									}
									else {
										settings.paused = false;
										$(settings.dom.playPauseID).removeClass('paused');
										restartTicker();
									}
									break;
							}	
						}
						else if (e.type == 'mouseover' && $('#' + button).hasClass('controls')) {
							$('#' + button).addClass('over');
						}
						else if (e.type == 'mousedown' && $('#' + button).hasClass('controls')) {
							$('#' + button).addClass('down');
						}
						else if (e.type == 'mouseup' && $('#' + button).hasClass('controls')) {
							$('#' + button).removeClass('down');
						}
						else if (e.type == 'mouseout' && $('#' + button).hasClass('controls')) {
							$('#' + button).removeClass('over');
						}
					});
					// add controls HTML to DOM
					$(settings.dom.wrapperID).append('<ul id="' + settings.dom.controlsID.replace('#', '') + '"><li id="' + settings.dom.playPauseID.replace('#', '') + '" class="controls"></li><li id="' + settings.dom.prevID.replace('#', '') + '" class="controls"></li><li id="' + settings.dom.nextID.replace('#', '') + '" class="controls"></li></ul>');
				}
				if (opts.displayType != 'fade') {
                		// add mouse over on the content
                		$(settings.dom.contentID).mouseover(function () {
                			if (settings.paused == false) {
                				pauseTicker();
                			}
                		}).mouseout(function () {
                			if (settings.paused == false) {
                				restartTicker();
                			}
                		});
				}
				// process the content for this ticker
				processContent();
			}

			/* Start to process the content for this ticker */
			function processContent() {
				// check to see if we need to load content
				if (settings.contentLoaded == false) {
					// construct content
					if (opts.ajaxFeed) {
						if (opts.feedType == 'xml') {
							$.ajax({
								url: opts.feedUrl,
								cache: false,
								dataType: opts.feedType,
								async: true,
								success: function(data){
									count = 0;	
									// get the 'root' node
									for (var a = 0; a < data.childNodes.length; a++) {
										if (data.childNodes[a].nodeName == 'rss') {
											xmlContent = data.childNodes[a];
										}
									}
									// find the channel node
									for (var i = 0; i < xmlContent.childNodes.length; i++) {
										if (xmlContent.childNodes[i].nodeName == 'channel') {
											xmlChannel = xmlContent.childNodes[i];
										}		
									}
									// for each item create a link and add the article title as the link text
									for (var x = 0; x < xmlChannel.childNodes.length; x++) {
										if (xmlChannel.childNodes[x].nodeName == 'item') {
											xmlItems = xmlChannel.childNodes[x];
											var title, link = false;
											for (var y = 0; y < xmlItems.childNodes.length; y++) {
												if (xmlItems.childNodes[y].nodeName == 'title') {      												    
													title = xmlItems.childNodes[y].lastChild.nodeValue;
												}
												else if (xmlItems.childNodes[y].nodeName == 'link') {												    
													link = xmlItems.childNodes[y].lastChild.nodeValue; 
												}
												if ((title !== false && title != '') && link !== false) {
												    settings.newsArr['item-' + count] = { type: opts.titleText, content: '<a href="' + link + '">' + title + '</a>' };												    count++;												    title = false;												    link = false;
												}
											}	
										}		
									}			
									// quick check here to see if we actually have any content - log error if not
									if (countSize(settings.newsArr < 1)) {
										debugError('Couldn\'t find any content from the XML feed for the ticker to use!');
										return false;
									}
									setupContentAndTriggerDisplay();
									settings.contentLoaded = true;
								}
							});							
						}
						else {
							debugError('Code Me!');	
						}						
					}
					else if (opts.htmlFeed) { 
						if($(newsID + ' LI').length > 0) {
							$(newsID + ' LI').each(function (i) {
								// maybe this could be one whole object and not an array of objects?
								settings.newsArr['item-' + i] = { type: opts.titleText, content: $(this).html()};
							});		
							setupContentAndTriggerDisplay();
						}	
						else {
							debugError('Couldn\'t find HTML any content for the ticker to use!');
							return false;
						}
					}
					else {
						debugError('The ticker is set to not use any types of content! Check the settings for the ticker.');
						return false;
					}					
				}			
			}

			function setupContentAndTriggerDisplay() {

				settings.contentLoaded = true;

				// update the ticker content with the correct item
				// insert news content into DOM
				$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
				$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);

				// set the next content item to be used - loop round if we are at the end of the content
				if (settings.position == (countSize(settings.newsArr) -1)) {
					settings.position = 0;
				}
				else {		
					settings.position++;
				}			

				// get the values of content and set the time of the reveal (so all reveals have the same speed regardless of content size)
				distance = $(settings.dom.contentID).width();
				time = distance / opts.speed;

				// start the ticker animation						
				revealContent();		
			}

			// slide back cover or fade in content
			function revealContent() {
				if(settings.play) {	
					// get the width of the title element to offset the content and reveal
					var offset = $(settings.dom.titleElem).width() + 20;
					$(settings.dom.revealID).css(opts.direction, offset + 'px');
					// show the reveal element and start the animation
					if (opts.displayType == 'fade') {
						// fade in effect ticker
						$(settings.dom.revealID).hide(0, function () {
							$(settings.dom.contentID).css(opts.direction, offset + 'px').fadeIn(opts.fadeInSpeed, postReveal);
						});						
					}
					else if (opts.displayType == 'scroll') {
						// to code
					}
					else {
						// default bbc scroll effect
						$(settings.dom.revealElem).show(0, function () {
							$(settings.dom.contentID).css(opts.direction, offset + 'px').show();
							// set our animation direction
							animationAction = opts.direction == 'right' ? { marginRight: distance + 'px'} : { marginLeft: distance + 'px' };
							$(settings.dom.revealID).css('margin-' + opts.direction, '0px').delay(20).animate(animationAction, time, 'linear', postReveal);
						});		
					}
				}
				else {
					return false;					
				}
			};

			// here we hide the current content and reset the ticker elements to a default state ready for the next ticker item
			function postReveal() {				
				if(settings.play) {		
					// we have to separately fade the content out here to get around an IE bug - needs further investigation
					$(settings.dom.contentID).delay(opts.pauseOnItems).fadeOut(opts.fadeOutSpeed);
					// deal with the rest of the content, prepare the DOM and trigger the next ticker
					if (opts.displayType == 'fade') {
						$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
							$(settings.dom.wrapperID)
								.find(settings.dom.revealElem + ',' + settings.dom.contentID)
									.hide()
								.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
									.show()
								.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
									.removeAttr('style');								
							setupContentAndTriggerDisplay();						
						});
					}
					else {
						$(settings.dom.revealID).hide(0, function () {
							$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
								$(settings.dom.wrapperID)
									.find(settings.dom.revealElem + ',' + settings.dom.contentID)
										.hide()
									.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
										.show()
									.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
										.removeAttr('style');								
								setupContentAndTriggerDisplay();						
							});
						});	
					}
				}
				else {
					$(settings.dom.revealElem).hide();
				}
			}

			// pause ticker
			function pauseTicker() {				
				settings.play = false;
				// stop animation and show content - must pass "true, true" to the stop function, or we can get some funky behaviour
				$(settings.dom.tickerID + ',' + settings.dom.revealID + ',' + settings.dom.titleID + ',' + settings.dom.titleElem + ',' + settings.dom.revealElem + ',' + settings.dom.contentID).stop(true, true);
				$(settings.dom.revealID + ',' + settings.dom.revealElem).hide();
				$(settings.dom.wrapperID)
					.find(settings.dom.titleID + ',' + settings.dom.titleElem).show()
						.end().find(settings.dom.contentID).show();
			}

			// play ticker
			function restartTicker() {				
				settings.play = true;
				settings.paused = false;
				// start the ticker again
				postReveal();	
			}

			// change the content on user input
			function manualChangeContent(direction) {
				pauseTicker();
				switch (direction) {
					case 'prev':
						if (settings.position == 0) {
							settings.position = countSize(settings.newsArr) -2;
						}
						else if (settings.position == 1) {
							settings.position = countSize(settings.newsArr) -1;
						}
						else {
							settings.position = settings.position - 2;
						}
						$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
						$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);						
						break;
					case 'next':
						$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
						$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
						break;
				}
				// set the next content item to be used - loop round if we are at the end of the content
				if (settings.position == (countSize(settings.newsArr) -1)) {
					settings.position = 0;
				}
				else {		
					settings.position++;
				}	
			}
		});  
	};  

	// plugin defaults - added as a property on our plugin function
	$.fn.ticker.defaults = {
		speed: 0.10,			
		ajaxFeed: false,
		feedUrl: '',
		feedType: 'xml',
		displayType: 'reveal',
		htmlFeed: true,
		debugMode: true,
		controls: true,
		titleText: 'Latest News:',	
		direction: 'ltr',	
		pauseOnItems: 3000,
		fadeInSpeed: 600,
		fadeOutSpeed: 300
	};	
})(jQuery);

/* --------------------------------------------------------------------------- */
