

var BEC = {
	a_l: 0,
	common: {
		init: function() {
			UTIL.exec( "_mostPopularPages" );
			var	inputFocus=false,
				becPerson=false;
			if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
				$(window).load(function(){
			    $('input:-webkit-autofill').each(function(){
			        var text = $(this).val(),
			        	name = $(this).attr('name');
			        $(this).after(this.outerHTML).remove();
			        $('input[name=' + name + ']').val(text);
			    });
			});}
			$('ul.helper li.logIn').hover(function() {
				$('#divHelper').toggleClass("closed");
				$(this).css("border-right", "1px solid #ccc");
				$(this).toggleClass("open");
				$('div.helperContent').addClass("closed");
				$('#divHelperLogIn').toggleClass("closed");
			});
			$('ul.helper li.admin').hover(function() {
				if ($('ul.helper  li').index($(this)) > 2 ){
					$('#divHelper').addClass("offset");					
				}			
				$('#divHelper').addClass("offset");
				$('#divHelper').toggleClass("closed");
				$('div.helperContent').addClass("closed");
				$(this).toggleClass("open");
				$('#divHelperAdmin').toggleClass("closed");
			});		
			$('ul.helper li.help').hover(function() {
				if ($('ul.helper  li').index($(this)) > 1 ){
					$('#divHelper').addClass("offset");					
				}
				$('#divHelper').toggleClass("closed");
				$('div.helperContent').addClass("closed");
				$(this).toggleClass("open");
				$('#divHelperHelp').toggleClass("closed");
			});	
			
			$('#divHelper input').mouseenter(function() {
				$(this).parents('#divHelper').removeClass("closed");
				var activeDivClasses = $('#divHelperContent div.helperContent:not(.closed)').attr("class"),
					activeDiv = jQuery.trim(activeDivClasses.replace("helperContent", ""));
				$('ul.helper li.'+ activeDiv).addClass("open");
			});
			$('#divHelper').mouseenter(function() {
				inputFocus=false;
				$(this).removeClass("closed");
				var activeDivClasses = $('#divHelperContent div.helperContent:not(.closed)').attr("class"),
					activeDiv = jQuery.trim(activeDivClasses.replace("helperContent", ""));
				$('ul.helper li.'+ activeDiv).addClass("open");
			});
			$('#divHelper').mouseleave(function() {
				if (inputFocus){ return false; };
				$('#divHelper').addClass("closed");
				$('ul.helper li').removeClass("open");		
			});
			$('input#user_name').focus(function(){
				inputFocus=true;
			});
			
			$(':input').each(function(){
				$(this).css("background-color, #fff");
			});
			
			$('.people').mouseover(function() {
				var numBecPeople= $('#divHeader .becPeople').children('div').length;
				if ($(this).hasClass('raw')){
					becPerson=$(this).find('img').attr('id');
					$(this).removeClass('raw').find('img').attr('src', $(this).find('img').attr('src').replace("becPeople", "becPeople/yellow"));
				}
				
			});
			
			
		}
	}, 
	
	frontPage: {
		init: function() {
			getSlideShow();
			UTIL.exec( "_mostPopularPages" );
			UTIL.exec( "_sideUpcomingWidget" );
			
			$('#divAllLeagues').cycle({
				fx: 'scrollLeft',
				timeout: 7000,
				next: '#divAllLeagues'
			});

			$('#jTweetsAnywhereSample').jTweetsAnywhere({
				searchParams: ['q=korfball','lang=en'],
				count: 6,
				showTweetFeed: {
					showTimestamp: {
						refreshInterval: 15
					},
					autorefresh: {
						mode: 'trigger-insert',
						interval: 30
					},
					paging: { mode: 'more' }
				},
				onDataRequestHandler: function(stats, options) {
					if (stats.dataRequestCount < 11) {
						return true;
					}
					else {
						stopAutorefresh(options);
					}
				}
			});
		}
	},
		
	viewCalendar: {
		init: function() {
			var view="month",         
				DATA_FEED_URL = "lib/AJAX/calendarDataFeed.php",
            	op = {
	                view: view,
	                theme:3,
	                showday: new Date(),
	                EditCmdhandler:Edit,
	                DeleteCmdhandler:Delete,
	                ViewCmdhandler:View,    
	                onWeekOrMonthToDay:wtd,
	                onBeforeRequestData: cal_beforerequest,
	                onAfterRequestData: cal_afterrequest,
	                onRequestDataError: cal_onerror, 
	                autoload:true,
	                url: DATA_FEED_URL + "?method=list",  
	                quickUpdateUrl: DATA_FEED_URL + "?method=update",
	                quickDeleteUrl: DATA_FEED_URL + "?method=remove"        
				},
				$dv = $("#calhead"),
				_MH = document.documentElement.clientHeight-100,
            	dvH = $dv.height() + 2;
            op.height = _MH - dvH;
            op.eventItems =[];

            var p = $("#gridcontainer").bcalendar(op).BcalGetOp();
            if (p && p.datestrshow) {
                $("#txtdatetimeshow").text(p.datestrshow);
            }
            $("#caltoolbar").noSelect();

            function cal_beforerequest(type)
            {
                var t="Loading data...";
                switch(type)
                {
                    case 1:
                        t="Loading data...";
                        break;
                    case 2:                      
                    case 3:  
                    case 4:    
                        t="The request is being processed ...";                                   
                        break;
                }
                $("#errorpannel").hide();
                $("#loadingpannel").html(t).show();    
            }
            function cal_afterrequest(type)
            {
                switch(type)
                {
                    case 1:
                        $("#loadingpannel").hide();
                        break;
                    case 2:
                    case 3:
                    case 4:
                        $("#loadingpannel").html("Success!");
                        window.setTimeout(function(){ $("#loadingpannel").hide();},2000);
                    break;
                }              
               
            }
            function cal_onerror(type,data)
            {
                $("#errorpannel").show();
            }
            function Edit(data)
            {
               var eurl="edit.php?id={0}&start={2}&end={3}&isallday={4}&title={1}";   
                if(data)
                {
                    var url = StrFormat(eurl,data);
                    OpenModelWindow(url,{ width: 600, height: 400, caption:"Manage  The Calendar",onclose:function(){
                       $("#gridcontainer").reload();
                    }});
                }
            }    
            function View(data)
            {
                var str = "";
                $.each(data, function(i, item){
                    str += "[" + i + "]: " + item + "\n";
                });
                alert(str);               
            }    
            function Delete(data,callback)
            {           
                
                $.alerts.okButton="Ok";  
                $.alerts.cancelButton="Cancel";  
                hiConfirm("Are You Sure to Delete this Event", 'Confirm',function(r){ r && callback(0);});           
            }
            function wtd(p)
            {
               if (p && p.datestrshow) {
                    $("#txtdatetimeshow").text(p.datestrshow);
                }
                $("#caltoolbar div.fcurrent").each(function() {
                    $(this).removeClass("fcurrent");
                })
                $("#showdaybtn").addClass("fcurrent");
            }
            //to show day view
            $("#showdaybtn").click(function(e) {
                //document.location.href="#day";
                $("#caltoolbar div.fcurrent").each(function() {
                    $(this).removeClass("fcurrent");
                })
                $(this).addClass("fcurrent");
                var p = $("#gridcontainer").swtichView("day").BcalGetOp();
                if (p && p.datestrshow) {
                    $("#txtdatetimeshow").text(p.datestrshow);
                }
                $("#dvtec").scrollTop($("#dvtec")[0].scrollHeight);
            });
            //to show week view
            $("#showweekbtn").click(function(e) {
                //document.location.href="#week";
                $("#caltoolbar div.fcurrent").each(function() {
                    $(this).removeClass("fcurrent");
                })
                $(this).addClass("fcurrent");
                var p = $("#gridcontainer").swtichView("week").BcalGetOp();
                if (p && p.datestrshow) {
                    $("#txtdatetimeshow").text(p.datestrshow);
                }
                $("#dvtec").scrollTop($("#dvtec")[0].scrollHeight);
            });
            //to show month view
            $("#showmonthbtn").click(function(e) {
                //document.location.href="#month";
                $("#caltoolbar div.fcurrent").each(function() {
                    $(this).removeClass("fcurrent");
                })
                $(this).addClass("fcurrent");
                var p = $("#gridcontainer").swtichView("month").BcalGetOp();
                if (p && p.datestrshow) {
                    $("#txtdatetimeshow").text(p.datestrshow);
                }
            });
            
            $("#showreflashbtn").click(function(e){
                $("#gridcontainer").reload();
            });
            
            //go to today
            $("#showtodaybtn").click(function(e) {
                var p = $("#gridcontainer").gotoDate().BcalGetOp();
                if (p && p.datestrshow) {
                    $("#txtdatetimeshow").text(p.datestrshow);
                }


            });
            //previous date range
            $("#sfprevbtn").click(function(e) {
                var p = $("#gridcontainer").previousRange().BcalGetOp();
                if (p && p.datestrshow) {
                    $("#txtdatetimeshow").text(p.datestrshow);
                }

            });
            //next date range
            $("#sfnextbtn").click(function(e) {
                var p = $("#gridcontainer").nextRange().BcalGetOp();
                if (p && p.datestrshow) {
                    $("#txtdatetimeshow").text(p.datestrshow);
                }
            });
		}
	},
	viewCompetitions: {
		init: function() {
			$('.filterBar a[href$="'+window.location.search+'"]').addClass("selected").parent("div").addClass("selected");
		}
	},
	viewContact: {
		init: function() {
			$("#contact_name").focus();
			$("#contactForm").validate({
				invalidHandler: function(form, validator) {
			   		var errors = validator.numberOfInvalids();
			    	if (errors) {
				        validator.errorList[0].element.focus(); //Set Focus
			    	}
				},
				focusCleanup: true,
				rules: {
					contact_name: "required",
					contact_email: {
						required: true,
						email: true
					}
				},	
				messages: {
					contact_email: "Please enter a valid email address"
				}
			});
			
			$("#sendMessageButton").click(function(){
				 if (!$("#contactForm").validate().form()) {
				 	return false;
				 };
				$("#sendMessageButton").text('Sending...');		
				var addString='message=' + $('#message').val() + '&';
				$("#contactForm input:text").each(function(){
					addString += $(this).attr("name") + '=' + $(this).val()	+ '&';
				});
				$("#contactForm input:checkbox").each(function(){
					if ($(this).is(':checked')) {
						addString += $(this).attr("name") + '=' + $(this).val()	+ '&';	
					}
					else {
						addString += $(this).attr("name") + '=&';	
					}
				});			
				addString = addString.slice(0,-1);
				$.ajax({
					type: "POST",
					url:"lib/AJAX/sendContactMessage.php",
					data: addString,
					success: function(response){
						if (response=="success"){
							$('#infoMessage').html("Thank you! Your message has been sent, we will respond to you shortly.");
							$('#divContactFormContent').hide();
						}
						else {
							$('#infoMessage').html("Hmm. There appears to have been a problem, please refresh the page and try again.");
							$('#divContactFormContent').hide();
						}
					}
				});
			});
		
		}
	},
	
	viewEvent: {
		init: function() {
			UTIL.exec( "_messages" );
			UTIL.exec( "_sideUpcomingWidget" );
			
			var member_id=$("input#member_id").val(),
				newResponse="";
			$("div.hide").hide();
			$("li.hide").hide();	
			$("span.response").click(function(){
				switch ($(this).attr("id")) {
					case 'yes_response': {
						newResponse="yes";
						$('span.respond').hide();				
						$('span#change_response').show();
						$('span#responded').html('You have said Yes to this event').show();
						$('span#notResponded').hide();
						$("#" + member_id).show();
						 break;
					}
					case 'no_response': {
						newResponse="no";
						$('span.respond').hide();
						$('span#change_response').show();
						$('span#responded').html('You have said No to this event').show();
						$('span#notResponded').hide();
						$("#" + member_id).hide();				
						 break;
					}			
					case 'maybe_response': {
						newResponse="maybe";
						$('span.respond').hide();	
						$('span#change_response').show();
						$('span#responded').html('You have said Maybe to this event').show();
						$('span#notResponded').hide();
						$("#" + member_id).show();
						 break;
					}
					case 'change_response': {
						newResponse="change";
						$('span.respond').show();
						$('span#change_response').hide();
						$('span#responded').hide();
						$('span#notResponded').show();			
						$("#" + member_id).hide();				
						 break;
					}			
				}
				var postString = 'response='+ newResponse + '&member_id=' + member_id + '&event_id=' + $("input#event_id").val();
				$.ajax({
					type: "POST",
					url:"lib/AJAX/updateEventResponse.php",
					data: postString,
					success: function(reply){
					}
				});
			});
		
		}
	},
	
	viewEvents: {
		init: function() {
			UTIL.exec( "_mostPopularPages" );
		}
	},
	
	viewGallery: {
		init: function() {
			UTIL.exec( "_messages" );
			var firstTime=true,
				currentWidth=0;
			$('.galleryImage').each(function(){
				var divWidth= $(this).parents('div').width(),
					imageSecret=$(this).attr('id');
				$('p.'+ imageSecret).css('width', divWidth).show();
				if ((currentWidth + divWidth) > 970){
					$(this).parents('div').css('clear', 'both');
					var currentWidth=divWidth;
				}	
				else {
					currentWidth += divWidth + 25;
				}
			});	
			
			if (BEC.a_l > 0){

				function tagMeInThis(image_secret){
					$.ajax({
						type: "POST",
						url:"lib/AJAX/updateTags.php?cmd=add",
						data: 'item_type=image&image_secret=' + image_secret,
						data: 'hootie=' + $('#hootie').val() + '&created_by_id=' + $('#created_by_id').val() + '&item_type=image&image_secret=' + image_secret ,
						success: function(response){
							alert("Tagged!");
						}
					});
				};
				function updateGalleryFeaturedImage(src){
					$.ajax({
						type: "POST",
						url:"lib/AJAX/updateGallery.php",
						data: 'hootie=' + $('#hootie').val() + '&created_by_id=' + $('#created_by_id').val() + '&cmd=featuredImage&photo_URL=' +   encodeURIComponent(src) + '&gallery_id=' + $("#gallery_id").val() ,
						success: function(response){
						}
					});	
				};
				function useImageForProfile(src){
					window.location.href = "?page=adminEditMyProfile&member_id=" + $('#member_id').val() + '&cmd=useImage&src=' + src;
				};
				function addImageTitle(flickr_secret){
					$('div.' + flickr_secret).show();
					$('input.' + flickr_secret).focus().keypress(function(e) {
						var imageTitle=$(this).val();
					    if(e.keyCode == 13) {
							$.ajax({
								type: "POST",
								url:"lib/AJAX/updateGallery.php",
								data: 'hootie=' + $('#hootie').val() + '&created_by_id=' + $('#created_by_id').val() + '&cmd=setImageTitle&image_title=' + imageTitle + '&flickr_secret=' + flickr_secret ,
								success: function(response){
									$('p.'+ flickr_secret).text(imageTitle);
									$('div.' + flickr_secret).hide();
									
								}
							});
			
					    	
					    }
					});
				}
				
				var menu = [
				   		 {'Add/change image title':{
						      onclick:function(menuItem,menu) { addImageTitle($(this).attr("id")); },
							  className:'menu3-custom-item',
							  disabled:false,
							  icon:'public/images/icons/tag_icon.png',
							  title:'This photo will show in your profile'
							}
						  },	        	
					 {'Tag me in this photo':{
					      onclick:function(menuItem,menu) { tagMeInThis($(this).attr("id")); },
						  className:'menu3-custom-item',
						  disabled:false,
						  icon:'public/images/icons/tag_icon.png',
						  title:'This photo will show in your profile'
						}
					  },
						 {'Use this picture for my profile':{
						      onclick:function(menuItem,menu) { useImageForProfile($(this).parent('a').attr("href")); },
							  className:'menu3-custom-item',
							  disabled:false,
							  icon:'public/images/icons/photos_icon.gif',
							  title:'This photo will show in your profile'
							}
						  },		  
					  {'Add to Featured Image List':{
					      onclick:function(menuItem,menu) { updateGalleryFeaturedImage($(this).attr("src")); },
						  className:'menu3-custom-item',
						  disabled:false,
						  icon:'public/images/icons/hot_menu_icon.gif',
						  title:'This list is used for the front page slide gallery'
						}
					  },
					 {'Cancel':{
					      onclick:function(menuItem,menu) { return true; },
						  disabled:false
						}
					  }
					];
	
				$(function() {
				  $('.galleryImage').contextMenu(menu,{
				  	 theme:'vista'
				  	});
				});
							
				$('.editTags').click(function(){
					firstTime=false;
					$('#divTagAdmin').show();
				});
				
				$("input#addTags").autocomplete("lib/AJAX/autoComplete.php?table=tags", {
					width: 260,
					matchContains: true,
					minChars: 1,
					max: 50,
					selectFirst: false
				});
				$('input#addTags').result(function(event, data, formatted) {
					$('ul#tagTargetList').append('<li class="tagToken edit">' + $('input#addTags').val().split("ID")[0] + '<span id="' + $('input#addTags').val().split("ID")[1] + '" class="closeButton"></span></li>');
					var newTagId=parseInt($('input#addTags').val().split("ID")[1]);
					if (tagArray.length > 0 ){
						tagArray[tagArray.length]=newTagId;
					}
					else {
						tagArray[0] = newTagId;
					}
					$('input#addTagsWindow').val(tagArray.join(","));
					$('input#addTags').val("").focus();
				});
				$('span.closeButton').live('click',function(){
					var removeTagId=parseInt($(this).attr('id')),
						index= tagArray.indexOf(removeTagId);
					tagArray.splice(index,1);
					$(this).parent('li').remove();
					$('input#addTagsWindow').val(tagArray.join(","));
				});
				$('#saveTagsTrigger').click(function(){
					$.ajax({
						type: "POST",
						url:"lib/AJAX/updateTags.php?cmd=update",
						data: 'tags=' + tagArray + '&item_type=gallery&content_id=' + $('#gallery_id').val(),
						success: function(response){
							location.reload();
						}
					});
				
				});
			
			}
		}
	},
	
	viewLogIn: {
		init: function() {
			
			$("#logInForm").validate({
				rules: {
					user_name: "required",
					password:  "required"
				}
			});
			function submitForm() {
				if (!$("#logInForm").validate().form()) {
					return false;
				}
				else {
					$("#submitButton").attr("disabled", "true");
					return true;
				};
				
			};
		}
	},
	
	viewMatch: {
		init: function() {
			UTIL.exec( "_messages" );
			UTIL.exec( "_sideUpcomingWidget" );
			$('#viewAdminSection').click(function(){
				$('#divMatchAdmin').slideToggle();
			});
		}
	},
	
	viewMyProfile: {
		init: function() {
			var numAddressees=0;
			$('img.removeTag').click(function(){
				var content_id=$(this).attr('id');
				$.ajax({
					type: "POST",
					url:"lib/AJAX/updateTags.php?cmd=delete",
					data: {content_id: content_id, member_id: $('#member_id').val(), item_type: 'image'},
					success: function(response){
						if (response=="removed"){
							$('div.' + content_id).hide();
						}
						else{
							alert(response);
						}
					}
				});	
			});	
			
			$("input#selectMember").autocomplete("lib/AJAX/autoComplete.php?table=members", {
				width: 151,
				matchContains: true,
				minChars: 1,
				selectFirst: false
			});
			
			$('input#selectMember').result(function(event, data, formatted) {
				if (numAddressees>=4){ alert("Only 4 addressees!"); $("input#selectMember").val(""); return false;}
				numAddressees++;
				var newAddress= '<li class="buzzAddress" id="'+ $("input#selectMember").val().split("ID")[1] + '">@' +  $("input#selectMember").val().split("ID")[0] + '<a class="closeButton" href="#"></a></li>';
				if ($("#buzzAddressList li").length > 2){
					$("#buzzAddressList li:nth-child(" + ($("#buzzAddressList li").length - 2) + ")").after($(newAddress));
				}
				else {
					$("#buzzAddressList").prepend(newAddress);
				}
				$(this).parents("li").hide();
				$(this).val("");
				$('#addBuzzAddress').show();
			});
			$('#sendBuzz').click(function(){
				$('#buzzAddressBar,#buzzMessageBody, #sendBuzzButton').slideDown('fast');
				$('input#selectMember').focus();
			});
			$("textarea#buzz_message").keypress(function(event) {
				if(event.which == '13') {
					return false;
				}
			});
			$('.addBuzzAddress').click(function(){
				$(this).next().show();	
				$(this).hide();
			});
			
			$('.cancelButton').click(function(){
				$(this).prev(':input').val("");
				$(this).parents('li').prev('li').show();		
				$(this).parents('li').hide();	

			});		
			$('a.closeButton').live('click',function(){
				$(this).parent('li').remove();
				numAddressees--;
			});
			$('#sendBuzzButton').click(function(){
				var address=false;
				if ($('textarea#buzz_message').val().length < 1){ return false;}
				var buzzString='member_id='+ $('#member_id').val() + '&buzz_message=' + encodeURIComponent($('textarea#buzz_message').val()) + '&addressList=';
				$('#buzzAddressBar li.buzzAddress').each(function(){
					buzzString+=$(this).attr('id') + ',';
				});
				buzzString = buzzString.slice(0,-1);
				$.ajax({
					type: "POST",
					url:"lib/AJAX/sendBuzz.php",
					data: buzzString,
					success: function(response){
						location.reload();
					}
				});	
			});	
			$('#markSeenButton').click(function(){
				$.ajax({
					type: "POST",
					url:"lib/AJAX/sendBuzz.php?cmd=markAllSeen",
					data: 'member_id=' + $('#member_id').val(),
					success: function(response){
						location.reload();
					}
				});	
			});
			$('#sentBuzzesButton').click(function(){
				$('.buzzMessage').toggle();
				if ($(this).text() == 'See your Inbox'){
					$(this).text('See sent buzzes');
				}
				else {
					$(this).text('See your Inbox')
				}
			});
			$('span.addressee a').click(function(){
				if (numAddressees >= 4){ alert("Only 4 addressees at the moment!"); return false;}
				numAddressees++;
				if (!$('#buzzAddressBar').is(':visible')) {
					$('#buzzAddressBar,#buzzMessageBody, #sendBuzzButton').slideDown('fast');
					$('input#selectMember').focus();
				}
				var newAddress= '<li class="buzzAddress" id="'+ $(this).attr('id') +'">' +  $(this).text() + '<a class="closeButton" href="#"></a></li>';
				if ($("#buzzAddressList li").length > 2){
					$("#buzzAddressList li:nth-child(" + ($("#buzzAddressList li").length - 2) + ")").after($(newAddress));
				}
				else {
					$("#buzzAddressList").prepend(newAddress);
				}
			});
			$('img.reply_all').click(function(){
				if (!$('#buzzAddressBar').is(':visible')) {
					$('#buzzAddressBar,#buzzMessageBody, #sendBuzzButton').slideDown('fast');
					
				}
				else {
					$('ul#buzzAddressList').html("");
				}
				numAddressees=0;
				$(this).parents("div.buzzMessageTop").find("a.replyTo, a.sender").each(function(){
					if ($(this).attr('id') != "-100" ){
						var newAddress= '<li class="buzzAddress" id="'+ $(this).attr('id') +'">' +  $(this).text() + '<a class="closeButton" href="#"></a></li>';
						if ($("#buzzAddressList li").length > 2){
							$("#buzzAddressList li:nth-child(" + ($("#buzzAddressList li").length - 2) + ")").after($(newAddress));
						}
						else {
							$("#buzzAddressList").prepend(newAddress);
						}
						numAddressees++;
					}
				});
				var oldMessage=$(this).parents("div.buzzMessage").find("p.buzz").html().replace( /\<br(\s*\/|)\>/g, '\r\n' );
				$('textarea#buzz_message').html( "\r\n" + "\r\n" + $(this).parents("div.buzzMessageTop").find("a.sender").text() + " buzzed - " + $(this).parents("div.buzzMessageTop").find("div.timeSent").text() + "\r\n" + oldMessage.replace(/&amp;/g, '%26')).focus();
			});
		}
	},	

	viewNews: {
		init: function() {
			UTIL.exec( "_tags" );
			UTIL.exec( "_messages" );
			UTIL.exec( "_mostPopularPages" );

			$('#saveTagsTrigger').click(function(){
				$.ajax({
					type: "POST",
					url:"lib/AJAX/updateTags.php?cmd=update",
					data: 'tags=' + tagArray + '&item_type=news&content_id=' + $('#news_id').val(),
					success: function(response){
						window.location.reload();
					}
				});
			
			});
		
		}
	},
	
	viewNewsHome: {
		init: function() {
			UTIL.exec( "_mostPopularPages" );
		}
	},

	viewRecoverPassword: {
		init: function() {
			$("#recoverPasswordForm").validate({
				rules: {
					email: {
						required: true
					}
				}
			});
			$('button#submitButton').click(function() {
				$(this).attr('disabled', 'disabled');
				if (!$("#recoverPasswordForm").validate().form()) {
					return false;
				}
				else {		
					$.ajax({
						type: "POST",
						url:"lib/AJAX/recoverPassword.php",
						data: 'email='+ $('input#email').val(),
						success: function(response){
							$("#recoverPasswordResponse").html(response);
							$('button#submitButton').removeAttr('disabled');
						}
					});
				}
				
			});
		}
	},
		
	viewResetPassword: {
		init: function() {
			$("#resetPasswordForm").validate({
				rules: {
					password: {
						required: true,
						minlength: 8,
						equalTo: "#password1"
					},
					password1: {
						required: true,
						minlength: 8
					}
				}
			});
			function resetPasswordForm() {
				if (!$("#logInForm").validate().form()) {
					return false;
				}
				else {
					$("#submitButton").attr("disabled", "true");
					return true;
				};
				
			};
		},

		action: function() {
			// do some stuff on a specific page
		}
	},
	viewTraining: {
		init: function() {
			UTIL.exec( "_messages" );
		}
	},
	WCviewTeam: {
		init: function() {
		    $('.headerImages').cycle({
				fx: 'fade',
				timeout: 7000,
			    speed:  2000,
			    next: '.headerImages'
			});
		}
	},
	
	_messages: {
		init: function() {
			var messageEntered=false;
			$("#postMessage").click(function(){
				$(this).html("");
				$("#postMessage").css("height", "100px");
			});
			
			$('img#post_message_button').click(function() {
				if ($("#postMessage").val().length == 0 || $("#postMessage").val()=="Post a message") {
					$("#postMessage").val("Post a message").css("height", "40px");
					return false;
			  	}
				if (messageEntered){
					return false;
				}
				messageEntered=true;
				postString ="hootie=" + $('#hootie').val() + "&message=" + $("#postMessage").val() + "&message_type=" + $("input#message_type").val() + "&type_id=" + $("input#type_id").val() + "&member_id=" + $("#member_id").val();
				$.ajax({
					type: "POST",
					url:"lib/AJAX/updateMessages.php",
					data: postString,
					success: function(response){
						var member_id=$("#member_id").val(),
							html='<div class="message_wrapper">';
						html+='<div class="divPostMessage">';
						html+='<img src="public/images/id_photos/avatars/' + $("#member_photo").val() +'" class="poster" />';
						html+='<p><a class="poster_name" href="?page=viewMember&member_id=' + member_id + '">You</a> said: </p><br />';
						html+= '<div class="rightMessage"><p class="post_message">' +  $("#postMessage").val().replace(/\n/g, "<br />") + '</p><br /></div>';
						html+='</div>';
						html+='<div class="postMessageRight">';
						html+='<img src="public/images/icons/delete_message_icon.png" class="delete_message"  id="message_' + response + '" alt="Delete this message" title="Delete this message"/>';
						html+='<p>Posted: Just a few seconds ago</p>';
						html+='</div>';
						html+='<div class="message_divider"></div>';	 
						html+='</div>';	
						$("#divViewMessages").prepend(html);
						$("#postMessage").val("Post a message").css("height", "40px");
						messageEntered=false;
					}
				});
			});
			
			$('img.delete_message').live('click', function() {
				if (confirm('Are you sure you want to delete this message?')){
					postString ="hootie=" + $('#hootie').val() + "&delete=yes" + "&message_id=" + $(this).attr("id").slice(8) + "&message_type=" + $("input#message_type").val() + "&type_id=" + $("input#type_id").val() + "&member_id=" + $("#member_id").val();
					message_identifier = $(this).attr("id");
					$.ajax({
						type: "POST",
						url:"lib/AJAX/updateMessages.php",
						data: postString,
						success: function(response){
							$("#" + message_identifier).parents("div.message_wrapper").slideToggle();	
						}
					});
					
				}
		  	});  
		}
	},
	
	_mostPopularPages: {
		init: function() {
			$('div.innerPanel.comments').hide();
		    $('#commentsTabTrigger').click(function(){
				$('#commentsTabTrigger').removeClass('closed');
				$('div.innerPanel.comments').show();		
				$('#viewsTabTrigger').addClass('closed');		
				$('div.innerPanel.views').hide();		
			});
		   $('#viewsTabTrigger').click(function(){
				$('#commentsTabTrigger').addClass('closed');
				$('div.innerPanel.comments').hide();		
				$('#viewsTabTrigger').removeClass('closed');		
				$('div.innerPanel.views').show();		
			});
		   $('div.smallInnerPanel').hover(function(){
				$(this).find('span.rank:first').toggleClass('selected');
			});	
		}
	},
	
	_sideUpcomingWidget: {
		init: function() {
			$('div.innerPanel.matches').hide();
			$('#matchesTabTrigger').click(function(){
				$('#matchesTabTrigger').removeClass('closed');
				$('div.innerPanel.matches').show();		
				$('#eventsTabTrigger').addClass('closed');		
				$('div.innerPanel.events').hide();		
			});
		   $('#eventsTabTrigger').click(function(){
				$('#matchesTabTrigger').addClass('closed');
				$('div.innerPanel.matches').hide();		
				$('#eventsTabTrigger').removeClass('closed');		
				$('div.innerPanel.events').show();		
			});
		}
	},
	
	_tags:{
		init: function() {
			$('.editTags').click(function(){
				$('#divTagAdmin').slideToggle();
			});
			$("input#addTags").autocomplete("lib/AJAX/autoComplete.php?table=tags", {
				width: 260,
				matchContains: true,
				minChars: 1,
				max: 50,
				selectFirst: false
			});
			$('input#addTags').result(function(event, data, formatted) {
				$('ul#tagTargetList').append('<li class="tagToken edit">' + $('input#addTags').val().split("ID")[0] + '<span id="' + $('input#addTags').val().split("ID")[1] + '" class="closeButton"></span></li>');
				var newTagId=parseInt($('input#addTags').val().split("ID")[1]);
				if (tagArray.length > 0 ){
					tagArray[tagArray.length]=newTagId;
				}
				else {
					tagArray[0] = newTagId;
				}
				$('input#addTagsWindow').val(tagArray.join(","));
				$('input#addTags').val("").focus();
			});
			$('span.closeButton').live('click',function(){
				var removeTagId=parseInt($(this).attr('id')),
					index= tagArray.indexOf(removeTagId);
				tagArray.splice(index,1);
				$(this).parent('li').remove();
				$('input#addTagsWindow').val(tagArray.join(","));
			});
		}
	}
};

UTIL = {
	exec: function( controller, action ) {
		var ns = BEC,
			action = ( action === undefined ) ? "init" : action;

		if ( controller !== "" && ns[controller] && typeof( ns[controller][action] ) == "function" ) {
			ns[controller][action]();
		}
	},

	init: function() {
		var body = document.body, controller = body.getAttribute( "data-controller" ), action = body.getAttribute( "data-action" );
		UTIL.exec( "common" );
		UTIL.exec( controller );
		UTIL.exec( controller, action );

		$(document).trigger('finalized');
	}
};

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
};

(function($){
 $.fn.extend({
 	customStyle : function(options) {
	  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
	  return this.each(function() {
	  
			var currentSelected = $(this).find(':selected');
			$(this).after('<span class="customStyleSelectBox"><span class="customStyleSelectBoxInner">'+currentSelected.text()+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
			var selectBoxSpan = $(this).next(),
				selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right')),
				selectBoxSpanInner = selectBoxSpan.find(':first-child');
			selectBoxSpan.css({display:'inline-block'});
			selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
			var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
			$(this).height(selectBoxHeight).change(function(){
				// selectBoxSpanInner.text($(this).val()).parent().addClass('changed');   This was not ideal
			selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
				// Thanks to Juarez Filho & PaddyMurphy
			});
			
	  });
	  }
	}
 });
})(jQuery);

function getSlideShow(){
	$.ajax({
		type: "POST",
		url:"lib/AJAX/AJAXSlideGallery.php",
		data: "",
		success: function(response){
			$("#divSlide").html(response);
			$('#divSlide').cycle({
				fx: 'scrollLeft',
				timeout: 7000,
				 after: onAfter,
				 before: onBefore
			});
			function onBefore(curr,next,opts) {
				var info_string=(this.id),
					split_string=info_string.split('|||');
				if (split_string[0]=="video" ) {
					var caption = '<a href="?page=viewMedia">Latest videos</a>';
				}
				else {
					var caption = '<a href="?page=viewGallery&amp;gallery_id=' + split_string[1] + '">' + split_string[0] + '</a>';
				}
				$('#caption').html(caption);
			}
			
			function onAfter(curr,next,opts) {
				var info_string=(this.id),
					split_string=info_string.split('|||');
				if (split_string[0]=="video" ) {
					var caption = '<a href="?page=viewMedia">Latest videos</a>';
				}
				else {
					var caption = '<a href="?page=viewGallery&amp;gallery_id=' + split_string[1] + '">' + split_string[0] + '</a>';
				}
				$('#caption').html(caption);
			}
		}
	});
	
	
};



function ucfirst(str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}
(function(e){e.fn.jTweetsAnywhere=function(a){a=e.extend({username:"BecKorfballClub",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);
