var preloadImgs = [], img; var left = 1, right = 0, NONE = 2; function Login(params) { this.currStory = 0; this.maxStories = 0; this.names = []; this.testimonialsShort = []; this.testimonialsLong = []; this.beforePics = []; this.afterPics = []; this.built = false; /*this.currStory = 2; this.maxStories = 2; this.names = ['Hiram', 'Doug']; this.testimonialsShort = ['I entered the Coast Guard in 1967, and for the first 20 years of my 30-year career, I didn't have any weight problems. The work I did was hard, so my weight stayed well within the required limits. In my last 10 years, however, I was assigned to a training command where all my time was spent in a classroom or traveling around the world to train others. I gained weight and found it hard to keep it off. Even though I exercised and tried to be active, my weight slowly increased. I started a walking plan and was able to stay within the required weight limit - but I was always at the top end...', 'I hated being an overweight child. People either made fun of me or (worse) tried to be polite and said, "He's just plump." What adolescent boy wants to hear that? In grade school I was so big they made me play on the upper grades' football team. By middle school, I had grown out of my heaviness, and by the time I graduated high school, I was 6 feet tall and skinny at 145 pounds. Life was good, and I swore I'd never be fat again...']; this.testimonialsLong = ['

Hiram's story


I entered the Coast Guard in 1967, and for the first 20 years of my 30-year career, I didn't have any weight problems. The work I did was hard, so my weight stayed well within the required limits. In my last 10 years, however, I was assigned to a training command where all my time was spent in a classroom or traveling around the world to train others. I gained weight and found it hard to keep it off. Even though I exercised and tried to be active, my weight slowly increased. I started a walking plan and was able to stay within the required weight limit - but I was always at the top end.
\
\ When I retired from the Coast Guard in 2004, I weighed 212 pounds. As I moved from job to job over the next eight years, I kept gaining weight until I weighed in at the Veterans Affairs (VA) Medical Center at 256 pounds. My wife noticed and started to worry about my health. She also has a chronic disease, and I am her primary-care provider. It was becoming difficult to help in some areas. In January, I weighed in on my scale at 260 pounds. I knew it was time to start losing weight. I started on a self-developed plan and used Jillian's DVDs, and by May when I went back to the VA Medical Center and entered their MOVE! national weight-loss program for veterans I had dropped 14 pounds and several inches from my waist. I combined parts of Jillian's DVDs, her Web site, and the VA MOVE! program and created a program that really focused on improving my body and my mind.
\
\ I've had amazing results! I now weigh 190 pounds went from a pants size 46 to 34, I no longer take blood-pressure medication, and my doctor has reduced my diabetes-pill dosage to one-fourth of what it was. I started working again, but I don't let that interfere with my workouts. I block off time on my calendar at work from 11:30 a.m. to 1 p.m. every day so meetings cannot be planned. I walk, jog, or sprint in intervals for about 45 minutes and usually carry two 18-ounce water containers wrapped in 1-kilo wrist weights. I'll stop at benches along the way and alternate sets of push-ups on one bench and then dips at the next. The people around me are very supportive and they constantly remind me if I am running late for my exercise period. They now EXPECT me to be gone and don't plan anything for me to do during that time, which motivates me to keep going and helps me make that change permanent.
\
\ Even though I'm 37, I feel as if I'm 21. I have gone from 29 percent body fat to 19 percent body fat in the past year, and I have a goal of 15 percent body fat. I have changed my priorities in life to reflect how I can better support myself and my family. In the past my priorities were God, family, and then me. I realized that I needed to have the order as God, me, and then family, because if I am not fit and able I could not properly support my family.

', '

Doug's story


I hated being an overweight child. People either made fun of me or (worse) tried to be polite and said, "He's just plump." What adolescent boy wants to hear that? In grade school I was so big they made me play on the upper grades' football team. By middle school, I had grown out of my heaviness, and by the time I graduated high school, I was 6 feet tall and skinny at 145 pounds. Life was good, and I swore I'd never be fat again.
\
\ Over the years, I filled out. At 30, when I married my wife, I was at a muscular and comfortable 185 pounds. Over the next 15 years, I slowly gained another 20 pounds. I was still active, so I got used to it, and nobody would've guessed I weighed over 200 pounds - I just had a little bit of paunch around the middle. It was September of last year, after I quit smoking, when I really started to blow up. I gained 25 pounds in four months, and I was speeding through clothes sizes: The people at J. C. Penney knew me by name. I was out of control and in denial every step of the way.
\
\ In May 2008, my wife and I went to Cancún for our yearly five-day sabbatical. When I was shopping for beach clothes, I realized I was at least four inches bigger around the waist than I had been the summer before. The size 38 shorts I bought were tight, but I couldn't stand the thought of going to a size 40. Still, we had a great time on our trip, lounging on the beach with a cold drink in one hand and a plate in the other (all-inclusive hotels are handy but not very health-friendly).
\
\ At home, when I started downloading the pictures from the trip, I was shocked to see a strange fat guy next to my wife in every picture. I knew I wasn't in the best shape, but that was a serious gut and set of chins I was looking at! While I was sitting there trying to decide whether to delete all those pictures, I got an e-mail; it was one of Jillian's newsletters. The timing was perfect - it had to be a sign. I immediately logged on to her site and signed up, and then I picked up the equipment I would need to work out and started planning my meals.
\
\ A couple of weeks after I started working out and eating the meals from the site's plan, I began reading the Message Boards to find some like-minded people for additional information and support, and those ladies set me straight on my eating habits. It turns out I wasn't eating enough, and after a few adjustments, I started losing in a big way.
\
\ In just 19 weeks, I lost 47 pounds, an average of almost 2.5 pounds per week - even better than the plan said I'd do. I attribute my speedy success to sticking strictly to Jillian's exercise and meal plans. I occasionally had a bad food day or missed a workout, but for the most part I was right there. I love the meal plan; counting calories isn't my thing, so the ease of printing shopping lists and getting all the daily recipes was right up my alley. The planner made staying within my 1600-1900 calories-a-day limit automatic. Even now that I've lost the weight, I still use the plan and just substitute some higher-calorie ingredients or have a larger serving.
\
\ For the first few months, I stuck to the circuits on the site, and that's when I posted the biggest losses. In August, one of the ladies from the "Fearless," a group that had formed on the Message Boards, challenged me to run a half marathon. What was she thinking? Me, a runner? I was the defensive lineman and shot-putter - the big guy in school who never had to run. I still don't know what made me accept the challenge, but I'm glad I did. The first time I ran 10 miles without stopping or walking, I almost cried (don't tell anyone). My oldest daughter ran the November 2 race with me, and we finished it together. My next race is a 10K in Fort Worth, and I think I've talked one of my friends from the site into joining me. This running stuff seems to be contagious!

' ]; var preloadURLs = [ "images/doug-before.gif", "images/doug-after.gif", "images/hiram-before.gif", "images/hiram-after.gif"]; preloadImgs = []; for (var i = 0; i < preloadURLs.length; i++) { img = new Image(); img.src = preloadURLs[i]; preloadImgs.push(img); }*/ this.storyTimer = null; this.storyTimerFade = null; this.username = params || ''; } Login.prototype.build = function(mode) { var obj = this; this.domObj = $('
\
\

Sign In

\ \
\
\
\
\
Don't have an account? Sign Up
\ \
\
\
\
\ '); //alert(mode); if (mode == 'forgotpw') { obj.domObj.find("#createaccountpanel,#loginpanel").hide(); obj.domObj.find("#forgotpwpanel").fadeIn(); } else if (mode == 'register') { obj.domObj.find("#forgotpwpanel,#loginpanel").hide(); obj.domObj.find("#createaccountpanel").fadeIn(); } this.domObj.find("#emaillogin").click(function(e) { e.preventDefault(); var widget = new Widget("EmailLogin", { callback: function(data) { g_userInfo = data.data; //g_userInfo.username = g_userInfo.b4b_id; //saveWindowSession('LOGIN', { username:obj.domObj.find("#username").val() }, function() { //}); LoggedIn(function() { setWindow(sessionStorage['defaultWindowOnLogin'] || "Feed"); }); }}); widget.renderIntoPopup('100%', '100%', $(this)); }); /*this.domObj.find("#forgotpw").click(function(e) { e.preventDefault(); var widget = new Widget("ForgotPassword", { }); widget.renderIntoPopup('100%', '100%', $(this)); });*/ /*this.domObj.find(".applestore").click(function(e) { e.preventDefault(); var widget = new Widget("Label", 'Coming soon...'); widget.renderIntoPopup('50%', '50%', $(this)); });*/ var ua = navigator.userAgent.toLowerCase(); var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile"); var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false ); if (isAndroid || iOS) { this.domObj.find("#mobilelinks").hide(); } $.ajax( { url: "/service/GetTestimonials.php", cache: false, dataType: "json", data: {}, success: function( data ) { obj.built = true; obj.currStory = data.length; var preloadURLs = []; obj.maxStories = data.length; for (var i = 0; i < data.length; i++) { obj.names.push(data[i].name); obj.testimonialsShort.push(data[i].text_short); obj.testimonialsLong.push(data[i].text_long); obj.beforePics.push("/service/GetFile.php?pic=" + data[i].fid_before); obj.afterPics.push("/service/GetFile.php?pic=" + data[i].fid_after); preloadURLs.push("/service/GetFile.php?pic=" + data[i].fid_before); preloadURLs.push("/service/GetFile.php?pic=" + data[i].fid_after); } preloadImgs = []; for (var i = 0; i < preloadURLs.length; i++) { img = new Image(); img.src = preloadURLs[i]; preloadImgs.push(img); } } }); $.ajax( { url: "/service/GetPageData.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&page=LOGIN", cache: false, dataType: "json", data: {}, success: function( data ) { obj.domObj.find("#username").val(data.data.username || ''); if (data.data.username) { obj.domObj.find("#password").focus(); } else { obj.domObj.find("#username").focus(); } } }); return false; } Login.prototype.getDomObj=function() { return this.domObj; } Login.prototype.setMode=function(mode) { this.domObj.find("#" + mode).triggerHandler(hitEvent); } Login.prototype.setSuccessStory=function(mode) { var win = this; var domObj = this.getDomObj(); domObj.find("#bg").stop(); var offsetRight = mode == right ? "-100px" : "100px"; var offsetLeft = mode == right ? "100px" : "-100px"; if (mode == NONE) { offsetLeft = "0px"; offsetRight = "0px"; } domObj.find("#bg").animate({"margin-left": offsetLeft, opacity: mode == NONE ? 0 : 0}, 200, 'linear', function() { if (mode == left) { win.currStory = win.currStory == win.maxStories ? 1 : ++win.currStory; } else { win.currStory = win.currStory == 1 ? win.maxStories : --win.currStory; } //if (mode != NONE) { domObj.find("#bg").hide().removeClass().addClass("before story" + win.currStory).css("background-image", "url('" + win.beforePics[win.currStory-1] + "')").css("margin-left", offsetRight).css("opacity", 0).show(); domObj.find("#story-name").html(win.names[win.currStory-1]); domObj.find("#testimonial_short").text(nl2br(win.testimonialsShort[win.currStory-1])); //} domObj.find("#bg").animate({"margin-left": 0, opacity: 1}, 200, 'linear', function() { win.storyTimerFade = setTimeout(function() { win.storyTimerFade = null; domObj.find("#bg").fadeOut(350, function() { domObj.find("#bg").removeClass().css("background-image", "url('" + win.afterPics[win.currStory-1] + "')").addClass("after story" + win.currStory); domObj.find("#bg").fadeIn(350, function () { win.setStoryTimer(); }); }); }, 2500); }); }); } Login.prototype.setStoryTimer=function() { var win = this; if (! win.storyTimer) { win.storyTimer = setTimeout(function() { win.setSuccessStory(left); win.storyTimer = null; }, 7500); } } Login.prototype.setHooks=function() { var domObj = this.getDomObj(); var win = this; var obj = this; obj.domObj.find("#loginsignup").click(function(e) { e.preventDefault(); setWindow('Login-register'); }); obj.domObj.find("#forgotpwlink").click(function(e) { e.preventDefault(); setWindow('Login-forgotpw'); }); domObj.find(".fbbutton").click(function(e) { e.preventDefault(); if ($(this).attr('loggedin') == '1') { return; } FB.login(function(response){ // Handle the response object, like in statusChangeCallback() in our demo // code. $(".fbbutton").attr('loggedin', '1'); //console.log(response); var access_token = response.authResponse.accessToken; if (response.status === 'connected') { // Logged into your app and Facebook. FB.api('/v2.4/me?fields=email,first_name,last_name,gender,birthday', function(response) { //console.log(JSON.stringify(response)); blockWindow(); $.ajax( { url: "/service/FBLogin.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { id: response.id, name: response.name, email: (response.email||''), token: access_token }, success: function( data ) { unblockWindow(); if (! data || ! data.success) { alert("An Error has occurred!"); $(".fbbutton").attr('loggedin', '0'); } else { g_userInfo = data.data; //g_userInfo.username = g_userInfo.b4b_id; //saveWindowSession('LOGIN', { username:obj.domObj.find("#username").val() }, function() { //}); LoggedIn(function() { setWindow(sessionStorage['defaultWindowOnLogin'] || "Feed"); }); } //obj.domObj.find("#error").show(); //alert(JSON.stringify(data)); } }); }); } else if (response.status === 'not_authorized') { // The person is logged into Facebook, but not your app. $(".fbbutton").attr('loggedin', '0'); } else { // The person is not logged into Facebook, so we're not sure if // they are logged into this app or not. } }, {return_scopes: true, scope: 'public_profile,email'}); }); domObj.find("#login").bind(hitEvent, function (e) { e.preventDefault(); if (obj.domObj.find("#username").val() == "") { obj.domObj.find("#username").css("border-color", "red").focus().prev("label").css("color", "red"); } else if (obj.domObj.find("#password").val() == "") { obj.domObj.find("#password").css("border-color", "red").focus().prev("label").css("color", "red"); } else { obj.domObj.find("#password,#username").css("border-color", ""); blockWindow(); $.ajax( { url: "/service/Login.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { username: obj.domObj.find("#username").val(), password: obj.domObj.find("#password").val() }, success: function( data ) { unblockWindow(); if (! data || ! data.success) { obj.domObj.find("#loginmsg").text(data.error || "Invalid username or password.").css("color", "red"); } else { g_userInfo = data.data; saveWindowSession('LOGIN', { username:obj.domObj.find("#username").val() }, function() { }); LoggedIn(function() { setWindow(sessionStorage['defaultWindowOnLogin'] || "Feed"); }); } //obj.domObj.find("#error").show(); //alert(JSON.stringify(data)); } }); } }); //alert(domObj.find("#login-form").length); domObj.find("#login-form").submit(function(e) { e.preventDefault(); obj.domObj.find("#login").triggerHandler("click"); }); domObj.find("#register-form").submit(function(e) { e.preventDefault(); obj.domObj.find("#register").triggerHandler("click"); }); domObj.find("#forgotpw-form").submit(function(e) { e.preventDefault(); obj.domObj.find("#forgotpw").triggerHandler("click"); }); domObj.find("#forgotpw").bind(hitEvent, function (e) { e.preventDefault(); $("input").blur(); var email = obj.domObj.find("#forgotpwemail").val(); if (email.indexOf('@') == -1) { obj.domObj.find(".forgotpwerror").text("Please enter a valid email."); obj.domObj.find("#forgotpwemail").focus(); return; } //obj.domObj.block({ showOverlay: false, centerY: false, css: { 'vertical-align':'middle', top: "0", width:"100%", height:"100px",position: 'relative', border: 0}, message: '' }); blockWindow(); $.ajax( { url: "/service/ForgotPassword.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { email: email }, success: function( data ) { unblockWindow(); if (! data || ! data.success) { if (data.errors) { obj.domObj.find(".forgotpwerror").text(data.errors['EMAIL']); } else { obj.domObj.find(".forgotpwerror").text("Please enter a valid email."); } } else { obj.domObj.find(".forgotpwsuccess").html('We have sent an email to:

' + email + '



Return'); obj.domObj.find("#forgotpw-form").remove(); obj.domObj.find("#closewin").click(function(e) { e.preventDefault(); setWindow("Login"); }); } } }); }); domObj.find("#register").bind(hitEvent, function(e) { e.preventDefault(); $("input").blur(); var fname = obj.domObj.find("#regfname").val(); if (! fname) { obj.domObj.find("#regfname").focus(); return; } var lname = obj.domObj.find("#reglname").val(); if (! lname) { obj.domObj.find("#reglname").focus(); return; } var email = obj.domObj.find("#regemail").val(); if (! email) { obj.domObj.find("#regemail").focus(); return; } if (email.indexOf('@') == -1) { obj.domObj.find("#regemail").focus(); obj.domObj.find(".regerror").text("Please enter a valid email."); return; } var pass = obj.domObj.find("#regpass").val(); if (! pass) { obj.domObj.find("#regpass").focus(); return; } if (pass.length < 6 || pass.length > 20) { obj.domObj.find("#regpass").focus(); obj.domObj.find(".regerror").text("Please enter a valid password (6-20 chars)."); return; } blockWindow(); $.ajax( { url: "/service/EmailLogin.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { email: email, password: pass, firstname: fname, lastname: lname }, success: function( data ) { //obj.domObj.unblock(); unblockWindow(); if (! data || ! data.success) { if (data.errors) { obj.domObj.find(".regerror").text(data.errors['EMAIL']); } else { obj.domObj.find(".regerror").text("Please enter a valid email."); } } else { g_userInfo = data.data; //g_userInfo.username = g_userInfo.b4b_id; //saveWindowSession('LOGIN', { username:obj.domObj.find("#username").val() }, function() { //}); LoggedIn(function() { setWindow(sessionStorage['defaultWindowOnLogin'] || "Feed"); }); } } }); //setWindow("Register-step1"); }); domObj.find("#viewplans").bind(hitEvent, function(e) { e.preventDefault(); var widget = new Widget("Viewplans"); widget.renderIntoPopup(750, 450, $(this)); }); domObj.find("a.whatisthis").bind(hitEvent, function(e) { e.preventDefault(); var widget = null; switch ($(this).attr('id')) { case 'username_wit': widget = new Widget("Label", 'This is your email address or the ID you created during registration.'); break; case 'password_wit': widget = new Widget("Label", 'This is your password that you created during registration.'); break; } if (widget) { widget.renderIntoPopup('50%', '50%', $(this)); } }); domObj.find("a.bio-link").bind(hitEvent, function(e) { e.preventDefault(); clearTimeout(win.storyTimer); win.storyTimer = -1; var widget = new Widget("ScrollContainer", '

' + htmlencode(win.names[win.currStory-1]) + ''s story


' + nl2br(htmlencode(win.testimonialsLong[win.currStory-1])) + '

'); widget.renderIntoPopup('80%', '80%', $(this), function() { win.storyTimer = null; win.setStoryTimer(); }); }); domObj.find("a#left-arrow").bind(hitEvent, function (e) { if (win.storyTimerFade) { clearTimeout(win.storyTimerFade); win.storyTimerFade = -1; } if (win.storyTimer) { clearTimeout(win.storyTimer); win.storyTimer = -1; } win.setSuccessStory(right); }); domObj.find("a#right-arrow").bind(hitEvent, function (e) { if (win.storyTimerFade) { clearTimeout(win.storyTimerFade); win.storyTimerFade = -1; } if (win.storyTimer) { clearTimeout(win.storyTimer); win.storyTimer = -1; } win.setSuccessStory(left); }); win.setSuccessStory(NONE); $(window).trigger('resize'); } Login.prototype.destroy=function() { if (this.storyTimerFade) { clearTimeout(this.storyTimerFade); this.storyTimerFade = null; } if (this.storyTimer) { clearTimeout(this.storyTimer); this.storyTimer = null; } //$("#previews,#nusers").remove(); } Login.prototype.isBuilt=function() { return this.built; } Login.prototype.resize=function() { //$("#previews").width(1); //console.log("" + window.innerWidth + " - " + $("#content").outerWidth()); $("#previews").width(window.innerWidth-20); } Login.prototype.contentSet=function(){ this.setSuccessStory(NONE); var obj = this; /* $.ajax( { url: "/service/GetNewUsers.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { }, success: function( datafr ) { if (! datafr) return; //var str = ''; var str2 = ''; for (var i = 0; i < datafr.results.length; i++) { //str += '' + htmlencode(datafr.results[i].firstname + ' ' + datafr.results[i].lastname) + '
' + (parseInt(datafr.results[i].stepcnt) > 0 ? 'Steps: ' + datafr.results[i].stepcnt + '' : '') + (datafr.results[i].weightlost > 0 ? 'Lost: ' + datafr.results[i].weightlost + ' lbs' : '' ) + '
'; str2 += '
' + htmlencode(datafr.results[i].firstname + ' ' + datafr.results[i].lastname) + '
' + (parseInt(datafr.results[i].stepcnt) > 0 ? 'Steps: ' + datafr.results[i].stepcnt + '' : '') + (datafr.results[i].weightlost > 0 ? 'Lost: ' + datafr.results[i].weightlost + ' lbs' : '' ) + '
'; } $('
New Users:
\ ' + str2 + '\
').insertAfter("#content"); $("#previews").on('click', '.sendmsgto', function(e) { e.preventDefault(); e.stopPropagation(); userClicked($(this).attr('username')); }); $('#previews').slick({ infinite: true, speed: 300, slidesToShow: 1, centerMode: true, variableWidth: true, arrows: false, autoplay: true, autoplaySpeed: 2000 }); obj.resize(); } });*/ //var str = ''; //for (var i = 0; i < 100; i++) { // str += '
'; //} //$("#previews").width(window.innerWidth); } var t9 = null; function Loading(params) { this.built = false; } Loading.prototype.build = function(mode) { var obj = this; setTimeout(function() { obj.built = true; }, 5000); this.domObj = $('
'); return false; } Loading.prototype.getDomObj=function() { return this.domObj; } Loading.prototype.setHooks=function() { this.domObj.click(function() { setWindow("Login"); }); } Loading.prototype.destroy=function() { } Loading.prototype.isBuilt=function() { return this.built; } Loading.prototype.setMode=function(mode) { } Loading.prototype.contentSet=function(){ } function Register(params) { this.built = false; this.username = ""; this.password = ""; this.password2 = ""; this.email = ""; this.firstname = ""; this.lastname = ""; this.gender = ''; this.birthyear = ""; this.birthmonth = ""; this.birthday = ""; this.ChoosePlans = null; this.currStep = 'step1'; this.choosePlanPage = 0; this.fetchingData = false; this.regCode = ''; this.currplanid = 0; this.plantype = 0; this.planname = ''; this.mode = 'step1'; } Register.prototype.makeAccount=function(code) { var obj = this; blockWindow(); $.ajax( { url: "/service/MakeAccount.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { code: code, regCode: obj.regCode }, success: function( data ) { if (! data || ! data.success) { obj.genRegisterCode(function() { unblockWindow(); obj.domObj.find("#captchaimg").attr('src', '/service/GetCaptcha.php?regCode=' + obj.regCode); var str = ""; for (var k in data.errors) { if (str != "") { str+="
"; } str+=data.errors[k]; } obj.domObj.find("#errors").show().html(str); }); } else { saveWindowSession('LOGIN', { username: obj.username }, function() { unblockWindow(); setWindow("Login"); }); } } }); } Register.prototype.genRegisterCode=function(callback) { var obj = this; $.ajax( { url: "/service/GetRegisterCode.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&page=REGISTER", cache: false, dataType: "json", data: {}, success: function( data ) { obj.regCode = data; callback(); } }); } Register.prototype.buildPage=function(mode, submode) { var obj = this; if (mode == 'step1') { this.domObj = $('
\
\
Create Account
\
Choose Plan
\
Confirm
\
\
\
\ Account Information
\

Please enter your account information

\ \
\
\ Your Information
\

Please enter your personal information

\ \
\

\
\ < Return to login\ \
\
'); for (var i = 1; i <= 31; i++) { this.domObj.find("#birthday").append(''); } for (var i = 2013; i >= 1920 ; i--) { this.domObj.find("#birthyear").append(''); } } else if (mode == 'step2') { this.domObj = $('
\
\
Create Account
\
Choose Plan
\
Confirm
\
\
\
\

\
\ \ \
\
'); if (! this.ChoosePlans) { this.ChoosePlans = new Widget("ChoosePlans", {allownoplan: true}); } /*var currPage = 1; var hashparts = window.location.hash.split("-"); if (hashparts.length >= 3 && hashparts[2] != '') { currPage = parseInt(hashparts[2]); }*/ //this.choosePlanPage = parseInt(this.choosePlanPage); /*this.ChoosePlans.setPage(obj.choosePlanPage, function() { g_doNotProcessHash = false; location.href = "#Register-step2-" + obj.ChoosePlans.getPageName(obj.choosePlanPage < 0 ? 0 : obj.choosePlanPage); obj.ChoosePlans.render(obj.domObj.find("#select-plan-container")) });*/ //this.ChoosePlans.setPage(this.choosePlanPage); var pageParts = getHash().split("-"); var pageNum = (submode) ? this.ChoosePlans.getPageNum(submode) : 0; var obj = this; this.ChoosePlans.setPage(pageNum, function() { //g_doNotProcessHash = true; //location.href = "#Register-step2-" + this.ChoosePlans.getPageName(this.choosePlanPage < 0 ? 0 : this.choosePlanPage); obj.ChoosePlans.render(obj.domObj.find("#select-plan-container")); }); return true; } else if (mode == 'step3') { this.domObj = $('
\
\
Create Account
\
Choose Plan
\
Confirm
\
\
\
\ \ \
\ Account Information
\
    \
  • \ \ ' + obj.username + '\
  • \
  • \ \ ' + obj.email + '\
  • \
  • \ \ ' + obj.firstname + '\
  • \
  • \ \ ' + obj.lastname + '\
  • \
\
\
\ Plan Information
\
    \
  • \ \ ' + ((parseInt(obj.currplanid) && parseInt(obj.plantype)) ? obj.planname : 'No plan selected') + '\
  • \
\
\
\ Verification
\
    \
  • \ \ \
  • \
  • \ \ \
  • \
\
\
\
\

\
\ \ \
\
'); return true; } } Register.prototype.getPlan=function(callback) { var obj = this; $.ajax( { url: "/service/GetPageData.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&page=REGISTER_PLAN", cache: false, dataType: "json", data: {}, success: function( data ) { obj.currplanid = data.data['plan']; $.ajax( { url: "/service/GetPageData.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&page=REGISTER_PLANTYPE", cache: false, dataType: "json", data: {}, success: function( data ) { obj.plantype = data.data['plantype']; $.ajax( { url: "/service/GetPlanInfo.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { plan_id: obj.currplanid }, success: function( data ) { obj.planname = data['name'] || ''; callback(); } }); } }); } }); } Register.prototype.build = function(mode, submode) { var obj = this; //obj.built = false; this.mode = mode; obj.genRegisterCode(function() { $.ajax( { url: "/service/GetPageData.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&page=REGISTER", cache: false, dataType: "json", data: {}, success: function( data ) { for (var k in data.data) { obj[k] = data.data[k]; } var f = function() { obj.buildPage(mode, submode); obj.built = true; }; if (mode == 'step3') { obj.getPlan(f); } else { f(); } } }); }); return false; } Register.prototype.setMode=function(mode, submode) { if (mode == 'step1') { this.domObj.find("#username").val(this.username); this.domObj.find("#password").val(this.password); this.domObj.find("#password2").val(this.password2); this.domObj.find("#email").val(this.email); this.domObj.find("#firstname").val(this.firstname); this.domObj.find("#lastname").val(this.lastname); if (this.gender == 'F') { this.domObj.find("#gender_female").attr('checked', true); } else if (this.gender == 'M') { this.domObj.find("#gender_male").attr('checked', true); } this.domObj.find("#birthmonth").val(this.birthmonth || '0'); this.domObj.find("#birthyear").val(this.birthyear || '0'); this.domObj.find("#birthday").val(this.birthday || '0'); this.built = true; } else if (mode == 'step2') { } } Register.prototype.getDomObj=function() { return this.domObj; } Register.prototype.validate = function(callback) { this.domObj.find("#username").triggerHandler("blur"); this.domObj.find("#password").triggerHandler("blur"); this.domObj.find("#password2").triggerHandler("blur"); this.domObj.find("#email").triggerHandler("blur"); this.domObj.find("#firstname").triggerHandler("blur"); this.domObj.find("#lastname").triggerHandler("blur"); this.domObj.find("#birthmonth, #birthday, #birthyear").triggerHandler("change"); this.domObj.find("input[name=gender]").triggerHandler("click"); if (this.domObj.find("span.validate[status=0]").length > 0) { // Failed validation unblockWindow(); return; } var obj = this; if (this.domObj.find("span.validate[status=2]").length > 0) { // AJAX Running //blockWindow(); var intrvl = setInterval(function() { if (obj.domObj.find("span.validate[status=2]").length == 0) { // AJAX finished running clearInterval(intrvl); //unblockWindow(); if (obj.domObj.find("span.validate[status=0]").length == 0) { // No failures callback(); } else { unblockWindow(); } } }, 100); return; } callback(); // No failures } Register.prototype.setHooks=function(mode) { var obj = this; if (mode == 'step1') { this.domObj.find("#ret-login").click(function() { setWindow("Login"); }); this.domObj.find("#next").click(function(e) { e.preventDefault(); blockWindow(); obj.validate(function () { var params = {}; params.username = obj.domObj.find("#username").val(); params.password = obj.domObj.find("#password").val(); params.password2 = obj.domObj.find("#password2").val(); params.email = obj.domObj.find("#email").val(); params.firstname = obj.domObj.find("#firstname").val(); params.lastname = obj.domObj.find("#lastname").val(); params.gender = obj.domObj.find("input[name=gender]:checked").val(); params.birthyear = obj.domObj.find("#birthyear").val(); params.birthday = obj.domObj.find("#birthday").val(); params.birthmonth = obj.domObj.find("#birthmonth").val(); saveWindowSession('REGISTER', params, function() { obj.username = params.username; obj.password = params.password; obj.password2 = params.password2; obj.email = params.email; obj.firstname = params.firstname; obj.lastname = params.lastname; obj.gender = params.gender; obj.birthyear = params.birthyear; obj.birthday = params.birthday; obj.birthmonth = params.birthmonth; var cplans = new ChoosePlans(); unblockWindow(); setWindow("Register-step2-" + cplans.getPageName(0)); //setWindow("Register-step2-1"); }); }); }); this.domObj.find("#username").blur(function () { if ($(this).val().length < 3) { obj.domObj.find("#username_status").attr("status", "0").html(' Username must be at least 3 characters.'); } else { obj.domObj.find("#username_status").attr("status", "2").html(''); $.ajax( { url: "/service/Unique.php", cache: false, dataType: "json", data: {type: 'ACCOUNT', field: 'USERNAME', val: $(this).val()}, success: function( data ) { if (data.success == false) { obj.domObj.find("#username_status").attr("status", "0").html(' Username is already taken.'); } else { obj.domObj.find("#username_status").attr("status", "1").html(''); } } }); } }); this.domObj.find("#password").blur(function () { if ($(this).val().length < 8) { obj.domObj.find("#password_status").attr("status", "0").html(' Password must be at least 8 characters.'); } else { obj.domObj.find("#password_status").attr("status", "1").html(''); } }); this.domObj.find("#password2").blur(function () { if ($(this).val() == '' || $(this).val() != obj.domObj.find("#password").val()) { obj.domObj.find("#password2_status").attr("status", "0").html(' Passwords must match.'); } else { obj.domObj.find("#password2_status").attr("status", "1").html(''); } }); this.domObj.find("#email").blur(function () { if ($(this).val().length < 3 || $(this).val().indexOf('@') == -1) { obj.domObj.find("#email_status").attr("status", "0").html(' Please enter a valid email address.'); } else { obj.domObj.find("#email_status").attr("status", "2").html(''); $.ajax( { url: "/service/Unique.php", cache: false, dataType: "json", data: {type: 'ACCOUNT', field: 'EMAIL', val: $(this).val()}, success: function( data ) { if (data.success == false) { obj.domObj.find("#email_status").attr("status", "0").html(' Email address has already been used.'); } else { obj.domObj.find("#email_status").attr("status", "1").html(''); } } }); } }); this.domObj.find("#firstname").blur(function () { if ($(this).val().length < 1) { obj.domObj.find("#firstname_status").attr("status", "0").html(' Please enter your firstname.'); } else { obj.domObj.find("#firstname_status").attr("status", "1").html(''); } }); this.domObj.find("#lastname").blur(function () { if ($(this).val().length < 1) { obj.domObj.find("#lastname_status").attr("status", "0").html(' Please enter your lastname.'); } else { obj.domObj.find("#lastname_status").attr("status", "1").html(''); } }); this.domObj.find("#birthmonth, #birthyear, #birthday").change(function () { if (obj.domObj.find("#birthmonth").val() == 0 || obj.domObj.find("#birthyear").val() == 0 || obj.domObj.find("#birthday").val() == 0) { obj.domObj.find("#birthdate_status").attr("status", "0").html(' Please enter your birth date.'); } else { obj.domObj.find("#birthdate_status").attr("status", "1").html(''); } }); this.domObj.find("input[name=gender]").click(function() { if (obj.domObj.find("#gender_male").is(":checked") == false && obj.domObj.find("#gender_female").is(":checked") == false){ obj.domObj.find("#gender_status").attr("status", "0").html(' Please select your gender.'); } else { obj.domObj.find("#gender_status").attr("status", "1").html(''); } }); } else if (mode == 'step2') { this.domObj.find("#prev").click(function() { obj.ChoosePlans.prev(function() { var done = obj.ChoosePlans.isDone(); if (done == true) { setWindow("Register-step1"); } else { //saveWindowSession('REGISTER', { choosePlanPage: obj.ChoosePlans.getCurrentPage() }, function() { g_doNotProcessHash = false; //location.href = "#Register-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage()); setWindow("Register-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage())); //obj.ChoosePlans.render(obj.domObj.find("#select-plan-container")); //}); } }); }); /*this.domObj.find("#next").click(function(e) { e.preventDefault(); obj.ChoosePlans.next(function () { var done = obj.ChoosePlans.isDone(); if (done == true) { setWindow("Register-step3"); } else { //saveWindowSession('REGISTER', { choosePlanPage: obj.ChoosePlans.getCurrentPage() }, function() { g_doNotProcessHash = false; //location.href = "#Register-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage()); setWindow("Register-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage())); //obj.ChoosePlans.render(obj.domObj.find("#select-plan-container")); //}); } }); });*/ this.domObj.find("#next").unbind(); } else if (mode == 'step3') { this.domObj.find("#next").click(function(e) { e.preventDefault(); if (obj.domObj.find("#captcha").val() == '') { obj.domObj.find("#captcha_label").css("color", "red"); obj.domObj.find("#captcha").focus(); } else { obj.makeAccount(obj.domObj.find("#captcha").val()); } }); this.domObj.find("#prev").click(function() { var cplans = new ChoosePlans(); setWindow("Register-step2-" + cplans.getPageName(cplans.getNumPages()-1)); }); } } Register.prototype.widgetCallback=function(widget, msg, data) { } Register.prototype.destroy=function() { } Register.prototype.isBuilt=function() { if (this.mode == 'step2') { return this.ChoosePlans && this.ChoosePlans.widget.isBuilt(); } return this.built; } Register.prototype.contentSet=function(){ var obj = this; $("#signup-form").submit(function(e) { e.preventDefault(); if ($(document.activeElement).attr('id') == 'planfilter') { $("input[type=text]").blur(); return; } obj.ChoosePlans.next(function () { var done = obj.ChoosePlans.isDone(); if (done == true) { setWindow("Register-step3"); } else { //saveWindowSession('REGISTER', { choosePlanPage: obj.ChoosePlans.getCurrentPage() }, function() { g_doNotProcessHash = false; //location.href = "#Register-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage()); setWindow("Register-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage())); //obj.ChoosePlans.render(obj.domObj.find("#select-plan-container")); //}); } }); }); /*$("#signup-form").submit(function(e) { e.preventDefault(); if ($(document.activeElement).attr('id') == 'planfilter') { return; } $("#next").triggerHandler('click'); });*/ } function CreatePlan(params) { this.inputs = {}; var obj = this; this.plan_id = 0; this.vars = { 'AGE': true, 'WEIGHT': true }; this.expBuilder = new Widget('ExpBuilder', {inputs: this.inputs, vars: this.vars} ); var callbackFunc = function() { // logic has moved to regresh //obj.expBuilder.widget.refreshInputs(); //obj.rulesBuilder.widget.refreshSelects(); //obj.formBuilderProperties.widget.refreshSelects(); }; var updateFunc = function(select) { //obj.exerciseBuilder.widget.popExercise(select); }; this.formBuilderProperties = new Widget("FormBuilderProperties", {inputs: this.inputs, refreshFunc: callbackFunc }); this.formBuilder = new Widget('FormBuilder', {edit: true, editprops: this.formBuilderProperties, inputs: this.inputs, refreshFunc: callbackFunc }); this.sideScroll = new Widget('SideScroll'); this.exerciseBuilder = new Widget('ExerciseBuilder', { refreshFunc: callbackFunc }); this.foodBuilder = new Widget('FoodBuilder'); this.rulesBuilder = new Widget('RuleBuilder', { foodBuilder: this.foodBuilder, exerciseBuilder: this.exerciseBuilder, updateFunc: updateFunc, inputs: this.inputs, vars: this.vars } ); this.saveParams = {}; } CreatePlan.prototype.getGeneralCat=function() { var obj = this; var ret = $('
\
\ Plan Information
\
    \
  • \ \ \
  • \
\
'); ret.on('click keyup', 'textarea, input[type=checkbox], input[type=text]', function(e) { obj.saveparams = {}; ret.find("input,textarea").each(function() { if ($(this).attr('type') == 'checkbox' && $(this).is(":checked")) { obj.saveparams[$(this).attr('id')] = $(this).val(); } else if ($(this).attr('type') == 'text' || $(this).prop('tagName').toLowerCase() == 'textarea') { //alert($(this).attr('id') + " = " + $(this).val()); obj.saveparams[$(this).attr('id')] = $(this).val(); } }); //console.log(saveparams); saveWindowSession('CREATEPLANGENERAL', obj.saveparams, function() {}); }); $.ajax( { url: "/service/GetPlanCats.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, success: function( data ) { //console.log(data.data); //alert(JSON.stringify(data)); var str = ''; var lbl = 'Category:'; var pad = 'padding-top:8px;'; for (var k in data) { str+= '
  • \ \  
    \
  • '; lbl = ' '; pad = ''; } str += '
  • \ \ \
  • '; ret.find("ul").append($(str)); } }); /*
  • \ \  
    \
  • \
  • \ \  
    \
  • \
  • \ \  
    \
  • \
  • \ \  
    \
  • \
  • \ \  
    \
  • \
  • \ \  
    \
  • \*/ return ret; } CreatePlan.prototype.build = function(mode) { this.domObj = $('
    \
    \
    \
      Load / New Plan
    '); this.scrollContent = $('\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \
    LabelDropdownMultiselectText BlockText InputRadio ButtonsCheckboxesModule
    '); this.scrollContent.find(".sizer,.fieldalign,.fieldvalign,.editfield").hide(); this.inputsCat = $('
    \
    \
    \
    \
    \
    \
    \
    \
    '); this.formulasCat = $('
    '); this.expBuilder.render(this.formulasCat); this.foodCat = $('
    '); this.foodBuilder.render(this.foodCat); this.generalCat = this.getGeneralCat(); this.rulesCat = $('
    '); this.rulesBuilder.render(this.rulesCat); this.exerciseCat = $('
    '); this.exerciseBuilder.render(this.exerciseCat); this.sideScroll.widget.addButton('

    '); this.sideScroll.widget.setScrollContent(this.scrollContent); this.sideScroll.render(this.inputsCat.find("#sidescroll")); this.formBuilderProperties.render($('
    ').appendTo("body")); this.domObj.find("div#create-plan-container").append(this.inputsCat); this.formBuilder.render(this.domObj.find("div#create-plan-content")); var obj = this; $.ajax( { url: "/service/GetPageData.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&page=CREATEPLANGENERAL", cache: false, dataType: "json", data: {}, success: function( data ) { //console.log(data.data); for (var k in data.data) { var etype = $(obj.generalCat).find("#" + k).attr('type'); //alert(k); var tag = $(obj.generalCat).find("#" + k).prop('tagName').toLowerCase(); if (etype == 'checkbox' && data.data[k]) { $(obj.generalCat).find("#" + k).prop('checked', true); } else if (etype == 'text') { $(obj.generalCat).find("#" + k).val(data.data[k]); } else if (tag = 'textarea') { $(obj.generalCat).find("#" + k).val(data.data[k]); } } } }); blockWindow(); $.ajax( { url: "/service/GetPageData.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&page=CREATEPLAN", cache: false, dataType: "json", data: {}, success: function( data ) { //console.log(data.data); obj.plan_id = data.data.plan_id || 0; unblockWindow(); } }); return false; } CreatePlan.prototype.getDomObj=function() { return this.domObj; } CreatePlan.prototype.setMode=function(mode) { } CreatePlan.prototype.setHooks=function() { var domObj = this.getDomObj(); var obj = this; obj.timer = null; obj.startx = 0; obj.starty = 0; var dragFunc = function(e) { e.preventDefault(); e.stopPropagation(); //console.log("mousedown"); if (obj.follow) { obj.follow.remove(); obj.follow = null; } obj.mouseX = e.pageX; obj.mouseY = e.pageY; if (e.type != 'mousedown') { if (e.originalEvent.touches.length != 1) { return; } obj.mouseX = e.originalEvent.touches[0].pageX; obj.mouseY = e.originalEvent.touches[0].pageY; } obj.startx = obj.mouseX; obj.starty = obj.mouseY; //console.log(e.pageX); //if (obj.timer !== null) { // clearTimeout(obj.timer); //console.log("clear3"); // obj.timer = null; //} //console.log(this.outerHTML); //console.log($(this).parents(".formfield:first").get(0).outerHTML); var dobj = $(this).parents(".formfield:first").parent().get(0); //console.log(dobj.outerHTML); //console.log("here"); obj.timer = setTimeout(function() { //console.log("1@"); if (dobj) { obj.follow = $(dobj.outerHTML).css("position", "absolute").addClass("dragging"); obj.follow.find("input,select,textarea").empty().val(''); $('body').append(obj.follow); obj.follow.css("left", (obj.mouseX - Math.floor(obj.follow.width() / 2.0)) + "px").css("top", (obj.mouseY - Math.floor(obj.follow.height() / 2.0)) + "px"); } else { obj.follow = null; } clearTimeout(obj.timer); obj.timer = null; }, 200); }; $(domObj).find("#selectfields").find('input,select,textarea,.sizing,label,.module').bind(pressEvent, dragFunc); $(domObj).find("tr.formfields td").bind(pressEvent, function(e) { e.preventDefault(); e.stopPropagation(); //$(this).find('input,select,textarea,.sizing,label,.module').triggerHandler(pressEvent, e); var dobj = $(this).find(".formfield:first").get(0); e.preventDefault(); e.stopPropagation(); //console.log("mousedown"); if (obj.follow) { obj.follow.remove(); obj.follow = null; } obj.mouseX = e.pageX; obj.mouseY = e.pageY; if (e.type != 'mousedown') { if (e.originalEvent.touches.length != 1) { return; } obj.mouseX = e.originalEvent.touches[0].pageX; obj.mouseY = e.originalEvent.touches[0].pageY; } obj.startx = obj.mouseX; obj.starty = obj.mouseY; //console.log(e.pageX); //if (obj.timer !== null) { // clearTimeout(obj.timer); //console.log("clear3"); // obj.timer = null; //} //console.log(this.outerHTML); //console.log($(this).parents(".formfield:first").get(0).outerHTML); //var dobj = $(this).parents(".formfield:first").parent().get(0); //console.log(dobj.outerHTML); //console.log("here"); obj.timer = setTimeout(function() { //console.log("1@"); obj.follow = $(dobj.outerHTML).css("position", "absolute").addClass("dragging"); obj.follow.find("input,select,textarea").empty().val(''); $('body').append(obj.follow); obj.follow.css("left", (obj.mouseX - Math.floor(obj.follow.width() / 2.0)) + "px").css("top", (obj.mouseY - Math.floor(obj.follow.height() / 2.0)) + "px"); clearTimeout(obj.timer); obj.timer = null; }, 200); }); this.follow = null; this.mouseX = 0, this.mouseY = 0; var obj = this; var sliding = false; obj.mouseup = function(e) { sliding = false; if (obj.timer !== null) { //console.log("clear2"); clearTimeout(obj.timer); obj.timer = null; } if (obj.follow) { e.preventDefault(); obj.formBuilder.widget.mousedrop(obj.follow, obj.mouseX, obj.mouseY); //obj.follow.remove(); obj.follow = null; } }; obj.mousemove = function(e) { var oldx = obj.mouseX; var oldy = obj.mouseY; obj.mouseX = e.pageX; obj.mouseY = e.pageY; if (e.type != 'mousemove') { if (e.originalEvent.touches.length != 1) { return; } obj.mouseX = e.originalEvent.touches[0].pageX; obj.mouseY = e.originalEvent.touches[0].pageY; } if (sliding) { obj.sideScroll.domObj.find(".scroller").scrollLeft(obj.sideScroll.domObj.find(".scroller").scrollLeft() - (obj.mouseX - oldx)); return; } //console.log(obj.mouseX); //console.log(obj.startx); //console.log(Math.abs(obj.startx - obj.mouseX)); if (Math.abs(obj.startx - obj.mouseX) > 5/* || Math.abs(obj.starty - obj.mouseY) > 5*/) { if (obj.timer !== null) { //alert("!!!!"); sliding = true; //console.log("clear1"); clearTimeout(obj.timer); obj.timer = null; return; } } if (obj.follow) { e.preventDefault(); //e.stopPropagation(); obj.follow.addClass("dragging").css("left", (obj.mouseX - Math.floor(obj.follow.width() / 2.0)) + "px").css("top", (obj.mouseY - Math.floor(obj.follow.height() / 2.0)) + "px"); obj.formBuilder.widget.mousedrag(obj.follow, obj.mouseX, obj.mouseY); } }; $(window).mouseup(obj.mouseup).bind('touchend', obj.mouseup); $(window).mousemove(obj.mousemove).bind('touchmove', obj.mousemove); var obj = this; this.domObj.find("#inputs_tab, #inputs_tab + label").bind(hitEvent, function() { obj.domObj.find("#inputs_tab").prop('checked', true); obj.domObj.find("div#create-plan-container").find(">:first-child").detach(); obj.domObj.find("div#create-plan-container").append(obj.inputsCat); $("#formBuildProps").show(); $(window).triggerHandler('resize'); }); this.domObj.find("#formulas_tab, #formulas_tab + label").bind(hitEvent, function() { obj.domObj.find("#formulas_tab").prop('checked', true); obj.domObj.find("div#create-plan-container").find(">:first-child").detach(); obj.domObj.find("div#create-plan-container").append(obj.formulasCat); $("#formBuildProps").hide(); $(window).triggerHandler('resize'); obj.expBuilder.widget.refresh(); /*var node = obj.formulasCat.find(".expname").focus().get(0); var selection = document.getSelection(); if (selection && node) { selection.removeAllRanges(); nativeRange = document.createRange(); nativeRange.setStart(node, 0); nativeRange.setEnd(node, 1); selection.addRange(nativeRange); }*/ }); this.domObj.find("#general_tab, #general_tab + label").bind(hitEvent, function() { obj.domObj.find("#general_tab").prop('checked', true); obj.domObj.find("div#create-plan-container").find(">:first-child").detach(); obj.domObj.find("div#create-plan-container").append(obj.generalCat); $("#formBuildProps").hide(); $(window).triggerHandler('resize'); }); this.domObj.find("#food_tab, #food_tab + label").bind(hitEvent, function() { obj.domObj.find("#food_tab").prop('checked', true); obj.domObj.find("div#create-plan-container").find(">:first-child").detach(); obj.domObj.find("div#create-plan-container").append(obj.foodCat); $("#formBuildProps").hide(); $(window).triggerHandler('resize'); }); this.domObj.find("#rules_tab, #rules_tab + label").bind(hitEvent, function() { obj.domObj.find("#rules_tab").prop('checked', true); obj.domObj.find("div#create-plan-container").find(">:first-child").detach(); obj.domObj.find("div#create-plan-container").append(obj.rulesCat); $("#formBuildProps").hide(); $(window).triggerHandler('resize'); obj.rulesBuilder.widget.refresh(); }); this.domObj.find("#exercise_tab, #exercise_tab + label").bind(hitEvent, function() { obj.domObj.find("#exercise_tab").prop('checked', true); obj.domObj.find("div#create-plan-container").find(">:first-child").detach(); obj.domObj.find("div#create-plan-container").append(obj.exerciseCat); $("#formBuildProps").hide(); $(window).triggerHandler('resize'); }); this.domObj.find("#loadplan").click(function(e) { e.preventDefault(); var widget = new Widget("LoadPlan", ''); widget.renderIntoPopup('280', '280', null, function() {}); }); this.domObj.find("#saveplan").click(function(e) { e.preventDefault(); blockWindow(); var saveparams = {}; $(obj.generalCat).find('textarea, input[type=checkbox], input[type=text]').each(function() { if ($(this).attr('type') == 'checkbox' && $(this).is(":checked")) { saveparams[$(this).attr('id')] = $(this).val(); } else if ($(this).attr('type') == 'text') { saveparams[$(this).attr('id')] = $(this).val(); } else if ($(this).prop('tagName').toLowerCase() == 'textarea') { saveparams[$(this).attr('id')] = $(this).val(); } }); obj.rulesBuilder.widget.save(function() { obj.expBuilder.widget.save(function() { obj.formBuilder.widget.savePlan(function() { obj.exerciseBuilder.widget.save(function() { obj.foodBuilder.widget.save(function() { saveWindowSession('CREATEPLANGENERAL', saveparams, function() { $.ajax( { url: "/service/SavePlan.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&plan_id=" + obj.plan_id, cache: false, dataType: "json", data: {}, success: function(data) { obj.plan_id = data; saveWindowSession('CREATEPLAN', { plan_id: obj.plan_id }, function() { unblockWindow(); }); } }); }); }); }); }); }); }); }); this.domObj.find("#general_tab").click(); } CreatePlan.prototype.isBuilt=function() { var obj = this; return (obj.foodBuilder.widget.isBuilt() && obj.formBuilder.widget.isBuilt() && obj.exerciseBuilder.widget.isBuilt() && obj.expBuilder.widget.isBuilt() && obj.rulesBuilder.widget.isBuilt()); } CreatePlan.prototype.contentSet=function(){ this.resizeFunc = function() { $("#admin_menu").css("position", "fixed").css("top", ($("section#header").outerHeight()) + "px"); $("#create-plan-container > div.cp").css("position", "relative").css("top", ($("#admin_menu").outerHeight() + 20) + "px"); $("#selectfields").css("position", "fixed").css("top", ($("section#header").outerHeight() + $("#admin_menu").outerHeight()) + "px"); $("#create-plan-spacer").css("height", (5 + $("#selectfields").outerHeight() + $("#admin_menu").outerHeight()) + "px"); $("#top-sub-nav").css("position", "fixed").css("top", $("#section#header").outerHeight() + "px"); $("#form-flow.root .editmode").css("top", ($("section#header").outerHeight() + 0+ $("#selectfields").outerHeight() + $("#admin_menu").outerHeight() + 5) + "px"); }; $("section#header").css("position", "fixed"); $("#content").removeClass("page_width"); $("#footer").hide(); $(window).resize(this.resizeFunc).triggerHandler('resize'); this.formBuilder.widget.setTrashBin($("#trashbin")); } CreatePlan.prototype.destroy=function() { var obj = this; $("section#header").css("position", ""); $("#content").addClass("page_width"); $("#footer").show(); $("#top-sub-nav").css("position", "absolute").css("top", "auto"); $(window).unbind('resize', this.resizeFunc); $(window).unbind('mouseup', obj.mouseup).unbind('touchend', obj.mouseup); $(window).unbind('mousemove', obj.mousemove).unbind('touchmove', obj.mousemove); $("#formBuildProps").remove(); } function ChangePlan(params) { this.built = false; this.loginRequired = true; this.ChoosePlans = null; this.currStep = 'step1'; this.choosePlanPage = 0; this.fetchingData = false; this.regCode = ''; this.currplanid = 0; this.plantype = 0; this.planname = ''; } ChangePlan.prototype.updateAccountPlan=function() { var obj = this; //blockWindow(); $.ajax( { url: "/service/ChangePlan.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { }, success: function( data ) { //unblockWindow(); $.ajax( { url: "/service/GetUserPlanInfo.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", retryCnt: -1, data: { 'b4b_id': g_userInfo.b4b_id }, success: function( data ) { if (! data) { g_userHasPlan = false; } else { g_userHasPlan = true; } setWindow("Feed"); } }); } }); } ChangePlan.prototype.buildPage=function(mode) { var obj = this; this.domObj = $('
    \
    \

    \
    \ \ \
    \
    '); return true; } ChangePlan.prototype.build = function(mode, submode) { var obj = this; obj.buildPage(mode); if (! mode) { obj.setMode('step2'); } else { //obj.setMode('step2'); } if (! this.ChoosePlans) { this.ChoosePlans = new Widget("ChoosePlans", { allownoplan: false} ); } /*var currPage = 1; var hashparts = window.location.hash.split("-"); if (hashparts.length >= 3 && hashparts[2] != '') { currPage = parseInt(hashparts[2]); }*/ //this.choosePlanPage = parseInt(this.choosePlanPage); /*this.ChoosePlans.setPage(obj.choosePlanPage, function() { g_doNotProcessHash = false; location.href = "#ChangePlan-step2-" + obj.ChoosePlans.getPageName(obj.choosePlanPage < 0 ? 0 : obj.choosePlanPage); obj.ChoosePlans.render(obj.domObj.find("#select-plan-container")) });*/ //this.ChoosePlans.setPage(this.choosePlanPage); var pageParts = getHash().split("-"); var pageNum = (submode != '') ? this.ChoosePlans.getPageNum(submode) : 0; var obj = this; //alert(submode); //alert(pageNum); this.ChoosePlans.setPage(pageNum, function() { //g_doNotProcessHash = true; //location.href = "#ChangePlan-step2-" + this.ChoosePlans.getPageName(this.choosePlanPage < 0 ? 0 : this.choosePlanPage); obj.ChoosePlans.render(obj.domObj.find("#select-plan-container"), function() { if (obj.ChoosePlans.widget.isLastPage()) { obj.domObj.find("#next").text("Submit").val("Submit"); } else { obj.domObj.find("#next").text("Next >").val("Next >"); } }); }); return false; } ChangePlan.prototype.setMode=function(mode) { } ChangePlan.prototype.getDomObj=function() { return this.domObj; } ChangePlan.prototype.setHooks=function(mode) { var obj = this; this.domObj.find("#prev").click(function() { obj.ChoosePlans.prev(function() { var done = obj.ChoosePlans.isDone(); if (done == true) { setWindow("Feed"); } else { //saveWindowSession('REGISTER', { choosePlanPage: obj.ChoosePlans.getCurrentPage() }, function() { g_doNotProcessHash = false; //location.href = "#ChangePlan-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage()); setWindow("ChangePlan-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage())); //obj.ChoosePlans.render(obj.domObj.find("#select-plan-container")); //}); } }); }); //this.domObj.find("#next").click(function(e) { // e.preventDefault(); //}); } ChangePlan.prototype.widgetCallback=function(widget, msg, data) { } ChangePlan.prototype.destroy=function() { } ChangePlan.prototype.isBuilt=function() { return this.ChoosePlans && this.ChoosePlans.widget.isBuilt(); } ChangePlan.prototype.contentSet=function(){ var obj = this; $("#signup-form").submit(function(e) { e.preventDefault(); if ($(document.activeElement).attr('id') == 'planfilter') { $("input[type=text]").blur(); return; } obj.ChoosePlans.next(function () { var done = obj.ChoosePlans.isDone(); if (done == true) { //setWindow("ChangePlan-step3"); //alert(process); obj.updateAccountPlan(); //setWindow("Feed"); } else { //saveWindowSession('REGISTER', { choosePlanPage: obj.ChoosePlans.getCurrentPage() }, function() { g_doNotProcessHash = false; //alert("current: " + obj.ChoosePlans.getCurrentPage()); //location.href = "#ChangePlan-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage()); setWindow("ChangePlan-step2-" + obj.ChoosePlans.getPageName(obj.ChoosePlans.getCurrentPage())); //obj.ChoosePlans.render(obj.domObj.find("#select-plan-container")); //}); } }); //$("#next").triggerHandler('click'); }); } function DateAdd(date, type, amount) { var y = date.getFullYear(), m = date.getMonth(), d = date.getDate(); if (type === 'y') { y += amount; }; if (type === 'm') { m += amount; }; if (type === 'd') { d += amount; }; return new Date(y, m, d); } (function () { Date.prototype.toYMD = Date_toYMD; function Date_toYMD() { var year, month, day; year = String(this.getFullYear()); month = String(this.getMonth() + 1); if (month.length == 1) { month = "0" + month; } day = String(this.getDate()); if (day.length == 1) { day = "0" + day; } return year + "-" + month + "-" + day; } })(); function Feed(params) { this.loginRequired = true; this.destroyed = false; this.built = false; var obj = this; this.updateScroll = function () { obj.scrolltime = Date.now(); $(window).triggerHandler('resize'); obj.scroll(); } this.burned = 0; this.limitcals = 0; this.viewed = []; //$(window).bind('scroll', this.updateScroll); //$(window).bind('scroll', scrollMaps); document.addEventListener('scroll', this.updateScroll, {passive: true}); document.addEventListener('scroll', scrollMaps, {passive: true}); this.ajaxRunning = false; this.gotComments = []; this.pendingComments = []; this.updatingComments = []; this.updatingLikes = []; this.topmostFeedId = 0; this.gotInitFeed = false; this.posted = false; this.goalSteps = 0; this.lineChartData = null; this.d = new Date(); this.dset = new Date(); } Feed.prototype.repositionBars = function (feedright) { var obj = this; if ($("#helpblock:visible").length > 0) { // dont move if help is active return; } var h = feedright.css('position') == 'static' ? feedright.parent().height() : feedright.height(); var o = $(".feedmain").offset().top; var fh = $(".feedmain").height(); var wh = window.innerHeight; var st = $(window).scrollTop(); var pos; if (fh + o < h) { feedright.css({ 'position': 'static' }); return; } if (h > wh && st > o + (h - wh)) { pos = (wh - h); pos -= Math.max((st + wh - $("#footer").offset().top), 0); console.log('pos = ' + pos); feedright.css({ 'position': 'fixed', 'top': (pos) + 'px', 'width': feedright.parent().width() + 'px' }); } else if (h < wh && st > o) { pos = 0; pos -= Math.max((st + wh - $("#footer").offset().top), 0); console.log('pos = ' + pos); feedright.css({ 'position': 'fixed', 'top': (pos) + 'px', 'width': feedright.parent().width() + 'px' }); } else { feedright.css({ 'position': 'static' }); } } Feed.prototype.scroll = function () { var obj = this; /*if (obj.posTimer) { clearTimeout(obj.posTimer); obj.posTimer = null; }*/ //if (!obj.posTimer) { // obj.posTimer = setTimeout(function() { obj.posTimer = null; if (window.innerWidth > 600) { obj.repositionBars($(".feedright>div")); obj.repositionBars($(".feedleft>div")); } var last = $('.feeditem:not(.status):last'); var first = $('.feeditem:not(.status):first'); if (last.length > 0 && $(window).scrollTop() + $(window).height() >= $(document).height() - 50) { obj.updateFeed(0, last.attr('feedid'), 1); } //if (first.length > 0 && $(window).scrollTop() <= first.offset().top) { //if (this.posted == true) { //this.posted = false; //this.updateFeed(1, this.topmostFeedId, 1); //} //} //}, 80); /*if (window.innerWidth > 600) { obj.repositionBars($(".feedright>div")); obj.repositionBars($(".feedleft>div")); }*/ //} /*if (obj.gotInitFeed) { $('.feeditem').each(function() { if (obj.viewed.indexOf(this) == -1) { if (isScrolledIntoView(this)) { var el = this; $.ajax( { url: "/service/ViewedItem.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: $(this).attr('feedid') }, success: function( data ) { obj.viewed.push(el); obj.scroll(); } }); } } }); }*/ /*var last = $('.feeditem:not(.status):last'); var first = $('.feeditem:not(.status):first'); if (last.length > 0 && $(window).scrollTop() + $(window).height() >= $(document).height() - 50) { this.updateFeed(0, last.attr('feedid'), 1); } if (first.length > 0 && $(window).scrollTop() <= first.offset().top) { //if (this.posted == true) { //this.posted = false; //this.updateFeed(1, this.topmostFeedId, 1); //} }*/ } //30 40 100 Feed.prototype.resize = function () { var obj = this; if (obj.last_win_size == window.innerWidth) return; obj.last_win_size = window.innerWidth; this.domObj.find("#scroll_mutual").width(50); this.domObj.find("#scroll_friends").width(50); if (window.innerWidth >= 1200) { obj.domObj.find("#mobile_friends").hide(); } else { obj.domObj.find("#mobile_friends").show(); } if (obj.barChartLarge) { obj.resizeCharts(); } // //this.domObj.find("canvas").width(50); //this.domObj.find("canvas").width(this.domObj.find("canvas").parent().width()-10); //if (window.myLine) { /*if (this.lineChartData) { var grabData = function(){} var show = false; for (var j = 0; j < this.lineChartData.datasets[0].data.length; j++) { if (this.lineChartData.datasets[0].data[j] > 0) { show = true; break; } } if (show) { obj.domObj.find("#chartlargeitem").show(); } else { obj.domObj.find("#chartlargeitem").hide(); } var thedata = {}; //alert(JSON.stringify(this.lineChartData)); var data = this.lineChartData.datasets[0].data; var c = 0; for (var i = data.length-1; i >= 0; i--) { if (i > 0) { thedata[c] = [data[i]-data[i-1]]; } else { thedata[c] = [data[i]]; } c++; } $("#infichart").height(340).width(Math.max($("#infichart").parent().width(), 100)); obj.barChart = new infichart(obj.domObj.find("#infichart")[0], infichart.BAR_CHART, 1, 0, data.length, 0); if (obj.d.toDateString() === new Date().toDateString()) { obj.barChart.infichart.labelmode = 'todayhours'; } else { obj.barChart.infichart.labelmode = 'hours'; } this.barChart.infichart.numbars = 1; this.barChart.setChartValues(thedata, 0, data.length, 0); //$(window).triggerHandler('resize'); setChartOptions(obj.barChart); obj.barChart.refreshInfiChart();*/ //alert("here"); /* if (typeof(obj.barChart) != 'undefined') { obj.barChart.destroy(); } if (window.innerWidth >= 1200) { //obj.lineChartData = data; obj.barChart = new Widget('LineChart', { height: 300 }); var show = false; for (var j = 0; j < this.lineChartData.datasets[0].data.length; j++) { if (this.lineChartData.datasets[0].data[j] > 0) { show = true; break; } } if (show) { obj.domObj.find("#chartlargeitem").show(); } else { obj.domObj.find("#chartlargeitem").hide(); } obj.barChart.widget.setData(obj.lineChartData); obj.barChart.render(obj.domObj.find("#chartlarge")); //this.barChart.widget.setData(this.lineChartData); } else { //obj.lineChartData = data; obj.barChart = new Widget('LineChart', {}); obj.domObj.find("#chartlargeitem").hide(); obj.domObj.find("#scroll_friends").hide(); var show = false; for (var j = 0; j < this.lineChartData.datasets[0].data.length; j++) { if (this.lineChartData.datasets[0].data[j] > 0) { show = true; break; } } //show = false; //setTimeout(function() { if (show) { obj.domObj.find("#chart").show(); obj.domObj.find("#chart").next("hr").show(); } else { obj.domObj.find("#chart").hide(); obj.domObj.find("#chart").next("hr").hide(); } obj.barChart.widget.setData(obj.lineChartData); obj.barChart.render(obj.domObj.find("#chart")); //}, 1000); this.barChart.widget.setData(this.lineChartData); } */ //} //window.myLine.resize(); //} setTimeout(function() { obj.domObj.find("#scroll_mutual").width(obj.domObj.find("#scroll_mutual").parent().width() - 10); obj.domObj.find("#scroll_friends").width(obj.domObj.find("#scroll_friends").parent().width() - 10).show(); }, 500); } Feed.prototype.getCommentStr = function (data, feedid) { var obj = this; return getCommentStr(obj, data, feedid); } Feed.prototype.getComments = function (feedid, reply_to_id) { var obj = this; return getComments(obj, feedid, reply_to_id); } Feed.prototype.getPreviousComments = function (feedid, before, reply_comment_id) { var obj = this; return getPreviousComments(obj, feedid, before, reply_comment_id); } Feed.prototype.getPendingComments = function () { var obj = this; return getPendingComments(obj); } Feed.prototype.getHighestComment = function (feedid) { var obj = this; return getHighestComment(obj, feedid); } Feed.prototype.startUpdatingCommentsAll = function (notimer) { var obj = this; return startUpdatingCommentsAll(obj, notimer); } Feed.prototype.startUpdatingComments = function () { var obj = this; return startUpdatingComments(obj); } Feed.prototype.startGettingComments = function () { var obj = this; return startGettingComments(obj); } Feed.prototype.getScheduleExercise = function () { var obj = this; $.ajax({ url: "/service/GetTodaysScheduledExercises.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", retryCnt: -1, data: { type: 'both', restrict: 'false' }, success: function (data) { if (data && data.length) { var str = ''; for (var i = 0; i < data.length; i++) { str += '
    ' + htmlencode(data[i].name) + '
    '; //obj.domObj.find('.exercise[eid="' + data[i].exercise_id + '"]').addClass("scheduled"); } obj.domObj.find("#schedex").html(str); } else { obj.domObj.find("#schedex").html('

    No exercise scheduled today!

    '); } } }); } Feed.prototype.updateLocStats=function() { var obj = this; var datestr = this.d.toYMD(); $.ajax({ url: "/service/GetLocStats.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", notWhenTracking: true, data: { b4b_id: g_userInfo.b4b_id, datestr: datestr }, retryCnt: -1, success: function (data) { obj.domObj.find("#distance").text(parseFloat(data.distance).toFixed(1)); obj.domObj.find("#speed").text(parseFloat(data.speed).toFixed(1)); obj.domObj.find("#uphill").text(parseInt(data.uphill * 3.28084)); obj.domObj.find("#downhill").text(parseInt(data.downhill * 3.28084)); } }); } Feed.prototype.getStepCount = function (notimer) { var obj = this; var datestr = this.d.toYMD(); $.ajax({ url: "/service/GetUserStepCount.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", notWhenTracking: true, data: { b4b_id: g_userInfo.b4b_id, datestr: datestr }, retryCnt: -1, success: function (data) { if (!obj.destroyed) { if (obj.d.toYMD() == datestr) { var steps = data.stepcnt || 0; if (typeof(obj.lastSteps) == 'undefined' || obj.lastSteps != steps || notimer) { obj.updateTotals(); obj.updateAdherence(); obj.getBarChartData(); } obj.lastSteps = steps; var dist = parseFloat(data.dist).toFixed(2); $(".STEPS").html('' + parseInt(steps).toLocaleString() + ' / ' + dist + "mi
    "); obj.updateGoalSteps(); obj.updateLocStats(); } if (!notimer) { setTimeout(function () { obj.getStepCount(); }, STEPCOUNT_UPDATE_TIME); } } } }); } Feed.prototype.setChartData = function(chart, $show, shouldshow) { var obj = this; var show = false; for (var j = 0; j < obj.lineChartData.datasets[0].data.length; j++) { if (obj.lineChartData.datasets[0].data[j] > 0) { show = true; break; } } if (show) { if (shouldshow) $show.show(); //obj.domObj.find("#chartlargeitem").show(); } else { $show.hide(); return; //obj.domObj.find("#chartlargeitem").hide(); } var thedata = {}; //alert(JSON.stringify(this.lineChartData)); var data = obj.lineChartData.datasets[0].data; var c = 0; for (var i = data.length-1; i >= 0; i--) { if (i > 0) { thedata[c] = [data[i]-data[i-1]]; } else { thedata[c] = [data[i]]; } c++; } if (obj.d.toDateString() === new Date().toDateString()) { chart.infichart.labelmode = 'todayhours'; } else { chart.infichart.labelmode = 'hours'; } chart.infichart.curri = obj.lineChartData.curr || 0; //chart.infichart.curri--; //alert(JSON.stringify(obj.lineChartData.labels)); chart.infichart.labels = obj.lineChartData.labels; chart.setChartValues(thedata, 0, data.length, chart.infichart.currval); //$(window).triggerHandler('resize'); //setChartOptions(chart); chart.refreshInfiChart(); } Feed.prototype.setChart = function($canvas, $show, shouldshow, height) { var obj = this; var grabData = function(){} var show = false; for (var j = 0; j < obj.lineChartData.datasets[0].data.length; j++) { if (obj.lineChartData.datasets[0].data[j] > 0) { show = true; break; } } if (show && shouldshow) { $show.show(); //obj.domObj.find("#chartlargeitem").show(); } else { $show.hide(); //obj.domObj.find("#chartlargeitem").hide(); } var thedata = {}; //alert(JSON.stringify(this.lineChartData)); var data = obj.lineChartData.datasets[0].data; var c = 0; for (var i = data.length-1; i >= 0; i--) { if (i > 0) { thedata[c] = [data[i]-data[i-1]]; } else { thedata[c] = [data[i]]; } c++; } $canvas.height(height).width(Math.max($canvas.parent().width(), 100)); obj.barChart = new infidaychart($canvas[0], infichart.BAR_CHART, 1, 0, data.length, 0); if (obj.d.toDateString() === new Date().toDateString()) { obj.barChart.infichart.labelmode = 'todayhours'; } else { obj.barChart.infichart.labelmode = 'hours'; } obj.barChart.infichart.numbars = 1; obj.barChart.infichart.curri = obj.lineChartData.curr || 0; obj.barChart.labels = obj.lineChartData.labels; obj.barChart.setChartValues(thedata, 0, data.length, 0); //$(window).triggerHandler('resize'); setChartOptions(obj.barChart); obj.barChart.refreshInfiChart(); return obj.barChart; } Feed.prototype.setChartOptions=function(chart, w) { w = chart.getInfiChartWidth()*chart.infichart.scale; chart.infichart.unitpadding = 1; chart.infichart.barpadding = 1; var padding = chart.infichart.barpadding; //var bw = -chart.infichart.numbars*(chart.infichart.barwidth+padding+padding)/2; var bw = 12; chart.infichart.barwidth = 2; chart.infichart.barwidth = w / (8 * 50); //w -= (24 * 2);// * PIXEL_RATIO; // subtract bar padding //w -= 30; //w -= 180;///PIXEL_RATIO; // scale clip //chart.infichart.barwidth = Math.max(1, Math.floor(w*PIXEL_RATIO/4/(24*2))); // 4 = scale, 24 = hours //chart.infichart.barwidth = Math.max(1.0, (w/(24*2*bw))); // 4 = scale, 24 = hours //chart.infichart.barwidth = 0.5; //chart.infichart.barwidth = w / this.infichart.numintervals / 3.5; } Feed.prototype.resizeCharts = function() { var obj = this; if (obj.lineChartData) { var show = false; for (var j = 0; j < obj.lineChartData.datasets[0].data.length; j++) { if (obj.lineChartData.datasets[0].data[j] > 0) { show = true; break; } } if (show) { if (window.innerWidth >= 1002) { $("#chartlargeitem").show(); $("#chart").hide(); } else { $("#chartlargeitem").hide(); $("#chart").show(); } } } //obj.barChartLarge.infichart.unitpadding = 2; //obj.barChartSmall.infichart.unitpadding = 2; //obj.barChartLarge.infichart.barwidth = 10; //obj.barChartSmall.infichart.barwidth = 10; $canvas1 = $("#chartlargeitem").find("#infichart"); $canvas2 = $("#chart").find("#infichart"); obj.setChartOptions(obj.barChartLarge, Math.max($canvas1.parent().width(), 100)); obj.setChartOptions(obj.barChartSmall, Math.max($canvas2.parent().width(), 100)); $canvas1.hide(); $canvas1.height(250).width(Math.max($canvas1.parent().width(), 100)); //obj.barChart.refreshInfiChart(); $canvas2.hide(); $canvas2.height(250).width(Math.max($canvas2.parent().width(), 100)); //obj.barChartSmall.refreshInfiChart(); obj.setChartData(obj.barChartLarge, $("#chartlargeitem")); obj.setChartData(obj.barChartSmall, $("#chart")); $canvas1.show(); $canvas2.show(); obj.setChartOptions(obj.barChartLarge); obj.setChartOptions(obj.barChartSmall); obj.barChartLarge.refreshInfiChart(); obj.barChartSmall.refreshInfiChart(); //setTimeout(function() { //obj.barChartLarge.setInfiChartRez(); // obj.barChartSmall.setInfiChartRez(); //obj.barChartLarge.drawInfiChart(); //obj.barChartSmall.drawInfiChart(); //}, 60); } Feed.prototype.getBarChartData = function () { var obj = this; var datestr = this.d.toYMD(); $.ajax({ url: "/service/GetTodaysStepChunks.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { datestr: datestr }, notWhenTracking: true, retryCnt: -1, success: function (data) { if (obj.d.toYMD() != datestr) return; if (!data || !data.datasets.length) { return; } obj.lineChartData = data; //obj.resize(); if (obj.lineChartData) { if (obj.barChartLarge) { obj.setChartData(obj.barChartLarge, $("#chartlargeitem"), window.innerWidth >= 1200); obj.setChartData(obj.barChartSmall, $("#chart"), window.innerWidth < 1200); } else { obj.barChartLarge = obj.setChart($("#chartlargeitem").find("#infichart"), $("#chartlargeitem"), window.innerWidth >= 1200, 340); obj.barChartSmall = obj.setChart($("#chart").find("#infichart"), $("#chart"), window.innerWidth < 1200, 180); } obj.last_win_size = 0; $(window).trigger('resize'); //obj.resizeCharts(); } /*if (typeof(obj.barChart) != 'undefined') { obj.barChart.destroy(); } obj.lineChartData = data; obj.barChart = new Widget('BarChart', { }); obj.barChart.widget.setData(obj.lineChartData); obj.barChart.render(obj.domObj.find("#chart"));*/ //obj.barChart.widget.setData({}); //obj.barChart.render(obj.domObj.find("#chart")); } }); } Feed.prototype.updateFeed = function (top, feed_id, viewed) { var obj = this; if (this.ajaxRunning) { return; } this.ajaxRunning = true; $.ajax({ url: "/service/GetFeed.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", retryCnt: -1, notWhenTracking: true, data: { top: top, feed_id: feed_id, viewed: viewed }, success: function (data) { if (!obj.gotInitFeed) { obj.gotInitFeed = true; //obj.startGettingComments(); //obj.startUpdatingComments(); obj.startUpdatingCommentsAll(); obj.startUpdatingLikesAll(); obj.getScheduleExercise(); obj.updateAdherence(); obj.getStepCount(); obj.getBarChartData(); } obj.ajaxRunning = false; obj.built = true; var profilepicurl = '/images/feedpics/nopic.png'; //var pics = [ '/images/feedpics/img1.jpg', '/images/feedpics/img2.png', '/images/feedpics/img3.jpg', '/images/feedpics/img1.jpg', '/images/feedpics/img2.png', '/images/feedpics/img3.jpg' ]; var str = ''; if (top && data.length > 0) { obj.posted = false; } for (var i = 0; i < data.length; i++) { if (top && i == 0) { obj.topmostFeedId = data[i].feed_id; } var numpics = data[i].fids.length; var pics = []; for (var j = 0; j < data[i].fids.length; j++) { pics.push("/service/GetFile.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&pic=" + data[i].fids[j]); } if (obj.domObj.find('.feeditem[feedid="' + data[i].feed_id + '"]').length != 0) { continue; } str += getFeedString(data[i], numpics, pics); str += ''; } var dobj = $(str); dobj.find("img").unveil(); if (top) { obj.domObj.find("#feedupdates").prepend(dobj); } else { obj.domObj.find("#feedupdates").append(dobj); } if (shouldTriggerScroll()) $(window).triggerHandler("scroll"); obj.scroll(); obj.updateTimes(); updateMaps(); } }); return false; } function days_between(date1, date2) { // The number of milliseconds in one day var ONE_DAY = 1000 * 60 * 60 * 24 // Convert both dates to milliseconds var date1_ms = date1.getTime() var date2_ms = date2.getTime() // Calculate the difference in milliseconds var difference_ms = Math.abs(date1_ms - date2_ms) // Convert back to days and return return Math.round(difference_ms / ONE_DAY) } Feed.prototype.updateDateLabels = function () { var labelstr = ''; var today = new Date(); if (this.d.getFullYear() == today.getFullYear() && this.d.getDate() == today.getDate() && this.d.getMonth() == today.getMonth()) { labelstr = "Today's"; } else { var days = ["Sunday's", "Monday's", "Tuesday's", "Wednesday's", "Thursday's", "Friday's", "Saturday's"]; if (Math.abs(days_between(today, this.d)) < 7 && this.d.getTime() < today.getTime()) { if (today.getDay() == 0) { labelstr = days[this.d.getDay()]; } else { if (this.d.getDay() > today.getDay()) { labelstr = 'Last '; labelstr += days[this.d.getDay()]; } else { labelstr = days[this.d.getDay()]; //labelstr = this.d.getMonth() + '/' + this.d.getDate() + '/' + this.d.getFullYear(); } } } else { labelstr = (this.d.getMonth()+1) + '/' + this.d.getDate() + '/' + this.d.getFullYear(); } } $(".datelbl").text(labelstr); } Feed.prototype.getMutualFriends = function () { var obj = this; obj.domObj.find("#mutual_friends").fadeOut(); return; $.ajax({ url: "/service/GetMutualFriends.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, notWhenTracking: true, success: function (datafr) { if (!datafr || !datafr.results.length) { obj.domObj.find("#mutual_friends").fadeOut(); return; } var str = ''; var profilepicurl = '/images/feedpics/nopic.png'; for (var i = 0; i < datafr.results.length; i++) { if (!datafr.results[i].b4b_id) { continue; } str += '
    ' + htmlencode((datafr.results[i].firstname || '') + ' ' + (datafr.results[i].lastname || '')) + '
    ' + (datafr.results[i].stepcnt > 0 ? 'Steps: ' + datafr.results[i].stepcnt + '' : '') + (datafr.results[i].weightlost > 0 ? 'Lost: ' + datafr.results[i].weightlost + ' lbs' : '') + '
    '; } //alert(str); var dobj = $(str); dobj.find("img").unveil(); obj.domObj.find("#mutual").html(dobj); if (shouldTriggerScroll()) $(window).triggerHandler("scroll"); } }); } Feed.prototype.build = function (mode) { var obj = this; $("#content").removeClass("page_width"); var str = ''; var profilepicurl = '/images/feedpics/nopic.png'; str += '
    '; str += '
    '; str += '
    \

    Your Team:

    \
    \
    \
    '; /*str += '
    \

    Friends:

    \
    \ \ \












    \
    ';*/ str += '
    '; str += '
    '; str += this.getTotalsBox(true); str += '
    \ \
    \
    \

    Your Team:

    \
    \
    \
    \
    \
    \
    \ \
    \
    \

    People you may know:

    \
    \
    \
    \
    \
    \
    \ \
    '; str += '
    '; str += '
    '; str += this.getStepsBox(); str += this.getTotalsBox(); str += this.getPlannedExerciseBox(); str += this.getPlannedAdherence(); str += '
    '; this.domObj = $(str); this.barChart = new Widget('LineChart', {}); obj.domObj.on("click", ".viewadheredet", function (e) { e.preventDefault(); var datestr = obj.d.toYMD(); var widget = new Widget("AdhereDetails", { datestr: datestr }); var goelem = this; widget.renderIntoPopup('100%', '100%', $(this), function () {}); }); obj.domObj.on('click', 'a.discuss', function (e) { e.preventDefault(); setWindow("Discuss-" + $(this).attr('did')); }); this.domObj.on("touchend", function (e) { obj.domObj.find("canvas").triggerHandler("touchend"); }); setTimeout(function () { obj.getMutualFriends(); }, 0); setTimeout(function () { obj.updateTotals(); }, 0); obj.domObj.find("#invitereq").click(function (e) { e.preventDefault(); blockWindow(); $.ajax({ url: "/service/InviteBuddies.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { invitees: obj.domObj.find("#invitees").val() }, success: function (data) { obj.domObj.find("#invitees").val(''); unblockWindow(); } }); }); obj.domObj.on('click', '.sendmsgto', function (e) { e.preventDefault(); e.stopPropagation(); userClicked($(this).attr('username')); }); obj.domObj.on('click', 'a.commentpost', function (e) { e.preventDefault(); var feedid = $(this).attr('feedid'); obj.domObj.find(".feeditem[feedid=" + feedid + "]").find(".leavecomment[reply_comment_id=0]").find("textarea").focus(); }); obj.domObj.on('click', 'a.likepost', function (e) { e.preventDefault(); var feedid = $(this).attr('feedid'); var link = this; $.ajax({ url: "/service/LikePost.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: feedid }, success: function (data) { $(link).text("Liked"); obj.startUpdatingLikesAll(true); } }); }); obj.domObj.on('click', 'a.prevdate', function (e) { e.preventDefault(); obj.d = DateAdd(obj.d, 'd', -1); obj.dset = new Date(); obj.getStepCount(true); obj.updateDateLabels(); }); obj.domObj.on('click', 'a.nextdate', function (e) { e.preventDefault(); obj.d = DateAdd(obj.d, 'd', 1); obj.dset = new Date(); obj.getStepCount(true); obj.updateDateLabels(); }); obj.domObj.on('click', 'a.sharepost', function (e) { e.preventDefault(); var feedid = $(this).attr('feedid'); var link = this; $.ajax({ url: "/service/SharePost.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: feedid }, success: function (data) { $(link).text("Shared"); } }); }); obj.domObj.on('click', '.reply', function (e) { e.preventDefault(); var feed_id = $(this).attr('feed_id'); var reply_comment_id = $(this).attr('comment_id'); var comcon = obj.domObj.find(".comment_container[feed_id=" + feed_id + "][reply_comment_id=" + reply_comment_id + "]"); //alert(".comment_container[feed_id=" + $(this).attr('feed_id') + "][reply_comment_id=" + $(this).attr('reply_comment_id') + "]"); if (comcon.find(".leavecomment").length == 0) { var str = '
    \ \ \ \ Post Comment\ \
    \ '; comcon.append(str); } }); obj.domObj.on('click', '.prevcomment', function (e) { e.preventDefault(); $(this).remove(); obj.getPreviousComments($(this).attr('feedid'), $(this).attr('reply_comment_id'), $(this).attr('parentid')); }); obj.domObj.on('click', '.postcomment', function (e) { e.preventDefault(); var reply_comment_id = $(this).attr('reply_comment_id'); var feed_id = $(this).attr('feed_id'); var commentbox = obj.domObj.find(".comment[feed_id=" + feed_id + "][reply_comment_id=" + reply_comment_id + "]"); if (commentbox.length == 0 || String(commentbox.val()).trim() == '') { return; } blockWindow(); $.ajax({ url: "/service/WriteComment.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: feed_id, reply_comment_id: reply_comment_id, msg: commentbox.val() }, success: function (data) { unblockWindow(); commentbox.val(''); obj.startUpdatingCommentsAll(true); } }); }); setTimeout(function () { obj.updateFriends(); }, 0); setTimeout(function () { obj.updateFeed(1, 0, 1); }, 0); //obj.startGettingComments(); //obj.startUpdatingComments(); //obj.startUpdatingLikes(); return true; } Feed.prototype.startUpdatingLikesAll = function (notimer) { var obj = this; return startUpdatingLikesAll(obj, notimer); } Feed.prototype.updateFriends = function () { var obj = this; var frupdate = function() { $.ajax({ url: "/service/GetFriends.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", retryCnt: -1, notWhenTracking: true, data: { account_id: g_userInfo.b4b_id }, success: function (datafr) { var str = ''; var str2 = ''; var profilepicurl = '/images/feedpics/nopic.png'; if (! datafr || ! datafr.results || datafr.results.length == 0) { str = '

    Search for teammates

    '; obj.domObj.find("#frlisting").html(str); obj.domObj.find(".searchlnk").click(function (e) { e.preventDefault(); setWindow("Search"); }); } else { for (var i = 0; i < datafr.results.length; i++) { str += '' + htmlencode(datafr.results[i].firstname + ' ' + datafr.results[i].lastname) + '
    ' + (parseInt(datafr.results[i].stepcnt) > 0 ? 'Steps: ' + datafr.results[i].stepcnt + '' : '') + (datafr.results[i].weightlost > 0 ? 'Lost: ' + datafr.results[i].weightlost + ' lbs' : '') + '
    '; str2 += '
    ' + htmlencode(datafr.results[i].firstname + ' ' + datafr.results[i].lastname) + '
    ' + (parseInt(datafr.results[i].stepcnt) > 0 ? 'Steps: ' + datafr.results[i].stepcnt + '' : '') + (datafr.results[i].weightlost > 0 ? 'Lost: ' + datafr.results[i].weightlost + ' lbs' : '') + '
    '; } str += '

    See all

    '; var dobj = $(str); var dobj2 = $(str2); dobj.find("img").unveil(); dobj2.find("img").unveil(); obj.domObj.find("#frlisting").html(dobj); obj.domObj.find("#mfriends").html(dobj2); if (shouldTriggerScroll()) $(window).triggerHandler("scroll"); $(window).triggerHandler('resize'); obj.domObj.find("#seeallfriends").click(function (e) { e.preventDefault(); setWindow("Friends"); }); } //obj.domObj.find("#frlisting").html(str); if (!obj.destroyed) setTimeout(frupdate, 10000); } }); }; frupdate(); //setTimeout(frupdate, 10000); /*var frutimeout = function() { if (! obj.scrolltime) obj.scrolltime = 0; if (Date.now() - obj.scrolltime > 1000) { frupdate(); } else { setTimeout(frutimeout, 80); } }; frutimeout();*/ } Feed.prototype.getDomObj = function () { return this.domObj; } Feed.prototype.updateAdherence = function () { var obj = this; var datestr = this.d.toYMD(); $.ajax({ url: "/service/GetTodayAdherence.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { datestr: datestr }, retryCnt: -1, success: function (data) { if (obj.d.toYMD() != datestr) return; var text = ''; var cls = ''; if (data == -100) { text = 'Choose a plan'; obj.domObj.find(".adherence").css("border", "2px solid #ff0000"); obj.domObj.find(".viewadheredet").hide(); } else { text = 'A'; if (data <= 0.8) { text = 'B'; } if (data <= 0.6) { text = 'C'; } if (data <= 0.4) { text = 'D'; } if (data <= 0.2) { text = 'F'; } } obj.domObj.find(".adherence").addClass(cls).html(text); obj.domObj.find(".userswitchplan").click(function (e) { e.preventDefault(); blockWindow(); $.ajax({ url: "/service/SetPlanSessionData.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, success: function (data) { unblockWindow(); setWindow("ChangePlan"); } }); }); } }); } Feed.prototype.updateGoalSteps = function () { var obj = this; if (obj.goalSteps) { obj.domObj.find(".goalsteps").html('Goal: ' + parseInt(obj.goalSteps).toLocaleString()); } } Feed.prototype.updateTotals = function () { var obj = this; var datestr = this.d.toYMD(); $.ajax({ url: "/service/GetTodaysTotals.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { datestr: datestr }, retryCnt: -1, success: function (data) { if (obj.d.toYMD() != datestr) return; var burned = (data['burned'] || 0); obj.domObj.find(".total_burned").text(parseFloat(data['burned'] || 0).toFixed(0)); obj.domObj.find(".total_calories").text(parseFloat(data['calories'] || 0).toFixed(0)); obj.domObj.find(".total_carbs").text(parseFloat(data['carbs'] || 0).toFixed(0)); obj.domObj.find(".total_protein").text(parseFloat(data['protein'] || 0).toFixed(0)); obj.domObj.find(".total_fat").text(parseFloat(data['fat'] || 0).toFixed(0)); obj.domObj.find(".total_sugar").text(parseFloat(data['sugar'] || 0).toFixed(0)); obj.domObj.find(".total_fiber").text(parseFloat(data['fiber'] || 0).toFixed(0)); obj.domObj.find(".total_satfat").text(parseFloat(data['satFat'] || 0).toFixed(0)); obj.domObj.find(".total_polyfat").text(parseFloat(data['polyFat'] || 0).toFixed(0)); obj.domObj.find(".total_monofat").text(parseFloat(data['monoFat'] || 0).toFixed(0)); obj.domObj.find(".total_cholesterol").text(parseFloat(data['cholesterol'] || 0).toFixed(0)); obj.domObj.find(".total_sodium").text(parseFloat(data['sodium'] || 0).toFixed(0)); obj.domObj.find(".total_potassium").text(parseFloat(data['potassium'] || 0).toFixed(0)); $.ajax({ url: "/service/GetTodaysLimits.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { datestr: datestr }, retryCnt: -1, success: function (data) { if (obj.d.toYMD() != datestr) return; if (data) { if (data.calories) { obj.domObj.find(".outof.daily_cals").text(" / " + (parseInt(parseFloat(data.calories) /* + parseFloat(burned)*/))); } if (data.carbs) { obj.domObj.find(".outof.daily_carbs").text(" / " + parseInt(data.carbs)); } if (data.protein) { obj.domObj.find(".outof.daily_protein").text(" / " + parseInt(data.protein)); } if (data.fat) { obj.domObj.find(".outof.daily_fat").text(" / " + parseInt(data.fat)); } if (data.steps) { obj.goalSteps = parseInt(data.steps); obj.updateGoalSteps(); } } //alert(JSON.stringify(data)); } }); } }); } Feed.prototype.getPlannedExerciseBox = function () { var str = ''; str += '
    \

    Scheduled Today:

    \
    \
    \
    \
    '; return str; } Feed.prototype.getStepsBox = function () { var str = ''; str += '
    '; str += '

    ' + ('Today Totals:') + '

    '; str += '
    \
    \

    \
    \ \
    Calories Burned:0 kCal
    \
    \
    '; return str; } Feed.prototype.getPlannedAdherence = function () { var str = ''; str += '
    '; //

    Plan Adherence:

    str += '

    ' + ('Today Adherence Grade:') + '

    '; str += '
    \ \
    '; return str; } Feed.prototype.getTotalsBox = function (mobile) { var str = ''; var style_str = ""; if (mobile) { style_str = ' style="padding-top:3px;padding-bottom:3px;" '; } str += '
    '; if (mobile) { str += '

    ' + ('Today Totals:') + '

    '; } else { //str += '

    ' + ('Today Intake') + '

    '; str += '

    ' + ('Today Intake:') + '

    '; } str += '
    '; if (mobile) { str += 'Step Count:

    '; str += '\ \ \
    Calories Burned:0 kCal
    '; str += '
    '; str += '\

    Today Location Totals:

    \ \ \
    Distance:

    0.00 / mi

    Speed:

    0.00 / mph

    Max Elevation:

    0.00 / ft

    Min Elevation:

    0.00 / ft

    '; str += '

    Today Intake:

    '; } str += '\ \ \ \ \ \ \ \ '; //var extra = ['Sugars', 'Saturated Fat', 'Trans Fat', 'Polyunsaturated Fat', 'Monounsaturated Fat', // 'Cholesterol', 'Sodium', 'Potassium', 'Dietary Fiber', 'Soluble Fiber' ]; str += ''; str += ''; str += ''; str += ''; str += ''; // for (var i = 0; i < extra.length; i++) { // str += ''; // } str += '
    Calories:0 kCal
    Protein:0 g
    Fat:0 g
    Saturated Fat:0 g
    Polyunsaturated Fat:0 g
    Monounsaturated Fat:0 g
    Carbohydrate:0 g
    Dietary Fiber:0 g
    Sugars:0 g
    Cholesterol:0 mg
    Sodium:0 mg
    Potassium:0 mg
    ' + extra[i] + ':0
    '; if (mobile) { str += '

    Adherence to Plan:

    View Details

    '; } str += '
    \
    '; return str; } Feed.prototype.setMode = function (mode) {} Feed.prototype.setHooks = function () { var obj = this; this.domObj.find("#poststatus").click(function (e) { e.preventDefault(); if (String(obj.domObj.find("#statustext").val()).trim() == '') { return; } blockWindow(); var fids = []; obj.domObj.find(".postingimage").each(function () { fids.push($(this).attr('fid')); }); $.ajax({ url: "/service/PostStatus.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { msg: obj.domObj.find("#statustext").val(), fids: fids.join(",") }, success: function (data) { obj.domObj.find("#statustext").val(''); obj.domObj.find(".postingimage").remove(); unblockWindow(); setTimeout(function () { var first = $('.feeditem:not(.status):first'); if (first.length > 0) { obj.updateFeed(1, obj.topmostFeedId, /*first.attr('feedid'),*/ 1); } else { obj.updateFeed(1, 0, 0); } }, 10000); obj.posted = true; } }); }); function resizeimages() { var numpics = obj.domObj.find("#imageblock").find(".postingimage").length; if (numpics == 1) { obj.domObj.find("#imageblock").find(".postingimage").css("width", "97%").css("height", "280px"); } else if (numpics == 2) { obj.domObj.find("#imageblock").find(".postingimage").css("width", "47%").css("height", "280px"); } else { obj.domObj.find("#imageblock").find(".postingimage").css("width", "30%").css("height", "140px"); } } this.domObj.on('click', '.removepic', function (e) { e.preventDefault(); var fid = $(this).attr('fid'); obj.domObj.find(".postingimage[fid='" + fid + "']").fadeOut('slow', function () { $(this).remove(); resizeimages(); }); }); this.domObj.find("#addpics").click(function (e) { e.preventDefault(); var goelem = this; var widget = new Widget("ImageUpload", { hidden: true, callback: function (fid) { //$('html, body').animate({ // scrollTop: ($(goelem).offset().top - 100) //}, 2000); if (fid) { var str = ''; if (fid.substr(0, 4) == 'vid_') { str += 'X\ \ '; } else { str += 'X'; } /*if (numpics == 1) { str += ''; } else if (numpics == 2) { str += ''; str += ''; } else { for (var j = 0; j < numpics; j++) { str += ''; } }*/ obj.domObj.find("#imageblock").append(str); resizeimages(); } } }); widget.renderIntoPopup('80%', '80%', $(this), function () {}); }); } Feed.prototype.destroy = function () { //$(window).unbind('scroll', this.updateScroll); //$(window).unbind('scroll', scrollMaps); document.removeEventListener('scroll', this.updateScroll); document.removeEventListener('scroll', scrollMaps); $("#content").addClass("page_width"); this.destroyed = true; } Feed.prototype.isBuilt = function () { return this.built; } Feed.prototype.updateTimes = function () { this.domObj.find(".feedtime").each(function () { var data = $(this).attr('data'); var t = data.split(/[- :]/); // Apply each element to the Date function var d = new Date(t[0], t[1] - 1, t[2], t[3], t[4], t[5]); $(this).text(timeSince(d)); }); } Feed.prototype.contentSet = function () { var obj = this; obj.last_win_size = 0; this.updateDateLabels(); var updateFunc = function () { if (!obj.destroyed) { var first = $('.feeditem:not(.status):first'); //obj.updateFriends(); //obj.getMutualFriends(); //if (obj.posted == true || obj.viewed.indexOf(first.get(0)) != -1) { if (first.length > 0) { //console.log($('.feeditem:not(.status):first').attr('feedid')); obj.updateFeed(1, obj.topmostFeedId, /*first.attr('feedid'),*/ 1); } else { obj.updateFeed(1, 0, 0); } //} setTimeout(updateFunc, FEED_UPDATE_TIME); } }; var friendsUpdateFunc = function() { if (!obj.destroyed) { obj.updateFriends(); //obj.getMutualFriends(); //setTimeout(friendsUpdateFunc, FRIENDS_UPDATE_TIME); } }; var updateTimeFunc = function () { obj.updateTimes(); if (!obj.destroyed) { setTimeout(updateTimeFunc, TIME_UPDATE_TIME); var now = new Date(); if (now.getTime() - obj.dset.getTime() > 1000 * 60 * 30) { obj.d = new Date(); obj.dset = new Date(); obj.updateDateLabels(); obj.getStepCount(true); } } }; setTimeout(updateFunc, FEED_UPDATE_TIME); setTimeout(updateTimeFunc, TIME_UPDATE_TIME); setTimeout(friendsUpdateFunc, FRIENDS_UPDATE_TIME); this.resize(); } function Friends(params) { this.loginRequired = false; this.destroyed = false; this.built = false; this.start = 0; } Friends.prototype.rejectOrApproveFriend=function(reject, friendid) { var obj = this; blockWindow(); $.ajax( { url: "/service/RejectOrApproveFriend.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { reject: reject, friend_id: friendid }, success:function(datareq) { unblockWindow(); obj.update(); } }); } Friends.prototype.getUserInfo=function(callback) { var obj = this; if (g_userInfo.b4b_Id == obj.username.toLowerCase()) { obj.userInfo = g_userInfo; obj.domObj.find(".utext").html(ucfirst(obj.userInfo.firstname) + ''s'); callback(); return; } $.ajax( { url: "/service/UserSearch.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { searchfor: obj.username, type: 'username', start: '0', end: '1' }, success: function( data ) { if (data && data.results.length > 0) { obj.userInfo = data.results[0]; obj.domObj.find(".utext").html(ucfirst(obj.userInfo.firstname) + ''s'); callback(); } } }); } Friends.prototype.update = function() { blockWindow(); var obj = this; $.ajax( { url: "/service/GetFriendRequests.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { }, success:function(datareq) { $.ajax( { url: "/service/GetFriends.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { start: obj.start, num: 15, account_id: obj.userInfo.b4b_id }, success:function(datafr) { unblockWindow(); obj.built = true; if (obj.start == 0) { obj.domObj.find("#prevfriendpage").css('visibility', 'hidden'); } else { obj.domObj.find("#prevfriendpage").css('visibility', 'visible'); } if (datafr.hasmore) { obj.domObj.find("#nextfriendpage").css('visibility', 'visible'); } else { obj.domObj.find("#nextfriendpage").css('visibility', 'hidden'); } var str = ''; var profilepicurl = '/images/feedpics/nopic.png'; for (var i = 0; i < datafr.results.length; i++) { str += '' + (obj.isOwn ? 'X' : '') + '' + htmlencode(datafr.results[i].firstname + ' ' + datafr.results[i].lastname) + '
    ' + (parseInt(datafr.results[i].stepcnt) > 0 ? 'Steps: ' + datafr.results[i].stepcnt + '' : '') + (datafr.results[i].weightlost > 0 ? 'Lost: ' + datafr.results[i].weightlost + ' lbs' : '' ) + '
    '; } //console.log(str); obj.domObj.find("#numfriends").html(datafr.total); obj.domObj.find("#friendlist").html(str); var str = ''; for (var i = 0; i < datareq.length; i++) { var profilepicurl = '/images/feedpics/nopic.png'; var sendfriendstr = '
    Reject Approve
    '; str += '
    ' + sendfriendstr + '' + htmlencode(datareq[i].firstname + ' ' + datareq[i].lastname) + '
    '; } if (datareq.length > 0) { obj.domObj.find("#friendrequests").html(str); obj.domObj.find(".friendapprovedeny").on('click', '.rejectfriend', function(e) { e.preventDefault(); var friendid = $(e.target).parent().attr('friendid'); obj.rejectOrApproveFriend(1, friendid); }).on('click', '.approvefriend', function(e) { e.preventDefault(); var friendid = $(e.target).parent().attr('friendid'); obj.rejectOrApproveFriend(0, friendid); }); } else { obj.domObj.find("#friendrequests").html('

    No pending team requests.

    '); } obj.domObj.find(".sendmsgto").click(function(e) { if (! $(e.target).hasClass("unfriend")) { e.preventDefault(); userClicked($(this).attr('username')); } }); } }); } }); } Friends.prototype.build = function(mode, submode) { var obj = this; var str = ''; //str+='
    '; obj.isOwn = false; if (submode) { obj.start = parseInt(submode); } obj.username = (g_userInfo.username || g_userInfo.b4b_id); obj.username_text = 'your'; if (mode && (String(mode).toLowerCase() != g_userInfo.b4b_id && String(mode).toLowerCase() != g_userInfo.username)) { obj.username = mode; str += '
    \
    < Back to profile


    \
    \
    \ Team (0)
    \
    \
    \
    \
    '; } else { obj.isOwn = true; str += '
    \
    < Back to profile


    \
    \
    \ Team Requests
    \
    \

    No pending team requests.

    \
    \
    \
    \
    \ Team (0)
    \
    \
    \
    \
    '; } this.domObj = $(str); obj.domObj.find(".backtoprofile").click(function(e) { e.preventDefault(); setWindow("Profile-" + obj.username); }); this.getUserInfo(function() { obj.update(); }); this.domObj.find("#prevfriendpage").click(function(e) { e.preventDefault(); obj.start--; setWindow("Friends-" + obj.username + "-" + obj.start); obj.update(); }); this.domObj.find("#nextfriendpage").click(function(e) { e.preventDefault(); obj.start++; setWindow("Friends-" + obj.username + "-" + obj.start); obj.update(); }); this.domObj.on("click", ".unfriend", function(e) { e.preventDefault(); if (confirm("Are you sure want remove this teammate?")) { $.ajax( { url: "/service/RemoveFriend.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { friend_id: $(this).attr('friendid') }, success:function(datareq) { obj.update(); } }); } }); return false; } Friends.prototype.getDomObj=function() { return this.domObj; } Friends.prototype.setMode=function(mode) { } Friends.prototype.setHooks=function() { var obj = this; } Friends.prototype.destroy=function() { $(window).unbind('scroll', this.updateScroll); this.destroyed = true; } Friends.prototype.isBuilt=function() { return this.built; } Friends.prototype.contentSet=function(){ var obj = this; } function Search(params) { this.loginRequired = false; this.destroyed = false; this.built = false; this.usersearch = new Widget('UserSearch'); this.autoSearch = params.autoSearch || ''; } Search.prototype.build = function(mode) { var obj = this; var str = ''; // str+='

    < Back

    \
    \
    \
    \ \
    \
    \
    '; this.domObj = $(str); this.usersearch.render(this.domObj.find("#results")); if (this.autoSearch != '') { obj.domObj.find(obj.domObj.find("#searchinput").val(obj.autoSearch)); $("input").blur(); obj.usersearch.widget.search(obj.domObj.find("#searchinput").val(), 'all'); } this.domObj.find("#back").click(function(e) { e.preventDefault(); window.history.back(); }); return true; } Search.prototype.getDomObj=function() { return this.domObj; } Search.prototype.setMode=function(mode) { var obj = this; } Search.prototype.setHooks=function() { var obj = this; this.domObj.find("#submit-form").submit(function(e) { e.preventDefault(); $("input").blur(); obj.usersearch.widget.search(obj.domObj.find("#searchinput").val(), 'all'); }); } Search.prototype.destroy=function() { $(window).unbind('scroll', this.updateScroll); this.destroyed = true; } Search.prototype.isBuilt=function() { return this.built; } Search.prototype.contentSet=function(){ var obj = this; } function Messages(params) { this.loginRequired = true; this.destroyed = false; this.built = false; this.username = params.username || ''; this.start = 0; } Messages.prototype.updateConversation=function(msgid) { var obj = this; $.ajax( { url: "/service/GetMessages.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { msgid: msgid }, success:function(datamsg) { var str = ''; for (var i = 0; i < datamsg.results.length; i++) { var uinfo = datamsg.results[i].to_info; if (datamsg.results[i].from_id != g_userInfo.b4b_id) { uinfo = datamsg.results[i].from_info; } //str = '
    '; var str = ''; var to = ''; if (datamsg.results[i].from_id != g_userInfo.b4b_id) { to = '' + htmlencode(uinfo.firstname) + ': '; } else if (false && datamsg.results[i].to_id != g_userInfo.b4b_id) { to = '' + htmlencode(datamsg.results[i].to_info.firstname) + ': '; } else { to = 'Me: '; } str += '
    ' + to + '' + nl2br(htmlencode( datamsg.results[i].msg)) + '
    '; for (var j = 0; j < datamsg.results[i].conversation.length; j++) { var to = ''; if (datamsg.results[i].conversation[j].from_id != g_userInfo.b4b_id) { to = '' + htmlencode(uinfo.firstname) + ': '; } else if (false && datamsg.results[i].conversation[j].to_id != g_userInfo.b4b_id) { to = '' + htmlencode(datamsg.results[i].to_info.firstname) + ': '; } else { to = 'Me: '; } str += '
    ' + to + '' + nl2br(htmlencode( datamsg.results[i].conversation[j].msg)) + '
    '; } obj.domObj.find(".convo[msgid=" + datamsg.results[i].msg_id + "]").html(str); //str += '
    '; } obj.domObj.find(".convo").each(function() { this.scrollTop = this.scrollHeight; }); } }); } Messages.prototype.updateConversations=function() { var obj = this; obj.domObj.find(".convo").each(function() { var msgid = $(this).attr('msgid'); obj.updateConversation(msgid); }); } Messages.prototype.update = function() { blockWindow(); var obj = this; $.ajax( { url: "/service/GetMessages.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { start: obj.start, num: 15 }, success:function(datamsg) { unblockWindow(); obj.built = true; if (obj.start == 0) { obj.domObj.find("#prevfriendpage").css('visibility', 'hidden'); } else { obj.domObj.find("#prevfriendpage").css('visibility', 'visible'); } if (datamsg.hasmore) { obj.domObj.find("#nextfriendpage").css('visibility', 'visible'); } else { obj.domObj.find("#nextfriendpage").css('visibility', 'hidden'); } obj.domObj.find("#nummessages").text(datamsg.total); obj.domObj.find("#friendlist").html(str); var str = ''; for (var i = 0; i < datamsg.results.length; i++) { var sendfriendstr = '';//
    Reply
    '; str += '
    ' + sendfriendstr ; var uinfo = datamsg.results[i].to_info; if (datamsg.results[i].from_id != g_userInfo.b4b_id) { uinfo = datamsg.results[i].from_info; } var profilepicurl = '/images/feedpics/nopic.png'; str += '
    ' + uinfo.firstname + ' ' + uinfo.lastname + '
    '; //str += '
    '; str += '
    '; var to = ''; if (datamsg.results[i].from_id != g_userInfo.b4b_id) { to = '' + htmlencode(uinfo.firstname) + ': '; } else if (false && datamsg.results[i].to_id != g_userInfo.b4b_id) { to = '' + htmlencode(datamsg.results[i].to_info.firstname) + ': '; } else { to = 'Me: '; } str += '
    ' + to + '' + nl2br(htmlencode( datamsg.results[i].msg)) + '
    '; for (var j = 0; j < datamsg.results[i].conversation.length; j++) { var to = ''; if (datamsg.results[i].conversation[j].from_id != g_userInfo.b4b_id) { to = '' + htmlencode(uinfo.firstname) + ': '; } else if (false && datamsg.results[i].conversation[j].to_id != g_userInfo.b4b_id) { to = '' + htmlencode(datamsg.results[i].to_info.firstname) + ': '; } else { to = 'Me: '; } str += '
    ' + to + '' + nl2br(htmlencode( datamsg.results[i].conversation[j].msg)) + '
    '; } str += '
    '; str += '
    \
    '; str += '
    '; } if (datamsg.results.length > 0) { obj.domObj.find("#msglist").html(str); } else { obj.domObj.find("#msglist").html('

    No messages.

    '); } $("html, body").animate({ scrollTop: 0 }, "slow"); obj.domObj.find(".sendreplymsg").click(function(e) { e.preventDefault(); var reply_to_id = $(this).attr('replymsgid'); var msgtxt = obj.domObj.find('.replytxt[replymsgid="' + reply_to_id + '"]').val(); var toid = $(this).attr('toid'); if (msgtxt.trim() != '') { blockWindow(); $.ajax( { url: "/service/SendMessage.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { to_id: toid, msgtxt: msgtxt, reply_to_id: reply_to_id }, success: function() { unblockWindow(); obj.start = 0; obj.domObj.find('.replytxt[replymsgid="' + reply_to_id + '"]').val(''); obj.updateConversations(); } }); } }); obj.domObj.find(".convo").each(function() { //alert(this.scrollHeight); this.scrollTop = this.scrollHeight; }); } }); } Messages.prototype.build = function(mode) { var obj = this; var str = ''; //str+='
    '; str += '
    \
    \
    \ Conversations (0)
    \
    \

    No messages.

    \
    \
    \
    \ \ '; this.domObj = $(str); this.domObj.find("#sendmsg").click(function(e) { e.preventDefault(); blockWindow(); $.ajax( { url: "/service/SendMessage.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { username: obj.username, msgtxt: obj.domObj.find("#msgtxt").val() }, success: function(datasend) { unblockWindow(); if (! datasend) { alert("Unable to send message!"); return; } obj.update(); } }); }); this.domObj.find("#prevfriendpage").click(function(e) { e.preventDefault(); obj.start--; obj.update(); }); this.domObj.find("#nextfriendpage").click(function(e) { e.preventDefault(); obj.start++; obj.update(); }); this.update(); obj.domObj.on('click', '.sendmsgto', function(e) { e.preventDefault(); userClicked($(this).attr('username')); }); return false; } Messages.prototype.getDomObj=function() { return this.domObj; } Messages.prototype.setMode=function(mode) { } Messages.prototype.setHooks=function() { var obj = this; if (obj.username != '') { blockWindow(); $.ajax( { url: "/service/UserSearch.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { searchfor: obj.username, type: 'username', start: '0', end: '1' }, success: function( data ) { unblockWindow(); if (data && data.results.length > 0) { obj.userInfo = data.results[0]; obj.domObj.find("#newconvo").show(); obj.domObj.find("#whom").text(obj.userInfo.firstname + ' ' + obj.userInfo.lastname); obj.domObj.find("#msgtxt").focus(); var offset = obj.domObj.find("#newmsg").offset(); // Contains .top and .left offset.left -= 20; offset.top -= 20; $('html, body').animate({ scrollTop: offset.top, scrollLeft: offset.left }); //obj.domObj.find("#newmsg").get(0).scrollIntoView(true); } } }); } } Messages.prototype.destroy=function() { $(window).unbind('scroll', this.updateScroll); this.destroyed = true; } Messages.prototype.isBuilt=function() { return this.built; } Messages.prototype.contentSet=function(){ var obj = this; obj.domObj.find(".convo").each(function() { //alert(this.scrollHeight); this.scrollTop = this.scrollHeight; }); } function Profile(params) { this.loginRequired = false; this.destroyed = false; this.built = false; var obj = this; this.updateScroll = function () { $(window).triggerHandler('resize'); obj.scroll(); } this.viewed = []; this.domObj = null; this.ajaxRunning = false; this.userInfo = {}; this.gotComments = []; this.pendingComments = []; this.updatingComments = []; this.updatingLikes = []; this.topmostFeedId = 0; this.gotInitFeed = false; //$(window).bind('scroll', scrollMaps); document.addEventListener('scroll', scrollMaps, {passive: true}); } function isScrolledIntoView(elem) { var $elem = $(elem); var $window = $(window); var docViewTop = $window.scrollTop(); var docViewBottom = docViewTop + $window.height(); var elemTop = $elem.offset().top; var elemBottom = elemTop + $elem.height(); return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); } Profile.prototype.repositionBars = function (feedright) { var obj = this; //var feedright = $(".feedright"); if (!$(".feedmain").length) return; var h = feedright.css('position') == 'static' ? feedright.parent().height() : feedright.height(); var o = $(".feedmain").offset().top; var fh = $(".feedmain").height(); var wh = window.innerHeight; var st = $(window).scrollTop(); var pos; if (fh + o < h) { feedright.css({ 'position': 'static' }); return; } if (h > wh && st > o + (h - wh)) { pos = (wh - h); pos -= Math.max((st + wh - $("#footer").offset().top), 0); console.log('pos = ' + pos); feedright.css({ 'position': 'fixed', 'top': (pos) + 'px', 'width': feedright.parent().width() + 'px' }); } else if (h < wh && st > o) { pos = 0; pos -= Math.max((st + wh - $("#footer").offset().top), 0); console.log('pos = ' + pos); feedright.css({ 'position': 'fixed', 'top': (pos) + 'px', 'width': feedright.parent().width() + 'px' }); } else { feedright.css({ 'position': 'static' }); } } Profile.prototype.scroll = function () { var obj = this; /*if (obj.posTimer) { clearTimeout(obj.posTimer); obj.posTimer = null; }*/ //if (!obj.posTimer) { // obj.posTimer = setTimeout(function() { // obj.posTimer = null; if (window.innerWidth > 600) { obj.repositionBars($(".feedright>div")); obj.repositionBars($(".feedleft>div")); } var last = $('.feeditem:not(.status):last'); var first = $('.feeditem:not(.status):first'); if (last.length > 0 && $(window).scrollTop() + $(window).height() >= $(document).height() - 50) { obj.updateProfile(0, last.attr('feedid'), 1); } //if (first.length > 0 && $(window).scrollTop() <= first.offset().top) { /*if (obj.posted == true) { obj.posted = false; this.updateProfile(1, this.topmostFeedId, 1); }*/ //} //}, 80); /*if (window.innerWidth > 600) { obj.repositionBars($(".feedright>div")); obj.repositionBars($(".feedleft>div")); }*/ //} //if (!obj.posTimer) { /*obj.posTimer = setTimeout(function() { obj.repositionBars($(".feedright")); obj.repositionBars($(".feedleft")); }, 100);*/ //obj.repositionBars($(".feedright>div")); // obj.repositionBars($(".feedleft>div")); //} /*if (obj.gotInitFeed) { $('.feeditem').each(function() { if (obj.viewed.indexOf(this) == -1) { if (isScrolledIntoView(this)) { var el = this; $.ajax( { url: "/service/ViewedItem.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: $(this).attr('feedid') }, success: function( data ) { obj.viewed.push(el); obj.scroll(); } }); } } }); }*/ } //30 40 100 Profile.prototype.resize = function () { var obj = this; if (!obj.domObj) { return false; } if (obj.last_win_size == window.innerWidth) return; obj.last_win_size = window.innerWidth; this.domObj.find("#scroll_friends").width(50); this.domObj.find("#scroll_friends").width(this.domObj.find("#scroll_friends").parent().width() - 10); if (window.innerWidth >= 1200) { obj.domObj.find("#mobile_friends").hide(); } else if (obj.privs.team) { obj.domObj.find("#mobile_friends").show(); } } Profile.prototype.getCommentStr = function (data, feedid) { var obj = this; return getCommentStr(obj, data, feedid); } Profile.prototype.getComments = function (feedid, reply_to_id) { var obj = this; return getComments(obj, feedid, reply_to_id); } Profile.prototype.getPreviousComments = function (feedid, before, reply_comment_id) { var obj = this; return getPreviousComments(obj, feedid, before, reply_comment_id); } Profile.prototype.getPendingComments = function () { var obj = this; return getPendingComments(obj); } Profile.prototype.getHighestComment = function (feedid) { var obj = this; return getHighestComment(obj, feedid); } Profile.prototype.startUpdatingComments = function () { var obj = this; return startUpdatingComments(obj); } Profile.prototype.startGettingComments = function () { var obj = this; return startGettingComments(obj); } Profile.prototype.startUpdatingCommentsAll = function (notimer) { var obj = this; return startUpdatingCommentsAll(obj, notimer); } Profile.prototype.startUpdatingLikesAll = function (notimer) { var obj = this; return startUpdatingLikesAll(obj, notimer); } Profile.prototype.getStepCount = function () { var obj = this; $.ajax({ url: "/service/GetUserStepCount.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", retryCnt: -1, data: { b4b_id: obj.userInfo.b4b_id }, success: function (data) { if (!obj.destroyed) { var steps = data.stepcnt || 0; var dist = parseFloat(data.dist).toFixed(2); var weightlost = data.weightlost; $(".STEPS").html('' + parseInt(steps).toLocaleString() + ' / ' + dist + "mi"); if (weightlost > 0) { $("#weightlost").html("Lost: " + weightlost + " lbs"); } setTimeout(function () { obj.getStepCount(); }, STEPCOUNT_UPDATE_TIME); } } }); } Profile.prototype.updateProfile = function (top, feed_id, viewed) { var obj = this; if (this.ajaxRunning) { return; } if (typeof(obj.userInfo.b4b_id) == 'undefined') { return; } this.ajaxRunning = true; $.ajax({ url: "/service/GetFeed.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", retryCnt: -1, data: { top: top, feed_id: feed_id, viewed: viewed, account_id: obj.userInfo.b4b_id }, success: function (data) { if (!obj.gotInitFeed) { obj.gotInitFeed = true; //obj.startGettingComments(); //obj.startUpdatingComments(); //obj.startUpdatingLikes(); obj.startUpdatingCommentsAll(); obj.startUpdatingLikesAll(); //obj.getStepCount(); } obj.ajaxRunning = false; obj.built = true; var profilepicurl = '/images/feedpics/nopic.png'; var pics = ['/images/feedpics/img1.jpg', '/images/feedpics/img2.png', '/images/feedpics/img3.jpg', '/images/feedpics/img1.jpg', '/images/feedpics/img2.png', '/images/feedpics/img3.jpg']; var str = ''; if (top && data.length > 0) { obj.posted = false; } for (var i = 0; i < data.length; i++) { if (top && i == 0) { obj.topmostFeedId = data[i].feed_id; } var numpics = data[i].fids.length; var pics = []; for (var j = 0; j < data[i].fids.length; j++) { pics.push("/service/GetFile.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode + "&pic=" + data[i].fids[j]); } if (obj.domObj.find('.feeditem[feedid="' + data[i].feed_id + '"]').length != 0) { continue; } str += getFeedString(data[i], numpics, pics); str += ''; } var dobj = $(str); dobj.find("img").unveil(); if (top) { obj.domObj.find("#feedupdates").prepend(dobj); } else { obj.domObj.find("#feedupdates").append(dobj); } if (shouldTriggerScroll()) $(window).triggerHandler("scroll"); updateMaps(); obj.updateTimes(); } }); return false; } Profile.prototype.updateInfo = function () { var obj = this; //obj.domObj.find("#usernameprofile").html('' + htmlencode(obj.userInfo.b4b_id) + ''); obj.domObj.find("#fullname").html('' + htmlencode(obj.userInfo.firstname + ' ' + obj.userInfo.lastname) + ''); obj.domObj.find(".profilepic").attr('src', '/service/GetProfilePic.php?account_id=' + obj.userInfo.b4b_id); obj.domObj.find(".profileheader").css("background-image", 'url(/service/GetHeaderPic.php?account_id=' + obj.userInfo.b4b_id + ')'); //alert(ucfirst(obj.userinfo.firstname) + '''); obj.domObj.find(".utext").html(ucfirst(obj.userInfo.firstname) + ''s'); obj.updateFriends(); obj.updateProfile(1, 0, 1); if (obj.privs.postpage) obj.domObj.find(".writeonwall").show(); obj.getStepCount(); $.ajax({ url: "/service/GetUserPlanInfo.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", retryCnt: -1, data: { b4b_id: obj.userInfo.b4b_id }, success: function (data) { if (data) { //alert(obj.domObj.find("#planname").length); obj.domObj.find(".userplanname").text(data.name); obj.domObj.find(".userplantypes").text(data.types); } else { obj.domObj.find(".userplaninfo").html('

    No plan chosen.

    '); obj.domObj.find(".userswitchplan").css("border", "2px solid #ff0000").text("Choose Plan"); } if (obj.userInfo.b4b_id == g_userInfo.b4b_id) { obj.domObj.find(".switchuserplan").show(); obj.domObj.find(".userswitchplan").click(function (e) { e.preventDefault(); blockWindow(); $.ajax({ url: "/service/SetPlanSessionData.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, success: function (data) { unblockWindow(); setWindow("ChangePlan"); } }); }); } } }); } Profile.prototype.getUserInfo = function () { var obj = this; if (g_userInfo.b4b_id == obj.username.toLowerCase()) { obj.userInfo = g_userInfo; obj.updateInfo(); obj.domObj.find("#displaystr").hide(); return; } $.ajax({ url: "/service/UserSearch.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { searchfor: obj.username, type: 'username', start: '0', end: '1' }, success: function (data) { if (data && data.results.length > 0) { obj.userInfo = data.results[0]; obj.updateInfo(); if (data.results[0].status == 2) { var str = "You and " + htmlencode(ucfirst(data.results[0].firstname) || ucfirst(data.results[0].username)) + ' are teammates. Send a message'; } else if (data.results[0].status == 1) { var str = 'Team request has been sent. Send a message'; } else { var str = "Do you know " + htmlencode(ucfirst(data.results[0].firstname) || ucfirst(data.results[0].username)) + '? Send a message or Add to your team'; } obj.domObj.find("#displaystr").html(str); } } }); } Profile.prototype.getStepsBox = function () { var obj = this; var str = ''; str += '
    \

    ' + ucfirst(obj.username_text) + ' Step Count:

    \
    \
    \

    \
    \
    '; return str; } Profile.prototype.build = function (mode) { var obj = this; //this.domObj = $('
    '); $.ajax({ url: "/service/GetPrivs.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { b4b_id: (mode || g_userInfo.b4b_id) }, success: function (data) { obj.privs = data; if (!data.page) { obj.domObj = $('

    This page is restricted by owner

    '); obj.built = true; } else { obj.postBuild(mode); //$(window).bind('scroll', obj.updateScroll); document.addEventListener('scroll', obj.updateScroll, {passive: true}); obj.built = true; } } }); return false; } Profile.prototype.postBuild = function (mode) { var obj = this; if (!g_userInfo.b4b_id) { obj.username = ""; } else { obj.username = g_userInfo.b4b_id; obj.username_text = 'your'; } if (mode && String(mode).toLowerCase() != obj.username.toLowerCase()) { obj.username = mode; obj.username_text = ''; //mode + ''s'; } $("#content").removeClass("page_width"); var str = ''; var profilepicurl = '/images/feedpics/nopic.png'; str += '
    \
    \ \ \
    \
    \
    \
    \
    \ \
    \ '; str += '
    '; str += '
    \

    ' + ucfirst(obj.username_text) + ' team:

    \
    \
    \
    '; /*str += '
    \

    Friends:

    \
    \ \ \












    \
    ';*/ str += '
    '; var clzLogout = ''; if (!isLoggedIn()) { clzLogout = ' loggedOut'; } str += '
    '; str += '
    \
    \

    ' + ucfirst(obj.username_text) + ' team:


    \
    \
    \
    \
    \
    \
    '; //console.log(obj.privs); str += this.getTotalsBox(); str += this.getStepsBox(); str += ''; str += '
    '; str += '
    '; str += this.getTotalsBox(); str += this.getStepsBox(); str += '
    '; this.domObj = $(str); this.domObj.find("#searchform").submit(function (e) { e.preventDefault(); var txt = obj.domObj.find("#searchinput").val().trim(); if (txt != '') { setWindow("Search", false, { autoSearch: txt }); } }); this.domObj.find("#searchform2").submit(function (e) { e.preventDefault(); var txt = obj.domObj.find("#searchinput2").val().trim(); if (txt != '') { setWindow("Search", false, { autoSearch: txt }); } }); obj.getUserInfo(); obj.domObj.on('click', 'a.discuss', function (e) { e.preventDefault(); setWindow("Discuss-" + $(this).attr('did')); }); obj.domObj.on('click', '.sendmsgto', function (e) { e.preventDefault(); e.stopPropagation(); userClicked($(this).attr('username')); }); obj.domObj.on('click', 'a.commentpost', function (e) { e.preventDefault(); if (!isLoggedIn()) { warnNotLoggedIn(); return; } var feedid = $(this).attr('feedid'); obj.domObj.find(".feeditem[feedid=" + feedid + "]").find(".leavecomment[reply_comment_id=0]").find("textarea").focus(); }); obj.domObj.on('click', 'a.friendreq', function (e) { e.preventDefault(); e.stopPropagation(); if (!isLoggedIn()) { warnNotLoggedIn(); return; } $.ajax({ url: "/service/SendFriendReq.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { 'friend_id': obj.userInfo.b4b_id }, success: function (data) { obj.getUserInfo(); } }); }); obj.domObj.on('click', 'a.writemsg', function (e) { e.preventDefault(); if (!isLoggedIn()) { warnNotLoggedIn(); return; } setWindow("Messages", null, { username: $(this).attr('username') }); }); obj.domObj.on('click', 'a.likepost', function (e) { e.preventDefault(); if (!isLoggedIn()) { warnNotLoggedIn(); return; } var feedid = $(this).attr('feedid'); var link = this; $.ajax({ url: "/service/LikePost.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: feedid }, success: function (data) { $(link).text("Liked"); obj.startUpdatingLikesAll(true); } }); }); obj.domObj.on('click', 'a.sharepost', function (e) { e.preventDefault(); if (!isLoggedIn()) { warnNotLoggedIn(); return; } var feedid = $(this).attr('feedid'); var link = this; $.ajax({ url: "/service/SharePost.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: feedid }, success: function (data) { $(link).text("Shared"); } }); }); obj.domObj.on('click', '.reply', function (e) { e.preventDefault(); if (!isLoggedIn()) { warnNotLoggedIn(); return; } var feed_id = $(this).attr('feed_id'); var reply_comment_id = $(this).attr('comment_id'); var comcon = obj.domObj.find(".comment_container[feed_id=" + feed_id + "][reply_comment_id=" + reply_comment_id + "]"); //alert(".comment_container[feed_id=" + $(this).attr('feed_id') + "][reply_comment_id=" + $(this).attr('reply_comment_id') + "]"); if (comcon.find(".leavecomment").length == 0) { var str = '
    \ \ \ \ Post Comment\ \
    \
    '; comcon.append(str); } }); obj.domObj.on('click', '.prevcomment', function (e) { e.preventDefault(); $(this).remove(); obj.getPreviousComments($(this).attr('feedid'), $(this).attr('reply_comment_id'), $(this).attr('parentid')); }); obj.domObj.on('click', '.postcomment', function (e) { e.preventDefault(); var reply_comment_id = $(this).attr('reply_comment_id'); var feed_id = $(this).attr('feed_id'); var commentbox = obj.domObj.find(".comment[feed_id=" + feed_id + "][reply_comment_id=" + reply_comment_id + "]"); if (commentbox.length == 0 || String(commentbox.val()).trim() == '') { return; } blockWindow(); $.ajax({ url: "/service/WriteComment.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: feed_id, reply_comment_id: reply_comment_id, msg: commentbox.val() }, success: function (data) { unblockWindow(); commentbox.val(''); obj.startUpdatingCommentsAll(true); } }); }); //obj.startGettingComments(); //obj.startUpdatingComments(); //obj.startUpdatingLikes(); return true; } Profile.prototype.startUpdatingLikes = function () { var obj = this; var found = false; obj.domObj.find(".feeditem").each(function () { var feedid = $(this).attr('feedid'); var feeditem = $(this); if (obj.updatingLikes.indexOf(feedid) == -1) { found = true; obj.updatingLikes.push(feedid); $.ajax({ url: "/service/GetNumLikes.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", retryCnt: -1, data: { feed_id: feedid }, success: function (data) { feeditem.find(".numlikes").text(likeText(data)); obj.startUpdatingLikes(); } }); return false; } }); if (found == false) { obj.updatingLikes = []; } else { return; } setTimeout(function () { if (!obj.destroyed) { obj.startUpdatingLikes(); } }, 1500); } Profile.prototype.updateFriends = function () { var obj = this; $.ajax({ url: "/service/GetFriends.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { account_id: obj.userInfo.b4b_id }, success: function (datafr) { if (!datafr) return; var str = ''; var str2 = ''; var profilepicurl = '/images/feedpics/nopic.png'; if (obj.userInfo.b4b_id == g_userInfo.b4b_id && datafr.results.length == 0) { str = '

    Search for friends

    '; obj.domObj.find("#frlisting").html(str); obj.domObj.find(".searchlnk").click(function (e) { e.preventDefault(); setWindow("Search"); }); } else { for (var i = 0; i < datafr.results.length; i++) { str += '' + htmlencode(datafr.results[i].firstname + ' ' + datafr.results[i].lastname) + '
    ' + (parseInt(datafr.results[i].stepcnt) > 0 ? 'Steps: ' + datafr.results[i].stepcnt + '' : '') + (datafr.results[i].weightlost > 0 ? 'Lost: ' + datafr.results[i].weightlost + ' lbs' : '') + '
    '; str2 += '
    ' + htmlencode(datafr.results[i].firstname + ' ' + datafr.results[i].lastname) + '
    ' + (parseInt(datafr.results[i].stepcnt) > 0 ? 'Steps: ' + datafr.results[i].stepcnt + '' : '') + (datafr.results[i].weightlost > 0 ? 'Lost: ' + datafr.results[i].weightlost + ' lbs' : '') + '
    '; } str += '

    See all

    '; var dobj = $(str); var dobj2 = $(str2); dobj2.find("img").unveil(); dobj.find("img").unveil(); obj.domObj.find("#frlisting").html(dobj); obj.domObj.find("#mfriends").html(dobj2); if (shouldTriggerScroll()) $(window).triggerHandler("scroll"); $(window).triggerHandler('resize'); obj.domObj.find("#seeallfriends").click(function (e) { e.preventDefault(); setWindow("Friends-" + obj.username); }); } } }); } Profile.prototype.getDomObj = function () { return this.domObj; } Profile.prototype.getTotalsBox = function () { var obj = this; var str = ''; str += '
    '; str += '

    ' + ucfirst(obj.username_text) + ' plan:

    '; str += '
    '; str += '
    '; str += '
      '; str += '
    • '; str += '
    • '; str += '
    '; str += '
    '; str += ''; str += '
    \
    '; return str; } Profile.prototype.setMode = function (mode) {} Profile.prototype.setHooks = function () { var obj = this; if (!obj.domObj) { return false; } this.domObj.find("#poststatus").click(function (e) { e.preventDefault(); if (String(obj.domObj.find("#statustext").val()).trim() == '') { return; } blockWindow(); var fids = []; obj.domObj.find(".postingimage").each(function () { fids.push($(this).attr('fid')); }); $.ajax({ url: "/service/PostStatus.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { msg: obj.domObj.find("#statustext").val(), postonwall: obj.userInfo.b4b_id, fids: fids.join(",") }, success: function (data) { obj.domObj.find("#statustext").val(''); obj.domObj.find(".postingimage").remove(); unblockWindow(); obj.posted = true; setTimeout(function () { var first = $('.feeditem:not(.status):first'); if (first.length > 0) { //console.log($('.feeditem:not(.status):first').attr('feedid')); obj.updateProfile(1, obj.topmostFeedId /*first.attr('feedid')*/, 1); } else { obj.updateProfile(1, 0, 0); } }, 10000); } }); }); obj.domObj.on('click', ".albums", function (e) { e.preventDefault(); e.stopPropagation(); if (obj.privs.pics) { setWindow("Albums-" + obj.username); } }); function resizeimages() { var numpics = obj.domObj.find("#imageblock").find(".postingimage").length; if (numpics == 1) { obj.domObj.find("#imageblock").find(".postingimage").css("width", "97%").css("height", "280px"); } else if (numpics == 2) { obj.domObj.find("#imageblock").find(".postingimage").css("width", "47%").css("height", "280px"); } else { obj.domObj.find("#imageblock").find(".postingimage").css("width", "30%").css("height", "140px"); } } this.domObj.on('click', '.removepic', function (e) { e.preventDefault(); var fid = $(this).attr('fid'); obj.domObj.find(".postingimage[fid='" + fid + "']").fadeOut('slow', function () { $(this).remove(); resizeimages(); }); }); this.domObj.find("#addpics").click(function (e) { e.preventDefault(); var goelem = this; var widget = new Widget("ImageUpload", { hidden: true, callback: function (fid) { //$('html, body').animate({ // scrollTop: ($(goelem).offset().top - 100) //}, 2000); if (fid) { var str = ''; if (fid.substr(0, 4) == 'vid_') { str += 'X\ \ '; } else { str += 'X'; } /*if (numpics == 1) { str += ''; } else if (numpics == 2) { str += ''; str += ''; } else { for (var j = 0; j < numpics; j++) { str += ''; } }*/ obj.domObj.find("#imageblock").append(str); resizeimages(); } } }); widget.renderIntoPopup('80%', '80%', $(this), function () {}); }); } Profile.prototype.destroy = function () { //$(window).unbind('scroll', this.updateScroll); //$(window).unbind('scroll', scrollMaps); document.removeEventListener('scroll', this.updateScroll); document.removeEventListener('scroll', scrollMaps); $("#content").addClass("page_width"); this.destroyed = true; } Profile.prototype.isBuilt = function () { return this.built; } Profile.prototype.updateTimes = function () { this.domObj.find(".feedtime").each(function () { var data = $(this).attr('data'); var t = data.split(/[- :]/); // Apply each element to the Date function var d = new Date(t[0], t[1] - 1, t[2], t[3], t[4], t[5]); $(this).text(timeSince(d)); }); } Profile.prototype.contentSet = function () { var obj = this; obj.last_win_size = 0; if (!obj.privs.page) { return; } var updateFunc = function () { if (!obj.destroyed) { var first = $('.feeditem:not(.status):first'); //obj.updateFriends(); if (obj.posted == true || obj.viewed.indexOf(first.get(0)) != -1) { //obj.posted = false; if (first.length > 0) { //console.log($('.feeditem:not(.status):first').attr('feedid')); obj.updateProfile(1, obj.topmostFeedId /*first.attr('feedid')*/, 1); } else { obj.updateProfile(1, 0, 0); } } setTimeout(updateFunc, FEED_UPDATE_TIME); } }; var friendsUpdateFunc = function () { if (!obj.destroyed) { obj.updateFriends(); setTimeout(friendsUpdateFunc, FRIENDS_UPDATE_TIME); } }; var updateTimeFunc = function () { obj.updateTimes(); if (!obj.destroyed) { setTimeout(updateTimeFunc, TIME_UPDATE_TIME); } }; setTimeout(updateFunc, FEED_UPDATE_TIME); setTimeout(updateTimeFunc, TIME_UPDATE_TIME); setTimeout(friendsUpdateFunc, FRIENDS_UPDATE_TIME); this.resize(); } function Albums(params) { this.loginRequired = false; this.destroyed = false; this.built = false; var obj = this; this.ajaxRunning = false; this.userInfo = {}; obj.start = 0; } Albums.prototype.resize=function() { } Albums.prototype.getUserAlbums=function() { var obj = this; var str = ''; if (obj.start == 0) { str += '\
    Default Album
    '; } blockWindow(); obj.domObj.find("#albumslist").empty().append($(str)); $.ajax( { url: "/service/GetUserAlbums.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { b4b_id: obj.userInfo.b4b_id, start: obj.start }, success: function( data ) { var str = ''; if (obj.start == 0) { obj.domObj.find(".prevpics").css('visibility', 'hidden'); } else { obj.domObj.find(".prevpics").css('visibility', 'visible'); } if (data.hasmore) { obj.domObj.find(".morepics").css('visibility', 'visible'); } else { obj.domObj.find(".morepics").css('visibility', 'hidden'); } if (data && data.results && data.results.length > 0) { for (var i = 0; i < data.results.length; i++) { str += '\
    ' + data.results[i].name + 'X
    '; } obj.domObj.find("#albumslist").append($(str)); } //if (String(g_userInfo.b4b_id).toLowerCase() != obj.username.toLowerCase()) { if (String(g_userInfo.b4b_id).toLowerCase() != obj.username.toLowerCase() && String(g_userInfo.username).toLowerCase() != obj.username.toLowerCase()) { obj.domObj.find(".deletealbum, .createalbum").hide(); } unblockWindow(); } }); } Albums.prototype.updateInfo=function() { var obj = this; obj.getUserAlbums(); obj.built = true; } Albums.prototype.getUserInfo=function() { var obj = this; if (g_userInfo.b4b_id == obj.username.toLowerCase()) { obj.userInfo = g_userInfo; obj.updateInfo(); return; } $.ajax( { url: "/service/UserSearch.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { searchfor: obj.username, type: 'username', start: '0', end: '1' }, success: function( data ) { if (data && data.results.length > 0) { obj.userInfo = data.results[0]; obj.updateInfo(); } } }); } Albums.prototype.build = function(mode) { var obj = this; if (isLoggedIn()) { obj.username = g_userInfo.b4b_id; obj.username_text = 'your'; if (mode && String(mode).toLowerCase() != obj.username.toLowerCase()) { obj.username = mode; obj.username_text = mode + ''s'; } } else { obj.username = mode || ''; } $("#content").removeClass("page_width"); var str = ''; var profilepicurl = '/images/feedpics/nopic.png'; str += '
    < Back to profile
    '; str += ''; str += '
    Create Album
    '; str += '
    '; this.domObj = $(str); obj.getUserInfo(); obj.domObj.on('click', '.viewalbum', function(e) { e.preventDefault(); var albumid = $(this).attr('albumid'); setWindow("Pictures-" + obj.username + "-" + albumid); }); obj.domObj.find(".backtoprofile").click(function(e) { e.preventDefault(); setWindow("Profile-" + obj.username); }); obj.domObj.find(".createalbum").click(function(e) { e.preventDefault(); var newname = prompt("Please enter a name for the new album"); if (newname) { $.ajax( { url: "/service/CreateAlbum.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { name: newname }, success: function( data ) { obj.getUserAlbums(); } }); } }); //if (mode && String(mode).toLowerCase() != obj.username.toLowerCase()) { if (String(g_userInfo.b4b_id).toLowerCase() != obj.username.toLowerCase() && String(g_userInfo.username).toLowerCase() != obj.username.toLowerCase()) { obj.domObj.find(".createalbum").hide(); } obj.domObj.find(".prevpics").click(function(e) { e.preventDefault(); obj.start--; obj.getUserAlbums(); }); obj.domObj.find(".morepics").click(function(e) { e.preventDefault(); obj.start++; obj.getUserAlbums(); }); obj.domObj.on('click', '.deletealbum', function(e) { e.preventDefault(); if (! confirm("Are you sure you want to delete this album and all its pictures?")) { return; } var albumid = $(this).attr('albumid'); $.ajax( { url: "/service/DeleteAlbum.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { album_id: albumid }, success: function( data ) { obj.getUserAlbums(); } }); }); return false; } Albums.prototype.getDomObj=function() { return this.domObj; } Albums.prototype.setMode=function(mode) { } Albums.prototype.setHooks=function() { var obj = this; } Albums.prototype.destroy=function() { $("#content").addClass("page_width"); this.destroyed = true; } Albums.prototype.isBuilt=function() { return this.built; } Albums.prototype.contentSet=function(){ var obj = this; } function Pictures(params) { this.loginRequired = false; this.destroyed = false; this.built = false; var obj = this; this.ajaxRunning = false; this.userInfo = {}; obj.start = 0; obj.album_id = 0; obj.albums = []; this.viewed = []; this.gotComments = []; this.pendingComments = []; this.updatingComments = []; this.updatingLikes = []; } Pictures.prototype.resize = function () {} Pictures.prototype.getAllAlbums = function () { var obj = this; $.ajax({ url: "/service/GetUserAlbums.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { b4b_id: obj.userInfo.b4b_id, start: 0 }, success: function (data) { if (data && data.results && data.results.length > 0) { var str = ''; for (var i = 0; i < data.results.length; i++) { str += ''; } obj.domObj.find(".picalbums").empty().html(str); } } }); } Pictures.prototype.getUserPictures = function () { var obj = this; blockWindow(); var str = ''; obj.domObj.find("#picslist").empty(); $.ajax({ url: "/service/GetAlbumPics.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { b4b_id: obj.userInfo.b4b_id, album_id: obj.album_id, start: obj.start }, success: function (data) { var str = ''; if (obj.start == 0) { obj.domObj.find(".prevpics").css('visibility', 'hidden'); } else { obj.domObj.find(".prevpics").css('visibility', 'visible'); } if (data.hasmore) { obj.domObj.find(".morepics").css('visibility', 'visible'); } else { obj.domObj.find(".morepics").css('visibility', 'hidden'); } if (data && data.results && data.results.length > 0) { for (var i = 0; i < data.results.length; i++) { if (data.results[i].pic_id.substr(0, 4) == 'vid_') { var imageStr = ''; } else { var imageStr = ''; } str += '' + imageStr + '\
    ' + data.results[i].created + '
    \


    Go
    \
    '; str += '\
    \
    ' + likeText(data.results[i].numLikes) + '
    '; /*for (var j = 0; j < numcomments; j++) { str += '
    \ \ \ \
    2hrs Like Reply
    \
    \
    '; }*/ str += '
    '; str += '
    \ \ \ \ Post Comment\ \
    \
    '; str += '
    '; } obj.domObj.find("#picslist").append($(str)); } if (String(g_userInfo.b4b_id).toLowerCase() != obj.username.toLowerCase() && String(g_userInfo.username).toLowerCase() != obj.username.toLowerCase()) { obj.domObj.find(".picactions, .createpic").hide(); } obj.getAllAlbums(); unblockWindow(); } }); } Pictures.prototype.updateTimes = function () { this.domObj.find(".feedtime").each(function () { var data = $(this).attr('data'); var t = data.split(/[- :]/); // Apply each element to the Date function var d = new Date(t[0], t[1] - 1, t[2], t[3], t[4], t[5]); $(this).text(timeSince(d)); }); } Pictures.prototype.getCommentStr = function (data, feedid) { var obj = this; return getCommentStr(obj, data, feedid); } Pictures.prototype.getPreviousComments = function (feedid, before, reply_comment_id) { var obj = this; return getPreviousComments(obj, feedid, before, reply_comment_id); } Pictures.prototype.getComments = function (feedid, reply_to_id) { var obj = this; return getComments(obj, feedid, reply_to_id); } Pictures.prototype.getPendingComments = function () { var obj = this; return getPendingComments(obj); } Pictures.prototype.getHighestComment = function (feedid) { var obj = this; return getHighestComment(obj, feedid); } Pictures.prototype.startUpdatingComments = function () { var obj = this; return startUpdatingComments(obj); } Pictures.prototype.startGettingComments = function () { var obj = this; return startGettingComments(obj); } Pictures.prototype.startUpdatingCommentsAll = function () { var obj = this; return startUpdatingCommentsAll(obj); } Pictures.prototype.startUpdatingLikesAll = function () { var obj = this; return startUpdatingLikesAll(obj); } Pictures.prototype.updateInfo = function () { var obj = this; obj.getUserPictures(); obj.built = true; //obj.startGettingComments(); //obj.startUpdatingComments(); //obj.startUpdatingLikes(); obj.startUpdatingCommentsAll(); obj.startUpdatingLikesAll(); } Pictures.prototype.getUserInfo = function () { var obj = this; if (g_userInfo.b4b_id == obj.username.toLowerCase()) { obj.userInfo = g_userInfo; obj.updateInfo(); return; } $.ajax({ url: "/service/UserSearch.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { searchfor: obj.username, type: 'username', start: '0', end: '1' }, success: function (data) { if (data && data.results.length > 0) { obj.userInfo = data.results[0]; obj.updateInfo(); } } }); } Pictures.prototype.build = function (mode, submode) { var obj = this; var clzLoggedOut = ''; if (isLoggedIn()) { obj.username = g_userInfo.b4b_id; obj.username_text = 'your'; if (mode && String(mode).toLowerCase() != obj.username.toLowerCase()) { obj.username = mode; obj.username_text = mode + ''s'; } } else { clzLoggedOut = ' loggedOut'; obj.username = mode || ''; } obj.album_id = submode; $("#content").removeClass("page_width"); var str = ''; var profilepicurl = '/images/feedpics/nopic.png'; str += '
    < Back to albums
    '; str += ''; str += '
    Upload Picture
    '; str += '
    '; this.domObj = $(str); obj.getUserInfo(); obj.domObj.on('click', '.viewalbum', function (e) { e.preventDefault(); var albumid = $(this).attr('albumid'); setWindow("Pictures-" + obj.username + "-" + albumid); }); obj.domObj.on('click', '.deletepic', function (e) { e.preventDefault(); if (!confirm("Are you sure you want to delete this picture?")) { return; } var picid = $(this).attr('picid'); $.ajax({ url: "/service/DeleteAlbumPic.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { pic: picid }, success: function (data) { obj.getUserPictures(); } }); }); obj.domObj.on('change', ".picaction", function (e) { if ($(this).val() == '3') { $(this).parent().find(".picalbums").show(); } else { $(this).parent().find(".picalbums").hide(); } }); obj.domObj.on('click', '.dopicaction', function (e) { e.preventDefault(); var picid = $(this).attr('picid'); var action = $(this).parent().find(".picaction").val(); if (action == '') { alert("Please select an action!"); return; } if (action == '4') { if (!confirm("Are you sure you want to delete this picture?")) { return; } $.ajax({ url: "/service/DeleteAlbumPic.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { pic: picid }, success: function (data) { obj.getUserPictures(); } }); } else if (action == '3') { var albumid = $(this).parent().find(".picalbums").val(); if (!albumid) { alert("Please select an album!"); return; } blockWindow(); $.ajax({ url: "/service/MovePic.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { pic: picid, album_id: albumid }, success: function (data) { obj.getUserPictures(); unblockWindow(); } }); } else if (action == '1') { // profile $.ajax({ url: "/service/SetPic.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { pic: picid, imgtype: 'PROFILE' }, success: function (data) { alert("Success"); } }); } else if (action == '2') { // header $.ajax({ url: "/service/SetPic.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { pic: picid, imgtype: 'HEADER' }, success: function (data) { alert("Success"); } }); } //picaction }); obj.domObj.find(".backtoalbums").click(function (e) { e.preventDefault(); setWindow("Albums-" + obj.username); }); obj.domObj.find(".prevpics").click(function (e) { e.preventDefault(); obj.start--; obj.getUserPictures(); }); obj.domObj.find(".morepics").click(function (e) { e.preventDefault(); obj.start++; obj.getUserPictures(); }); obj.domObj.find(".createpic").click(function (e) { e.preventDefault(); var widget = new Widget("ImageUpload", { album_id: obj.album_id, callback: function () { obj.getUserPictures(); } }); widget.renderIntoPopup('80%', '80%', $(this)); }); obj.domObj.on('click', '.viewpic', function (e) { e.preventDefault(); var picid = $(this).attr('picid'); var widget = new Widget("ViewPic", { pic: picid }); widget.renderIntoPopup('95%', '95%', $(this)); }); obj.domObj.on('click', 'a.commentpost', function (e) { e.preventDefault(); if (!isLoggedIn()) { warnNotLoggedIn(); return; } var feedid = $(this).attr('feedid'); obj.domObj.find(".feeditem[feedid=" + feedid + "]").find(".leavecomment[reply_comment_id=0]").find("textarea").focus(); }); obj.domObj.on('click', 'a.likepost', function (e) { e.preventDefault(); if (!isLoggedIn()) { warnNotLoggedIn(); return; } var feedid = $(this).attr('feedid'); var link = this; $.ajax({ url: "/service/LikePost.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: feedid }, success: function (data) { $(link).text("Liked"); } }); }); obj.domObj.on('click', 'a.sharepost', function (e) { e.preventDefault(); if (!isLoggedIn()) { warnNotLoggedIn(); return; } var feedid = $(this).attr('feedid'); var link = this; $.ajax({ url: "/service/SharePost.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: feedid }, success: function (data) { $(link).text("Shared"); } }); }); obj.domObj.on('click', '.reply', function (e) { e.preventDefault(); var feed_id = $(this).attr('feed_id'); var reply_comment_id = $(this).attr('comment_id'); var comcon = obj.domObj.find(".comment_container[feed_id=" + feed_id + "][reply_comment_id=" + reply_comment_id + "]"); //alert(".comment_container[feed_id=" + $(this).attr('feed_id') + "][reply_comment_id=" + $(this).attr('reply_comment_id') + "]"); if (comcon.find(".leavecomment").length == 0) { var str = '
    \ \ \ \ Post Comment\ \
    \ '; comcon.append(str); } }); //this.updateFriends(); obj.domObj.on('click', '.prevcomment', function (e) { e.preventDefault(); $(this).remove(); obj.getPreviousComments($(this).attr('feedid'), $(this).attr('reply_comment_id'), $(this).attr('parentid')); }); obj.domObj.on('click', '.postcomment', function (e) { e.preventDefault(); var reply_comment_id = $(this).attr('reply_comment_id'); var feed_id = $(this).attr('feed_id'); var commentbox = obj.domObj.find(".comment[feed_id=" + feed_id + "][reply_comment_id=" + reply_comment_id + "]"); if (commentbox.length == 0 || String(commentbox.val()).trim() == '') { return; } blockWindow(); $.ajax({ url: "/service/WriteComment.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { feed_id: feed_id, reply_comment_id: reply_comment_id, msg: commentbox.val() }, success: function (data) { unblockWindow(); commentbox.val(''); } }); }); return false; } Pictures.prototype.getDomObj = function () { return this.domObj; } Pictures.prototype.setMode = function (mode) {} Pictures.prototype.setHooks = function () { var obj = this; } Pictures.prototype.destroy = function () { $("#content").addClass("page_width"); this.destroyed = true; } Pictures.prototype.isBuilt = function () { return this.built; } Pictures.prototype.contentSet = function () { var obj = this; var updateTimeFunc = function () { obj.updateTimes(); if (!obj.destroyed) { setTimeout(updateTimeFunc, TIME_UPDATE_TIME); } }; setTimeout(updateTimeFunc, TIME_UPDATE_TIME); } function Outline(params) { this.built = false; this.events = []; this.createdCalendar = false; params = params || {}; this.type = params.type || {}; this.currEid = 0; this.timer = -1; this.destroyed = false; } Outline.prototype.getWeekScheduledExercises=function() { var obj = this; obj.domObj.find(".scheduled").removeClass("scheduled"); $.ajax( { url: "/service/GetWeekScheduledExercises.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { type: obj.type, restrict: (obj.domObj.find("#restrict:checked").length > 0 ? 'true': 'false') }, success: function( data ) { if (data) { for (var i = 0; i < data.length; i++) { obj.domObj.find('.exercise[eid="' + data[i].exercise_id + '"]').addClass("scheduled"); } } } }); } Outline.prototype.getExercises=function() { var obj = this; blockWindow(); $.ajax( { url: "/service/GetPlanExercise.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { type: obj.type, restrict: (obj.domObj.find("#restrict:checked").length > 0 ? 'true': 'false') }, success: function( data ) { //obj.exerciseTypes = data.data.exerciseTypes; //obj.exercises = data.data.exercises; unblockWindow(); var html = '
    '; var lastcat = -1; for (var i = 0; i < data.length; i++) { if (lastcat != data[i].catid) { html += '

    ' + data[i].catname + '

    '; } var boldstart = ''; var boldend = ''; if (data[i].fid && data[i].fid != '0') { boldstart = ''; boldend = ''; } var italicstart = ''; var italicend = ''; if (! data[i].description || data[i].description == 'null') { italicstart = ''; italicend = ''; } html += '
    ' + boldstart + italicstart + data[i].name + italicend + boldend + '
    '; lastcat = data[i].catid; } //for (var type in obj.exerciseTypes) { /*var type = 'anaerobic'; //html += ''; //html += '
      ' + obj.exerciseTypes[type].name + ' 
    '; for (var grp in obj.exerciseTypes[type].groups) { var edit_str = ''; if (! obj.exerciseTypes[type].groups[grp].system) { //edit_str = 'X'; } html += '

    ' + obj.exerciseTypes[type].groups[grp].name + '

    '; //html += '
    '; for (var id in obj.exerciseTypes[type].groups[grp].types) { //html += ''; var edit_str = ''; if (String(id).substr(0, 1) == 'd') { //edit_str = '' } html += '
    ' + obj.exercises[id].name + '
    '; } //html += '
    '; //html += '

    '; }*/ html += '
    '; //html += '
    Add Custom Exercise
    '; html+= '
    '; //} obj.domObj.find("#exerciseindex").html(html); if ($.contains(document, obj.domObj.find("#exerciseindex>div>div.column")[0])) { obj.domObj.find("#exerciseindex>div>div.column").columnize({width:200}); } //$('#mydiv'); obj.built = true; obj.getWeekScheduledExercises(); } }); } Outline.prototype.createCalendar=function() { var obj = this; var dragstart = 0; if (! obj.createdCalendar) { obj.domObj.find(".excalendar").fullCalendar({header: { left: 'prev,next today', center: 'title', right: '' /*right: 'month,agendaWeek,agendaDay'*/ }, columnFormat: 'ddd\nM/D', views: { agendaWeek: { // name of view titleRangeSeparator: ' - ' // other view-specific options here } }, viewRender:function( view, element ) { //alert("dayrender"); var start = view.start; var end = view.end; obj.events[obj.currId] = []; blockWindow(); $.ajax( { url: "/service/GetExerciseSchedule.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { exercise_id: obj.currId, start: String(start), end: String(end) }, success: function( data ) { //unblockWindow(); obj.events[obj.currId] = data; if (typeof(obj.events[obj.currId]) == 'undefined') { obj.events[obj.currId] = []; } obj.domObj.find(".excalendar").fullCalendar('removeEvents', function(evt) { return true; }); for (var i = 0; i < obj.events[obj.currId].length; i++) { var t = obj.events[obj.currId][i].start.split(/[- :]/); var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]); obj.events[obj.currId][i].start = d; var t = obj.events[obj.currId][i].end.split(/[- :]/); var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]); obj.events[obj.currId][i].end = d; obj.domObj.find(".excalendar").fullCalendar('renderEvent', obj.events[obj.currId][i], true); } unblockWindow(); } }); }, selectable: true, selectHelper: true, eventDragStart: function( event, jsEvent, ui, view ) { dragstart = event.start; }, eventDrop: function( event, delta, revertFunc, jsEvent, ui, view ) { blockWindow(); $.ajax( { url: "/service/RemoveExerciseSchedule.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { exercise_id: obj.currId, start: String(dragstart) }, success: function( data ) { $.ajax( { url: "/service/AddExerciseSchedule.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { exercise_id: obj.currId, start: String(event.start), end: String(event.end) }, success: function( data ) { unblockWindow(); } }); } }); }, eventResize: function ( event, delta, revertFunc, jsEvent, ui, view) { blockWindow(); $.ajax( { url: "/service/AddExerciseSchedule.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { exercise_id: obj.currId, start: String(event.start), end: String(event.end) }, success: function( data ) { unblockWindow(); } }); }, select: function(start, end) { var eventData; var title = obj.currEx; //if (title) { eventData = { title: title, start: start, end: end }; if (typeof(obj.events[obj.currId]) == 'undefined') { obj.events[obj.currId] = []; } obj.events[obj.currId].push(eventData); blockWindow(); $.ajax( { url: "/service/AddExerciseSchedule.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { exercise_id: obj.currId, start: String(eventData.start), end: String(eventData.end) }, success: function( data ) { unblockWindow(); } }); obj.domObj.find(".excalendar").fullCalendar('renderEvent', eventData, true); // stick? = true //} obj.domObj.find(".excalendar").fullCalendar('unselect'); }, eventClick: function(calEvent, jsEvent, view) { for (var i = obj.events[obj.currId].length - 1; i >= 0; i--) { //alert(obj.events[obj.currId][i].start + "\n" + calEvent.start ); if (String(obj.events[obj.currId][i].start).trim() == String(calEvent.start).trim()) { obj.events[obj.currId].splice(i, 1); } } obj.domObj.find(".excalendar").fullCalendar('removeEvents', function(evt) { blockWindow(); $.ajax( { url: "/service/RemoveExerciseSchedule.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { exercise_id: obj.currId, start: String(calEvent.start) }, success: function( data ) { unblockWindow(); } }); if (evt == calEvent) { return true; } return false; }); }, editable: true, defaultView: 'agendaWeek', allDaySlot: false } ) obj.domObj.find(".excalendar").fullCalendar( 'changeView', 'agendaWeek' ); obj.createdCalendar = true; } else { obj.domObj.find(".excalendar").fullCalendar('removeEvents', function(evt) { return true; }); var view = obj.domObj.find(".excalendar").fullCalendar('getView'); var start = view.start; var end = view.end; obj.events[obj.currId] = []; blockWindow(); $.ajax( { url: "/service/GetExerciseSchedule.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { exercise_id: obj.currId, start: String(start), end: String(end) }, success: function( data ) { //unblockWindow(); obj.events[obj.currId] = data; if (typeof(obj.events[obj.currId]) == 'undefined') { obj.events[obj.currId] = []; } obj.domObj.find(".excalendar").fullCalendar('removeEvents', function(evt) { return true; }); for (var i = 0; i < obj.events[obj.currId].length; i++) { var t = obj.events[obj.currId][i].start.split(/[- :]/); var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]); obj.events[obj.currId][i].start = d; var t = obj.events[obj.currId][i].end.split(/[- :]/); var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]); obj.events[obj.currId][i].end = d; obj.domObj.find(".excalendar").fullCalendar('renderEvent', obj.events[obj.currId][i], true); } unblockWindow(); } }); } obj.events[obj.currId] = []; obj.domObj.find(".excalendar").fullCalendar( 'today' ); } Outline.prototype.build = function(mode) { var obj = this; obj.type = mode || 'strength'; var str = '
    \


    \
    \ \ \
    '; this.domObj = $(str); obj.domObj.find("#restrict").change(function() { obj.getExercises(); }); this.getExercises(); obj.currEx = ''; obj.currId = -1; obj.domObj.on('click', '.exercise', function(e) { e.preventDefault(); obj.domObj.find(".exname").text($(this).text()); obj.currEx = $(this).text(); obj.currId = $(this).attr('eid'); obj.currEid = obj.currId; obj.currFid = $(this).attr('fid'); if (obj.timer != -1) { clearTimeout(obj.timer); obj.timer = -1; } if ($(this).attr('fid').substr(0, 4) == 'vid_') { var html = ''; } else { var fids = $(this).attr('fid').split("|"); var thefid = obj.currFid; var c = 0; var html = ''; var chgimgfunc = function() { //console.log("pth1"); if (fids.length > 1) { //console.log("pth2"); //obj.domObj.find("#epic").fadeOut('fast', function() { c++; if (c >= fids.length) { c = 0; } //console.log("pth3"); obj.domObj.find("#epic").attr('src', '/service/GetFile.php?pic=' + fids[c]); //console.log("pth4"); if (obj.timer != -1 && ! obj.destroyed && obj.currFid == thefid) { obj.timer = setTimeout(chgimgfunc, 2000); } //}); //}); }; } obj.timer = setTimeout(chgimgfunc, 2000); } obj.domObj.find(".exercisepic").html(html); obj.domObj.find("#description").html(nl2br(htmlencode($(this).attr('description') || ''))); obj.domObj.find("#showtypeselector").fadeOut('slow', function() { obj.domObj.find("#exerciseindex").slideUp('slow', function() { if (! obj.currFid || obj.currFid == '0' && (obj.domObj.find("#description").html() == '' || obj.domObj.find("#description").html() == 'null')) { obj.domObj.find(".viewexercisecal").slideDown('slow', function() { obj.createCalendar(); }); } else { if (! obj.currFid || obj.currFid == '0') { obj.domObj.find("#epic").hide(); } else { obj.domObj.find("#epic").show(); } obj.domObj.find("#viewexercises").slideDown('slow'); } }); }); }); obj.domObj.on('click', '.sched-btn', function(e) { e.preventDefault(); obj.domObj.find("#showtypeselector").hide(); obj.domObj.find("#viewexercises").slideUp('slow', function() { obj.domObj.find(".viewexercisecal").slideDown('slow', function() { obj.createCalendar(); }); }); }); obj.domObj.on('click', '.back', function(e) { e.preventDefault(); obj.domObj.find("#viewexercises").slideUp('slow', function() { obj.domObj.find("#exerciseindex").slideDown('slow', function() { $(window).triggerHandler("resize"); }); obj.domObj.find("#showtypeselector").show(); obj.getWeekScheduledExercises(); }); }); obj.domObj.on('click', '.backinfo', function(e) { e.preventDefault(); obj.domObj.find("#showtypeselector").hide(); obj.domObj.find(".viewexercisecal").slideUp('slow', function() { if (! obj.currFid || obj.currFid == '0' && (obj.domObj.find("#description").html() == '' || obj.domObj.find("#description").html() == 'null')) { obj.domObj.find("#exerciseindex").slideDown('slow'); obj.domObj.find("#showtypeselector").show(); obj.getWeekScheduledExercises(); } else { if (! obj.currFid || obj.currFid == '0') { obj.domObj.find("#epic").hide(); } else { obj.domObj.find("#epic").show(); } obj.domObj.find("#viewexercises").slideDown('slow'); } }); }); return false; } Outline.prototype.resize=function() { //this.domObj.find(".fc-time-grid-container.fc-scroller").css('height', (window.innerHeight - $("#header").height()) / 2.2 + 'px !important'); } Outline.prototype.getDomObj=function() { return this.domObj; } Outline.prototype.setMode=function(mode) { } Outline.prototype.setHooks=function() { var obj = this; obj.domObj.find("#exerciseindex>div>div.column").columnize({width:200}); obj.domObj.on('click', "#addexercise", function(e) { e.preventDefault(); var widget = new Widget("ExerciseBuilder", { userEditing: true, chooseCallback: function() { obj.getExercises(); } }); widget.renderIntoPopup('100%', '100%', $(this)); }); } Outline.prototype.destroy=function() { var obj = this; $("#content").addClass("page_width"); $("#footer").show(); this.destroyed = true; if (obj.timer != -1) { clearTimeout(obj.timer); obj.timer = -1; } } Outline.prototype.isBuilt=function() { return this.built; } Outline.prototype.contentSet=function(){ } function RemoveAccount(params) { this.loginRequired = true; this.destroyed = false; this.built = false; this.canceled = false; this.confirmPage = false; this.donePage = false; } RemoveAccount.prototype.getAccountRemoveRequest = function(cb) { const obj = this; $.ajax( { url: "/service/GetAccountRemoveRequest.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, success: function( remreq ) { if (remreq && remreq.has_req === true) { obj.remreq = { all_apps: remreq.all_apps, app_list: remreq.app_list }; } else { obj.remreq = null; } cb(); } }); } RemoveAccount.prototype.doesUserHaveConfirmedRemoveRequest = function(cb) { const obj = this; $.ajax( { url: "/service/DoesUserHaveConfirmedRemoveRequest.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, success: function( hasreq ) { cb(hasreq); } }); } RemoveAccount.prototype.buildAppSelectPage = function(mode, submode) { var obj = this; obj.confirmPage = false; var str = ''; str += '
    \ \ \
    '; obj.domObj = $(str); obj.doesUserHaveConfirmedRemoveRequest(function(has_req) { if (has_req) { obj.canceled = obj.built = true; return true; } $.ajax( { url: "/service/NeedsPasswordVerify.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, success: function( needsVerify ) { obj.needsVerify = needsVerify; $.ajax( { url: "/service/GetRemovableInstances.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, success: function( applist ) { obj.applist = applist; obj.getAccountRemoveRequest(function() { obj.built = true; }); } }); } }); }); return false; } RemoveAccount.prototype.buildConfirmPage = function(mode, submode) { var obj = this; obj.confirmPage = true; var str = ''; str += '
    \

    Please confirm the account data removal request:



    \
    \

    We have sent an email to ' + htmlencode(g_userInfo.email) + '.

    \

    Please enter the confirmation code below to remove account data:

    \

    \

    \
    \





    \
    \ \

    \
    '; obj.domObj = $(str); obj.doesUserHaveConfirmedRemoveRequest(function(has_req) { if (has_req) { obj.canceled = obj.built = true; return; } else { obj.remreq = null; obj.getAccountRemoveRequest(function() { obj.built = true; if (! obj.remreq) { setWindow('RemoveAccount'); return; } }); } }); return false; } RemoveAccount.prototype.buildDonePage = function(mode, submode) { var obj = this; obj.confirmPage = true; var str = ''; str += '
    \

    We have received your request



    \

    We have received your removal request and have begun processing it.

    \

    You will receive an email at ' + htmlencode(g_userInfo.email) + ' when the request is complete.

    \

    \
    '; obj.domObj = $(str); return true; } RemoveAccount.prototype.build = function(mode, submode) { var obj = this; if (mode === 'confirm') { return obj.buildConfirmPage(); } else if (mode === 'done') { return obj.buildDonePage(); } else { return obj.buildAppSelectPage(); } return false; } RemoveAccount.prototype.getDomObj=function() { return this.domObj; } RemoveAccount.prototype.setMode=function(mode) { } RemoveAccount.prototype.setHooks=function() { var obj = this; } RemoveAccount.prototype.destroy=function() { this.destroyed = true; } RemoveAccount.prototype.isBuilt=function() { return this.built || this.canceled; } RemoveAccount.prototype.buildAppList=function() { const obj = this; const data = obj.applist; if (data) { let htmlstr = '

    Please select the app data you want to remove:



    '; htmlstr += ''; obj.domObj.find("#app_list").html(htmlstr); } } RemoveAccount.prototype.checkAppList=function() { const obj = this; const applist = obj.remreq; if (applist) { if (applist.all_apps) { obj.domObj.find('#all_apps').prop('checked', true).triggerHandler('change'); } else { for (let i = 0; i < applist.app_list.length; i++) { const appname = applist.app_list[i].appname; const appguid = applist.app_list[i].appguid; obj.domObj.find(".actdel_chkbox").filter(function() { const curr_appname = $(this).attr('data-appname'); const curr_appguid = $(this).attr('data-appguid'); if (curr_appname === appname && curr_appguid === appguid) { return true; } return false; }).prop('checked', true).triggerHandler('change'); } } } else { obj.domObj.find(".actdel_chkbox").filter(function() { const curr_appname = $(this).attr('data-appname'); if (curr_appname === 'FITSTEPPER') { return true; } return false; }).prop('checked', true).triggerHandler('change'); } } RemoveAccount.prototype.contentSetAppSelectPage = function() { const obj = this; obj.buildAppList(); obj.domObj.find("#verify_account_form").submit(function(e) { e.preventDefault(); const password = obj.domObj.find("#password").val(); $.ajax( { url: "/service/VerifyPassword.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { password: password }, success: function( data ) { if (data && data.success === false) { obj.domObj.find("#verifyerror").text(data.error); } else if (data && data.success === true) { obj.domObj.find("#verifyerror").text(''); obj.domObj.find("#verify_account_block").slideUp('slow', function() { obj.domObj.find("#app_select_block").slideDown('slow'); }); } } }); }); obj.domObj.find(".cancelremoveaccount").click(function(e) { e.preventDefault(); setWindow('Settings'); }); obj.domObj.find("#doremoveaccount").click(function(e) { e.preventDefault(); const num_checked = obj.domObj.find(".actdel_chkbox:checked").length; if (num_checked <= 0) { return; } var all_apps = 0; var app_list = []; obj.domObj.find(".actdel_chkbox:checked:not(.skip)").each(function() { const id = $(this).attr('id'); if (id == 'all_apps') { all_apps = 1; } else { const appname = $(this).attr('data-appname'); const appguid = $(this).attr('data-appguid'); app_list.push({ appname: appname, appguid: appguid }); } }); $.ajax( { url: "/service/RemoveAccounts.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { all_apps: all_apps, app_list: app_list }, success: function( data ) { if (data && data.success === false && data.need_verify === true) { obj.domObj.find("#app_select_block").slideUp('slow', function() { obj.domObj.find("#verify_account_block").slideDown('slow'); }); } else if (data && data.success === true) { setWindow('RemoveAccount-confirm'); } } }); }); obj.domObj.find(".actdel_chkbox").on('change', function(e) { const id = $(this).attr('id'); const checked = $(this).is(':checked'); if (id == 'all_apps') { if (checked) { obj.domObj.find(".actdel_chkbox").prop('checked', true); } } else { const appname = $(this).attr('data-appname'); const appguid = $(this).attr('data-appguid'); if (! checked) { obj.domObj.find('#all_apps').prop('checked', false); if (appguid) { obj.domObj.find(".actdel_chkbox").filter(function() { const curr_appname = $(this).attr('data-appname'); const curr_appguid = $(this).attr('data-appguid'); if (curr_appname === appname && ! curr_appguid) { return true; } return false; }).prop('checked', false); } else { obj.domObj.find(".actdel_chkbox").filter(function() { const curr_appname = $(this).attr('data-appname'); const curr_appguid = $(this).attr('data-appguid'); if (curr_appname === appname) { return true; } return false; }).prop('checked', false); } } else { if (! appguid) { obj.domObj.find(".actdel_chkbox").filter(function() { const curr_appname = $(this).attr('data-appname'); const curr_appguid = $(this).attr('data-appguid'); if (curr_appname === appname && curr_appguid) { return true; } return false; }).prop('checked', true); } else { const num = obj.domObj.find(".actdel_chkbox").filter(function() { const curr_appname = $(this).attr('data-appname'); const curr_appguid = $(this).attr('data-appguid'); if (curr_appname === appname && curr_appguid) { return true; } return false; }).length; const num_checked = obj.domObj.find(".actdel_chkbox:checked").filter(function() { const curr_appname = $(this).attr('data-appname'); const curr_appguid = $(this).attr('data-appguid'); if (curr_appname === appname && curr_appguid) { return true; } return false; }).length; if (num === num_checked) { obj.domObj.find(".actdel_chkbox").filter(function() { const curr_appname = $(this).attr('data-appname'); const curr_appguid = $(this).attr('data-appguid'); if (curr_appname === appname) { return true; } return false; }).prop('checked', true); } } } } const num_checked = obj.domObj.find(".actdel_chkbox:checked").length; if (num_checked <= 0) { obj.domObj.find("#doremoveaccount").prop('disabled', true); } else { obj.domObj.find("#doremoveaccount").prop('disabled', false); } }); obj.checkAppList(); if (obj.needsVerify) { obj.domObj.find("#verify_account_block").slideDown('slow'); } else { obj.domObj.find("#app_select_block").slideDown('slow'); } } RemoveAccount.prototype.contentSetDonePage = function() { } RemoveAccount.prototype.contentSetConfirmPage = function() { const obj = this; var code_check_in_progress = false; obj.domObj.find("#cancelremoveaccountreq").click(function(e) { e.preventDefault(); $.ajax( { url: "/service/CancelRemoveAccounts.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, success: function( data ) { setWindow('Settings'); } }); }); (function($domobj, num, donefunc) { (function() { // generate inputs var htmlstr = ''; for (let i = 1; i <= num; i++) { htmlstr += ''; } htmlstr += '

    '; $domobj.html(htmlstr); })(); const validChars = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]; var block_complete = false; var block_complete_timer = null; var resetPosition = function(obj) { const $start_input = $domobj.find('#digit1'); var $next_input = $(obj); if ($start_input[0] === obj || String($(obj).val()).length >= 1) { $(obj).val(''); for (;;) { $next_input = $next_input.next('.digitinput'); if ($next_input.length) $next_input.val(''); else break; } } $next_input = $start_input; for (;;) { if ($next_input.length == 0) return; if (String($next_input.val()).length <= 0) { if ($next_input[0] !== obj) { $next_input.focus(); for (;;) { $next_input = $next_input.next('.digitinput'); if ($next_input.length) $next_input.val(''); else break; } } return; } $next_input = $next_input.next('.digitinput'); } }; var resetFocused = function() { let $focused = $domobj.find(".digitinput:focus"); if ($focused.length) { resetPosition($focused[0]); } }; $domobj.find(".digitinput").on('paste', function(e) { let paste = String((event.clipboardData || window.clipboardData).getData("text")); e.preventDefault(); if (paste) { $domobj.find(".digitinput").val(''); const $start_input = $domobj.find('#digit1'); let $curr_input = $start_input; for (let i = 0; i < paste.length; i++) { if (validChars.indexOf(paste.substr(i, 1)) == -1) { block_complete = true; $curr_input.focus(); if (block_complete_timer !== null) clearTimeout(block_complete_timer); block_complete_timer = setTimeout(function() { $curr_input.val(''); resetFocused(); block_complete = false; }, 0); return; } else { $curr_input.val(paste.substr(i, 1)); $curr_input = $curr_input.next('.digitinput'); if ($curr_input.length == 0) { if (! block_complete) donefunc(); return; } } } block_complete = true; $curr_input.focus(); if (block_complete_timer !== null) clearTimeout(block_complete_timer); block_complete_timer = setTimeout(function() { $curr_input.val(''); resetFocused(); block_complete = false; }, 0); } }); $domobj.find(".digitinput").on('input keydown', function(e) { $domobj.find("#code_error").text(''); if (String($(this).val()).length >= 1 && validChars.indexOf($(this).val()) == -1) { $(this).val(''); return; } else if (String($(this).val()).length == 0) $(this).val(''); if (String($(this).val()).length >= 1) { const $next_input = $(this).next('.digitinput'); if ($next_input.length == 0) { if (! block_complete) donefunc(); return; } else { $next_input.focus(); } } else if (e.key == 'Delete' || e.key == 'Backspace') { const $prev_input = $(this).prev('.digitinput'); if ($prev_input.length) { $prev_input.val(''); $prev_input.focus(); } } resetFocused(); }); $domobj.find(".digitinput").on('focus', function() { resetPosition(this); }); })(obj.domObj.find("#code_entry"), 6, function() { if (code_check_in_progress) return; code_check_in_progress = true; obj.domObj.find(".digitinput").blur(); obj.domObj.find(".digitinput, #cancelremoveaccountreq").prop('disabled', true); obj.domObj.find("#code_error").text(''); var code = String(obj.domObj.find("#digit1").val()) + String(obj.domObj.find("#digit2").val()) + String(obj.domObj.find("#digit3").val()) + String(obj.domObj.find("#digit4").val()) + String(obj.domObj.find("#digit5").val()) + String(obj.domObj.find("#digit6").val()); setTimeout(function() { $.ajax( { url: "/service/ConfirmAccountRemovalCode.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { code: code } , success: function( data ) { if (! data || data.success === false) { if (data && data.error) obj.domObj.find("#code_error").text(data.error); else if (! data) obj.domObj.find("#code_error").text('An error has occurred, please try again later.'); setTimeout(function() { code_check_in_progress = false; obj.domObj.find(".digitinput").val(''); obj.domObj.find(".digitinput, #cancelremoveaccountreq").prop('disabled', false); obj.domObj.find("#digit1").focus(); }, 2500); } else if (data && data.success === true) { setWindow('RemoveAccount-done'); } } }); }, 1100); }); obj.domObj.find("#digit1").focus(); } RemoveAccount.prototype.contentSet=function(){ const obj = this; if (obj.canceled) { setWindow('Settings'); return; } if (obj.donePage === true) { return obj.contentSetDonePage(); } else if (obj.confirmPage === true) { return obj.contentSetConfirmPage(); } else { return obj.contentSetAppSelectPage(); } } function LogFood(params) { params = params || {}; this.loginRequired = true; this.destroyed = false; this.built = false; this.request = null; this.autosearch = params.autosearch || ''; //'0039400019763'; this.results = {}; this.viewmode = 1; this.bucket_id = -1; this.lastSearch = ''; this.results = { 0: {}, 1: {}, // food 2: {}, // recent 3: {}, // myfood 4: {} // overview }; this.servings = { 0: {}, 1: {}, 2: {}, 3: {}, 4: {} }; this.added = { 0: {}, 1: {}, 2: {}, 3: {}, 4: {} }; this.recent_food_servings = { 0: {}, 1: {}, 2: {}, 3: {}, 4: {} }; } LogFood.prototype.appendFood = function(id, name, servings, servingDesc, calories, protein, carbs, sugar, fiber, fat, satFat, monoFat, polyFat, cholesterol, sodium, potassium, food_log_type, servingG, food_id, meal_id, servid, cal_input, weight_input, weight_unit) { var obj = this; var str = ''; servingG = servingG || 0; obj.domObj.find('[logid="' + id + '"]').remove(); var strhtml = '
    Calories: ' + parseFloat(calories * servings).toFixed(2) + ' kCal'; strhtml += '
    Protein: ' + parseFloat(protein * servings).toFixed(2) + ' g'; strhtml += '
    Carbs: ' + parseFloat(carbs * servings).toFixed(2) + ' g'; strhtml += '
    Fat: ' + parseFloat(fat * servings).toFixed(2) + ' g'; strhtml += '
    Remove'; strhtml += '
    '; str += '
    ' + htmlencode(name) + '' + strhtml + '
    '; obj.domObj.find("#addedfoods").prepend(str); obj.domObj.find('[logid="' + id + '"]').attr('foodname', name); //.attr('servingSize', servingSize); //foodname="' + htmlencode(name) + '" } LogFood.prototype.addFood = function(bucket_id, logday, servings, name, calories, protein, carbs, sugar, fiber, fat, satFat, monoFat, polyFat, cholesterol, sodium, potassium, food_log_type, servingG, food_id, servid, cal_input, weight_input, weight_unit, callback) { var obj = this; //blockWindow(); //servid = servid || ''; //servingG = servingG || 0; cal_input = cal_input || ''; weight_input = weight_input || ''; weight_unit_input = weight_unit || ''; $.ajax({ url: "/service/LogFood.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { name: name, bucket_id: bucket_id, logday: logday, food_id: (food_id || ''), food_log_type: food_log_type, servings: servings, calories: calories, protein: protein, carbs: carbs, sugar: sugar, fiber: fiber, fat: fat, satFat: satFat, monoFat: monoFat, polyFat: polyFat, cholesterol: cholesterol, sodium: sodium, potassium: potassium, servingG: servingG, servid: servid, cal_input: cal_input, weight_input: weight_input, weight_unit: weight_unit }, success: function(data) { //obj.appendFood(data, name, servings, servingDesc, calories, protein, carbs, sugar, fiber, fat, satFat, monoFat, polyFat, cholesterol, sodium, potassium, food_log_type, servingG, food_id, meal_id, servid); //obj.doSearch(); //unblockWindow(); callback(data); } }); } LogFood.prototype.getLoggedFood = function() { var obj = this; $.ajax({ url: "/service/GetLoggedFood.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: {}, success: function(data) { obj.built = true; for (var i = 0; i < data.length; i++) { obj.appendFood(data[i].food_log_id, data[i].name, data[i].servings, data[i].servingDesc, data[i].calories, data[i].protein, data[i].carbs, data[i].sugar, data[i].fiber, data[i].fat, data[i].satFat, data[i].monoFat, data[i].polyFat, data[i].cholesterol, data[i].sodium, data[i].potassium, data[i].food_log_type, data[i].servingG, data[i].food_id, '', data[i].servid, data[i].cal_input, data[i].weight_input, data[i].weight_unit); } } }); } LogFood.prototype.setInfiRangeValue = function(val) { var obj = this; this.infirange.canvas.width = $(this.infirange.canvas).width(); this.infirange.canvas.height = $(this.infirange.canvas).height(); var h = this.infirange.canvas.height; var w = this.infirange.canvas.width; val -= obj.infirange.startval; val *= obj.infirange.incby; this.infirange.ctx.moveTo(0, h / 2); this.infirange.ctx.lineTo(w, h / 2); var radius = 4; var offset = this.infirange.offset; //offset += w/2; var incby = parseInt(w / obj.infirange.numintervals); var center = parseInt(w / 2); this.infirange.offset = -(incby * val - center); //console.log(this.infirange.offset); this.drawInfiRange(); } LogFood.prototype.getInfiRangeCurrentValue = function() { var obj = this; //obj.canvas.width = $(obj.canvas).width(); //obj.canvas.height = $(obj.canvas).height(); var h = obj.infirange.canvas.height; var w = obj.infirange.canvas.width; var offset = obj.infirange.offset; var incby = parseInt(w / obj.infirange.numintervals); var x = offset % incby; if (isNaN(x)) x = 0; //var num = parseInt(Math.abs(offset)/incby); var center = w / 2; var closest_x = null; var new_offset = 0; for (;;) { //console.log("loop2 - x: " + x + " incby: " + incby); x += incby; if (closest_x === null || Math.abs(center - x) < Math.abs(new_offset)) { closest_x = x; new_offset = center - x; } if (x > w) break; } //console.log(new_offset); var gotox = Math.ceil(obj.infirange.offset + new_offset - center); var ret = parseInt(Math.abs(gotox) / incby); //ret /= 2.0; //ret += obj.infirange.startval; return ret; // var obj = this; var h = obj.infirange.canvas.height; var w = obj.infirange.canvas.width; var offset = obj.infirange.offset; var incby = parseInt(w / obj.infirange.numintervals); var center = w / 2; var ret = parseInt(Math.abs(offset - center) / incby); //console.log(ret); return ret; } LogFood.prototype.drawInfiRange = function() { var obj = this; this.infirange.canvas.width = $(this.infirange.canvas).width(); this.infirange.canvas.height = $(this.infirange.canvas).height(); var h = this.infirange.canvas.height; var w = this.infirange.canvas.width; if (this.infirange.offset > w / 2) { this.infirange.offset = w / 2; //return; } this.infirange.ctx.clearRect(0, 0, w, h); this.infirange.ctx.beginPath(); this.infirange.ctx.moveTo(0, h / 2); this.infirange.ctx.lineTo(w, h / 2); this.infirange.ctx.stroke(); this.infirange.ctx.beginPath(); this.infirange.ctx.moveTo(w / 2, h / 2 - 15); this.infirange.ctx.lineTo(w / 2, h / 2); this.infirange.ctx.stroke(); this.infirange.ctx.beginPath(); var radius = 4; var offset = this.infirange.offset; // console.log(this.infirange.offset); //offset += w/2; var incby = parseInt(w / obj.infirange.numintervals); var x = offset % incby; if (isNaN(x)) x = 0; //var num = parseInt(offset/incby); var num = parseInt(offset / incby); // console.log(num); // if (offset > 0) num = 0; // console.log(this.infirange.offset); //var start = x; for (;;) { //console.log("loop1 - x: " + x + " incby: " + incby); if (num <= 0) { this.infirange.ctx.arc(x, h / 2, radius, 0, 2 * Math.PI, false); this.infirange.ctx.fillStyle = 'green'; this.infirange.ctx.fill(); //this.ctx.lineWidth = 5; this.infirange.ctx.strokeStyle = '#003300'; this.infirange.ctx.stroke(); this.infirange.ctx.font = "12px Arial"; var numstr = '' + (Math.abs(num) / obj.infirange.incby + obj.infirange.startval); this.infirange.ctx.fillText(numstr, x - numstr.length * 3, h / 2 + 20); } //console.log(x - this.infirange.offset); x += incby; num--; if (x > w) break; } var curr_num = (this.getInfiRangeCurrentValue() / obj.infirange.incby + obj.infirange.startval); var numstr = '' + curr_num; //console.log(numstr); this.infirange.ctx.font = "16px Arial"; //this.ctx.fillText(numstr, w/2-numstr.length*3, h/2-20); numstr += ' ' + (curr_num == 1 ? obj.infirange.labels.single : obj.infirange.labels.multi); this.infirange.ctx.fillText(numstr, (w / 2) - (numstr.length * 4), h / 2 - 20); this.infirange.ctx.fill(); if (curr_num != obj.infirange.curr_num) { obj.setServing(); obj.infirange.curr_num = curr_num; } } LogFood.prototype.updateDash = function(datestr) { var obj = this; $.ajax({ url: "/service/GetTodaysTotals.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { datestr: datestr }, retryCnt: -1, success: function(data) { var num_cals = parseFloat(data['calories'] || 0).toFixed(0); var num_carbs = parseFloat(data['carbs'] || 0).toFixed(0); var num_protein = parseFloat(data['protein'] || 0).toFixed(0); var num_fat = parseFloat(data['fat'] || 0).toFixed(0); var buckets = data.buckets; if (obj.domObj.find("#logdate").val() != datestr) return; $.ajax({ url: "/service/GetTodaysLimits.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { datestr: datestr }, retryCnt: -1, success: function(data) { if (obj.domObj.find("#logdate").val() != datestr) return; obj.domObj.find(".bucket_overlay").hide().removeClass('filled'); for (var bucket_id in buckets) { if (buckets[bucket_id].calories) { obj.domObj.find(".logmeal[bucketid=" + bucket_id + "]").find(".bucket_cals").text(Math.round(buckets[bucket_id].calories)); obj.domObj.find(".logmeal[bucketid=" + bucket_id + "]").find(".bucket_overlay").show().addClass('filled'); } //alert(JSON.stringify(buckets)); } //num_cals = 2693; var daily_cals = 2000; if (data) { if (data.calories) { daily_cals = parseInt(parseFloat(data.calories) /* + parseFloat(burned)*/ ); } } obj.domObj.find(".carb_val").text(num_carbs); obj.domObj.find(".protein_val").text(num_protein); obj.domObj.find(".fat_val").text(num_fat); if (num_cals <= daily_cals) { obj.domObj.find(".cals_less").show(); obj.domObj.find(".cals_greater").hide(); var w = Math.min(Math.ceil(num_cals / daily_cals * 100), 100); obj.domObj.find(".cals_bar_left").css('width', w + '%'); obj.domObj.find(".cals_bar_right").css('width', (100 - w) + '%'); obj.domObj.find(".cals_left").css('width', w + '%'); obj.domObj.find(".cals_right").css('width', (100 - w) + '%'); obj.domObj.find(".daily_cals").text(daily_cals); obj.domObj.find(".num_cals").text(num_cals); obj.domObj.find(".your_cals_block").css('left', Math.floor(obj.domObj.find(".your_cals_block").parent().width() * (w / 100) - obj.domObj.find(".your_cals_block").width() / 2) + 'px'); } else { obj.domObj.find(".cals_less").hide(); obj.domObj.find(".cals_greater").show(); obj.domObj.find(".daily_cals").text(daily_cals); obj.domObj.find(".num_cals").text(num_cals); var w = Math.min(Math.ceil(daily_cals / num_cals * 100), 100); obj.domObj.find(".cals_bar_left").css('width', w + '%'); obj.domObj.find(".cals_bar_right").css('width', (100 - w) + '%'); obj.domObj.find(".cals_left").css('width', w + '%'); obj.domObj.find(".cals_right").css('width', (100 - w) + '%'); obj.domObj.find(".your_cals_block").css('left', Math.floor(obj.domObj.find(".your_cals_block").parent().width() - obj.domObj.find(".your_cals_block").width() / 2) + 'px'); } } }); } }); } LogFood.prototype.showNewFood = function() { var obj = this; obj.domObj.find("#fooddash").hide(); obj.domObj.find("#searchfoodscreen").hide(); obj.domObj.find("#addcustomscreen").show(); //obj.domObj.find("#mealoverview").show(); obj.domObj.find(".spacer:visible").height(obj.domObj.find(".floatbar:visible").height()); $("#navbar,#navmenu").hide(); $(window).scrollTop(0); $(window).triggerHandler('scroll'); setMinHeight(); obj.domObj.find("#newfoodname").focus(); setMinHeight(); obj.domObj.find(".searchfoodnavcell.positive").unbind('click').bind('click', function(e) { e.preventDefault(); if (obj.domObj.find("#newfoodname").val().trim() == '') { alert("Please enter name for new food!"); return; } $.ajax({ url: "/service/AddCustomFood.php?session_id=" + g_sessionId + "&access_code=" + g_accessCode, cache: false, dataType: "json", data: { name: obj.domObj.find("#newfoodname").val(), calories: obj.domObj.find("#newfoodcal").val(), protein: obj.domObj.find("#newfoodprotein").val(), carbs: obj.domObj.find("#newfoodcarbs").val(), fat: obj.domObj.find("#newfoodfat").val() }, success: function(data) { obj.domObj.find("#cancelserving").click(); obj.doSearch(); } }); }); } LogFood.prototype.showFood = function() { //var id = $(this).attr('logid') || 0; var obj = this; if (obj.bucket_id == -1) { obj.domObj.find("#bucket_select_container").show(); } else { obj.domObj.find("#bucket_select_container").hide(); } //var servid = $(this).attr('servid') || 0; var food_id = obj.food_id; //obj.food_id = food_id; obj.scrolltop = $(window).scrollTop(); //console.log(obj.results); //e.preventDefault(); console.log(obj.results[obj.getri()]); obj.domObj.find("#foodname").text(obj.results[obj.getri()][food_id].name); if (!obj.results[obj.getri()][food_id].ingredients) { obj.domObj.find("#ingredient-row").hide().prev().children().css('border-bottom', 'none'); } else { obj.domObj.find("#ingredient-row").show().prev().children().css('border-bottom', '1px solid black'); } var unitstr = ''; if (!obj.servings[obj.getri()][food_id] || !obj.servings[obj.getri()][food_id].length) { unitstr += $('
    ').append($('