Drupal.locale = { 'pluralFormula': function ($n) { return Number(($n!=1)); }, 'strings': {"An AJAX HTTP error occurred.":"Er is een AJAX HTTP fout opgetreden.","HTTP Result Code: !status":"HTTP-resultaatcode: !status","An AJAX HTTP request terminated abnormally.":"Een AJAX HTTP-aanvraag is onverwacht afgebroken","Debugging information follows.":"Debug informatie volgt.","Path: !uri":"Pad: !uri","StatusText: !statusText":"Statustekst: !statusText","ResponseText: !responseText":"Antwoordtekst: !responseText","ReadyState: !readyState":"ReadyState: !readyState","Hide":"Verbergen","Show":"Weergeven","Show shortcuts":"Snelkoppelingen weergeven","Hide shortcuts":"Verberg snelkoppelingen","Re-order rows by numerical weight instead of dragging.":"Herschik de rijen op basis van gewicht, in plaats van slepen.","Show row weights":"Gewicht van rijen tonen","Hide row weights":"Gewicht van rij verbergen","Drag to re-order":"Slepen om de volgorde te wijzigen","Changes made in this table will not be saved until the form is submitted.":"Wijzigingen in deze tabel worden pas opgeslagen wanneer het formulier wordt ingediend.","None":"Geen","Edit":"Bewerken","(active tab)":"(actieve tabblad)","Not published":"Niet gepubliceerd","Cancel":"Annuleren","Disabled":"Uitgeschakeld","Select":"Selecteer","Please wait...":"Even geduld...","The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.":"Het bestand %filename kan niet ge\u00fcpload worden. Alleen bestanden met de volgende extensies zijn toegestaan: %extensions","Loading...":"Bezig met laden...","Hide summary":"Samenvatting verbergen","Edit summary":"Samenvatting bewerken","Not in menu":"Niet in een menu","Alias: @alias":"Alias: @alias","No alias":"Geen alias","1 redirect":"1 omleiding","@count redirects":"@count omleidingen","No redirects":"Geen omleidingen","New revision":"Nieuwe revisie","No revision":"Geen revisie","By @name on @date":"Door @name op @date","By @name":"Door @name","@number comments per page":"@number reacties per pagina","Autocomplete popup":"Popup voor automatisch aanvullen","Searching for matches...":"Zoeken naar overeenkomsten...","Submit":"Indienen","Only files with the following extensions are allowed: %files-allowed.":"Uitsluitend bestanden met de volgende extensies zijn toegelaten: %files-allowed.","%filename is not an image.":"%filename is geen afbeelding.","Select all rows in this table":"Selecteer alle regels van deze tabel","Deselect all rows in this table":"De-selecteer alle regels van deze tabel","all":"alle","none":"geen","This permission is inherited from the authenticated user role.":"Dit toegangsrecht is ge\u00ebrfd van de rol 'geverifieerde gebruiker'.","Not restricted":"Geen beperking","Restricted to certain pages":"Beperkt tot bepaalde pagina's","Not customizable":"Niet aanpasbaar","The changes to these blocks will not be saved until the \u003cem\u003eSave blocks\u003c\/em\u003e button is clicked.":"Wijzigingen aan de blokken worden pas opgeslagen wanneer u de knop \u003cem\u003eBlokken opslaan\u003c\/em\u003e aanklikt.","The block cannot be placed in this region.":"Het blok kan niet worden geplaatst in dit gebied.","Remove group":"Groep verwijderen","Apply (all displays)":"Toepassen (alle weergaven)","Apply (this display)":"Toepassen (deze weergave)","Requires a title":"Een titel is verplicht","Don't display post information":"Geen berichtinformatie weergeven","Add file":"Voeg bestand toe","One domain with multiple subdomains":"E\u00e9n domein met meerdere subdomeinen"} };;
// ColorBox v1.3.17.2 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+
// Copyright (c) 2011 Jack Moore - jack@colorpowered.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
(function(a,b,c){function bc(b){if(!U){P=b,_(),y=a(P),Q=0,K.rel!=="nofollow"&&(y=a("."+g).filter(function(){var b=a.data(this,e).rel||this.rel;return b===K.rel}),Q=y.index(P),Q===-1&&(y=y.add(P),Q=y.length-1));if(!S){S=T=!0,r.show();if(K.returnFocus)try{P.blur(),a(P).one(l,function(){try{this.focus()}catch(a){}})}catch(c){}q.css({opacity:+K.opacity,cursor:K.overlayClose?"pointer":"auto"}).show(),K.w=Z(K.initialWidth,"x"),K.h=Z(K.initialHeight,"y"),X.position(),o&&z.bind("resize."+p+" scroll."+p,function(){q.css({width:z.width(),height:z.height(),top:z.scrollTop(),left:z.scrollLeft()})}).trigger("resize."+p),ba(h,K.onOpen),J.add(D).hide(),I.html(K.close).show()}X.load(!0)}}function bb(){var a,b=f+"Slideshow_",c="click."+f,d,e,g;K.slideshow&&y[1]?(d=function(){F.text(K.slideshowStop).unbind(c).bind(j,function(){if(Q<y.length-1||K.loop)a=setTimeout(X.next,K.slideshowSpeed)}).bind(i,function(){clearTimeout(a)}).one(c+" "+k,e),r.removeClass(b+"off").addClass(b+"on"),a=setTimeout(X.next,K.slideshowSpeed)},e=function(){clearTimeout(a),F.text(K.slideshowStart).unbind([j,i,k,c].join(" ")).one(c,d),r.removeClass(b+"on").addClass(b+"off")},K.slideshowAuto?d():e()):r.removeClass(b+"off "+b+"on")}function ba(b,c){c&&c.call(P),a.event.trigger(b)}function _(b){K=a.extend({},a.data(P,e));for(b in K)a.isFunction(K[b])&&b.substring(0,2)!=="on"&&(K[b]=K[b].call(P));K.rel=K.rel||P.rel||"nofollow",K.href=K.href||a(P).attr("href"),K.title=K.title||P.title,typeof K.href=="string"&&(K.href=a.trim(K.href))}function $(a){return K.photo||/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(a)}function Z(a,b){return Math.round((/%/.test(a)?(b==="x"?z.width():z.height())/100:1)*parseInt(a,10))}function Y(c,d,e){e=b.createElement("div"),c&&(e.id=f+c),e.style.cssText=d||"";return a(e)}var d={transition:"elastic",speed:300,width:!1,initialWidth:"600",innerWidth:!1,maxWidth:!1,height:!1,initialHeight:"450",innerHeight:!1,maxHeight:!1,scalePhotos:!0,scrolling:!0,inline:!1,html:!1,iframe:!1,fastIframe:!0,photo:!1,href:!1,title:!1,rel:!1,opacity:.9,preloading:!0,current:"image {current} of {total}",previous:"previous",next:"next",close:"close",open:!1,returnFocus:!0,loop:!0,slideshow:!1,slideshowAuto:!0,slideshowSpeed:2500,slideshowStart:"start slideshow",slideshowStop:"stop slideshow",onOpen:!1,onLoad:!1,onComplete:!1,onCleanup:!1,onClosed:!1,overlayClose:!0,escKey:!0,arrowKey:!0,top:!1,bottom:!1,left:!1,right:!1,fixed:!1,data:!1},e="colorbox",f="cbox",g=f+"Element",h=f+"_open",i=f+"_load",j=f+"_complete",k=f+"_cleanup",l=f+"_closed",m=f+"_purge",n=a.browser.msie&&!a.support.opacity,o=n&&a.browser.version<7,p=f+"_IE6",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X;X=a.fn[e]=a[e]=function(b,c){var f=this;b=b||{};if(!f[0]){if(f.selector)return f;f=a("<a/>"),b.open=!0}c&&(b.onComplete=c),f.each(function(){a.data(this,e,a.extend({},a.data(this,e)||d,b)),a(this).addClass(g)}),(a.isFunction(b.open)&&b.open.call(f)||b.open)&&bc(f[0]);return f},X.init=function(){z=a(c),r=Y().attr({id:e,"class":n?f+(o?"IE6":"IE"):""}),q=Y("Overlay",o?"position:absolute":"").hide(),s=Y("Wrapper"),t=Y("Content").append(A=Y("LoadedContent","width:0; height:0; overflow:hidden"),C=Y("LoadingOverlay").add(Y("LoadingGraphic")),D=Y("Title"),E=Y("Current"),G=Y("Next"),H=Y("Previous"),F=Y("Slideshow").bind(h,bb),I=Y("Close")),s.append(Y().append(Y("TopLeft"),u=Y("TopCenter"),Y("TopRight")),Y(!1,"clear:left").append(v=Y("MiddleLeft"),t,w=Y("MiddleRight")),Y(!1,"clear:left").append(Y("BottomLeft"),x=Y("BottomCenter"),Y("BottomRight"))).children().children().css({"float":"left"}),B=Y(!1,"position:absolute; width:9999px; visibility:hidden; display:none"),a("body").prepend(q,r.append(s,B)),t.children().hover(function(){a(this).addClass("hover")},function(){a(this).removeClass("hover")}).addClass("hover"),L=u.height()+x.height()+t.outerHeight(!0)-t.height(),M=v.width()+w.width()+t.outerWidth(!0)-t.width(),N=A.outerHeight(!0),O=A.outerWidth(!0),r.css({"padding-bottom":L,"padding-right":M}).hide(),G.click(function(){X.next()}),H.click(function(){X.prev()}),I.click(function(){X.close()}),J=G.add(H).add(E).add(F),t.children().removeClass("hover"),q.click(function(){K.overlayClose&&X.close()}),a(b).bind("keydown."+f,function(a){var b=a.keyCode;S&&K.escKey&&b===27&&(a.preventDefault(),X.close()),S&&K.arrowKey&&y[1]&&(b===37?(a.preventDefault(),H.click()):b===39&&(a.preventDefault(),G.click()))})},X.remove=function(){r.add(q).remove(),a("."+g).removeData(e).removeClass(g)},X.position=function(a,c){function g(a){u[0].style.width=x[0].style.width=t[0].style.width=a.style.width,C[0].style.height=C[1].style.height=t[0].style.height=v[0].style.height=w[0].style.height=a.style.height}var d=0,e=0;z.unbind("resize."+f),r.hide(),K.fixed&&!o?r.css({position:"fixed"}):(d=z.scrollTop(),e=z.scrollLeft(),r.css({position:"absolute"})),K.right!==!1?e+=Math.max(z.width()-K.w-O-M-Z(K.right,"x"),0):K.left!==!1?e+=Z(K.left,"x"):e+=Math.round(Math.max(z.width()-K.w-O-M,0)/2),K.bottom!==!1?d+=Math.max(b.documentElement.clientHeight-K.h-N-L-Z(K.bottom,"y"),0):K.top!==!1?d+=Z(K.top,"y"):d+=Math.round(Math.max(b.documentElement.clientHeight-K.h-N-L,0)/2),r.show(),a=r.width()===K.w+O&&r.height()===K.h+N?0:a||0,s[0].style.width=s[0].style.height="9999px",r.dequeue().animate({width:K.w+O,height:K.h+N,top:d,left:e},{duration:a,complete:function(){g(this),T=!1,s[0].style.width=K.w+O+M+"px",s[0].style.height=K.h+N+L+"px",c&&c(),setTimeout(function(){z.bind("resize."+f,X.position)},1)},step:function(){g(this)}})},X.resize=function(a){if(S){a=a||{},a.width&&(K.w=Z(a.width,"x")-O-M),a.innerWidth&&(K.w=Z(a.innerWidth,"x")),A.css({width:K.w}),a.height&&(K.h=Z(a.height,"y")-N-L),a.innerHeight&&(K.h=Z(a.innerHeight,"y"));if(!a.innerHeight&&!a.height){var b=A.wrapInner("<div style='overflow:auto'></div>").children();K.h=b.height(),b.replaceWith(b.children())}A.css({height:K.h}),X.position(K.transition==="none"?0:K.speed)}},X.prep=function(b){function h(){K.h=K.h||A.height(),K.h=K.mh&&K.mh<K.h?K.mh:K.h;return K.h}function g(){K.w=K.w||A.width(),K.w=K.mw&&K.mw<K.w?K.mw:K.w;return K.w}if(!!S){var c,d=K.transition==="none"?0:K.speed;A.remove(),A=Y("LoadedContent").append(b),A.hide().appendTo(B.show()).css({width:g(),overflow:K.scrolling?"auto":"hidden"}).css({height:h()}).prependTo(t),B.hide(),a(R).css({"float":"none"}),o&&a("select").not(r.find("select")).filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one(k,function(){this.style.visibility="inherit"}),c=function(){function o(){n&&r[0].style.removeAttribute("filter")}var b,c,g,h,i=y.length,k,l;!S||(l=function(){clearTimeout(W),C.hide(),ba(j,K.onComplete)},n&&R&&A.fadeIn(100),D.html(K.title).add(A).show(),i>1?(typeof K.current=="string"&&E.html(K.current.replace("{current}",Q+1).replace("{total}",i)).show(),G[K.loop||Q<i-1?"show":"hide"]().html(K.next),H[K.loop||Q?"show":"hide"]().html(K.previous),b=Q?y[Q-1]:y[i-1],g=Q<i-1?y[Q+1]:y[0],K.slideshow&&F.show(),K.preloading&&(h=a.data(g,e).href||g.href,c=a.data(b,e).href||b.href,h=a.isFunction(h)?h.call(g):h,c=a.isFunction(c)?c.call(b):c,$(h)&&(a("<img/>")[0].src=h),$(c)&&(a("<img/>")[0].src=c))):J.hide(),K.iframe?(k=a("<iframe/>").addClass(f+"Iframe")[0],K.fastIframe?l():a(k).one("load",l),k.name=f+ +(new Date),k.src=K.href,K.scrolling||(k.scrolling="no"),n&&(k.frameBorder=0,k.allowTransparency="true"),a(k).appendTo(A).one(m,function(){k.src="//about:blank"})):l(),K.transition==="fade"?r.fadeTo(d,1,o):o())},K.transition==="fade"?r.fadeTo(d,0,function(){X.position(0,c)}):X.position(d,c)}},X.load=function(b){var c,d,e=X.prep;T=!0,R=!1,P=y[Q],b||_(),ba(m),ba(i,K.onLoad),K.h=K.height?Z(K.height,"y")-N-L:K.innerHeight&&Z(K.innerHeight,"y"),K.w=K.width?Z(K.width,"x")-O-M:K.innerWidth&&Z(K.innerWidth,"x"),K.mw=K.w,K.mh=K.h,K.maxWidth&&(K.mw=Z(K.maxWidth,"x")-O-M,K.mw=K.w&&K.w<K.mw?K.w:K.mw),K.maxHeight&&(K.mh=Z(K.maxHeight,"y")-N-L,K.mh=K.h&&K.h<K.mh?K.h:K.mh),c=K.href,W=setTimeout(function(){C.show()},100),K.inline?(Y().hide().insertBefore(a(c)[0]).one(m,function(){a(this).replaceWith(A.children())}),e(a(c))):K.iframe?e(" "):K.html?e(K.html):$(c)?(a(R=new Image).addClass(f+"Photo").error(function(){K.title=!1,e(Y("Error").text("This image could not be loaded"))}).load(function(){var a;R.onload=null,K.scalePhotos&&(d=function(){R.height-=R.height*a,R.width-=R.width*a},K.mw&&R.width>K.mw&&(a=(R.width-K.mw)/R.width,d()),K.mh&&R.height>K.mh&&(a=(R.height-K.mh)/R.height,d())),K.h&&(R.style.marginTop=Math.max(K.h-R.height,0)/2+"px"),y[1]&&(Q<y.length-1||K.loop)&&(R.style.cursor="pointer",R.onclick=function(){X.next()}),n&&(R.style.msInterpolationMode="bicubic"),setTimeout(function(){e(R)},1)}),setTimeout(function(){R.src=c},1)):c&&B.load(c,K.data,function(b,c,d){e(c==="error"?Y("Error").text("Request unsuccessful: "+d.statusText):a(this).contents())})},X.next=function(){!T&&y[1]&&(Q<y.length-1||K.loop)&&(Q=Q<y.length-1?Q+1:0,X.load())},X.prev=function(){!T&&y[1]&&(Q||K.loop)&&(Q=Q?Q-1:y.length-1,X.load())},X.close=function(){S&&!U&&(U=!0,S=!1,ba(k,K.onCleanup),z.unbind("."+f+" ."+p),q.fadeTo(200,0),r.stop().fadeTo(300,0,function(){r.add(q).css({opacity:1,cursor:"auto"}).hide(),ba(m),A.remove(),setTimeout(function(){U=!1,ba(l,K.onClosed)},1)}))},X.element=function(){return a(P)},X.settings=d,V=function(a){a.button!==0&&typeof a.button!="undefined"||a.ctrlKey||a.shiftKey||a.altKey||(a.preventDefault(),bc(this))},a.fn.delegate?a(b).delegate("."+g,"click",V):a("."+g).live("click",V),a(X.init)})(jQuery,document,this);;
(function ($) {

Drupal.behaviors.initColorbox = {
  attach: function (context, settings) {
    if (!$.isFunction($.colorbox)) {
      return;
    }
    $('a, area, input', context)
      .filter('.colorbox')
      .once('init-colorbox-processed')
      .colorbox(settings.colorbox);
  }
};

{
  $(document).bind('cbox_complete', function () {
    Drupal.attachBehaviors('#cboxLoadedContent');
  });
}

})(jQuery);
;
(function ($) {

Drupal.behaviors.initColorboxDefaultStyle = {
  attach: function (context, settings) {
    $(document).bind('cbox_complete', function () {
      // Only run if there is a title.
      if ($('#cboxTitle:empty', context).length == false) {
        setTimeout(function () { $('#cboxTitle', context).slideUp() }, 1500);
        $('#cboxLoadedContent img', context).bind('mouseover', function () {
          $('#cboxTitle', context).slideDown();
        });
        $('#cboxOverlay', context).bind('mouseover', function () {
          $('#cboxTitle', context).slideUp();
        });
      }
      else {
        $('#cboxTitle', context).hide();
      }
    });
  }
};

})(jQuery);
;

(function ($) {
  Drupal.Panels = {};

  Drupal.Panels.autoAttach = function() {
    if ($.browser.msie) {
      // If IE, attach a hover event so we can see our admin links.
      $("div.panel-pane").hover(
        function() {
          $('div.panel-hide', this).addClass("panel-hide-hover"); return true;
        },
        function() {
          $('div.panel-hide', this).removeClass("panel-hide-hover"); return true;
        }
      );
      $("div.admin-links").hover(
        function() {
          $(this).addClass("admin-links-hover"); return true;
        },
        function(){
          $(this).removeClass("admin-links-hover"); return true;
        }
      );
    }
  };

  $(Drupal.Panels.autoAttach);
})(jQuery);
;
/*
* qTip2 - Pretty pwoerful tooltips
* http://craigsworks.com/projects/qtip2/
*
* Version: 2.0.0pre
* Copyright 2009-2010 Craig Michael Thompson - http://craigsworks.com
*
* Dual licensed under MIT or GPLv2 licenses
* http://en.wikipedia.org/wiki/MIT_License
* http://en.wikipedia.org/wiki/GNU_General_Public_License
*
* Date: Mon Dec 13 21:52:07 2010 +0000
*/

"use strict"; // Enable ECMAScript "strict" operation for this function. See more: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
/*jslint browser: true, onevar: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true */
/*global window: false, jQuery: false */

// Munge the primitives - Paul Irish tip
var TRUE = true,
FALSE = false,
NULL = null;

(function($, window, undefined) {

// Option object sanitizer
function sanitizeOptions(opts)
{
var content;

if(!opts) { return FALSE; }

if('object' !== typeof opts.metadata) {
opts.metadata = {
type: opts.metadata
};
}

if('content' in opts) {
if('object' !== typeof opts.content || opts.content.jquery) {
opts.content = {
text: opts.content
};
}

content = opts.content.text || FALSE;
if(!$.isFunction(content) && ((!content && !content.attr) || content.length < 1 || ('object' === typeof content && !content.jquery))) {
content = opts.content.text = FALSE;
}

if('title' in opts.content && 'object' !== typeof opts.content.title) {
opts.content.title = {
text: opts.content.title
};
}
}

if('position' in opts) {
if('object' !== typeof opts.position) {
opts.position = {
my: opts.position,
at: opts.position
};
}

if('object' !== typeof opts.position.adjust) {
opts.position.adjust = {};
}

if('undefined' !== typeof opts.position.adjust.screen) {
opts.position.adjust.screen = !!opts.position.adjust.screen;
}
}

if('show' in opts) {
if('object' !== typeof opts.show) {
opts.show = {
event: opts.show
};
}

if('object' !== typeof opts.show) {
if(opts.show.jquery) {
opts.show = { target: opts.show };
}
else {
opts.show = { event: opts.show };
}
}
}

if('hide' in opts) {
if('object' !== typeof opts.hide) {
if(opts.hide.jquery) {
opts.hide = { target: opts.hide };
}
else {
opts.hide = { event: opts.hide };
}
}
}

if('style' in opts && 'object' !== typeof opts.style) {
opts.style = {
classes: opts.style
};
}

// Sanitize plugin options
$.each($.fn.qtip.plugins, function() {
if(this.sanitize) { this.sanitize(opts); }
});

return opts;
}

/*
* Core plugin implementation
*/
function QTip(target, options, id)
{
// Declare this reference
var self = this,

// Shortcut vars
uitooltip = 'ui-tooltip',
selector = '.qtip.'+uitooltip;

// Setup class attributes
self.id = id;
self.rendered = FALSE;
self.elements = { target: target };
self.cache = { event: {}, target: NULL, disabled: FALSE, position: NULL };
self.timers = { img: [] };
self.options = options;
self.plugins = {};

/*
* Private core functions
*/
function convertNotation(notation)
{
var i, obj,

// Split notation into array
actual = notation.split('.'),

// Locate required option
option = options[ actual[0] ];

// Loop through
for(i = 1; i < actual.length; i+=1) {
obj = option[ actual[i] ];
if(typeof obj === 'object' && !obj.jquery && !obj.precedance) {
option = option[ actual[i] ];
}
else { break; }
}

return actual[i] !== undefined ? [option, actual[i] ] : [options, actual[0]];
}

function offset(elem, container) {
var pos = { left: 0, top: 0 },
addScroll = !$.fn.qtip.plugins.iOS,
offsetParent, parentIsContainer;

if(container) {
pos = offset(container);
pos.left *= -1; pos.top *= -1;
}

if(elem.offsetParent) {
do {
offsetParent = elem.offsetParent;
parentIsContainer = offsetParent === container;

pos.left += elem.offsetLeft - (addScroll && offsetParent && !parentIsContainer ? offsetParent.scrollLeft : 0);
pos.top += elem.offsetTop - (addScroll && offsetParent && !parentIsContainer ? offsetParent.scrollTop : 0);
}
while(elem = offsetParent);
}

return pos;
}

function calculate(detail, fluid)
{
var tooltip = self.elements.tooltip,
accessible = uitooltip + '-accessible ' + (fluid ? uitooltip + '-accessible-fluid' : ''),
show = !tooltip.is(':visible'),
returned = FALSE;

// Make sure tooltip is rendered and if not, return
if(!self.rendered) { return FALSE; }

// Show and hide tooltip to make sure properties are returned correctly
if(show) { tooltip.addClass(accessible); }
switch(detail)
{
case 'dimensions':
// Find initial dimensions
returned = {
height: tooltip.outerHeight(),
width: tooltip.outerWidth()
};
break;

case 'position':
returned = offset(tooltip[0], options.position.container);
break;
}
if(show) { tooltip.removeClass(accessible); }

return returned;
}

function removeTitle()
{
var elems = self.elements;

if(elems.title) {
elems.titlebar.remove();
elems.titlebar = elems.title = elems.button = NULL;
elems.tooltip.removeAttr('aria-labelledby');
}
}

function createButton()
{
var elems = self.elements,
button = options.content.title.button;

if(elems.button) { elems.button.remove(); }

// Use custom button if one was supplied by user, else use default
if(button.jquery) {
elems.button = button;
}
else if('string' === typeof button) {
elems.button = $('<a />', { 'html': button });
}
else {
elems.button = $('<a />', {
'class': 'ui-state-default',
'text': 'Close tooltip',
'title': 'Close tooltip',
'css': { 'text-indent': '-10000em' }
})
.prepend(
$('<span />', { 'class': (options.style.widget ? 'ui' : uitooltip) + '-icon ui-icon-close' })
);
}

// Create button and setup attributes
elems.button
.prependTo(elems.titlebar)
.attr('role', 'button')
.addClass(uitooltip + '-close')
.hover(function(event){ $(this).toggleClass('ui-state-hover', event.type === 'mouseenter'); })
.click(function() {
if(!elems.tooltip.hasClass('ui-state-disabled')) { self.hide(); }
return FALSE;
})
.bind('mousedown keydown mouseup keyup mouseout', function(event) {
$(this).toggleClass('ui-state-active ui-state-focus', (/down$/i).test(event.type));
});

// Redraw the tooltip when we're done
self.redraw();
}

function createTitle()
{
var elems = self.elements;

// Destroy previous title element, if present
if(elems.titlebar) { removeTitle(); }

// Create title bar and title elements
elems.titlebar = $('<div />', {
'class': uitooltip + '-titlebar ' + (options.style.widget ? 'ui-widget-header' : '')
})
.append(
elems.title = $('<div />', {
'id': uitooltip + '-'+id+'-title',
'class': uitooltip + '-title',
'html': options.content.title.text
})
)
.prependTo(elems.wrapper);

// Create button if enabled
if(options.content.title.button) { createButton(); }

// Redraw the tooltip dimensions if it's rendered
else if(self.rendered === TRUE){ self.redraw(); }
}

function updateButton(button)
{
var elem = self.elements.button,
title = self.elements.title;

// Make sure tooltip is rendered and if not, return
if(!self.rendered) { return FALSE; }

if(!button) {
elem.remove();
}
else {
if(!title) {
createTitle();
}
createButton();
}
}

function updateTitle(content)
{
// Make sure tooltip is rendered and if not, return
if(!self.rendered) { return FALSE; }

// If title isn't already created, create it now
if(!self.elements.title && content) {
createTitle();
self.reposition();
}
else if(!content) {
removeTitle();
}
else {
// Set the new content
self.elements.title.html(content);
}
}

function updateContent(content)
{
var elements = self.elements;

// Make sure tooltip is rendered and content is defined. If not return
if(!self.rendered || !content) { return FALSE; }

// Use function to parse content
if($.isFunction(content)) {
content = content.call(target);
}

// Append new content if its a DOM array and show it if hidden
if(content.jquery && content.length > 0) {
elements.content.empty().append(content.css({ display: 'block' }));
}

// Content is a regular string, insert the new content
else {
elements.content.html(content);
}

// Insert into 'fx' queue our image dimension checker which will halt the showing of the tooltip until image dimensions can be detected
elements.tooltip.queue('fx', function(next) {
// Find all content images without dimensions
var images = $('img:not([height]):not([width])', self.elements.content);

// Update tooltip width and position when all images are loaded
function imageLoad(img) {
// Remove the image from the array
images = images.not(img);

// If queue is empty, update tooltip and continue the queue
if(images.length === 0) {
self.redraw();
if(self.rendered === TRUE) {
self.reposition(self.cache.event);
}

next();
}
}

// Apply the callback to img events and height checker method to ensure queue continues no matter what!
images.each(function(i, elem) {
// Apply the imageLoad to regular events to make sure the queue continues
var events = ['abort','error','load','unload',''].join('.qtip-image ');
$(this).bind(events, function() {
clearTimeout(self.timers.img[i]);
imageLoad(this);
});

// Apply a recursive method that polls the image for dimensions every 20ms
(function timer(){
// When the dimensions are found, remove the image from the queue
if(elem.height) {
return imageLoad(elem);
}

self.timers.img[i] = setTimeout(timer, 20);
}());

return TRUE;
});

// If no images were found, continue with queue
if(images.length === 0) { imageLoad(images); }
});

return self;
}

function assignEvents(show, hide, tooltip, doc)
{
var namespace = '.qtip-'+id,
posOptions = options.position,
targets = {
show: options.show.target,
hide: options.hide.target,
tooltip: self.elements.tooltip,
container: posOptions.container[0] === document.body ? document : posOptions.container
},
events = { show: String(options.show.event).split(' '), hide: String(options.hide.event).split(' ') },
IE6 = $.browser.msie && parseInt($.browser.version, 10) === 6;

// Define show event method
function showMethod(event)
{
if(targets.tooltip.hasClass('ui-state-disabled')) { return FALSE; }

// If set, hide tooltip when inactive for delay period
targets.show.trigger('qtip-'+id+'-inactive');

// Clear hide timers
clearTimeout(self.timers.show);
clearTimeout(self.timers.hide);

// Start show timer
var callback = function(){ self.show(event); };
if(options.show.delay > 0) {
self.timers.show = setTimeout(callback, options.show.delay);
}
else{ callback(); }
}

// Define hide method
function hideMethod(event)
{
if(targets.tooltip.hasClass('ui-state-disabled')) { return FALSE; }

// Check if new target was actually the tooltip element
var ontoTooltip = $(event.relatedTarget || event.target).parents(selector)[0] === targets.tooltip[0],
ontoTarget = $(event.relatedTarget || event.target)[0] === targets.show[0];

// Clear timers and stop animation queue
clearTimeout(self.timers.show);
clearTimeout(self.timers.hide);

// Prevent hiding if tooltip is fixed and event target is the tooltip. Or if mouse positioning is enabled and cursor momentarily overlaps
if(options.hide.fixed && ((posOptions.target === 'mouse' && ontoTooltip) || ((/mouse(out|leave|move)/).test(event.type) && (ontoTooltip || ontoTarget))))
{
// Prevent default and popagation
event.stopPropagation();
event.preventDefault();
return FALSE;
}

// If tooltip has displayed, start hide timer
targets.tooltip.stop(1, 1);

if(options.hide.delay > 0) {
self.timers.hide = setTimeout(function(){ self.hide(event); }, options.hide.delay);
}
else{ self.hide(event); }
}

// Define inactive method
function inactiveMethod(event)
{
if(targets.tooltip.hasClass('ui-state-disabled')) { return FALSE; }

// Clear timer
clearTimeout(self.timers.inactive);
self.timers.inactive = setTimeout(function(){ self.hide(event); }, options.hide.inactive);
}

function repositionMethod(event) {
if(self.cache.processing) { return; }

// Only update position if tooltip is visible
self.cache.processing = 1;
if(self.elements.tooltip.is(':visible')) { self.reposition(event); }
self.cache.processing = 0;
}

// Catch remove events on target element to destroy tooltip
target.bind('remove.qtip', function(){ self.destroy(); });

// Check if the tooltip is 'fixed'
if(tooltip && options.hide.fixed)
{
// Add tooltip as a hide target
targets.hide = targets.hide.add(targets.tooltip);

// Clear hide timer on tooltip hover to prevent it from closing
targets.tooltip.bind('mouseover'+namespace, function() {
if(!targets.tooltip.hasClass('ui-state-disabled')) {
clearTimeout(self.timers.hide);
}
});
}

// Assign hide events
if(hide) {
// Check if the tooltip hides when inactive
if('number' === typeof options.hide.inactive)
{
// Bind inactive method to target as a custom event
targets.show.bind('qtip-'+id+'-inactive', inactiveMethod);

// Define events which reset the 'inactive' event handler
$.each($.fn.qtip.inactiveEvents, function(index, type){
targets.hide.add(self.elements.tooltip).bind(type+namespace+'-inactive', inactiveMethod);
});
}

// Apply hide events
$.each(events.hide, function(index, type) {
var showIndex = $.inArray(type, events.show);

// Both events and targets are identical, apply events using a toggle
if((showIndex > -1 && $(targets.hide).add(targets.show).length === $(targets.hide).length) || type === 'unfocus')
{
targets.show.bind(type+namespace, function(event)
{
if(targets.tooltip.is(':visible')) { hideMethod(event); }
else{ showMethod(event); }
});

// Don't bind the event again
delete events.show[ showIndex ];
}

// Events are not identical, bind normally
else{ targets.hide.bind(type+namespace, hideMethod); }
});
}

// Apply show events
if(show) {
$.each(events.show, function(index, type) {
targets.show.bind(type+namespace, showMethod);
});

// Focus the tooltip on mouseover
targets.tooltip.bind('mouseover'+namespace, function(){ self.focus(); });
}

// Apply document events
if(doc) {
// Adjust positions of the tooltip on window resize if enabled
if(posOptions.adjust.resize || posOptions.adjust.screen) {
$($.event.special.resize ? targets.container : window).bind('resize'+namespace, repositionMethod);
}

// Adjust tooltip position on scroll if screen adjustment is enabled
if(posOptions.adjust.screen || (IE6 && targets.tooltip.css('position') === 'fixed')) {
$(targets.container).bind('scroll'+namespace, repositionMethod);
}

// Hide tooltip on document mousedown if unfocus events are enabled
if((/unfocus/i).test(options.hide.event)) {
$(document).bind('mousedown'+namespace, function(event) {
var tooltip = self.elements.tooltip;

if($(event.target).parents(selector).length === 0 && $(event.target).add(target).length > 1 &&
tooltip.is(':visible') && !tooltip.hasClass('ui-state-disabled')) {
self.hide();
}
});
}

// If mouse is the target, update tooltip position on document mousemove
if(posOptions.target === 'mouse') {
$(document).bind('mousemove'+namespace, function(event) {
// Update the tooltip position only if the tooltip is visible and adjustment is enabled
if(posOptions.adjust.mouse && !targets.tooltip.hasClass('ui-state-disabled') && targets.tooltip.is(':visible')) {
self.reposition(event || $.fn.qtip.mouse);
}
});
}
}
}

function unassignEvents(show, hide, tooltip, doc)
{
doc = parseInt(doc, 10) !== 0;
var namespace = '.qtip-'+id,
targets = {
show: show ? options.show.target : NULL,
hide: hide ? options.hide.target : NULL,
tooltip: tooltip ? self.elements.tooltip : NULL,
content: tooltip ? self.elements.content : NULL,
container: doc ? options.position.container[0] === document.body ? document : options.position.container : NULL,
window: doc ? window : NULL
};

// Check if tooltip is rendered
if(self.rendered)
{
$([]).pushStack(
$.grep(
[ targets.show, targets.hide, targets.tooltip, targets.container, targets.content, targets.window ],
function(){ return this !== null; }
)
)
.unbind(namespace);
}

// Tooltip isn't yet rendered, remove render event
else if(show) { targets.show.unbind(namespace+'-create'); }
}

/*
* Public API methods
*/
$.extend(self, {
render: function(show)
{
var elements = self.elements, callback = $.Event('tooltiprender');

// If tooltip has already been rendered, exit
if(self.rendered) { return FALSE; }

// Call API method and set rendered status
self.rendered = show ? -2 : -1; // -1: rendering -2: rendering and show when done

// Create initial tooltip elements
elements.tooltip = $('<div/>')
.attr({
'id': uitooltip + '-'+id,
'role': 'tooltip',
'class': uitooltip + ' qtip ui-tooltip-accessible ui-helper-reset ' + options.style.classes
})
.css('z-index', $.fn.qtip.zindex + $(selector).length)
.toggleClass('ui-widget', options.style.widget)
.toggleClass('ui-state-disabled', self.cache.disabled)
.data('qtip', self)
.appendTo(options.position.container);

// Append to container element
elements.wrapper = $('<div />', { 'class': uitooltip + '-wrapper' }).appendTo(elements.tooltip);
elements.content = $('<div />', {
'class': uitooltip + '-content ' + (options.style.widget ? 'ui-widget-content' : ''),
'id': uitooltip + '-' + id + '-content'
})
.appendTo(elements.wrapper);

// Setup content and title (if enabled)
if(options.content.title.text) {
createTitle();
}
updateContent(options.content.text);

// Initialize 'render' plugins
$.each($.fn.qtip.plugins, function() {
if(this.initialize === 'render') { this(self); }
});

// Set rendered status to TRUE
self.rendered = TRUE;

// Assign events
assignEvents(1, 1, 1, 1);
$.each(options.events, function(name, callback) {
if(callback) { elements.tooltip.bind('tooltip'+name, callback); }
});

/* Queue this part of the render process in our fx queue so we can
* load images before the tooltip renders fully.
*
* See: updateContent method
*/
elements.tooltip.queue('fx', function(next) {
// Remove accessible class
elements.tooltip.removeClass('ui-tooltip-accessible');

// Trigger tooltiprender event and pass original triggering event as original
callback.originalEvent = self.cache.event;
elements.tooltip.trigger(callback, [self]);

// Update tooltip position and show tooltip if needed
if(options.show.ready || show) {
elements.tooltip.hide();
self.show(self.cache.event);
}

next(); // Move on
});

return self;
},

get: function(notation)
{
var result, o;

switch(notation.toLowerCase())
{
case 'offset':
result = calculate('position');
break;

case 'dimensions':
result = calculate('dimensions');
break;

default:
o = convertNotation(notation.toLowerCase());
result = (o[0].precedance) ? o[0].string() : (o[0].jquery) ? o[0] : o[0][ o[1] ];
break;
}

return result;
},

set: function(notation, value)
{
notation = notation.toLowerCase();
var option = convertNotation(notation),
elems = self.elements,
tooltip = elems.tooltip,
previous,
category, rule,
checks = {
builtin: {
// Core checks
'id': function(obj, opt, val, prev) {
var id = value === TRUE ? $.fn.qtip.nextid : value,
idStr = uitooltip + '-' + id;

if(id !== FALSE && id.length > 0 && !$('#ui-tooltip-'+id).length) {
tooltip[0].id = idStr;
elems.content[0].id = idStr + '-content';
elems.title[0].id = idStr + '-title';
}
},

// Content checks
'^content.text': function(){ updateContent(value); },
'^content.title.text': function(){ updateTitle(value); },
'^content.title.button': function(){ updateButton(value); },

// Position checks
'^position.(my|at)$': function(){
// Parse new corner value into Corner objecct
var corner = (/my$/i).test(notation) ? 'my' : 'at';

if('string' === typeof value) {
options.position[corner] = new $.fn.qtip.plugins.Corner(value);
}
},
'^position.(my|at|adjust|target)': function(){ if(self.rendered) { self.reposition(); } },
'^position.container$': function(){
if(self.rendered === TRUE) {
tooltip.appendTo(value);
self.reposition();
}
},

// Show & hide checks
'^(show|hide).(event|target|fixed|delay|inactive)': function(obj, opt, val, prev) {
var args = notation.search(/fixed/i) > -1 ? [0, [0,1,1,1]] : [notation.substr(0,3), notation.charAt(0) === 's' ? [1,0,0,0] : [0,1,0,0]];

if(args[0]) { obj[opt] = prev; }
unassignEvents.apply(self, args[1]);

if(args[0]) { obj[opt] = val; }
assignEvents.apply(self, args[1]);
},
'^show.ready$': function() { if(self.rendered === FALSE) { self.show(); } },

// Style checks
'^style.classes$': function() { self.elements.tooltip.attr('class', uitooltip + ' qtip ui-helper-reset ' + value); },
'^style.widget$': function() {
var trigger = !!value;

tooltip.toggleClass('ui-widget', trigger);
elems.titlebar.toggleClass('ui-widget-header', trigger);
elems.content.toggleClass('ui-widget-content', trigger);
elems.button.children('span').toggleClass(uitooltip+'-icon', !trigger).toggleClass('ui-icon', trigger);
},

// Events check
'^events.(render|show|move|hide|focus|blur)': function(obj, opt, val, prev) {
elems.tooltip[($.isFunction(value) ? '' : 'un') + 'bind']('tooltip'+opt, val);
}
}
};

// Merge active plugin checks
$.each(self.plugins, function(name) {
if('object' === typeof this.checks) {
checks[name] = this.checks;
}
});

// Set new option value
previous = option[0][ option[1] ];
option[0][ option[1] ] = value.nodeType ? $(value) : value;

// Re-sanitize options
sanitizeOptions(options);

// Execute any valid callbacks
for(category in checks) {
for(rule in checks[category]) {
if((new RegExp(rule, 'i')).test(notation)) {
checks[category][rule].call(self, option[0], option[1], value, previous);
}
}
}

return self;
},

toggle: function(state, event)
{
if(self.rendered === FALSE) { return FALSE; }

var type = state ? 'show' : 'hide',
tooltip = self.elements.tooltip,
opts = options[type],
visible = tooltip.is(':visible'),
callback;

// Detect state if valid one isn't provided
if((typeof state).search('boolean|number')) { state = !tooltip.is(':visible'); }

// Return if element is already in correct state
if((!visible && !state) || tooltip.is(':animated')) { return self; }

// Try to prevent flickering when tooltip overlaps show element
if(event) {
if((/over|enter/).test(event.type) && (/out|leave/).test(self.cache.event.type) &&
event.target === options.show.target[0] && tooltip.has(event.relatedTarget).length){
return self;
}

// Cache event
self.cache.event = $.extend({}, event);
}

// Define after callback
function after()
{
var elem = $(this),
attr = state ? 'attr' : 'removeAttr',
opacity = (/^1|0$/).test(elem.css('opacity')),
ieStyle = this.style;

// Apply ARIA attributes when tooltip is shown
if(self.elements.title){ target[attr]('aria-labelledby', uitooltip + '-'+id+'-title'); }
target[attr]('aria-describedby', uitooltip + '-'+id+'-content');

// Prevent antialias from disappearing in IE7 by removing filter and opacity attribute
if(state) {
if($.browser.msie && ieStyle && opacity) {
ieStyle.removeAttribute('filter');
ieStyle.removeAttribute('opacity');
}
}

// Otherwise just hide
else if(opacity) { elem.hide(); }
}

// Call API methods
callback = $.Event('tooltip'+type);
callback.originalEvent = event ? self.cache.event : NULL;
tooltip.trigger(callback, [self, 90]);
if(callback.isDefaultPrevented()){ return self; }

// Execute state specific properties
if(state) {
self.focus(); // Focus the tooltip before show to prevent visual stacking
self.reposition(event); // Update tooltip position

// Hide other tooltips if tooltip is solo
if(opts.solo) { $(selector).qtip('hide'); }
}

// Clear show timer if we're hiding
else { clearTimeout(self.timers.show); }

// Set ARIA hidden status attribute
tooltip.attr('aria-hidden', Boolean(!state));

// Clear animation queue
tooltip.stop(1, 1);

// Use custom function if provided
if($.isFunction(opts.effect)) {
opts.effect.call(tooltip, self);
tooltip.queue(function(){ after.call(this); $(this).dequeue(); });
}

// If no effect type is supplied, use a simple toggle
else if(opts.effect === FALSE) {
tooltip[ type ]();
after.call(tooltip);
}

// Use basic fade function by default
else { tooltip.fadeTo(90, state ? 1 : 0, after); }

// If inactive hide method is set, active it
if(state) { opts.target.trigger('qtip-'+id+'-inactive'); }

return self;
},

show: function(event){ self.toggle(TRUE, event); },

hide: function(event){ self.toggle(FALSE, event); },

focus: function(event)
{
if(self.rendered === FALSE) { return FALSE; }

var tooltip = self.elements.tooltip,
qtips = $(selector),
curIndex = parseInt(tooltip[0].style.zIndex, 10),
newIndex = $.fn.qtip.zindex + qtips.length,
focusClass = uitooltip + '-focus',
cachedEvent = $.extend({}, event),
callback;

// Only update the z-index if it has changed and tooltip is not already focused
if(!tooltip.hasClass(focusClass) && curIndex !== newIndex)
{
// Reduce our z-index's and keep them properly ordered
qtips.each(function() {
this.style.zIndex = this.style.zIndex - 1;
});

// Fire blur event for focussed tooltip
$(selector + '.' + focusClass).each(function() {
var self = $(this), api = self.qtip(), blur;

if(!api || api.rendered === FALSE) { return TRUE; }

// Set focused status to FALSE
self.removeClass(focusClass);

// Trigger blur event
blur = $.Event('tooltipblur');
blur.originalEvent = cachedEvent;
self.trigger(blur, [api, newIndex]);
});

// Call API method
callback = $.Event('tooltipfocus');
callback.originalEvent = cachedEvent;
tooltip.trigger(callback, [self, newIndex]);

// Set the new z-index and set focus status to TRUE if callback wasn't FALSE
if(!callback.isDefaultPrevented()) {
tooltip.addClass(focusClass)[0].style.zIndex = newIndex;
}
}

return self;
},

reposition: function(event)
{
if(self.rendered === FALSE) { return FALSE; }

var target = options.position.target,
tooltip = self.elements.tooltip,
posOptions = options.position,
my = posOptions.my,
at = posOptions.at,
adjust = posOptions.adjust,
elemWidth = self.elements.tooltip.width(),
elemHeight = self.elements.tooltip.height(),
targetWidth = 0,
targetHeight = 0,
callback = $.Event('tooltipmove'),
fixed = tooltip.css('position') === 'fixed',
viewport = posOptions.container[0] !== document.body ? posOptions.container : $(window),
position = { left: 0, top: 0 },
readjust = {
left: function(posLeft) {
var viewportScroll = viewport.scrollLeft,
myWidth = my.x === 'left' ? elemWidth : my.x === 'right' ? -elemWidth : -elemWidth / 2,
atWidth = at.x === 'left' ? targetWidth : at.x === 'right' ? -targetWidth : -targetWidth / 2,
adjustX = (my.x === my.y ? 1 : -2) * adjust.x,
overflowLeft = viewportScroll - posLeft,
overflowRight = posLeft + elemWidth - viewport.width - viewportScroll,
offset = myWidth - adjustX - (my.precedance === 'x' || my.x === my.y ? atWidth : 0);

if(overflowLeft > 0 && (my.x !== 'left' || overflowRight > 0)) {
position.left -= offset;
}
else if(overflowRight > 0 && (my.x !== 'right' || overflowLeft > 0) ) {
position.left -= (my.x === 'center' ? -1 : 1) * offset;
}

if(position.left < 0) { position.left = posLeft; }

return position.left - posLeft;
},
top: function(posTop) {
var viewportScroll = viewport.scrollTop,
myHeight = my.y === 'top' ? elemHeight : my.y === 'bottom' ? -elemHeight : -elemHeight / 2,
atHeight = at.y === 'top' ? targetHeight : at.y === 'bottom' ? -targetHeight : -targetHeight / 2,
adjustY = (my.y === my.x ? 1 : -2) * adjust.y,
overflowTop = viewportScroll - posTop,
overflowBottom = posTop + elemHeight - viewport.height - viewportScroll + adjust.y,
offset = myHeight - adjustY - (my.precedance === 'y' || my.x === my.y ? atHeight : 0);

if(overflowTop > 0 && (my.y !== 'top' || overflowBottom > 0)) {
position.top -= offset;
}
else if(overflowBottom > 0 && (my.y !== 'bottom' || overflowTop > 0) ) {
position.top -= (my.y === 'center' ? -1 : 1) * offset;
}

if(position.top < 0) { position.top = posTop; }

return position.top - posTop;
}
};

// Cache our viewport details
viewport = {
elem: viewport,
height: viewport[ (viewport[0] === window ? 'h' : 'outerH') + 'eight' ](),
width: viewport[ (viewport[0] === window ? 'w' : 'outerW') + 'idth' ](),
scrollLeft: viewport.scrollLeft(),
scrollTop: viewport.scrollTop()
};

// Check if mouse was the target
if(target === 'mouse') {
// Force left top to allow flipping
at = { x: 'left', y: 'top' };

// Use cached event if one isn't available for positioning
event = event && (event.type === 'resize' || event.type === 'scroll') ? self.cache.event :
adjust.mouse || !event || !event.pageX ? $.extend({}, $.fn.qtip.mouse) : event;

// Use event coordinates for position
position = { top: event.pageY, left: event.pageX };
}
else {
// Check if event targetting is being used
if(target === 'event') {
if(event && event.target && event.type !== 'scroll' && event.type !== 'resize') {
target = self.cache.target = $(event.target);
}
else {
target = self.cache.target;
}
}

// Parse the target into a jQuery object and make sure there's an element present
target = $(target).eq(0);
if(target.length === 0) { return self; }

// Check if window or document is the target
else if(target[0] === document || target[0] === window) {
targetWidth = target.width();
targetHeight = target.height();

if(target[0] === window) {
position = {
top: fixed ? 0 : viewport.scrollTop,
left: fixed ? 0 : viewport.scrollLeft
};
}
}

// Use Imagemap plugin if target is an AREA element
else if(target.is('area') && $.fn.qtip.plugins.imagemap) {
position = $.fn.qtip.plugins.imagemap(target, at);
targetWidth = position.width;
targetHeight = position.height;
position = position.offset;
}

else {
targetWidth = target.outerWidth();
targetHeight = target.outerHeight();

position = offset(target[0], posOptions.container[0]);
}

// Adjust position relative to target
position.left += at.x === 'right' ? targetWidth : at.x === 'center' ? targetWidth / 2 : 0;
position.top += at.y === 'bottom' ? targetHeight : at.y === 'center' ? targetHeight / 2 : 0;
}

// Adjust position relative to tooltip
position.left += adjust.x + (my.x === 'right' ? -elemWidth : my.x === 'center' ? -elemWidth / 2 : 0);
position.top += adjust.y + (my.y === 'bottom' ? -elemHeight : my.y === 'center' ? -elemHeight / 2 : 0);

// Calculate collision offset values
if(adjust.screen && target[0] !== window && target[0] !== document.body) {
position.adjusted = { left: readjust.left(position.left), top: readjust.top(position.top) };
}
else {
position.adjusted = { left: 0, top: 0 };
}

// Set tooltip position class
tooltip.attr('class', function(i, val) {
return $(this).attr('class').replace(/ui-tooltip-pos-\w+/i, '');
})
.addClass(uitooltip + '-pos-' + my.abbreviation());


// Call API method
callback.originalEvent = $.extend({}, event);
tooltip.trigger(callback, [self, position, viewport.elem]);
if(callback.isDefaultPrevented()){ return self; }
delete position.adjusted;

// Use custom function if provided
if(tooltip.is(':visible') && $.isFunction(posOptions.effect)) {
posOptions.effect.call(tooltip, self, position);
tooltip.queue(function() {
var elem = $(this);
// Reset attributes to avoid cross-browser rendering bugs
elem.css({ opacity: '', height: '' });
if($.browser.msie && this.style) { this.style.removeAttribute('filter'); }
elem.dequeue();
});
}
else if(!isNaN(position.left, position.top)) {
tooltip.css(position);
}

return self;
},

// IE max/min height/width simulartor function
redraw: function()
{
// Make sure tooltip is rendered and the browser needs the redraw
if(!self.rendered || !($.browser.msie && parseInt($.browser.version.charAt(0), 10) < 9)) { return FALSE; }

var tooltip = self.elements.tooltip,
style = tooltip.attr('style'),
dimensions;

// Determine actual dimensions using our calculate function
tooltip.css({ width: 'auto', height: 'auto' });
dimensions = calculate('dimensions', 1);

// Determine actual width
$.each(['width', 'height'], function(i, prop) {
// Parse our max/min properties
var max = parseInt(tooltip.css('max-'+prop), 10) || 0,
min = parseInt(tooltip.css('min-'+prop), 10) || 0;

// Determine new dimension size based on max/min/current values
dimensions[prop] = max + min ? Math.min( Math.max( dimensions[prop], min ), max ) : dimensions[prop];
});

// Set the newly calculated dimensions
tooltip.css(dimensions);
},

disable: function(state)
{
var tooltip = self.elements.tooltip;

if(self.rendered) {
tooltip.toggleClass('ui-state-disabled', state);
}
else {
self.cache.disabled = !!state;
}

return self;
},

destroy: function()
{
var elements = self.elements,
oldtitle = elements.target.data('oldtitle');

// Destroy any associated plugins when rendered
if(self.rendered) {
$.each(self.plugins, function() {
if(this.initialize === 'render') { this.destroy(); }
});
}

// Remove bound events
unassignEvents(1, 1, 1, 1);

// Remove api object and tooltip
target.removeData('qtip');
if(self.rendered) { elements.tooltip.remove(); }

// Reset old title attribute if removed and reset describedby attribute
if(oldtitle) {
target.attr('title', oldtitle);
}
target.removeAttr('aria-describedby');

return target;
}
});
}

// Initialization method
function init(id, opts)
{
var obj, posOptions,

// Setup element references
elem = $(this),
docBody = $(document.body),

// Use document body instead of document element if needed
newTarget = this === document ? docBody : elem,

// Grab metadata from element if plugin is present
metadata = (elem.metadata) ? elem.metadata(opts.metadata) : NULL,

// Check if the metadata returned is in HTML5 form and grab 'name' from the object instead
metadata5 = metadata && opts.metadata.type === 'html5' ? metadata[opts.metadata.name] : NULL,

// Merge in our sanitized metadata and remove metadata object so we don't interfere with other metadata calls
config = $.extend(TRUE, {}, $.fn.qtip.defaults, opts, sanitizeOptions(metadata5 || metadata));
elem.removeData('metadata');

// Re-grab our positioning options now we've merged our metadata
posOptions = config.position;

// Setup missing content if none is detected
if('boolean' === typeof config.content.text) {

// Grab from supplied attribute if available
if(config.content.attr !== FALSE && elem.attr(config.content.attr)) {
config.content.text = elem.attr(config.content.attr);
}

// No valid content was found, abort render
else {
return FALSE;
}
}

// Setup target options
if(posOptions.container === FALSE) { posOptions.container = docBody; }
if(posOptions.target === FALSE) { posOptions.target = newTarget; }
if(config.show.target === FALSE) { config.show.target = newTarget; }
if(config.hide.target === FALSE) { config.hide.target = newTarget; }

// Convert position corner values into x and y strings
posOptions.at = new $.fn.qtip.plugins.Corner(posOptions.at);
posOptions.my = new $.fn.qtip.plugins.Corner(posOptions.my);

// Destroy previous tooltip if overwrite is enabled, or skip element if not
if(elem.data('qtip')) {
if(config.overwrite) {
elem.qtip('destroy');
}
else if(config.overwrite === FALSE) {
return FALSE;
}
}

// Remove title attribute and store it if present
if(elem.attr('title')) {
elem.data('oldtitle', elem.attr('title')).removeAttr('title');
}

// Initialize the tooltip and add API reference
obj = new QTip(elem, config, id);
elem.data('qtip', obj);

return obj;
}

// jQuery $.fn extension method
$.fn.qtip = function(options, notation, newValue)
{
var command = String(options).toLowerCase(), // Parse command
returned = NULL,
args = command === 'disable' ? [TRUE] : $.makeArray(arguments).slice(1, 10),
event = args[args.length - 1],
opts;

// Check for API request
if((!arguments.length && this.data('qtip')) || command === 'api') {
opts = this.data('qtip');
return opts ? opts : undefined;
}

// Execute API command if present
else if('string' === typeof options)
{
this.each(function()
{
var api = $(this).data('qtip');
if(!api) { return TRUE; }

// Call APIcommand
if((/option|set/).test(command) && notation) {
if(newValue !== undefined) {
api.set(notation, newValue);
}
else {
returned = api.get(notation);
}
}
else {
// Render tooltip if not already rendered when tooltip is to be shown
if(!api.rendered && (command === 'show' || command === 'toggle')) {
if(event && event.timeStamp) { api.cache.event = event; }
api.render(1);
}

// Check for disable/enable commands
else if(command === 'enable') {
command = 'disable'; args = [FALSE];
}

// Execute API command
if(api[command]) {
api[command].apply(api[command], args);
}
}
});

return returned !== NULL ? returned : this;
}

// No API commands. validate provided options and setup qTips
else if('object' === typeof options || !arguments.length)
{
opts = sanitizeOptions($.extend(TRUE, {}, options));

// Bind the qTips
return $.fn.qtip.bind.call(this, opts, event);
}
};

// $.fn.qtip Bind method
$.fn.qtip.bind = function(opts, event)
{
return this.each(function(i) {
var options, targets, events,

// Find next available ID, or use custom ID if provided
id = opts.id = (!opts.id || opts.id === FALSE || opts.id.length < 1 || $('#ui-tooltip-'+opts.id).length) ? $.fn.qtip.nextid++ : opts.id,

// Setup events namespace
namespace = '.qtip-'+id+'-create',

// Initialize the qTip and re-grab newly sanitized options
self = init.call(this, id, opts);
if(self === FALSE) { return TRUE; }
options = self.options;

// Initialize plugins
$.each($.fn.qtip.plugins, function() {
if(this.initialize === 'initialize') { this(self); }
});

// Determine hide and show targets
targets = { show: options.show.target, hide: options.hide.target };
events = {
show: String(options.show.event).replace(' ', namespace+' ') + namespace,
hide: String(options.hide.event).replace(' ', namespace+' ') + namespace
};

// Define hoverIntent function
function hoverIntent(event) {
function render() {
// Cache mouse coords,render and render the tooltip
self.render(typeof event === 'object' || options.show.ready);

// Unbind show and hide event
targets.show.unbind(events.show);
targets.hide.unbind(events.hide);
}

// Only continue if tooltip isn't disabled
if(self.cache.disabled) { return FALSE; }

// Cache the event data
self.cache.event = $.extend({}, event);

// Start the event sequence
if(options.show.delay > 0) {
clearTimeout(self.timers.show);
self.timers.show = setTimeout(render, options.show.delay);
if(events.show !== events.hide) {
targets.hide.bind(events.hide, function() { clearTimeout(self.timers.show); });
}
}
else { render(); }
}

// Bind show events to target
targets.show.bind(events.show, hoverIntent);

// Prerendering is enabled, create tooltip now
if(options.show.ready || options.prerender) { hoverIntent(event); }
});
};

// Override some of the core jQuery methods for library-specific purposes
$.each({
/* Allow other plugins to successfully retrieve the title of an element with a qTip applied */
attr: function(attr) {
var self = $(this), api = self.data('qtip');
return (arguments.length === 1 && attr === 'title' && api && api.rendered === TRUE) ? self.data('oldtitle') : NULL;
},

/*
* Taken directly from jQuery 1.8.2 widget source code
* Trigger 'remove' event on all elements on removal if jQuery UI isn't present
*/
remove: $.ui ? NULL : function( selector, keepData ) {
$(this).each(function() {
if (!keepData) {
if (!selector || $.filter( selector, [ this ] ).length) {
$('*', this).add(this).each(function() {
$(this).triggerHandler('remove');
});
}
}
});
}
},
function(name, func) {
if(!func) { return TRUE; }
$.fn['Old'+name] = $.fn[name];
$.fn[name] = function() {
return func.apply(this, arguments) || $.fn['Old'+name].apply(this, arguments);
};
});

/*
* Add ARIA role attribute to document body if not already present
* http://wiki.jqueryui.com/Tooltip - 4.3 Accessibility recommendation
*/
$(document.body).attr('role', function(i, val) { return !val ? 'application' : val; });

// Cache mousemove events for positioning purposes
$(document).bind('mousemove.qtip', function(event) {
$.fn.qtip.mouse = { pageX: event.pageX, pageY: event.pageY };
});

// Set global qTip properties
$.fn.qtip.version = '2.0.0pre';
$.fn.qtip.nextid = 0;
$.fn.qtip.inactiveEvents = 'click dblclick mousedown mouseup mousemove mouseleave mouseenter'.split(' ');
$.fn.qtip.zindex = 15000;

// Setup base plugins
$.fn.qtip.plugins = {
// Corner object parser
Corner: function(corner) {
corner = String(corner).replace(/([A-Z])/, ' $1').replace(/middle/gi, 'center').toLowerCase();
this.x = (corner.match(/left|right/i) || corner.match(/center/) || ['inherit'])[0].toLowerCase();
this.y = (corner.match(/top|bottom|center/i) || ['inherit'])[0].toLowerCase();

this.precedance = (corner.charAt(0).search(/^(t|b)/) > -1) ? 'y' : 'x';
this.string = function() { return this.precedance === 'y' ? this.y+this.x : this.x+this.y; };
this.abbreviation = function() {
var x = this.x.substr(0,1), y = this.y.substr(0,1);
return x === y ? x : (x === 'c' || (x !== 'c' && y !== 'c')) ? y + x : x + y;
};
},

/*
* iOS 4.0 and below scroll fix detection used in offset() function.
*/
iOS: parseFloat(((/CPU.+OS ([0-9_]{3}).*AppleWebkit.*Mobile/i.exec(navigator.userAgent)) || [0,'4_2'])[1].replace('_','.')) < 4.1
};

// Define configuration defaults
$.fn.qtip.defaults = {
prerender: FALSE,
id: FALSE,
overwrite: TRUE,
metadata: {
type: 'class'
},
content: {
text: TRUE,
attr: 'title',
title: {
text: FALSE,
button: FALSE
}
},
position: {
my: 'top left',
at: 'bottom right',
target: FALSE,
container: FALSE,
adjust: {
x: 0, y: 0,
mouse: TRUE,
screen: FALSE,
resize: TRUE
},
effect: TRUE
},
show: {
target: FALSE,
event: 'mouseenter',
effect: TRUE,
delay: 90,
solo: FALSE,
ready: FALSE
},
hide: {
target: FALSE,
event: 'mouseleave',
effect: TRUE,
delay: 0,
fixed: FALSE,
inactive: FALSE
},
style: {
classes: '',
widget: FALSE
},
events: {
render: NULL,
move: NULL,
show: NULL,
hide: NULL,
focus: NULL,
blur: NULL
}
};function Ajax(qTip)
{
var self = this;

self.checks = {
'^content.ajax': function() { this.plugins.ajax.load(this.options.content.ajax); }
};

$.extend(self, {

init: function()
{
// Grab ajax options
var ajax = qTip.options.content.ajax;

// Bind render event to load initial content
qTip.elements.tooltip.bind('tooltiprender.ajax', function() {
self.load(ajax);

// Bind show event
qTip.elements.tooltip.bind('tooltipshow.ajax', function() {
// Update content if content.ajax.once is FALSE and the tooltip is rendered
if(ajax.once === FALSE && qTip.rendered === TRUE) { self.load(ajax); }
});
});
},

load: function(ajax)
{
// Define success and error handlers
function successHandler(content, status)
{
// Call user-defined success handler if present
if($.isFunction(ajax.success)) {
var result = ajax.success.call(qTip, content, status);
if(result === FALSE){ return; }
}

// Update content
qTip.set('content.text', content);

}
function errorHandler(xhr, status, error)
{
var content = status || error, result;

// Call user-defined success handler if present
if($.isFunction(ajax.error)) {
result = ajax.error.call(qTip, xhr, status, error);
if(result === FALSE){ return; }
}

// Update tooltip content to indicate error
qTip.set('content.text', content);
}

// Setup $.ajax option object and process the request
$.ajax( $.extend(TRUE, {}, ajax, { success: successHandler, error: errorHandler }) );

return self;
},

destroy: function()
{
// Remove bound events
qTip.elements.tooltip.unbind('tooltipshow.ajax');
}
});

self.init();
}


$.fn.qtip.plugins.ajax = function(qTip)
{
var api = qTip.plugins.ajax,
opts = qTip.options.content.ajax;

// Make sure the qTip uses the $.ajax functionality
if(opts && opts.url) {
// An API is already present, return it
if(api) {
return api;
}
// No API was found, create new instance
else {
qTip.plugins.ajax = new Ajax(qTip);
return qTip.plugins.ajax;
}
}
};

$.fn.qtip.plugins.ajax.initialize = 'render';

// Setup plugin sanitization
$.fn.qtip.plugins.ajax.sanitize = function(options)
{
var content = options.content, opts;
if(content && 'ajax' in content) {
opts = content.ajax;
if(typeof opts !== 'object') { opts = options.content.ajax = { url: opts }; }
if('boolean' !== typeof opts.once && opts.once) { opts.once = !!opts.once; }
}
};

// Extend original qTip defaults
$.extend(TRUE, $.fn.qtip.defaults, {
content: {
ajax: {
once: TRUE
}
}
});// Tip coordinates calculator
function calculateTip(corner, width, height)
{
var width2 = Math.floor(width / 2), height2 = Math.floor(height / 2),

// Define tip coordinates in terms of height and width values
tips = {
bottomright: [[0,0], [width,height], [width,0]],
bottomleft: [[0,0], [width,0], [0,height]],
topright: [[0,height], [width,0], [width,height]],
topleft: [[0,0], [0,height], [width,height]],
topcenter: [[0,height], [width2,0], [width,height]],
bottomcenter: [[0,0], [width,0], [width2,height]],
rightcenter: [[0,0], [width,height2], [0,height]],
leftcenter: [[width,0], [width,height], [0,height2]]
};

// Set common side shapes
tips.lefttop = tips.bottomright; tips.righttop = tips.bottomleft;
tips.leftbottom = tips.topright; tips.rightbottom = tips.topleft;

return tips[corner];
}

function Tip(qTip, command)
{
var self = this,
opts = qTip.options.style.tip,
elems = qTip.elements,
tooltip = elems.tooltip,
wrapper = elems.wrapper,
cache = {
top: 0,
left: 0,
corner: { string: function(){} }
},
size = {
width: opts.width,
height: opts.height
},
color = { },
border = opts.border || 0,
method = opts.method || FALSE;

self.corner = NULL;
self.mimic = NULL;
self.checks = {
'^position.my|style.tip.(corner|mimic|method|border)': function() {
// Re-determine tip type and update
border = opts.border;

// Make sure a tip can be drawn
if(!self.init()) {
self.destroy();
}

// Only update the position if mouse isn't the target
else if(this.get('position.target') !== 'mouse') {
this.reposition();
}
},
'^style.tip.(height|width)': function() {
// Re-set dimensions and redraw the tip
size = {
width: opts.width,
height: opts.height
};
self.create();
self.update();

// Reposition the tooltip
qTip.reposition();
},
'^style.(classes|widget)$': function() {
self.detectColours();
self.update();
}
};

// Tip position method
function position(corner)
{
var tip = elems.tip,
corners = ['left', 'right'],
offset = opts.offset,
precedance, precedanceOp;

// Return if tips are disabled or tip is not yet rendered
if(opts.corner === FALSE || !tip) { return FALSE; }

// Inherit corner if not provided
corner = corner || self.corner;

// Cache precedances
precedance = corner.precedance;
precedanceOp = precedance === 'y' ? 'x' : 'y';

// Setup corners to be adjusted
corners[ precedance === 'y' ? 'push' : 'unshift' ]('top', 'bottom');

// Calculate offset adjustments
offset = Math.max(corner[ precedanceOp ] === 'center' ? offset : 0, offset);

// Reet initial position
tip.css({ top: '', bottom: '', left: '', right: '', margin: '' });

// Adjust primary corners
switch(corner[ precedance === 'y' ? 'x' : 'y' ])
{
case 'center':
tip.css(corners[0], '50%').css('margin-'+corners[0], -Math.floor(size[ (precedance === 'y') ? 'width' : 'height' ] / 2) + offset);
break;

case corners[0]:
tip.css(corners[0], offset);
break;

case corners[1]:
tip.css(corners[1], offset);
break;
}

// Determine secondary adjustments
offset = size[ (precedance === 'x') ? 'width' : 'height' ];
if(border) {
tooltip.toggleClass('ui-tooltip-accessible', !tooltip.is(':visible'));
offset -= parseInt(wrapper.css('border-' + corner[ precedance ] + '-width'), 10) || 0;
tooltip.removeClass('ui-tooltip-accessible');
}

// VML adjustments
if(method === 'vml' && (/bottom|right/).test(corner[ corner.precedance ])) {
offset += border ? 1 : -1;
}

// Adjust secondary corners
tip.css(corner[precedance], -offset);
}

function reposition(event, api, pos, viewport) {
if(!elems.tip) { return; }

var newCorner = $.extend({}, self.corner),
precedance = newCorner.precedance === 'y' ? ['y', 'top', 'left', 'height', 'x'] : ['x', 'left', 'top', 'width', 'y'],
adjusted = pos.adjusted,
offset = [0, 0];

// Make sure our tip position isn't fixed e.g. doesn't adjust with adjust.screen
if(self.corner.fixed !== TRUE) {
// Adjust tip corners
if(adjusted.left) {
newCorner.x = newCorner.x === 'center' ? (adjusted.left > 0 ? 'left' : 'right') : (newCorner.x === 'left' ? 'right' : 'left');
}
if(adjusted.top) {
newCorner.y = newCorner.y === 'center' ? (adjusted.top > 0 ? 'top' : 'bottom') : (newCorner.y === 'top' ? 'bottom' : 'top');
}

// Update and redraw the tip if needed
if(newCorner.string() !== cache.corner.string() && (cache.top !== adjusted.top || cache.left !== adjusted.left)) {
self.update(newCorner);
}
}

// Setup offset adjustments
offset[0] = border ? parseInt(wrapper.css('border-' + newCorner[ precedance[0] ] + '-width'), 10) || 0 : (method === 'vml' ? 1 : 0);
offset[1] = Math.max(newCorner[ precedance[4] ] === 'center' ? opts.offset : 0, opts.offset);

// Adjust tooltip position in relation to tip element
pos[ precedance[1] ] += (newCorner[ precedance[0] ] === precedance[1] ? 1 : -1) * (size[ precedance[3] ] - offset[0]);
pos[ precedance[2] ] -= (newCorner[ precedance[4] ] === precedance[2] || newCorner[ precedance[4] ] === 'center' ? 1 : -1) * offset[1];

// Cache details
cache.left = adjusted.left;
cache.top = adjusted.top;
cache.corner = newCorner;
}

$.extend(self, {
init: function()
{
var ie = $.browser.msie,
enabled = self.detectCorner(),
center = self[self.mimic ? 'mimic' : 'corner'].string().indexOf('center') > -1;

// Determine tip corner and type
if(enabled) {
// Check if rendering method is possible and if not fall back
if(method === TRUE) {
method = $('<canvas />')[0].getContext ? 'canvas' : ie && (center || size.height !== size.width) ? 'vml' : 'polygon';
}
else {
if(method === 'canvas') {
method = ie ? 'vml' : !$('<canvas />')[0].getContext ? 'polygon' : 'canvas';
}
else if(method === 'polygon') {
method = ie && center ? 'vml' : method;
}
}

// Create a new tip
self.create();
self.detectColours();
self.update();

// Bind update events
tooltip.unbind('.qtip-tip').bind('tooltipmove.qtip-tip', reposition);
}

return enabled;
},

detectCorner: function()
{
var corner = opts.corner,
at = qTip.options.position.at,
my = qTip.options.position.my;
if(my.string) { my = my.string(); }

// Detect corner and mimic properties
if(corner === FALSE || (my === FALSE && at === FALSE)) {
return FALSE;
}
else {
if(corner === TRUE) {
self.corner = new $.fn.qtip.plugins.Corner(my);
}
else if(!corner.string) {
self.corner = new $.fn.qtip.plugins.Corner(corner);
self.corner.fixed = TRUE;
}
}

return self.corner.string() !== 'centercenter';
},

detectColours: function() {
var tip = elems.tip,
corner = self.corner,
precedance = self.corner[ self.corner.precedance ],
borderSide = 'border-' + precedance + '-color',
invalid = /rgba?\(0, 0, 0(, 0)?\)|transparent/i,
isTitleTop = elems.titlebar && corner.y === 'top',
isWidget = qTip.options.style.widget,
elemFill = isWidget ? elems.content : isTitleTop ? elems.titlebar : elems.wrapper,
elemBorder = !isWidget ? elems.wrapper : isTitleTop ? elems.titlebar : elems.content;

// Detect tip colours from CSS styles
color.fill = tip.css({ backgroundColor: '', border: '' }).css('background-color') || 'transparent';
color.border = tip.get(0).style ? tip.get(0).style['border' + precedance.charAt(0) + precedance.substr(1) + 'Color'] : tip.css(borderSide) || 'transparent';

// Make sure colours are valid and reset background and border properties
if(invalid.test(color.fill)) {
color.fill = border ? elemFill.css('background-color') : elemBorder.css(borderSide);
}
if(!color.border || invalid.test(color.border)) {
color.border = elemBorder.css(borderSide) || color.fill;
}

// Reset background and border colours
$('*', tip).add(tip).css('background-color', 'transparent').css('border', 0);
},

create: function()
{
var width = size.width,
height = size.height;

// Create tip element and prepend to the tooltip if needed
if(elems.tip){ elems.tip.remove(); }
elems.tip = $('<div class="ui-tooltip-tip" />')
.toggleClass('ui-widget-content', qTip.options.style.widget)
.css(size).prependTo(tooltip);

// Create tip element
switch(method)
{
case 'canvas':
// save() as soon as we create the canvas element so FF2 doesn't bork on our first restore()!
$('<canvas height="'+height+'" width="'+width+'" />').appendTo(elems.tip)[0].getContext('2d').save();
break;

case 'vml':
elems.tip.html('<vml:shape coordorigin="0 0" coordsize="'+width+' '+height+'" stroked="' + !!border + '" ' +
' style="behavior:url(#default#VML); display:inline-block; antialias:TRUE; position: absolute; ' +
' top:0; left:0; width:'+width+'px; height:'+height+'px; vertical-align:'+self.corner.y+';">' +

'<vml:stroke weight="' + (border-2) + 'px" joinstyle="miter" miterlimit="10" ' +
' style="behavior:url(#default#VML); display:inline-block;" />' +

'</vml:shape>');
break;

case 'polygon':
elems.tip.append('<div class="ui-tooltip-tip-inner" />').append(border ? '<div class="ui-tooltip-tip-border" />' : '');
break;
}

return self;
},

update: function(corner)
{
var tip = elems.tip,
width = size.width,
height = size.height,
regular = 'px solid ',
transparent = 'px dashed transparent', // Dashed IE6 border-transparency hack. Awesome!
i = border > 0 ? 0 : 1,
translate = Math.ceil(border / 2 + 0.5),
mimic = opts.mimic,
factor, context, path, coords, inner, round;

// Re-determine tip if not already set
if(!corner) { corner = self.corner; }

// Use corner property if we detect an invalid mimic value
if(mimic === FALSE) { mimic = corner; }

// Otherwise inherit mimic properties from the corner object as necessary
else {
mimic = new $.fn.qtip.plugins.Corner(mimic);
mimic.precedance = corner.precedance;

if(mimic.x === 'inherit') { mimic.x = corner.x; }
else if(mimic.y === 'inherit') { mimic.y = corner.y; }
else if(mimic.x === mimic.y) {
mimic[ corner.precedance ] = corner[ corner.precedance ];
}
}

// Determine what type of rounding to use so we get pixel perfect precision!
round = Math[ /b|r/.test(mimic[ mimic.precedance === 'y' ? 'x' : 'y' ]) ? 'ceil' : 'floor' ];

// Find inner child of tip element
inner = tip.children();

// Create tip element
switch(method)
{
case 'canvas':
// Grab canvas context and clear it
context = inner.get(0).getContext('2d');
if(context.restore) { context.restore(); }
context.clearRect(0,0,3000,3000);

// Grab tip coordinates
coords = calculateTip(mimic.string(), width, height);

// Draw the canvas tip (Delayed til after DOM creation)
for(i; i < 2; i++) {
// Save and translate canvas origin
if(i) {
context.save();
context.translate(
round((mimic.x === 'left' ? 1 : mimic.x === 'right' ? -1 : 0) * (border + 1) * (mimic.precedance === 'y' ? 0.5 : 1)),
round((mimic.y === 'top' ? 1 : mimic.y === 'bottom' ? -1 : 0) * (border + 1) * (mimic.precedance === 'x' ? 0.5 : 1))
);
}

context.beginPath();
context.moveTo(coords[0][0], coords[0][1]);
context.lineTo(coords[1][0], coords[1][1]);
context.lineTo(coords[2][0], coords[2][1]);
context.closePath();
context.fillStyle = color[ i ? 'fill' : 'border' ];
context.fill();
}
break;

case 'vml':
// Determine tip coordinates based on dimensions
coords = calculateTip(mimic.string(), width, height);

// Create coordize and tip path using tip coordinates
path = 'm' + coords[0][0] + ',' + coords[0][1] + ' l' + coords[1][0] +
',' + coords[1][1] + ' ' + coords[2][0] + ',' + coords[2][1] + ' xe';

inner.attr({ 'path': path, 'fillcolor': color.fill });

if(border) {
inner.children().attr('color', color.border);

if(mimic.precedance === 'y') {
inner.css('top', (mimic.y === 'top' ? 1 : -1) * (border - 2));
inner.css('left', (mimic.x === 'left' ? 1 : -2));
}
else {
inner.css('left', (mimic.x === 'left' ? 1 : -1) * (border - 2));
inner.css('top', (mimic.y === 'top' ? 1 : -2));
}

}
break;

case 'polygon':
// Determine border translations
if(mimic.precedance === 'y') {
factor = width > height ? 1.5 : width < height ? 5 : 2.2;
translate = [
mimic.x === 'left' ? translate : mimic.x === 'right' ? -translate : 0,
Math.floor(factor * translate * (mimic.y === 'bottom' ? -1 : 1) * (mimic.x === 'center' ? 0.8 : 1))
];
}
else {
factor = width < height ? 1.5 : width > height ? 5 : 2.2;
translate = [
Math.floor(factor * translate * (mimic.x === 'right' ? -1 : 1) * (mimic.y === 'center' ? 0.9 : 1)),
mimic.y === 'top' ? translate : mimic.y === 'bottom' ? -translate : 0
];
}

inner.removeAttr('style').each(function(i) {
// Determine what border corners/colors to set
var toSet = {
x: mimic.precedance === 'x' ? (mimic.x === 'left' ? 'right' : 'left') : mimic.x,
y: mimic.precedance === 'y' ? (mimic.y === 'top' ? 'bottom' : 'top') : mimic.y
},
path = mimic.x === 'center' ? ['left', 'right', toSet.y, height, width] : ['top', 'bottom', toSet.x, width, height],
col = color[!i && border ? 'border' : 'fill'];

if(i) {
$(this).css({ 'position': 'absolute', 'z-index': 1, 'left': translate[0], 'top': translate[1] });
}

// Setup borders based on corner values
if(mimic.x === 'center' || mimic.y === 'center') {
$(this).css('border-' + path[2], path[3] + regular + col)
.css('border-' + path[0], Math.floor(path[4] / 2) + transparent)
.css('border-' + path[1], Math.floor(path[4] / 2) + transparent);
}
else {
$(this).css('border-width', Math.floor(height / 2) + 'px ' + Math.floor(width / 2) + 'px')
.css('border-' + toSet.x, Math.floor(width / 2) + regular + col)
.css('border-' + toSet.y, Math.floor(height / 2) + regular + col);
}
});
break;
}

// Update position
position(corner);

return self;
},

destroy: function()
{
// Remove previous tip if present
if(elems.tip) {
elems.tip.remove();
}

// Remove bound events
tooltip.unbind('.qtip-tip');
}
});
}

$.fn.qtip.plugins.tip = function(qTip)
{
var api = qTip.plugins.tip,
opts = qTip.options.style.tip;

// Make sure tip options are present
if(opts && opts.corner) {
// An API is already present,
if(api) {
return api;
}
// No API was found, create new instance
else {
qTip.plugins.tip = new Tip(qTip);
qTip.plugins.tip.init();

return qTip.plugins.tip;
}
}
};

// Initialize tip on render
$.fn.qtip.plugins.tip.initialize = 'render';

// Setup plugin sanitization options
$.fn.qtip.plugins.tip.sanitize = function(options)
{
var style = options.style, opts;
if(style && 'tip' in style) {
opts = options.style.tip;
if(typeof opts !== 'object'){ options.style.tip = { corner: opts }; }
if(!(/string|boolean/i).test(typeof opts.corner)) { opts.corner = true; }
if(typeof opts.method !== 'string'){ opts.method = TRUE; }
if(!(/canvas|polygon/i).test(opts.method)){ opts.method = TRUE; }
if(typeof opts.width !== 'number'){ delete opts.width; }
if(typeof opts.height !== 'number'){ delete opts.height; }
if(typeof opts.border !== 'number'){ delete opts.border; }
if(typeof opts.offset !== 'number'){ delete opts.offset; }
}
};

// Extend original qTip defaults
$.extend(TRUE, $.fn.qtip.defaults, {
style: {
tip: {
corner: TRUE,
mimic: FALSE,
method: TRUE,
width: 9,
height: 9,
border: 0,
offset: 0
}
}
});$.fn.qtip.plugins.imagemap = function(area, corner)
{
var shape = area.attr('shape').toLowerCase(),
baseCoords = area.attr('coords').split(','),
coords = [],
image = $('img[usemap="#'+area.parent('map').attr('name')+'"]'),
imageOffset = image.offset(),
result = {
width: 0, height: 0,
offset: { top: 1e10, right: 0, bottom: 0, left: 1e10 }
},
i = 0, next = 0;

// POLY area coordinate calculator
// Special thanks to Ed Cradock for helping out with this.
// Uses a binary search algorithm to find suitable coordinates.
function polyCoordinates(result, coords)
{
var i = 0,
compareX = 1, compareY = 1,
realX = 0, realY = 0,
newWidth = result.width,
newHeight = result.height;

// Use a binary search algorithm to locate most suitable coordinate (hopefully)
while(newWidth > 0 && newHeight > 0 && compareX > 0 && compareY > 0)
{
newWidth = Math.floor(newWidth / 2);
newHeight = Math.floor(newHeight / 2);

if(corner.x === 'left'){ compareX = newWidth; }
else if(corner.x === 'right'){ compareX = result.width - newWidth; }
else{ compareX += Math.floor(newWidth / 2); }

if(corner.y === 'top'){ compareY = newHeight; }
else if(corner.y === 'bottom'){ compareY = result.height - newHeight; }
else{ compareY += Math.floor(newHeight / 2); }

i = coords.length; while(i--)
{
if(coords.length < 2){ break; }

realX = coords[i][0] - result.offset.left;
realY = coords[i][1] - result.offset.top;

if((corner.x === 'left' && realX >= compareX) ||
(corner.x === 'right' && realX <= compareX) ||
(corner.x === 'center' && (realX < compareX || realX > (result.width - compareX))) ||
(corner.y === 'top' && realY >= compareY) ||
(corner.y === 'bottom' && realY <= compareY) ||
(corner.y === 'center' && (realY < compareY || realY > (result.height - compareY)))) {
coords.splice(i, 1);
}
}
}

return { left: coords[0][0], top: coords[0][1] };
}

// Make sure we account for padding and borders on the image
imageOffset.left += Math.ceil((image.outerWidth() - image.width()) / 2);
imageOffset.top += Math.ceil((image.outerHeight() - image.height()) / 2);

// Parse coordinates into proper array
if(shape === 'poly') {
i = baseCoords.length; while(i--)
{
next = [ parseInt(baseCoords[--i], 10), parseInt(baseCoords[i+1], 10) ];

if(next[0] > result.offset.right){ result.offset.right = next[0]; }
if(next[0] < result.offset.left){ result.offset.left = next[0]; }
if(next[1] > result.offset.bottom){ result.offset.bottom = next[1]; }
if(next[1] < result.offset.top){ result.offset.top = next[1]; }

coords.push(next);
}
}
else {
coords = $.map(baseCoords, function(coord){ return parseInt(coord, 10); });
}

// Calculate details
switch(shape)
{
case 'rect':
result = {
width: Math.abs(coords[2] - coords[0]),
height: Math.abs(coords[3] - coords[1]),
offset: { left: coords[0], top: coords[1] }
};
break;

case 'circle':
result = {
width: coords[2] + 2,
height: coords[2] + 2,
offset: { left: coords[0], top: coords[1] }
};
break;

case 'poly':
$.extend(result, {
width: Math.abs(result.offset.right - result.offset.left),
height: Math.abs(result.offset.bottom - result.offset.top)
});

if(corner.string() === 'centercenter') {
result.offset = {
left: result.offset.left + (result.width / 2),
top: result.offset.top + (result.height / 2)
};
}
else {
result.offset = polyCoordinates(result, coords.slice());
}

result.width = result.height = 0;
break;
}

// Add image position to offset coordinates
result.offset.left += imageOffset.left;
result.offset.top += imageOffset.top;

return result;
};

function Modal(qTip, options)
{
var self = this,
elems = qTip.elements,
tooltip = elems.tooltip,
namespace = '.qtipmodal',
events = 'tooltipshow'+namespace+' tooltiphide'+namespace;

// See if overlay is already present
elems.overlay = $('#qtip-overlay');

$.extend(self, {
init: function()
{
// Check if the tooltip is modal
tooltip.bind(events, function(event, api, duration) {
var type = event.type.replace('tooltip', '');

if($.isFunction(options[type])) {
options[type].call(elems.overlay, duration, api);
}
else {
self[type](duration);
}
});

// Create the overlay if needed
if(!elems.overlay.length) {
self.create();
}

// Hide tooltip on overlay click if enabled
if(options.blur === TRUE) {
elems.overlay.bind('click'+namespace+qTip.id, function(){ qTip.hide.call(qTip); });
}
},

create: function()
{
// Create document overlay
elems.overlay = $('<div />', {
id: 'qtip-overlay',
css: {
position: 'absolute',
top: 0,
left: 0,
display: 'none'
}
})
.appendTo(document.body);

// Update position on window resize or scroll
$(window).bind('resize'+namespace, function() {
elems.overlay.css({
height: Math.max( $(window).height(), $(document).height() ),
width: Math.max( $(window).width(), $(document).width() )
});
})
.trigger('resize');
},

toggle: function(state)
{
var overlay = elems.overlay,
effect = qTip.options.show.modal.effect,
type = state ? 'show': 'hide';

// Setop all animations
overlay.stop(TRUE, FALSE);

// Use custom function if provided
if($.isFunction(effect)) {
effect.call(overlay, state);
}

// If no effect type is supplied, use a simple toggle
else if(effect === FALSE) {
overlay[ type ]();
}

// Use basic fade function
else {
overlay.fadeTo(90, state ? 0.7 : 0, function() {
if(!state) { $(this).hide(); }
});
}
},

show: function() { self.toggle(TRUE); },
hide: function() { self.toggle(FALSE); },

destroy: function()
{
var delBlanket = TRUE;

// Check if any other modal tooltips are present
$('*').each(function() {
var api = $(this).data('qtip');
if(api && api.id !== qTip.id && api.options.show.modal) {
// Another modal tooltip was present, leave overlay
delBlanket = FALSE;
return FALSE;
}
});

// Remove overlay if needed
if(delBlanket) {
elems.overlay.remove();
$(window).unbind('scroll'+namespace+' resize'+namespace);
}
else {
elems.overlay.unbind('click'+namespace+qTip.id);
}

// Remove bound events
tooltip.unbind(events);
}
});

self.init();
}

$.fn.qtip.plugins.modal = function(qTip)
{
var api = qTip.plugins.modal,
opts = qTip.options.show.modal;

// An API is already present,
if(api) {
return api;
}
// No API was found, create new instance
else if(opts && opts.on === TRUE) {
qTip.plugins.modal = new Modal(qTip, opts);
return qTip.plugins.modal;
}
};

// Plugin needs to be initialized on render
$.fn.qtip.plugins.modal.initialize = 'render';

// Setup sanitiztion rules
$.fn.qtip.plugins.modal.sanitize = function(opts) {
if(opts.show) {
if(typeof opts.show.modal !== 'object') { opts.show.modal = { on: !!opts.show.modal }; }
else if(typeof opts.show.modal.on === 'undefined') { opts.show.modal.on = TRUE; }
}
};

// Extend original qTip defaults
$.extend(TRUE, $.fn.qtip.defaults, {
show: {
modal: {
on: FALSE,
effect: TRUE,
blur: TRUE
}
}
});/* BGIFrame adaption (http://plugins.jquery.com/project/bgiframe) - Special thanks to Brandon Aaron */
function BGIFrame(qTip)
{
var self = this,
elems = qTip.elements,
tooltip = elems.tooltip,
namespace = '.bgiframe-' + qTip.id,
events = 'tooltipmove'+namespace+' tooltipshow'+namespace;

$.extend(self, {
init: function()
{
// Create the BGIFrame element
elems.bgiframe = $('<iframe class="ui-tooltip-bgiframe" frameborder="0" tabindex="-1" src="javascript:\'\';" ' +
' style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=0);"></iframe>');

// Append the new element to the tooltip
elems.bgiframe.appendTo(tooltip);

// Update BGIFrame on tooltip move
tooltip.bind(events, self.adjust);
},

adjust: function()
{
var dimensions = qTip.get('dimensions'), // Determine current tooltip dimensions
plugin = qTip.plugins.tip,
tip = qTip.elements.tip,
tipAdjust, offset;

// Adjust border offset
offset = parseInt(tooltip.css('border-left-width'), 10) || 0;
offset = { left: -offset, top: -offset };

// Adjust for tips plugin
if(plugin && tip) {
tipAdjust = (plugin.corner.precedance === 'x') ? ['width', 'left'] : ['height', 'top'];
offset[ tipAdjust[1] ] -= tip[ tipAdjust[0] ]();
}

// Update bgiframe
elems.bgiframe.css(offset).css(dimensions);
},

destroy: function()
{
// Remove iframe
self.iframe.remove();

// Remove bound events
tooltip.unbind(events);
}
});

self.init();
}

$.fn.qtip.plugins.bgiframe = function(qTip)
{
// Proceed only if the browser is IE6 and offending elements are present
if(!($.browser.msie && (/^6\.[0-9]/).test($.browser.version) && $('select, object').length)) {
return FALSE;
}

// Retrieve previous API object
var api = qTip.plugins.bgiframe;

// An API is already present,
if(api) {
return api;
}
// No API was found, create new instance
else {
qTip.plugins.bgiframe = new BGIFrame(qTip);
return qTip.plugins.bgiframe;
}
};

// Plugin needs to be initialized on render
$.fn.qtip.plugins.bgiframe.initialize = 'render';

}(jQuery, window));;
// $Id: qtip.js,v 1.4 2010/12/15 22:56:58 bocaj Exp $
(function ($) {
Drupal.behaviors.qtip = {
  attach: function(context) {

    // Set delay on click to immediate
    if (Drupal.settings.qtip.show_event_type == 'click') {
      show_delay = 1;
    }
    else {
      show_delay = 140; // This is the default qTip value, set for hover links
    }

    // Determine how to position the tooltip
    if (Drupal.settings.qtip.show_speech_bubble_tip) {
      // Set the proper qtip speech-bubble tip position
      if (Drupal.settings.qtip.show_speech_bubble_tip_side) {
        switch_position = Drupal.settings.qtip.tooltip_position.split('_');
        // We do not want to put tooltip on it's side if it is being displayed
        // in the center or side of an element
        if (switch_position[1] == 'center') {
          tip_position = Drupal.settings.qtip.tooltip_position;
        }
        else {
          tip_position = switch_position[1] + ' ' + switch_position[0];
        }
      }
      // Otherwise just set it to the same value as the tooltip
      else {
        tip_position = Drupal.settings.qtip.tooltip_position;
      }
    }
    else {
      tip_position = false;
    }
    
    // Is a custom style declared by the admin?
    if(Drupal.settings.qtip.color == 'custom-color') {
      Drupal.settings.qtip.color = Drupal.settings.qtip.custom_color;
    }

    // Do we want a shadow to show under the tooltip?
    if(Drupal.settings.qtip.show_shadow) {
      style_classes = 'ui-tooltip-shadow ' + Drupal.settings.qtip.color;
    }
    else {
      style_classes = Drupal.settings.qtip.color;
    }
    
    // Do we want to show the tooltips with rounded corners?
    if(Drupal.settings.qtip.rounded_corners) {
      style_classes += ' ui-tooltip-rounded';
    }
    
    //Do we want a solid tip to display
    if (Drupal.settings.qtip.show_speech_bubble_tip_solid) {
      solid_tip = false;
    }
    else {
      solid_tip = 5;
    }

/*** Standard Settings ***/
    $('.qtip-link').each(function() {
      if(Drupal.settings.qtip.show_event_type == 'click') {
        $(this).addClass('ui-tooltip-click');
      }
      
      // if there is a title associated with this qtip...
      if ($(this).children('.qtip-header').length) {
        tooltip_title = $(this).children('.qtip-header').html();
      }
      // if there isn't we don't want a blank title area to show on the qtip...
      else {
        tooltip_title = false;
      }
      
      build_qtip(this, 'node');
    });
    
/*** Additional Elements ***/
    if(Drupal.settings.qtip.additional_elements) {
      $(Drupal.settings.qtip.additional_elements).each(function() {
        $(this).addClass('qtip-additional-element');
        if(Drupal.settings.qtip.show_event_type == 'click') {
          $(this).addClass('ui-tooltip-click');
        }
        
        // if there is a title associated with this qtip...
        if ($(this).children('.qtip-header').length) {
          tooltip_title = $(this).children('.qtip-header').html();
        }
        // if there isn't we don't want a blank title area to show on the qtip...
        else {
          tooltip_title = false;
        }
        
        build_qtip(this, 'node');
      });
    }

/*** Webform Settings ***/
    // Does the admin even want the descriptions to show up in a tooltip?
    if (Drupal.settings.qtip.show_webform_descriptions) {
      /*
       form-text - works well
       form-textarea - works, but width can throw off the tooltip
       form-radios - works, but the radios element wrapper is 100% width, so throws off tooltip like form-textarea
       form-select - works well - should maybe have something like mouseenter or something for usability
      */
      // Elements where description is a sibling to the selected element
      $('form.webform-client-form .form-text,' +
        'form.webform-client-form .form-select').each(function() {
        description = $(this).siblings('.description');
        description.css('display', 'none');
        tooltip_title = false;
        show_delay = 1;
        build_qtip(this, 'form', description.html());
      });
  
      // Elements where description is a sibling to the PARENT of the selected element
      $('form.webform-client-form .form-radios,' +
        'form.webform-client-form .form-textarea').each(function() {
        description = $(this).parent().siblings('.description');
        description.css('display', 'none');
        tooltip_title = false;
        show_delay = 1;
        
        build_qtip(this, 'form', description.html());
      });
    }
    
    
    
    function build_qtip(el, type, desc) {
      if (type == 'form') {
        show_text = desc;
        // By default, the description text is wrapped inside <p>
        // Since we are putting this in a tooltip we want to remove this
        // and any other tags that might possibly get set
        show_text = show_text.replace(/(<.*?>)/ig,"");
        set_my = 'left_center';
        tip_position = 'left_center';
        set_at = 'right_center';
        show_event = 'focus';
        hide_event = 'blur';
      }
      else { // "Normal" tooltip
        show_text = $(el).children('.qtip-tooltip');
        set_my = Drupal.settings.qtip.tooltip_position;
        set_at = Drupal.settings.qtip.target_position;
        show_event = Drupal.settings.qtip.show_event_type;
        hide_event = Drupal.settings.qtip.hide_event_type;
      }
      $(el).qtip({
        content: {
          text: show_text,
          title: {
            text: tooltip_title
          }
        },
        position: {
          my: set_my, // my = speech bubble position on tooltip
          at: set_at, // at = where on link text tooltip will appear
          adjust: {
            screen: true // Keeps tooltip within visible window
          }
        },
        style: {
          classes: style_classes,
          tip: {
            corner: tip_position, // Position of speech bubble tip...false will not display tip
            border: solid_tip, // parseInt(Drupal.settings.qtip.border_width)
            width: parseInt(Drupal.settings.qtip.speech_bubble_size),
            height: parseInt(Drupal.settings.qtip.speech_bubble_size)
          }
        },
        show: {
          event: show_event,
          solo: true, // Determines whether or not the tooltip will hide all others when the show.event is triggered on the show.target. 
          delay: show_delay
        },
        hide: {
          event: hide_event,
          fixed: true //When set to true, the tooltip will not hide if moused over, allowing the contents to be clicked and interacted with.
        }
      });
    }
  }
};
})(jQuery);;
(function ($) {
  Drupal.viewsSlideshow = Drupal.viewsSlideshow || {};
  
  Drupal.behaviors.viewsSlideshowControlsText = {
    attach: function (context) {
  
      // Process previous link
      $('.views_slideshow_controls_text_previous:not(.views-slideshow-controls-text-previous-processed)', context).addClass('views-slideshow-controls-text-previous-processed').each(function() {
        var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_previous_', '');
        $(this).click(function() {
          Drupal.viewsSlideshow.action({ "action": 'previousSlide', "slideshowID": uniqueID });
          return false;
        });
      });
      
      // Process next link
      $('.views_slideshow_controls_text_next:not(.views-slideshow-controls-text-next-processed)', context).addClass('views-slideshow-controls-text-next-processed').each(function() {
        var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_next_', '');
        $(this).click(function() {
          Drupal.viewsSlideshow.action({ "action": 'nextSlide', "slideshowID": uniqueID });
          return false;
        });
      });
      
      // Process pause link
      $('.views_slideshow_controls_text_pause:not(.views-slideshow-controls-text-pause-processed)', context).addClass('views-slideshow-controls-text-pause-processed').each(function() {
        var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_pause_', '');
        $(this).click(function() {
          if (Drupal.settings.viewsSlideshow[uniqueID].paused) {
            Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": uniqueID });
          }
          else {
            Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": uniqueID });
          }
          return false;
        });
      });
    }
  };
  
  Drupal.viewsSlideshowControlsText = Drupal.viewsSlideshowControlsText || {};

  /**
   * Implement hook_viewsSlideshowPause for text controls.
   */
  Drupal.viewsSlideshowControlsText.pause = function (options) {
    var pauseText = Drupal.theme.prototype['viewsSlideshowControlsPause'] ? Drupal.theme('viewsSlideshowControlsPause') : '';
    $('#views_slideshow_controls_text_pause_' + options.slideshowID).text(pauseText);
  }
  
  /**
   * Implement hook_viewsSlideshowPlay for text controls.
   */
  Drupal.viewsSlideshowControlsText.play = function (options) {
    var playText = Drupal.theme.prototype['viewsSlideshowControlsPlay'] ? Drupal.theme('viewsSlideshowControlsPlay') : '';
    $('#views_slideshow_controls_text_pause_' + options.slideshowID).text(playText);
  }
  
  // Theme control pause.
  Drupal.theme.prototype.viewsSlideshowControlsPause = function () {
    return Drupal.t('Resume');
  }
  
  // Theme control pause.
  Drupal.theme.prototype.viewsSlideshowControlsPlay = function () {
    return Drupal.t('Pause');
  }
  
  Drupal.behaviors.viewsSlideshowPagerFields = {
    attach: function (context) {
      // Process pause on hover.
      $('.views_slideshow_pager_field:not(.views-slideshow-pager-field-processed)', context).addClass('views-slideshow-pager-field-processed').each(function() {
        // Parse out the location and unique id from the full id.
        var pagerInfo = $(this).attr('id').split('_');
        var location = pagerInfo[2];
        pagerInfo.splice(0, 3);
        var uniqueID = pagerInfo.join('_');
        
        // Add the activate and pause on pager hover event to each pager item.
        if (Drupal.settings.viewsSlideshowPagerFields[uniqueID][location].activatePauseOnHover) {
          $(this).children().each(function(index, pagerItem) {
            $(pagerItem).hover(function() {
              Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index });
              Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": uniqueID });
            },
            function() {
              Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": uniqueID });
            });
          });
        }
        else {
          $(this).children().each(function(index, pagerItem) {
            $(pagerItem).click(function() {
              Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index });
            });
          });
        }
      });
    }
  };
  
  Drupal.viewsSlideshowPagerFields = Drupal.viewsSlideshowPagerFields || {};
  
  /**
   * Implement hook_viewsSlidshowTransitionBegin for pager fields pager.
   */
  Drupal.viewsSlideshowPagerFields.transitionBegin = function (options) {
    // Remove active class from pagers
    $('[id^="views_slideshow_pager_field_item_' + options.slideshowID + '"]').removeClass('active');
    
    // Add active class to active pager.
    $('#views_slideshow_pager_field_item_' + options.slideshowID + '_' + options.slideNum).addClass('active');
  }
  
  Drupal.viewsSlideshowSlideCounter = Drupal.viewsSlideshowSlideCounter || {};
  
  /**
   * Implement hook_viewsSlidshowTransitionBegin for pager fields pager.
   */
  Drupal.viewsSlideshowSlideCounter.transitionBegin = function (options) {
    $('#views_slideshow_slide_counter_' + options.slideshowID + ' .num').text(options.slideNum + 1);
  }
  
  /**
   * This is used as a router to process actions for the slideshow.
   */
  Drupal.viewsSlideshow.action = function (options) {
    // Set default values for our return status.
    var status = {
      'value': true,
      'text': ''
    }

    // If an action isn't specified return false.
    if (typeof options.action == 'undefined' || options.action == '') {
      status.value = false;
      status.text =  Drupal.t('There was no action specified.');
      return error;
    }
    
    // If we are using pause or play switch paused state accordingly.
    if (options.action == 'pause') {
      Drupal.settings.viewsSlideshow[options.slideshowID].paused = 1;
    }
    else if (options.action == 'play') {
      Drupal.settings.viewsSlideshow[options.slideshowID].paused = 0;
    }
    
    // We use a switch statement here mainly just to limit the type of actions
    // that are available.
    switch (options.action) {
      case "goToSlide":
      case "transitionBegin":
      case "transitionEnd":
        // The three methods above require a slide number. Checking if it is
        // defined and it is a number that is an integer.
        if (typeof options.slideNum == 'undefined' || typeof options.slideNum !== 'number' || parseInt(options.slideNum) != (options.slideNum - 0)) {
          status.value = false;
          status.text = Drupal.t('An invalid integer was specified for slideNum.');
        }
      case "pause":
      case "play":
      case "nextSlide":
      case "previousSlide":
        // Grab our list of methods.
        var methods = Drupal.settings.viewsSlideshow[options.slideshowID]['methods'];
        
        // if the calling method specified methods that shouldn't be called then
        // exclude calling them.
        var excludeMethodsObj = {};
        if (typeof options.excludeMethods !== 'undefined') {
          // We need to turn the excludeMethods array into an object so we can use the in
          // function.
          for (var i=0; i < excludeMethods.length; i++) {
            excludeMethodsObj[excludeMethods[i]] = '';
          }
        }
        
        // Call every registered method and don't call excluded ones.
        for (i = 0; i < methods[options.action].length; i++) {
          if (Drupal[methods[options.action][i]] != undefined && typeof Drupal[methods[options.action][i]][options.action] == 'function' && !(methods[options.action][i] in excludeMethodsObj)) {
            Drupal[methods[options.action][i]][options.action](options);
          }
        }
        break;
      
      // If it gets here it's because it's an invalid action. 
      default:
        status.value = false;
        status.text = Drupal.t('An invalid action "!action" was specified.', { "!action": options.action });
    }
    return status;
  }
})(jQuery);
;
/*!
 * jQuery Cycle Plugin (with Transition Definitions)
 * Examples and documentation at: http://jquery.malsup.com/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version: 2.9995 (09-AUG-2011)
 * Dual licensed under the MIT and GPL licenses.
 * http://jquery.malsup.com/license.html
 * Requires: jQuery v1.3.2 or later
 */
;(function($) {

var ver = '2.9995';

// if $.support is not defined (pre jQuery 1.3) add what I need
if ($.support == undefined) {
	$.support = {
		opacity: !($.browser.msie)
	};
}

function debug(s) {
	$.fn.cycle.debug && log(s);
}		
function log() {
	window.console && console.log && console.log('[cycle] ' + Array.prototype.join.call(arguments,' '));
}
$.expr[':'].paused = function(el) {
	return el.cyclePause;
}


// the options arg can be...
//   a number  - indicates an immediate transition should occur to the given slide index
//   a string  - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc)
//   an object - properties to control the slideshow
//
// the arg2 arg can be...
//   the name of an fx (only used in conjunction with a numeric value for 'options')
//   the value true (only used in first arg == 'resume') and indicates
//	 that the resume should occur immediately (not wait for next timeout)

$.fn.cycle = function(options, arg2) {
	var o = { s: this.selector, c: this.context };

	// in 1.3+ we can fix mistakes with the ready state
	if (this.length === 0 && options != 'stop') {
		if (!$.isReady && o.s) {
			log('DOM not ready, queuing slideshow');
			$(function() {
				$(o.s,o.c).cycle(options,arg2);
			});
			return this;
		}
		// is your DOM ready?  http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
		log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
		return this;
	}

	// iterate the matched nodeset
	return this.each(function() {
		var opts = handleArguments(this, options, arg2);
		if (opts === false)
			return;

		opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink;
		
		// stop existing slideshow for this container (if there is one)
		if (this.cycleTimeout)
			clearTimeout(this.cycleTimeout);
		this.cycleTimeout = this.cyclePause = 0;

		var $cont = $(this);
		var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children();
		var els = $slides.get();

		var opts2 = buildOptions($cont, $slides, els, opts, o);
		if (opts2 === false)
			return;

		if (els.length < 2) {
			log('terminating; too few slides: ' + els.length);
			return;
		}

		var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards);

		// if it's an auto slideshow, kick it off
		if (startTime) {
			startTime += (opts2.delay || 0);
			if (startTime < 10)
				startTime = 10;
			debug('first timeout: ' + startTime);
			this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards)}, startTime);
		}
	});
};

function triggerPause(cont, byHover, onPager) {
	var opts = $(cont).data('cycle.opts');
	var paused = !!cont.cyclePause;
	if (paused && opts.paused)
		opts.paused(cont, opts, byHover, onPager);
	else if (!paused && opts.resumed)
		opts.resumed(cont, opts, byHover, onPager);
}

// process the args that were passed to the plugin fn
function handleArguments(cont, options, arg2) {
	if (cont.cycleStop == undefined)
		cont.cycleStop = 0;
	if (options === undefined || options === null)
		options = {};
	if (options.constructor == String) {
		switch(options) {
		case 'destroy':
		case 'stop':
			var opts = $(cont).data('cycle.opts');
			if (!opts)
				return false;
			cont.cycleStop++; // callbacks look for change
			if (cont.cycleTimeout)
				clearTimeout(cont.cycleTimeout);
			cont.cycleTimeout = 0;
			opts.elements && $(opts.elements).stop();
			$(cont).removeData('cycle.opts');
			if (options == 'destroy')
				destroy(opts);
			return false;
		case 'toggle':
			cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1;
			checkInstantResume(cont.cyclePause, arg2, cont);
			triggerPause(cont);
			return false;
		case 'pause':
			cont.cyclePause = 1;
			triggerPause(cont);
			return false;
		case 'resume':
			cont.cyclePause = 0;
			checkInstantResume(false, arg2, cont);
			triggerPause(cont);
			return false;
		case 'prev':
		case 'next':
			var opts = $(cont).data('cycle.opts');
			if (!opts) {
				log('options not found, "prev/next" ignored');
				return false;
			}
			$.fn.cycle[options](opts);
			return false;
		default:
			options = { fx: options };
		};
		return options;
	}
	else if (options.constructor == Number) {
		// go to the requested slide
		var num = options;
		options = $(cont).data('cycle.opts');
		if (!options) {
			log('options not found, can not advance slide');
			return false;
		}
		if (num < 0 || num >= options.elements.length) {
			log('invalid slide index: ' + num);
			return false;
		}
		options.nextSlide = num;
		if (cont.cycleTimeout) {
			clearTimeout(cont.cycleTimeout);
			cont.cycleTimeout = 0;
		}
		if (typeof arg2 == 'string')
			options.oneTimeFx = arg2;
		go(options.elements, options, 1, num >= options.currSlide);
		return false;
	}
	return options;
	
	function checkInstantResume(isPaused, arg2, cont) {
		if (!isPaused && arg2 === true) { // resume now!
			var options = $(cont).data('cycle.opts');
			if (!options) {
				log('options not found, can not resume');
				return false;
			}
			if (cont.cycleTimeout) {
				clearTimeout(cont.cycleTimeout);
				cont.cycleTimeout = 0;
			}
			go(options.elements, options, 1, !options.backwards);
		}
	}
};

function removeFilter(el, opts) {
	if (!$.support.opacity && opts.cleartype && el.style.filter) {
		try { el.style.removeAttribute('filter'); }
		catch(smother) {} // handle old opera versions
	}
};

// unbind event handlers
function destroy(opts) {
	if (opts.next)
		$(opts.next).unbind(opts.prevNextEvent);
	if (opts.prev)
		$(opts.prev).unbind(opts.prevNextEvent);
	
	if (opts.pager || opts.pagerAnchorBuilder)
		$.each(opts.pagerAnchors || [], function() {
			this.unbind().remove();
		});
	opts.pagerAnchors = null;
	if (opts.destroy) // callback
		opts.destroy(opts);
};

// one-time initialization
function buildOptions($cont, $slides, els, options, o) {
	// support metadata plugin (v1.0 and v2.0)
	var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
	var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null;
	if (meta)
		opts = $.extend(opts, meta);
	if (opts.autostop)
		opts.countdown = opts.autostopCount || els.length;

	var cont = $cont[0];
	$cont.data('cycle.opts', opts);
	opts.$cont = $cont;
	opts.stopCount = cont.cycleStop;
	opts.elements = els;
	opts.before = opts.before ? [opts.before] : [];
	opts.after = opts.after ? [opts.after] : [];

	// push some after callbacks
	if (!$.support.opacity && opts.cleartype)
		opts.after.push(function() { removeFilter(this, opts); });
	if (opts.continuous)
		opts.after.push(function() { go(els,opts,0,!opts.backwards); });

	saveOriginalOpts(opts);

	// clearType corrections
	if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
		clearTypeFix($slides);

	// container requires non-static position so that slides can be position within
	if ($cont.css('position') == 'static')
		$cont.css('position', 'relative');
	if (opts.width)
		$cont.width(opts.width);
	if (opts.height && opts.height != 'auto')
		$cont.height(opts.height);

	if (opts.startingSlide)
		opts.startingSlide = parseInt(opts.startingSlide,10);
	else if (opts.backwards)
		opts.startingSlide = els.length - 1;

	// if random, mix up the slide array
	if (opts.random) {
		opts.randomMap = [];
		for (var i = 0; i < els.length; i++)
			opts.randomMap.push(i);
		opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
		opts.randomIndex = 1;
		opts.startingSlide = opts.randomMap[1];
	}
	else if (opts.startingSlide >= els.length)
		opts.startingSlide = 0; // catch bogus input
	opts.currSlide = opts.startingSlide || 0;
	var first = opts.startingSlide;

	// set position and zIndex on all the slides
	$slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) {
		var z;
		if (opts.backwards)
			z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i;
		else
			z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i;
		$(this).css('z-index', z)
	});

	// make sure first slide is visible
	$(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case
	removeFilter(els[first], opts);

	// stretch slides
	if (opts.fit) {
		if (!opts.aspect) {
	        if (opts.width)
	            $slides.width(opts.width);
	        if (opts.height && opts.height != 'auto')
	            $slides.height(opts.height);
		} else {
			$slides.each(function(){
				var $slide = $(this);
				var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect;
				if( opts.width && $slide.width() != opts.width ) {
					$slide.width( opts.width );
					$slide.height( opts.width / ratio );
				}

				if( opts.height && $slide.height() < opts.height ) {
					$slide.height( opts.height );
					$slide.width( opts.height * ratio );
				}
			});
		}
	}

	if (opts.center && ((!opts.fit) || opts.aspect)) {
		$slides.each(function(){
			var $slide = $(this);
			$slide.css({
				"margin-left": opts.width ?
					((opts.width - $slide.width()) / 2) + "px" :
					0,
				"margin-top": opts.height ?
					((opts.height - $slide.height()) / 2) + "px" :
					0
			});
		});
	}

	if (opts.center && !opts.fit && !opts.slideResize) {
	  	$slides.each(function(){
	    	var $slide = $(this);
	    	$slide.css({
	      		"margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0,
	      		"margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0
	    	});
	  	});
	}
		
	// stretch container
	var reshape = opts.containerResize && !$cont.innerHeight();
	if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9
		var maxw = 0, maxh = 0;
		for(var j=0; j < els.length; j++) {
			var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight();
			if (!w) w = e.offsetWidth || e.width || $e.attr('width');
			if (!h) h = e.offsetHeight || e.height || $e.attr('height');
			maxw = w > maxw ? w : maxw;
			maxh = h > maxh ? h : maxh;
		}
		if (maxw > 0 && maxh > 0)
			$cont.css({width:maxw+'px',height:maxh+'px'});
	}

	var pauseFlag = false;  // https://github.com/malsup/cycle/issues/44
	if (opts.pause)
		$cont.hover(
			function(){
				pauseFlag = true;
				this.cyclePause++;
				triggerPause(cont, true);
			},
			function(){
				pauseFlag && this.cyclePause--;
				triggerPause(cont, true);
			}
		);

	if (supportMultiTransitions(opts) === false)
		return false;

	// apparently a lot of people use image slideshows without height/width attributes on the images.
	// Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that.
	var requeue = false;
	options.requeueAttempts = options.requeueAttempts || 0;
	$slides.each(function() {
		// try to get height/width of each slide
		var $el = $(this);
		this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0);
		this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0);

		if ( $el.is('img') ) {
			// sigh..  sniffing, hacking, shrugging...  this crappy hack tries to account for what browsers do when
			// an image is being downloaded and the markup did not include sizing info (height/width attributes);
			// there seems to be some "default" sizes used in this situation
			var loadingIE	= ($.browser.msie  && this.cycleW == 28 && this.cycleH == 30 && !this.complete);
			var loadingFF	= ($.browser.mozilla && this.cycleW == 34 && this.cycleH == 19 && !this.complete);
			var loadingOp	= ($.browser.opera && ((this.cycleW == 42 && this.cycleH == 19) || (this.cycleW == 37 && this.cycleH == 17)) && !this.complete);
			var loadingOther = (this.cycleH == 0 && this.cycleW == 0 && !this.complete);
			// don't requeue for images that are still loading but have a valid size
			if (loadingIE || loadingFF || loadingOp || loadingOther) {
				if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever
					log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH);
					setTimeout(function() {$(o.s,o.c).cycle(options)}, opts.requeueTimeout);
					requeue = true;
					return false; // break each loop
				}
				else {
					log('could not determine size of image: '+this.src, this.cycleW, this.cycleH);
				}
			}
		}
		return true;
	});

	if (requeue)
		return false;

	opts.cssBefore = opts.cssBefore || {};
	opts.cssAfter = opts.cssAfter || {};
	opts.cssFirst = opts.cssFirst || {};
	opts.animIn = opts.animIn || {};
	opts.animOut = opts.animOut || {};

	$slides.not(':eq('+first+')').css(opts.cssBefore);
	$($slides[first]).css(opts.cssFirst);

	if (opts.timeout) {
		opts.timeout = parseInt(opts.timeout,10);
		// ensure that timeout and speed settings are sane
		if (opts.speed.constructor == String)
			opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10);
		if (!opts.sync)
			opts.speed = opts.speed / 2;
		
		var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250;
		while((opts.timeout - opts.speed) < buffer) // sanitize timeout
			opts.timeout += opts.speed;
	}
	if (opts.easing)
		opts.easeIn = opts.easeOut = opts.easing;
	if (!opts.speedIn)
		opts.speedIn = opts.speed;
	if (!opts.speedOut)
		opts.speedOut = opts.speed;

	opts.slideCount = els.length;
	opts.currSlide = opts.lastSlide = first;
	if (opts.random) {
		if (++opts.randomIndex == els.length)
			opts.randomIndex = 0;
		opts.nextSlide = opts.randomMap[opts.randomIndex];
	}
	else if (opts.backwards)
		opts.nextSlide = opts.startingSlide == 0 ? (els.length-1) : opts.startingSlide-1;
	else
		opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1;

	// run transition init fn
	if (!opts.multiFx) {
		var init = $.fn.cycle.transitions[opts.fx];
		if ($.isFunction(init))
			init($cont, $slides, opts);
		else if (opts.fx != 'custom' && !opts.multiFx) {
			log('unknown transition: ' + opts.fx,'; slideshow terminating');
			return false;
		}
	}

	// fire artificial events
	var e0 = $slides[first];
	if (!opts.skipInitializationCallbacks) {
		if (opts.before.length)
			opts.before[0].apply(e0, [e0, e0, opts, true]);
		if (opts.after.length)
			opts.after[0].apply(e0, [e0, e0, opts, true]);
	}
	if (opts.next)
		$(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1)});
	if (opts.prev)
		$(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0)});
	if (opts.pager || opts.pagerAnchorBuilder)
		buildPager(els,opts);

	exposeAddSlide(opts, els);

	return opts;
};

// save off original opts so we can restore after clearing state
function saveOriginalOpts(opts) {
	opts.original = { before: [], after: [] };
	opts.original.cssBefore = $.extend({}, opts.cssBefore);
	opts.original.cssAfter  = $.extend({}, opts.cssAfter);
	opts.original.animIn	= $.extend({}, opts.animIn);
	opts.original.animOut   = $.extend({}, opts.animOut);
	$.each(opts.before, function() { opts.original.before.push(this); });
	$.each(opts.after,  function() { opts.original.after.push(this); });
};

function supportMultiTransitions(opts) {
	var i, tx, txs = $.fn.cycle.transitions;
	// look for multiple effects
	if (opts.fx.indexOf(',') > 0) {
		opts.multiFx = true;
		opts.fxs = opts.fx.replace(/\s*/g,'').split(',');
		// discard any bogus effect names
		for (i=0; i < opts.fxs.length; i++) {
			var fx = opts.fxs[i];
			tx = txs[fx];
			if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) {
				log('discarding unknown transition: ',fx);
				opts.fxs.splice(i,1);
				i--;
			}
		}
		// if we have an empty list then we threw everything away!
		if (!opts.fxs.length) {
			log('No valid transitions named; slideshow terminating.');
			return false;
		}
	}
	else if (opts.fx == 'all') {  // auto-gen the list of transitions
		opts.multiFx = true;
		opts.fxs = [];
		for (p in txs) {
			tx = txs[p];
			if (txs.hasOwnProperty(p) && $.isFunction(tx))
				opts.fxs.push(p);
		}
	}
	if (opts.multiFx && opts.randomizeEffects) {
		// munge the fxs array to make effect selection random
		var r1 = Math.floor(Math.random() * 20) + 30;
		for (i = 0; i < r1; i++) {
			var r2 = Math.floor(Math.random() * opts.fxs.length);
			opts.fxs.push(opts.fxs.splice(r2,1)[0]);
		}
		debug('randomized fx sequence: ',opts.fxs);
	}
	return true;
};

// provide a mechanism for adding slides after the slideshow has started
function exposeAddSlide(opts, els) {
	opts.addSlide = function(newSlide, prepend) {
		var $s = $(newSlide), s = $s[0];
		if (!opts.autostopCount)
			opts.countdown++;
		els[prepend?'unshift':'push'](s);
		if (opts.els)
			opts.els[prepend?'unshift':'push'](s); // shuffle needs this
		opts.slideCount = els.length;

		$s.css('position','absolute');
		$s[prepend?'prependTo':'appendTo'](opts.$cont);

		if (prepend) {
			opts.currSlide++;
			opts.nextSlide++;
		}

		if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
			clearTypeFix($s);

		if (opts.fit && opts.width)
			$s.width(opts.width);
		if (opts.fit && opts.height && opts.height != 'auto')
			$s.height(opts.height);
		s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height();
		s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width();

		$s.css(opts.cssBefore);

		if (opts.pager || opts.pagerAnchorBuilder)
			$.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts);

		if ($.isFunction(opts.onAddSlide))
			opts.onAddSlide($s);
		else
			$s.hide(); // default behavior
	};
}

// reset internal state; we do this on every pass in order to support multiple effects
$.fn.cycle.resetState = function(opts, fx) {
	fx = fx || opts.fx;
	opts.before = []; opts.after = [];
	opts.cssBefore = $.extend({}, opts.original.cssBefore);
	opts.cssAfter  = $.extend({}, opts.original.cssAfter);
	opts.animIn	= $.extend({}, opts.original.animIn);
	opts.animOut   = $.extend({}, opts.original.animOut);
	opts.fxFn = null;
	$.each(opts.original.before, function() { opts.before.push(this); });
	$.each(opts.original.after,  function() { opts.after.push(this); });

	// re-init
	var init = $.fn.cycle.transitions[fx];
	if ($.isFunction(init))
		init(opts.$cont, $(opts.elements), opts);
};

// this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt
function go(els, opts, manual, fwd) {
	// opts.busy is true if we're in the middle of an animation
	if (manual && opts.busy && opts.manualTrump) {
		// let manual transitions requests trump active ones
		debug('manualTrump in go(), stopping active transition');
		$(els).stop(true,true);
		opts.busy = 0;
	}
	// don't begin another timeout-based transition if there is one active
	if (opts.busy) {
		debug('transition active, ignoring new tx request');
		return;
	}

	var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide];

	// stop cycling if we have an outstanding stop request
	if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual)
		return;

	// check to see if we should stop cycling based on autostop options
	if (!manual && !p.cyclePause && !opts.bounce &&
		((opts.autostop && (--opts.countdown <= 0)) ||
		(opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) {
		if (opts.end)
			opts.end(opts);
		return;
	}

	// if slideshow is paused, only transition on a manual trigger
	var changed = false;
	if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) {
		changed = true;
		var fx = opts.fx;
		// keep trying to get the slide size if we don't have it yet
		curr.cycleH = curr.cycleH || $(curr).height();
		curr.cycleW = curr.cycleW || $(curr).width();
		next.cycleH = next.cycleH || $(next).height();
		next.cycleW = next.cycleW || $(next).width();

		// support multiple transition types
		if (opts.multiFx) {
			if (fwd && (opts.lastFx == undefined || ++opts.lastFx >= opts.fxs.length))
				opts.lastFx = 0;
			else if (!fwd && (opts.lastFx == undefined || --opts.lastFx < 0))
				opts.lastFx = opts.fxs.length - 1;
			fx = opts.fxs[opts.lastFx];
		}

		// one-time fx overrides apply to:  $('div').cycle(3,'zoom');
		if (opts.oneTimeFx) {
			fx = opts.oneTimeFx;
			opts.oneTimeFx = null;
		}

		$.fn.cycle.resetState(opts, fx);

		// run the before callbacks
		if (opts.before.length)
			$.each(opts.before, function(i,o) {
				if (p.cycleStop != opts.stopCount) return;
				o.apply(next, [curr, next, opts, fwd]);
			});

		// stage the after callacks
		var after = function() {
			opts.busy = 0;
			$.each(opts.after, function(i,o) {
				if (p.cycleStop != opts.stopCount) return;
				o.apply(next, [curr, next, opts, fwd]);
			});
		};

		debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide);
		
		// get ready to perform the transition
		opts.busy = 1;
		if (opts.fxFn) // fx function provided?
			opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
		else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ?
			$.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent);
		else
			$.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
	}

	if (changed || opts.nextSlide == opts.currSlide) {
		// calculate the next slide
		opts.lastSlide = opts.currSlide;
		if (opts.random) {
			opts.currSlide = opts.nextSlide;
			if (++opts.randomIndex == els.length)
				opts.randomIndex = 0;
			opts.nextSlide = opts.randomMap[opts.randomIndex];
			if (opts.nextSlide == opts.currSlide)
				opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1;
		}
		else if (opts.backwards) {
			var roll = (opts.nextSlide - 1) < 0;
			if (roll && opts.bounce) {
				opts.backwards = !opts.backwards;
				opts.nextSlide = 1;
				opts.currSlide = 0;
			}
			else {
				opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1;
				opts.currSlide = roll ? 0 : opts.nextSlide+1;
			}
		}
		else { // sequence
			var roll = (opts.nextSlide + 1) == els.length;
			if (roll && opts.bounce) {
				opts.backwards = !opts.backwards;
				opts.nextSlide = els.length-2;
				opts.currSlide = els.length-1;
			}
			else {
				opts.nextSlide = roll ? 0 : opts.nextSlide+1;
				opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
			}
		}
	}
	if (changed && opts.pager)
		opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass);
	
	// stage the next transition
	var ms = 0;
	if (opts.timeout && !opts.continuous)
		ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd);
	else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic
		ms = 10;
	if (ms > 0)
		p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards) }, ms);
};

// invoked after transition
$.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) {
   $(pager).each(function() {
       $(this).children().removeClass(clsName).eq(currSlide).addClass(clsName);
   });
};

// calculate timeout value for current transition
function getTimeout(curr, next, opts, fwd) {
	if (opts.timeoutFn) {
		// call user provided calc fn
		var t = opts.timeoutFn.call(curr,curr,next,opts,fwd);
		while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout
			t += opts.speed;
		debug('calculated timeout: ' + t + '; speed: ' + opts.speed);
		if (t !== false)
			return t;
	}
	return opts.timeout;
};

// expose next/prev function, caller must pass in state
$.fn.cycle.next = function(opts) { advance(opts,1); };
$.fn.cycle.prev = function(opts) { advance(opts,0);};

// advance slide forward or back
function advance(opts, moveForward) {
	var val = moveForward ? 1 : -1;
	var els = opts.elements;
	var p = opts.$cont[0], timeout = p.cycleTimeout;
	if (timeout) {
		clearTimeout(timeout);
		p.cycleTimeout = 0;
	}
	if (opts.random && val < 0) {
		// move back to the previously display slide
		opts.randomIndex--;
		if (--opts.randomIndex == -2)
			opts.randomIndex = els.length-2;
		else if (opts.randomIndex == -1)
			opts.randomIndex = els.length-1;
		opts.nextSlide = opts.randomMap[opts.randomIndex];
	}
	else if (opts.random) {
		opts.nextSlide = opts.randomMap[opts.randomIndex];
	}
	else {
		opts.nextSlide = opts.currSlide + val;
		if (opts.nextSlide < 0) {
			if (opts.nowrap) return false;
			opts.nextSlide = els.length - 1;
		}
		else if (opts.nextSlide >= els.length) {
			if (opts.nowrap) return false;
			opts.nextSlide = 0;
		}
	}

	var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated
	if ($.isFunction(cb))
		cb(val > 0, opts.nextSlide, els[opts.nextSlide]);
	go(els, opts, 1, moveForward);
	return false;
};

function buildPager(els, opts) {
	var $p = $(opts.pager);
	$.each(els, function(i,o) {
		$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);
	});
	opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass);
};

$.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) {
	var a;
	if ($.isFunction(opts.pagerAnchorBuilder)) {
		a = opts.pagerAnchorBuilder(i,el);
		debug('pagerAnchorBuilder('+i+', el) returned: ' + a);
	}
	else
		a = '<a href="#">'+(i+1)+'</a>';
		
	if (!a)
		return;
	var $a = $(a);
	// don't reparent if anchor is in the dom
	if ($a.parents('body').length === 0) {
		var arr = [];
		if ($p.length > 1) {
			$p.each(function() {
				var $clone = $a.clone(true);
				$(this).append($clone);
				arr.push($clone[0]);
			});
			$a = $(arr);
		}
		else {
			$a.appendTo($p);
		}
	}

	opts.pagerAnchors =  opts.pagerAnchors || [];
	opts.pagerAnchors.push($a);
	
	var pagerFn = function(e) {
		e.preventDefault();
		opts.nextSlide = i;
		var p = opts.$cont[0], timeout = p.cycleTimeout;
		if (timeout) {
			clearTimeout(timeout);
			p.cycleTimeout = 0;
		}
		var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated
		if ($.isFunction(cb))
			cb(opts.nextSlide, els[opts.nextSlide]);
		go(els,opts,1,opts.currSlide < i); // trigger the trans
//		return false; // <== allow bubble
	}
	
	if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) {
		$a.hover(pagerFn, function(){/* no-op */} );
	}
	else {
		$a.bind(opts.pagerEvent, pagerFn);
	}
	
	if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble)
		$a.bind('click.cycle', function(){return false;}); // suppress click
	
	var cont = opts.$cont[0];
	var pauseFlag = false; // https://github.com/malsup/cycle/issues/44
	if (opts.pauseOnPagerHover) {
		$a.hover(
			function() { 
				pauseFlag = true;
				cont.cyclePause++; 
				triggerPause(cont,true,true);
			}, function() { 
				pauseFlag && cont.cyclePause--; 
				triggerPause(cont,true,true);
			} 
		);
	}
};

// helper fn to calculate the number of slides between the current and the next
$.fn.cycle.hopsFromLast = function(opts, fwd) {
	var hops, l = opts.lastSlide, c = opts.currSlide;
	if (fwd)
		hops = c > l ? c - l : opts.slideCount - l;
	else
		hops = c < l ? l - c : l + opts.slideCount - c;
	return hops;
};

// fix clearType problems in ie6 by setting an explicit bg color
// (otherwise text slides look horrible during a fade transition)
function clearTypeFix($slides) {
	debug('applying clearType background-color hack');
	function hex(s) {
		s = parseInt(s,10).toString(16);
		return s.length < 2 ? '0'+s : s;
	};
	function getBg(e) {
		for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {
			var v = $.css(e,'background-color');
			if (v && v.indexOf('rgb') >= 0 ) {
				var rgb = v.match(/\d+/g);
				return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
			}
			if (v && v != 'transparent')
				return v;
		}
		return '#ffffff';
	};
	$slides.each(function() { $(this).css('background-color', getBg(this)); });
};

// reset common props before the next transition
$.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) {
	$(opts.elements).not(curr).hide();
	if (typeof opts.cssBefore.opacity == 'undefined')
		opts.cssBefore.opacity = 1;
	opts.cssBefore.display = 'block';
	if (opts.slideResize && w !== false && next.cycleW > 0)
		opts.cssBefore.width = next.cycleW;
	if (opts.slideResize && h !== false && next.cycleH > 0)
		opts.cssBefore.height = next.cycleH;
	opts.cssAfter = opts.cssAfter || {};
	opts.cssAfter.display = 'none';
	$(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0));
	$(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1));
};

// the actual fn for effecting a transition
$.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) {
	var $l = $(curr), $n = $(next);
	var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut;
	$n.css(opts.cssBefore);
	if (speedOverride) {
		if (typeof speedOverride == 'number')
			speedIn = speedOut = speedOverride;
		else
			speedIn = speedOut = 1;
		easeIn = easeOut = null;
	}
	var fn = function() {
		$n.animate(opts.animIn, speedIn, easeIn, function() {
			cb();
		});
	};
	$l.animate(opts.animOut, speedOut, easeOut, function() {
		$l.css(opts.cssAfter);
		if (!opts.sync) 
			fn();
	});
	if (opts.sync) fn();
};

// transition definitions - only fade is defined here, transition pack defines the rest
$.fn.cycle.transitions = {
	fade: function($cont, $slides, opts) {
		$slides.not(':eq('+opts.currSlide+')').css('opacity',0);
		opts.before.push(function(curr,next,opts) {
			$.fn.cycle.commonReset(curr,next,opts);
			opts.cssBefore.opacity = 0;
		});
		opts.animIn	   = { opacity: 1 };
		opts.animOut   = { opacity: 0 };
		opts.cssBefore = { top: 0, left: 0 };
	}
};

$.fn.cycle.ver = function() { return ver; };

// override these globally if you like (they are all optional)
$.fn.cycle.defaults = {
	activePagerClass: 'activeSlide', // class name used for the active pager link
	after:		   null,  // transition callback (scope set to element that was shown):  function(currSlideElement, nextSlideElement, options, forwardFlag)
	allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling
	animIn:		   null,  // properties that define how the slide animates in
	animOut:	   null,  // properties that define how the slide animates out
	aspect:		   false,  // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option)
	autostop:	   0,	  // true to end slideshow after X transitions (where X == slide count)
	autostopCount: 0,	  // number of transitions (optionally used with autostop to define X)
	backwards:     false, // true to start slideshow at last slide and move backwards through the stack
	before:		   null,  // transition callback (scope set to element to be shown):	 function(currSlideElement, nextSlideElement, options, forwardFlag)
	center: 	   null,  // set to true to have cycle add top/left margin to each slide (use with width and height options)
	cleartype:	   !$.support.opacity,  // true if clearType corrections should be applied (for IE)
	cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
	containerResize: 1,	  // resize container to fit largest slide
	continuous:	   0,	  // true to start next transition immediately after current one completes
	cssAfter:	   null,  // properties that defined the state of the slide after transitioning out
	cssBefore:	   null,  // properties that define the initial state of the slide before transitioning in
	delay:		   0,	  // additional delay (in ms) for first transition (hint: can be negative)
	easeIn:		   null,  // easing for "in" transition
	easeOut:	   null,  // easing for "out" transition
	easing:		   null,  // easing method for both in and out transitions
	end:		   null,  // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
	fastOnEvent:   0,	  // force fast transitions when triggered manually (via pager or prev/next); value == time in ms
	fit:		   0,	  // force slides to fit container
	fx:			  'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle')
	fxFn:		   null,  // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
	height:		  'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well)
	manualTrump:   true,  // causes manual transition to stop an active transition instead of being ignored
	metaAttr:     'cycle',// data- attribute that holds the option data for the slideshow
	next:		   null,  // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide
	nowrap:		   0,	  // true to prevent slideshow from wrapping
	onPagerEvent:  null,  // callback fn for pager events: function(zeroBasedSlideIndex, slideElement)
	onPrevNextEvent: null,// callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement)
	pager:		   null,  // element, jQuery object, or jQuery selector string for the element to use as pager container
	pagerAnchorBuilder: null, // callback fn for building anchor links:  function(index, DOMelement)
	pagerEvent:	  'click.cycle', // name of event which drives the pager navigation
	pause:		   0,	  // true to enable "pause on hover"
	pauseOnPagerHover: 0, // true to pause when hovering over pager link
	prev:		   null,  // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide
	prevNextEvent:'click.cycle',// event which drives the manual transition to the previous or next slide
	random:		   0,	  // true for random, false for sequence (not applicable to shuffle fx)
	randomizeEffects: 1,  // valid when multiple effects are used; true to make the effect sequence random
	requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded
	requeueTimeout: 250,  // ms delay for requeue
	rev:		   0,	  // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle)
	shuffle:	   null,  // coords for shuffle animation, ex: { top:15, left: 200 }
	skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition
	slideExpr:	   null,  // expression for selecting slides (if something other than all children is required)
	slideResize:   1,     // force slide width/height to fixed size before every transition
	speed:		   1000,  // speed of the transition (any valid fx speed value)
	speedIn:	   null,  // speed of the 'in' transition
	speedOut:	   null,  // speed of the 'out' transition
	startingSlide: 0,	  // zero-based index of the first slide to be displayed
	sync:		   1,	  // true if in/out transitions should occur simultaneously
	timeout:	   4000,  // milliseconds between slide transitions (0 to disable auto advance)
	timeoutFn:     null,  // callback for determining per-slide timeout value:  function(currSlideElement, nextSlideElement, options, forwardFlag)
	updateActivePagerLink: null, // callback fn invoked to update the active pager link (adds/removes activePagerClass style)
	width:         null   // container width (if the 'fit' option is true, the slides will be set to this width as well)
};

})(jQuery);


/*!
 * jQuery Cycle Plugin Transition Definitions
 * This script is a plugin for the jQuery Cycle Plugin
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version:	 2.73
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {

//
// These functions define slide initialization and properties for the named
// transitions. To save file size feel free to remove any of these that you
// don't need.
//
$.fn.cycle.transitions.none = function($cont, $slides, opts) {
	opts.fxFn = function(curr,next,opts,after){
		$(next).show();
		$(curr).hide();
		after();
	};
};

// not a cross-fade, fadeout only fades out the top slide
$.fn.cycle.transitions.fadeout = function($cont, $slides, opts) {
	$slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 });
	opts.before.push(function(curr,next,opts,w,h,rev) {
		$(curr).css('zIndex',opts.slideCount + (!rev === true ? 1 : 0));
		$(next).css('zIndex',opts.slideCount + (!rev === true ? 0 : 1));
	});
	opts.animIn.opacity = 1;
	opts.animOut.opacity = 0;
	opts.cssBefore.opacity = 1;
	opts.cssBefore.display = 'block';
	opts.cssAfter.zIndex = 0;
};

// scrollUp/Down/Left/Right
$.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) {
	$cont.css('overflow','hidden');
	opts.before.push($.fn.cycle.commonReset);
	var h = $cont.height();
	opts.cssBefore.top = h;
	opts.cssBefore.left = 0;
	opts.cssFirst.top = 0;
	opts.animIn.top = 0;
	opts.animOut.top = -h;
};
$.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
	$cont.css('overflow','hidden');
	opts.before.push($.fn.cycle.commonReset);
	var h = $cont.height();
	opts.cssFirst.top = 0;
	opts.cssBefore.top = -h;
	opts.cssBefore.left = 0;
	opts.animIn.top = 0;
	opts.animOut.top = h;
};
$.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) {
	$cont.css('overflow','hidden');
	opts.before.push($.fn.cycle.commonReset);
	var w = $cont.width();
	opts.cssFirst.left = 0;
	opts.cssBefore.left = w;
	opts.cssBefore.top = 0;
	opts.animIn.left = 0;
	opts.animOut.left = 0-w;
};
$.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) {
	$cont.css('overflow','hidden');
	opts.before.push($.fn.cycle.commonReset);
	var w = $cont.width();
	opts.cssFirst.left = 0;
	opts.cssBefore.left = -w;
	opts.cssBefore.top = 0;
	opts.animIn.left = 0;
	opts.animOut.left = w;
};
$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
	$cont.css('overflow','hidden').width();
	opts.before.push(function(curr, next, opts, fwd) {
		if (opts.rev)
			fwd = !fwd;
		$.fn.cycle.commonReset(curr,next,opts);
		opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW);
		opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW;
	});
	opts.cssFirst.left = 0;
	opts.cssBefore.top = 0;
	opts.animIn.left = 0;
	opts.animOut.top = 0;
};
$.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) {
	$cont.css('overflow','hidden');
	opts.before.push(function(curr, next, opts, fwd) {
		if (opts.rev)
			fwd = !fwd;
		$.fn.cycle.commonReset(curr,next,opts);
		opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1);
		opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH;
	});
	opts.cssFirst.top = 0;
	opts.cssBefore.left = 0;
	opts.animIn.top = 0;
	opts.animOut.left = 0;
};

// slideX/slideY
$.fn.cycle.transitions.slideX = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$(opts.elements).not(curr).hide();
		$.fn.cycle.commonReset(curr,next,opts,false,true);
		opts.animIn.width = next.cycleW;
	});
	opts.cssBefore.left = 0;
	opts.cssBefore.top = 0;
	opts.cssBefore.width = 0;
	opts.animIn.width = 'show';
	opts.animOut.width = 0;
};
$.fn.cycle.transitions.slideY = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$(opts.elements).not(curr).hide();
		$.fn.cycle.commonReset(curr,next,opts,true,false);
		opts.animIn.height = next.cycleH;
	});
	opts.cssBefore.left = 0;
	opts.cssBefore.top = 0;
	opts.cssBefore.height = 0;
	opts.animIn.height = 'show';
	opts.animOut.height = 0;
};

// shuffle
$.fn.cycle.transitions.shuffle = function($cont, $slides, opts) {
	var i, w = $cont.css('overflow', 'visible').width();
	$slides.css({left: 0, top: 0});
	opts.before.push(function(curr,next,opts) {
		$.fn.cycle.commonReset(curr,next,opts,true,true,true);
	});
	// only adjust speed once!
	if (!opts.speedAdjusted) {
		opts.speed = opts.speed / 2; // shuffle has 2 transitions
		opts.speedAdjusted = true;
	}
	opts.random = 0;
	opts.shuffle = opts.shuffle || {left:-w, top:15};
	opts.els = [];
	for (i=0; i < $slides.length; i++)
		opts.els.push($slides[i]);

	for (i=0; i < opts.currSlide; i++)
		opts.els.push(opts.els.shift());

	// custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!)
	opts.fxFn = function(curr, next, opts, cb, fwd) {
		if (opts.rev)
			fwd = !fwd;
		var $el = fwd ? $(curr) : $(next);
		$(next).css(opts.cssBefore);
		var count = opts.slideCount;
		$el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() {
			var hops = $.fn.cycle.hopsFromLast(opts, fwd);
			for (var k=0; k < hops; k++)
				fwd ? opts.els.push(opts.els.shift()) : opts.els.unshift(opts.els.pop());
			if (fwd) {
				for (var i=0, len=opts.els.length; i < len; i++)
					$(opts.els[i]).css('z-index', len-i+count);
			}
			else {
				var z = $(curr).css('z-index');
				$el.css('z-index', parseInt(z,10)+1+count);
			}
			$el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() {
				$(fwd ? this : curr).hide();
				if (cb) cb();
			});
		});
	};
	$.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 });
};

// turnUp/Down/Left/Right
$.fn.cycle.transitions.turnUp = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,true,false);
		opts.cssBefore.top = next.cycleH;
		opts.animIn.height = next.cycleH;
		opts.animOut.width = next.cycleW;
	});
	opts.cssFirst.top = 0;
	opts.cssBefore.left = 0;
	opts.cssBefore.height = 0;
	opts.animIn.top = 0;
	opts.animOut.height = 0;
};
$.fn.cycle.transitions.turnDown = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,true,false);
		opts.animIn.height = next.cycleH;
		opts.animOut.top   = curr.cycleH;
	});
	opts.cssFirst.top = 0;
	opts.cssBefore.left = 0;
	opts.cssBefore.top = 0;
	opts.cssBefore.height = 0;
	opts.animOut.height = 0;
};
$.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,false,true);
		opts.cssBefore.left = next.cycleW;
		opts.animIn.width = next.cycleW;
	});
	opts.cssBefore.top = 0;
	opts.cssBefore.width = 0;
	opts.animIn.left = 0;
	opts.animOut.width = 0;
};
$.fn.cycle.transitions.turnRight = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,false,true);
		opts.animIn.width = next.cycleW;
		opts.animOut.left = curr.cycleW;
	});
	$.extend(opts.cssBefore, { top: 0, left: 0, width: 0 });
	opts.animIn.left = 0;
	opts.animOut.width = 0;
};

// zoom
$.fn.cycle.transitions.zoom = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,false,false,true);
		opts.cssBefore.top = next.cycleH/2;
		opts.cssBefore.left = next.cycleW/2;
		$.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH });
		$.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 });
	});
	opts.cssFirst.top = 0;
	opts.cssFirst.left = 0;
	opts.cssBefore.width = 0;
	opts.cssBefore.height = 0;
};

// fadeZoom
$.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,false,false);
		opts.cssBefore.left = next.cycleW/2;
		opts.cssBefore.top = next.cycleH/2;
		$.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH });
	});
	opts.cssBefore.width = 0;
	opts.cssBefore.height = 0;
	opts.animOut.opacity = 0;
};

// blindX
$.fn.cycle.transitions.blindX = function($cont, $slides, opts) {
	var w = $cont.css('overflow','hidden').width();
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts);
		opts.animIn.width = next.cycleW;
		opts.animOut.left   = curr.cycleW;
	});
	opts.cssBefore.left = w;
	opts.cssBefore.top = 0;
	opts.animIn.left = 0;
	opts.animOut.left = w;
};
// blindY
$.fn.cycle.transitions.blindY = function($cont, $slides, opts) {
	var h = $cont.css('overflow','hidden').height();
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts);
		opts.animIn.height = next.cycleH;
		opts.animOut.top   = curr.cycleH;
	});
	opts.cssBefore.top = h;
	opts.cssBefore.left = 0;
	opts.animIn.top = 0;
	opts.animOut.top = h;
};
// blindZ
$.fn.cycle.transitions.blindZ = function($cont, $slides, opts) {
	var h = $cont.css('overflow','hidden').height();
	var w = $cont.width();
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts);
		opts.animIn.height = next.cycleH;
		opts.animOut.top   = curr.cycleH;
	});
	opts.cssBefore.top = h;
	opts.cssBefore.left = w;
	opts.animIn.top = 0;
	opts.animIn.left = 0;
	opts.animOut.top = h;
	opts.animOut.left = w;
};

// growX - grow horizontally from centered 0 width
$.fn.cycle.transitions.growX = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,false,true);
		opts.cssBefore.left = this.cycleW/2;
		opts.animIn.left = 0;
		opts.animIn.width = this.cycleW;
		opts.animOut.left = 0;
	});
	opts.cssBefore.top = 0;
	opts.cssBefore.width = 0;
};
// growY - grow vertically from centered 0 height
$.fn.cycle.transitions.growY = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,true,false);
		opts.cssBefore.top = this.cycleH/2;
		opts.animIn.top = 0;
		opts.animIn.height = this.cycleH;
		opts.animOut.top = 0;
	});
	opts.cssBefore.height = 0;
	opts.cssBefore.left = 0;
};

// curtainX - squeeze in both edges horizontally
$.fn.cycle.transitions.curtainX = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,false,true,true);
		opts.cssBefore.left = next.cycleW/2;
		opts.animIn.left = 0;
		opts.animIn.width = this.cycleW;
		opts.animOut.left = curr.cycleW/2;
		opts.animOut.width = 0;
	});
	opts.cssBefore.top = 0;
	opts.cssBefore.width = 0;
};
// curtainY - squeeze in both edges vertically
$.fn.cycle.transitions.curtainY = function($cont, $slides, opts) {
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,true,false,true);
		opts.cssBefore.top = next.cycleH/2;
		opts.animIn.top = 0;
		opts.animIn.height = next.cycleH;
		opts.animOut.top = curr.cycleH/2;
		opts.animOut.height = 0;
	});
	opts.cssBefore.height = 0;
	opts.cssBefore.left = 0;
};

// cover - curr slide covered by next slide
$.fn.cycle.transitions.cover = function($cont, $slides, opts) {
	var d = opts.direction || 'left';
	var w = $cont.css('overflow','hidden').width();
	var h = $cont.height();
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts);
		if (d == 'right')
			opts.cssBefore.left = -w;
		else if (d == 'up')
			opts.cssBefore.top = h;
		else if (d == 'down')
			opts.cssBefore.top = -h;
		else
			opts.cssBefore.left = w;
	});
	opts.animIn.left = 0;
	opts.animIn.top = 0;
	opts.cssBefore.top = 0;
	opts.cssBefore.left = 0;
};

// uncover - curr slide moves off next slide
$.fn.cycle.transitions.uncover = function($cont, $slides, opts) {
	var d = opts.direction || 'left';
	var w = $cont.css('overflow','hidden').width();
	var h = $cont.height();
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,true,true,true);
		if (d == 'right')
			opts.animOut.left = w;
		else if (d == 'up')
			opts.animOut.top = -h;
		else if (d == 'down')
			opts.animOut.top = h;
		else
			opts.animOut.left = -w;
	});
	opts.animIn.left = 0;
	opts.animIn.top = 0;
	opts.cssBefore.top = 0;
	opts.cssBefore.left = 0;
};

// toss - move top slide and fade away
$.fn.cycle.transitions.toss = function($cont, $slides, opts) {
	var w = $cont.css('overflow','visible').width();
	var h = $cont.height();
	opts.before.push(function(curr, next, opts) {
		$.fn.cycle.commonReset(curr,next,opts,true,true,true);
		// provide default toss settings if animOut not provided
		if (!opts.animOut.left && !opts.animOut.top)
			$.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 });
		else
			opts.animOut.opacity = 0;
	});
	opts.cssBefore.left = 0;
	opts.cssBefore.top = 0;
	opts.animIn.left = 0;
};

// wipe - clip animation
$.fn.cycle.transitions.wipe = function($cont, $slides, opts) {
	var w = $cont.css('overflow','hidden').width();
	var h = $cont.height();
	opts.cssBefore = opts.cssBefore || {};
	var clip;
	if (opts.clip) {
		if (/l2r/.test(opts.clip))
			clip = 'rect(0px 0px '+h+'px 0px)';
		else if (/r2l/.test(opts.clip))
			clip = 'rect(0px '+w+'px '+h+'px '+w+'px)';
		else if (/t2b/.test(opts.clip))
			clip = 'rect(0px '+w+'px 0px 0px)';
		else if (/b2t/.test(opts.clip))
			clip = 'rect('+h+'px '+w+'px '+h+'px 0px)';
		else if (/zoom/.test(opts.clip)) {
			var top = parseInt(h/2,10);
			var left = parseInt(w/2,10);
			clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)';
		}
	}

	opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)';

	var d = opts.cssBefore.clip.match(/(\d+)/g);
	var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10);

	opts.before.push(function(curr, next, opts) {
		if (curr == next) return;
		var $curr = $(curr), $next = $(next);
		$.fn.cycle.commonReset(curr,next,opts,true,true,false);
		opts.cssAfter.display = 'block';

		var step = 1, count = parseInt((opts.speedIn / 13),10) - 1;
		(function f() {
			var tt = t ? t - parseInt(step * (t/count),10) : 0;
			var ll = l ? l - parseInt(step * (l/count),10) : 0;
			var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h;
			var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w;
			$next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' });
			(step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none');
		})();
	});
	$.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 });
	opts.animIn	   = { left: 0 };
	opts.animOut   = { left: 0 };
};

})(jQuery);
;

/**
 *  @file
 *  A simple jQuery Cycle Div Slideshow Rotator.
 */

/**
 * This will set our initial behavior, by starting up each individual slideshow.
 */
(function ($) {
  Drupal.behaviors.viewsSlideshowCycle = {
    attach: function (context) {
      $('.views_slideshow_cycle_main:not(.viewsSlideshowCycle-processed)', context).addClass('viewsSlideshowCycle-processed').each(function() {
        var fullId = '#' + $(this).attr('id');
        var settings = Drupal.settings.viewsSlideshowCycle[fullId];
        settings.targetId = '#' + $(fullId + " :first").attr('id');
        settings.slideshowId = settings.targetId.replace('#views_slideshow_cycle_teaser_section_', '');
        settings.paused = false;
    
        settings.opts = {
          speed:settings.speed,
          timeout:settings.timeout,
          delay:settings.delay,
          sync:settings.sync,
          random:settings.random,
          nowrap:settings.nowrap,
          after:function(curr, next, opts) {
            // Need to do some special handling on first load.
            var slideNum = opts.currSlide;
            if (typeof settings.processedAfter == 'undefined' || !settings.processedAfter) {
              settings.processedAfter = 1;
              slideNum = (typeof settings.opts.startingSlide == 'undefined') ? 0 : settings.opts.startingSlide;
            }
            Drupal.viewsSlideshow.action({ "action": 'transitionEnd', "slideshowID": settings.slideshowId, "slideNum": slideNum });
          },
          before:function(curr, next, opts) {
            // Remember last slide.
            if (settings.remember_slide) {
              createCookie(settings.vss_id, opts.currSlide + 1, settings.remember_slide_days);
            }
    
            // Make variable height.
            if (!settings.fixed_height) {
              //get the height of the current slide
              var $ht = $(this).height();
              //set the container's height to that of the current slide
              $(this).parent().animate({height: $ht});
            }
            
            // Need to do some special handling on first load.
            var slideNum = opts.nextSlide;
            if (typeof settings.processedBefore == 'undefined' || !settings.processedBefore) {
              settings.processedBefore = 1;
              slideNum = (typeof settings.opts.startingSlide == 'undefined') ? 0 : settings.opts.startingSlide;
            }
            
            Drupal.viewsSlideshow.action({ "action": 'transitionBegin', "slideshowID": settings.slideshowId, "slideNum": slideNum });
          },
          cleartype:(settings.cleartype)? true : false,
          cleartypeNoBg:(settings.cleartypenobg)? true : false
        }
        
        // Set the starting slide if we are supposed to remember the slide
        if (settings.remember_slide) {
          var startSlide = readCookie(settings.vss_id);
          if (startSlide == null) {
            startSlide = 0;
          }
          settings.opts.startingSlide =  startSlide;
        }
    
        if (settings.effect == 'none') {
          settings.opts.speed = 1;
        }
        else {
          settings.opts.fx = settings.effect;
        }
        
        // Take starting item from fragment.
        var hash = location.hash;
        if (hash) {
          var hash = hash.replace('#', '');
          var aHash = hash.split(';');
          var aHashLen = aHash.length;
          
          // Loop through all the possible starting points.
          for (var i = 0; i < aHashLen; i++) {
            // Split the hash into two parts. One part is the slideshow id the
            // other is the slide number.
            var initialInfo = aHash[i].split(':');
            // The id in the hash should match our slideshow.
            // The slide number chosen shouldn't be larger than the number of
            // slides we have.
            if (settings.slideshowId == initialInfo[0] && settings.num_divs > initialInfo[1]) {
              settings.opts.startingSlide = parseInt(initialInfo[1]);
            }
          }
        }

        // Pause on hover.
        if (settings.pause) {
          $('#views_slideshow_cycle_teaser_section_' + settings.vss_id).hover(function() {
            Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": settings.slideshowId });
          }, function() {
            if (!settings.paused) {
              Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": settings.slideshowId });
            }
          });
        }
    
        // Pause on clicking of the slide.
        if (settings.pause_on_click) {
          $('#views_slideshow_cycle_teaser_section_' + settings.vss_id).click(function() {
            Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": settings.slideshowId });
          });
        }
        
        if (typeof JSON != 'undefined') {
          var advancedOptions = JSON.parse(settings.advanced_options);
          for (var option in advancedOptions) {
            advancedOptions[option] = $.trim(advancedOptions[option]);
            advancedOptions[option] = advancedOptions[option].replace(/\n/g, '');
            if (!isNaN(parseInt(advancedOptions[option]))) {
              advancedOptions[option] = parseInt(advancedOptions[option]);
            }
            else if (advancedOptions[option].toLowerCase() == 'true') {
              advancedOptions[option] = true;
            }
            else if (advancedOptions[option].toLowerCase() == 'false') {
              advancedOptions[option] = false;
            }
            
            switch(option) {
              
              // Standard Options
              case "activePagerClass":
              case "allowPagerClickBubble":
              case "autostop":
              case "autostopCount":
              case "backwards":
              case "bounce":
              case "cleartype":
              case "cleartypeNoBg":
              case "containerResize":
              case "continuous":
              case "delay":
              case "easeIn":
              case "easeOut":
              case "easing":
              case "fastOnEvent":
              case "fit":
              case "fx":
              case "height":
              case "manualTrump":
              case "next":
              case "nowrap":
              case "pager":
              case "pagerEvent":
              case "pause":
              case "pauseOnPagerHover":
              case "prev":
              case "prevNextEvent":
              case "random":
              case "randomizeEffects":
              case "requeueOnImageNotLoaded":
              case "requeueTimeout":
              case "rev":
              case "slideExpr":
              case "slideResize":
              case "speed":
              case "speedIn":
              case "speedOut":
              case "startingSlide":
              case "sync":
              case "timeout":
                settings.opts[option] = advancedOptions[option];
                break;
              
              // These process options that look like {top:50, bottom:20}
              case "animIn":
              case "animOut":
              case "cssBefore":
              case "cssAfter":
              case "shuffle":
                settings.opts[option] = eval('(' + advancedOptions[option] + ')');
                break;
              
              // These options have their own functions.
              case "after":
                // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag) 
                settings.opts[option] = function(currSlideElement, nextSlideElement, options, forwardFlag) {
                  eval(advancedOptions[option]);
                }
                break;
              
              case "before":
                // transition callback (scope set to element to be shown):     function(currSlideElement, nextSlideElement, options, forwardFlag) 
                settings.opts[option] = function(currSlideElement, nextSlideElement, options, forwardFlag) {
                  eval(advancedOptions[option]);
                }
                break;
              
              case "end":
                // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
                settings.opts[option] = function(options) {
                  eval(advancedOptions[option]);
                }
                break;
              
              case "fxFn":
                // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
                settings.opts[option] = function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag) {
                  eval(advancedOptions[option]);
                }
                break;
              
              case "onPagerEvent":
                settings.opts[option] = function(zeroBasedSlideIndex, slideElement) {
                  eval(advancedOptions[option]);
                }
                break;
              
              case "onPrevNextEvent":
                settings.opts[option] = function(isNext, zeroBasedSlideIndex, slideElement) {
                  eval(advancedOptions[option]);
                }
                break;
              
              case "pagerAnchorBuilder":
                // callback fn for building anchor links:  function(index, DOMelement)
                settings.opts[option] = function(index, DOMelement) {
                  eval(advancedOptions[option]);
                }
                break;
              
              case "pagerClick":
                // callback fn for pager clicks:    function(zeroBasedSlideIndex, slideElement)
                settings.opts[option] = function(zeroBasedSlideIndex, slideElement) {
                  eval(advancedOptions[option]);
                }
                break;
              
              case "timeoutFn":
                settings.opts[option] = function(currSlideElement, nextSlideElement, options, forwardFlag) {
                  eval(advancedOptions[option]);
                }
                break;
          
              case "updateActivePagerLink":
                // callback fn invoked to update the active pager link (adds/removes activePagerClass style)
                settings.opts[option] = function(pager, currSlideIndex) {
                  eval(advancedOptions[option]);
                }
                break;
            }
          }
        }
        
        // If selected wait for the images to be loaded.
        // otherwise just load the slideshow.
        if (settings.wait_for_image_load) {
          // For IE/Chrome/Opera we if there are images then we need to make
          // sure the images are loaded before starting the slideshow.
          settings.totalImages = $(settings.targetId + ' img').length;
          if (settings.totalImages) {
            settings.loadedImages = 0;
  
            // Add a load event for each image.
            $(settings.targetId + ' img').each(function() {
              var $imageElement = $(this);
              $imageElement.bind('load', function () {
                Drupal.viewsSlideshowCycle.imageWait(fullId);
              });
              
              // Removing the source and adding it again will fire the load event.
              var imgSrc = $imageElement.attr('src');
              $imageElement.attr('src', '');
              $imageElement.attr('src', imgSrc);
            });
          }
          else {
            Drupal.viewsSlideshowCycle.load(fullId);
          }
        }
        else {
          Drupal.viewsSlideshowCycle.load(fullId);
        }
      });
    }
  };
  
  Drupal.viewsSlideshowCycle = Drupal.viewsSlideshowCycle || {};
  
  // This checks to see if all the images have been loaded.
  // If they have then it starts the slideshow.
  Drupal.viewsSlideshowCycle.imageWait = function(fullId) {
    if (++Drupal.settings.viewsSlideshowCycle[fullId].loadedImages == Drupal.settings.viewsSlideshowCycle[fullId].totalImages) {
      Drupal.viewsSlideshowCycle.load(fullId);
    }
  }
  
  // Start the slideshow.
  Drupal.viewsSlideshowCycle.load = function (fullId) {
    var settings = Drupal.settings.viewsSlideshowCycle[fullId];
    $(settings.targetId).cycle(settings.opts);
    
    // Start Paused
    if (settings.start_paused) {
      Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": settings.slideshowId });
    }
    
    // Pause if hidden.
    if (settings.pause_when_hidden) {
      var checkPause = function(settings) {
        // If the slideshow is visible and it is paused then resume.
        // otherwise if the slideshow is not visible and it is not paused then
        // pause it.
        var visible = viewsSlideshowCycleIsVisible(settings.targetId, settings.pause_when_hidden_type, settings.amount_allowed_visible);
        if (visible && settings.paused) {
          Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": settings.slideshowId });
        }
        else if (!visible && !settings.paused) {
          Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": settings.slideshowId });
        }
      }
     
      // Check when scrolled.
      $(window).scroll(function() {
       checkPause(settings);
      });
      
      // Check when the window is resized.
      $(window).resize(function() {
        checkPause(settings);
      });
    }
  }
  
  Drupal.viewsSlideshowCycle.pause = function (options) {
    $('#views_slideshow_cycle_teaser_section_' + options.slideshowID).cycle('pause');
  }
  
  Drupal.viewsSlideshowCycle.play = function (options) {
    $('#views_slideshow_cycle_teaser_section_' + options.slideshowID).cycle('resume');
  }
  
  Drupal.viewsSlideshowCycle.previousSlide = function (options) {
    $('#views_slideshow_cycle_teaser_section_' + options.slideshowID).cycle('prev');
  }
  
  Drupal.viewsSlideshowCycle.nextSlide = function (options) {
    $('#views_slideshow_cycle_teaser_section_' + options.slideshowID).cycle('next');
  }
  
  Drupal.viewsSlideshowCycle.goToSlide = function (options) {
    $('#views_slideshow_cycle_teaser_section_' + options.slideshowID).cycle(options.slideNum);
  }
  
  // Verify that the value is a number.
  function IsNumeric(sText) {
    var ValidChars = "0123456789";
    var IsNumber=true;
    var Char;
  
    for (var i=0; i < sText.length && IsNumber == true; i++) { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
        IsNumber = false;
      }
    }
    return IsNumber;
  }
  
  /**
   * Cookie Handling Functions
   */
  function createCookie(name,value,days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    }
    else {
      var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
  }
  
  function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) {
        return c.substring(nameEQ.length,c.length);
      }
    }
    return null;
  }
  
  function eraseCookie(name) {
    createCookie(name,"",-1);
  }
  
  /**
   * Checks to see if the slide is visible enough.
   * elem = element to check.
   * type = The way to calculate how much is visible.
   * amountVisible = amount that should be visible. Either in percent or px. If
   *                it's not defined then all of the slide must be visible.
   *
   * Returns true or false
   */
  function viewsSlideshowCycleIsVisible(elem, type, amountVisible) {
    // Get the top and bottom of the window;
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var docViewLeft = $(window).scrollLeft();
    var docViewRight = docViewLeft + $(window).width();
  
    // Get the top, bottom, and height of the slide;
    var elemTop = $(elem).offset().top;
    var elemHeight = $(elem).height();
    var elemBottom = elemTop + elemHeight;
    var elemLeft = $(elem).offset().left;
    var elemWidth = $(elem).width();
    var elemRight = elemLeft + elemWidth;
    var elemArea = elemHeight * elemWidth;
    
    // Calculate what's hiding in the slide.
    var missingLeft = 0;
    var missingRight = 0;
    var missingTop = 0;
    var missingBottom = 0;
    
    // Find out how much of the slide is missing from the left.
    if (elemLeft < docViewLeft) {
      missingLeft = docViewLeft - elemLeft;
    }
  
    // Find out how much of the slide is missing from the right.
    if (elemRight > docViewRight) {
      missingRight = elemRight - docViewRight;
    }
    
    // Find out how much of the slide is missing from the top.
    if (elemTop < docViewTop) {
      missingTop = docViewTop - elemTop;
    }
  
    // Find out how much of the slide is missing from the bottom.
    if (elemBottom > docViewBottom) {
      missingBottom = elemBottom - docViewBottom;
    }
    
    // If there is no amountVisible defined then check to see if the whole slide
    // is visible.
    if (type == 'full') {
      return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
      && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop)
      && (elemLeft >= docViewLeft) && (elemRight <= docViewRight)
      && (elemLeft <= docViewRight) && (elemRight >= docViewLeft));
    }
    else if(type == 'vertical') {
      var verticalShowing = elemHeight - missingTop - missingBottom;
      
      // If user specified a percentage then find out if the current shown percent
      // is larger than the allowed percent.
      // Otherwise check to see if the amount of px shown is larger than the
      // allotted amount.
      if (amountVisible.indexOf('%')) {
        return (((verticalShowing/elemHeight)*100) >= parseInt(amountVisible));
      }
      else {
        return (verticalShowing >= parseInt(amountVisible));
      }
    }
    else if(type == 'horizontal') {
      var horizontalShowing = elemWidth - missingLeft - missingRight;
      
      // If user specified a percentage then find out if the current shown percent
      // is larger than the allowed percent.
      // Otherwise check to see if the amount of px shown is larger than the
      // allotted amount.
      if (amountVisible.indexOf('%')) {
        return (((horizontalShowing/elemWidth)*100) >= parseInt(amountVisible));
      }
      else {
        return (horizontalShowing >= parseInt(amountVisible));
      }
    }
    else if(type == 'area') {
      var areaShowing = (elemWidth - missingLeft - missingRight) * (elemHeight - missingTop - missingBottom);
      
      // If user specified a percentage then find out if the current shown percent
      // is larger than the allowed percent.
      // Otherwise check to see if the amount of px shown is larger than the
      // allotted amount.
      if (amountVisible.indexOf('%')) {
        return (((areaShowing/elemArea)*100) >= parseInt(amountVisible));
      }
      else {
        return (areaShowing >= parseInt(amountVisible));
      }
    }
  }
})(jQuery);
;
// $Id: extlink.js,v 1.8 2010/05/26 01:25:56 quicksketch Exp $
(function ($) {

function extlinkAttach(context) {
  // Strip the host name down, removing ports, subdomains, or www.
  var pattern = /^(([^\/:]+?\.)*)([^\.:]{4,})((\.[a-z]{1,4})*)(:[0-9]{1,5})?$/;
  var host = window.location.host.replace(pattern, '$3$4');
  var subdomain = window.location.host.replace(pattern, '$1');

  // Determine what subdomains are considered internal.
  if (Drupal.settings.extlink.extSubdomains) {
    var subdomains = "([^/]*\\.)?";
  }
  else if (subdomain == 'www.' || subdomain == '') {
    var subdomains = "(www\\.)?";
  }
  else {
    var subdomains = subdomain.replace(".", "\\.");
  }

  // Build regular expressions that define an internal link.
  var internal_link = new RegExp("^https?://" + subdomains + host, "i");

  // Extra internal link matching.
  var extInclude = false;
  if (Drupal.settings.extlink.extInclude) {
    extInclude = new RegExp(Drupal.settings.extlink.extInclude.replace(/\\/, '\\'));
  }

  // Extra external link matching.
  var extExclude = false;
  if (Drupal.settings.extlink.extExclude) {
    extExclude = new RegExp(Drupal.settings.extlink.extExclude.replace(/\\/, '\\'));
  }

  // Find all links which are NOT internal and begin with http (as opposed
  // to ftp://, javascript:, etc. other kinds of links.
  // When operating on the 'this' variable, the host has been appended to
  // all links by the browser, even local ones.
  // In jQuery 1.1 and higher, we'd use a filter method here, but it is not
  // available in jQuery 1.0 (Drupal 5 default).
  var external_links = new Array();
  var mailto_links = new Array();
  $("a:not(." + Drupal.settings.extlink.extClass + ", ." + Drupal.settings.extlink.mailtoClass + ")", context).each(function(el) {
    try {
      var url = this.href.toLowerCase();
      if (url.indexOf('http') == 0 && (!url.match(internal_link) || (extInclude && url.match(extInclude))) && !(extExclude && url.match(extExclude))) {
        external_links.push(this);
      }
      else if (url.indexOf('mailto:') == 0) {
        mailto_links.push(this);
      }
    }
    // IE7 throws errors often when dealing with irregular links, such as:
    // <a href="node/10"></a> Empty tags.
    // <a href="http://user:pass@example.com">example</a> User:pass syntax.
    catch(error) {
      return false;
    }
  });

  if (Drupal.settings.extlink.extClass) {
    // Apply the "ext" class to all links not containing images.
    if (parseFloat($().jquery) < 1.2) {
      $(external_links).not('[img]').addClass(Drupal.settings.extlink.extClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.extClass + '></span>'); });
    }
    else {
      $(external_links).not($(external_links).find('img').parents('a')).addClass(Drupal.settings.extlink.extClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.extClass + '></span>'); });
    }
  }

  if (Drupal.settings.extlink.mailtoClass) {
    // Apply the "mailto" class to all mailto links not containing images.
    if (parseFloat($().jquery) < 1.2) {
      $(mailto_links).not('[img]').addClass(Drupal.settings.extlink.mailtoClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.mailtoClass + '></span>'); });
    }
    else {
      $(mailto_links).not($(mailto_links).find('img').parents('a')).addClass(Drupal.settings.extlink.mailtoClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.mailtoClass + '></span>'); });
    }
  }

  if (Drupal.settings.extlink.extTarget) {
    // Apply the target attribute to all links.
    $(external_links).attr('target', Drupal.settings.extlink.extTarget);
  }

  if (Drupal.settings.extlink.extAlert) {
    // Add pop-up click-through dialog.
    $(external_links).click(function(e) {
     return confirm(Drupal.settings.extlink.extAlertText);
    });
  }

  // Work around for Internet Explorer box model problems.
  if (($.support && !($.support.boxModel === undefined) && !$.support.boxModel) || ($.browser.msie && parseInt($.browser.version) <= 7)) {
    $('span.ext, span.mailto').css('display', 'inline-block');
  }
}

Drupal.behaviors.extlink = {
  attach: function(context){
    extlinkAttach(context);
  }
}

})(jQuery);
;
(function ($) {

$(document).ready(function() {

  // Accepts a string; returns the string with regex metacharacters escaped. The returned string
  // can safely be used at any point within a regex to match the provided literal string. Escaped
  // characters are [ ] { } ( ) * + ? - . , \ ^ $ # and whitespace. The character | is excluded
  // in this function as it's used to separate the domains names.
  RegExp.escapeDomains = function(text) {
    return (text) ? text.replace(/[-[\]{}()*+?.,\\^$#\s]/g, "\\$&") : '';
  }

  // Attach onclick event to document only and catch clicks on all elements.
  $(document.body).click(function(event) {
    // Catch the closest surrounding link of a clicked element.
    $(event.target).closest("a,area").each(function() {

      var ga = Drupal.settings.googleanalytics;
      // Expression to check for absolute internal links.
      var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
      // Expression to check for special links like gotwo.module /go/* links.
      var isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
      // Expression to check for download links.
      var isDownload = new RegExp("\\.(" + ga.trackDownloadExtensions + ")$", "i");
      // Expression to check for the sites cross domains.
      var isCrossDomain = new RegExp("^(https?|ftp|news|nntp|telnet|irc|ssh|sftp|webcal):\/\/.*(" + RegExp.escapeDomains(ga.trackCrossDomains) + ")", "i");

      // Is the clicked URL internal?
      if (isInternal.test(this.href)) {
        // Is download tracking activated and the file extension configured for download tracking?
        if (ga.trackDownload && isDownload.test(this.href)) {
          // Download link clicked.
          var extension = isDownload.exec(this.href);
          _gaq.push(["_trackEvent", "Downloads", extension[1].toUpperCase(), this.href.replace(isInternal, '')]);
        }
        else if (isInternalSpecial.test(this.href)) {
          // Keep the internal URL for Google Analytics website overlay intact.
          _gaq.push(["_trackPageview", this.href.replace(isInternal, '')]);
        }
      }
      else {
        if (ga.trackMailto && $(this).is("a[href^=mailto:],area[href^=mailto:]")) {
          // Mailto link clicked.
          _gaq.push(["_trackEvent", "Mails", "Click", this.href.substring(7)]);
        }
        else if (ga.trackOutbound && this.href) {
          if (ga.trackDomainMode == 2 && isCrossDomain.test(this.href)) {
            // Top-level cross domain clicked. document.location is handled by _link internally.
            _gaq.push(["_link", this.href]);
          }
          else if (ga.trackOutboundAsPageview) {
            // Track all external links as page views after URL cleanup.
            // Currently required, if click should be tracked as goal.
            _gaq.push(["_trackPageview", '/outbound/' + this.href.replace(/^(https?|ftp|news|nntp|telnet|irc|ssh|sftp|webcal):\/\//i, '').split('/').join('--')]);
          }
          else {
            // External link clicked.
            _gaq.push(["_trackEvent", "Outbound links", "Click", this.href]);
          }
        }
      }
    });
  });
});

})(jQuery);
;

