var BrowserDetect={init:function(){this.browser=this.searchString(this.dataBrowser)||"An unknown browser";this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"an unknown version";this.OS=this.searchString(this.dataOS)||"an unknown OS";},searchString:function(d){for(var a=0;a<d.length;a++){var b=d[a].string;var c=d[a].prop;this.versionSearchString=d[a].versionSearch||d[a].identity;if(b){if(b.indexOf(d[a].subString)!=-1){return d[a].identity;}}else{if(c){return d[a].identity;}}}},searchVersion:function(b){var a=b.indexOf(this.versionSearchString);if(a==-1){return;}return parseFloat(b.substring(a+this.versionSearchString.length+1));},dataBrowser:[{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari"},{prop:window.opera,identity:"Opera"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],dataOS:[{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.platform,subString:"Mac",identity:"Mac"},{string:navigator.platform,subString:"Linux",identity:"Linux"}]};BrowserDetect.init();var WeekUtil={getDay:function(e,d){var b=this.getDayName(d);for(var c=0;c<e.length;c++){var a=e[c];if(a.name==b){return a;}}return null;},getDayName:function(a){switch(a){case 1:return"monday";case 2:return"tuesday";case 3:return"wednesday";case 4:return"thursday";case 5:return"friday";case 6:return"saturday";case 7:return"sunday";default:return"";}}};var WorkoutUtil={appendEditDiv:function(b,i,e,g,f){var d=document.createElement("div");d.className=e;b.appendChild(d);var c=document.createElement("a");c.href="";c.id="edit_"+i;c.className=g;c.innerHTML="E";d.appendChild(c);var a=document.createTextNode("\u00a0");d.appendChild(a);Event.observe(c,"click",EditWorkout.editWorkout.bindAsEventListener(EditWorkout));var h=document.createElement("a");h.href="";h.id="delete_"+i;h.className=f;h.innerHTML="X";d.appendChild(h);Event.observe(h,"click",DeleteWorkout.deleteWorkout.bindAsEventListener(DeleteWorkout));},appendPlannedEditDiv:function(b,i,e,g,f){var d=document.createElement("div");d.className=e;b.appendChild(d);var c=document.createElement("a");c.href="";c.id="editPlanned_"+i;c.className=g;c.innerHTML="E";d.appendChild(c);var a=document.createTextNode("\u00a0");d.appendChild(a);Event.observe(c,"click",EditPlannedWorkout.editWorkout.bindAsEventListener(EditPlannedWorkout));var h=document.createElement("a");h.href="";h.id="deletePlanned_"+i;h.className=f;h.innerHTML="X";d.appendChild(h);Event.observe(h,"click",DeletePlannedWorkout.deleteWorkout.bindAsEventListener(DeletePlannedWorkout));}};var StringUtil={trimString:function(a){return a.replace(/^\s+/g,"").replace(/\s+$/g,"");}};function entityEncode(b,f){if(!isNaN(b)){return b;}var d=[];var a=[];var i=0;var c=0;var h=/[\\w\\s]/;for(var l=0;l<b.length;++l){var g=b.charAt(l);var k=g.charCodeAt(0);if(isNaN(k)){d.push(a.push(g));}else{var e="&#"+k+";";a.push(e);d.push(h.test(g)?g:e);}}return(f?d.join(""):a.join(""));}var URLUtil={encode:function(a){return escape(this._utf8_encode(a));},decode:function(a){return this._utf8_decode(unescape(a));},_utf8_encode:function(b){b=b.replace(/\r\n/g,"\n");var a="";for(var e=0;e<b.length;e++){var d=b.charCodeAt(e);if(d<128){a+=String.fromCharCode(d);}else{if((d>127)&&(d<2048)){a+=String.fromCharCode((d>>6)|192);a+=String.fromCharCode((d&63)|128);}else{a+=String.fromCharCode((d>>12)|224);a+=String.fromCharCode(((d>>6)&63)|128);a+=String.fromCharCode((d&63)|128);}}}return a;},_utf8_decode:function(a){var b="";var d=0;var e=c1=c2=0;while(d<a.length){e=a.charCodeAt(d);if(e<128){b+=String.fromCharCode(e);d++;}else{if((e>191)&&(e<224)){c2=a.charCodeAt(d+1);b+=String.fromCharCode(((e&31)<<6)|(c2&63));d+=2;}else{c2=a.charCodeAt(d+1);c3=a.charCodeAt(d+2);b+=String.fromCharCode(((e&15)<<12)|((c2&63)<<6)|(c3&63));d+=3;}}}return b;}};var I18N={messages:new Array(),addMessage:function(a,b){this.messages[a]=b;},getMessage:function(a){return this.messages[a];}};var FormValidator={MONTH_LOOKUP:{"01":31,"03":31,"04":30,"05":31,"06":30,"07":31,"08":31,"09":30,"10":31,"11":30,"12":31},MONTH_REGEX:/^\d{4}(\-)\d{2}\1\d{2}$/,HR_REGEX:/^\d{2,3}$/,DOUBLE_DIGIT_REGEX:/^\d{1,2}$/,DECIMAL_REGEX:/(^\d\d*\.\d*$)|(^\d\d*$)|(^\.\d\d*$)/,SINGLE_DIGIT_REGEX:/^\d{1}$/,EMAIL_REGEX:/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,INVALID:"INVALID",VALID:"VALID",INVALID_EMPTY:"INVALID_EMPTY",INVALID_CONTAINS_SPACES:"INVALID_CONTAINS_SPACES",INVALID_LENGTH:"INVALID_LENGTH",INVALID_CHARACTERS:"INVALID_CHARACTERS",validateDate:function(a){return this.validateDate(a,true);},validateDate:function(f,a){var d=false;if(f==""){if(a){return true;}else{return false;}}else{if(!this.MONTH_REGEX.test(f)){return false;}else{var b="-";var g=f.split(b);var h=parseInt(g[2],10);if(this.MONTH_LOOKUP[g[1]]!=null){if(h<=this.MONTH_LOOKUP[g[1]]&&h!=0){return true;}}var e=parseInt(g[1],10);if(e==2){var c=parseInt(g[0]);if(h>0&&h<29){return true;}else{if(h==29){if((c%4==0)&&(c%100!=0)||(c%400==0)){return true;}}}}}}return false;},validateHr:function(a){if(a==""){return true;}if(!this.HR_REGEX.test(a)){return false;}else{if(a>=20&&a<=240){return true;}}return false;},validateDoubleDigit:function(a){if(a==""){return true;}else{return this.DOUBLE_DIGIT_REGEX.test(a);}},validateDecimal:function(a){return this.validateDecimal(a,true);},validateDecimal:function(b,a){if(!b){if(a){return true;}else{return false;}}else{return this.DECIMAL_REGEX.test(b);}},validateSingleDigit:function(a){if(!a){return true;}else{return this.SINGLE_DIGIT_REGEX.test(a);}},validateUser:function(b,d,c){var a=new UserValidator(b,c,"ValidateUser",d);a.validateUser();},validateNewUserId:function(b,d,c){var a=new UserValidator(b,c,"CheckFreeUsername",d);a.validateUser();},validatePassword:function(a){if(!a){return this.INVALID_EMPTY;}else{if(/\s/g.test(a)){return this.INVALID_CONTAINS_SPACES;}else{if(a.length<4||a.length>100){return this.INVALID_LENGTH;}}}return this.VALID;},validateEmail:function(a){if(!a){return true;}return this.EMAIL_REGEX.test(a);},validateLength:function(b,a){if(!b){return true;}if(b.length>a){return false;}return true;},validateGoalName:function(a){if(!a){return this.INVALID_EMPTY;}else{if(a.length>100){return this.INVALID_LENGTH;}}return this.VALID;},validateRouteName:function(a){if(!a){return this.INVALID_EMPTY;}else{if(a.length>100){return this.INVALID_LENGTH;}}return this.VALID;},validateNewGroupName:function(b,d,c){var a=new GroupValidator(b,c,d);a.validateName();},validateNewGroupId:function(b,d,c){var a=new GroupValidator(b,c,d);a.validateId();},validateAcceptTerms:function(a){return a.checked;},alertException:function(b,a){alert(a);},showResult:function(a,b){if(!b){this.validationResultElement.update("");a.style.backgroundColor="white";}else{this.validationResultElement.update(entityEncode(b));this.validationResultElement.style.color="red";a.style.backgroundColor="red";}this.validationResultElement.style.display="block";}};UserValidator=Class.create();UserValidator.prototype={SPACES_REGEX:/\s/g,initialize:function(b,c,a,d){this.element=b;this.validationResultElement=$(c);this.serverCall=a;this.callback=d;},validateUser:function(){if(!this.element.value){this.callback.apply(this,new Array(FormValidator.INVALID_EMPTY,this.element));return;}if(this.element.value.length>30){this.callback.apply(this,new Array(FormValidator.INVALID_LENGTH,this.element));return;}if(this.SPACES_REGEX.test(this.element.value)){this.callback.apply(this,new Array(FormValidator.INVALID_CONTAINS_SPACES),this.element);return;}this.validationResultElement.update(I18N.getMessage("jsMessage.loadMessage.checkingUser"));var b="user="+this.element.value;var a=new Ajax.Request(this.serverCall,{method:"get",parameters:b,onSuccess:this.handleUserValidationResult.bind(this),onFailure:this.alertException.bind(this)});},alertException:function(b,a){alert(a);},handleUserValidationResult:function(request){this.validationResultElement.update("");var resultJSON=eval("("+request.responseText+")");if(resultJSON.ok){this.callback.apply(this,new Array(FormValidator.VALID,this.element));}else{this.callback.apply(this,new Array(resultJSON.message,this.element));}}};GroupValidator=Class.create();GroupValidator.prototype={SPACES_REGEX:/\s/g,GROUPID_REGEX:/^([0-9A-Za-z_])+$/,initialize:function(a,b,c){this.element=a;this.validationResultElement=b;this.callback=c;},validateName:function(){if(!this.element.value){this.callback.apply(this,new Array(FormValidator.INVALID_EMPTY,this.element));return;}if(this.element.value.length>100){this.callback.apply(this,new Array(FormValidator.INVALID_LENGTH,this.element));return;}this.validationResultElement.update(I18N.getMessage("jsMessage.loadMessage.checkingName"));var b="groupname="+this.element.value;var a=new Ajax.Request("ValidateGroup",{method:"get",parameters:b,onSuccess:this.handleValidationResult.bind(this),onFailure:this.alertException.bind(this)});},validateId:function(){if(!this.element.value){this.callback.apply(this,new Array(FormValidator.INVALID_EMPTY,this.element));return;}if(this.element.value.length>30){this.callback.apply(this,new Array(FormValidator.INVALID_LENGTH,this.element));return;}if(this.SPACES_REGEX.test(this.element.value)){this.callback.apply(this,new Array(FormValidator.INVALID_CONTAINS_SPACES),this.element);return;}if(!this.GROUPID_REGEX.test(this.element.value)){this.callback.apply(this,new Array(FormValidator.INVALID_CHARACTERS),this.element);return;}this.validationResultElement.update(I18N.getMessage("jsMessage.loadMessage.checkingId"));var b="groupid="+this.element.value;var a=new Ajax.Request("ValidateGroup",{method:"get",parameters:b,onSuccess:this.handleValidationResult.bind(this),onFailure:this.alertException.bind(this)});},alertException:function(b,a){alert(a);},handleValidationResult:function(request){this.validationResultElement.update("");var resultJSON=eval("("+request.responseText+")");if(resultJSON.ok){this.callback.apply(this,new Array(FormValidator.VALID,this.element));}else{this.callback.apply(this,new Array(resultJSON.message,this.element));}}};var ValidationMessageHandler={handleInvalidDate:function(a,b){this.handleInvalid(a,"validation.invalidDate",b);},handleInvalidHr:function(a,b){this.handleInvalid(a,"validation.invalidHr",b);},handleInvalidSingleDigit:function(a,b){this.handleInvalid(a,"validation.invalidSingleDigit",b);},handleInvalidDoubleDigit:function(a,b){this.handleInvalid(a,"validation.invalidDoubleDigit",b);},handleInvalidDecimal:function(a,b){this.handleInvalid(a,"validation.invalidDecimal",b);},handleInvalidEmail:function(a,b){this.handleInvalid(a,"validation.invalidEmail",b);},handleEmpty:function(a,b){this.handleInvalid(a,"validation.invalidEmpty",b);},handleTooLong30:function(a,b){this.handleInvalid(a,"validation.tooLong30",b);},handleContainSpaces:function(a,b){this.handleInvalid(a,"validation.invalidContainSpaces",b);},handleInvalidNewName:function(a,b){this.handleInvalid(a,"validation.invalidNewName",b);},handleInvalidPasswordLength:function(a,b){this.handleInvalid(a,"validation.invalidPasswordLength",b);},handleInvalidLength100:function(a,b){this.handleInvalid(a,"validation.tooLong100",b);},handleInvalidLength50:function(a,b){this.handleInvalid(a,"validation.tooLong50",b);},handleInvalidCharacters:function(a,b){this.handleInvalid(a,"validation.invalidCharacters",b);},handleInvalidCountry:function(a,b){this.handleInvalid(a,"validation.invalidCountry",b);},handleNotAcceptedTerms:function(a,b){this.handleInvalid(a,"validation.notAcceptedTerms",b);},handleInvalid:function(a,c,b){$(a).update(entityEncode(I18N.getMessage(c)));$(a).show();},handleInvalidNoI18N:function(a,c,b){$(a).update(entityEncode(c));$(a).show();},setValid:function(a,b){$(a).update("");$(a).hide();}};Tags=Class.create();Tags.prototype={initialize:function(){},MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday",DAY_WORKOUT:"dayworkout",SPORT:"sport",DURATION:"duration",DISTANCE:"distance",WID:"wid",IS_TODAY:"istoday"};DatePicker=Class.create();DatePicker.prototype={initialize:function(f,b,e,a,c,d){this.calendar=new YAHOO.widget.Calendar(f,e);this.datePickerContainerId=b;this.dateInputId=d;this.calendar.selectEvent.subscribe(this.calendarDateSelected.bind(this),this.calendar,true);Event.observe($(c),"click",this.closeCalendar.bindAsEventListener(this));Event.observe($(a),"click",this.show.bindAsEventListener(this));this.manualSelect=false;},init:function(c){if(!c){c=new Date();}var d=c.getFullYear();var e=c.getMonth()+1;var b=c.getDate();if(e<10){e="0"+e;}if(b<10){b="0"+b;}var a=this.getCalendarDateStr(d,e,b);$(this.dateInputId).value=this.getFormDateStr(d,e,b);this.manualSelect=false;this.calendar.select(c);this.calendar.setYear(d);this.calendar.setMonth(e-1);},show:function(h){Event.stop(h);if($(this.datePickerContainerId).visible()){return;}var c=$(this.dateInputId).value;if(c&&FormValidator.validateDate(c)){var f=c.split("-");var d=f[0];var g=f[1];var b=f[2];var a=this.getCalendarDateStr(d,g,b);this.manualSelect=false;this.calendar.select(a);this.calendar.setYear(d);this.calendar.setMonth(g-1);}this.calendar.render();this.manualSelect=true;Effect.BlindDown(this.datePickerContainerId);},calendarDateSelected:function(h,g,c){if(!this.manualSelect){return;}var b=g[0][0];var i=b[0];var f=b[1];if(f<10){f="0"+f;}var k=b[2];if(k<10){k="0"+k;}var a=this.getFormDateStr(i,f,k);$(this.dateInputId).value=a;if(document.createEvent){var d=document.createEvent("HTMLEvents");d.initEvent("change",true,false);$(this.dateInputId).dispatchEvent(d);}else{if(document.createEventObject){$(this.dateInputId).fireEvent("onchange");}}this.closeCalendar();},getCalendarDateStr:function(b,c,a){return c+"/"+a+"/"+b;},getFormDateStr:function(b,c,a){return b+"-"+c+"-"+a;},closeCalendar:function(a){if(a){Event.stop(a);}Effect.BlindUp(this.datePickerContainerId);}};ServerAction=Class.create();ServerAction.prototype={initialize:function(){},alertException:function(b,a){this.showMessage(a,false);},handleMessage:function(request){try{var message=eval("("+request.responseText+")");if(message.redirecturl&&message.ok){window.location=message.redirecturl;return true;}if(message.message){this.showMessage(message.message,message.ok);return message.ok;}else{this.showMessage(I18N.getMessage("jsMessage.unknownError"),false);return false;}}catch(e){this.showMessage(I18N.getMessage("jsMessage.messageError"),false);return false;}return false;},showMessage:function(b,a){if(a){$("infoMessage").update(entityEncode(b));$("errorMessage").update("");new Effect.Highlight("infoMessage",{startcolor:"#489eda;",duration:"3"});}else{$("errorMessage").update(entityEncode(b));$("infoMessage").update("");new Effect.Highlight("errorMessage",{startcolor:"#663399;",duration:"3"});}}};EnterSleep=Class.create();EnterSleep.prototype=Object.extend(new ServerAction(),{enterSleep:function(g){this.showLoading();Event.stop(g);var c=$("EnterSleepForm");var d=Form.serialize(c);var a="EnterSleep";var b=new Ajax.Request(a,{method:"post",parameters:d,onSuccess:this.updateChart.bind(this),onFailure:this.alertException.bind(this)});},updateChart:function(a){this.hideLoading();plotrSleep.getChart();this.handleMessage(a);},showLoading:function(){$("loadingMainArea").style.display="block";},hideLoading:function(){$("loadingMainArea").style.display="none";}});EnterSleep=new EnterSleep();EnterWeight=Class.create();EnterWeight.prototype=Object.extend(new ServerAction(),{enterWeight:function(g){this.showLoading();Event.stop(g);var c=$("EnterWeightForm");var d=Form.serialize(c);var a=Context.HOST+"/EnterWeight";var b=new Ajax.Request(a,{method:"post",parameters:d,onSuccess:this.updateChart.bind(this),onFailure:this.alertException.bind(this)});},updateChart:function(a){this.hideLoading();plotrWeight.getChart();this.handleMessage(a);},showLoading:function(){$("loadingMainArea").style.display="block";},hideLoading:function(){$("loadingMainArea").style.display="none";}});EnterWeight=new EnterWeight();EditUserView=Class.create();EditUserView.prototype={initialize:function(){},addEventListeners:function(){Event.observe($("metricUnit"),"click",this.toggleMetric.bindAsEventListener(this));Event.observe($("usUnit"),"click",this.toggleUS.bindAsEventListener(this));Event.observe($("firstName"),"blur",this.ehCheckFirstName.bindAsEventListener(this));Event.observe($("lastName"),"blur",this.ehCheckLastName.bindAsEventListener(this));Event.observe($("email"),"blur",this.ehCheckEmail.bindAsEventListener(this));Event.observe($("birthday"),"blur",this.ehCheckDate.bindAsEventListener(this));Event.observe($("height1"),"blur",this.ehCheckHeight1.bindAsEventListener(this));Event.observe($("height2"),"blur",this.ehCheckHeight2.bindAsEventListener(this));Event.observe($("submitUser"),"click",this.ehCheckAll.bindAsEventListener(this));},ehCheckEmail:function(b){var a=Event.element(b);this.checkEmail(a);},checkEmail:function(a){if(FormValidator.validateEmail(a.value)==true){ValidationMessageHandler.setValid("emailValidation",a);return true;}else{ValidationMessageHandler.handleInvalidEmail("emailValidation",a);return false;}},ehCheckFirstName:function(b){var a=Event.element(b);this.checkFirstName(a);},checkFirstName:function(a){if(FormValidator.validateLength(a.value,100)==true){ValidationMessageHandler.setValid("firstNameValidation",a);return true;}else{ValidationMessageHandler.handleInvalidLength100("firstNameValidation",a);return false;}},ehCheckLastName:function(b){var a=Event.element(b);this.checkLastName(a);},checkLastName:function(a){if(FormValidator.validateLength(a.value,100)==true){ValidationMessageHandler.setValid("lastNameValidation",a);return true;}else{ValidationMessageHandler.handleInvalidLength100("lastNameValidation",a);return false;}},ehCheckDate:function(b){var a=Event.element(b);this.checkDate(a);},checkDate:function(a){var b=FormValidator.validateDate(a.value);if(!b){ValidationMessageHandler.handleInvalidDate("birthdayValidation",a);}else{ValidationMessageHandler.setValid("birthdayValidation",a);}return b;},ehCheckHeight1:function(b){var a=Event.element(b);this.checkHeight1(a);},checkHeight1:function(a){var b=FormValidator.validateSingleDigit(a.value);if(!b){ValidationMessageHandler.handleInvalidSingleDigit("height1Validation",a);}else{ValidationMessageHandler.setValid("height1Validation",a);}return b;},ehCheckHeight2:function(b){var a=Event.element(b);this.checkHeight2(a);},checkHeight2:function(a){var b=FormValidator.validateDoubleDigit(a.value);if(!b){ValidationMessageHandler.handleInvalidDoubleDigit("height2Validation",a);}else{ValidationMessageHandler.setValid("height2Validation",a);}return b;},ehCheckAll:function(a){if(!this.checkFirstName($("firstName"))){Event.stop(a);}if(!this.checkLastName($("lastName"))){Event.stop(a);}if(!this.checkEmail($("email"))){Event.stop(a);}if(!this.checkDate($("birthday"))){Event.stop(a);}if(!this.checkHeight1($("height1"))){Event.stop(a);}if(!this.checkHeight2($("height2"))){Event.stop(a);}this.__ehCheckAll(a);},toggleMetric:function(){$("heigh1label").update(I18N.getMessage("jsMessage.unit.m"));$("heigh2label").update(I18N.getMessage("jsMessage.unit.cm"));},toggleUS:function(){$("heigh1label").update(I18N.getMessage("jsMessage.unit.ft"));$("heigh2label").update(I18N.getMessage("jsMessage.unit.in"));}};LoadGroups=Class.create();LoadGroups.prototype=Object.extend(new ServerAction(),{initialize:function(){},searchGroup:function(h){Event.stop(h);var a=$("loadingArea");a.style.display="block";var d=$("searchGroupForm");var g=Form.serialize(d);var b="SearchGroup";var c=new Ajax.Request(b,{method:"get",parameters:g,onSuccess:this.showSearchResult.bind(this),onFailure:this.alertException.bind(this)});},sortGroup:function(f){Event.stop(f);var a=$("loadingArea");a.style.display="block";var c=Event.element(f);var g="sortBy="+c.value+"&startFrom=0";var b="SortGroups";var d=new Ajax.Request(b,{method:"get",parameters:g,onSuccess:this.showSearchResult.bind(this),onFailure:this.alertException.bind(this)});},navigateGroup:function(h){Event.stop(h);scroll(0,0);var a=$("loadingArea");a.style.display="block";var d=$("sortGroupBy");var c=Event.element(h);if(c.tagName=="DIV"){c=c.parentNode;}var g=c.href.split("Groups?")[1];var i="?sortBy="+d.value+"&"+g;var b="SortGroups";var f=new Ajax.Request(b,{method:"get",parameters:i,onSuccess:this.showSearchResult.bind(this),onFailure:this.alertException.bind(this)});},clearResultArea:function(){var a=$("groupsDiv");a.update("");},showSearchResult:function(request){var resultJSON=eval("("+request.responseText+")");var groups=resultJSON.result;this.clearResultArea();var groupsDiv=$("groupsDiv");var groupTemplateStr='<div class="group"><div><div class="spacer"></div><div style="float:left;"><a href="#{href}"><img src="#{imgSrc}"></a></div><div style="float:left"><div><a href="#{href}">#{groupName}</a></div><div>#{memberNum} members</div></div><div class="spacer"></div></div></div>';var groupTemplate=new Template(groupTemplateStr);for(var i=0;i<groups.length;i++){var toInsert="";var group=groups[i];var left=i%2!=0;if(!left){toInsert+='<div><div class="spacer"></div>';}toInsert+=groupTemplate.evaluate({href:"ViewGroup?groupid="+entityEncode(group.groupid),groupName:entityEncode(group.name),notes:entityEncode(group.notes),imgSrc:"images/group/"+entityEncode(group.smallimgthumburl),memberNum:entityEncode(group.membernum)});if(left){toInsert+='<div class="spacer"></div></div>';}new Insertion.Bottom(groupsDiv,toInsert);}this.navigation.updateNavigation(resultJSON,this.navigateGroup.bindAsEventListener(this));var loadingArea=$("loadingArea");loadingArea.style.display="none";}});var LoadGroups=new LoadGroups();NewGroupView=Class.create();NewGroupView.prototype={initialize:function(){this.observeInputFields();},observeInputFields:function(){Event.observe($("groupName"),"blur",this.ehCheckGroupName.bindAsEventListener(this));Event.observe($("groupId"),"blur",this.ehCheckGroupId.bindAsEventListener(this));Event.observe($("submitGroup"),"click",this.ehCheckAll.bindAsEventListener(this));},ehCheckGroupName:function(b){var a=Event.element(b);this.checkGroupName(a,this.handleGroupNameValidationResult.bind(this));},checkGroupName:function(a,b){FormValidator.validateNewGroupName(a,b,"groupNameValidation");},ehCheckGroupId:function(b){var a=Event.element(b);this.checkGroupId(a,this.handleGroupIdValidationResult.bind(this));},checkGroupId:function(a,b){FormValidator.validateNewGroupId(a,b,"groupIdValidation");},ehCheckAll:function(a){},handleGroupNameValidationResult:function(b,a){if(b==FormValidator.VALID){ValidationMessageHandler.setValid("groupNameValidation",a);}else{if(b==FormValidator.INVALID_EMPTY){ValidationMessageHandler.handleEmpty("groupNameValidation",a);}else{if(b==FormValidator.INVALID_LENGTH){ValidationMessageHandler.handleInvalidLength100("groupNameValidation",a);}else{if(b==FormValidator.INVALID){ValidationMessageHandler.handleInvalidNewName("groupNameValidation",a);}else{ValidationMessageHandler.handleInvalid("groupNameValidation",b,a);}}}}},handleGroupIdValidationResult:function(b,a){if(b==FormValidator.VALID){ValidationMessageHandler.setValid("groupIdValidation",a);}else{if(b==FormValidator.INVALID_EMPTY){ValidationMessageHandler.handleEmpty("groupIdValidation",a);}else{if(b==FormValidator.INVALID_LENGTH){ValidationMessageHandler.handleTooLong30("groupIdValidation",a);}else{if(b==FormValidator.INVALID_CONTAINS_SPACES){ValidationMessageHandler.handleContainSpaces("groupIdValidation",a);}else{if(b==FormValidator.INVALID_CHARACTERS){ValidationMessageHandler.handleInvalidCharacters("groupIdValidation",a);}else{if(b==FormValidator.INVALID){ValidationMessageHandler.handleInvalidNewName("groupIdValidation",a);}else{ValidationMessageHandler.handleInvalid("groupIdValidation",b,a);}}}}}}}};NewUserView=Class.create();NewUserView.prototype=Object.extend(new EditUserView(),{initialize:function(){this.addEventListeners();},addEventListeners:function(){Event.observe($("username"),"blur",this.ehCheckUserName.bindAsEventListener(this));Event.observe($("pwd1"),"blur",this.ehCheckPassword1.bindAsEventListener(this));Event.observe($("pwd2"),"blur",this.ehCheckPassword2.bindAsEventListener(this));Event.observe($("email"),"blur",this.ehCheckEmail.bindAsEventListener(this));Event.observe($("terms"),"click",this.ehCheckAccept.bindAsEventListener(this));Event.observe($("submitUser"),"click",this.ehCheckAll.bindAsEventListener(this));},ehCheckAccept:function(b){var a=Event.element(b);this.checkAccept(a);},checkAccept:function(b){var a=FormValidator.validateAcceptTerms(b);if(a){ValidationMessageHandler.setValid("termsValidation",b);return true;}ValidationMessageHandler.handleNotAcceptedTerms("termsValidation",b);return false;},ehCheckUserName:function(b){var a=Event.element(b);this.checkUserName(a,this.handleUserValidationResult.bind(this));},checkUserName:function(a,b){FormValidator.validateNewUserId(a,b,"usernameValidation");},ehCheckPassword1:function(b){var a=Event.element(b);this.checkPassword(a,"pwdValidation1");},ehCheckPassword2:function(b){var a=Event.element(b);this.checkPassword(a,"pwdValidation2");},checkPassword:function(b,a){var c=FormValidator.validatePassword(b.value);if(c==FormValidator.VALID){ValidationMessageHandler.setValid(a,b);return true;}else{if(c==FormValidator.INVALID_EMPTY){ValidationMessageHandler.handleEmpty(a,b);}else{if(c==FormValidator.INVALID_CONTAINS_SPACES){ValidationMessageHandler.handleContainSpaces(a,b);}else{if(c==FormValidator.INVALID_LENGTH){ValidationMessageHandler.handleInvalidPasswordLength(a,b);}else{ValidationMessageHandler.handleInvalid(a,c,b);}}}}return false;},handleUserValidationResult:function(b,a){if(b==FormValidator.VALID){ValidationMessageHandler.setValid("usernameValidation",a);}else{if(b==FormValidator.INVALID_EMPTY){ValidationMessageHandler.handleEmpty("usernameValidation",a);}else{if(b==FormValidator.INVALID_LENGTH){ValidationMessageHandler.handleTooLong30("usernameValidation",a);}else{if(b==FormValidator.INVALID_CONTAINS_SPACES){ValidationMessageHandler.handleContainSpaces("usernameValidation",a);}else{if(b==FormValidator.INVALID_CHARACTERS){ValidationMessageHandler.handleInvalidCharacters("usernameValidation",a);}else{if(b==FormValidator.INVALID){ValidationMessageHandler.handleInvalidNewName("usernameValidation",a);}else{ValidationMessageHandler.handleInvalidNoI18N("usernameValidation",b,a);}}}}}}},ehCheckAll:function(a){if(!this.checkPassword($("pwd1"),"pwdValidation1")){Event.stop(a);}if(!this.checkPassword($("pwd2"),"pwdValidation2")){Event.stop(a);}if(!this.checkEmail($("email"))){Event.stop(a);}if(!this.checkAccept($("terms"))){Event.stop(a);}}});TimelineManager=Class.create();TimelineManager.prototype={initialize:function(){},addEventListeners:function(){Event.observe(window,"load",this.initTimeline.bindAsEventListener(this));var a=this.initTimeline.bindAsEventListener(this);EventManager.registerEventHandler(Events.WORKOUT_ADDED,a);},initTimeline:function(){var a=new Date();eventSource=new Timeline.DefaultEventSource(0);var b=[Timeline.createBandInfo({eventSource:eventSource,date:a,width:"80%",intervalUnit:Timeline.DateTime.DAY,intervalPixels:100}),Timeline.createBandInfo({width:"20%",intervalUnit:Timeline.DateTime.MONTH,intervalPixels:200})];b[1].syncWith=0;b[1].highlight=true;this.tl=Timeline.create(document.getElementById("timeline"),b);this.tl.loadJSON("GetTimelineData",function(d,c){eventSource.loadJSON(d,c);});}};var TimelineManager=new TimelineManager();NewGroupView=Class.create();NewGroupView.prototype={initialize:function(){this.observeInputFields();},observeInputFields:function(){Event.observe($("groupName"),"blur",this.ehCheckGroupName.bindAsEventListener(this));Event.observe($("groupId"),"blur",this.ehCheckGroupId.bindAsEventListener(this));Event.observe($("submitGroup"),"click",this.ehCheckAll.bindAsEventListener(this));},ehCheckGroupName:function(b){var a=Event.element(b);this.checkGroupName(a,this.handleGroupNameValidationResult.bind(this));},checkGroupName:function(a,b){FormValidator.validateNewGroupName(a,b,"groupNameValidation");},ehCheckGroupId:function(b){var a=Event.element(b);this.checkGroupId(a,this.handleGroupIdValidationResult.bind(this));},checkGroupId:function(a,b){FormValidator.validateNewGroupId(a,b,"groupIdValidation");},ehCheckAll:function(a){},handleGroupNameValidationResult:function(b,a){if(b==FormValidator.VALID){ValidationMessageHandler.setValid("groupNameValidation",a);}else{if(b==FormValidator.INVALID_EMPTY){ValidationMessageHandler.handleEmpty("groupNameValidation",a);}else{if(b==FormValidator.INVALID_LENGTH){ValidationMessageHandler.handleInvalidLength100("groupNameValidation",a);}else{if(b==FormValidator.INVALID){ValidationMessageHandler.handleInvalidNewName("groupNameValidation",a);}else{ValidationMessageHandler.handleInvalid("groupNameValidation",b,a);}}}}},handleGroupIdValidationResult:function(b,a){if(b==FormValidator.VALID){ValidationMessageHandler.setValid("groupIdValidation",a);}else{if(b==FormValidator.INVALID_EMPTY){ValidationMessageHandler.handleEmpty("groupIdValidation",a);}else{if(b==FormValidator.INVALID_LENGTH){ValidationMessageHandler.handleTooLong30("groupIdValidation",a);}else{if(b==FormValidator.INVALID_CONTAINS_SPACES){ValidationMessageHandler.handleContainSpaces("groupIdValidation",a);}else{if(b==FormValidator.INVALID_CHARACTERS){ValidationMessageHandler.handleInvalidCharacters("groupIdValidation",a);}else{if(b==FormValidator.INVALID){ValidationMessageHandler.handleInvalidNewName("groupIdValidation",a);}else{ValidationMessageHandler.handleInvalid("groupIdValidation",b,a);}}}}}}}};SummarySelector=Class.create();SummarySelector.prototype={initialize:function(d,b,c,a){this.previousSelector=$(d);this.nextSelector=$(b);this.selection=$(c);this.updateEvent=a;Event.observe(this.selection,"change",this.selectionChanged.bindAsEventListener(this));Event.observe(this.previousSelector,"click",this.previous.bindAsEventListener(this));Event.observe(this.nextSelector,"click",this.next.bindAsEventListener(this));},next:function(a){if(this.selection.selectedIndex<(this.selection.options.length-1)){this.selection.selectedIndex=this.selection.selectedIndex+1;this.selectionChanged(a);}},previous:function(a){if(this.selection.selectedIndex>0){this.selection.selectedIndex=this.selection.selectedIndex-1;this.selectionChanged(a);}},selectionChanged:function(a){Event.stop(a);this.updateSelectorStyles();EventManager.fireEvent(this.updateEvent,a);},updateSelectorStyles:function(){if(this.selection.selectedIndex==(this.selection.options.length-1)){Event.observe(this.nextSelector,"click",this.killEvent.bindAsEventListener(this));this.nextSelector.className="statRightArrowInactive";}else{Event.stopObserving(this.nextSelector,"click",this.killEvent.bindAsEventListener(this));this.nextSelector.className="statRightArrow";}if(this.selection.selectedIndex==0){Event.observe(this.previousSelector,"click",this.killEvent.bindAsEventListener(this));this.previousSelector.className="statLeftArrowInactive";}else{Event.stopObserving(this.previousSelector,"click",this.killEvent.bindAsEventListener(this));this.previousSelector.className="statLeftArrow";}},killEvent:function(a){Event.stop(a);}};AbstractDialog=Class.create();AbstractDialog.prototype=Object.extend(new ServerAction(),{MASK_HTML:'<div id="mask" class="mask"><!--[if IE 6]><iframe></iframe><![endif]--></div>',init:function(a){this.dialogPrefixId=a;this.dialogId=a+"Dialog";this.closeButton=$(a+"Close");this.cancelButton=$(a+"Cancel");this.dialogHeaderId=a+"Header";this.dialogLabelId=this.dialogHeaderId+"Label";this.formId=a+"Form";new Draggable(this.dialogId,{handle:this.dialogHeaderId});Event.observe(this.closeButton,"click",this.close.bindAsEventListener(this));Event.observe(this.cancelButton,"click",this.close.bindAsEventListener(this));Event.observe($(a+"Ok"),"click",this.handleSubmit.bindAsEventListener(this));},getWindowSize:function(){var b=0,a=0;if(typeof(window.innerWidth)=="number"){b=window.innerWidth;a=window.innerHeight;}else{if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)){b=document.documentElement.clientWidth;a=document.documentElement.clientHeight;}else{if(document.body&&(document.body.clientWidth||document.body.clientHeight)){b=document.body.clientWidth;a=document.body.clientHeight;}}}var c=new Object();c.height=a;c.width=b;return c;},handleClick:function(a){if(a!=null){Event.stop(a);}this.show();},show:function(){var c=$$("div.swfchart");if(c){c.each(function(f,e){f.style.visibility="hidden";});}new Insertion.Top(document.body,this.MASK_HTML);var a=$("mask");a.style.width=document.documentElement.scrollWidth+"px";a.style.height=document.documentElement.scrollHeight+"px";this.hideLoading();window.scrollTo(0,0);var b=$(this.dialogId);var d=this.getWindowSize();b.style.top=(d.height-b.offsetHeight)/2+"px";b.style.left=(d.width-b.offsetWidth)/2+"px";b.style.visibility="visible";},clearDialog:function(){},close:function(b){if(b){Event.stop(b);}this.clearDialog();$("mask").remove();if(this.selectMask){this.selectMask.remove();}var a=$$("div.swfchart");if(a){a.each(function(d,c){d.style.visibility="visible";});}$(this.dialogId).style.visibility="hidden";},showLoading:function(){$("loadingMainArea").style.display="block";},hideLoading:function(){$("loadingMainArea").style.display="none";}});OkCancelDialog=Class.create();OkCancelDialog.prototype=Object.extend(new AbstractDialog(),{addEventListeners:function(b,a){Event.observe($(b),"click",this.handleOk.bindAsEventListener(this));Event.observe($(a),"click",this.handleCancel.bindAsEventListener(this));},handleOk:function(a){},handleCancel:function(a){Event.stop(a);this.close();}});CommentDialog=Class.create();CommentDialog.prototype=Object.extend(new AbstractDialog(),{initialize:function(d,c,a,b){this.init(d);this.wid=c;this.user=a;this.isPlanned=b;},invoke:function(a){$(this.dialogLabelId).update(I18N.getMessage("jsMessage.commentDialog.addComment"));this.newComment=true;this.handleClick(a);},invokeEdit:function(a){$(this.dialogLabelId).update(I18N.getMessage("jsMessage.commentDialog.editComment"));this.newComment=false;this.cid=a;this.doEditRequest();},doEditRequest:function(){var c=$(this.formId);var d=Form.serialize(c);d+="&cid="+this.cid+"&isPlanned="+this.isPlanned;var a=Context.HOST+"/GetComment";var b=new Ajax.Request(a,{method:"get",parameters:d,onSuccess:this.showEditDialog.bind(this),onFailure:this.alertException.bind(this)});},showEditDialog:function(request){this.setValues(eval("("+request.responseText+")"));this.handleClick();},setValues:function(a){this.newComment=false;$("workoutComment").value=a.comment;},handleSubmit:function(d){Event.stop(d);var c=$(this.formId);var g=Form.serialize(c);if(this.newComment){g+="&wid="+this.wid+"&forUser="+this.user+"&isPlanned="+this.isPlanned;}else{g+="&cid="+this.cid+"&isPlanned="+this.isPlanned;}var a=Context.HOST+(this.newComment?"/NewComment":"/EditComment");var b=new Ajax.Request(a,{method:"post",parameters:g,onSuccess:this.showSubmitResult.bind(this),onFailure:this.alertException.bind(this)});},showSubmitResult:function(request){this.close();var message=eval("("+request.responseText+")");if(message.ok){if(this.newComment){EventManager.fireEvent(Events.WORKOUT_COMMENT_ADDED);}else{EventManager.fireEvent(Events.WORKOUT_COMMENT_EDITED);}}this.handleMessage(request);},clearDialog:function(){Form.reset($(this.formId));}});DeleteGoalDialog=Class.create();DeleteGoalDialog.prototype=Object.extend(new OkCancelDialog(),{initialize:function(){this.init("deleteGoal");},invoke:function(c){Event.stop(c);var a=Event.element(c);var d=Event.element(c).id;var b=d.split("deleteGoal_")[1];this.goalId=b.split("_")[0];this.goalType=b.split("_")[1];this.handleClick();},handleSubmit:function(d){Event.stop(d);var b="goalId="+this.goalId+"&goalType="+this.goalType;var a=Context.HOST+"/DeleteGoal";var c=new Ajax.Request(a,{method:"post",parameters:b,onSuccess:this.handleMessage.bind(this),onFailure:this.alertException.bind(this)});this.close();}});DeleteRouteDialog=Class.create();DeleteRouteDialog.prototype=Object.extend(new OkCancelDialog(),{initialize:function(a){this.init("deleteRoute");this.routeId=a;this.addEventListeners("deleteRouteOk","deleteRouteCancel");},handleSubmit:function(d){Event.stop(d);var b="routeId="+this.routeId;var a=Context.HOST+"/DeleteRoute";var c=new Ajax.Request(a,{method:"post",parameters:b,onSuccess:this.deleteOk.bind(this),onFailure:this.alertException.bind(this)});this.close();},deleteOk:function(a){this.handleMessage(a);}});DeleteWorkoutDialog=Class.create();DeleteWorkoutDialog.prototype=Object.extend(new OkCancelDialog(),{initialize:function(b,c){this.wid=b;this.referer=c;var a="deleteWorkout";this.init(a);this.addEventListeners(a+"Ok",a+"Cancel");},handleSubmit:function(d){Event.stop(d);var b="wid="+this.wid+"&backTo="+this.referer;var a=Context.HOST+"/DeleteWorkout";var c=new Ajax.Request(a,{method:"post",parameters:b,onSuccess:this.handleMessage.bind(this),onFailure:this.alertException.bind(this)});this.close();}});DeleteMessageDialog=Class.create();DeleteMessageDialog.prototype=Object.extend(new OkCancelDialog(),{initialize:function(a,b){this.mid=a;this.referer=b;this.init("deleteMessage");},handleSubmit:function(d){Event.stop(d);var b="mid="+this.mid+"&backTo="+this.referer;var a=Context.HOST+"/DeleteMessage";var c=new Ajax.Request(a,{method:"post",parameters:b,onSuccess:this.handleMessage.bind(this),onFailure:this.alertException.bind(this)});this.close();}});DeleteReportDialog=Class.create();DeleteReportDialog.prototype=Object.extend(new OkCancelDialog(),{initialize:function(){var a="deleteReport";this.init(a);},showDialog:function(b){var a=Event.element(b);this.id=a.id.split("deleteReport_")[1];this.handleClick(b);},handleSubmit:function(d){Event.stop(d);var b="id="+this.id;var a=Context.HOST+"/DeleteReport";var c=new Ajax.Request(a,{method:"post",parameters:b,onSuccess:this.handleResult.bind(this),onFailure:this.alertException.bind(this)});this.close();},handleResult:function(a){if(this.handleMessage(a)){$("reportEntry_"+this.id).remove();}}});FilterRoutesDialog=Class.create();FilterRoutesDialog.prototype=Object.extend(new AbstractDialog(),{initialize:function(a){this.init(a);this.isUserRoutes=false;},__observeInputFields:function(){},invoke:function(a){this.clearDialog();this.isUserRoutes=false;this.handleClick(a);},invokeUserRoutes:function(a){this.clearDialog();this.isUserRoutes=true;this.handleClick(a);},handleSubmit:function(b){Event.stop(b);var a=$(this.formId);a.submit();},clearDialog:function(){Form.reset($(this.formId));var b=$$("div.validation");b.each(function(d,c){d.update("");});var a=$$("input.dialogInput");a.each(function(d,c){d.style.backgroundColor=ValidationMessageHandler.VALID_COLOR;});}});ForumPostDialog=Class.create();ForumPostDialog.prototype=Object.extend(new AbstractDialog(),{initialize:function(a,c,d,e,b){this.init(a,c,d);this.formId=e;Event.observe($(b),"click",this.handleSubmit.bindAsEventListener(this));},invoke:function(d){var c=Event.element(d);var a=c.id;var b=a.indexOf("replyToGroupPost_");if(b!=-1){this.replyToId=a.split("replyToGroupPost_")[1];}else{this.replyToId=null;}this.handleClick(d);},handleSubmit:function(h){var d=$(this.formId);var g=Form.serialize(d);var a=Form.serialize(d,true);this.groupId=a.forumPostGroupId;this.threadId=a.forumThreadId;if(this.replyToId){g+="&replyToId="+this.replyToId;}var b=Context.HOST+"/NewForumPost";this.close();var c=new Ajax.Request(b,{method:"post",parameters:g,onSuccess:this.showSubmitResult.bind(this),onFailure:this.alertException.bind(this)});},showSubmitResult:function(a){this.handleMessage(a);if(this.replyToId){this.reloadThread();}else{this.reloadThreadList();}},reloadThreadList:function(){LoadForumThreadList.loadThreadList(this.threadId,this.groupId);},reloadThread:function(){},clearDialog:function(){Form.reset($(this.formId));}});GoalDialog=Class.create();GoalDialog.prototype=Object.extend(new AbstractDialog(),{GOAL_UNIT_TEMPLATE_STR:'<option value="0">#{metricUnit}</option><option value="1">#{usUnit}</option>',initialize:function(a){this.init(a);this.UNIT_TEMPLATE=new Template(this.GOAL_UNIT_TEMPLATE_STR);this.noRedirect=false;Event.observe($("goalType"),"change",this.ehHandleTypeChange.bindAsEventListener(this));this.startCalendar=new DatePicker(a+"StartDatePickerCal",a+"StartDateContainer",a+"StartCalContainer",a+"StartDatePicker",a+"StartCloseCal",a+"StartDate");this.calendar=new DatePicker(a+"DatePickerCal",a+"DateContainer",a+"CalContainer",a+"DatePicker",a+"CloseCal",a+"Date");this.observeInputFields();},setNoRedirect:function(a){this.noRedirect=a;},observeInputFields:function(){Event.observe($("goalName"),"change",this.ehCheckGoalName.bindAsEventListener(this));Event.observe($("goalValue"),"change",this.ehCheckGoalValue.bindAsEventListener(this));Event.observe($(this.dialogPrefixId+"StartDate"),"change",this.ehCheckStart.bindAsEventListener(this));Event.observe($(this.dialogPrefixId+"Date"),"change",this.ehCheckCompleteBy.bindAsEventListener(this));},getServerCall:function(){if(this.newGoal){return Context.HOST+"/NewGoal";}return Context.HOST+"/EditGoal";},invoke:function(b){this.newGoal=true;var a=$("goalType");a.enable();this.handleTypeChange(a.value);this.calendar.init();this.startCalendar.init();this.handleClick(b);},invokeEdit:function(f){Event.stop(f);var a=Event.element(f);var g=Event.element(f).id;var d=g.split("editGoal_")[1];var c=d.split("_")[0];var b=d.split("_")[1];this.doEditRequest(c,b);},doEditRequest:function(c,b){var d="goalId="+c+"&goalType="+b;var a=Context.HOST+"/GetGoal";var e=new Ajax.Request(a,{method:"get",parameters:d,onSuccess:this.showEdit.bind(this),onFailure:this.alertException.bind(this)});},showEdit:function(request){this.setValues(eval("("+request.responseText+")"));this.handleClick(null);},setValues:function(b){this.newGoal=false;this.goalId=b.id;var a=$("goalType");a.value=b.type;this.handleTypeChange(a.value);a.disable();if(b.type=="simple"){$("goalName").value=b.name;$("goalDescription").value=b.description;$(this.dialogPrefixId+"StartDate").value=b.startdate;$(this.dialogPrefixId+"Date").value=b.enddate;}else{$("goalValue").value=b.goalvalue;$("goalValueUnit").value=b.unit;$("goalValueFrequency").value=b.goalmeasure;$(this.dialogPrefixId+"StartDate").value=b.startdate;$(this.dialogPrefixId+"Date").value=b.enddate;if(b.sport){$("goalSport").value=b.sport.id;}else{$("goalSport").value="";}$("goalDescription").value=b.comment;}},ehHandleTypeChange:function(b){var a=Event.element(b);this.handleTypeChange(a.value);},handleTypeChange:function(a){if(a=="time"){this.showTimeDialog();}else{if(a=="distance"){this.showDistanceDialog();}else{if(a=="weight"){this.showWeightDialog();}else{if(a=="frequency"){this.showFrequencyDialog();}else{this.showSimpleDialog();}}}}},showTimeDialog:function(){$("goalNameDiv").hide();$("goalValueUnit").hide();$("goalValueUnitDiv").update(I18N.getMessage("jsMessage.goalDialog.hours"));$("goalValueLabel").update(I18N.getMessage("jsMessage.goalDialog.time"));$("goalSportDiv").show();$("goalTimeDiv").show();$("goalValueFrequency").show();$("goalValueUnitDiv").show();},showDistanceDialog:function(){this.showUnits(I18N.getMessage("jsMessage.unit.km"),I18N.getMessage("jsMessage.unit.mi"));$("goalValueLabel").update(I18N.getMessage("jsMessage.goalDialog.distance"));$("goalSportDiv").show();$("goalTimeDiv").show();$("goalValueFrequency").show();$("goalNameDiv").hide();$("goalValueUnitDiv").hide();},showWeightDialog:function(){$("goalNameDiv").hide();$("goalSportDiv").hide();$("goalValueFrequency").hide();$("goalValueUnitDiv").hide();this.showUnits(I18N.getMessage("jsMessage.unit.kg"),I18N.getMessage("jsMessage.unit.lbs"));$("goalValueLabel").update(I18N.getMessage("jsMessage.goalDialog.weight"));$("goalTimeDiv").show();},showFrequencyDialog:function(){$("goalNameDiv").hide();$("goalValueUnit").hide();$("goalValueUnitDiv").update(I18N.getMessage("jsMessage.goalDialog.times"));$("goalValueLabel").update(I18N.getMessage("jsMessage.goalDialog.frequency"));$("goalSportDiv").show();$("goalTimeDiv").show();$("goalValueFrequency").show();$("goalValueUnitDiv").show();},showSimpleDialog:function(){$("goalSportDiv").hide();$("goalTimeDiv").hide();$("goalNameDiv").show();},showUnits:function(b,d){var a=$("goalValueUnit");a.update("");var c=this.UNIT_TEMPLATE.evaluate({metricUnit:b,usUnit:d});new Insertion.Bottom(a,c);a.show();},handleSubmit:function(d){Event.stop(d);if(!this.checkAll()){return;}var b=$(this.formId);var c=Form.serialize(b);c+="&goalValueUnit="+$("goalValueUnit").value;if(!this.newGoal){c+="&goalId="+this.goalId+"&goalType="+$("goalType").value;}if(this.noRedirect){c+="&noRedirect=true";}this.close();var a=new Ajax.Request(this.getServerCall(),{method:"post",parameters:c,onSuccess:this.showSubmitResult.bind(this),onFailure:this.alertException.bind(this)});},showSubmitResult:function(b){var a=this.handleMessage(b);if(!a){return;}if(!this.newGoal){EventManager.fireEvent(Events.GOAL_EDITED);}},clearDialog:function(){Form.reset($(this.formId));var b=$$("div.validation");b.each(function(d,c){d.update("");});var a=$$("input.dialogInput");a.each(function(d,c){d.style.backgroundColor=ValidationMessageHandler.VALID_COLOR;});},checkAll:function(){var a=this.checkGoalName($("goalName"));if(!a){return false;}a=this.checkGoalValue($("goalValue"));if(!a){return false;}a=this.checkStart($(this.dialogPrefixId+"StartDate"));if(!a){return false;}a=this.checkCompleteBy($(this.dialogPrefixId+"Date"));if(!a){return false;}return true;},ehCheckGoalName:function(b){var a=Event.element(b);this.checkGoalName(a);},checkGoalName:function(a){if($("goalType").value!="simple"){return true;}var b=FormValidator.validateGoalName(a.value);if(b==FormValidator.INVALID_LENGTH){ValidationMessageHandler.handleInvalidLength100("goalNameValidation",a);return false;}else{if(b==FormValidator.INVALID_EMPTY){ValidationMessageHandler.handleEmpty("goalNameValidation",a);return false;}else{ValidationMessageHandler.setValid("goalNameValidation",a);return true;}}},ehCheckGoalValue:function(b){var a=Event.element(b);this.checkGoalValue(a);},checkGoalValue:function(a){if($("goalType").value=="simple"){return true;}var b=FormValidator.validateDecimal(a.value);if(!b){ValidationMessageHandler.handleInvalidDecimal("goalValueValidation",a);}else{ValidationMessageHandler.setValid("goalValueValidation",a);}return b;},ehCheckStart:function(b){var a=Event.element(b);this.checkStart(a);},checkStart:function(a){var b=FormValidator.validateDate(a.value);if(!b){ValidationMessageHandler.handleInvalidDate("goalStartValidation",a);}else{ValidationMessageHandler.setValid("goalStartValidation",a);}return b;},ehCheckCompleteBy:function(b){var a=Event.element(b);this.checkCompleteBy(a);},checkCompleteBy:function(a){var b=FormValidator.validateDate(a.value);if(!b){ValidationMessageHandler.handleInvalidDate("goalCompleteByValidation",a);}else{ValidationMessageHandler.setValid("goalCompleteByValidation",a);}return b;}});NewMessageDialog=Class.create();NewMessageDialog.prototype=Object.extend(new AbstractDialog(),{initialize:function(a){this.init(a);this.observeInputFields();},invoke:function(a){this.handleClick(a);},invokeReply:function(c){Event.stop(c);var b=Event.element(c).href;var a=b.split("replyto/");$("toUser").value=a[1];this.handleClick(c);},handleSubmit:function(g){Event.stop(g);var c=$(this.formId);var d=Form.serialize(c);var a=Context.HOST+"/NewMessage";this.close();var b=new Ajax.Request(a,{method:"post",parameters:d,onSuccess:this.showSubmitResult.bind(this),onFailure:this.alertException.bind(this)});},showSubmitResult:function(a){this.handleMessage(a);},clearDialog:function(){Form.reset($(this.formId));$("usernameValidation").innerHTML="";},observeInputFields:function(){Event.observe($("toUser"),"blur",this.ehCheckUserName.bindAsEventListener(this));},ehCheckUserName:function(b){var a=Event.element(b);this.checkUserName(a,this.handleUserValidationResult.bind(this));},checkUserName:function(a,b){FormValidator.validateUser(a,b,"usernameValidation");},handleUserValidationResult:function(b,a){if(b==FormValidator.VALID){ValidationMessageHandler.setValid("usernameValidation",a);}else{if(b==FormValidator.INVALID_EMPTY){ValidationMessageHandler.handleEmpty("usernameValidation",a);}else{if(b==FormValidator.INVALID_LENGTH){ValidationMessageHandler.handleTooLong30("usernameValidation",a);}else{if(b==FormValidator.INVALID_CONTAINS_SPACES){ValidationMessageHandler.handleContainSpaces("usernameValidation",a);}else{if(b==FormValidator.INVALID_CHARACTERS){ValidationMessageHandler.handleInvalidCharacters("usernameValidation",a);}else{if(b==FormValidator.INVALID){ValidationMessageHandler.handleInvalidNewName("usernameValidation",a);}else{ValidationMessageHandler.handleInvalidNoI18N("usernameValidation",b,a);}}}}}}}});ShowElevationDialog=Class.create();ShowElevationDialog.prototype=Object.extend(new OkCancelDialog(),{initialize:function(){this.init("showElevation");this.addEventListeners("showElevationOk","showElevationCancel");},handleSubmit:function(a){Event.stop(a);this.close();EventManager.fireEvent(Events.SHOW_ELEVATION);}});WorkoutDialog=Class.create();WorkoutDialog.prototype=Object.extend(new AbstractDialog(),{initialize:function(dialogPrefixId,wid,routeList,favRouteList,currentRoute){this.init(dialogPrefixId);this.wid=wid;if(routeList){this.routeList=eval(routeList);}if(favRouteList){this.favRouteList=eval(favRouteList);}if(currentRoute){this.currentRoute=eval(currentRoute);}var sportDropdown=$("selectSport");var options=sportDropdown.options;this.sportMap=new Array();for(var i=0;i<options.length;i++){var option=options[i];var json=eval("("+option.getAttribute("json")+")");this.sportMap[option.value]=json;}this.handleUnit();this.calendar=new DatePicker(dialogPrefixId+"DatePickerCal",dialogPrefixId+"DateContainer",dialogPrefixId+"CalContainer",dialogPrefixId+"DatePicker",dialogPrefixId+"CloseCal",dialogPrefixId+"Date");Event.observe(sportDropdown,"change",this.handleUnit.bindAsEventListener(this));Event.observe(sportDropdown,"change",this.handleDialogType.bindAsEventListener(this));Event.observe(sportDropdown,"change",this.ehUpdateRouteList.bindAsEventListener(this));Event.observe($("selectRoute"),"change",this.routeChanged.bindAsEventListener(this));this.observeInputFields();},handleDialogType:function(g){var b=$("selectSport");var a=b.selectedIndex;if(a==-1){return;}var c=this.sportMap[b.value];if(c.category=="weights"){var f=$$("tr.strengthRow");if(f){f.each(function(h,e){h.show();});}var d=$$("tr.enduranceRow");if(d){d.each(function(h,e){h.hide();});}}else{if(c.category=="endurance"){var f=$$("tr.strengthRow");if(f){f.each(function(h,e){h.hide();});}var d=$$("tr.enduranceRow");if(d){d.each(function(h,e){h.show();});}}else{var f=$$("tr.strengthRow");if(f){f.each(function(h,e){h.hide();});}var d=$$("tr.enduranceRow");if(d){d.each(function(h,e){h.hide();});}}}},handleUnit:function(i){var l=$("selectSport");var f=l.selectedIndex;if(f==-1){return;}var k=$("distanceUnit");k.update("");var c=l.options[f].value;var a=this.sportMap[c];var b=a.usunit;var d=a.metricunit;var h=document.createElement("select");h.id="distanceUnitSelection";h.name="distanceUnitSelection";var m=new Option(a.usunit,1);var g=new Option(a.metricunit,0);a.metric?g.selected=true:m.selected=true;k.appendChild(h);h.options[0]=m;h.options[1]=g;this.updateSpeedAndPace(i);Event.observe($("distanceUnitSelection"),"change",this.updateSpeedAndPace.bindAsEventListener(this));},observeInputFields:function(){Event.observe($("workoutDate"),"change",this.ehCheckDate.bindAsEventListener(this));Event.observe($("durationHH"),"change",this.ehCheckDuration.bindAsEventListener(this));Event.observe($("durationMM"),"change",this.ehCheckDuration.bindAsEventListener(this));Event.observe($("durationSS"),"change",this.ehCheckDuration.bindAsEventListener(this));Event.observe($("distance"),"change",this.ehCheckDistance.bindAsEventListener(this));Event.observe($("durationHH"),"change",this.updateSpeedAndPace.bindAsEventListener(this));Event.observe($("durationMM"),"change",this.updateSpeedAndPace.bindAsEventListener(this));Event.observe($("durationSS"),"change",this.updateSpeedAndPace.bindAsEventListener(this));Event.observe($("distance"),"change",this.updateSpeedAndPace.bindAsEventListener(this));Event.observe($("avghr"),"change",this.ehCheckHR.bindAsEventListener(this));},checkDate:function(a){var b=FormValidator.validateDate(a.value);if(!b){ValidationMessageHandler.handleInvalidDate("dateValidation",a);}else{ValidationMessageHandler.setValid("dateValidation",a);}return b;},ehCheckDate:function(b){var a=Event.element(b);this.checkDate(a);},checkDuration:function(a){var b=FormValidator.validateDoubleDigit(a.value);if(!b){ValidationMessageHandler.handleInvalidDoubleDigit("durationValidation",a);}else{ValidationMessageHandler.setValid("durationValidation",a);}return b;},ehCheckDuration:function(b){var a=Event.element(b);this.checkDuration(a);},checkDistance:function(a){if(!a.value){ValidationMessageHandler.setValid("distanceValidation",a);return true;}var b=FormValidator.validateDecimal(a.value);if(!b){ValidationMessageHandler.handleInvalidDecimal("distanceValidation",a);}else{ValidationMessageHandler.setValid("distanceValidation",a);}return b;},ehCheckDistance:function(b){var a=Event.element(b);this.checkDistance(a);},checkHR:function(a){var b=FormValidator.validateHr(a.value);if(!b){ValidationMessageHandler.handleInvalidHr("hrValidation",a);}else{ValidationMessageHandler.setValid("hrValidation",a);}return b;},ehCheckHR:function(b){var a=Event.element(b);this.checkHR(a);},convertDistance:function(b){var a=$("distanceUnitSelection").value==0;var c=$("selectSport").value;if(a){if(c=="swim"){return;}else{return Math.round((b/1000)*10)/10;}}else{if(c=="swim"){return Math.round((b/0.914)*10)/10;}else{return Math.round((b/1609.344)*10)/10;}}},updateSpeedAndPace:function(k){var b=($("distance")).value;if(!b||isNaN(b)){return;}var c=($("durationHH")).value;var d=($("durationMM")).value;var m=($("durationSS")).value;if(!c&&!d&&!m){return;}if(c&&isNaN(c)){return;}if(d&&isNaN(d)){return;}if(m&&isNaN(m)){return;}var n=0;if(c){n+=(c*3600);}if(d){n+=(d*60);}if(m){n+=m*1;}if(n==0){return;}var f=$("selectSport").value;var h=f=="swim"?n:n/3600;var q=$("distanceUnitSelection").value==0;var p="";if(q){p=f=="swim"?I18N.getMessage("jsMessage.unit.ms"):I18N.getMessage("jsMessage.unit.kmh");}else{p=f=="swim"?I18N.getMessage("jsMessage.unit.ydss"):I18N.getMessage("jsMessage.unit.mih");}var g=Math.round((b/h)*10)/10;$("avgSpeed").innerHTML=g+" "+p;var i="";if(q){i=f=="swim"?I18N.getMessage("jsMessage.unit.100m"):I18N.getMessage("jsMessage.unit.km");}else{i=f=="swim"?I18N.getMessage("jsMessage.unit.100yds"):I18N.getMessage("jsMessage.unit.mi");}var l=n/b;if(f=="swim"){l=l*100;}var o=Math.floor(l/60);var a=o+":"+Math.round((l-o*60));$("avgPace").innerHTML=a+" / "+i;},checkAll:function(){if(!this.checkDate($("workoutDate"))){return false;}if(!this.checkDuration($("durationHH"))){return false;}if(!this.checkDuration($("durationMM"))){return false;}if(!this.checkDuration($("durationSS"))){return false;}if(!this.checkDistance($("distance"))){return false;}if(!this.checkHR($("avghr"))){return false;}return true;},handleSubmit:function(g){Event.stop(g);var a=this.checkAll();if(!a){return;}var c=$(this.formId);var d=Form.serialize(c);d+="&isPlanned="+this.plan+"&isNew="+this.newWorkout;if(!this.newWorkout){d+="&wid="+this.wid;}this.close(g);var b=new Ajax.Request(Context.HOST+"/EnterWorkout",{method:"post",parameters:d,onSuccess:this.showSubmitResult.bind(this),onFailure:this.alertException.bind(this)});},showSubmitResult:function(a){this.handleMessage(a);this.fireOkEvent(a);},invokeLog:function(a){this.newWorkout=true;this.plan=false;$("workoutHeaderLabel").update(I18N.getMessage("jsMessage.workoutDialog.header.log"));this._invoke(a);},invokePlan:function(a){this.newWorkout=true;this.plan=true;$("workoutHeaderLabel").update(I18N.getMessage("jsMessage.workoutDialog.header.plan"));this._invoke(a);},invokeLoggedEdit:function(a){Event.stop(a);this.plan=false;$("workoutHeaderLabel").update(I18N.getMessage("jsMessage.workoutDialog.header.editlog"));this.doEditRequest();},invokePlannedEdit:function(a){Event.stop(a);this.plan=true;$("workoutHeaderLabel").update(I18N.getMessage("jsMessage.workoutDialog.header.editplan"));this.doEditRequest();},doEditRequest:function(){var b="wid="+this.wid+"&isPlanned="+this.plan;var a=Context.HOST+"/GetWorkout";var c=new Ajax.Request(a,{method:"get",parameters:b,onSuccess:this.showEditDialog.bind(this),onFailure:this.alertException.bind(this)});},showEditDialog:function(request){this.setValues(eval("("+request.responseText+")"));this.handleDialogType();this.handleClick();},_invoke:function(a){Event.stop(a);this.calendar.init();this.handleUnit();this.handleDialogType();this.handleClick(a);},setValues:function(b){this.newWorkout=false;$("selectSport").value=b.sport.id;this.handleUnit();this.updateRouteList(b.sport);$("workoutDate").value=b.date;$("distance").value=b.distance;if(b.distanceunit){$("distanceUnitSelection").value=0;}else{$("distanceUnitSelection").value=1;}$("notes").value=b.notes;var a=this.getDurationArray(b);if(a!=null){if(a.length>0){$("durationHH").value=a[0];}if(a.length>1){$("durationMM").value=a[1];}if(a.length>2){$("durationSS").value=a[2];}}if(b.avghr){$("avghr").value=b.avghr;}if(b.route){$("selectRoute").value=b.route.routeid;}if(b.intensity){$("intensity").value=b.intensity;}if(b.tagstring){$("tags").value=b.tagstring;}},getDurationArray:function(b){var a=b.duration;if(a!=null){return a.split(":");}return null;},clearDialog:function(){Form.reset($(this.formId));var b=$$("div.validation");b.each(function(d,c){d.innerHTML="";});var a=$$("input.dialogInput");a.each(function(d,c){d.style.backgroundColor=ValidationMessageHandler.VALID_COLOR;});},showDatePicker:function(a){Event.stop(a);this.calendar.show();},routeChanged:function(c){var a=Event.element(c);var b=a.options[a.selectedIndex];var d=b.getAttribute("distance");$("distance").value=this.convertDistance(d);this.handleUnit();this.updateSpeedAndPace();},ehUpdateRouteList:function(c){var a=Event.element(c);var b=a.options[a.selectedIndex];var d=b.value;this.updateRouteList(d);},updateRouteList:function(f){var a=$("selectRoute");a.options.length=1;if(this.currentRoute){var e=new Option(this.currentRoute.name,this.currentRoute.routeid);e.setAttribute("distance",this.currentRoute.distance);a.options[a.options.length]=e;}if(this.routeList){var b=this.routeList.result;for(var d=0;d<b.length;d++){var c=b[d];if(c.sport.id==f){var e=new Option(c.name,c.routeid);e.setAttribute("distance",c.distance);a.options[a.options.length]=e;}}}if(this.favRouteList){var b=this.favRouteList.result;for(var d=0;d<b.length;d++){var c=b[d];if(c.sport.id==f){var e=new Option(c.name,c.routeid);e.setAttribute("distance",c.distance);a.options[a.options.length]=e;}}}},fireOkEvent:function(a){if(this.newWorkout){EventManager.fireEvent(Events.WORKOUT_ADDED);}else{EventManager.fireEvent(Events.WORKOUT_UPDATED);}}});UpdateWeightDialog=Class.create();UpdateWeightDialog.prototype=Object.extend(new AbstractDialog(),{initialize:function(b,a){this.init(b);this.metricUser=a;this.datePicker=new DatePicker(b+"DatePickerCal",b+"DateContainer",b+"CalContainer",b+"DatePicker",b+"CloseCal",b+"Date");this.observeInputFields();},invoke:function(f){Event.stop(f);var g=Event.element(f).id;var d=g.split("_");if(d.length>1){var b=d[1];var a=b.split("-");var c=new Date();c.setYear(a[0]);c.setMonth(a[1]-1);c.setDate(a[2]);this.datePicker.init(c);}else{this.datePicker.init();}if(this.metricUser){$("weightUnit").value=0;}else{$("weightUnit").value=1;}this.handleClick(f);},observeInputFields:function(){Event.observe($(this.dialogPrefixId+"Date"),"change",this.ehCheckWeightDate.bindAsEventListener(this));Event.observe($("weight"),"change",this.ehCheckWeight.bindAsEventListener(this));},handleSubmit:function(g){Event.stop(g);if(!this.checkAll()){return;}var c=$(this.formId);var d=Form.serialize(c);this.weight=c.weight.value;this.metricWeightUnit=c.weightUnit.value==0;this.date=c.updateWeightDate.value;var a=Context.HOST+"/EnterWeight";this.close();var b=new Ajax.Request(a,{method:"post",parameters:d,onSuccess:this.showSubmitResult.bind(this),onFailure:this.alertException.bind(this)});},showSubmitResult:function(e){var a=this.handleMessage(e);if(!a){return;}var d=" "+(this.metricUser?I18N.getMessage("jsMessage.unit.kg"):I18N.getMessage("jsMessage.unit.lbs"));var c=new Number(this.weight);c=c.toFixed(1);if(this.metricUser!=this.metricWeightUnit){if(this.metricUser){c=new Number(this.weight*0.45359237);c=c.toFixed(1);}else{c=new Number(this.weight/0.45359237);c=c.toFixed(1);}}var b=c+d;EventManager.fireEvent(Events.WEIGHT_UPDATED,{weight:b,date:this.date});},clearDialog:function(){Form.reset($(this.formId));},checkAll:function(){var a=this.checkWeightDate($(this.dialogPrefixId+"Date"));if(!a){return false;}return this.checkWeight($("weight"));},checkWeightDate:function(a){var b=FormValidator.validateDate(a.value);if(!b){ValidationMessageHandler.handleInvalidDate("weightDateValidation",a);}else{ValidationMessageHandler.setValid("weightDateValidation",a);}return b;},ehCheckWeightDate:function(b){var a=Event.element(b);this.checkWeightDate(a);},checkWeight:function(a){var b=FormValidator.validateDecimal(a.value);if(!b){ValidationMessageHandler.handleInvalidDecimal("weightValidation",a);}else{ValidationMessageHandler.setValid("weightValidation",a);}return b;},ehCheckWeight:function(b){var a=Event.element(b);this.checkWeight(a);}});RunReportDialog=Class.create();RunReportDialog.prototype=Object.extend(new AbstractDialog(),{REPORT_ITEM_TEMPLATE_STR:'<div class="listentry" id="reportEntry_#{id}"><div class="spacer"></div><div class="spinner" style="display:block;float:left;"></div><span style="font-weight:bold;float:left;margin-left:5px;">#{name}</span><div class="spacer"></div><div>#{params}</div><div style="margin-top:10px;">Started at #{start}</div><div style="margin-top:10px;">Running report, please wait...</div><div/>',VIEW_REPORT_LINKS_TEMPLATE_STR:'<a target="_blank" href="report?action=view&report=#{type}&id=#{id}&format=html">#{name} (html)</a>&nbsp;&nbsp;<a href="report?action=view&report=#{type}&id=#{id}&format=pdf">(PDF)</a>&nbsp;&nbsp;<a href="report?action=view&report=#{type}&id=#{id}&format=xls">(MS Excel)</a>&nbsp;&nbsp;<a href="report?action=view&report=#{type}&id=#{id}&format=doc">(MS Word)</a>',VIEW_EXPORT_LINK_TEMPLATE_STR:'<a href="report?action=view&report=#{type}&id=#{id}">#{name}</a>',REPORT_DONE_ITEM_TEMPLATE_STR:'<div class="centerInnerLink" style="position: static;"><ul class="subNavList"><li><a id="rerunReport_#{id}" href="">Re-run</a> <img src="'+Context.STATIC_HOST+"/skin/"+Context.SKIN+"/images/centerarea/sub_subnav_divider.png?v="+Context.VERSION+'"/> </li><li><a id="deleteReport_#{id}" href="">Delete</a></li></ul></div>#{links}<div>#{params}</div><div class="reportListStartedMessage">Started at #{start}</div><div> Finished successfully on #{end}</div>',PARAM_TEMPLATE_STR:'<tr class="dynamicReportParam"><td><label class="dialogItemLabel" for="#{inputId}">#{label}:</label></td><td>#{input}</td></tr>',initialize:function(){this.init("runReport");this.REPORT_ITEM_TEMPLATE=new Template(this.REPORT_ITEM_TEMPLATE_STR);this.REPORT_DONE_ITEM_TEMPLATE=new Template(this.REPORT_DONE_ITEM_TEMPLATE_STR);this.PARAM_TEMPLATE=new Template(this.PARAM_TEMPLATE_STR);this.VIEW_REPORT_LINKS_TEMPLATE=new Template(this.VIEW_REPORT_LINKS_TEMPLATE_STR);this.VIEW_EXPORT_LINK_TEMPLATE=new Template(this.VIEW_EXPORT_LINK_TEMPLATE_STR);this.reportTypes=[];},showDialog:function(b){this.removeParams();var a=Event.element(b).id;this.showParams(a);this.handleClick(b);this.runningId=null;},rerunReport:function(b){Event.stop(b);var d=Event.element(b).id.replace("rerunReport_","");if(this.pe!=null){alert("You can only run one report at a time...");return;}var c="action=run&id="+d;var a=Context.HOST+"/report";new Ajax.Request(a,{method:"get",parameters:c,onSuccess:this.showRerunResult.bind(this),onFailure:this.alertException.bind(this)});},showRerunResult:function(request){if(this.handleMessage(request)){var message=eval("("+request.responseText+")");this.runningId=message.params.id;$("reportEntry_"+this.runningId).remove();this.addRunningReport(message.params);}},addReportType:function(a){this.reportTypes.push(a);},removeParams:function(){var a=$$("tr.dynamicReportParam");if(a){a.each(function(c,b){c.remove();});}$("runReportDialogName").innerHTML="";},showParams:function(d){var c=0;var a=$("runReportDialogName");var e=$("runReportParams");var b=function(f,g){if(f.id==d){paramIter=function(k,i){var h=this.PARAM_TEMPLATE.evaluate({inputId:k.name+"Id",paramName:k.name,label:k.label,input:k.input});new Insertion.Bottom(e,h);};$("reportTypeInput").value=d;a.innerHTML=f.name;reportParams=f.params;reportParams.each(paramIter.bind(this));return;}};this.reportTypes.each(b.bind(this));},handleSubmit:function(g){Event.stop(g);if(this.pe!=null){alert("You can only run one report at a time...");return;}var c=$(this.formId);var d=Form.serialize(c)+"&action=run";var a="report";var b=new Ajax.Request(a,{method:"get",parameters:d,onSuccess:this.showSubmitResult.bind(this),onFailure:this.alertException.bind(this)});},showSubmitResult:function(request){if(this.handleMessage(request)){var message=eval("("+request.responseText+")");this.runningId=message.params.id;this.addRunningReport(message.params);this.close();}},addRunningReport:function(c){var b="";if(c.parameters){b="("+c.parameters+")";}var a=this.REPORT_ITEM_TEMPLATE.evaluate({id:c.id,name:c.name,start:c.start,params:b});new Insertion.Top($("reports"),a);this.pe=new PeriodicalExecuter(this.periodicalCheck.bind(this),5);},periodicalCheck:function(a){new Ajax.Request("GetReportStatus",{method:"get",parameters:"id="+this.runningId,onSuccess:this.showReportDone.bind(this),onFailure:this.showReportCheckFailed.bind(this)});},showReportDone:function(request){var ok=this.handleMessage(request);if(!ok){this.pe.stop();this.pe=null;this.runningId=null;$("reportEntry_"+report.id).remove();return;}var message=eval("("+request.responseText+")");var report=message.model;if(report.status==1){return;}this.pe.stop();this.pe=null;this.runningId=null;var parameters="";if(report.parameters){parameters="("+report.parameters+")";}var links=report.type=="ugomo_export"?this.VIEW_EXPORT_LINK_TEMPLATE.evaluate({id:report.id,type:report.type,name:report.name}):this.VIEW_REPORT_LINKS_TEMPLATE.evaluate({id:report.id,type:report.type,name:report.name});var toInsert=this.REPORT_DONE_ITEM_TEMPLATE.evaluate({id:report.id,name:report.name,start:report.formattedstart,end:report.formattedend,params:parameters,links:links});$("reportEntry_"+report.id).innerHTML=toInsert;Event.observe($("deleteReport_"+report.id),"click",showDeleteReportDialog.bindAsEventListener(showDeleteReportDialog));Event.observe($("rerunReport_"+report.id),"click",rerunReport.bindAsEventListener(rerunReport));},showReportCheckFailed:function(b,a){this.pe.stop();this.pe=null;this.runningId=null;this.alertException(b,a);},clearDialog:function(){Form.reset($(this.formId));}});Events=Class.create();Events.prototype={initialize:function(){},WORKOUT_ADDED:"NEW_WORKOUT",UPDATE_WORKOUT:"UPDATE_WORKOUT",WORKOUT_UPDATED:"WORKOUT_UPDATED",DELETE_WORKOUT:"DELETE_WORKOUT",WORKOUT_DELETED:"DELETE_WORKOUT",SUMMARY_YEAR_CHANGED:"SUMMARY_YEAR_CHANGED",SUMMARY_MONTH_CHANGED:"SUMMARY_MONTH_CHANGED",SUMMARY_WEEK_CHANGED:"SUMMARY_WEEK_CHANGED",GOAL_ADDED:"GOAL_ADDED",GOAL_EDITED:"GOAL_EDITED",GOAL_DELETED:"GOAL_DELETED",THREAD_ADDED:"THREAD_ADDED",NOT_ENOUGH_ROUTE_POINTS:"NOT_ENOUGH_ROUTE_POINTS",SHOW_ELEVATION:"SHOW_ELEVATION",ELEVATION_REQUEST_ERROR:"ELEVATION_REQUEST_ERROR",CLEAR_ROUTE_ERROR:"CLEAR_ROUTE_ERROR",ROUTE_DELETED:"ROUTE_DELETED",ROUTE_EDITED:"ROUTE_EDITED",WORKOUT_COMMENT_ADDED:"WORKOUT_COMMENT_ADDED",WORKOUT_COMMENT_DELETED:"WORKOUT_COMMENT_DELETED",WORKOUT_COMMENT_EDITED:"WORKOUT_COMMENT_EDITED",WEIGHT_UPDATED:"WEIGHT_UPDATED"};EventManager=Class.create();EventManager.prototype={initialize:function(){Events=new Events();this.eventMap=new Array();},registerEventHandler:function(c,b){var a=this.eventMap[c];if(a==null){a=new Array();}a.push(b);this.eventMap[c]=a;},fireEvent:function(e){if(e==null){return;}var a=this.eventMap[e];if(a==null){return;}var b=new Array();for(var c=1;c<arguments.length;c++){b.push(arguments[c]);}for(var c=0;c<a.length;c++){var d=a[c];d.apply(null,b);}}};EventManager=new EventManager();LoadRoutes=Class.create();LoadRoutes.prototype=Object.extend(new ServerAction(),{ROUTE_TEMPLATE_STR:'<div class="listentry"><div class="listdate">Created on #{createdOn} by <a href="#{host}/user/#{userId} %>">#{userId}</a></div><div><a href="#{host}/route/#{id}">#{name}</a>#{distance} #{sport}</div><div>#{city} , #{country}</div><div>#{notes}</div></div>',initialize:function(){this.ROUTE_TEMPLATE=new Template(this.ROUTE_TEMPLATE_STR);},navigatePublicRoutes:function(a){this.navigate(a,false);},navigateUserRoutes:function(a){this.navigate(a,true);},navigate:function(h,b){Event.stop(h);scroll(0,0);var a=$("loadingArea");a.style.display="block";var d=Event.element(h);if(d.tagName=="IMG"){d=d.parentNode;}var g=d.href.split("Routes?")[1];var i="?"+g;if(b){i+="&isUserRoutes=true";}var c=Context.HOST+"/FilterRoutes";var f=new Ajax.Request(c,{method:"get",parameters:i,onSuccess:this.showSearchResult.bind(this),onFailure:this.alertException.bind(this)});},clearResultArea:function(){var a=$("routesDiv");a.update("");},showSearchResult:function(request){var resultJSON=eval("("+request.responseText+")");var routes=resultJSON.result;this.clearResultArea();var routesDiv=$("routesDiv");for(var i=0;i<routes.length;i++){var route=routes[i];var toInsert=this.ROUTE_TEMPLATE.evaluate({host:Context.HOST,createdOn:entityEncode(route.createdon),userId:entityEncode(route.userid),id:entityEncode(route.routeid),name:entityEncode(route.name),distance:entityEncode(route.converteddistance),sport:entityEncode(route.sport),city:entityEncode(route.city),country:entityEncode(route.country),notes:entityEncode(route.notes)});new Insertion.Bottom(routesDiv,toInsert);}var navigateFunction=resultJSON.publicRoutes?this.navigatePublicRoutes.bindAsEventListener(this):this.navigateUserRoutes.bindAsEventListener(this);var loadingArea=$("loadingArea");loadingArea.style.display="none";}});var LoadRoutes=new LoadRoutes();LoadSummary=Class.create();LoadSummary.prototype=Object.extend(new ServerAction(),{YEAR_TABLE_ID:"summaryTableYear",MONTH_TABLE_ID:"summaryTableMonth",WEEK_TABLE_ID:"summaryTableWeek",SUMMARY_ROW_TEMPLATE_STR:'<tr class="#{class}"><td>#{sport}</td><td>#{duration}</td><td>#{distance}</td></tr>',initialize:function(a){var b=this.loadSummary.bindAsEventListener(this);EventManager.registerEventHandler(Events.WORKOUT_ADDED,b);EventManager.registerEventHandler(Events.WORKOUT_UPDATED,b);EventManager.registerEventHandler(Events.WORKOUT_DELETED,b);EventManager.registerEventHandler(Events.SUMMARY_YEAR_CHANGED,this.loadYearSummary.bindAsEventListener(this));EventManager.registerEventHandler(Events.SUMMARY_MONTH_CHANGED,this.loadMonthSummary.bindAsEventListener(this));EventManager.registerEventHandler(Events.SUMMARY_WEEK_CHANGED,this.loadWeekSummary.bindAsEventListener(this));this.yearSummarySelector=new SummarySelector("previousYearSummary","nextYearSummary","yearSummarySelector",Events.SUMMARY_YEAR_CHANGED);this.monthSummarySelector=new SummarySelector("previousMonthSummary","nextMonthSummary","monthSummarySelector",Events.SUMMARY_MONTH_CHANGED);this.weekSummarySelector=new SummarySelector("previousWeekSummary","nextWeekSummary","weekSummarySelector",Events.SUMMARY_WEEK_CHANGED);Event.observe(window,"load",this.clearAllSelectElements.bindAsEventListener(this));this.serverCall=a;this.SUMMARY_ROW_TEMPLATE=new Template(this.SUMMARY_ROW_TEMPLATE_STR);},_loadSummary:function(e,b,c){if(c){var a=$(c);a.style.display="block";}else{$("workoutYearSpinner").style.display="block";$("workoutMonthSpinner").style.display="block";$("workoutWeekSpinner").style.display="block";}if(this.groupId){e+="&groupId="+this.groupId;}if(this.userId){e+="&userId="+this.userId;}var d=new Ajax.Request(this.serverCall,{method:"get",parameters:e,onSuccess:b,onFailure:this.alertException.bind(this)});},loadSummary:function(a){this._loadSummary("",this.showSummary.bind(this));this.loadWorkoutChart();},loadWorkoutChart:function(a){if(document.workoutDistributionChart&&document.workoutDistributionChart.SetVariable){document.workoutDistributionChart.SetVariable("update_url",Context.HOST+"/GetWorkoutDistributionXml");}},loadYearSummary:function(f){Event.stop(f);var b=$("yearSummarySelector");var d=b.value;var c=d;if(!c){var a=new Date();c=a.getFullYear();}var g="year="+c;this._loadSummary(g,this.updateYearSummary.bind(this),"workoutYearSpinner");},loadMonthSummary:function(g){Event.stop(g);var i=$("monthSummarySelector");var c=i.value;var a=new Date();var d=a.getFullYear();var f=a.getMonth()+1;a.setDate(1);if(c){var b=c.split("-");d=b[0];f=b[1];a.setYear(d);a.setMonth(f-1);}var h="month="+c;this._loadSummary(h,this.updateMonthSummary.bind(this),"workoutMonthSpinner");},loadWeekSummary:function(f){Event.stop(f);var d=$("weekSummarySelector");var c=d.value;var a=new Date();if(c){var b=c.split("-");year=b[0];month=b[1];day=b[2];a.setYear(year);a.setMonth(month-1);a.setDate(day);}var g="week="+c;this._loadSummary(g,this.updateWeekSummary.bind(this),"workoutWeekSpinner");},clearSummaryTable:function(d){var c=$(d);var e=c.getElementsByTagName("tr");var b=new Array();for(var a=0;a<e.length;a++){var f=e[a];b.push(f);}for(var a=0;a<b.length;a++){var f=b[a];Element.remove(f);}},clearAllSelectElements:function(a){this.clearYearSelectElement();this.clearMonthSelectElement();this.clearWeekSelectElement();},clearYearSelectElement:function(){var a=new Date();var b=a.getFullYear();$("yearSummarySelector").value=b;this.yearSummarySelector.updateSelectorStyles();},clearMonthSelectElement:function(c){var b=new Date();var d=b.getFullYear();var e=b.getMonth()+1;var a="1";$("monthSummarySelector").value=d+"-"+e+"-"+a;this.monthSummarySelector.updateSelectorStyles();},clearWeekSelectElement:function(a){$("weekSummarySelector").value=this.getStartOfThisWeek();this.weekSummarySelector.updateSelectorStyles();},getStartOfThisWeek:function(){var c=new Date();var b=c.getDay();if(b==0){b=6;}else{b--;}c=YAHOO.widget.DateMath.subtract(c,YAHOO.widget.DateMath.DAY,b);var d=c.getFullYear();var e=c.getMonth()+1;var a=c.getDate();return d+"-"+e+"-"+a;},updateTable:function(k,c){this.clearSummaryTable(c);var p=k.children;var o=$(c);var f=o.getElementsByTagName("tbody")[0];var e=0;for(e=0;e<p.length;e++){var m=p[e];var d="";var b="";if(c==this.YEAR_TABLE_ID){d=m.ytddurationstring;b=m.ytddistancestring;}else{if(c==this.MONTH_TABLE_ID){d=m.mtddurationstring;b=m.mtddistancestring;}else{if(c==this.WEEK_TABLE_ID){d=m.wtddurationstring;b=m.wtddistancestring;}}}var h=(e%2==0)?"evenStatTableRow":"oddStatTableRow";var l=this.SUMMARY_ROW_TEMPLATE.evaluate({"class":h,sport:entityEncode(m.sport.localizedname),duration:entityEncode(d),distance:entityEncode(b)});new Insertion.Bottom(f,l);}var n="";if(c==this.YEAR_TABLE_ID){n=k.ytdtotal;}else{if(c==this.MONTH_TABLE_ID){n=k.mtdtotal;}else{if(c==this.WEEK_TABLE_ID){n=k.wtdtotal;}}}var g="";if(c==this.YEAR_TABLE_ID){g=k.ytddistancetotal;}else{if(c==this.MONTH_TABLE_ID){g=k.mtddistancetotal;}else{if(c==this.WEEK_TABLE_ID){g=k.wtddistancetotal;}}}var h=(e%2==0)?"evenStatTableRowTotal":"oddStatTableRowTotal";var a=this.SUMMARY_ROW_TEMPLATE.evaluate({"class":h,sport:"Total",duration:entityEncode(n),distance:entityEncode(g)});new Insertion.Bottom(f,a);},updateYearSummary:function(request){var summaryJSON=eval("("+request.responseText+")");this.updateTable(summaryJSON,this.YEAR_TABLE_ID);var loadingArea=$("workoutYearSpinner");loadingArea.style.display="none";},updateYearSelector:function(b){$("yearSummarySelector").update("");var d=b.summaryyears;var a=new Date();for(var c=0;c<d.length;c++){$("yearSummarySelector").options[c]=new Option(d[c].year,d[c].year);if(a.getFullYear()==d[c].year){$("yearSummarySelector").options[c].selected=true;}}},updateMonthSummary:function(request){var summaryJSON=eval("("+request.responseText+")");this.updateTable(summaryJSON,this.MONTH_TABLE_ID);var loadingArea=$("workoutMonthSpinner");loadingArea.style.display="none";},updateMonthSelector:function(d){$("monthSummarySelector").update("");var a=d.summarymonths;var b=new Date();for(var c=0;c<a.length;c++){$("monthSummarySelector").options[c]=new Option(a[c].display,a[c].value);if(b.getFullYear()==a[c].year&&(b.getMonth()+1)==a[c].month){$("monthSummarySelector").options[c].selected=true;}}},updateWeekSummary:function(request){var summaryJSON=eval("("+request.responseText+")");this.updateTable(summaryJSON,this.WEEK_TABLE_ID);var loadingArea=$("workoutWeekSpinner");loadingArea.style.display="none";},updateWeekSelector:function(d){$("weekSummarySelector").update("");var e=d.summaryweeks;var b=new Date();var a=this.getStartOfThisWeek();for(var c=0;c<e.length;c++){$("weekSummarySelector").options[c]=new Option(e[c].display,e[c].value);if(a==e[c].value){$("weekSummarySelector").options[c].selected=true;}}},showSummary:function(request){var summaryJSON=eval("("+request.responseText+")");this.updateYearSelector(summaryJSON.yearsummary);this.yearSummarySelector.updateSelectorStyles();this.updateWeekSelector(summaryJSON.weeksummary);this.weekSummarySelector.updateSelectorStyles();this.updateMonthSelector(summaryJSON.monthsummary);this.monthSummarySelector.updateSelectorStyles();this.updateTable(summaryJSON.yearsummary,this.YEAR_TABLE_ID);this.updateTable(summaryJSON.monthsummary,this.MONTH_TABLE_ID);this.updateTable(summaryJSON.weeksummary,this.WEEK_TABLE_ID);$("workoutYearSpinner").style.display="none";$("workoutMonthSpinner").style.display="none";$("workoutWeekSpinner").style.display="none";},setGroupId:function(a){this.groupId=a;},setUserId:function(a){this.userId=a;}});RefreshWorkoutChart=Class.create();RefreshWorkoutChart.prototype={initialize:function(){var a=this.refreshChart.bindAsEventListener(this);},refreshChart:function(){var a=$("workoutChartImage");a.src="images/loading.gif";var b=new Date();var c=b.getTime();a.src="GetChartImage?nocache="+c.valueOf();}};var RefreshWorkoutChart=new RefreshWorkoutChart();AbstractWorkoutView=Class.create();AbstractWorkoutView.prototype=Object.extend(new ServerAction(),{initialize:function(){},init:function(){this.resultArea=$("resultArea");this.loadingArea=$("loadingMainArea");},handleClick:function(a){if(a!=null){Event.stop(a);}this.clearAll();this.__handleClick(a);},clearAll:function(){this.loadingArea.style.display="block";},clearResultArea:function(){this.resultArea.style.display="none";while(this.resultArea.hasChildNodes()){this.resultArea.removeChild(this.resultArea.firstChild);}},showResultArea:function(){this.loadingArea.style.display="none";this.resultArea.style.display="block";}});AbstractListView=Class.create();AbstractListView.prototype=Object.extend(new AbstractWorkoutView(),{LIST_NAV_TEMPLATE_STR:"#{previousLink}#{nextLink}",PREVIOUS_LINK_TEMPLATE_STR:'<a href="#{host}/#{uri}" id="#{indicatorId}" class="leftIndicator">&lt;</a><a href="#{host}/#{uri}" id="#{id}" style="float:left;">#{text}</a><div style="float:left;">&nbsp;</div>',NEXT_LINK_TEMPLATE_STR:'<a href="#{host}/#{uri}" id="#{id}" style="float:left;">#{text}</a><a href="#{host}/#{uri}" id="#{indicatorId}" class="rightIndicator">&gt;</a>	',LIST_ITEM_TEMPLATE_STR:'<div class="#{listEntryClass}" id=#{id}><div class="listdate">#{dateString}</div></div>',WORKOUT_ITEM_TEMPLATE_STR:'<div><div><div class=spacer></div><div class="loggedEventIcon"></div><div style="float:left;"><a href="#{host}/workout/#{wid}" class="blogsport">#{sport}</a>&nbsp<span>#{formattedValues}</span></div><div class=spacer></div></div>#{notes}</div>',PLANNED_WORKOUT_ITEM_TEMPLATE_STR:'<div><div><div class=spacer></div><div class="plannedEventIcon"></div><div style="float:left;"><a href="#{host}/planned/#{wid}" class="blogsport">#{sport}</a>&nbsp<span>#{formattedValues}</span></div><div class=spacer></div></div>#{notes}</div>',WORKOUT_NOTES_TEMPLATE_STR:'<div class="listworkoutnotes">#{notes}</div>',WEIGHT_TEMPLATE_STR:'<div class="weekDayWeight" id="#{weightId}"><div class="spacer"></div><div class="weightIcon"></div><div style="float:left;"><a href="" id="#{updateId}">#{weight}</a></div><div class="spacer"></div></div>',initListView:function(a,g,f,e,c,b){this.init();this.listId=a;this.navId=g;this.previousId=f;this.nextId=e;this.previousText=c;this.nextText=b;var d=this.handleClick.bindAsEventListener(this);EventManager.registerEventHandler(Events.WORKOUT_ADDED,d);EventManager.registerEventHandler(Events.WORKOUT_UPDATED,d);EventManager.registerEventHandler(Events.WORKOUT_DELETED,d);EventManager.registerEventHandler(Events.WEIGHT_UPDATED,this.updateWeight.bindAsEventListener(this));this.LIST_NAV_TEMPLATE=new Template(this.LIST_NAV_TEMPLATE_STR);this.PREVIOUS_LINK_TEMPLATE=new Template(this.PREVIOUS_LINK_TEMPLATE_STR);this.NEXT_LINK_TEMPLATE=new Template(this.NEXT_LINK_TEMPLATE_STR);this.LIST_ITEM_TEMPLATE=new Template(this.LIST_ITEM_TEMPLATE_STR);this.WORKOUT_ITEM_TEMPLATE=new Template(this.WORKOUT_ITEM_TEMPLATE_STR);this.WORKOUT_NOTES_TEMPLATE=new Template(this.WORKOUT_NOTES_TEMPLATE_STR);this.PLANNED_WORKOUT_ITEM_TEMPLATE=new Template(this.PLANNED_WORKOUT_ITEM_TEMPLATE_STR);this.WEIGHT_TEMPLATE=new Template(this.WEIGHT_TEMPLATE_STR);},clearList:function(){var a=$(this.listId);a.update("");var b=$(this.navId);b.update("");},getView:function(){},getPreviousParameters:function(a){},getNextParameters:function(a){},showView:function(request){this.clearList();var listDiv=$(this.listId);list=eval("("+request.responseText+")");var insertPreviousLink="";if(list.showprevious){insertPreviousLink=this.PREVIOUS_LINK_TEMPLATE.evaluate({host:Context.HOST,uri:entityEncode(this.getPreviousParameters(list)),id:entityEncode(this.previousId),indicatorId:entityEncode(this.previousId+"Indicator"),text:entityEncode(this.previousText)});}var insertNextLink="";if(list.shownext){insertNextLink=this.NEXT_LINK_TEMPLATE.evaluate({host:Context.HOST,uri:entityEncode(this.getNextParameters(list)),id:entityEncode(this.nextId),indicatorId:entityEncode(this.nextId+"Indicator"),text:entityEncode(this.nextText)});}var insertNav=this.LIST_NAV_TEMPLATE.evaluate({previousLink:insertPreviousLink,nextLink:insertNextLink});new Insertion.Bottom($(this.navId),insertNav);if(list.showprevious){Event.observe($(this.previousId),"click",this.handleClick.bindAsEventListener(this));Event.observe($(this.previousId+"Indicator"),"click",this.handleClick.bindAsEventListener(this));}if(list.shownext){Event.observe($(this.nextId),"click",this.handleClick.bindAsEventListener(this));Event.observe($(this.nextId+"Indicator"),"click",this.handleClick.bindAsEventListener(this));}var days=list.children;for(var i=0;i<days.length;i++){var day=days[i];var listEntryClass=day.today?"todaylistentry":"listentry";var insertItem=this.LIST_ITEM_TEMPLATE.evaluate({listEntryClass:listEntryClass,dateString:entityEncode(day.datestring),id:day.dayid});new Insertion.Bottom(listDiv,insertItem);this.addWorkouts(day.workouts,day.dayid,this.WORKOUT_ITEM_TEMPLATE);this.addWorkouts(day.plannedworkouts,day.dayid,this.PLANNED_WORKOUT_ITEM_TEMPLATE);if(day.weight&&day.weight.weight){var weightId="weight_"+day.year+"-"+day.month+"-"+day.dayinmonth;var updateId="updateWeight_"+day.year+"-"+day.month+"-"+day.dayinmonth;var weightInsert=this.WEIGHT_TEMPLATE.evaluate({weight:day.weight.formattedweight,weightId:weightId,updateId:updateId});new Insertion.Bottom($(day.dayid),weightInsert);if(typeof updateWeight!="undefined"){Event.observe($(updateId),"click",updateWeight.invoke.bindAsEventListener(updateWeight));}}}this.showResultArea();},addWorkouts:function(f,b,e){if(!f){return;}for(var d=0;d<f.length;d++){var g=f[d];var a="";if(g.notes){a=this.WORKOUT_NOTES_TEMPLATE.evaluate({notes:entityEncode(g.notes)});}var c=e.evaluate({host:Context.HOST,wid:g.wid,sport:entityEncode(g.sportname),formattedValues:entityEncode(g.formattedvalues),notes:a});new Insertion.Bottom($(b),c);}},updateWeight:function(d){if(!d){return;}var b="weight_"+d.date;if($(b)){$(b).remove();}var c="updateWeight_"+d.date;var a=this.WEIGHT_TEMPLATE.evaluate({weight:d.weight,weightId:b,updateId:c});new Insertion.Bottom($("day_"+d.date),a);Event.observe($(c),"click",updateWeight.invoke.bindAsEventListener(updateWeight));}});BlogView=Class.create();BlogView.prototype=Object.extend(new AbstractListView(),{initialize:function(g,a,h,f,d,c,b,e){this.initListView(a,h,f,d,c,b,e);this.page=g;},__handleClick:function(g){var h=1;var d="";if(g){try{var f=g.element();if(f.tagName!="A"){f=f.parentNode;}var c=f.getAttribute("href");var k=c.split("page-");h=k[1];if(!h){h=1;}d="";k=c.split("user/");if(k.length>1){split1=k[1].split("/");d=split1[0];if(!d){d="";}}}catch(i){}}var l="page="+h+"&user="+d;var b=Context.HOST+"/GetWorkouts";var a=new Ajax.Request(b,{method:"get",parameters:l,onSuccess:this.showView.bind(this),onFailure:this.alertException.bind(this)});},getView:function(){return"list";},getPreviousParameters:function(a){return"user/"+a.user+"/page-"+a.previous;},getNextParameters:function(a){return"user/"+a.user+"/page-"+a.next;}});MonthSelector=Class.create();MonthSelector.prototype={MONTH_SELECTOR_TEMPLATE_STR:'<div id="monthSelectorClose" class="monthSelectorClose">X</div><table class="monthSelectorTable"><tr><td class="monthSelectorYear" colspan=3><div class="spacer"></div><div class="leftIndicator" id="monthSelectorPrevYear">&lt;</div><div id="monthSelectorYear" style="float:left;">#{year}</div><div class="rightIndicator" id="monthSelectorNextYear">&gt;</div><div class="spacer"></div></td></tr><tr><td><a href="" id="monthSelectorMonth_1">Jan</a></td><td><a href="" id="monthSelectorMonth_2">Feb</a></td><td><a href="" id="monthSelectorMonth_3">Mar</a></td></tr><tr><td><a href="" id="monthSelectorMonth_4">Apr</a></td><td><a href="" id="monthSelectorMonth_5">May</a></td><td><a href="" id="monthSelectorMonth_6">Jun</a></td></tr><tr><td><a href="" id="monthSelectorMonth_7">Jul</a></td><td><a href="" id="monthSelectorMonth_8">Aug</a></td><td><a href="" id="monthSelectorMonth_9">Sep</a></td></tr><tr><td><a href="" id="monthSelectorMonth_10">Oct</a></td><td><a href="" id="monthSelectorMonth_11">Nov</a></td><td><a href="" id="monthSelectorMonth_12">Dec</a></td></tr></table>',initialize:function(a){this.view=a;this.MONTH_SELECTOR_TEMPLATE=new Template(this.MONTH_SELECTOR_TEMPLATE_STR);},show:function(d){Event.stop(d);$("monthSelectorDiv").update("");var f="";var h="";this.user="";if(d!=null){var c=Event.element(d);var a=c.getAttribute("href");var k=a.split("/month/");var g=k[1].split("-");h=g[0];if(!h){h="";}f=g[1];if(!f){f="";}k=a.split("/user/");if(k.length>1){g=k[1].split("/");this.user=g[0];if(!this.user){user="";}}}var l=this.MONTH_SELECTOR_TEMPLATE.evaluate({year:entityEncode(h)});new Insertion.Bottom($("monthSelectorDiv"),l);Event.observe($("monthSelectorPrevYear"),"click",this.prevYear.bindAsEventListener(this));Event.observe($("monthSelectorNextYear"),"click",this.nextYear.bindAsEventListener(this));Event.observe($("monthSelectorClose"),"click",this.close.bindAsEventListener(this));for(var b=1;b<13;b++){Event.observe($("monthSelectorMonth_"+b),"click",this.handleSelection.bindAsEventListener(this));}Effect.BlindDown($("monthSelectorDiv"));},nextYear:function(b){Event.stop(b);var a=($("monthSelectorYear").innerHTML)*1;a++;$("monthSelectorYear").update(a);},prevYear:function(b){Event.stop(b);var a=($("monthSelectorYear").innerHTML)*1;a--;$("monthSelectorYear").update(a);},close:function(a){if(a){Event.stop(a);}Effect.BlindUp($("monthSelectorDiv"));},handleSelection:function(d){Event.stop(d);var a=Event.element(d);var f=a.id;var c=f.replace("monthSelectorMonth_","");var b=$("monthSelectorYear").innerHTML;this.close();this.view.doMonthRequest(b,c,this.user);}};MonthView=Class.create();MonthView.prototype=Object.extend(new AbstractWorkoutView(),{ROW_TEMPLATE_STR:'<tr class="monthWeek" id=#{id}></tr>',TD_TEMPLATE_STR:'<td class=#{dayClass}><div class="monthDayContent" id="day_#{dayId}"><div class="monthDate">#{dayInMonth}</div><div class="workoutContainer" id="wc_#{dayId}"></div><div class="workoutContainer" id="pwc_#{dayId}"></div></div></td>',WORKOUT_TEMPLATE_STR:'<div class="monthDayWorkout"><div class="spacer"></div><div class="loggedEventIcon"></div><div style="float:left;"><a id="#{wid}" title="#{title}" href="#{host}/workout/#{wid}">#{sport}</a></div><div class="spacer"></div></div>',PLANNED_WORKOUT_TEMPLATE_STR:'<div class="monthDayPlannedWorkout"><div class="spacer"></div><div class="plannedEventIcon"></div><div style="float:left;"><a id="#{wid}" title="#{title}" href="#{host}/planned/#{wid}">#{sport}</a></div><div class="spacer"></div></div>',WEIGHT_TEMPLATE_STR:'<div class="monthDayWeight" id="#{weightId}"><div class="spacer"></div><div class="weightIcon"></div><div style="float:left;"><a href="" id="#{updateId}">#{weight}</a></div><div class="spacer"></div></div>',initialize:function(){this.init();var a=this.handleClick.bindAsEventListener(this);EventManager.registerEventHandler(Events.WORKOUT_ADDED,a);EventManager.registerEventHandler(Events.WORKOUT_UPDATED,a);EventManager.registerEventHandler(Events.WORKOUT_DELETED,a);EventManager.registerEventHandler(Events.PLANNED_WORKOUT_ADDED,a);EventManager.registerEventHandler(Events.PLANNED_WORKOUT_UPDATED,a);EventManager.registerEventHandler(Events.PLANNED_WORKOUT_DELETED,a);EventManager.registerEventHandler(Events.WEIGHT_UPDATED,this.handleUpdatedWeight.bindAsEventListener(this));this.ROW_TEMPLATE=new Template(this.ROW_TEMPLATE_STR);this.TD_TEMPLATE=new Template(this.TD_TEMPLATE_STR);this.WORKOUT_TEMPLATE=new Template(this.WORKOUT_TEMPLATE_STR);this.PLANNED_WORKOUT_TEMPLATE=new Template(this.PLANNED_WORKOUT_TEMPLATE_STR);this.WEIGHT_TEMPLATE=new Template(this.WEIGHT_TEMPLATE_STR);var b=new MonthSelector(this);Event.observe($("monthHeader"),"click",b.show.bindAsEventListener(b));},__handleClick:function(d){var f="";var i="";var b="";if(d){try{var c=Event.element(d);if(c.tagName=="DIV"){c=c.parentNode;}var a=c.getAttribute("href");var k=a.split("month/");var h=k[1].split("-");i=h[0];if(!i){i="";}f=h[1];if(!f){f="";}b="";k=a.split("/user/");if(k.length>1){h=k[1].split("/");b=h[0];if(!b){b="";}}}catch(g){}}this.doMonthRequest(i,f,b);},doMonthRequest:function(c,f,a){var d="month="+f+"&year="+c;if(a){d+="&user="+a;}var b=Context.HOST+"/GetMonth";var e=new Ajax.Request(b,{method:"get",parameters:d,onSuccess:this.showMonth.bind(this),onFailure:this.alertException.bind(this)});},clearMonthTable:function(){var a=$("monthTable");var d=a.getElementsByTagName("tr");var c=new Array();for(var b=0;b<d.length;b++){var e=d[b];if(e.className=="monthWeek"){c.push(e);}}for(var b=0;b<c.length;b++){var e=c[b];Element.remove(e);}},showMonth:function(request){var month=eval("("+request.responseText+")");var previousLink=$("previousWorkoutMonth");previousLink.href=previousLink.href.split("/month/")[0]+"/month/"+month.previousyear+"-"+month.previousmonth;var nextLink=$("nextWorkoutMonth");nextLink.href=nextLink.href.split("/month/")[0]+"/month/"+month.nextyear+"-"+month.nextmonth;$("monthHeader").update(entityEncode(month.formattedmonth));var weeks=month.children;this.clearMonthTable();var table=$("monthTable");var tbody=table.getElementsByTagName("tbody")[0];for(var i=0;i<weeks.length;i++){var week=weeks[i];var days=week.children;var rowInsert=this.ROW_TEMPLATE.evaluate({id:"row_"+i});new Insertion.Bottom(tbody,rowInsert);for(j=1;j<=days.length;j++){var day=WeekUtil.getDay(days,j);var tdInsert=this.TD_TEMPLATE.evaluate({dayInMonth:(day.dayinmonth>0?entityEncode(day.dayinmonth):""),dayId:entityEncode(day.month+"-"+day.dayinmonth),dayClass:entityEncode(day.today?"monthDayToday":"monthDay")});new Insertion.Bottom($("row_"+i),tdInsert);var date=day.dayinmonth;if(date!=-1){var workouts=day.workouts;if(workouts){for(var k=0;k<workouts.length;k++){var workout=workouts[k];var workoutInsert=this.WORKOUT_TEMPLATE.evaluate({host:Context.HOST,wid:workout.wid,title:entityEncode(workout.formattedvalues),sport:entityEncode(workout.sportname)});new Insertion.Bottom($("wc_"+day.month+"-"+day.dayinmonth),workoutInsert);}}var plannedWorkouts=day.plannedworkouts;if(plannedWorkouts){for(var k=0;k<plannedWorkouts.length;k++){var plannedWorkout=plannedWorkouts[k];var plannedWorkoutInsert=this.PLANNED_WORKOUT_TEMPLATE.evaluate({host:Context.HOST,wid:plannedWorkout.wid,title:entityEncode(plannedWorkout.formattedvalues),sport:entityEncode(plannedWorkout.sportname)});new Insertion.Bottom($("pwc_"+day.month+"-"+day.dayinmonth),plannedWorkoutInsert);}}var weight=day.weight;if(weight&&weight.weight){var dayId="day_"+day.month+"-"+day.dayinmonth;var weightId="weight_"+day.month+"-"+day.dayinmonth;var updateId="updateWeight_"+day.year+"-"+day.month+"-"+day.dayinmonth;var weightInsert=this.WEIGHT_TEMPLATE.evaluate({weight:weight.formattedweight,weightId:weightId,updateId:updateId});new Insertion.Bottom($(dayId),weightInsert);if(typeof updateWeight!="undefined"){Event.observe($(updateId),"click",updateWeight.invoke.bindAsEventListener(updateWeight));}}}}}this.showResultArea();},handleUpdatedWeight:function(f){if(f&&f.weight){var d=f.date.split("-");var c="day_"+d[1]+"-"+d[2];var b="weight_"+d[1]+"-"+d[2];if($(b)){Element.remove($(b));}var e="updateWeight_"+d[0]+"-"+d[1]+"-"+d[2];var a=this.WEIGHT_TEMPLATE.evaluate({weight:f.weight,weightId:b,updateId:e});new Insertion.Bottom($(c),a);Event.observe($(e),"click",updateWeight.invoke.bindAsEventListener(updateWeight));}}});ViewWorkoutView=Class.create();ViewWorkoutView.prototype=Object.extend(new ServerAction(),{COMMENT_TEMPLATE_STR:'<div id="commentText_#{cid}" class="workoutComment"><div class="workoutCommentEditContainer"><ul class="subNavList">#{editListItem}#{deleteListItem}</ul></div><div>#{comment}</div><div class="workoutCommentPostedBy">Posted by: <a href="user/#{user}">#{user}</a> on #{commentTime}#{editedTime}</div></div>',EDITED_TIME_TEMPLATE_STR:"<br/>(Edited on #{editTime})",EDIT_LIST_ITEM_TEMPLATE_STR:'<li><a href="" id="editComment_#{cid}">Edit</a><img src="'+Context.STATIC_HOST+"/skin/"+Context.SKIN+"/images/centerarea/sub_subnav_divider.png?v="+Context.VERSION+'"/></li>',DELETE_LIST_ITEM_TEMPLATE_STR:'<li><a href="" id="deleteComment_#{cid}">Delete</a></li>',initialize:function(c,d,e,b,a){this.wid=c;this.workoutUser=d;this.loggedInUser=e;this.isPlanned=b;this.isMetric=a;EventManager.registerEventHandler(Events.WORKOUT_COMMENT_ADDED,this.loadComments.bindAsEventListener(this));EventManager.registerEventHandler(Events.WORKOUT_COMMENT_DELETED,this.loadComments.bindAsEventListener(this));EventManager.registerEventHandler(Events.WORKOUT_COMMENT_EDITED,this.loadComments.bindAsEventListener(this));EventManager.registerEventHandler(Events.WORKOUT_UPDATED,this.loadWorkout.bindAsEventListener(this));this.COMMENT_TEMPLATE=new Template(this.COMMENT_TEMPLATE_STR);this.EDITED_TIME_TEMPLATE=new Template(this.EDITED_TIME_TEMPLATE_STR);this.EDIT_LIST_ITEM_TEMPLATE=new Template(this.EDIT_LIST_ITEM_TEMPLATE_STR);this.DELETE_LIST_ITEM_TEMPLATE=new Template(this.DELETE_LIST_ITEM_TEMPLATE_STR);},loadWorkout:function(){this.doLoad(Context.HOST+"/GetWorkout");},doLoad:function(a){var c="wid="+this.wid;var b=new Ajax.Request(a,{method:"get",parameters:c,onSuccess:this.showUpdatedWorkout.bind(this),onFailure:this.alertException.bind(this)});},showUpdatedWorkout:function(request){var workout=eval("("+request.responseText+")");$("viewWorkoutSport").update(entityEncode(workout.sport));if(workout.formattedduration){$("viewWorkoutDurationDiv").show();$("viewWorkoutDuration").update(entityEncode(workout.formattedduration));}else{$("viewWorkoutDurationDiv").hide();}if(workout.distancestring){$("viewWorkoutDistanceDiv").show();$("viewWorkoutDistance").update(entityEncode(workout.distancestring));}else{$("viewWorkoutDistanceDiv").hide();}if(workout.avghr&&workout.avghr>0){$("viewWorkoutAvgHRDiv").show();$("viewWorkoutHR").update(entityEncode(workout.avghr));}else{$("viewWorkoutAvgHRDiv").hide();}if(workout.avgspeedstring){$("viewWorkoutAvgSpeedDiv").show();$("viewWorkoutSpeed").update(entityEncode(workout.avgspeedstring));}else{$("viewWorkoutAvgSpeedDiv").hide();}if(workout.avgpacestring){$("viewWorkoutAvgPaceDiv").show();$("viewWorkoutPace").update(entityEncode(workout.avgpacestring));}else{$("viewWorkoutAvgPaceDiv").hide();}if(workout.notes){$("viewWorkoutNotesDiv").update(entityEncode(workout.notes));$("viewWorkoutNotesDiv").show();}else{$("viewWorkoutNotesDiv").hide();}if(workout.route){$("viewWorkoutRouteDiv").show();$("viewWorkoutRouteName").href=Context.HOST+"/route/"+workout.route.routeid;$("viewWorkoutRouteName").update(entityEncode(workout.route.name));if(!viewRouteMap){viewRouteMap=new GMap2($("viewRouteMap"));viewRouteMap.setUIToDefault();}if(workout.route.polyline.elevation){$("routeElevationChartDiv").show();}else{$("routeElevationChartDiv").hide();}viewRouteMap.clearOverlays();viewWorkoutViewRoute=new ViewRoute(viewRouteMap,workout.route,false,false,this.isMetric,true);}if(workout.intensity){$("viewWorkoutIntensity").update(entityEncode(workout.intensity));}},loadComments:function(b){var c="wid="+this.wid+"&isPlanned="+this.isPlanned;var a=new Ajax.Request(Context.HOST+"/GetWorkoutComments",{method:"get",parameters:c,onSuccess:this.reloadComments.bind(this),onFailure:this.alertException.bind(this)});},reloadComments:function(request){var commentContainer=$("viewWorkoutComments");commentContainer.update("");var commentsJSON=eval("("+request.responseText+")");var comments=commentsJSON.children;for(var i=0;i<comments.length;i++){var comment=comments[i];var editListItem="";var canEdit=comment.fromuser==this.loggedInUser;if(canEdit){editListItem=this.EDIT_LIST_ITEM_TEMPLATE.evaluate({cid:comment.cid});}var deleteListItem="";var canDelete=(comment.fromuser==this.loggedInUser||this.loggedInUser==this.workoutuser);if(canDelete){deleteListItem=this.DELETE_LIST_ITEM_TEMPLATE.evaluate({cid:comment.cid});}var editedTime="";if(comment.formattededitedtime){editedTime=this.EDITED_TIME_TEMPLATE.evaluate({editTime:entityEncode(comment.formattededitedtime)});}var insertComment=this.COMMENT_TEMPLATE.evaluate({editListItem:editListItem,deleteListItem:deleteListItem,cid:entityEncode(comment.cid),comment:entityEncode(comment.comment),user:entityEncode(comment.fromuser),commentTime:entityEncode(comment.formattedcommenttime),editedTime:editedTime});new Insertion.Bottom(commentContainer,insertComment);if(canEdit){Event.observe($("editComment_"+comment.cid),"click",this.editComment.bindAsEventListener(this));}if(canDelete){Event.observe($("deleteComment_"+comment.cid),"click",this.deleteComment.bindAsEventListener(this));}}},deleteComment:function(c){Event.stop(c);var a=Event.element(c);var g=a.id;var f=g.replace("deleteComment_","");var d="cid="+f+"&isPlanned="+this.isPlanned;var b=new Ajax.Request(Context.HOST+"/DeleteWorkoutComment",{method:"post",parameters:d,onSuccess:this.handleCommentDeleted.bind(this),onFailure:this.alertException.bind(this)});},handleCommentDeleted:function(request){var message=eval("("+request.responseText+")");if(message.ok){EventManager.fireEvent(Events.WORKOUT_COMMENT_DELETED);}this.handleMessage(request);},editComment:function(b){Event.stop(b);var a=Event.element(b);var d=a.id;var c=d.replace("editComment_","");commentDialog.invokeEdit(c);},showTotal:function(d){Event.stop(d);var c=Event.element(d);var a=$("viewWorkoutLapsList").getElementsByTagName("a");for(var b=0;b<a.length;b++){a[b].className="";}c.className="active";var f="wid="+this.wid;new Ajax.Request(Context.HOST+"/GetWorkout",{method:"get",parameters:f,onSuccess:this.showUpdatedWorkout.bind(this),onFailure:this.alertException.bind(this)});},showLap:function(f){Event.stop(f);var d=Event.element(f);var a=$("viewWorkoutLapsList").getElementsByTagName("a");for(var c=0;c<a.length;c++){a[c].className="";}d.className="active";var h=d.id;var b=(h.replace("showLap_",""))*1-1;var g="wid="+this.wid+"&lap="+b;new Ajax.Request(Context.HOST+"/GetLap",{method:"get",parameters:g,onSuccess:this.showUpdatedWorkout.bind(this),onFailure:this.alertException.bind(this)});}});WeekView=Class.create();WeekView.prototype=Object.extend(new AbstractListView(),{initialize:function(a,g,f,d,c,b,e){this.initListView(a,g,f,d,c,b,e);},__handleClick:function(f){var m="";if(f){var d=Event.element(f);if(d.tagName!="A"){d=d.parentNode;}var c=d.getAttribute("href");var k=c.split("/week/");var h=k[1].split("-");var i=h[0];var g=h[1];var l=h[2];user="";k=c.split("/user/");if(k.length>1){h=k[1].split("/");user=h[0];if(!user){user="";}}m="year="+i+"&month="+g+"&day="+l;if(user){m+="&user="+user;}}var b=Context.HOST+"/GetWeek";var a=new Ajax.Request(b,{method:"get",parameters:m,onSuccess:this.showView.bind(this),onFailure:this.alertException.bind(this)});},getView:function(){return"week";},getPreviousParameters:function(a){return"user/"+a.user+"/week/"+a.previous;},getNextParameters:function(a){return"user/"+a.user+"/week/"+a.next;}});ViewGoalView=Class.create();ViewGoalView.prototype=Object.extend(new ServerAction(),{GOAL_HEADER_TEMPLATE_STR:'#{name} by <a href="user/#{user}">#{user}</a>',GOAL_TEMPLATE_STR:'<div class="actualSpecification">#{description}</div>#{comment}#{completeBy}',GOAL_COMMENT_TEMPLATE_STR:'<div class="goalComment">#{comment}</div>',GOAL_COMPLETE_BY_TEMPLATE_STR:'<div class="goalEndedBy">#{completeBy}</div>',initialize:function(b,a){this.goalId=b;this.goalType=a;this.GOAL_HEADER_TEMPLATE=new Template(this.GOAL_HEADER_TEMPLATE_STR);this.GOAL_TEMPLATE=new Template(this.GOAL_TEMPLATE_STR);this.GOAL_COMMENT_TEMPLATE=new Template(this.GOAL_COMMENT_TEMPLATE_STR);this.GOAL_COMPLETE_BY_TEMPLATE=new Template(this.GOAL_COMPLETE_BY_TEMPLATE_STR);EventManager.registerEventHandler(Events.GOAL_DELETED,this.loadGoal.bindAsEventListener(this));EventManager.registerEventHandler(Events.GOAL_EDITED,this.loadGoal.bindAsEventListener(this));},loadGoal:function(c){var a="goalId="+this.goalId+"&goalType="+this.goalType;var b=new Ajax.Request(Context.HOST+"/GetGoal",{method:"get",parameters:a,onSuccess:this.showUpdatedGoal.bind(this),onFailure:this.alertException.bind(this)});},showUpdatedGoal:function(request){var goal=eval("("+request.responseText+")");var toInsertHeader=this.GOAL_HEADER_TEMPLATE.evaluate({name:entityEncode(goal.name),user:entityEncode(goal.user)});$("viewGoalHeader").update(toInsertHeader);var comment=goal.comment?this.GOAL_COMMENT_TEMPLATE.evaluate({comment:entityEncode(goal.comment)}):"";var completeBy=goal.completeby?this.GOAL_COMPLETE_BY_TEMPLATE.evaluate({completeBy:entityEncode(goal.completeby)}):"";var toInsert=this.GOAL_TEMPLATE.evaluate({description:entityEncode(goal.description),comment:comment,completeBy:completeBy});$("viewGoalDiv").update(toInsert);}});MyProfileView=Class.create();MyProfileView.prototype={initialize:function(a){this.metricUser=a;EventManager.registerEventHandler(Events.WEIGHT_UPDATED,this.showUpdatedWeight.bindAsEventListener(this));},showUpdatedWeight:function(a){$("profileWeight").update(a.weight);}};SignInView=Class.create();SignInView.prototype={initialize:function(a){Event.observe($("ugomoCheckbox"),"click",this.ehSwitchLoginType.bindAsEventListener(this));Event.observe($("rpxCheckbox"),"click",this.ehSwitchLoginType.bindAsEventListener(this));if(!a){a="rpx";}this.switchLoginType(a+"Checkbox");},switchLoginType:function(a){$(a).checked="checked";if(a=="ugomoCheckbox"){$("rpxForm").hide();$("ugomoForm").show();}else{$("ugomoForm").hide();$("rpxForm").show();}},ehSwitchLoginType:function(b){var a=Event.element(b);var c=a.id;this.switchLoginType(c);}};FlashChart=Class.create();FlashChart.prototype={initialize:function(d,c,a,b){this.xmlSource=b;this.so=new SWFObject(Context.STATIC_HOST+"/flashlib/xml_charts/charts.swf",d,c+"px",a+"px","6","#ffffff");this.so.addVariable("u",new Date().getTime());this.so.addVariable("stage_width",c);this.so.addVariable("stage_height",a);this.so.addVariable("v",Context.VERSION);this.so.addVariable("library_path",Context.STATIC_HOST+"/flashlib/xml_charts/charts_library");this.so.addVariable("xml_source",b);this.so.useExpressInstall(Context.STATIC_HOST+"/flashlib/expressinstall.swf");},render:function(a){this.so.write(a);},reload:function(a){if(a){a.SetVariable("update_url",this.xmlSource);}}};var GarminConnector=Class.create();GarminConnector.prototype=Object.extend(new ServerAction(),{FIND_DEVICE:"FIND_DEVICE",GET_DATA:"GET_DATA",UPLOAD:"UPLOAD",initialize:function(b,a){this.state=this.FIND_DEVICE;this.status=$(b);this.factory=null;this.keys=a;this.topContinue=$("topContinue");this.topContinueIndicator=$("topContinueIndicator");Event.observe(this.topContinue,"click",this.onContinue.bindAsEventListener(this));Event.observe(this.topContinueIndicator,"click",this.onContinue.bindAsEventListener(this));Event.observe($("cancelLink"),"click",this.onCancel.bindAsEventListener(this));this.deviceSelect=$("deviceSelect");this.readTracksText=$("readTracksText");this.compressedDataString="";this.progressBar=$("progressBar");this.progressBarDisplay=$("progressBarDisplay");this.activityListing=$("activityListing");this.garminController=null;this.intializeController();this.activityDirectory=null;this.activitySelection=null;this.activityQueue=null;this.fileTypeRead="FitnessHistory";if(this.garminController&&this.garminController.isPluginInitialized()){this.showFindDeviceLink();}},intializeController:function(){try{this.garminController=new Garmin.DeviceControl();this.garminController.register(this);if(this.garminController.unlock(this.keys)){this.setStatus("Connect your Garmin device to your computer and click below...");}else{this.setStatus("The plug-in was not unlocked successfully.");this.garminController=null;}}catch(a){this.handleException(a);}},showProgressBar:function(){Element.show(this.progressBar);},hideProgressBar:function(){Element.hide(this.progressBar);},updateProgressBar:function(b){if(b){var a=(b<=100)?b:100;this.progressBarDisplay.style.width=a+"%";}},onStartFindDevices:function(a){this.setStatus("Looking for connected Garmin devices");},onFinishFindDevices:function(b){try{if(b.controller.numDevices>0){var a=b.controller.getDevices();this.setStatus("Found "+a.length+" devices.");this.listDevices(a);this.showGetDataLink();}else{this.setStatus("No devices found.");this._clearHtmlSelect(this.deviceSelect);this.deviceSelect.disabled=true;}this.hideProgressBar();}catch(c){this.handleException(c);}},onCancelFindDevices:function(a){this.setStatus("Find cancelled");},listDevices:function(a){this._clearHtmlSelect(this.deviceSelect);for(var b=0;b<a.length;b++){this.deviceSelect.options[b]=new Option(a[b].getDisplayName(),a[b].getNumber());if(a[b].getNumber()==this.garminController.deviceNumber){this.deviceSelect.selectedIndex=b;this.showDeviceInfo(a[b]);}}this.deviceSelect.selectedIndex=0;this.showDeviceInfo(a[0]);this.deviceSelect.onchange=function(){var c=this.garminController.getDevices()[this.deviceSelect.value];this.showDeviceInfo(c);this.garminController.setDeviceNumber(this.deviceSelect.value);}.bind(this);this.deviceSelect.disabled=false;},showDeviceInfo:function(a){this.setStatus(a.getDescription());},onReadDataButton:function(a){this.activities=null;this.hideContinue();this.showProgressBar();$("listWorkouts").update("");this.garminController.readHistoryFromFitnessDevice();},onProgressReadFromDevice:function(a){this.updateProgressBar(a.progress.getPercentage());if(a.progress=="Transfer Complete"){this.setStatus("Transfer complete, preparing data...");}else{this.setStatus(a.progress);}},onCancelReadFromDevice:function(a){this.setStatus("Read cancelled");},onFinishReadFromDevice:function(b){try{this.setStatus("Processing retrieved data...");this.hideProgressBar();this.compressedDataString=b.controller.gpsDataStringCompressed;this.factory=Garmin.TcxActivityFactory;if(this.factory!=null){if(this.activities==null){this.activities=new Array();}this.activities=this.factory.parseDocument(b.controller.gpsData);}if(this.activityQueue==null||this.activityQueue.length==0){if(this.fileTypeRead!=Garmin.DeviceControl.FILE_TYPES.tcxDir&&this.fileTypeRead!=Garmin.DeviceControl.FILE_TYPES.crsDir){if(this.activities!=null){this.setStatus("Listing activities...");var a=this._listActivities(this.activities);this.setStatus(new Template("Results: #{tracks} workouts found").evaluate(a));}else{this.setStatus("Finished retrieving data.");}}}this.showUpload();}catch(c){this.handleException(c);}},_listActivities:function(d){var c=0;$("listWorkouts").update("");for(var a=0;a<d.length;a++){var b=d[a];this._listTrack(b);}return{tracks:d.length};},_listTrack:function(d){var e=I18N.getMessage("jsMessage.garmin.sport."+d.getAttribute(Garmin.Activity.ATTRIBUTE_KEYS.activitySport));var a=d.getSummaryValue(Garmin.Activity.SUMMARY_KEYS.startTime).getValue();var c=d.getSummaryValue(Garmin.Activity.SUMMARY_KEYS.endTime).getValue();var b=a.getDateString()+" ("+e+": "+a.getDurationTo(c)+")\n";$("listWorkouts").insert({bottom:b});},_clearHtmlSelect:function(a){if(a){a.options.size=0;}},onException:function(a){this.handleException(a.msg);},handleException:function(a){var b=a.name+": "+a.message;if(Garmin.PluginUtils.isDeviceErrorXml(a)){b=Garmin.PluginUtils.getDeviceErrorMessage(a);}this.setStatus(b);},setStatus:function(a){this.status.innerHTML=a;},onCancel:function(a){Event.stop(a);if(this.state==this.FIND_DEVICE){this.garminController.cancelFindDevices();return;}if(this.state==this.GET_DATA){this.garminController.cancelReadFromDevice();return;}},showFindDeviceLink:function(){$("topContinue").update("Connect to device");$("topContinue").show();$("topContinueIndicator").show();this.state=this.FIND_DEVICE;},hideContinue:function(){$("topContinueIndicator").hide();$("topContinue").hide();},showGetDataLink:function(){$("topContinue").update("Get data from device");$("topContinue").show();$("topContinueIndicator").show();this.showFindDevice();this.state=this.GET_DATA;},showUploadLink:function(){$("topContinue").update("Finish");$("topContinue").show();$("topContinueIndicator").show();this.state=this.UPLOAD;},onContinue:function(a){Event.stop(a);if(this.state==this.FIND_DEVICE){this.hideContinue();this.garminController.findDevices();}else{if(this.state==this.GET_DATA){$("deviceBox").hide();this.onReadDataButton();}else{if(this.state==this.UPLOAD){this.uploadDataToServer();return;}}}},showFindDevice:function(){$("deviceBox").show();$("uploadBox").hide();},showUpload:function(){$("deviceBox").hide();$("uploadBox").show();this.showUploadLink();},showFinished:function(a){this.handleMessage(a);},setReadFileType:function(a){this.fileTypeRead=Event.element(a).value;},showSpinner:function(){$("statusSpinner").style.display="block";},hideSpinner:function(){$("statusSpinner").style.display="none";},uploadDataToServer:function(){var c="dataCompressed="+this.compressedDataString;var a=Context.HOST+"/UploadGarminData";this.hideContinue();this.showSpinner();this.setStatus("Uploading to server, please wait...");$("uploadBox").hide();var b=new Ajax.Request(a,{method:"post",parameters:c,onSuccess:this.showFinished.bind(this),onFailure:this.alertException.bind(this)});}});