(function(e){e.fn.jTweetsAnywhere=function(a){a=e.extend({username:"tbillenstein",list:null,searchParams:null,count:0,tweetProfileImagePresent:null,tweetFilter:defaultTweetFilter,showTweetFeed:true,showFollowButton:false,showConnectButton:false,showLoginInfo:false,showTweetBox:false,mainDecorator:defaultMainDecorator,tweetFeedDecorator:defaultTweetFeedDecorator,tweetDecorator:defaultTweetDecorator,tweetProfileImageDecorator:defaultTweetProfileImageDecorator,tweetBodyDecorator:defaultTweetBodyDecorator, tweetUsernameDecorator:defaultTweetUsernameDecorator,tweetTextDecorator:defaultTweetTextDecorator,tweetAttributesDecorator:defaultTweetAttributesDecorator,tweetTimestampDecorator:defaultTweetTimestampDecorator,tweetSourceDecorator:defaultTweetSourceDecorator,tweetGeoLocationDecorator:defaultTweetGeoLocationDecorator,tweetInReplyToDecorator:defaultTweetInReplyToDecorator,tweetRetweeterDecorator:defaultTweetRetweeterDecorator,tweetFeedControlsDecorator:defaultTweetFeedControlsDecorator,tweetFeedControlsMoreBtnDecorator:defaultTweetFeedControlsMoreBtnDecorator, tweetFeedControlsPrevBtnDecorator:defaultTweetFeedControlsPrevBtnDecorator,tweetFeedControlsNextBtnDecorator:defaultTweetFeedControlsNextBtnDecorator,tweetFeedAutorefreshTriggerDecorator:defaultTweetFeedAutorefreshTriggerDecorator,tweetFeedAutorefreshTriggerContentDecorator:defaultTweetFeedAutorefreshTriggerContentDecorator,connectButtonDecorator:defaultConnectButtonDecorator,loginInfoDecorator:defaultLoginInfoDecorator,loginInfoContentDecorator:defaultLoginInfoContentDecorator,followButtonDecorator:defaultFollowButtonDecorator, tweetBoxDecorator:defaultTweetBoxDecorator,linkDecorator:defaultLinkDecorator,usernameDecorator:defaultUsernameDecorator,hashtagDecorator:defaultHashtagDecorator,loadingDecorator:defaultLoadingDecorator,errorDecorator:defaultErrorDecorator,noDataDecorator:defaultNoDataDecorator,tweetTimestampFormatter:defaultTweetTimestampFormatter,tweetTimestampTooltipFormatter:defaultTweetTimestampTooltipFormatter,tweetVisualizer:defaultTweetVisualizer,loadingIndicatorVisualizer:defaultLoadingIndicatorVisualizer, autorefreshTriggerVisualizer:defaultAutorefreshTriggerVisualizer,onDataRequestHandler:defaultOnDataRequestHandler,onRateLimitDataHandler:defaultOnRateLimitDataHandler,_tweetFeedConfig:{expandHovercards:false,showTimestamp:{refreshInterval:0},showSource:false,showGeoLocation:true,showInReplyTo:true,showProfileImages:null,showUserScreenNames:null,showUserFullNames:false,includeRetweets:true,paging:{mode:"none",_limit:0,_offset:0},autorefresh:{mode:"none",interval:60,duration:3600,_startTime:null,_triggerElement:null}, _pageParam:0,_maxId:null,_recLevel:0,_noData:false,_clearBeforePopulate:false},_tweetBoxConfig:{counter:true,width:515,height:65,label:"What's happening?",defaultContent:"",onTweet:function(){}},_connectButtonConfig:{size:"medium"},_baseSelector:null,_baseElement:null,_tweetFeedElement:null,_tweetFeedControlsElement:null,_followButtonElement:null,_loginInfoElement:null,_connectButtonElement:null,_tweetBoxElement:null,_loadingIndicatorElement:null,_noDataElement:null,_tweetsCache:[],_autorefreshTweetsCache:[], _stats:{dataRequestCount:0,rateLimitPreventionCount:0,rateLimit:{remaining_hits:150,hourly_limit:150}}},a);if(a.mainDecorator){a._baseSelector=this.selector;if(typeof a.username!="string"){if(!a.searchParams)a.searchParams=["q=from:"+a.username.join(" OR from:")];a.username=a.username[0]}typeof a.showTweetFeed=="object"&&e.extend(true,a._tweetFeedConfig,a.showTweetFeed);if(typeof a.showTweetBox=="object"){a._tweetBoxConfig=a.showTweetBox;a.showTweetBox=true}if(typeof a.showConnectButton=="object"){a._connectButtonConfig= a.showConnectButton;a.showConnectButton=true}if(a._tweetFeedConfig.showProfileImages==null)a._tweetFeedConfig.showProfileImages=a.tweetProfileImagePresent;if(a._tweetFeedConfig.showProfileImages==null)a._tweetFeedConfig.showProfileImages=(a.list||a.searchParams)&&a.tweetProfileImageDecorator;if(a._tweetFeedConfig.showUserScreenNames==null){if(a.list||a.searchParams)a._tweetFeedConfig.showUserScreenNames=true;if(!a.tweetUsernameDecorator)a._tweetFeedConfig.showUserScreenNames=false}if(a._tweetFeedConfig.showUserFullNames== null){if(a.list||a.searchParams)a._tweetFeedConfig.showUserFullNames=true;if(!a.tweetUsernameDecorator)a._tweetFeedConfig.showUserFullNames=false}a.count=validateRange(a.count,0,a.searchParams?100:20);a._tweetFeedConfig.autorefresh.interval=Math.max(30,a._tweetFeedConfig.autorefresh.interval);a._tweetFeedConfig.paging._offset=0;a._tweetFeedConfig.paging._limit=a.count;if(a.count==0||!a.showTweetFeed){a.tweetFeedDecorator=null;a.tweetFeedControlsDecorator=null}if(a._tweetFeedConfig.paging.mode=="none")a.tweetFeedControlsDecorator= null;if(!a.showFollowButton)a.followButtonDecorator=null;if(!a.showTweetBox)a.tweetBoxDecorator=null;if(!a.showConnectButton)a.connectButtonDecorator=null;if(!a.showLoginInfo)a.loginInfoDecorator=null;if(!a._tweetFeedConfig.showTimestamp)a.tweetTimestampDecorator=null;if(!a._tweetFeedConfig.showSource)a.tweetSourceDecorator=null;if(!a._tweetFeedConfig.showGeoLocation)a.tweetGeoLocationDecorator=null;if(!a._tweetFeedConfig.showInReplyTo)a.tweetInReplyToDecorator=null;e.ajaxSetup({cache:true});return this.each(function(){a._baseElement= e(this);a._tweetFeedElement=a.tweetFeedDecorator?e(a.tweetFeedDecorator(a)):null;a._tweetFeedControlsElement=a.tweetFeedControlsDecorator?e(a.tweetFeedControlsDecorator(a)):null;a._followButtonElement=a.followButtonDecorator?e(a.followButtonDecorator(a)):null;a._tweetBoxElement=a.tweetBoxDecorator?e(a.tweetBoxDecorator(a)):null;a._connectButtonElement=a.connectButtonDecorator?e(a.connectButtonDecorator(a)):null;a._loginInfoElement=a.loginInfoDecorator?e(a.loginInfoDecorator(a)):null;a.mainDecorator(a); populateTweetFeed(a);populateAnywhereControls(a);bindEventHandlers(a);a._tweetFeedConfig.autorefresh._startTime=(new Date).getTime();startAutorefresh(a);startTimestampRefresh(a)})}};defaultMainDecorator=function(a){a._tweetFeedElement&&a._baseElement.append(a._tweetFeedElement);a._tweetFeedControlsElement&&a._baseElement.append(a._tweetFeedControlsElement);a._connectButtonElement&&a._baseElement.append(a._connectButtonElement);a._loginInfoElement&&a._baseElement.append(a._loginInfoElement);a._followButtonElement&& a._baseElement.append(a._followButtonElement);a._tweetBoxElement&&a._baseElement.append(a._tweetBoxElement)};defaultTweetFeedControlsDecorator=function(a){var b="";if(a._tweetFeedConfig.paging.mode=="prev-next"){if(a.tweetFeedControlsPrevBtnDecorator)b+=a.tweetFeedControlsPrevBtnDecorator(a);if(a.tweetFeedControlsNextBtnDecorator)b+=a.tweetFeedControlsNextBtnDecorator(a)}else if(a._tweetFeedConfig.paging.mode!="endless-scroll")if(a.tweetFeedControlsMoreBtnDecorator)b+=a.tweetFeedControlsMoreBtnDecorator(a); return'<div class="jta-tweet-list-controls">'+b+"</div>"};defaultTweetFeedControlsMoreBtnDecorator=function(){return'<span class="jta-tweet-list-controls-button jta-tweet-list-controls-button-more">More</span>'};defaultTweetFeedControlsPrevBtnDecorator=function(){return'<span class="jta-tweet-list-controls-button jta-tweet-list-controls-button-prev">Prev</span>'};defaultTweetFeedControlsNextBtnDecorator=function(){return'<span class="jta-tweet-list-controls-button jta-tweet-list-controls-button-next">Next</span>'}; defaultTweetFeedAutorefreshTriggerDecorator=function(a,b){var c="";if(b.tweetFeedAutorefreshTriggerContentDecorator)c=b.tweetFeedAutorefreshTriggerContentDecorator(a,b);return'<li class="jta-tweet-list-autorefresh-trigger">'+c+"</li>"};defaultTweetFeedAutorefreshTriggerContentDecorator=function(a){return'<span class="jta-tweet-list-autorefresh-trigger-content">'+(""+a+" new "+(a>1?" tweets":" tweet"))+"</span>"};defaultTweetFeedDecorator=function(){return'<ul class="jta-tweet-list"></ul>'};defaultTweetDecorator= function(a,b){var c="";if(b._tweetFeedConfig.showProfileImages)c+=b.tweetProfileImageDecorator(a,b);if(b.tweetBodyDecorator)c+=b.tweetBodyDecorator(a,b);c+='<div class="jta-clear">&nbsp;</div>';return'<li class="jta-tweet-list-item">'+c+"</li>"};defaultTweetProfileImageDecorator=function(a){a=a.retweeted_status||a;var b=a.user?a.user.screen_name:a.from_user;return'<div class="jta-tweet-profile-image">'+('<a class="jta-tweet-profile-image-link" href="http://twitter.com/'+b+'" target="_blank"><img src="'+ (a.user?a.user.profile_image_url:a.profile_image_url)+'" alt="'+b+'"'+(isAnywherePresent()?"":' title="'+b+'"')+"/></a>")+"</div>"};defaultTweetBodyDecorator=function(a,b){var c="";if(b.tweetTextDecorator)c+=b.tweetTextDecorator(a,b);if(b.tweetAttributesDecorator)c+=b.tweetAttributesDecorator(a,b);return'<div class="jta-tweet-body '+(b._tweetFeedConfig.showProfileImages?"jta-tweet-body-list-profile-image-present":"")+'">'+c+"</div>"};defaultTweetTextDecorator=function(a,b){var c=a.text;if(a.retweeted_status&& (b._tweetFeedConfig.showUserScreenNames||b._tweetFeedConfig.showUserScreenNames==null||b._tweetFeedConfig.showUserFullNames||b._tweetFeedConfig.showUserFullNames==null))c=a.retweeted_status.text;if(b.linkDecorator)c=b.linkDecorator(c,b);if(b.usernameDecorator)c=b.usernameDecorator(c,b);if(b.hashtagDecorator)c=b.hashtagDecorator(c,b);if(b._tweetFeedConfig.showUserScreenNames||b._tweetFeedConfig.showUserFullNames||a.retweeted_status&&(b._tweetFeedConfig.showUserScreenNames==null||b._tweetFeedConfig.showUserFullNames== null))c=b.tweetUsernameDecorator(a,b)+" "+c;return'<span class="jta-tweet-text">'+c+"</span>"};defaultTweetUsernameDecorator=function(a,b){var c=a.retweeted_status||a,d=c.user?c.user.screen_name:c.from_user;c=c.user?c.user.name:null;var f;if(d&&(b._tweetFeedConfig.showUserScreenNames||b._tweetFeedConfig.showUserScreenNames==null&&a.retweeted_status))f='<span class="jta-tweet-user-screen-name"><a class="jta-tweet-user-screen-name-link" href="http://twitter.com/'+d+'" target="_blank">'+d+"</a></span>"; var g;if(c&&(b._tweetFeedConfig.showUserFullNames||b._tweetFeedConfig.showUserFullNames==null&&a.retweeted_status))g='<span class="jta-tweet-user-full-name">'+(f?" (":"")+'<a class="jta-tweet-user-full-name-link" href="http://twitter.com/'+d+'" name="'+d+'" target="_blank">'+c+"</a>"+(f?")":"")+"</span>";d="";if(f)d+=f;if(g){if(f)d+=" ";d+=g}if(f||g)d='<span class="jta-tweet-user-name">'+(a.retweeted_status?"RT ":"")+d+"</span>";return d};defaultTweetAttributesDecorator=function(a,b){var c="";if(b.tweetTimestampDecorator|| b.tweetSourceDecorator||b.tweetGeoLocationDecorator||b.tweetInReplyToDecorator||a.retweeted_status&&b.tweetRetweeterDecorator){c+='<span class="jta-tweet-attributes">';if(b.tweetTimestampDecorator)c+=b.tweetTimestampDecorator(a,b);if(b.tweetSourceDecorator)c+=b.tweetSourceDecorator(a,b);if(b.tweetGeoLocationDecorator)c+=b.tweetGeoLocationDecorator(a,b);if(b.tweetInReplyToDecorator)c+=b.tweetInReplyToDecorator(a,b);if(a.retweeted_status&&b.tweetRetweeterDecorator)c+=b.tweetRetweeterDecorator(a,b); c+="</span>"}return c};defaultTweetTimestampDecorator=function(a,b){var c=a.retweeted_status||a,d=formatDate(c.created_at),f=b.tweetTimestampFormatter(d),g=b.tweetTimestampTooltipFormatter(d);return'<span class="jta-tweet-timestamp"><a class="jta-tweet-timestamp-link" data-timestamp="'+d+'" href="http://twitter.com/'+(c.user?c.user.screen_name:c.from_user)+"/status/"+c.id+'" target="_blank" title="'+g+'">'+f+"</a></span>"};defaultTweetTimestampTooltipFormatter=function(a){return(new Date(a)).toLocaleString()}; defaultTweetTimestampFormatter=function(a){var b=new Date,c=parseInt((b.getTime()-Date.parse(a))/1E3),d="";if(c<60)d+=c+" second"+(c==1?"":"s")+" ago";else if(c<3600){b=parseInt((c+30)/60);d+=b+" minute"+(b==1?"":"s")+" ago"}else if(c<86400){b=parseInt((c+1800)/3600);d+=b+" hour"+(b==1?"":"s")+" ago"}else{a=new Date(a);a.getHours();a.getMinutes();d+=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][a.getMonth()]+" "+a.getDate();if(a.getFullYear()<b.getFullYear())d+=", "+a.getFullYear(); b=parseInt((c+43200)/86400);d+=" ("+b+" day"+(b==1?"":"s")+" ago)"}return d};exTimestampFormatter=function(a){var b=parseInt(((new Date).getTime()-Date.parse(a))/1E3),c="";if(b<60)c+="less than a minute ago";else if(b<3600){b=parseInt((b+30)/60);c+=b+" minute"+(b==1?"":"s")+" ago"}else if(b<86400){b=parseInt((b+1800)/3600);c+="about "+b+" hour"+(b==1?"":"s")+" ago"}else{b=parseInt((b+43200)/86400);c+="about "+b+" day"+(b==1?"":"s")+" ago";a=new Date(a);b="AM";var d=a.getHours();if(d>12){d-=12;b="PM"}var f= a.getMinutes();c+=" ("+d+":"+((f<10?"0":"")+f)+" "+b+" "+(a.getMonth()+1)+"/"+a.getDate()+"/"+a.getFullYear()+")"}return c};defaultTweetSourceDecorator=function(a){return'<span class="jta-tweet-source"> via <span class="jta-tweet-source-link">'+(a.retweeted_status||a).source.replace(/\&lt\;/gi,"<").replace(/\&gt\;/gi,">").replace(/\&quot\;/gi,'"')+"</span></span>"};defaultTweetGeoLocationDecorator=function(a){var b="";a=a.retweeted_status||a;var c;if(a.geo&&a.geo.coordinates)c=a.geo.coordinates.join(); else if(a.place&&a.place.full_name)c=a.place.full_name;if(c){b="here";if(a.place&&a.place.full_name)b=a.place.full_name;b='<span class="jta-tweet-location"> from <a class="jta-tweet-location-link" href="'+("http://maps.google.com/maps?q="+c)+'" target="_blank">'+b+"</a></span>"}return b};defaultTweetInReplyToDecorator=function(a){a=a.retweeted_status||a;var b="";if(a.in_reply_to_status_id&&a.in_reply_to_screen_name)b='<span class="jta-tweet-inreplyto"> <a class="jta-tweet-inreplyto-link" href="http://twitter.com/'+ a.in_reply_to_screen_name+"/status/"+a.in_reply_to_status_id+'" target="_blank">in reply to '+a.in_reply_to_screen_name+"</a></span>";return b};defaultTweetRetweeterDecorator=function(a){var b="";if(a.retweeted_status){b=a.user?a.user.screen_name:a.from_user;a=(a.retweeted_status.retweet_count||0)-1;var c=" and "+a+(a>1?" others":" other");b='<br/><span class="jta-tweet-retweeter">Retweeted by '+('<a class="jta-tweet-retweeter-link" href="http://twitter.com/'+b+'" target="_blank">'+b+"</a>")+(a>0? c:"")+"</span>"}return b};defaultConnectButtonDecorator=function(){return'<div class="jta-connect-button"></div>'};defaultLoginInfoDecorator=function(){return'<div class="jta-login-info"></div>'};defaultLoginInfoContentDecorator=function(a,b){var c="";if(b.isConnected()){c=b.currentUser.data("screen_name");var d=b.currentUser.data("profile_image_url");c='<div class="jta-login-info-profile-image"><a href="http://twitter.com/'+c+'" target="_blank"><img src="'+d+'" alt="'+c+'" title="'+c+'"/></a></div><div class="jta-login-info-block"><div class="jta-login-info-screen-name"><a href="http://twitter.com/'+ c+'" target="_blank">'+c+'</a></div><div class="jta-login-info-sign-out">Sign out</div></div><div class="jta-clear">&nbsp;</div>'}return c};defaultFollowButtonDecorator=function(){return'<div class="jta-follow-button"></div>'};defaultTweetBoxDecorator=function(){return'<div class="jta-tweet-box"></div>'};defaultLinkDecorator=function(a){return a.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1" class="jta-tweet-a jta-tweet-link" target="_blank" rel="nofollow">$1</a>')}; defaultUsernameDecorator=function(a){return isAnywherePresent()?a:a.replace(/@([a-zA-Z0-9_]+)/gi,'@<a href="http://twitter.com/$1" class="jta-tweet-a twitter-anywhere-user" target="_blank" rel="nofollow">$1</a>')};defaultHashtagDecorator=function(a){return a.replace(/#([a-zA-Z0-9_]+)/gi,'<a href="http://search.twitter.com/search?q=%23$1" class="jta-tweet-a jta-tweet-hashtag" title="#$1" target="_blank" rel="nofollow">#$1</a>')};defaultLoadingDecorator=function(){return'<li class="jta-loading">loading ...</li>'}; defaultErrorDecorator=function(a){return'<li class="jta-error">ERROR: '+a+"</li>"};defaultNoDataDecorator=function(){return'<li class="jta-nodata">No more data</li>'};defaultTweetFilter=function(){return true};defaultTweetVisualizer=function(a,b,c){a[c](b)};defaultLoadingIndicatorVisualizer=function(a,b,c,d){defaultVisualizer(a,b,"append","fadeIn",600,"fadeOut",200,d)};defaultAutorefreshTriggerVisualizer=function(a,b,c,d){defaultVisualizer(a,b,"prepend","slideDown",600,"fadeOut",200,d)};defaultVisualizer= function(a,b,c,d,f,g,k,h){var j=function(){h&&h()};if(a){b.hide();a[c](b);b[d](f,j)}else b[g](k,function(){b.remove();j()})};defaultOnDataRequestHandler=function(){return true};defaultOnRateLimitDataHandler=function(){};updateLoginInfoElement=function(a,b){if(a._loginInfoElement&&a.loginInfoContentDecorator){a._loginInfoElement.children().remove();a._loginInfoElement.append(a.loginInfoContentDecorator(a,b));e(a._baseSelector+" .jta-login-info-sign-out").bind("click",function(){twttr.anywhere.signOut()})}}; getFeedUrl=function(a,b){var c="https:"==document.location.protocol?"https:":"http:";if(a.searchParams)c+="//search.twitter.com/search.json?"+(a.searchParams instanceof Array?a.searchParams.join("&"):a.searchParams)+"&rpp=100";else if(a.list)c+="//api.twitter.com/1/"+a.username+"/lists/"+a.list+"/statuses.json?per_page=20";else{c+="//api.twitter.com/1/statuses/user_timeline.json?screen_name="+a.username+"&count=20";if(a._tweetFeedConfig.includeRetweets)c+="&include_rts=true"}if(b)c+=(a._tweetFeedConfig._maxId? "&max_id="+a._tweetFeedConfig._maxId:"")+"&page="+a._tweetFeedConfig._pageParam;c+="&callback=?";return c};isAnywherePresent=function(){return typeof twttr!="undefined"};clearTweetFeed=function(a){a._tweetFeedElement&&a._tweetFeedElement.empty()};populateTweetFeed=function(a){a.tweetDecorator&&a._tweetFeedElement&&getPagedTweets(a,function(b,c){c._tweetFeedConfig._clearBeforePopulate&&clearTweetFeed(c);hideLoadingIndicator(c,function(){e.each(b,function(d,f){c.tweetVisualizer(c._tweetFeedElement, e(c.tweetDecorator(f,c)),"append",c)});if(c._tweetFeedConfig._noData&&c.noDataDecorator&&!c._tweetFeedConfig._noDataElement){c._tweetFeedConfig._noDataElement=e(c.noDataDecorator(c));c._tweetFeedElement.append(c._tweetFeedConfig._noDataElement)}c._tweetFeedConfig._clearBeforePopulate&&c._tweetFeedElement.scrollTop(0);addHovercards(c)})})};populateTweetFeed2=function(a){if(a._tweetFeedElement&&a._autorefreshTweetsCache.length>0)if(a._tweetFeedConfig.autorefresh.mode=="trigger-insert")if(a._tweetFeedConfig.autorefresh._triggerElement)a.tweetFeedAutorefreshTriggerContentDecorator&& a._tweetFeedConfig.autorefresh._triggerElement.html(a.tweetFeedAutorefreshTriggerContentDecorator(a._autorefreshTweetsCache.length,a));else{if(a.tweetFeedAutorefreshTriggerDecorator){a._tweetFeedConfig.autorefresh._triggerElement=e(a.tweetFeedAutorefreshTriggerDecorator(a._autorefreshTweetsCache.length,a));a._tweetFeedConfig.autorefresh._triggerElement.bind("click",function(){a.autorefreshTriggerVisualizer(null,a._tweetFeedConfig.autorefresh._triggerElement,a,function(){insertTriggerTweets(a)});a._tweetFeedConfig.autorefresh._triggerElement= null});a.autorefreshTriggerVisualizer(a._tweetFeedElement,a._tweetFeedConfig.autorefresh._triggerElement,a)}}else insertTriggerTweets(a)};insertTriggerTweets=function(a){if(a.tweetDecorator&&a._autorefreshTweetsCache.length>0){for(;a._autorefreshTweetsCache.length>0;){var b=a._autorefreshTweetsCache.pop();a._tweetsCache.unshift(b);a._tweetFeedConfig.paging._offset++;a.tweetVisualizer(a._tweetFeedElement,e(a.tweetDecorator(b,a)),"prepend",a)}addHovercards(a)}};addHovercards=function(a){isAnywherePresent()&& twttr.anywhere(function(b){b(a._baseSelector+" .jta-tweet-list").hovercards({expanded:a._tweetFeedConfig.expandHovercards});b(a._baseSelector+" .jta-tweet-profile-image img").hovercards({expanded:a._tweetFeedConfig.expandHovercards,username:function(c){return c.alt}});b(a._baseSelector+" .jta-tweet-retweeter-link").hovercards({expanded:a._tweetFeedConfig.expandHovercards,username:function(c){return c.text}});b(a._baseSelector+" .jta-tweet-user-screen-name-link").hovercards({expanded:a._tweetFeedConfig.expandHovercards, username:function(c){return c.text}});b(a._baseSelector+" .jta-tweet-user-full-name-link").hovercards({expanded:a._tweetFeedConfig.expandHovercards,username:function(c){return c.name}})})};populateAnywhereControls=function(a){isAnywherePresent()&&twttr.anywhere(function(b){a.tweetBoxDecorator&&b(a._baseSelector+" .jta-tweet-box").tweetBox(a._tweetBoxConfig);a.followButtonDecorator&&b(a._baseSelector+" .jta-follow-button").followButton(a.username);if(a.connectButtonDecorator){var c=e.extend({authComplete:function(){updateLoginInfoElement(a, b)},signOut:function(){updateLoginInfoElement(a,b)}},a._connectButtonConfig);b(a._baseSelector+" .jta-connect-button").connectButton(c);updateLoginInfoElement(a,b)}})};bindEventHandlers=function(a){if(a.tweetFeedControlsDecorator)if(a._tweetFeedConfig.paging.mode=="prev-next"){e(a._baseSelector+" .jta-tweet-list-controls-button-prev").bind("click",function(){!isLoading(a)&&a._tweetFeedConfig.paging._offset>0&&prevPage(a,true)});e(a._baseSelector+" .jta-tweet-list-controls-button-next").bind("click", function(){isLoading(a)||nextPage(a,true)})}else a._tweetFeedConfig.paging.mode=="endless-scroll"?a._tweetFeedElement.bind("scroll",function(){!isLoading(a)&&e(this)[0].scrollHeight-e(this).scrollTop()==e(this).outerHeight()&&nextPage(a,false)}):e(a._baseSelector+" .jta-tweet-list-controls-button-more").bind("click",function(){isLoading(a)||nextPage(a,false)})};nextPage=function(a,b){doPage(a,b,Math.min(a._tweetFeedConfig.paging._offset+a._tweetFeedConfig.paging._limit,a._tweetsCache.length))};prevPage= function(a,b){doPage(a,b,Math.max(0,a._tweetFeedConfig.paging._offset-a._tweetFeedConfig.paging._limit))};doPage=function(a,b,c){a._tweetFeedConfig.paging._offset=c;a._tweetFeedConfig._clearBeforePopulate=b;populateTweetFeed(a)};startAutorefresh=function(a){if(a._tweetFeedConfig.autorefresh.mode!="none"&&a._tweetFeedConfig.paging.mode!="prev-next"&&a._tweetFeedConfig.autorefresh.duration!=0&&(a._tweetFeedConfig.autorefresh.duration<0||(new Date).getTime()-a._tweetFeedConfig.autorefresh._startTime<= a._tweetFeedConfig.autorefresh.duration*1E3))window.setTimeout(function(){processAutorefresh(a)},a._tweetFeedConfig.autorefresh.interval*1E3)};stopAutorefresh=function(a){a._tweetFeedConfig.autorefresh.duration=0};processAutorefresh=function(a){if(a._tweetFeedConfig.autorefresh.duration!=0){getRateLimitedData(a,true,getFeedUrl(a,false),function(b,c){var d=(b.results||b).slice(0);d.reverse();e.each(d,function(f,g){isTweetInCache(g,c)||c.tweetFilter(g,c)&&c._autorefreshTweetsCache.unshift(g)});populateTweetFeed2(c)}); startAutorefresh(a)}};startTimestampRefresh=function(a){a.tweetTimestampDecorator&&typeof a._tweetFeedConfig.showTimestamp=="object"&&a._tweetFeedConfig.showTimestamp.refreshInterval>0&&window.setTimeout(function(){processTimestampRefresh(a)},a._tweetFeedConfig.showTimestamp.refreshInterval*1E3)};processTimestampRefresh=function(a){e.each(a._tweetFeedElement.find(".jta-tweet-timestamp-link"),function(b,c){var d=e(c).attr("data-timestamp");e(c).html(a.tweetTimestampFormatter(d))});startTimestampRefresh(a)}; isTweetInCache=function(a,b){for(var c=b._tweetsCache.length,d=0;d<c;d++)if(a.id==b._tweetsCache[d].id)return true;return false};showLoadingIndicator=function(a){if(a._tweetFeedElement&&a.loadingDecorator&&!a._loadingIndicatorElement){a._loadingIndicatorElement=e(a.loadingDecorator(a));a.loadingIndicatorVisualizer(a._tweetFeedElement,a._loadingIndicatorElement,a,null);a._tweetFeedElement.scrollTop(1E6)}};hideLoadingIndicator=function(a,b){if(a._loadingIndicatorElement){a.loadingIndicatorVisualizer(null, a._loadingIndicatorElement,a,b);a._loadingIndicatorElement=null}else b&&b()};isLoading=function(a){return a._loadingIndicatorElement!=null};formatDate=function(a){return a.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i,"$1,$2$4$3")};validateRange=function(a,b,c){if(a<b)a=b;if(a>c)a=c;return a};showError=function(a,b){a.errorDecorator&&a._tweetFeedElement&&a._tweetFeedElement.append(a.errorDecorator(b,a))};getPagedTweets=function(a,b){a._tweetFeedConfig._recLevel=0;getRecPagedTweets(a,a._tweetFeedConfig.paging._offset, a._tweetFeedConfig.paging._limit,b)};getRecPagedTweets=function(a,b,c,d){++a._tweetFeedConfig._recLevel;if(b+c<=a._tweetsCache.length||a._tweetFeedConfig._recLevel>3||a._tweetFeedConfig._noData){if(b+c>a._tweetsCache.length)c=Math.max(0,a._tweetsCache.length-b);for(var f=[],g=0;g<c;g++)f[g]=a._tweetsCache[b+g];d(f,a)}else{++a._tweetFeedConfig._pageParam;getRateLimitedData(a,false,getFeedUrl(a,true),function(k,h){var j=k.results||k;if(j.length==0)h._tweetFeedConfig._noData=true;else e.each(j,function(l, i){if(i.id_str)i.id=i.id_str;if(i.in_reply_to_status_id_str)i.in_reply_to_status_id=i.in_reply_to_status_id_str;if(!h._tweetFeedConfig._maxId)h._tweetFeedConfig._maxId=i.id;h.tweetFilter(i,h)&&h._tweetsCache.push(i)});getRecPagedTweets(h,b,c,d)})}};getRateLimitedData=function(a,b,c,d){getRateLimit(a,function(f){if(f&&f.remaining_hits<=0){a._stats.rateLimitPreventionCount++;hideLoadingIndicator(a,null)}else getData(a,b,c,d)})};getData=function(a,b,c,d){a._stats.dataRequestCount++;if(a.onDataRequestHandler(a._stats, a)){b||showLoadingIndicator(a);e.getJSON(c,function(f){f.error?showError(a,f.error):d(f,a)})}else hideLoadingIndicator(a,null)};getRateLimit=function(a,b){e.getJSON("http://api.twitter.com/1/account/rate_limit_status.json?callback=?",function(c){a._stats.rateLimit=c;a.onRateLimitDataHandler(a._stats,a);b(c)})}})(jQuery);

/**
 * Plugin: jquery.zRSSFeed
 * 
 * Version: 1.1.3
 * (c) Copyright 2010-2011, Zazar Ltd
 * 
 * Description: jQuery plugin for display of RSS feeds via Google Feed API
 *              (Based on original plugin jGFeed by jQuery HowTo. Filesize function by Cary Dunn.)
 * 
 * History:
 * 1.1.3 - Check for valid published date
 * 1.1.2 - Added user callback function due to issue with ajaxStop after jQuery 1.4.2
 * 1.1.1 - Correction to null xml entries and support for media with jQuery < 1.5
 * 1.1.0 - Added support for media in enclosure tags
 * 1.0.3 - Added feed link target
 * 1.0.2 - Fixed issue with GET parameters (Seb Dangerfield) and SSL option
 * 1.0.1 - Corrected issue with multiple instances
 *
 **/

(function($){

	$.fn.rssfeed = function(url, options, fn) {	
	
		// Set pluign defaults
		var defaults = {
			limit: 10,
			header: true,
			titletag: 'h4',
			date: true,
			content: true,
			snippet: true,
			showerror: true,
			errormsg: '',
			key: null,
			ssl: false,
			linktarget: '_self'
		};  
		var options = $.extend(defaults, options); 
		
		// Functions
		return this.each(function(i, e) {
			var $e = $(e);
			var s = '';

			// Check for SSL protocol
			if (options.ssl) s = 's';
			
			// Add feed class to user div
			if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
			
			// Check for valid url
			if(url == null) return false;
			
			// Create Google Feed API address
			var api = "http"+ s +"://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + encodeURIComponent(url);
			if (options.limit != null) api += "&num=" + options.limit;
			if (options.key != null) api += "&key=" + options.key;
			api += "&output=json_xml"

			// Send request
			$.getJSON(api, function(data){
				
				// Check for error
				if (data.responseStatus == 200) {
	
					// Process the feeds
					_process(e, data.responseData, options);

					// Optional user callback function
					if ($.isFunction(fn)) fn.call(this,$e);
					
				} else {

					// Handle error if required
					if (options.showerror)
						if (options.errormsg != '') {
							var msg = options.errormsg;
						} else {
							var msg = data.responseDetails;
						};
						$(e).html('<div class="rssError"><p>'+ msg +'</p></div>');
				};
			});				
		});
	};
	
	// Function to create HTML result
	var _process = function(e, data, options) {

		// Get JSON feed data
		var feeds = data.feed;
		if (!feeds) {
			return false;
		}
		var html = '';	
		var row = 'odd';
		
		// Get XML data for media (parseXML not used as requires 1.5+)
		var xml = getXMLDocument(data.xmlString);
		var xmlEntries = xml.getElementsByTagName('item');
		
		// Add header if required
		if (options.header)
			html +=	'<div class="rssHeader">' +
				'<a href="'+feeds.link+'" title="'+ feeds.description +'">'+ feeds.title +'</a>' +
				'</div>';
			
		// Add body
		html += '<div class="rssBody">' +
			'<ul>';
		
		// Add feeds
		for (var i=0; i<feeds.entries.length; i++) {
			
			// Get individual feed
			var entry = feeds.entries[i];
			var pubDate;

			// Format published date
			if (entry.publishedDate) {
				var entryDate = new Date(entry.publishedDate);
				var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
			}
			
			// Add feed row
			html += '<li class="rssRow '+row+'">' + 
				'<'+ options.titletag +'><a href="'+ entry.link +'" title="View this feed at '+ feeds.title +'" target="'+ options.linktarget +'">'+ entry.title +'</a></'+ options.titletag +'>'
			if (options.date && pubDate) html += '<div>'+ pubDate +'</div>'
			if (options.content) {
			
				// Use feed snippet if available and optioned
				if (options.snippet && entry.contentSnippet != '') {
					var content = entry.contentSnippet;
				} else {
					var content = entry.content;
				}
				
				html += '<p>'+ content +'</p>'
			}
			
			// Add any media
			if(xmlEntries.length > 0) {
				var xmlMedia = xmlEntries[i].getElementsByTagName('enclosure');
				if (xmlMedia.length > 0) {
					html += '<div class="rssMedia"><div>Media files</div><ul>'
					for (var m=0; m<xmlMedia.length; m++) {
						var xmlUrl = xmlMedia[m].getAttribute("url");
						var xmlType = xmlMedia[m].getAttribute("type");
						var xmlSize = xmlMedia[m].getAttribute("length");
						html += '<li><a href="'+ xmlUrl +'" title="Download this media">'+ xmlUrl.split('/').pop() +'</a> ('+ xmlType +', '+ formatFilesize(xmlSize) +')</li>';
					}
					html += '</ul></div>'
				}
				html += '</li>';
			}
			
			// Alternate row classes
			if (row == 'odd') {
				row = 'even';
			} else {
				row = 'odd';
			}			
		}
		
		html += '</ul>' +
			'</div>'
		
		$(e).html(html);
	};
	
	function formatFilesize(bytes) {
		var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
		var e = Math.floor(Math.log(bytes)/Math.log(1024));
		return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
	}

	function getXMLDocument(string) {
		var browser = navigator.appName;
		var xml;
		if (browser == 'Microsoft Internet Explorer') {
			xml = new ActiveXObject('Microsoft.XMLDOM');
			xml.async = 'false'
			xml.loadXML(string);
		} else {
			xml = (new DOMParser()).parseFromString(string, 'text/xml');
		}
		return xml;
	}

})(jQuery);



/**
 * jQuery bxSlider v3.0
 * http://bxslider.com
 *
 * Copyright 2011, Steven Wanderski
 * http://bxcreative.com
 *
 * Free to use and abuse under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */


(function($){
	
	$.fn.bxSlider = function(options){		
				
		var defaults = {
			mode: 'horizontal',									// 'horizontal', 'vertical', 'fade'
			infiniteLoop: true,									// true, false - display first slide after last
			hideControlOnEnd: false,						// true, false - if true, will hide 'next' control on last slide and 'prev' control on first
			controls: true,											// true, false - previous and next controls
			speed: 500,													// integer - in ms, duration of time slide transitions will occupy
			easing: 'swing',                    // used with jquery.easing.1.3.js - see http://gsgd.co.uk/sandbox/jquery/easing/ for available options
			pager: false,												// true / false - display a pager
			pagerSelector: null,								// jQuery selector - element to contain the pager. ex: '#pager'
			pagerType: 'full',									// 'full', 'short' - if 'full' pager displays 1,2,3... if 'short' pager displays 1 / 4
			pagerLocation: 'bottom',						// 'bottom', 'top' - location of pager
			pagerShortSeparator: '/',						// string - ex: 'of' pager would display 1 of 4
			pagerActiveClass: 'pager-active',		// string - classname attached to the active pager link
			nextText: 'next',										// string - text displayed for 'next' control
			nextImage: '',											// string - filepath of image used for 'next' control. ex: 'images/next.jpg'
			nextSelector: null,									// jQuery selector - element to contain the next control. ex: '#next'
			prevText: 'prev',										// string - text displayed for 'previous' control
			prevImage: '',											// string - filepath of image used for 'previous' control. ex: 'images/prev.jpg'
			prevSelector: null,									// jQuery selector - element to contain the previous control. ex: '#next'
			captions: false,										// true, false - display image captions (reads the image 'title' tag)
			captionsSelector: null,							// jQuery selector - element to contain the captions. ex: '#captions'
			auto: false,												// true, false - make slideshow change automatically
			autoDirection: 'next',							// 'next', 'prev' - direction in which auto show will traverse
			autoControls: false,								// true, false - show 'start' and 'stop' controls for auto show
			autoControlsSelector: null,					// jQuery selector - element to contain the auto controls. ex: '#auto-controls'
			autoStart: true,										// true, false - if false show will wait for 'start' control to activate
			autoHover: false,										// true, false - if true show will pause on mouseover
			autoDelay: 0,                       // integer - in ms, the amount of time before starting the auto show
			pause: 3000,												// integer - in ms, the duration between each slide transition
			startText: 'start',									// string - text displayed for 'start' control
			startImage: '',											// string - filepath of image used for 'start' control. ex: 'images/start.jpg'
			stopText: 'stop',										// string - text displayed for 'stop' control
			stopImage: '',											// string - filepath of image used for 'stop' control. ex: 'images/stop.jpg'
			ticker: false,											// true, false - continuous motion ticker mode (think news ticker)
																					// note: autoControls, autoControlsSelector, and autoHover apply to ticker!
			tickerSpeed: 5000,								  // float - use value between 1 and 5000 to determine ticker speed - the smaller the value the faster the ticker speed
			tickerDirection: 'next',						// 'next', 'prev' - direction in which ticker show will traverse
			tickerHover: false,                 // true, false - if true ticker will pause on mouseover
			wrapperClass: 'bx-wrapper',					// string - classname attached to the slider wraper
			startingSlide: 0, 									// integer - show will start on specified slide. note: slides are zero based!
			displaySlideQty: 1,									// integer - number of slides to display at once
			moveSlideQty: 1,										// integer - number of slides to move at once
			randomStart: false,									// true, false - if true show will start on a random slide
			onBeforeSlide: function(){},				// function(currentSlideNumber, totalSlideQty, currentSlideHtmlObject) - advanced use only! see the tutorial here: http://bxslider.com/custom-pager
			onAfterSlide: function(){},					// function(currentSlideNumber, totalSlideQty, currentSlideHtmlObject) - advanced use only! see the tutorial here: http://bxslider.com/custom-pager
			onLastSlide: function(){},					// function(currentSlideNumber, totalSlideQty, currentSlideHtmlObject) - advanced use only! see the tutorial here: http://bxslider.com/custom-pager
			onFirstSlide: function(){},					// function(currentSlideNumber, totalSlideQty, currentSlideHtmlObject) - advanced use only! see the tutorial here: http://bxslider.com/custom-pager
			onNextSlide: function(){},					// function(currentSlideNumber, totalSlideQty, currentSlideHtmlObject) - advanced use only! see the tutorial here: http://bxslider.com/custom-pager
			onPrevSlide: function(){},					// function(currentSlideNumber, totalSlideQty, currentSlideHtmlObject) - advanced use only! see the tutorial here: http://bxslider.com/custom-pager
			buildPager: null										// function(slideIndex, slideHtmlObject){ return string; } - advanced use only! see the tutorial here: http://bxslider.com/custom-pager
		}
		
		var options = $.extend(defaults, options);
		
		// cache the base element
		var base = this;
		// initialize (and localize) all variables
		var $parent = '';
		var $origElement = '';
		var $children = '';
		var $outerWrapper = '';
		var $firstChild = '';
		var childrenWidth = '';
		var childrenOuterWidth = '';
		var wrapperWidth = '';
		var wrapperHeight = '';
		var $pager = '';	
		var interval = '';
		var $autoControls = '';
		var $stopHtml = '';
		var $startContent = '';
		var $stopContent = '';
		var autoPlaying = true;
		var loaded = false;
		var childrenMaxWidth = 0;
		var childrenMaxHeight = 0;
		var currentSlide = 0;	
		var origLeft = 0;
		var origTop = 0;
		var origShowWidth = 0;
		var origShowHeight = 0;
		var tickerLeft = 0;
		var tickerTop = 0;
		var isWorking = false;
    
		var firstSlide = 0;
		var lastSlide = $children.length - 1;
		
						
		// PUBLIC FUNCTIONS
						
		/**
		 * Go to specified slide
		 */		
		this.goToSlide = function(number, stopAuto){
			if(!isWorking){
				isWorking = true;
				// set current slide to argument
				currentSlide = number;
				options.onBeforeSlide(currentSlide, $children.length, $children.eq(currentSlide));
				// check if stopAuto argument is supplied
				if(typeof(stopAuto) == 'undefined'){
					var stopAuto = true;
				}
				if(stopAuto){
					// if show is auto playing, stop it
					if(options.auto){
						base.stopShow(true);
					}
				}			
				slide = number;
				// check for first slide callback
				if(slide == firstSlide){
					options.onFirstSlide(currentSlide, $children.length, $children.eq(currentSlide));
				}
				// check for last slide callback
				if(slide == lastSlide){
					options.onLastSlide(currentSlide, $children.length, $children.eq(currentSlide));
				}
				// horizontal
				if(options.mode == 'horizontal'){
					$parent.animate({'left': '-'+getSlidePosition(slide, 'left')+'px'}, options.speed, options.easing, function(){
						isWorking = false;
						// perform the callback function
						options.onAfterSlide(currentSlide, $children.length, $children.eq(currentSlide));
					});
				// vertical
				}else if(options.mode == 'vertical'){
					$parent.animate({'top': '-'+getSlidePosition(slide, 'top')+'px'}, options.speed, options.easing, function(){
						isWorking = false;
						// perform the callback function
						options.onAfterSlide(currentSlide, $children.length, $children.eq(currentSlide));
					});			
				// fade	
				}else if(options.mode == 'fade'){
					setChildrenFade();
				}
				// check to remove controls on last/first slide
				checkEndControls();
				// accomodate multi slides
				if(options.moveSlideQty > 1){
					number = Math.floor(number / options.moveSlideQty);
				}
				// make the current slide active
				makeSlideActive(number);
				// display the caption
				showCaptions();
			}
		}
		
		/**
		 * Go to next slide
		 */		
		this.goToNextSlide = function(stopAuto){
			// check if stopAuto argument is supplied
			if(typeof(stopAuto) == 'undefined'){
				var stopAuto = true;
			}
			if(stopAuto){
				// if show is auto playing, stop it
				if(options.auto){
					base.stopShow(true);
				}
			}			
			// makes slideshow finite
			if(!options.infiniteLoop){
				if(!isWorking){
					var slideLoop = false;
					// make current slide the old value plus moveSlideQty
					currentSlide = (currentSlide + (options.moveSlideQty));
					// if current slide has looped on itself
					if(currentSlide <= lastSlide){
						checkEndControls();
						// next slide callback
						options.onNextSlide(currentSlide, $children.length, $children.eq(currentSlide));
						// move to appropriate slide
						base.goToSlide(currentSlide);						
					}else{
						currentSlide -= options.moveSlideQty;
					}
				} // end if(!isWorking)		
			}else{ 
				if(!isWorking){
					isWorking = true;					
					var slideLoop = false;
					// make current slide the old value plus moveSlideQty
					currentSlide = (currentSlide + options.moveSlideQty);
					// if current slide has looped on itself
					if(currentSlide > lastSlide){
						currentSlide = currentSlide % $children.length;
						slideLoop = true;
					}
					// next slide callback
					options.onNextSlide(currentSlide, $children.length, $children.eq(currentSlide));
					// slide before callback
					options.onBeforeSlide(currentSlide, $children.length, $children.eq(currentSlide));
					if(options.mode == 'horizontal'){						
						// get the new 'left' property for $parent
						var parentLeft = (options.moveSlideQty * childrenOuterWidth);
						// animate to the new 'left'
						$parent.animate({'left': '-='+parentLeft+'px'}, options.speed, options.easing, function(){
							isWorking = false;
							// if its time to loop, reset the $parent
							if(slideLoop){
								$parent.css('left', '-'+getSlidePosition(currentSlide, 'left')+'px');
							}
							// perform the callback function
							options.onAfterSlide(currentSlide, $children.length, $children.eq(currentSlide));
						});
					}else if(options.mode == 'vertical'){
						// get the new 'left' property for $parent
						var parentTop = (options.moveSlideQty * childrenMaxHeight);
						// animate to the new 'left'
						$parent.animate({'top': '-='+parentTop+'px'}, options.speed, options.easing, function(){
							isWorking = false;
							// if its time to loop, reset the $parent
							if(slideLoop){
								$parent.css('top', '-'+getSlidePosition(currentSlide, 'top')+'px');
							}
							// perform the callback function
							options.onAfterSlide(currentSlide, $children.length, $children.eq(currentSlide));
						});
					}else if(options.mode == 'fade'){
						setChildrenFade();
					}					
					// make the current slide active
					if(options.moveSlideQty > 1){
						makeSlideActive(Math.ceil(currentSlide / options.moveSlideQty));
					}else{
						makeSlideActive(currentSlide);
					}
					// display the caption
					showCaptions();
				} // end if(!isWorking)
				
			}	
		} // end function
		
		/**
		 * Go to previous slide
		 */		
		this.goToPreviousSlide = function(stopAuto){
			// check if stopAuto argument is supplied
			if(typeof(stopAuto) == 'undefined'){
				var stopAuto = true;
			}
			if(stopAuto){
				// if show is auto playing, stop it
				if(options.auto){
					base.stopShow(true);
				}
			}			
			// makes slideshow finite
			if(!options.infiniteLoop){	
				if(!isWorking){
					var slideLoop = false;
					// make current slide the old value plus moveSlideQty
					currentSlide = currentSlide - options.moveSlideQty;
					// if current slide has looped on itself
					if(currentSlide < 0){
						currentSlide = 0;
						// if specified, hide the control on the last slide
						if(options.hideControlOnEnd){
							$('.bx-prev', $outerWrapper).hide();
						}
					}
					checkEndControls();
					// next slide callback
					options.onPrevSlide(currentSlide, $children.length, $children.eq(currentSlide));
					// move to appropriate slide
					base.goToSlide(currentSlide);
				}							
			}else{
				if(!isWorking){
					isWorking = true;			
					var slideLoop = false;
					// make current slide the old value plus moveSlideQty
					currentSlide = (currentSlide - (options.moveSlideQty));
					// if current slide has looped on itself
					if(currentSlide < 0){
						negativeOffset = (currentSlide % $children.length);
						if(negativeOffset == 0){
							currentSlide = 0;
						}else{
							currentSlide = ($children.length) + negativeOffset; 
						}
						slideLoop = true;
					}
					// next slide callback
					options.onPrevSlide(currentSlide, $children.length, $children.eq(currentSlide));
					// slide before callback
					options.onBeforeSlide(currentSlide, $children.length, $children.eq(currentSlide));
					if(options.mode == 'horizontal'){
						// get the new 'left' property for $parent
						var parentLeft = (options.moveSlideQty * childrenOuterWidth);
						// animate to the new 'left'
						$parent.animate({'left': '+='+parentLeft+'px'}, options.speed, options.easing, function(){
							isWorking = false;
							// if its time to loop, reset the $parent
							if(slideLoop){
								$parent.css('left', '-'+getSlidePosition(currentSlide, 'left')+'px');
							}
							// perform the callback function
							options.onAfterSlide(currentSlide, $children.length, $children.eq(currentSlide));
						});
					}else if(options.mode == 'vertical'){
						// get the new 'left' property for $parent
						var parentTop = (options.moveSlideQty * childrenMaxHeight);
						// animate to the new 'left'
						$parent.animate({'top': '+='+parentTop+'px'}, options.speed, options.easing, function(){
							isWorking = false;
							// if its time to loop, reset the $parent
							if(slideLoop){
								$parent.css('top', '-'+getSlidePosition(currentSlide, 'top')+'px');
							}
							// perform the callback function
							options.onAfterSlide(currentSlide, $children.length, $children.eq(currentSlide));
						});
					}else if(options.mode == 'fade'){
						setChildrenFade();
					}					
					// make the current slide active
					if(options.moveSlideQty > 1){
						makeSlideActive(Math.ceil(currentSlide / options.moveSlideQty));
					}else{
						makeSlideActive(currentSlide);
					}
					// display the caption
					showCaptions();
				} // end if(!isWorking)				
			}
		} // end function
		
		/**
		 * Go to first slide
		 */		
		this.goToFirstSlide = function(stopAuto){
			// check if stopAuto argument is supplied
			if(typeof(stopAuto) == 'undefined'){
				var stopAuto = true;
			}
			base.goToSlide(firstSlide, stopAuto);
		}
		
		/**
		 * Go to last slide
		 */		
		this.goToLastSlide = function(){
			// check if stopAuto argument is supplied
			if(typeof(stopAuto) == 'undefined'){
				var stopAuto = true;
			}
			base.goToSlide(lastSlide, stopAuto);
		}
		
		/**
		 * Get the current slide
		 */		
		this.getCurrentSlide = function(){
			return currentSlide;
		}
		
		/**
		 * Get the total slide count
		 */		
		this.getSlideCount = function(){
			return $children.length;
		}
		
		/**
		 * Stop the slideshow
		 */		
		this.stopShow = function(changeText){
			clearInterval(interval);
			// check if changeText argument is supplied
			if(typeof(changeText) == 'undefined'){
				var changeText = true;
			}
			if(changeText && options.autoControls){
				$autoControls.html($startContent).removeClass('stop').addClass('start');
				autoPlaying = false;
			}
		}
		
		/**
		 * Start the slideshow
		 */		
		this.startShow = function(changeText){
			// check if changeText argument is supplied
			if(typeof(changeText) == 'undefined'){
				var changeText = true;
			}
			setAutoInterval();
			if(changeText && options.autoControls){
				$autoControls.html($stopContent).removeClass('start').addClass('stop');
				autoPlaying = true;
			}
		}
		
		/**
		 * Stops the ticker
		 */		
		this.stopTicker = function(changeText){
			$parent.stop();
			// check if changeText argument is supplied
			if(typeof(changeText) == 'undefined'){
				var changeText = true;
			}
			if(changeText && options.ticker){
				$autoControls.html($startContent).removeClass('stop').addClass('start');
				autoPlaying = false;
			}			
		}
		
		/**
		 * Starts the ticker
		 */		
		this.startTicker = function(changeText){
			if(options.mode == 'horizontal'){
				if(options.tickerDirection == 'next'){
					// get the 'left' property where the ticker stopped
					var stoppedLeft = parseInt($parent.css('left'));
					// calculate the remaining distance the show must travel until the loop
					var remainingDistance = (origShowWidth + stoppedLeft) + $children.eq(0).width();			
				}else if(options.tickerDirection == 'prev'){
					// get the 'left' property where the ticker stopped
					var stoppedLeft = -parseInt($parent.css('left'));
					// calculate the remaining distance the show must travel until the loop
					var remainingDistance = (stoppedLeft) - $children.eq(0).width();
				}
				// calculate the speed ratio to seamlessly finish the loop
				var finishingSpeed = (remainingDistance * options.tickerSpeed) / origShowWidth;
				// call the show
				moveTheShow(tickerLeft, remainingDistance, finishingSpeed);					
			}else if(options.mode == 'vertical'){
				if(options.tickerDirection == 'next'){
					// get the 'top' property where the ticker stopped
					var stoppedTop = parseInt($parent.css('top'));
					// calculate the remaining distance the show must travel until the loop
					var remainingDistance = (origShowHeight + stoppedTop) + $children.eq(0).height();			
				}else if(options.tickerDirection == 'prev'){
					// get the 'left' property where the ticker stopped
					var stoppedTop = -parseInt($parent.css('top'));
					// calculate the remaining distance the show must travel until the loop
					var remainingDistance = (stoppedTop) - $children.eq(0).height();
				}
				// calculate the speed ratio to seamlessly finish the loop
				var finishingSpeed = (remainingDistance * options.tickerSpeed) / origShowHeight;
				// call the show
				moveTheShow(tickerTop, remainingDistance, finishingSpeed);
				// check if changeText argument is supplied
				if(typeof(changeText) == 'undefined'){
					var changeText = true;
				}
				if(changeText && options.ticker){
					$autoControls.html($stopContent).removeClass('start').addClass('stop');
					autoPlaying = true;
				}						
			}
		}
				
		/**
		 * Initialize a new slideshow
		 */		
		this.initShow = function(){
			
			// reinitialize all variables
			// base = this;
			$parent = $(this);
			$origElement = $parent.clone();
			$children = $parent.children();
			$outerWrapper = '';
			$firstChild = $parent.children(':first');
			childrenWidth = $firstChild.width();
			childrenMaxWidth = 0;
			childrenOuterWidth = $firstChild.outerWidth();
			childrenMaxHeight = 0;
			wrapperWidth = getWrapperWidth();
			wrapperHeight = getWrapperHeight();
			isWorking = false;
			$pager = '';	
			currentSlide = 0;	
			origLeft = 0;
			origTop = 0;
			interval = '';
			$autoControls = '';
			$stopHtml = '';
			$startContent = '';
			$stopContent = '';
			autoPlaying = true;
			loaded = false;
			origShowWidth = 0;
			origShowHeight = 0;
			tickerLeft = 0;
			tickerTop = 0;
      
			firstSlide = 0;
			lastSlide = $children.length - 1;
						
			// get the largest child's height and width
			$children.each(function(index) {
			  if($(this).outerHeight() > childrenMaxHeight){
					childrenMaxHeight = $(this).outerHeight();
				}
				if($(this).outerWidth() > childrenMaxWidth){
					childrenMaxWidth = $(this).outerWidth();
				}
			});

			// get random slide number
			if(options.randomStart){
				var randomNumber = Math.floor(Math.random() * $children.length);
				currentSlide = randomNumber;
				origLeft = childrenOuterWidth * (options.moveSlideQty + randomNumber);
				origTop = childrenMaxHeight * (options.moveSlideQty + randomNumber);
			// start show at specific slide
			}else{
				currentSlide = options.startingSlide;
				origLeft = childrenOuterWidth * (options.moveSlideQty + options.startingSlide);
				origTop = childrenMaxHeight * (options.moveSlideQty + options.startingSlide);
			}
						
			// set initial css
			initCss();
			
			// check to show pager
			if(options.pager && !options.ticker){
				if(options.pagerType == 'full'){
					showPager('full');
				}else if(options.pagerType == 'short'){
					showPager('short');
				}
			}
						
			// check to show controls
			if(options.controls && !options.ticker){
				setControlsVars();
			}
						
			// check if auto
			if(options.auto || options.ticker){
				// check if auto controls are displayed
				if(options.autoControls){
					setAutoControlsVars();
				}
				// check if show should auto start
				if(options.autoStart){
					// check if autostart should delay
					setTimeout(function(){
						base.startShow(true);
					}, options.autoDelay);
				}else{
					base.stopShow(true);
				}
				// check if show should pause on hover
				if(options.autoHover && !options.ticker){
					setAutoHover();
				}
			}						
			// make the starting slide active
			if(options.moveSlideQty > 1){
				makeSlideActive(Math.ceil(currentSlide / options.moveSlideQty));
			}else{			
				makeSlideActive(currentSlide);			
			}
			// check for finite show and if controls should be hidden
			checkEndControls();
			// show captions
			if(options.captions){
				showCaptions();
			}
			// perform the callback function
			options.onAfterSlide(currentSlide, $children.length, $children.eq(currentSlide));
		}
		
		/**
		 * Destroy the current slideshow
		 */		
		this.destroyShow = function(){			
			// stop the auto show
			clearInterval(interval);
			// remove any controls / pagers that have been appended
			$('.bx-next, .bx-prev, .bx-pager, .bx-auto', $outerWrapper).remove();
			// unwrap all bx-wrappers
			$parent.unwrap().unwrap().removeAttr('style');
			// remove any styles that were appended
			$parent.children().removeAttr('style').not('.pager').remove();
			// remove any childrent that were appended
			$children.removeClass('pager');
			
		}
		
		/**
		 * Reload the current slideshow
		 */		
		this.reloadShow = function(){
			base.destroyShow();
			base.initShow();
		}
		
		// PRIVATE FUNCTIONS
		
		/**
		 * Creates all neccessary styling for the slideshow
		 */		
		function initCss(){
			// layout the children
			setChildrenLayout(options.startingSlide);
			// CSS for horizontal mode
			if(options.mode == 'horizontal'){
				// wrap the <ul> in div that acts as a window and make the <ul> uber wide
				$parent
				.wrap('<div class="'+options.wrapperClass+'" style="width:'+wrapperWidth+'px; position:relative;"></div>')
				.wrap('<div class="bx-window" style="position:relative; overflow:hidden; width:'+wrapperWidth+'px;"></div>')
				.css({
				  width: '999999px',
				  position: 'relative',
					left: '-'+(origLeft)+'px'
				});
				$parent.children().css({
					width: childrenWidth,
				  'float': 'left',
				  listStyle: 'none'
				});					
				$outerWrapper = $parent.parent().parent();
				$children.addClass('pager');
			// CSS for vertical mode
			}else if(options.mode == 'vertical'){
				// wrap the <ul> in div that acts as a window and make the <ul> uber tall
				$parent
				.wrap('<div class="'+options.wrapperClass+'" style="width:'+childrenMaxWidth+'px; position:relative;"></div>')
				.wrap('<div class="bx-window" style="width:'+childrenMaxWidth+'px; height:'+wrapperHeight+'px; position:relative; overflow:hidden;"></div>')
				.css({
				  height: '999999px',
				  position: 'relative',
					top: '-'+(origTop)+'px'
				});
				$parent.children().css({
				  listStyle: 'none',
					height: childrenMaxHeight
				});					
				$outerWrapper = $parent.parent().parent();
				$children.addClass('pager');
			// CSS for fade mode
			}else if(options.mode == 'fade'){
				// wrap the <ul> in div that acts as a window
				$parent
				.wrap('<div class="'+options.wrapperClass+'" style="width:'+childrenMaxWidth+'px; position:relative;"></div>')
				.wrap('<div class="bx-window" style=" width:'+childrenMaxWidth+'px; position:relative; overflow:hidden;"></div>');
				$parent.children().css({
				  listStyle: 'none',
				  position: 'absolute',
					top: 0,
					left: 0,
					zIndex: 98
				});					
				$outerWrapper = $parent.parent().parent();
				$children.not(':eq('+currentSlide+')').fadeTo(0, 0);
				$children.eq(currentSlide).css('zIndex', 99);
			}
			// if captions = true setup a div placeholder
			if(options.captions && options.captionsSelector == null){
				$outerWrapper.append('<div class="bx-captions"></div>');
			}			
		}
		
		/**
		 * Depending on mode, lays out children in the proper setup
		 */		
		function setChildrenLayout(){			
			// lays out children for horizontal or vertical modes
			if(options.mode == 'horizontal' || options.mode == 'vertical'){
								
				// get the children behind
				var $prependedChildren = getArraySample($children, 0, options.moveSlideQty, 'backward');
				
				// add each prepended child to the back of the original element
				$.each($prependedChildren, function(index) {
					$parent.prepend($(this));
				});			
				
				// total number of slides to be hidden after the window
				var totalNumberAfterWindow = ($children.length + options.moveSlideQty) - 1;
				// number of original slides hidden after the window
				var pagerExcess = $children.length - options.displaySlideQty;
				// number of slides to append to the original hidden slides
				var numberToAppend = totalNumberAfterWindow - pagerExcess;
				// get the sample of extra slides to append
				var $appendedChildren = getArraySample($children, 0, numberToAppend, 'forward');
				
				if(options.infiniteLoop){
					// add each appended child to the front of the original element
					$.each($appendedChildren, function(index) {
						$parent.append($(this));
					});
				}
			}
		}
		
		/**
		 * Sets all variables associated with the controls
		 */		
		function setControlsVars(){
			// check if text or images should be used for controls
			// check "next"
			if(options.nextImage != ''){
				nextContent = options.nextImage;
				nextType = 'image';
			}else{
				nextContent = options.nextText;
				nextType = 'text';
			}
			// check "prev"
			if(options.prevImage != ''){
				prevContent = options.prevImage;
				prevType = 'image';
			}else{
				prevContent = options.prevText;
				prevType = 'text';
			}
			// show the controls
			showControls(nextType, nextContent, prevType, prevContent);
		}			
		
		/**
		 * Puts slideshow into auto mode
		 *
		 * @param int pause number of ms the slideshow will wait between slides 
		 * @param string direction 'forward', 'backward' sets the direction of the slideshow (forward/backward)
		 * @param bool controls determines if start/stop controls will be displayed
		 */		
		function setAutoInterval(){
			if(options.auto){
				// finite loop
				if(!options.infiniteLoop){
					if(options.autoDirection == 'next'){
						interval = setInterval(function(){
							currentSlide += options.moveSlideQty;
							// if currentSlide has exceeded total number
							if(currentSlide > lastSlide){
								currentSlide = currentSlide % $children.length;
							}
							base.goToSlide(currentSlide, false);
						}, options.pause);
					}else if(options.autoDirection == 'prev'){
						interval = setInterval(function(){
							currentSlide -= options.moveSlideQty;
							// if currentSlide is smaller than zero
							if(currentSlide < 0){
								negativeOffset = (currentSlide % $children.length);
								if(negativeOffset == 0){
									currentSlide = 0;
								}else{
									currentSlide = ($children.length) + negativeOffset; 
								}
							}
							base.goToSlide(currentSlide, false);
						}, options.pause);
					}
				// infinite loop
				}else{
					if(options.autoDirection == 'next'){
						interval = setInterval(function(){
							base.goToNextSlide(false);
						}, options.pause);
					}else if(options.autoDirection == 'prev'){
						interval = setInterval(function(){
							base.goToPreviousSlide(false);
						}, options.pause);
					}
				}
			
			}else if(options.ticker){
				
				options.tickerSpeed *= 10;
												
				// get the total width of the original show
				$('.pager', $outerWrapper).each(function(index) {
				  origShowWidth += $(this).width();
					origShowHeight += $(this).height();
				});
				
				// if prev start the show from the last slide
				if(options.tickerDirection == 'prev' && options.mode == 'horizontal'){
					$parent.css('left', '-'+(origShowWidth+origLeft)+'px');
				}else if(options.tickerDirection == 'prev' && options.mode == 'vertical'){
					$parent.css('top', '-'+(origShowHeight+origTop)+'px');
				}
				
				if(options.mode == 'horizontal'){
					// get the starting left position
					tickerLeft = parseInt($parent.css('left'));
					// start the ticker
					moveTheShow(tickerLeft, origShowWidth, options.tickerSpeed);
				}else if(options.mode == 'vertical'){
					// get the starting top position
					tickerTop = parseInt($parent.css('top'));
					// start the ticker
					moveTheShow(tickerTop, origShowHeight, options.tickerSpeed);
				}												
				
				// check it tickerHover applies
				if(options.tickerHover){
					setTickerHover();
				}					
			}			
		}
		
		function moveTheShow(leftCss, distance, speed){
			// if horizontal
			if(options.mode == 'horizontal'){
				// if next
				if(options.tickerDirection == 'next'){
					$parent.animate({'left': '-='+distance+'px'}, speed, 'linear', function(){
						$parent.css('left', leftCss);
						moveTheShow(leftCss, origShowWidth, options.tickerSpeed);
					});
				// if prev
				}else if(options.tickerDirection == 'prev'){
					$parent.animate({'left': '+='+distance+'px'}, speed, 'linear', function(){
						$parent.css('left', leftCss);
						moveTheShow(leftCss, origShowWidth, options.tickerSpeed);
					});
				}
			// if vertical		
			}else if(options.mode == 'vertical'){
				// if next
				if(options.tickerDirection == 'next'){
					$parent.animate({'top': '-='+distance+'px'}, speed, 'linear', function(){
						$parent.css('top', leftCss);
						moveTheShow(leftCss, origShowHeight, options.tickerSpeed);
					});
				// if prev
				}else if(options.tickerDirection == 'prev'){
					$parent.animate({'top': '+='+distance+'px'}, speed, 'linear', function(){
						$parent.css('top', leftCss);
						moveTheShow(leftCss, origShowHeight, options.tickerSpeed);
					});
				}
			}
		}		
		
		/**
		 * Sets all variables associated with the controls
		 */		
		function setAutoControlsVars(){
			// check if text or images should be used for controls
			// check "start"
			if(options.startImage != ''){
				startContent = options.startImage;
				startType = 'image';
			}else{
				startContent = options.startText;
				startType = 'text';
			}
			// check "stop"
			if(options.stopImage != ''){
				stopContent = options.stopImage;
				stopType = 'image';
			}else{
				stopContent = options.stopText;
				stopType = 'text';
			}
			// show the controls
			showAutoControls(startType, startContent, stopType, stopContent);
		}
		
		/**
		 * Handles hover events for auto shows
		 */		
		function setAutoHover(){
			// hover over the slider window
			$outerWrapper.find('.bx-window').hover(function() {
				if(autoPlaying){
					base.stopShow(false);
				}
			}, function() {
				if(autoPlaying){
					base.startShow(false);
				}
			});
		}
		
		/**
		 * Handles hover events for ticker mode
		 */		
		function setTickerHover(){
			// on hover stop the animation
			$parent.hover(function() {
				if(autoPlaying){
					base.stopTicker(false);
				}
			}, function() {
				if(autoPlaying){
					base.startTicker(false);
				}
			});
		}		
		
		/**
		 * Handles fade animation
		 */		
		function setChildrenFade(){
			// fade out any other child besides the current
			$children.not(':eq('+currentSlide+')').fadeTo(options.speed, 0).css('zIndex', 98);
			// fade in the current slide
			$children.eq(currentSlide).css('zIndex', 99).fadeTo(options.speed, 1, function(){
				isWorking = false;
				// ie fade fix
				if(jQuery.browser.msie){
					$children.eq(currentSlide).get(0).style.removeAttribute('filter');
				}
				// perform the callback function
				options.onAfterSlide(currentSlide, $children.length, $children.eq(currentSlide));
			});
		};
				
		/**
		 * Makes slide active
		 */		
		function makeSlideActive(number){
			if(options.pagerType == 'full' && options.pager){
				// remove all active classes
				$('a', $pager).removeClass(options.pagerActiveClass);
				// assign active class to appropriate slide
				$('a', $pager).eq(number).addClass(options.pagerActiveClass);
			}else if(options.pagerType == 'short' && options.pager){
				$('.bx-pager-current', $pager).html(currentSlide+1);
			}
		}
				
		/**
		 * Displays next/prev controls
		 *
		 * @param string nextType 'image', 'text'
		 * @param string nextContent if type='image', specify a filepath to the image. if type='text', specify text.
		 * @param string prevType 'image', 'text'
		 * @param string prevContent if type='image', specify a filepath to the image. if type='text', specify text.
		 */		
		function showControls(nextType, nextContent, prevType, prevContent){
			// create pager html elements
			var $nextHtml = $('<a href="" class="bx-next"></a>');
			var $prevHtml = $('<a href="" class="bx-prev"></a>');
			// check if next is 'text' or 'image'
			if(nextType == 'text'){
				$nextHtml.html(nextContent);
			}else{
				$nextHtml.html('<img src="'+nextContent+'" />');
			}
			// check if prev is 'text' or 'image'
			if(prevType == 'text'){
				$prevHtml.html(prevContent);
			}else{
				$prevHtml.html('<img src="'+prevContent+'" />');
			}
			// check if user supplied a selector to populate next control
			if(options.prevSelector){
				$(options.prevSelector).append($prevHtml);
			}else{
				$outerWrapper.append($prevHtml);
			}
			// check if user supplied a selector to populate next control
			if(options.nextSelector){
				$(options.nextSelector).append($nextHtml);
			}else{
				$outerWrapper.append($nextHtml);
			}
			// click next control
			$nextHtml.click(function() {
				base.goToNextSlide();
				return false;
			});
			// click prev control
			$prevHtml.click(function() {
				base.goToPreviousSlide();
				return false;
			});
		}
		
		/**
		 * Displays the pager
		 *
		 * @param string type 'full', 'short'
		 */		
		function showPager(type){
			// sets up logic for finite multi slide shows
			var pagerQty = $children.length;
			// if we are moving more than one at a time and we have a finite loop
			if(options.moveSlideQty > 1){
				// if slides create an odd number of pages
				if($children.length % options.moveSlideQty != 0){
					// pagerQty = $children.length / options.moveSlideQty + 1;
					pagerQty = Math.ceil($children.length / options.moveSlideQty);
				// if slides create an even number of pages
				}else{
					pagerQty = $children.length / options.moveSlideQty;
				}
			}
			var pagerString = '';
			// check if custom build function was supplied
			if(options.buildPager){
				for(var i=0; i<pagerQty; i++){
					pagerString += options.buildPager(i, $children.eq(i * options.moveSlideQty));
				}
				
			// if not, use default pager
			}else if(type == 'full'){
				// build the full pager
				for(var i=1; i<=pagerQty; i++){
					pagerString += '<a href="" class="pager-link pager-'+i+'">'+i+'</a>';
				}
			}else if(type == 'short') {
				// build the short pager
				pagerString = '<span class="bx-pager-current">'+(options.startingSlide+1)+'</span> '+options.pagerShortSeparator+' <span class="bx-pager-total">'+$children.length+'</span>';
			}	
			// check if user supplied a pager selector
			if(options.pagerSelector){
				$(options.pagerSelector).append(pagerString);
				$pager = $(options.pagerSelector);
			}else{
				var $pagerContainer = $('<div class="bx-pager"></div>');
				$pagerContainer.append(pagerString);
				// attach the pager to the DOM
				if(options.pagerLocation == 'top'){
					$outerWrapper.prepend($pagerContainer);
				}else if(options.pagerLocation == 'bottom'){
					$outerWrapper.append($pagerContainer);
				}
				// cache the pager element
				$pager = $('.bx-pager', $outerWrapper);
			}
			$pager.children().click(function() {
				// only if pager is full mode
				if(options.pagerType == 'full'){
					// get the index from the link
					var slideIndex = $pager.children().index(this);
					// accomodate moving more than one slide
					if(options.moveSlideQty > 1){
						slideIndex *= options.moveSlideQty;
					}
					base.goToSlide(slideIndex);
				}
				return false;
			});
		}
				
		/**
		 * Displays captions
		 */		
		function showCaptions(){
			// get the title from each image
		  var caption = $('img', $children.eq(currentSlide)).attr('title');
			// if the caption exists
			if(caption != ''){
				// if user supplied a selector
				if(options.captionsSelector){
					$(options.captionsSelector).html(caption);
				}else{
					$('.bx-captions', $outerWrapper).html(caption);
				}
			}else{
				// if user supplied a selector
				if(options.captionsSelector){
					$(options.captionsSelector).html('&nbsp;');
				}else{
					$('.bx-captions', $outerWrapper).html('&nbsp;');
				}				
			}
		}
		
		/**
		 * Displays start/stop controls for auto and ticker mode
		 *
		 * @param string type 'image', 'text'
		 * @param string next [optional] if type='image', specify a filepath to the image. if type='text', specify text.
		 * @param string prev [optional] if type='image', specify a filepath to the image. if type='text', specify text.
		 */
		function showAutoControls(startType, startContent, stopType, stopContent){
			// create pager html elements
			$autoControls = $('<a href="" class="bx-start"></a>');
			// check if start is 'text' or 'image'
			if(startType == 'text'){
				$startContent = startContent;
			}else{
				$startContent = '<img src="'+startContent+'" />';
			}
			// check if stop is 'text' or 'image'
			if(stopType == 'text'){
				$stopContent = stopContent;
			}else{
				$stopContent = '<img src="'+stopContent+'" />';
			}
			// check if user supplied a selector to populate next control
			if(options.autoControlsSelector){
				$(options.autoControlsSelector).append($autoControls);
			}else{
				$outerWrapper.append('<div class="bx-auto"></div>');
				$('.bx-auto', $outerWrapper).html($autoControls);
			}
						
			// click start control
			$autoControls.click(function() {
				if(options.ticker){
					if($(this).hasClass('stop')){
						base.stopTicker();
					}else if($(this).hasClass('start')){
						base.startTicker();
					}
				}else{
					if($(this).hasClass('stop')){
						base.stopShow(true);
					}else if($(this).hasClass('start')){
						base.startShow(true);
					}
				}
				return false;
			});
			
		}
		
		/**
		 * Checks if show is in finite mode, and if slide is either first or last, then hides the respective control
		 */		
		function checkEndControls(){
			if(!options.infiniteLoop && options.hideControlOnEnd){
				// check previous
				if(currentSlide == firstSlide){
					$('.bx-prev', $outerWrapper).hide();				
				}else{
					$('.bx-prev', $outerWrapper).show();
				}
				// check next
				if(currentSlide == lastSlide){
					$('.bx-next', $outerWrapper).hide();
				}else{
					$('.bx-next', $outerWrapper).show();
				}
			}
		}
		
		/**
		 * Returns the left offset of the slide from the parent container
		 */		
		function getSlidePosition(number, side){			
			if(side == 'left'){
				var position = $('.pager', $outerWrapper).eq(number).position().left;
			}else if(side == 'top'){
				var position = $('.pager', $outerWrapper).eq(number).position().top;
			}
			return position;
		}
		
		/**
		 * Returns the width of the wrapper
		 */		
		function getWrapperWidth(){
			var wrapperWidth = $firstChild.outerWidth() * options.displaySlideQty;
			return wrapperWidth;
		}
		
		/**
		 * Returns the height of the wrapper
		 */		
		function getWrapperHeight(){
			// if displaying multiple slides, multiple wrapper width by number of slides to display
			var wrapperHeight = $firstChild.outerHeight() * options.displaySlideQty;
			return wrapperHeight;
		}
		
		/**
		 * Returns a sample of an arry and loops back on itself if the end of the array is reached
		 *
		 * @param array array original array the sample is derived from
		 * @param int start array index sample will start
		 * @param int length number of items in the sample
		 * @param string direction 'forward', 'backward' direction the loop should travel in the array
		 */		
		function getArraySample(array, start, length, direction){
			// initialize empty array
			var sample = [];
			// clone the length argument
			var loopLength = length;
			// determines when the empty array should start being populated
			var startPopulatingArray = false;
			// reverse the array if direction = 'backward'
			if(direction == 'backward'){
				array = $.makeArray(array);
				array.reverse();
			}
			// loop through original array until the length argument is met
			while(loopLength > 0){				
				// loop through original array
				$.each(array, function(index, val) {
					// check if length has been met
					if(loopLength > 0){
						// don't do anything unless first index has been reached
					  if(!startPopulatingArray){
							// start populating empty array
							if(index == start){
								startPopulatingArray = true;
								// add element to array
								sample.push($(this).clone());
								// decrease the length clone variable
								loopLength--;
							}
						}else{
							// add element to array
							sample.push($(this).clone());
							// decrease the length clone variable
							loopLength--;
						}
					// if length has been met, break loose
					}else{
						return false;
					}			
				});				
			}
			return sample;
		}
												
		this.each(function(){
			// make sure the element has children
			if($(this).children().length > 0){
				base.initShow();
			}
		});
				
		return this;						
	}
	
	jQuery.fx.prototype.cur = function(){
		if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
			return this.elem[ this.prop ];
		}

		var r = parseFloat( jQuery.css( this.elem, this.prop ) );
		// return r && r > -10000 ? r : 0;
		return r;
	}

		
})(jQuery);



/*
  jQuery MegaMenu Plugin
  Author: GeekTantra
  Author URI: http://www.geektantra.com
*/
var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;

jQuery.fn.megamenu = function(options) {
  options = jQuery.extend({
	  activate_action: "mouseover",
	  deactivate_action: "mouseleave",
	  show_method: "FadeSlide",
	  hide_method: "FadeSlide",
	  justify: "left",
	  enable_js_shadow: true,
	  shadow_size: 2,
	  mm_timeout: 300
  }, options);
  var $megamenu_object = this;
  if( options.activate_action == "click" ) options.mm_timeout = 0;
  $megamenu_object.children("li").each(function(){
    jQuery(this).addClass("mm-item");
    //jQuery(".mm-item").css({ 'float': options.justify });
    
    jQuery(this).find("div:first").addClass("mm-item-content");
    jQuery(this).find("a:first").addClass("mm-item-link");
    var $mm_item_content = jQuery(this).find(".mm-item-content");
    var $mm_item_link = jQuery(this).find(".mm-item-link");
    $mm_item_content.hide();
    
    jQuery(document).bind("click", function(){
      jQuery(".mm-item-content").hide();
      jQuery(".mm-item-link").removeClass("mm-item-link-hover");
    });
    jQuery(this).bind("click", function(e){
      e.stopPropagation();
    });
    $mm_item_content.wrapInner('<div class="mm-content-base"></div>');
    if(options.enable_js_shadow == true) {
      $mm_item_content.append('<div class="mm-js-shadow"></div>');
    }
    var $mm_timer = 0;
    // Activation Method Starts
    jQuery(this).bind(options.activate_action, function(e){
      e.stopPropagation();
      var mm_item_link_obj = jQuery(this).find("a.mm-item-link");
      var mm_item_content_obj = jQuery(this).find("div.mm-item-content");
      clearTimeout($mm_timer);
      $mm_timer = setTimeout(function(){ //Emulate HoverIntent
        mm_item_link_obj.addClass("mm-item-link-hover");
        mm_item_content_obj.css({
          'top': ($mm_item_link.offset().top + $mm_item_link.outerHeight()) - 1 +"px",
          'left': ($mm_item_link.offset().left) - 5 + 'px'
        })
        
        if(options.justify == "left"){
          var mm_object_right_end = $megamenu_object.offset().left + $megamenu_object.outerWidth();
                                    // Coordinates of the right end of the megamenu object
          var mm_content_right_end = $mm_item_link.offset().left + $mm_item_content.outerWidth() - 5 ;
                                    // Coordinates of the right end of the megamenu content
          if( mm_content_right_end >= mm_object_right_end ) { // Menu content exceeding the outer box
            mm_item_content_obj.css({
              'left': ($mm_item_link.offset().left - (mm_content_right_end - mm_object_right_end)) - 2 + 'px'
            }); // Limit megamenu inside the outer box
          }
        } else if( options.justify == "right" ) {
          var mm_object_left_end = $megamenu_object.offset().left;
                                    // Coordinates of the left end of the megamenu object
          var mm_content_left_end = $mm_item_link.offset().left - mm_item_content_obj.outerWidth() + 
                                    $mm_item_link.outerWidth() + 5;
                                    // Coordinates of the left end of the megamenu content
          if( mm_content_left_end <= mm_object_left_end ) { // Menu content exceeding the outer box
            mm_item_content_obj.css({
              'left': mm_object_left_end + 2 + 'px'
            }); // Limit megamenu inside the outer box
          } else {
            mm_item_content_obj.css({
              'left': mm_content_left_end + 'px'
            }); // Limit megamenu inside the outer box
          }
        }
        if(options.enable_js_shadow == true) {
          mm_item_content_obj.find(".mm-js-shadow").height( mm_item_content_obj.height() );
          mm_item_content_obj.find(".mm-js-shadow").width( mm_item_content_obj.width() );
          mm_item_content_obj.find(".mm-js-shadow").css({
            'top': (options.shadow_size) + (isIE6 ? 2 : 0) + "px",
            'left': (options.shadow_size) + (isIE6 ? 2 : 0) + "px",
            'opacity': 0.5
          });
        }
        switch(options.show_method) {
          case "simple":
                mm_item_content_obj.show();
                break;
          case "slideDown":
                mm_item_content_obj.height("auto");
                mm_item_content_obj.slideDown('fast');
                break;
          case "fadeIn":
                mm_item_content_obj.fadeTo(400, 1);
                break;
		  case "FadeSlide":
                mm_item_content_obj.animate({opacity: 'show', height: 'show'}, {duration: 300});
                break;
          default:
                mm_item_content_obj.each( options.show_method );
                break;
        }
      }, options.mm_timeout);
    });
    // Activation Method Ends
    // Deactivation Method Starts
    jQuery(this).bind(options.deactivate_action, function(e){
      e.stopPropagation();
      clearTimeout($mm_timer);
      var mm_item_link_obj = jQuery(this).find("a.mm-item-link");
      var mm_item_content_obj = jQuery(this).find("div.mm-item-content");
//      mm_item_content_obj.stop();
      switch(options.hide_method) {
        case "simple":
              mm_item_content_obj.hide();
              mm_item_link_obj.removeClass("mm-item-link-hover");
              break;
        case "slideUp":
              mm_item_content_obj.slideUp( 'fast',  function() {
                mm_item_link_obj.removeClass("mm-item-link-hover");
              });
              break;
        case "fadeOut":
              mm_item_content_obj.fadeOut( 'fast', function() {
                mm_item_link_obj.removeClass("mm-item-link-hover");
              });
              break;
		case "FadeSlide":
                mm_item_content_obj.animate({opacity: 'hide', height: 'hide'}, {duration: 200, complete:function(){
					mm_item_link_obj.removeClass("mm-item-link-hover");
				}});
                break;
        default:
              mm_item_content_obj.each( options.hide_method );
              mm_item_link_obj.removeClass("mm-item-link-hover");
              break;
      }
      if(mm_item_content_obj.length < 1) mm_item_link_obj.removeClass("mm-item-link-hover");
    });
//    Deactivation Method Ends
  });
  this.find(">li:last").after('<li class="clear-fix"></li>');
  this.show();
};

$(document).ready(function(){
	
	$(".megamenu").megamenu();
	
	$('.checkout-final-step .submitandpay').click(function(){
		var CustomerFirstName = "";
		var CustomerSurnameName = "";
		var CustomerEmail = "";
		var CustomerPhone = "";
		CustomerFirstName = $('.registration-step-1 input.registration-input:eq(0)').val();
		CustomerSurnameName = $('.registration-step-1 input.registration-input:eq(1)').val();
		CustomerEmail = $('.registration-form-input-full input.registration-input:eq(0)').val();
		_gaq.push(['_trackEvent', 'Checkout', 'Pay', 'Customer/' + CustomerFirstName + '/' + CustomerSurnameName + '/' + CustomerEmail + '']);
	});

	
	/* shop masthead tabs */
    $('#shopMastheadTabs div').hide();
    $('#shopMastheadTabs div:first').show();
    $('ul.shopTabsCont li:first a').addClass('selected')

    $('#shopMastheadTabs ul li a').click(function(){
		var currentTab = $(this).attr('href');
		$('ul.shopTabsCont li a').removeClass('selected');
		$('#shopMastheadTabs div').hide();
		$(currentTab).show();
		$(this).addClass('selected');
		return false;
    });


    if (!$('.PaymentForm_CreditCardType').length == 0)
	{
		$(".cardSelectDropDown").hide();
		function SetCreditCardType(CCtype, thisCC){
			$('select.PaymentForm_CreditCardType').val(thisCC);
			$('.CreditCardImage').removeClass('Activated');
			CCtype.addClass('Activated');
			
			switch(thisCC){
				case "Maestro":
					$('#CardStartDate, tr.IssueNumber').show();
					$('.ThisCardTypeHelper').html('Maestro');
					break;
				case "Solo":
					$('#CardStartDate, tr.IssueNumber').show();
					$('.ThisCardTypeHelper').html('Solo');
					break;
				//Otherwise
				case "Visa":
					$('#CardStartDate, tr.IssueNumber').hide();
					$('.ThisCardTypeHelper').html('Visa');
					break;
				case "MasterCard":
					$('#CardStartDate, tr.IssueNumber').hide();
					$('.ThisCardTypeHelper').html('Mastercard');
					break;
				case "Discover":
					$('#CardStartDate, tr.IssueNumber').hide();
					$('.ThisCardTypeHelper').html('Discover');
					break;
			}

			
			
		}
		
		SetCreditCardType($('.CreditCardImage[rel="' + $('.PaymentForm_CreditCardType').val() + '"]'),$('select.PaymentForm_CreditCardType').val());
		
		//Some new fancy checkout styling
		$('.CreditCardImage').click(function(){
			SetCreditCardType($(this), $(this).attr('rel'));
		});
	
	}
	
	function uiFormSwapValue(thisInput){
		swapValues = [];
			$(thisInput).each(function(i){
				swapValues[i] = $(this).val();
				$(this).focus(function(){
					if ($(this).val() == swapValues[i]) {
						$(this).val("");
					}
				}).blur(function(){
					if ($.trim($(this).val()) == "") {
						$(this).val(swapValues[i]);
				}
			});
		});
	}
	uiFormSwapValue('.learningacademytextbox');
	$('.learningacademysearchbutton').click(function(){
		var thisElement = $(this);
		var searchInput = $(this).parent().children('.learningacademytextbox').val();
		if (searchInput == ""){
			return false;
		}
		else{
			thisElement.attr("href", "http://www.mrsite.co.uk/support/Search/?Keywords=" + searchInput).attr('target', '_self');
		}
	});
	
	$('.learningacademytextbox').bind('keypress', function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		if(code == 13) {
			var searchInput = $(this).val();
			if (searchInput == ""){
				return false;
			}
			else{
				$('.learningacademysearchbutton').attr('onclick','window.location.href="http://www.mrsite.co.uk/support/Search/?Keywords=' + searchInput + '";return false;').click();
				return false;
			}
			return false;
		}
	});

	
	
	$('#.menuLogin a').mouseover(function(){
		$(this).addClass('mouseover');
	}).mousedown(function(){
		$(this).addClass('mousedown');
	}).mouseleave(function(){
		$(this).removeClass('mousedown');
		$(this).addClass('mouseover');
	});
	
	$('#pickcountry').val(1)
	$('#pickcountry').change(function(){
		$('.contact-container').hide();
		$('.contact-container[countryid="'+ $(this).val() +'"]').show();
	});
	
		
	var twitterUsername = 'mr_site';
	var tweetCount = 1;
	var ShowAvatar = true;
	var ShowScreenNames = true;

	$('.TweetsContainer').jTweetsAnywhere({
		username: twitterUsername,
		count: tweetCount,
		showTweetFeed: {
			showProfileImages: ShowAvatar,
			showUserScreenNames: ShowScreenNames
		},
		onDataRequestHandler: function(stats) {
			if (stats.dataRequestCount < 11) {
				return true;
			}
		}
	});
	
	$('#TumblrFeed').rssfeed('http://mrsite.tumblr.com/rss', {
		limit: 5
	});


});
