// ---------------------------  Document Ready
$(document).ready(function(){
//Open External Links in a New Window
$('a[rel="external"]').click( function() {
        window.open( $(this).attr('href') );
        return false;
    });

// Dropdown Nav
	$("#Nav > ul > li").addClass("parent");
	$("#Nav li ul").addClass("slideDown");
	$("#Nav li ul").hide();
	$("#Nav li ul").parent("li").addClass("hasSub");
	$("#Nav li").hover(function () {
		$(this).children("ul")
		.show();
		}, function () {
		$(this).children("ul")
		.hide();
	});
	$("#Nav li ul").hover(function () {
		$(this).parent("li")
		.addClass("active");
		}, function () {
		$(this).parent("li")
		.removeClass("active");
	});

//Home Tabs
$(".tabNav li:first-child").addClass("first");
	var tabContainers = $('div.tabs > div');
	tabContainers.hide().filter(':first').show();
$('div.tabs ul.tabNav a').click(function () {
	tabContainers.hide();
	tabContainers.filter(this.hash).fadeIn();
	$('div.tabs ul.tabNav a').parent("li").removeClass('selected');
	$(this).parent("li").addClass('selected');
	$(this).parent("li").next().addClass('next');
	return false;
}).filter(':first').click();
 
// Search Form
	$("#searchForm input").focus(function() {
		$(this).addClass("active");
	});
	$("#searchForm input").blur(function() {
		$(this).removeClass("active");
	});
// Call overlabel
	$("label.overlabel").overlabel();
// Footer Contact Info Slide Panel
$(".btn-contact").click(function(){
		$("#slidepanel").slideToggle("slow");
		$(this).toggleClass("active"); return false;
	});
//Accordion sidebar
    $('ul.accordion').accordion({
        header: 'h3',
		active: false
	});

// Truncate text
	$('div.truncbox p').expander({
	    slicePoint:       540,  // default is 100
	    expandText:       'view more&nbsp;', // default is 'read more...'
		widow:            15,
		expandPrefix:     '&nbsp;', // text to come before the expand link
	    userCollapseText: '[^]',  // default is '[collapse expanded text]'
	 	expandEffect: 'fadeIn'
	  });
// the end of Document Load
}); 

// ---------------------------  Overlabel for Search
( function( $ ) {
    // plugin definition
    $.fn.overlabel = function( options ) {
         // build main options before element iteration
        var opts = $.extend( {}, $.fn.overlabel.defaults, options );
        var selection = this.filter( 'label[for]' ).map( function() {
            var label = $( this );
            var id = label.attr( 'for' );
            var field = document.getElementById( id );
           if ( !field ) return;
            // build element specific options
            var o = $.meta ? $.extend( {}, opts, label.data() ) : opts;
            label.addClass( o.label_class );
            var hide_label = function() { label.css( o.hide_css ) };
            var show_label = function() { this.value || label.css( o.show_css ) };
            $( field )
                 .parent().addClass( o.wrapper_class ).end()
                 .focus( hide_label ).blur( show_label ).each( hide_label ).each( show_label );
            return this;
        } );
        return opts.filter ? selection : selection.end();
    };
    // publicly accessible defaults
    $.fn.overlabel.defaults = {
        label_class:   'overlabel-apply',
        wrapper_class: 'overlabel-wrapper',
        hide_css:      { 'text-indent': '-10000px' },
        show_css:      { 'text-indent': '0px', 'cursor': 'text' },
        filter:        false
    };
} )( jQuery );


// --------------------------------- JQUERY Dimensions effects
(function($){
$.dimensions = {
	version: '@VERSION'
};
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		return num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		options = $.extend({ margin: false }, options || {});
		return num( this, name.toLowerCase() )
				+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
				+ num(this, 'padding' + torl) + num(this, 'padding' + borr)
				+ (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});
// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		return val != undefined ?
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});
$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');
			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');
			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}
		return results;
	},
	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});
function num(el, prop) {
	return parseInt($.css(el.jquery?el[0]:el,prop))||0;
};
})(jQuery);

// -------------------- Accordion jquery plugin
;(function($){$.ui=$.ui||{};$.fn.extend({accordion:function(options,data){var args=Array.prototype.slice.call(arguments,1);return this.each(function(){if(typeof options=="string"){var accordion=$.data(this,"accordion");if(accordion)accordion[options].apply(accordion,args);}else if(!$(this).is(".ui-accordion"))$.data(this,"accordion",new $.ui.accordion(this,options));});},activate:function(index){return this.accordion("activate",index);}});$.ui.accordion=function(container,options){this.options=options=$.extend({},$.ui.accordion.defaults,options);this.element=container;$(container).addClass("ui-accordion");if(options.navigation){var current=$(container).find("a").filter(options.navigationFilter);if(current.length){if(current.filter(options.header).length){options.active=current;}else{options.active=current.parent().parent().prev();current.addClass("current");}}}options.headers=$(container).find(options.header);options.active=findActive(options.headers,options.active);if(options.fillSpace){var maxHeight=$(container).parent().height();options.headers.each(function(){maxHeight-=$(this).outerHeight();});var maxPadding=0;options.headers.next().each(function(){maxPadding=Math.max(maxPadding,$(this).innerHeight()-$(this).height());}).height(maxHeight-maxPadding);}else if(options.autoHeight){var maxHeight=0;options.headers.next().each(function(){maxHeight=Math.max(maxHeight,$(this).outerHeight());}).height(maxHeight);}options.headers.not(options.active||"").next().hide();options.active.parent().andSelf().addClass(options.selectedClass);if(options.event)$(container).bind((options.event)+".accordion",clickHandler);};$.ui.accordion.prototype={activate:function(index){clickHandler.call(this.element,{target:findActive(this.options.headers,index)[0]});},enable:function(){this.options.disabled=false;},disable:function(){this.options.disabled=true;},destroy:function(){this.options.headers.next().css("display","");if(this.options.fillSpace||this.options.autoHeight){this.options.headers.next().css("height","");}$.removeData(this.element,"accordion");$(this.element).removeClass("ui-accordion").unbind(".accordion");}};function scopeCallback(callback,scope){return function(){return callback.apply(scope,arguments);};};function completed(cancel){if(!$.data(this,"accordion"))return;var instance=$.data(this,"accordion");var options=instance.options;options.running=cancel?0:--options.running;if(options.running)return;if(options.clearStyle){options.toShow.add(options.toHide).css({height:"",overflow:""});}$(this).triggerHandler("accordionchange",[options.data],options.change);}function toggle(toShow,toHide,data,clickedActive,down){var options=$.data(this,"accordion").options;options.toShow=toShow;options.toHide=toHide;options.data=data;var complete=scopeCallback(completed,this);options.running=toHide.size()==0?toShow.size():toHide.size();if(options.animated){if(!options.alwaysOpen&&clickedActive){$.ui.accordion.animations[options.animated]({toShow:jQuery([]),toHide:toHide,complete:complete,down:down,autoHeight:options.autoHeight});}else{$.ui.accordion.animations[options.animated]({toShow:toShow,toHide:toHide,complete:complete,down:down,autoHeight:options.autoHeight});}}else{if(!options.alwaysOpen&&clickedActive){toShow.toggle();}else{toHide.hide();toShow.show();}complete(true);}}function clickHandler(event){var options=$.data(this,"accordion").options;if(options.disabled)return false;if(!event.target&&!options.alwaysOpen){options.active.parent().andSelf().toggleClass(options.selectedClass);var toHide=options.active.next(),data={instance:this,options:options,newHeader:jQuery([]),oldHeader:options.active,newContent:jQuery([]),oldContent:toHide},toShow=options.active=$([]);toggle.call(this,toShow,toHide,data);return false;}var clicked=$(event.target);if(clicked.parents(options.header).length)while(!clicked.is(options.header))clicked=clicked.parent();var clickedActive=clicked[0]==options.active[0];
if(options.running||(options.alwaysOpen&&clickedActive))return false;
if(!clicked.is(options.header))return;
options.active.parent().andSelf().toggleClass(options.selectedClass);if(!clickedActive){clicked.parent().andSelf().addClass(options.selectedClass);}var toShow=clicked.next(),toHide=options.active.next(),data={instance:this,options:options,newHeader:clicked,oldHeader:options.active,newContent:toShow,oldContent:toHide},down=options.headers.index(options.active[0])>options.headers.index(clicked[0]);options.active=clickedActive?$([]):clicked;toggle.call(this,toShow,toHide,data,clickedActive,down);return false;};function findActive(headers,selector){return selector!=undefined?typeof selector=="number"?headers.filter(":eq("+selector+")"):headers.not(headers.not(selector)):selector===false?$([]):headers.filter(":eq(0)");}$.extend($.ui.accordion,{defaults:{selectedClass:"selected",alwaysOpen:true,animated:'slide',event:"click",header:"a",autoHeight:true,running:0,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase();}},animations:{slide:function(options,additions){options=$.extend({easing:"swing",duration:300},options,additions);if(!options.toHide.size()){options.toShow.animate({height:"show"},options);return;}var hideHeight=options.toHide.height(),showHeight=options.toShow.height(),difference=showHeight/hideHeight;options.toShow.css({height:0,overflow:'hidden'}).show();options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate({height:"hide"},{step:function(now){var current=(hideHeight-now)*difference;if($.browser.msie||$.browser.opera){current=Math.ceil(current);}options.toShow.height(current);},duration:options.duration,easing:options.easing,complete:function(){if(!options.autoHeight){options.toShow.css("height","auto");}options.complete();}});},bounceslide:function(options){this.slide(options,{easing:options.down?"bounceout":"swing",duration:options.down?1000:200});},easeslide:function(options){this.slide(options,{easing:"easeinout",duration:700});}}});})(jQuery);

// ----------------------- Truncate/Expander jquery plugin
(function($) {

  $.fn.expander = function(options) {

    var opts = $.extend({}, $.fn.expander.defaults, options);
    var delayedCollapse;
    return this.each(function() {
      var $this = $(this);
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
     	var cleanedTag, startTags, endTags;	
     	var allText = $this.html();
     	var startText = allText.slice(0, o.slicePoint).replace(/\w+$/,'');
     	startTags = startText.match(/<\w[^>]*>/g);
   	  if (startTags) {startText = allText.slice(0,o.slicePoint + startTags.join('').length).replace(/\w+$/,'');}
   	  
     	if (startText.lastIndexOf('<') > startText.lastIndexOf('>') ) {
     	  startText = startText.slice(0,startText.lastIndexOf('<'));
     	}
     	var endText = allText.slice(startText.length);    	  
     	// create necessary expand/collapse elements if they don't already exist
   	  if (!$('span.details', this).length) {
        // end script if text length isn't long enough.
       	if ( endText.replace(/\s+$/,'').split(' ').length < o.widow ) { return; }
       	// otherwise, continue...    
       	if (endText.indexOf('</') > -1) {
         	endTags = endText.match(/<(\/)?[^>]*>/g);
          for (var i=0; i < endTags.length; i++) {

            if (endTags[i].indexOf('</') > -1) {
              var startTag, startTagExists = false;
              for (var j=0; j < i; j++) {
                startTag = endTags[j].slice(0, endTags[j].indexOf(' ')).replace(/(\w)$/,'$1>');
                if (startTag == rSlash(endTags[i])) {
                  startTagExists = true;
                }
              }              
              if (!startTagExists) {
                startText = startText + endTags[i];
                var matched = false;
                for (var s=startTags.length - 1; s >= 0; s--) {
                  if (startTags[s].slice(0, startTags[s].indexOf(' ')).replace(/(\w)$/,'$1>') == rSlash(endTags[i]) 
                  && matched == false) {
                    cleanedTag = cleanedTag ? startTags[s] + cleanedTag : startTags[s];
                    matched = true;
                  }
                };
              }
            }
          }

          endText = cleanedTag && cleanedTag + endText || endText;
        }
     	  $this.html([
     		startText,
     		'<span class="read-more">',
     		o.expandPrefix,
       		'<a href="#">',
       		  o.expandText,
       		'</a>',
        '</span>',
     		'<span class="details">',
     		  endText,
     		'</span>'
     		].join('')
     	  );
      }
      var $thisDetails = $('span.details', this),
        $readMore = $('span.read-more', this);
   	  $thisDetails.hide();
 	    $readMore.find('a').click(function() {
 	      $readMore.hide();

 	      if (o.expandEffect === 'show' && !o.expandSpeed) {
          o.beforeExpand($this);
 	        $thisDetails.show();
          o.afterExpand($this);
          delayCollapse(o, $thisDetails);
 	      } else {
          o.beforeExpand($this);
 	        $thisDetails[o.expandEffect](o.expandSpeed, function() {
            $thisDetails.css({zoom: ''});
            o.afterExpand($this);
            delayCollapse(o, $thisDetails);
 	        });
 	      }
        return false;
 	    });
      if (o.userCollapse) {
        $this
        .find('span.details').append('<span class="re-collapse">' + o.userCollapsePrefix + '<a href="#">' + o.userCollapseText + '</a></span>');
        $this.find('span.re-collapse a').click(function() {

          clearTimeout(delayedCollapse);
          var $detailsCollapsed = $(this).parents('span.details');
          reCollapse($detailsCollapsed);
          o.onCollapse($this, true);
          return false;
        });
      }
    });
    function reCollapse(el) {
       el.hide()
        .prev('span.read-more').show();
    }
    function delayCollapse(option, $collapseEl) {
      if (option.collapseTimer) {
        delayedCollapse = setTimeout(function() {  
          reCollapse($collapseEl);
          option.onCollapse($collapseEl.parent(), false);
          },
          option.collapseTimer
        );
      }
    }
    function rSlash(rString) {
      return rString.replace(/\//,'');
    }    
  };
    // plugin defaults
  $.fn.expander.defaults = {
    slicePoint:       100,  // the number of characters at which the contents will be sliced into two parts. 
                            // Note: any tag names in the HTML that appear inside the sliced element before 
                            // the slicePoint will be counted along with the text characters.
    widow:            4,  // a threshold of sorts for whether to initially hide/collapse part of the element's contents. 
                          // If after slicing the contents in two there are fewer words in the second part than 
                          // the value set by widow, we won't bother hiding/collapsing anything.
    expandText:       'read more', // text displayed in a link instead of the hidden part of the element. 
                                      // clicking this will expand/show the hidden/collapsed text
    expandPrefix:     '&hellip; ',
    collapseTimer:    0, // number of milliseconds after text has been expanded at which to collapse the text again
    expandEffect:     'fadeIn',
    expandSpeed:      '',   // speed in milliseconds of the animation effect for expanding the text
    userCollapse:     true, // allow the user to re-collapse the expanded text.
    userCollapseText: '[collapse expanded text]',  // text to use for the link to re-collapse the text
    userCollapsePrefix: ' ',
    beforeExpand: function($thisEl) {},
    afterExpand: function($thisEl) {},
    onCollapse: function($thisEl, byUser) {}
  };
})(jQuery);
