var BELOJS = (typeof BELOJS === "object") ? BELOJS : {};

function setcookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    var rootdomain = document.domain.substring(document.domain.search(/(\w+\.\w+)$/));
    document.cookie = name+"="+value+expires+"; domain="+rootdomain+";path=/";
}
function readcookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
BELOJS.reg = {
	getnow:function() {
		return Number(new Date().getTime());
	},
	init:function(token) {
		callback={
			"success":"initSuccess",
			"fail":"initfail"
			}
		genus.init(token,callback);
	},
	pagecount:{
		get:function() {
			var pagecount = Number(genus.readcookie("BELO_PageCount"));
			var countts = genus.readcookie("BELO_CountTS");
			if(pagecount == null || countts == null) {
				BELOJS.reg.pagecount.reset();
				pagecount = 1;
			}
			return pagecount;
		},
		reset:function() {
			var now = BELOJS.reg.getnow();
			genus.setcookie("BELO_PageCount",1);
			genus.setcookie("BELO_CountTS",now);
		},
		increment:function() {
			var pagecount = Number(genus.readcookie("BELO_PageCount"));
			var countts = Number(genus.readcookie("BELO_CountTS"));
			// Get Current Timestamp
			var now = BELOJS.reg.getnow();
			// Expire in 30 Minutes
			var deadtime = (30-((now-countts)/1000/60));
			if(pagecount == null || countts == null || deadtime < 0) {
				BELOJS.reg.pagecount.reset();
				pagecount = 0;
			}
			genus.setcookie("BELO_PageCount",pagecount+1);
		}
	},
	optout: {
		get:function() {
			var optout = genus.readcookie("BELO_OptOut");
			return (optout)?true:false;				
		},
		set:function() {
			genus.setcookie("BELO_OptOut","true",30);
		},
		clear:function() {
			genus.setcookie("BELO_OptOut","");
		}
	}
};

BELOJS.reg.openSSOReg = function() {
	BELOJS.reg.resetModal();
	bimreg.listener.removeListener("ssoWindowClose",BELOJS.reg.showLoginModal);
	$("#regModal").dialog({ 
		title: '<h2 >Verify your information supplied by <span class="ssoService"></span>:</h2>' 
	});
	$("#regOptions").hide();
	$("#regModal #register, #regModal #ssoReg").removeClass("hide").show();
	$(".ui-dialog-titlebar-close").hide();
}

BELOJS.reg.startSSO = function(){
	$("#regModal .ssoService").text(bimreg.ssoservice);
	BELOJS.reg.resetModal();
	$(".ui-dialog-titlebar-close").hide();
	$("#regModal").dialog({ 
		title: '<h2 >Accessing <span class="ssoService"></span>:</h2>' 
	});	
	$("#ssoInProcess").removeClass("hide").show();
	bimreg.listener.addListener("ssoWindowClose",BELOJS.reg.showLoginModal);
}

BELOJS.reg.resetModal = function() {
	$("#regModal #loginwrapper,#regModal #register,#regModal #regNewsletters, #userCreatedThanks, #ssoInProcess, #normReg, #ssoReg, #loading-user").hide();
	$("#overlayLogin #loading-user").remove();
	$("#overlayLogin .login-submit").show();
	$(".ui-dialog-titlebar-close").show();
}

BELOJS.reg.showRegModal = function(){
	BELOJS.reg.resetModal();
	$("#regOptions").show();
	$("#regModal").dialog({ title: '<h2>Create an account</h2>' });
    $("#normregoption").addClass("selected");
    $("#regModal #register, #regModal #normReg").removeClass("hide").show();
    bimreg.listener.removeListener("ssoWindowClose",BELOJS.reg.showLoginModal);
    Recaptcha.create(
    	"6LdR_QcAAAAAADreWCjddEjPzu0iGV8u-fdy-UW0",
	    "modal_recaptcha_div",
	    {theme: "white"}
	);
    return false;	
}

BELOJS.reg.showNewslettersReg = function() {
	BELOJS.reg.resetModal();
	$(".ui-dialog-titlebar-close").hide();
	$("#newsletterUpdate").show();
	$("#loading-user-newsletter").hide();
	$("#regModal #regNewsletters").show().removeClass("hide");
}

BELOJS.reg.showThankYou = function() {
	BELOJS.reg.resetModal();
	$("#regModal").dialog({ title: '<h2>Thank you for registering!</h2>' });
	$("#userCreatedThanks").show().removeClass("hide");
}

BELOJS.reg.showLoginModal = function() {
	BELOJS.reg.resetModal();
	$("#regModal").removeClass("hide").dialog("open");
	$("#memBenies").removeClass("hide");
	$("#regModal").dialog({ 
		title: '<h2 class="halfTitle">Sign in with your azfamily.com account:</h2><h2 class="halfTitle">Or connect via the following websites:</h2>' 
	});
	$("#loginwrapper").show();
}

BELOJS.reg.closeModal = function() {
	BELOJS.reg.resetModal();
	$("#regModal").dialog("close");
}

BELOJS.reg.loginModalClose = function() {
	if($("#regModal").is(":visible")){
		$("#regModal").dialog("close");
		$("#overlayLogin .login-submit").show();
		$("#overlayLogin input").attr("readonly", false);
		$("#loading-user").hide();
	}
	bimreg.listener.removeListener("userLogin",BELOJS.reg.loginModalClose);
}

BELOJS.reg.onfailLogin = function(event) {
	//Normal failed login code
	$("#status-loggingin").hide();
	$("#login-nav").show();
	$(".signin").addClass("menu-open");
	$("#toolbar-status ul").hide();
	$("#toolbar-status").hide();
	var ul = document.createElement("ul");        
	var txt = document.createTextNode(event.error);
	var li = document.createElement("li");
	li.appendChild(txt);
	ul.appendChild(li);
	$("#overlayLogin .loginError").empty().append(ul);
	$("#overlayLogin .loginError").addClass("error-message");
	$("#overlayLogin .login-submit").show();
	$("#overlayLogin input").attr("readonly", false);
	$("#status-loggingin").hide();
	$("#loading-user").hide();
}
bimreg.listener.addListener("failedLogin",BELOJS.reg.onfailLogin);

BELOJS.reg.createmodaluser = function() {
	var nlform = document.newsletterSignup;
	var password = $("#reg_pass").val();
	var password1 = password.replace(/^\s*|\s*$/g,'');
	user = {
		"username":$("#reg_userName").val(),
		"password":password1,
		"email":$("#reg_email").val(),
		"birth_date":$("#reg_birthYear").val()+"-01-01T00:00:00Z",
		"zip_code":$("#reg_zip").val(),
		"AZFAMILY_SPECIALS":$("input#reg_specials:checked").val() ? 1 : 0,
		"BELONATIONAL_SPECIALS":$("input#reg_specials:checked").val() ? 1 : 0
	}
			user["AZFAMILY_NEWS"] = (nlform["AZFAMILY_NEWS"].checked)?"1":"";
			user["AZFAMILY_BREAK"] = (nlform["AZFAMILY_BREAK"].checked)?"1":"";
			user["AZFAMILY_SPORTS"] = (nlform["AZFAMILY_SPORTS"].checked)?"1":"";
			user["AZFAMILY_SPORTS_BREAK"] = (nlform["AZFAMILY_SPORTS_BREAK"].checked)?"1":"";
			user["AZFAMILY_RECIPES"] = (nlform["AZFAMILY_RECIPES"].checked)?"1":"";
			user["AZFAMILY_HEALTH"] = (nlform["AZFAMILY_HEALTH"].checked)?"1":"";
			user["AZFAMILY_PETS"] = (nlform["AZFAMILY_PETS"].checked)?"1":"";
			user["AZFAMILY_EDUCATION"] = (nlform["AZFAMILY_EDUCATION"].checked)?"1":"";
			user["AZFAMILY_TODAYINHISTORY"] = (nlform["AZFAMILY_TODAYINHISTORY"].checked)?"1":"";
			user["AZFAMILY_ENTERTAINMENT"] = (nlform["AZFAMILY_ENTERTAINMENT"].checked)?"1":"";
			user["AZFAMILY_MUSIC"] = (nlform["AZFAMILY_MUSIC"].checked)?"1":"";
			user["AZFAMILY_NEWSCHANNEL"] = (nlform["AZFAMILY_NEWSCHANNEL"].checked)?"1":"";
			user["AZFAMILY_EVENTS"] = (nlform["AZFAMILY_EVENTS"].checked)?"1":"";
		$("#regUpdateProf").hide();
	$("#normFormSubmit .loadingHolder").append('<span id="loading-user"><img src="'+ajaxImgObj+'" id="loadingGraphic" />Registering User...</span>');
	$(".errors").empty();
	bimreg.createuser(user);
};

BELOJS.reg.modalcreateuserfail = function(status){
	BELOJS.reg.showRegModal();
	var ul = document.createElement("ul");
	var txt = document.createTextNode(status.error);
	var li = document.createElement("li");
	li.appendChild(txt);
	ul.appendChild(li);
	$("#regUpdateProf").show();
	$("#normReg #loading-user").empty();
	$("#normFormSubmit .error").empty().append(ul).show();
}
bimreg.listener.addListener("userNotCreated",BELOJS.reg.modalcreateuserfail);

BELOJS.reg.modalUserCreated = function(){
	BELOJS.reg.showThankYou();
}

bimreg.listener.addListener("userCreated",BELOJS.reg.modalUserCreated);

$("#reg_birthYear").change(function(){
    var year = $("#reg_birthYear").val();
    var mydate = new Date();
    var month = 01;
    var day = 01;
    mydate.setFullYear(year,month,day);
    $("#reg_birthdateobject").val(mydate);
});

function completeSsoReg() {
	var password = $("#sso_pass").val();
	var password1 = password.replace(/^\s*|\s*$/g,'');
	var user = {
		username: $("#sso_userName").val(),
		email : $("#sso_email").val(),
		password: password1,
		zip_code : $("#sso_zip").val(),
		"birth_date":$("#sso_birthYear").val()+"-01-01T00:00:00Z",
		"AZFAMILY_SPECIALS":$("input#sso_specials:checked").val() ? 1 : 0,
		"BELONATIONAL_SPECIALS":$("input#sso_specials:checked").val() ? 1 : 0
	};
	$("#ssoUpdateProf").hide();
	$("#sso_dataNeeded input").attr("readonly", true);
	$("#sso_dataNeeded .loadingHolder").html('<span id="loading-user-sso"><img src="'+ajaxImgObj+'" id="loadingGraphicSso" />Registering User...</span>');
	bimreg.completessoreg(user);
	bimreg.listener.addListener("completeSSOReg",BELOJS.reg.closeModal);
	$("#sso_updateProf .error span").empty();
	return false;
};

BELOJS.reg.ssoModal = function(){
	if(bimreg.ssoservice != 'twitter'){
		$("#sso_email").val(bimreg.getuserkey("email"));
	}
	$("#sso_pass").val('');
	$("#sso_zip").val(bimreg.getuserkey("zip_code"));
	
	$("#ssoReg").validate({
		rules:{
			sso_birthdateobject:{oldenough : true},
			sso_zipcode:{postalcode : true}
		},
		submitHandler: function(form) {
			$("div.error").hide();
			completeSsoReg();
		},
		invalidHandler: function(form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
				? 'You missed 1 field. It has been highlighted'
				: 'You missed ' + errors + ' fields. They have been highlighted';
				$("#sso_dataNeeded div.error span").html(message);
				$("#sso_dataNeeded div.error").show();
			} else {
				$("#sso_dataNeeded div.error").hide();
			}
		}
	});
	
	BELOJS.reg.resetModal();
	$("#regOptions").hide();
	BELOJS.reg.openSSOReg();
	$("#regModal").dialog('open');
	$("#sso_userName").focus();
}
bimreg.listener.addListener("userregsso",BELOJS.reg.ssoModal);

BELOJS.reg.ssoRegFailure = function(status){
	var ul = document.createElement("ul");
	var txt = document.createTextNode(status.error);
	var li = document.createElement("li");
	li.appendChild(txt);
	ul.appendChild(li);
	$("#sso_updateProf .error span").empty().append(ul).show();
	$("#sso_updateProf .error").show();
	$("#ssoUpdateProf").show();
	$("#sso_dataNeeded input").attr("readonly", false);
	bimreg.listener.removeListener("completeSSOReg",BELOJS.reg.closeModal);
}
bimreg.listener.addListener("SSORegFail",BELOJS.reg.ssoRegFailure);

BELOJS.reg.ssoLoginFail = function(error){
	BELOJS.reg.showLoginModal();
	$("#ssoLoginOpts .errors").empty().append(error);
}

bimreg.listener.addListener("failedRegsso",BELOJS.reg.ssoLoginFail);

(function beloRememeberMe() {
	if(genus.readcookie("BELO_rememberme")) {
		$("#overlayUsername").val(genus.readcookie("BELO_rememberme"));
		$("#rememberMe").attr("checked","true");
	}
})();

function loadCarousel(){
	$('ul#myRoundabout').roundabout({
		startingChild: 3,
		btnNext: '#carousel-right',
        btnPrev: '#carousel-left',
        minOpacity: 0.0, // invisible!
         minScale: 0.1 // tiny!
	});
};



BELOJS.winRefresh = {
	init: function(int) {
		if (typeof(int) === "number") {
			this.refreshInt = int;
			this.startTime = new Date().getTime();
			this.staticInt = int;
			this.run();	
		}
	},
	pause: function() {
		window.clearInterval(this.refreshId);
		this.refreshInt = this.refreshInt - (new Date().getTime() - this.startTime);
    },
	refresh: function() {
                var articleList1 = [
            "Sat Feb 11 20:41:48 PST 2012","Sat Feb 11 16:21:46 PST 2012","Sat Feb 11 16:33:17 PST 2012","Sat Feb 11 16:09:41 PST 2012","Fri Feb 10 18:27:27 PST 2012","Sat Feb 11 15:23:48 PST 2012","Sat Feb 11 15:24:34 PST 2012","Fri Feb 10 16:12:14 PST 2012","Fri Feb 10 09:25:53 PST 2012","Fri Feb 10 16:01:25 PST 2012","Fri Feb 10 09:41:50 PST 2012","Fri Feb 10 06:53:22 PST 2012","Sat Feb 11 19:05:47 PST 2012","Thu Feb 09 19:18:43 PST 2012","Fri Feb 10 12:48:25 PST 2012","Thu Feb 09 13:38:49 PST 2012","Fri Feb 10 10:48:42 PST 2012","Fri Feb 10 10:45:46 PST 2012"         ];
        
                var articleList2 = [
                     ];
        
                var articleList3 = [
                     ];
    
                var articleList4 = [
            "Sat Feb 11 20:41:48 PST 2012","Fri Feb 10 11:42:49 PST 2012","Sat Feb 11 16:21:46 PST 2012","Fri Feb 10 09:41:50 PST 2012","Fri Feb 10 10:16:06 PST 2012","Fri Feb 10 10:53:39 PST 2012"         ];
        
        jQuery.get(
            "http://www.azfamily.com/internal?get=belohomeupdated",
            "",
            function(data) {
                var i = 0;
                var j = 0;
                var refresh = false;
                for (arr in data) {
                    j = j + 1;
                    for (story in data[arr]) {
                        if (j = 1) {
                            if (story != articleList1[i]) {
                                refresh = true;
                            }
                        } else if (j = 2) {
                            if (story != articleList2[i]) {
                                refresh = true;
                            }
                        } else if (j = 3) {
                            if (story != articleList3[i]) {
                                refresh = true;
                            }
                        } else if (j = 4) {
                            if (story != articleList4[i]) {
                                refresh = true;
                            }
                        }
                        i = i + 1;
                    }
                    if ($('.bimVideoPlayer').length > 0) {
	 	               ///check the state of any video players on the page before restarting
	 	               		$f("*").each(function() {
						      var player = this;
						      if(player.isLoaded()){
						         if(player.isPlaying()){
						            refresh=false;
						         }
						       }
						   });
		            }	
                    if (refresh == true && !$("#regModal").is(":visible")) {
                        window.location.reload(true);
                    }  else {
						BELOJS.winRefresh.init(300000);  
                    }
                }
            },
            "json"
        );
	},
	restart: function() {
		var fnContext = this;
		this.refreshId = window.setTimeout(function(){
			fnContext.refresh();
			fnContext.refreshInt = fnContext.staticInt;
			fnContext.run();
		}, this.refreshInt);
	},
	run: function() {
		if (this.refreshId !== "undefined") {
			window.clearInterval(this.refreshId);
		}
		var fnContext = this;
		this.refreshId = setTimeout(function() {
			fnContext.refresh();
		}, this.refreshInt);
	}
};




//Commenting code

	//Function that shows all comment tools, called from bottom
		function showcommentTools() {
			if ($("#comments-post").size() > 0) {
				var username = bimreg.getuserkey("username");
			 	$("#post-author").val(username);   
	            $("#post-email").val(username);
	            $("#comments-post").show().removeClass("hide");
	            $("#comments-message").hide();
				$('.commentFlag').removeClass('hide');
				$('.commentFlag').addClass('jqModal');
			}
		};
		
	//Function that hides all comment tools, called from bottom
		function hidecommentTools() {
            $("#post-author").val("");
            $("#post-email").val("");
            $("#comments-post").hide();
            $("#comments-message").show();
            $('.commentFlag').addClass('hide');
			$('.commentFlag').removeClass('jqModal');
		};

//Jquery plugin for scrollers
(function($){  
 $.fn.beloScroll = function() {  
    return this.each(function() {  
    	var options = {  
			defaultSpeed: 1,  
			fastForward: 3,  
			currentSpeed: 1,  
			controlWidth: 460,  
			weatherWidth: 0  
		};
    	var wxScrollweatherWidth = 0;
    	var obj = this;
    	var scrollItem = $(".scrollMask ul", obj);
    	var width = 0
		$(scrollItem).find("li:not(.end)").each(function(){
		    width += $(this).outerWidth();
		})
		if(width > $(".scrollMask").innerWidth()){
	    	//this is to add a little buffer that is the same width as the viewport
	    	var viewPortWidth = parseInt($(".scrollMask", obj).outerWidth());
	    	var scrollItemWidth = viewPortWidth + 80; // ensurance
	    	var currentPos = 0;
	    	$('li',scrollItem).each(function (options) {
				scrollItemWidth = scrollItemWidth + $(this).outerWidth();
			});
			scrollItem.css('left',  viewPortWidth + "px");
			setInterval(function() {
				//Get the weather Alert container
				currentPos = Math.abs(scrollItemWidth + currentPos + options.currentSpeed) % scrollItemWidth;
				scrollItem.css('left', viewPortWidth - currentPos + "px");
			},30)
			$('.back, .forward', obj).css("display","block");
			//Hover
			$('.scrollMask ul', obj).hover(function (){options.currentSpeed = 0;}, function (){options.currentSpeed = options.defaultSpeed;});
			//Backwards
			$('.back', obj).hover(function (){options.currentSpeed=-3*options.defaultSpeed;}, function (){options.currentSpeed = options.defaultSpeed;});
			//faster
			$('.forward', obj).hover(function (){options.currentSpeed=options.fastForward;}, function (){options.currentSpeed = options.defaultSpeed;});
		}else{
			$('.back, .forward', obj).hide().css("background","none");
		}
    });  
 };  
})(jQuery);

//Standard ajax load image
(function($){  
 $.fn.loadingGrapic = function(text, imageSize) {  
    return this.each(function() {
    	if(imageSize = "small"){
    		var	ajaxImgObj = 'http://media.king5.com/designimages/belo_ajax-loader-s.gif';
    	}else{
			var	ajaxImgObj = 'http://media.king5.com/designimages/belo_ajax-loader2.gif';
    	}
		var obj = this;
		if(text) {
			var displayText = text;
		}else{
			var displayText = "Updating Profile...";
		}
		$(obj).html('<span id="loading-user"><img src="'+ajaxImgObj+'" id="loadingGraphic" />' + displayText + '</span>');
   	});  
 };  
})(jQuery);

//Newsletter widget code
(function($){  
 $.fn.newsletterwidget = function(options) {
 	return this.each(function() {
 		var settings ={} 
 		jQuery.extend(settings, options);
 		var obj = this;
	    var enteredEmail = $("#widget-email", obj).val();
	    if(settings.multi){
			var currentNewsletter = $(".datranNewsletterName", obj);
	    }else{
	    	var currentNewsletter = $(".datranNewsletterName", obj).val();
	    };
		newsletterwidget = {};
	 	function loadingNewsletter(ajaxText) {
			$("#widget-email", obj).hide();
			$("input[type=submit]", obj).addClass("hide");
			$("#loading", obj).loadingGrapic(ajaxText);	
		}
 		function emailCheck(email) {
			newsletterwidget.checkemail = true;
			newsletterwidget.enteredEmail = enteredEmail;
			setcookie("BELO_newsletterAutoSelect", -1, -1);
			if(settings.multi){
				currentNewsletter = $(".datranNewsletterName");
				var user = {}
				currentNewsletter.each(function(){
						var newsletterName = $(this)
						if(newsletterName.attr("checked") || newsletterName.attr("type") == "hidden"){
							user[newsletterName.attr("id")] = 1;
						}
				});
				user = JSON.stringify(user);
				setcookie("BELO_newsletterAutoSelect",user,1);
		    }else{
		    	var user = {}
		    	user[currentNewsletter] = 1;
		    	user = JSON.stringify(user);
				setcookie("BELO_newsletterAutoSelect",user,1);
		    } 
			setcookie("BELO_newsletterEmailAddress", -1, -1);
			setcookie("BELO_newsletterEmailAddress",enteredEmail,1);
 			bimreg.emailcheck(email);
			
			function _userIsThere() {
				//go to login page and store signup data after sign in update profile/goto to thank you page.
				newsletterwidget.checkemail = false;
				bimreg.logoutRedirect = '/register/?form=login&newsletterDocReferrer='+encodeURI(window.location);
				if(bimreg.loggedin) {
					belologout(belologoutFromNav);
				}else{
					window.location = '/register/?form=login&newsletterDocReferrer='+encodeURI(window.location);
				}
				bimreg.listener.removeListener("checkedUserEmailAvailable",_userNotThere);
				bimreg.listener.removeListener("checkedEmailExists",_userIsThere);
			}
			bimreg.listener.addListener("checkedEmailExists",_userIsThere);
			function _userNotThere(){
				//no matching email goes to reg
				newsletterwidget.checkemail = false;
				bimreg.logoutRedirect = '/register/?form=signup&docReferrer='+encodeURI(window.location);
				if(bimreg.loggedin) {
					belologout(belologoutFromNav);
				}else{
					window.location = '/register/?form=signup&docReferrer='+encodeURI(window.location);
				}
				bimreg.listener.removeListener("checkedUserEmailAvailable",_userNotThere);
				bimreg.listener.removeListener("checkedEmailExists",_userIsThere);
			}
			bimreg.listener.addListener("checkedUserEmailAvailable",_userNotThere);
 		} 
		if(bimreg.loggedin) {
			if(enteredEmail == bimreg.getuserkey("email")) {
                var user = {}
				//add loading graphic remove button and form fields
				loadingNewsletter();
				if(settings.multi){
					currentNewsletter.each(function(){
							var newsletterName = $(this)
							user[newsletterName.attr("id")] = (newsletterName.attr("checked")|| newsletterName.attr("type") == "hidden") ? 1 : 0;
					});
			    }else{
			    	user[currentNewsletter] = 1;
			    } 
				bimreg.updateprofile(user);
                return false;
				//error handling
			} else {
				//sign out go to login store signup data after sign in update profile/goto to thank you page.
                loadingNewsletter("Verifying Your E-mail Address...");
                emailCheck(enteredEmail);
                return false;
			}   
		}  else {
			loadingNewsletter("Verifying Your E-mail Address...");
			emailCheck(enteredEmail);
		}

   	});  
 };
 
 
 // VERTICALLY ALIGN FUNCTION
	jQuery.fn.vAlign = function() {
		return this.each(function(i){
		var ah = $(this).height();
		var ph = $(this).parent().height();
		var mh = (ph - ah) / 2;
		$(this).css('margin-top', mh);
		});
	};
 
 //Add html5 placeholder functionality
 	jQuery.fn.placeholder = function(options) {
		settings = jQuery.extend({
			onClass: 'focused',
			offClass: false,
			placeholderSupport: (function(){
				return 'placeholder' in document.createElement('input');
			})()
		}, options);
		return this.each(function() {
			var input = this;
			if(!settings['placeholderSupport']){
				input.defaultValue = $(input).attr('placeholder');
				$(input).blur();
			}
			$(input).bind('focus', function(){
				if(!settings['placeholderSupport'] && ($(this).val() == this.defaultValue)) $(this).val('');
				if(settings['onClass']) $(this).addClass(settings['onClass']);
				if(settings['offClass']) $(this).removeClass(settings['offClass']);
			}).bind('blur', function(){
				if(!settings['placeholderSupport'] && !$(this).val().length){
					$(this).val(this.defaultValue);
					if(settings['offClass']) $(this).addClass(settings['offClass']);
				}
				if(settings['onClass']) $(this).removeClass(settings['onClass']);
			});
			$(input).closest('form').bind('submit', function(){
				if($(input).val() == input.defaultValue) $(input).val('');
			});
		});
	};
  
})(jQuery);

function newsletterSelect() {
 	var newslettersToSelect = readcookie('BELO_newsletterAutoSelect');
 	if(newslettersToSelect) {
	 	$("#" + newslettersToSelect).attr('checked', true);
	 	$("#reg-specialoffers").attr('checked', false);
	 	setcookie("BELO_newsletterAutoSelect", -1, -1);
 	}
 };

(function($){  
	$.fn.emailAddressSet = function() { 
		return this.each(function() {
			var userEmail = readcookie('BELO_newsletterEmailAddress');
			setcookie("BELO_newsletterEmailAddress", -1, -1);
			$(this).val(userEmail);	
		});
	};
})(jQuery);

function readingList(options){
	
	function supports_html5_storage() {
	  try {
	    return 'localStorage' in window && window['localStorage'] !== null;
	  } catch (e) {
	    return false;
	  }
	}
	
	function addBookmark(foo){
		//store the object in local storage as json.
		var storeName = foo.url;
		var jsonString = JSON.stringify(foo);
		localStorage.setItem(storeName,jsonString);
		resetList();
		if($("#selectedReadings:visible").length == 0){
			$("#showReadingList").trigger("click");	
		}
	};
	
	function setUpList(){
		var readingList = $("#selectedReadings");
		
		for (var i=0, l=localStorage.length; i<l; i++){
        	var item = localStorage.key(i);
			if(localStorage[item] != "null" && localStorage[item] != "undefined"){
				jsObject = JSON.parse(localStorage[item])
				var name = jsObject.name;
				name = unescape(name)
				if(typeof(jsObject) == "object" && jsObject.hasOwnProperty("name") && jsObject.hasOwnProperty("url")){
					var html="<li class='list-item'><a href='"+jsObject.url+"' title='"+name+"'>"+name+"</a><span class='delete-item' data-item-id='"+jsObject.url+"'>X</span></li>"
					readingList.append(html);
				}
			}
		}
		//setup deletion
		$("#selectedReadings .delete-item").click(function(){
			deleteItem(this);
		});
	};
	
	function resetList(){
		$("#selectedReadings li").remove()
		setUpList();	
	}
	
	function deleteItem(el){
		var id = $(el).attr("data-item-id");
		localStorage.removeItem(id);
		resetList();
	};
	
	function bookmarkBarSetup(){
		//create tools
		$("body").append("<div id='show-pers-toolbar' class='hide'><a href='#' id='showtools'>Show Tools</a></div>");
		$("body").append("<div id='pers-toolbar'><div id='pers-toolbar-inner'></div></div>");
		var toolbar = $("#pers-toolbar-inner");
		var html = "<a href='#' id='hidetools'>Close Tools</a><img src='http://cdn.bimfs.com/BIM/94c79496c9f308c8957cbb810d4f196a.jpg' alt='avatar' class='avatar' /><div class='user-info'><a href='#' class='login'>Login</a><a href='/profile' class='profile hide'>Edit Profile</a></div><div id='centerToolbarContent'></div>";
		toolbar.append(html);
		var html = "<div id='reading-wrapper'><ul id='selectedReadings' class='hide'><li id='direction'>Add stories to your reading list by click on the<span></span>icon next to the story's title.</li></ul></div>"
		$("body").append(html)
		var html = "<div id='readingList'><a href='#' id='showReadingList' title='view reading list'>View Reading List</a></div>"
		//add tools to the tool bar
		toolbar.append(html);
		if(options.sharetools){
			var html = "<span class='shareTools'><a href='#' class='facebook-share'>Share On Facebook</a><a href='#' class='twitter-share'>Tweet</a><span class='google-share'><g:plusone size='small' count='false'></g:plusone>Google +1</span></span>"
			$("#centerToolbarContent").append(html);
		}
		if(options.comment && options.sharetools){
			var html = "<a href='#commentform' class='comment'>Comment</a>"
			$("#centerToolbarContent .shareTools").append(html);
			$("#centerToolbarContent .shareTools .twitter-share").click(function(){
				var el = $("#imwarelist .tool-twitter-custom a:first");
				var location= el.attr("href");
				el.trigger("click");
				window.open(location);
				return false;
			});
			$("#centerToolbarContent .shareTools .facebook-share").click(function(){
				$("#imwarelist .tool-facebook a:first").trigger("click");
				return false;
			});
		}
		var readingList = $("#selectedReadings");
		setUpList();
		$("#showReadingList").click(function(){
			readingList.slideToggle();
			return false;
		});	
		readingList.removeClass("hide");
		$("#selectedReadings").slideToggle();
		$("#pers-toolbar a.login").click(function(e) {
		   	modalShow();
		   	return false;
		});
		
		$("#pers-toolbar #hidetools").click(function(){
			
		    if($("#selectedReadings:visible").length > 0 && !genus.readcookie("Belo_tools_hide")){
		    	readingList.slideToggle(function(){$("#pers-toolbar").hide()});
		    }else{
		    	$("#pers-toolbar").hide();	
		    }
		    genus.setcookie("Belo_tools_hide",true);
		    $("#show-pers-toolbar").removeClass("hide");
		    return false;
		});
		
		$("#show-pers-toolbar a").click(function(){
			genus.setcookie("Belo_tools_hide","");
		    $("#pers-toolbar").show();
		    $("#show-pers-toolbar").addClass("hide");
		    return false;
		});
		
		if(genus.readcookie("Belo_tools_hide")){
			$("#pers-toolbar #hidetools").trigger("click");
		}
	}
	
	function toolsloginEvents(){
		$("#pers-toolbar a.login").hide();
		$("#pers-toolbar a.profile").removeClass("hide");
		if(typeof bimreg.getuseravatar() != "undefined"){
			$("#pers-toolbar .avatar").attr("src",bimreg.getuseravatar())
		}
	}
	
	function toolslogoutEvents(){
		$("#pers-toolbar a.login").show();
		$("#pers-toolbar a.profile").addClass("hide");
		$("#pers-toolbar .avatar").attr("src","http://cdn.bimfs.com/BIM/94c79496c9f308c8957cbb810d4f196a.jpg")
	}
	
	function init(){
		//setup boomark buttons
		$("ul li a.addToList").each(function(){
		    $(this).removeClass("hide").show();
		});
		
		bimreg.listener.addListener("userLogin",toolsloginEvents);
		bimreg.listener.addListener("userLogout",toolslogoutEvents);
		
		
		$(".addToList").click(function(){
		    var link = $(this).siblings("a.storyLink");
		    var bookmark = {}
		    bookmark.name = escape(link.text());
		    bookmark.url = link.attr("href");
		    if($("#pers-toolbar:visible").length == 0){
		    	$("#show-pers-toolbar a").trigger("click")
		    }
		    addBookmark(bookmark);
		    return false;
		});
		//setup bookmark bar
		bookmarkBarSetup();
		
		//check current story to see if it is in the list set current attr as appropriate
		
	};
	
	if(supports_html5_storage()){
		//if local storage is available, start the bookmarks
		init();	
	}
};

/**
 * jQuery Roundabout - v1.1
 * http://fredhq.com/projects/roundabout/
 *
 * Moves list-items of enabled ordered and unordered lists long
 * a chosen path. Includes the default "lazySusan" path, that
 * moves items long a spinning turntable.
 *
 * Terms of Use // jQuery Roundabout
 * 
 * Open source under the BSD license
 *
 * Copyright (c) 2010, Fred LeBlanc
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above 
 *     copyright notice, this list of conditions and the following 
 *     disclaimer in the documentation and/or other materials provided 
 *     with the distribution.
 *   - Neither the name of the author nor the names of its contributors 
 *     may be used to endorse or promote products derived from this 
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 */

jQuery.extend({roundabout_shape:{def:'lazySusan',lazySusan:function(r,a,t){return{x:Math.sin(r+a),y:(Math.sin(r+3*Math.PI/2+a)/8)*t,z:(Math.cos(r+a)+1)/2,scale:(Math.sin(r+Math.PI/2+a)/2)+0.5}}}});jQuery.fn.roundabout=function(){var options=(typeof arguments[0]!='object')?{}:arguments[0];options={bearing:(typeof options.bearing=='undefined')?0.0:jQuery.roundabout_toFloat(options.bearing%360.0),tilt:(typeof options.tilt=='undefined')?0.0:jQuery.roundabout_toFloat(options.tilt),minZ:(typeof options.minZ=='undefined')?100:parseInt(options.minZ,10),maxZ:(typeof options.maxZ=='undefined')?400:parseInt(options.maxZ,10),minOpacity:(typeof options.minOpacity=='undefined')?0.40:jQuery.roundabout_toFloat(options.minOpacity),maxOpacity:(typeof options.maxOpacity=='undefined')?1.00:jQuery.roundabout_toFloat(options.maxOpacity),minScale:(typeof options.minScale=='undefined')?0.40:jQuery.roundabout_toFloat(options.minScale),maxScale:(typeof options.maxScale=='undefined')?1.00:jQuery.roundabout_toFloat(options.maxScale),duration:(typeof options.duration=='undefined')?600:parseInt(options.duration,10),btnNext:options.btnNext||null,btnPrev:options.btnPrev||null,easing:options.easing||'swing',clickToFocus:(options.clickToFocus!==false),focusBearing:(typeof options.focusBearing=='undefined')?0.0:jQuery.roundabout_toFloat(options.focusBearing%360.0),shape:options.shape||'lazySusan',debug:options.debug||false,childSelector:options.childSelector||'li',startingChild:(typeof options.startingChild=='undefined')?null:parseInt(options.startingChild,10),reflect:(typeof options.reflect=='undefined'||options.reflect===false)?false:true};this.each(function(i){var ref=jQuery(this);var period=jQuery.roundabout_toFloat(360.0/ref.children(options.childSelector).length);var startingBearing=(options.startingChild===null)?options.bearing:options.startingChild*period;ref.addClass('roundabout-holder').css('padding',0).css('position','relative').css('z-index',options.minZ);ref.data('roundabout',{'bearing':startingBearing,'tilt':options.tilt,'minZ':options.minZ,'maxZ':options.maxZ,'minOpacity':options.minOpacity,'maxOpacity':options.maxOpacity,'minScale':options.minScale,'maxScale':options.maxScale,'duration':options.duration,'easing':options.easing,'clickToFocus':options.clickToFocus,'focusBearing':options.focusBearing,'animating':0,'childInFocus':-1,'shape':options.shape,'period':period,'debug':options.debug,'childSelector':options.childSelector,'reflect':options.reflect});if(options.clickToFocus===true){ref.children(options.childSelector).each(function(i){jQuery(this).click(function(e){var degrees=(options.reflect===true)?360.0-(period*i):period*i;degrees=jQuery.roundabout_toFloat(degrees);if(!jQuery.roundabout_isInFocus(ref,degrees)){e.preventDefault();if(ref.data('roundabout').animating===0){ref.roundabout_animateAngleToFocus(degrees)}return false}})})}if(options.btnNext){jQuery(options.btnNext).bind('click.roundabout',function(e){e.preventDefault();if(ref.data('roundabout').animating===0){ref.roundabout_animateToNextChild()}return false})}if(options.btnPrev){jQuery(options.btnPrev).bind('click.roundabout',function(e){e.preventDefault();if(ref.data('roundabout').animating===0){ref.roundabout_animateToPreviousChild()}return false})}});this.roundabout_startChildren();if(typeof arguments[1]==='function'){var callback=arguments[1],ref=this;setTimeout(function(){callback(ref)},0)}return this};jQuery.fn.roundabout_startChildren=function(){this.each(function(i){var ref=jQuery(this);var data=ref.data('roundabout');var children=ref.children(data.childSelector);children.each(function(i){var degrees=(data.reflect===true)?360.0-(data.period*i):data.period*i;jQuery(this).addClass('roundabout-moveable-item').css('position','absolute');jQuery(this).data('roundabout',{'startWidth':jQuery(this).width(),'startHeight':jQuery(this).height(),'startFontSize':parseInt(jQuery(this).css('font-size'),10),'degrees':degrees})});ref.roundabout_updateChildPositions()});return this};jQuery.fn.roundabout_setTilt=function(newTilt){this.each(function(i){jQuery(this).data('roundabout').tilt=newTilt;jQuery(this).roundabout_updateChildPositions()});if(typeof arguments[1]==='function'){var callback=arguments[1],ref=this;setTimeout(function(){callback(ref)},0)}return this};jQuery.fn.roundabout_setBearing=function(newBearing){this.each(function(i){jQuery(this).data('roundabout').bearing=jQuery.roundabout_toFloat(newBearing%360,2);jQuery(this).roundabout_updateChildPositions()});if(typeof arguments[1]==='function'){var callback=arguments[1],ref=this;setTimeout(function(){callback(ref)},0)}return this};jQuery.fn.roundabout_adjustBearing=function(delta){delta=jQuery.roundabout_toFloat(delta);if(delta!==0){this.each(function(i){jQuery(this).data('roundabout').bearing=jQuery.roundabout_getBearing(jQuery(this))+delta;jQuery(this).roundabout_updateChildPositions()})}if(typeof arguments[1]==='function'){var callback=arguments[1],ref=this;setTimeout(function(){callback(ref)},0)}return this};jQuery.fn.roundabout_adjustTilt=function(delta){delta=jQuery.roundabout_toFloat(delta);if(delta!==0){this.each(function(i){jQuery(this).data('roundabout').tilt=jQuery.roundabout_toFloat(jQuery(this).roundabout_get('tilt')+delta);jQuery(this).roundabout_updateChildPositions()})}if(typeof arguments[1]==='function'){var callback=arguments[1],ref=this;setTimeout(function(){callback(ref)},0)}return this};jQuery.fn.roundabout_animateToBearing=function(bearing){bearing=jQuery.roundabout_toFloat(bearing);var currentTime=new Date();var duration=(typeof arguments[1]=='undefined')?null:arguments[1];var easingType=(typeof arguments[2]=='undefined')?null:arguments[2];var passedData=(typeof arguments[3]!=='object')?null:arguments[3];this.each(function(i){var ref=jQuery(this),data=ref.data('roundabout'),timer,easingFn,newBearing;var thisDuration=(duration===null)?data.duration:duration;var thisEasingType=(easingType!==null)?easingType:data.easing||'swing';if(passedData===null){passedData={timerStart:currentTime,start:jQuery.roundabout_getBearing(ref),totalTime:thisDuration}}timer=currentTime-passedData.timerStart;if(timer<thisDuration){data.animating=1;if(typeof jQuery.easing.def=='string'){easingFn=jQuery.easing[thisEasingType]||jQuery.easing[jQuery.easing.def];newBearing=easingFn(null,timer,passedData.start,bearing-passedData.start,passedData.totalTime)}else{newBearing=jQuery.easing[thisEasingType]((timer/passedData.totalTime),timer,passedData.start,bearing-passedData.start,passedData.totalTime)}ref.roundabout_setBearing(newBearing,function(){ref.roundabout_animateToBearing(bearing,thisDuration,thisEasingType,passedData)})}else{bearing=(bearing<0)?bearing+360:bearing%360;data.animating=0;ref.roundabout_setBearing(bearing)}});return this};jQuery.fn.roundabout_animateToDelta=function(delta){var duration=arguments[1],easing=arguments[2];this.each(function(i){delta=jQuery.roundabout_getBearing(jQuery(this))+jQuery.roundabout_toFloat(delta);jQuery(this).roundabout_animateToBearing(delta,duration,easing)});return this};jQuery.fn.roundabout_animateToChild=function(childPos){var duration=arguments[1],easing=arguments[2];this.each(function(i){var ref=jQuery(this),data=ref.data('roundabout');if(data.childInFocus!==childPos&&data.animating===0){var child=jQuery(ref.children(data.childSelector)[childPos]);ref.roundabout_animateAngleToFocus(child.data('roundabout').degrees,duration,easing)}});return this};jQuery.fn.roundabout_animateToNearbyChild=function(passedArgs,which){var duration=passedArgs[0],easing=passedArgs[1];this.each(function(i){var data=jQuery(this).data('roundabout');var bearing=jQuery.roundabout_toFloat(360.0-jQuery.roundabout_getBearing(jQuery(this)));var period=data.period,j=0,range;var reflect=data.reflect;var length=jQuery(this).children(data.childSelector).length;bearing=(reflect===true)?bearing%360.0:bearing;if(data.animating===0){if((reflect===false&&which==='next')||(reflect===true&&which!=='next')){bearing=(bearing===0)?360:bearing;while(true&&j<length){range={lower:jQuery.roundabout_toFloat(period*j),upper:jQuery.roundabout_toFloat(period*(j+1))};range.upper=(j==length-1)?360.0:range.upper;if(bearing<=range.upper&&bearing>range.lower){jQuery(this).roundabout_animateToDelta(bearing-range.lower,duration,easing);break}j++}}else{while(true){range={lower:jQuery.roundabout_toFloat(period*j),upper:jQuery.roundabout_toFloat(period*(j+1))};range.upper=(j==length-1)?360.0:range.upper;if(bearing>=range.lower&&bearing<range.upper){jQuery(this).roundabout_animateToDelta(bearing-range.upper,duration,easing);break}j++}}}});return this};jQuery.fn.roundabout_animateToNextChild=function(){return this.roundabout_animateToNearbyChild(arguments,'next')};jQuery.fn.roundabout_animateToPreviousChild=function(){return this.roundabout_animateToNearbyChild(arguments,'previous')};jQuery.fn.roundabout_animateAngleToFocus=function(target){var duration=arguments[1],easing=arguments[2];this.each(function(i){var delta=jQuery.roundabout_getBearing(jQuery(this))-target;delta=(Math.abs(360.0-delta)<Math.abs(0.0-delta))?360.0-delta:0.0-delta;delta=(delta>180)?-(360.0-delta):delta;if(delta!==0){jQuery(this).roundabout_animateToDelta(delta,duration,easing)}});return this};jQuery.fn.roundabout_updateChildPositions=function(){this.each(function(i){var ref=jQuery(this),data=ref.data('roundabout');var inFocus=-1;var info={bearing:jQuery.roundabout_getBearing(ref),tilt:data.tilt,stage:{width:Math.floor(ref.width()*0.9),height:Math.floor(ref.height()*0.9)},animating:data.animating,inFocus:data.childInFocus,focusBearingRad:jQuery.roundabout_degToRad(data.focusBearing),shape:jQuery.roundabout_shape[data.shape]||jQuery.roundabout_shape[jQuery.roundabout_shape.def]};info.midStage={width:info.stage.width/2,height:info.stage.height/2};info.nudge={width:info.midStage.width+info.stage.width*0.05,height:info.midStage.height+info.stage.height*0.05};info.zValues={min:data.minZ,max:data.maxZ,diff:data.maxZ-data.minZ};info.opacity={min:data.minOpacity,max:data.maxOpacity,diff:data.maxOpacity-data.minOpacity};info.scale={min:data.minScale,max:data.maxScale,diff:data.maxScale-data.minScale};ref.children(data.childSelector).each(function(i){if(jQuery.roundabout_updateChildPosition(jQuery(this),ref,info,i)&&info.animating===0){inFocus=i;jQuery(this).addClass('roundabout-in-focus')}else{jQuery(this).removeClass('roundabout-in-focus')}});if(inFocus!==info.inFocus){jQuery.roundabout_triggerEvent(ref,info.inFocus,'blur');if(inFocus!==-1){jQuery.roundabout_triggerEvent(ref,inFocus,'focus')}data.childInFocus=inFocus}});return this};jQuery.roundabout_getBearing=function(el){return jQuery.roundabout_toFloat(el.data('roundabout').bearing)%360};jQuery.roundabout_degToRad=function(degrees){return(degrees%360.0)*Math.PI/180.0};jQuery.roundabout_isInFocus=function(el,target){return(jQuery.roundabout_getBearing(el)%360===(target%360))};jQuery.roundabout_triggerEvent=function(el,child,eventType){return(child<0)?this:jQuery(el.children(el.data('roundabout').childSelector)[child]).trigger(eventType)};jQuery.roundabout_toFloat=function(number){number=Math.round(parseFloat(number)*1000)/1000;return parseFloat(number.toFixed(2))};jQuery.roundabout_updateChildPosition=function(child,container,info,childPos){var ref=jQuery(child),data=ref.data('roundabout'),out=[];var rad=jQuery.roundabout_degToRad((360.0-ref.data('roundabout').degrees)+info.bearing);while(rad<0){rad=rad+Math.PI*2}while(rad>Math.PI*2){rad=rad-Math.PI*2}var factors=info.shape(rad,info.focusBearingRad,info.tilt);factors.scale=(factors.scale>1)?1:factors.scale;factors.adjustedScale=(info.scale.min+(info.scale.diff*factors.scale)).toFixed(4);factors.width=(factors.adjustedScale*data.startWidth).toFixed(4);factors.height=(factors.adjustedScale*data.startHeight).toFixed(4);ref.css('left',((factors.x*info.midStage.width+info.nudge.width)-factors.width/2.0).toFixed(1)+'px').css('top',((factors.y*info.midStage.height+info.nudge.height)-factors.height/2.0).toFixed(1)+'px').css('width',factors.width+'px').css('height',factors.height+'px').css('opacity',(info.opacity.min+(info.opacity.diff*factors.scale)).toFixed(2)).css('z-index',Math.round(info.zValues.min+(info.zValues.diff*factors.z))).css('font-size',(factors.adjustedScale*data.startFontSize).toFixed(2)+'px').attr('current-scale',factors.adjustedScale);if(container.data('roundabout').debug===true){out.push('<div style="font-weight: normal; font-size: 10px; padding: 2px; width: '+ref.css('width')+'; background-color: #ffc;">');out.push('<strong style="font-size: 12px; white-space: nowrap;">Child '+childPos+'</strong><br />');out.push('<strong>left:</strong> '+ref.css('left')+'<br /><strong>top:</strong> '+ref.css('top')+'<br />');out.push('<strong>width:</strong> '+ref.css('width')+'<br /><strong>opacity:</strong> '+ref.css('opacity')+'<br />');out.push('<strong>z-index:</strong> '+ref.css('z-index')+'<br /><strong>font-size:</strong> '+ref.css('font-size')+'<br />');out.push('<strong>scale:</strong> '+ref.attr('current-scale'));out.push('</div>');ref.html(out.join(''))}return jQuery.roundabout_isInFocus(container,ref.data('roundabout').degrees)};


/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/*
 * jQuery.SerialScroll - Animated scrolling of series
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 06/14/2009
 * @author Ariel Flesler
 * @version 1.2.2
 * http://flesler.blogspot.com/2008/02/jqueryserialscroll.html
 */
;(function(a){var b=a.serialScroll=function(c){return a(window).serialScroll(c)};b.defaults={duration:1e3,axis:"x",event:"click",start:0,step:1,lock:!0,cycle:!0,constant:!0};a.fn.serialScroll=function(c){return this.each(function(){var t=a.extend({},b.defaults,c),s=t.event,i=t.step,r=t.lazy,e=t.target?this:document,u=a(t.target||this,e),p=u[0],m=t.items,h=t.start,g=t.interval,k=t.navigation,l;if(!r){m=d()}if(t.force){f({},h)}a(t.prev||[],e).bind(s,-i,q);a(t.next||[],e).bind(s,i,q);if(!p.ssbound){u.bind("prev.serialScroll",-i,q).bind("next.serialScroll",i,q).bind("goto.serialScroll",f)}if(g){u.bind("start.serialScroll",function(v){if(!g){o();g=!0;n()}}).bind("stop.serialScroll",function(){o();g=!1})}u.bind("notify.serialScroll",function(x,w){var v=j(w);if(v>-1){h=v}});p.ssbound=!0;if(t.jump){(r?u:d()).bind(s,function(v){f(v,j(v.target))})}if(k){k=a(k,e).bind(s,function(v){v.data=Math.round(d().length/k.length)*k.index(this);f(v,this)})}function q(v){v.data+=h;f(v,this)}function f(B,z){if(!isNaN(z)){B.data=z;z=p}var C=B.data,v,D=B.type,A=t.exclude?d().slice(0,-t.exclude):d(),y=A.length,w=A[C],x=t.duration;if(D){B.preventDefault()}if(g){o();l=setTimeout(n,t.interval)}if(!w){v=C<0?0:y-1;if(h!=v){C=v}else{if(!t.cycle){return}else{C=y-v-1}}w=A[C]}if(!w||t.lock&&u.is(":animated")||D&&t.onBefore&&t.onBefore(B,w,u,d(),C)===!1){return}if(t.stop){u.queue("fx",[]).stop()}if(t.constant){x=Math.abs(x/i*(h-C))}u.scrollTo(w,x,t).trigger("notify.serialScroll",[C])}function n(){u.trigger("next.serialScroll")}function o(){clearTimeout(l)}function d(){return a(m,p)}function j(w){if(!isNaN(w)){return w}var x=d(),v;while((v=x.index(w))==-1&&w!=p){w=w.parentNode}return v}})}})(jQuery);

