function destroy_submitting(id,form_id){var frm=$('lightbox').getElementsByClassName(id+form_id)[0];var green_button=frm.getElementsBySelector('[id=smgr_button'+form_id+']')[0];green_button.replace('<b>Submitting</b> <span><img src="/RoR/images/wait_arrows.gif"></span>');return true;}
function validate_ut_journals(){title=$('user_journal_title').value;message=$('user_journal_message').value;if((title.length!=0&&message.length==0)||(title.length==0&&message.length!=0)){tr_form.tracker_disable_form('title_message','Title and message must both be filled or both be blank.');}
else if(title.length>40){tr_form.tracker_disable_form('title','Title is too long.');}
else if(message.length>40000){tr_form.tracker_disable_form('message','Message is too long.');}
else{tr_form.tracker_clear_form();}}
function user_tracker_after_render_cb(lb){if(this.page==this.config.length-1){Element.show('tutorial_n');$('tutorial_n').href="javascript:myLightbox.end();tr_form.show(546, 'chart', dayToDate(39), 84);";}else{$('tutorial_n').href="javascript:tutorial_lb.next();";}}
var current_section="";var current_date="";var calculated_coords=null;function validateFloatValue(value,min,max){if(value==''){return true;}
var re=/^([-+]?[0-9]*\.?[0-9]+)$/;if(value.match(re)){if(min!==null&&min>value){return false;}
if(max!==null&&max<value){return false;}
return true;}
return false;}
function validateIntegerValue(value,min,max){if(value==''){return true;}
var re=/^([-+]?[0-9]+)$/;if(value.match(re)){if(min!==null&&min>value){return false;}
if(max!==null&&max<value){return false;}
return true;}
return false;}
function validate_float(id,min,max){value=$(id).value;return validateFloatValue(value,min,max);}
function validate_integer(id,min,max){value=$(id).value;return validateIntegerValue(value,min,max);}
function point_within(x,y,coords){return(x>coords[0]&&y>coords[1]&&x<coords[2]&&y<coords[3]);}
function sectionDayFromEvent(e){image_coords=Position.cumulativeOffset($('chart_image'))
x=Event.pointerX(e)-image_coords[0]-1;y=Event.pointerY(e)-image_coords[1]-1;sectionName=null;day=null;tr_sections.each(function(name){if(tr_coords[name]!=null&&point_within(x,y,tr_coords[name])){sectionName=name;}})
coords=calculate_coords();if(point_within(x,y,calculated_coords.active_area)){day=(Event.pointerX(e)-image_coords[0]-2-calculated_coords.active_area[0])/14;return[sectionName,day,x,y];}
return[sectionName,day,x,y];}
function calculate_coords(){if(calculated_coords==null){top_sec=tr_coords[tr_sections.first()];bottom_sec=tr_coords[tr_sections.last()];calculated_coords={bar:{left:top_sec[0],top:top_sec[1],height:bottom_sec[3]-top_sec[1],width:13},active_area:[top_sec[0],top_sec[1],bottom_sec[2],bottom_sec[3]]}}
return calculated_coords;}
function dayToDate(day){return new Date(start_date.getTime()+24*3600*1000*day);}
function get_field_name(yOffset,yBoxOffset,fieldNames){offset=yOffset-yBoxOffset;index=Math.floor(offset/grid_size);return fieldNames[index]}
function tr_image_click(e){if($show_input_hint){Element.hide('gen_tutorial_outer');Element.hide('lb_trk_tut_bx_r_arr');}
clickInfo=sectionDayFromEvent(e);if(clickInfo[0]==null&&tr_form.sections.indexOf("pain")>=0){clickInfo=painStripClick(clickInfo,e);}
if(clickInfo[0]==null)return;if(tr_calculated_sections[clickInfo[0]])return;dayOffset=Math.ceil(clickInfo[1]-1)*14;sectionName=clickInfo[0];date=dayToDate(clickInfo[1]);yOffset=clickInfo[3];tr_form.currentSectionName=sectionName;if(sectionName=="journals"){yBoxOffset=tr_coords["journals"][1];fieldNames=tr_section_field_names["journals"];formatted_date=formatDate(date);fieldName=get_field_name(yOffset,yBoxOffset,fieldNames);values_date=dateToString(date);values_data=tr_values[values_date];if(values_data&&values_data["data"]){values=values_data["data"];tracker_field_id=tr_form.user_journal_tracker_field_id;user_journal_id=values[tracker_field_id];if(user_journal_id){url='/user_trackers/get_user_journal'+'?start_date='+formatted_date;new Ajax.Request(url,{method:'post',parameters:{user_journal_id:user_journal_id,field_name:fieldName},onSuccess:function(transport){switch(transport.responseText){case'redirect':window.location="/user_journals/show/"+user_journal_id;return false;case'private':alert("This journal entry is private");return false;case'disabled':alert("This journal entry is disabled");return false;case'reload':window.location.reload();return false;default:return false;}}});}
else{showForm(e,clickInfo[1],dayOffset,sectionName,date,yOffset);}}
else{showForm(e,clickInfo[1],dayOffset,sectionName,date,yOffset);}}
else{showForm(e,clickInfo[1],dayOffset,sectionName,date,yOffset);}}
function showForm(e,clickInfo_1,dayOffset,sectionName,date,yOffset){if(can_edit==true){tr_form.show(dayOffset,sectionName,date,yOffset);showBarHover(e,clickInfo_1);hideDateHover();}
else{return false;}}
function tr_image_mmove(e){if(tr_form.visible){return;}
clickInfo=sectionDayFromEvent(e);bar=$('tr_hover_bar');mini_me=$('chart_image_mini_mes');mini_me.show();mini_me.style.left=Event.pointerX(e)-2+"px";mini_me.style.top=Event.pointerY(e)-2+"px";if(clickInfo[1]){showBarHover(e,clickInfo[1]);showDateHover(e,getReadableDate(dayToDate(clickInfo[1])));}else{hideBarHover();hideDateHover();}}
function showBarHover(event,day){coords=calculate_coords();bar=$('tr_hover_bar');cursorY=Event.pointerY(event)-image_coords[1]-coords.bar.top;bar.show();bar.style.width=coords.bar.width+1+"px";bar.style.height=coords.bar.height+"px";Position.clone($('chart_image'),bar,{setHeight:false,setWidth:false,offsetTop:coords.bar.top,offsetLeft:coords.bar.left+Math.floor(day)*14});}
function hideBarHover(){$('tr_hover_bar').hide();}
function showSliderDateHover(dateString){hover_date=$('tr_hover_date');hover_date.innerHTML=dateString;hover_date.clonePosition($('timeline_slider_knob'),{setWidth:false,setHeight:false,offsetTop:30});hover_date.show();}
function showDateHover(event,dateString){hover_date=$('tr_hover_date');hover_date.innerHTML=dateString+"<br/><span class='hint'>Click to add data</span>";hover_date.style.left=Event.pointerX(event)+20+'px';hover_date.style.top=Event.pointerY(event)+20+'px';hover_date.show();}
function hideDateHover(){$('tr_hover_date').hide();}
function dateToString(date){return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();}
function stringToDate(date){var d=date.split("-");return(new Date(d[0],d[1]-1,d[2]));}
var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December');var WEEK_DAYS=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
function getReadableDate(date){return WEEK_DAYS[date.getDay()]+', '+MONTH_NAMES[date.getMonth()]+' '+date.getDate();}
function TrackerInputForm(section_coords,sections,refElement,options){options=options||{};this.link_tid=null;this.section_coords=section_coords;this.sections=sections;this.refElement=refElement;this.currentSectionName=null;this.date=null;this.visible=false;this.user_tracker_id=options["user_tracker_id"];this.user_journal_tracker_field_id=options["user_journal_tracker_field_id"];user_journal_exists=false;this.tr_validation_errors=new Hash({});this.getErrorElement=function(){return $('ut_'+this.currentSectionName).getElementsBySelector(".trk_error")[0];}
this.hasErrors=function(){return this.tr_validation_errors.keys().length!=0;}
this.tracker_clear_form=function(){this.tr_validation_errors=new Hash({});this.getErrorElement().innerHTML="";$('ut_'+this.currentSectionName).getElementsBySelector(".trk_btn").each(function(node){node.style.opacity=1;node.removeClassName('disable_hover');});}
this.tracker_enable_form=function(name){this.tr_validation_errors.unset(name);if(this.hasErrors()){this.getErrorElement().innerHTML=this.tr_validation_errors.values().first();}else{this.getErrorElement().innerHTML="";$('ut_'+this.currentSectionName).getElementsBySelector(".trk_btn").each(function(node){node.style.opacity=1;node.removeClassName('disable_hover');});}}
this.tracker_disable_form=function(name,text){this.tr_validation_errors.set(name,text);this.getErrorElement().innerHTML=text;$('ut_'+this.currentSectionName).getElementsBySelector(".trk_btn").each(function(node){node.style.opacity=0.5;node.addClassName('disable_hover');});}
this.prev=function(){if(this.hasErrors()){return;}
if(trFormCallbacks.get(this.currentSectionName))trFormCallbacks.get(this.currentSectionName).get("onSectionClose")();Element.hide('ut_'+this.currentSectionName);index=this.sections.indexOf(this.currentSectionName);do{index=index-1;if(index<0){index=this.sections.length-1;}}while(index>=0&&(tr_coords[this.sections[index]]==null||tr_calculated_sections[this.sections[index]]));this.currentSectionName=this.sections[index];if(this.currentSectionName=="journals"&&user_journal_exists==true){tr_form.prev();}
if(trFormCallbacks.get(this.currentSectionName))trFormCallbacks.get(this.currentSectionName).get("onSectionShow")();this.reposition_and_show(section_coords[this.currentSectionName][1]+5);}
this.next=function(){if(this.hasErrors()){return;}
if(trFormCallbacks.get(this.currentSectionName))trFormCallbacks.get(this.currentSectionName).get("onSectionClose")();Element.hide('ut_'+this.currentSectionName);index=this.sections.indexOf(this.currentSectionName)
do{index=index+1;if(index>=this.sections.length){index=0;}}while(index<this.sections.length&&(tr_coords[this.sections[index]]==null||tr_calculated_sections[this.sections[index]]));this.currentSectionName=this.sections[index];if(this.currentSectionName=="journals"&&user_journal_exists==true){tr_form.next();}
if(trFormCallbacks.get("onSectionShow"))trFormCallbacks.get("onSectionShow")();this.reposition_and_show(section_coords[this.currentSectionName][1]+5);}
this.close=function(){Element.hide('ut_'+this.currentSectionName);for(var i=0;i<this.sections.length;i++){if(trFormCallbacks.get(this.sections[i]))trFormCallbacks.get(this.sections[i]).get("onFormClose")();}
Element.hide('bx_l_arr');Element.hide('bx_r_arr');this.visible=false;}
this.done=function(){if(this.hasErrors()){return;}
this.close();trFormCallbacks.keys().each(function(sectionName){trFormCallbacks.get(sectionName).get("onFormSubmit")();});photo_element=$('photo_file')
if(photo_element&&photo_element.value!=""){document.user_tracker_values_form.submit();}else{$('chart_image').src='/RoR/images/blank.gif';$('user_tracker_values_form').submit();}
hideBarHover();}
this.onChartLoad=function(){if(!imageCallbacksExecuted&&$('gen_tutorial_outer')!==null){imageCallbacksExecuted=true;}else{return;}
if(tr_show_form!==""){var y_offset=tr_coords[tr_show_form][1]+5;$('gen_tutorial_outer').hide();this.show(39*14,tr_show_form,new Date(),y_offset);tr_show_form=null;}}
this.show=function(dayOffset,sectionName,date,yOffset){this.date=dateToString(date);this.dateObj=date;this.dayOffset=dayOffset;if(trFormCallbacks.get(sectionName))trFormCallbacks.get(sectionName).get("onSectionShow")();$('user_tracker_values_form').getElementsBySelector(".ut_frm_date").each(function(node){node.innerHTML=getReadableDate(date);});values=tr_values[this.date];tf_id=this.user_journal_tracker_field_id;if(sectionName!='journals'){user_journal_exists=false;}
Form.reset('user_tracker_values_form');$inputFields.resetFields();if(values){$H(values.data).each(function(pair){field=$('user_tracker_data_'+pair.key)
if(field!=null){populateField(field,pair.value);}
if(pair.key==tf_id){user_journal_exists=true;}});}
$('user_tracker_value_timestamp').value=this.date;$('start_date').value=start_date
if(this.currentSectionName!=null){Element.hide("ut_"+this.currentSectionName);}
this.currentSectionName=sectionName;this.tracker_clear_form();this.reposition_and_show(yOffset);this.visible=true;}
this.reposition_and_show=function(yOffset){var sectionName=this.currentSectionName;var sectionElement=$('ut_'+sectionName);var x=section_coords[sectionName][0]+this.dayOffset+30;var y=0;if(trFormCallbacks.get(sectionName)){trFormCallbacks.get(sectionName).get("repositionAndShow")(yOffset,refElement,sectionElement);}else{if(x>400){Position.clone(refElement,sectionElement,{setHeight:false,setWidth:false,offsetTop:y+yOffset-44,offsetLeft:x-sectionElement.getWidth()-38});Position.clone(refElement,$('bx_r_arr'),{setHeight:false,setWidth:false,offsetTop:y+yOffset-14,offsetLeft:x-74});Element.hide('bx_l_arr');Element.show('bx_r_arr');}else{Position.clone(refElement,sectionElement,{setHeight:false,setWidth:false,offsetTop:y+yOffset-44,offsetLeft:x-6});Position.clone(refElement,$('bx_l_arr'),{setHeight:false,setWidth:false,offsetTop:y+yOffset-14,offsetLeft:x-34});Element.hide('bx_r_arr');Element.show('bx_l_arr');}
sectionElement.show();}
var firstInput=sectionElement.getElementsBySelector(".tr_f_elem")[0];if(firstInput!=null)firstInput.focus();new Effect.ScrollTo('ut_'+sectionName,{offset:-50});}
this.resizeFrame=function(sectionElement){maxWidth=0;sectionElement.getElementsBySelector(".trk_data").each(function(node){input=node.getElementsBySelector('.tracker_input');unit=node.getElementsBySelector('.fld_anw_unit');if(input.size()>1){node_width=0;for(var i=0;i<input.length;i++){node_width+=input[i].getWidth();}}
else if(unit.size()!=0){node_width=input[0].getWidth()+unit[0].getWidth()+25;}
else{node_width=input[0].getWidth();}
if(maxWidth<node_width){maxWidth=node_width;}});maxWidth=maxWidth+330;sectionElement.getElementsBySelector(".resizable_middle").each(function(node){node.style.width=(maxWidth+30)+'px';;});sectionElement.getElementsBySelector(".resizable").each(function(node){node.style.width=maxWidth+'px';;});}}
function updateMiniMes(){var chart_image=$('chart_image')
var minime1=$('trks_mini_me1');var minime2=$('trks_mini_me2');minime1.src=chart_image.src;minime2.src=chart_image.src;return false;}
function formatDate(date){var retval=date.getFullYear()+'-';var m=date.getMonth()+1;if(m<10){retval=retval+'0';}
retval=retval+m+'-';var d=date.getDate();if(d<10){retval=retval+'0';}
retval=retval+d;return retval;}
function sliderPositionToDate(value){var d=new Date(timeline_start_date.getTime()+24*3600*1000*(parseInt(value)));return d;}
function sliderChange(value){hideDateHover();var d=sliderPositionToDate(value);var formatted_date=formatDate(d);if(tr_form.visible)tr_form.close();$('chart_image').src='/RoR/images/blank.gif';new Ajax.Updater('chart_container','/user_trackers/show/'+utid+'?start_date='+formatted_date,{parameters:{inline:true},evalScripts:true});}
function sliderMove(value){var d=sliderPositionToDate(value);showSliderDateHover(getReadableDate(d));}
function showInputHint(){currentElement=$('lb_gen_tutorial');$('lb_gen_tutorial').style.marginLeft='0px';$('lb_gen_tutorial').style.marginRight='0px';targetElement=$('chart_container');currentElement.style.position='absolute';Position.clone(targetElement,currentElement,{setHeight:false,setWidth:false,offsetTop:43,offsetLeft:395});Position.clone(targetElement,$('lb_trk_tut_bx_r_arr'),{setHeight:false,setWidth:false,offsetTop:50,offsetLeft:672});Element.hide('trk_tut_close');Element.hide('lb_tutorial_n');Element.hide('lb_tutorial_b');$('lb_tutorial_text').innerHTML="Click here to start entering data"
Element.show('gen_tutorial_outer');Element.show('lb_trk_tut_bx_r_arr');new Effect.ScrollTo(targetElement,{offset:0});}
function moveTrackerFields(action){var tracker_fields_included=$('tracker_fields_included');var tracker_fields_excluded=$('tracker_fields_excluded');var movedFields=[];var source;var target;if(action=='remove'){movedFields=findSelectedOptions(tracker_fields_included);source='tracker_fields_included';target='tracker_fields_excluded';}else{movedFields=findSelectedOptions(tracker_fields_excluded);source='tracker_fields_excluded';target='tracker_fields_included';}
for(var i=0;i<movedFields.length;i++){var item=movedFields[i];moveOption(source,target,item);}
var excludedFields=$$('#tracker_fields_excluded option');var excludedFieldNames=[];excludedFields.each(function(field){excludedFieldNames.push(field.value);});$('tracker_setup_field_exclude_tracker_fields').value=excludedFieldNames.toJSON();}
function findSelectedOptions(element){var selectedOptions=[];var len=element.options.length;for(var i=0;i<len;i++){if(element.options[i].selected){selectedOptions.push(element.options[i]);}}
return selectedOptions;}
function moveOption(source,target,item){var groupName=item.parentNode.label;var group=$$('#'+target+' .og_'+groupName)[0];var children=$(group).getElementsByTagName('option');for(var i=0;i<children.length;i++){if(item.text<children[i].text){group.insertBefore(item,children[i]);return;}}
group.appendChild(item);}
function display_suggested_trackers(value){var suggested_keywords=[];value.split(' ').each(function(v){Object.keys(keywords).each(function(k){if(k.toLowerCase().startsWith(v.toLowerCase())&&v.length>=3){suggested_keywords.push(k);}});});suggested_keywords.compact();var tracker_ids=[];suggested_keywords.each(function(keyword){tracker_ids=tracker_ids.concat(keywords[keyword]).uniq();});var suggested_trackers=[];tracker_ids.each(function(id){var newTracker=new Hash();newTracker.set('id',id);newTracker.set('name',keywords_info[id]['name']);newTracker.set('type',keywords_info[id]['type']);newTracker.set('icon_name',keywords_info[id]['icon_name']);newTracker.set('description',keywords_info[id]['description']);suggested_trackers.push(newTracker);});if(suggested_trackers.size()>0){suggested_trackers=suggested_trackers.sortBy(function(s){return s.get('name')});$('tracker_filter_results').innerHTML=update_trackers_filter(value,suggested_trackers);$('tracker_filter_results').show();}else{$('tracker_filter_results').hide();}};function update_trackers_filter(value,trackers){var size=trackers.size();var results='';var count=1;results="<div class='filter'>";trackers.each(function(tracker){results+="<div class='trk_fil_elmt";if(count!==size){results+=" spacer"}
results+="'>";results+="<div class='trk_icon'>";results+="<div class='trk_icon_img "+tracker.get('icon_name')+"_icon'><img src='/RoR/images/blank.gif'></div>";results+="</div>";results+="<div class='trk_info'>";results+="<div class='trk_name'>";results+="<a href='/user_trackers/new?type="+tracker.get('type')+"'>"+tracker.get('name')+"</a>";results+="</div>";results+="<div class='trk_desc'>"+tracker.get('description')+"</div>";results+="</div>";results+="</div>";count+=1;});results+='</div>';return results;};if(!Control)var Control={};Control.Slider=Class.create({initialize:function(handle,track,options){var slider=this;if(Object.isArray(handle)){this.handles=handle.collect(function(e){return $(e)});}else{this.handles=[$(handle)];}
this.track=$(track);this.options=options||{};this.axis=this.options.axis||'horizontal';this.increment=this.options.increment||1;this.step=parseInt(this.options.step||'1');this.range=this.options.range||$R(0,1);this.value=0;this.values=this.handles.map(function(){return 0});this.spans=this.options.spans?this.options.spans.map(function(s){return $(s)}):false;this.options.startSpan=$(this.options.startSpan||null);this.options.endSpan=$(this.options.endSpan||null);this.restricted=this.options.restricted||false;this.maximum=this.options.maximum||this.range.end;this.minimum=this.options.minimum||this.range.start;this.alignX=parseInt(this.options.alignX||'0');this.alignY=parseInt(this.options.alignY||'0');this.trackLength=this.maximumOffset()-this.minimumOffset();this.handleLength=this.isVertical()?(this.handles[0].offsetHeight!=0?this.handles[0].offsetHeight:this.handles[0].style.height.replace(/px$/,"")):(this.handles[0].offsetWidth!=0?this.handles[0].offsetWidth:this.handles[0].style.width.replace(/px$/,""));this.active=false;this.dragging=false;this.disabled=false;if(this.options.disabled)this.setDisabled();this.allowedValues=this.options.values?this.options.values.sortBy(Prototype.K):false;if(this.allowedValues){this.minimum=this.allowedValues.min();this.maximum=this.allowedValues.max();}
this.eventMouseDown=this.startDrag.bindAsEventListener(this);this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.update.bindAsEventListener(this);this.handles.each(function(h,i){i=slider.handles.length-1-i;slider.setValue(parseFloat((Object.isArray(slider.options.sliderValue)?slider.options.sliderValue[i]:slider.options.sliderValue)||slider.range.start),i);h.makePositioned().observe("mousedown",slider.eventMouseDown);});this.track.observe("mousedown",this.eventMouseDown);document.observe("mouseup",this.eventMouseUp);document.observe("mousemove",this.eventMouseMove);this.initialized=true;},dispose:function(){var slider=this;Event.stopObserving(this.track,"mousedown",this.eventMouseDown);Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);this.handles.each(function(h){Event.stopObserving(h,"mousedown",slider.eventMouseDown);});},setDisabled:function(){this.disabled=true;},setEnabled:function(){this.disabled=false;},getNearestValue:function(value){if(this.allowedValues){if(value>=this.allowedValues.max())return(this.allowedValues.max());if(value<=this.allowedValues.min())return(this.allowedValues.min());var offset=Math.abs(this.allowedValues[0]-value);var newValue=this.allowedValues[0];this.allowedValues.each(function(v){var currentOffset=Math.abs(v-value);if(currentOffset<=offset){newValue=v;offset=currentOffset;}});return newValue;}
if(value>this.range.end)return this.range.end;if(value<this.range.start)return this.range.start;return value;},setValue:function(sliderValue,handleIdx){if(!this.active){this.activeHandleIdx=handleIdx||0;this.activeHandle=this.handles[this.activeHandleIdx];this.updateStyles();}
handleIdx=handleIdx||this.activeHandleIdx||0;if(this.initialized&&this.restricted){if((handleIdx>0)&&(sliderValue<this.values[handleIdx-1]))
sliderValue=this.values[handleIdx-1];if((handleIdx<(this.handles.length-1))&&(sliderValue>this.values[handleIdx+1]))
sliderValue=this.values[handleIdx+1];}
sliderValue=this.getNearestValue(sliderValue);this.values[handleIdx]=sliderValue;this.value=this.values[0];this.handles[handleIdx].style[this.isVertical()?'top':'left']=this.translateToPx(sliderValue);this.drawSpans();if(!this.dragging||!this.event)this.updateFinished();},setValueBy:function(delta,handleIdx){this.setValue(this.values[handleIdx||this.activeHandleIdx||0]+delta,handleIdx||this.activeHandleIdx||0);},translateToPx:function(value){return Math.round(((this.trackLength-this.handleLength)/(this.range.end-this.range.start))*(value-this.range.start))+"px";},translateToValue:function(offset){return((offset/(this.trackLength-this.handleLength)*(this.range.end-this.range.start))+this.range.start);},getRange:function(range){var v=this.values.sortBy(Prototype.K);range=range||0;return $R(v[range],v[range+1]);},minimumOffset:function(){return(this.isVertical()?this.alignY:this.alignX);},maximumOffset:function(){return(this.isVertical()?(this.track.offsetHeight!=0?this.track.offsetHeight:this.track.style.height.replace(/px$/,""))-this.alignY:(this.track.offsetWidth!=0?this.track.offsetWidth:this.track.style.width.replace(/px$/,""))-this.alignX);},isVertical:function(){return(this.axis=='vertical');},drawSpans:function(){var slider=this;if(this.spans)
$R(0,this.spans.length-1).each(function(r){slider.setSpan(slider.spans[r],slider.getRange(r))});if(this.options.startSpan)
this.setSpan(this.options.startSpan,$R(0,this.values.length>1?this.getRange(0).min():this.value));if(this.options.endSpan)
this.setSpan(this.options.endSpan,$R(this.values.length>1?this.getRange(this.spans.length-1).max():this.value,this.maximum));},setSpan:function(span,range){if(this.isVertical()){span.style.top=this.translateToPx(range.start);span.style.height=this.translateToPx(range.end-range.start+this.range.start);}else{span.style.left=this.translateToPx(range.start);span.style.width=this.translateToPx(range.end-range.start+this.range.start);}},updateStyles:function(){this.handles.each(function(h){Element.removeClassName(h,'selected')});Element.addClassName(this.activeHandle,'selected');},startDrag:function(event){if(Event.isLeftClick(event)){if(!this.disabled){this.active=true;var handle=Event.element(event);var pointer=[Event.pointerX(event),Event.pointerY(event)];var track=handle;if(track==this.track){var offsets=Position.cumulativeOffset(this.track);this.event=event;this.setValue(this.translateToValue((this.isVertical()?pointer[1]-offsets[1]:pointer[0]-offsets[0])-(this.handleLength/2)));var offsets=Position.cumulativeOffset(this.activeHandle);this.offsetX=(pointer[0]-offsets[0]);this.offsetY=(pointer[1]-offsets[1]);}else{while((this.handles.indexOf(handle)==-1)&&handle.parentNode)
handle=handle.parentNode;if(this.handles.indexOf(handle)!=-1){this.activeHandle=handle;this.activeHandleIdx=this.handles.indexOf(this.activeHandle);this.updateStyles();var offsets=Position.cumulativeOffset(this.activeHandle);this.offsetX=(pointer[0]-offsets[0]);this.offsetY=(pointer[1]-offsets[1]);}}}
Event.stop(event);}},update:function(event){if(this.active){if(!this.dragging)this.dragging=true;this.draw(event);if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);}},draw:function(event){var pointer=[Event.pointerX(event),Event.pointerY(event)];var offsets=Position.cumulativeOffset(this.track);pointer[0]-=this.offsetX+offsets[0];pointer[1]-=this.offsetY+offsets[1];this.event=event;this.setValue(this.translateToValue(this.isVertical()?pointer[1]:pointer[0]));if(this.initialized&&this.options.onSlide)
this.options.onSlide(this.values.length>1?this.values:this.value,this);},endDrag:function(event){if(this.active&&this.dragging){this.finishDrag(event,true);Event.stop(event);}
this.active=false;this.dragging=false;},finishDrag:function(event,success){this.active=false;this.dragging=false;this.updateFinished();},updateFinished:function(){if(this.initialized&&this.options.onChange)
this.options.onChange(this.values.length>1?this.values:this.value,this);this.event=null;}});var $trSliders=new Hash();function populateField(field,value){var inputField=$inputFields.find(field.id);if(inputField===null){if(field.type=='checkbox'){field.checked=(value==true);}else{$(field.id).value=value;}}else{inputField.populateField(value);}
return true;}
function inputFieldsStore(){this.inputFieldsHash=new Hash();this.create=function(fieldType,fieldId,rootId,options){if(typeof(rootId)=="undefined"||rootId===null){rootId=fieldId;}
if(typeof(options)=="undefined"||options===null){options={};}
var rootInputField=null;if(rootId!=fieldId){rootInputField=this.find(rootId);}
var fieldObject=new fieldType(fieldId,rootInputField,options);this.inputFieldsHash.set(fieldId,fieldObject);return fieldObject;};this.find=function(fieldId){if(this.inputFieldsHash.get(fieldId)){return this.inputFieldsHash.get(fieldId);}else{return null;}};this.resetFields=function(){this.inputFieldsHash.each(function(pair){if(pair[1].rootInputField.fieldId==pair[1].fieldId){pair[1].resetField();}});};this.deleteField=function(fieldId){this.inputFieldsHash.unset(fieldId);};this.clearStore=function(){this.inputFieldsHash=new Hash();};this.copyField=function(sourceFieldId,destinationFieldId){var sourceField=this.find(sourceFieldId);var rootFieldId=null;if(sourceField.fieldId!=sourceField.rootInputField.fieldId){rootFieldId=sourceField.rootInputField.fieldId;}
var destinationField=sourceField.copy(destinationFieldId,rootFieldId);return destinationField;};}
var $inputFields=new inputFieldsStore();function synthesizeTime(timeValue,useCivilianTime){var twentyFourHours=24*60*60;var twelveHours=12*60*60;while(timeValue>=twentyFourHours){timeValue-=twentyFourHours;}
var minuteValue=timeValue%(60*60);var hourValue=timeValue-minuteValue;var meridianValue=0;if(useCivilianTime){if(hourValue>=twelveHours){hourValue-=twelveHours;meridianValue=twelveHours;}
return[hourValue,minuteValue,meridianValue];}else{return[hourValue,minuteValue];}}
function TimeSelect(fieldId,rootInputField,options){this.useCivilianTime=options['use_12hour'];this.fieldId=fieldId;this.options=options;if(rootInputField===null){this.rootInputField=this;}else{this.rootInputField=rootInputField;}
this.copy=function(newFieldId,rootFieldId){return $inputFields.create(TimeSelect,newFieldId,rootFieldId,this.options);};this.resetField=function(){$(this.fieldId+"_hr").value="";$(this.fieldId+"_min").value="";if(this.useCivilianTime){$(this.fieldId+"_mer").value="";}};this.populateField=function(value){if(value===""){return;}
var timeValues=synthesizeTime(value,this.useCivilianTime);$(this.fieldId+"_hr").value=timeValues[0];$(this.fieldId+"_min").value=timeValues[1];if(this.useCivilianTime){$(this.fieldId+"_mer").value=timeValues[2];}};this.value=function(){this.snapDefaults();var hour=parseInt($(this.fieldId+"_hr").value);var minute=parseInt($(this.fieldId+"_min").value);if(isNaN(hour)||isNaN(minute)){return null;}
if(this.useCivilianTime){var meridian=parseInt($(this.fieldId+"_mer").value);if(isNaN(meridian)){return null;}
hour+=meridian;}
var time=(hour+minute);$(fieldId).value=time.toJSON();return time;};this.validate=function(values,additionalValues){var valuesHash=new Hash();for(var i=0;i<values.length;i++){if(valuesHash.get(values[i])){tr_form.tracker_disable_form(this.rootInputField.fieldId,"Timestamps must not repeat");return false;}
valuesHash.set(values[i],true);}
if(this.rootInputField.id==this.fieldId){tr_form.tracker_enable_form(this.fieldId);}
return true;};this.snapDefaults=function(){var hour_unsel=$(this.fieldId+"_hr").value==="";var min_unsel=$(this.fieldId+"_min").value==="";var mer_unsel=0;if(this.useCivilianTime){mer_unsel=$(this.fieldId+"_mer").value==="";}
if((hour_unsel||min_unsel||mer_unsel)&&!(hour_unsel&&min_unsel&&mer_unsel)){if(this.useCivilianTime&&$(this.fieldId+"_mer").value===""){$(this.fieldId+"_mer").value=0;}
if($(this.fieldId+"_hr").value===""){$(this.fieldId+"_hr").value=0;}
if($(this.fieldId+"_min").value===""){$(this.fieldId+"_min").value=0;}}};$(this.fieldId+"_hr").observe('change',this.rootInputField.validate.bindAsEventListener(this.rootInputField));$(this.fieldId+"_min").observe('change',this.rootInputField.validate.bindAsEventListener(this.rootInputField));if(this.useCivilianTime){$(this.fieldId+"_mer").observe('change',this.rootInputField.validate.bindAsEventListener(this.rootInputField));}}
function TimeRange(fieldId,rootInputField,options){this.fieldId=fieldId;if(rootInputField===null){this.rootInputField=this;}else{this.rootInputField=rootInputField;}
this.startTimeSelectId=this.fieldId+"_start";this.endTimeSelectId=this.fieldId+"_end";this.dayBoundary=options['day_boundary'];this.options=options;this.startTime=function(){return $inputFields.find(this.startTimeSelectId);};this.endTime=function(){return $inputFields.find(this.endTimeSelectId);};this.copy=function(newFieldId,rootFieldId){this.startTime().copy(newFieldId+"_start",rootFieldId);this.endTime().copy(newFieldId+"_end",rootFieldId);return $inputFields.create(TimeRange,newFieldId,rootFieldId,this.options);};this.resetField=function(){this.populateField("");};this.populateField=function(value){if(value===""){this.startTime().resetField();this.endTime().resetField();}else{this.startTime().populateField(value[0]);this.endTime().populateField(value[1]);}};this.value=function(){var startTime=this.startTime().value();var endTime=this.endTime().value();var hours24=24*60*60;if(startTime!==null&&endTime!==null){if(startTime>endTime){endTime+=hours24;}
if(startTime<this.dayBoundary){startTime+=hours24;endTime+=hours24;}
var trValue=[startTime,endTime];$(this.fieldId).value=trValue.toJSON();return trValue;}else{return null;}};this.validate=function(values,valuesByDate){if(this.rootInputField.id==this.fieldId){tr_form.tracker_enable_form(this.fieldId);}
if(typeof(values)=="undefined"||values===null){var fieldValue=this.value();if(fieldValue===null){return true;}
values=[fieldValue];}
var hours24=24*60*60;for(var i=0;i<values.length;i++){if(values[i]===""){continue;}
var startTime=values[i][0];var endTime=values[i][1];if(startTime==endTime){tr_form.tracker_disable_form(this.rootInputField.fieldId,"Start time and End time must not be same");return false;}}
values.sort(function(a,b){if(a[0]<b[0]){return-1;}else if(a[0]>b[0]){return 1;}else{return 0;}});var i;for(var i=0;i<values.length;i++){if(i+1<values.length&&values[i][1]>values[i+1][0]){tr_form.tracker_disable_form(this.rootInputField.fieldId,"Time intervals must not overlap");return false;}}
var tomorrow=dateToString(new Date(tr_form.dateObj.getTime()+24*3600*1000));var yesterday=dateToString(new Date(tr_form.dateObj.getTime()-24*3600*1000));var tomorrowsValue=valuesByDate.get(tomorrow);var yesterdaysValue=valuesByDate.get(yesterday);if(yesterdaysValue){var overlap=0;for(var i=0;i<yesterdaysValue.length;i++){var timeRange=yesterdaysValue[i];if((timeRange[1]-hours24)>this.dayBoundary&&((timeRange[1]-hours24)>values[0][0])){overlap=1;}}
if(overlap==1){tr_form.tracker_disable_form(this.rootInputField.fieldId,"Time intervals must not overlap with previous days intervals");return false;}}
if((values.last()[1]-hours24>this.dayBoundary)&&tomorrowsValue){var overlap=0;for(var i=0;i<tomorrowsValue.length;i++){var timeRange=tomorrowsValue[i];if(timeRange[0]<(values.last()[1]-hours24)){overlap=1;}}
if(overlap==1){tr_form.tracker_disable_form(this.rootInputField.fieldId,"Time intervals must not overlap with next days intervals");return false;}}
return true;};}
function getAdditionalValues(fieldName){var tomorrow=dateToString(new Date(tr_form.dateObj.getTime()+24*3600*1000));var yesterday=dateToString(new Date(tr_form.dateObj.getTime()-24*3600*1000));var tomorrowsValues=new Array();var yesterdaysValues=new Array();if(tr_values[tomorrow]&&tr_values[tomorrow]['data']&&tr_values[tomorrow]['data'][fieldName]){tomorrowsValues=tr_values[tomorrow]['data'][fieldName];}
if(tr_values[yesterday]&&tr_values[yesterday]['data']&&tr_values[yesterday]['data'][fieldName]){yesterdaysValues=tr_values[yesterday]['data'][fieldName];}
var additionalValues=new Hash();additionalValues.set(tomorrow,tomorrowsValues);additionalValues.set(yesterday,yesterdaysValues);return additionalValues;}
function MultiValuedField(fieldId,rootInputField,options){this.fieldId=fieldId;if(rootInputField===null){this.rootInputField=this;}else{this.rootInputField=rootInputField;}
this.templateFieldId=this.field_id+"_mv_tmpl";this.nextFieldNumber=0;this.containedFields=new Array();this.fieldName=options['field_name'];this.updateAddDelLinks=function(values,valid){if(values.length<this.containedFields.length||!valid){$(this.fieldId+"_add_link").hide();}else{$(this.fieldId+"_add_link").show();}};this.value=function(){var values=new Array();var cfValue=null;for(var i=0;i<this.containedFields.length;i++){cfValue=$inputFields.find(this.containedFields[i]).value();if(cfValue!==null){values.push(cfValue);}}
if(values.length>0){$(this.fieldId).value=values.toJSON();}else{$(this.fieldId).value="";}
return values;};this.validate=function(values,additionalValuesHash){tr_form.tracker_enable_form(this.fieldId);var values=this.value();var valid=true;if(values.length>0){var additionalValues=getAdditionalValues(this.fieldName);valid=$inputFields.find(this.containedFields[0]).validate(values,additionalValues);}
this.updateAddDelLinks(values,valid);return valid;};this.deleteField=function(field){var fieldNumber=field.id.match(this.fieldId+"_([0-9]+)_del_btn")[1];var delFieldId=this.fieldId+"_"+fieldNumber;$(delFieldId+"_ctr").remove();this.containedFields=this.containedFields.without(delFieldId);$inputFields.deleteField(delFieldId);this.validate();};this.addField=function(value){var nextFieldId=this.nextFieldNumber;var ifCopy=$(this.fieldId+"_template_ctr").innerHTML.stripScripts();var ifCtr=$(this.fieldId+"_inputs_ctr");ifCtr.insert({'bottom':ifCopy});var ifCtrChildren=ifCtr.childElements();var copiedTemplate=null;for(var i=0;i<ifCtrChildren.length;i++){if(ifCtrChildren[i].id==this.fieldId+"_template"){copiedTemplate=ifCtrChildren[i];break;}}
var newInputFieldId=this.fieldId+"_"+nextFieldId;copiedTemplate.id=newInputFieldId+"_ctr";var tmplDescendants=copiedTemplate.descendants();for(var i=0;i<tmplDescendants.length;i++){var desc=tmplDescendants[i];if(desc.id.match(/mv_tmpl/)){desc.id=desc.id.gsub(/mv_tmpl/,""+nextFieldId);}}
var newField=$inputFields.copyField(this.fieldId+"_mv_tmpl",newInputFieldId);newField.populateField(value);this.containedFields.push(newInputFieldId);this.nextFieldNumber++;this.validate();};this.resetField=function(){this.populateField("");$(this.fieldId).value="";};this.populateField=function(value){this.nextFieldNumber=0;this.containedFields=new Array();$(this.fieldId+"_inputs_ctr").update("");if(value===""||value.length==0){this.addField("");}else{for(var i=0;i<value.length;i++){this.addField(value[i]);}}};}
function MultiField(fieldId,rootInputField,options){this.fieldId=fieldId;if(rootInputField===null){this.rootInputField=this;}else{this.rootInputField=rootInputField;}
this.subFieldFormats=options['sub_fields'];this.require_all_fields=options['require_all_fields'];this.booleanIndex=null;this.containedFields=new Array();for(var i=0;i<this.subFieldFormats.length;i++){this.containedFields.push(this.fieldId+"_mf_"+i);if(this.subFieldFormats[i]=="boolean"){this.booleanIndex=i;}}
this.fieldName=options['field_name'];this.options=options;this.resetField=function(){this.populateField("");};this.populateField=function(value){if(value==""||value.length==0){for(var i=0;i<this.containedFields.length;i++){$inputFields.find(this.containedFields[i]).populateField("");}
$(this.fieldId).value="";}else{for(var i=0;i<this.containedFields.length;i++){$inputFields.find(this.containedFields[i]).populateField(value[i]);}
$(this.fieldId).value=value.toJSON();}};this.value=function(){this.snapDefaults();var mValue=[];var blank=true;var overrideBlank=false;if(this.booleanIndex!==null){if($inputFields.find(this.containedFields[this.booleanIndex]).value()===false){overrideBlank=true;}}
this.containedFields.each(function(containedField){var cValue=$inputFields.find(containedField).value();if(cValue===null||cValue===""||cValue===false){mValue.push("");}else{mValue.push(cValue);blank=false;}}.bind(this));if(blank||overrideBlank){$(this.fieldId).value="";return null;}else{$(this.fieldId).value=mValue.toJSON();return mValue;}};this.snapDefaults=function(){if(this.booleanIndex===null){return;}
var currentValue=$(this.fieldId).value;if(currentValue!==""){currentValue=currentValue.evalJSON();var currentBooleanValue=currentValue[this.booleanIndex];var newBooleanValue=$(this.containedFields[this.booleanIndex]).checked;if(currentBooleanValue==true&&newBooleanValue==false){return;}}
var setBoolean=false;for(var i=0;i<this.containedFields.length;i++){if(i==this.booleanIndex){continue;}
var cValue=$inputFields.find(this.containedFields[i]).value();if(cValue!==""&&cValue!==null){setBoolean=true;}}
if(setBoolean){$inputFields.find(this.containedFields[this.booleanIndex]).populateField("1");}};this.sliceValues=function(values){var slicedValues=[];if(typeof(values)=="undefined"||values===null||values===""){values=[];}
for(var i=0;i<this.containedFields.length;i++){var fieldValues=[];for(var j=0;j<values.length;j++){fieldValues.push(values[j][i]);}
slicedValues.push(fieldValues);}
return slicedValues;};this.validate=function(values,additionalValues){if(this.rootInputField.fieldId==this.fieldId){tr_form.tracker_enable_form(this.fieldId);var sValue=this.value();if(sValue===null){return true;}
values=[sValue];}
if(this.require_all_fields){for(var i=0;i<values.length;i++){for(var j=0;j<values[i].length;j++){if(values[i][j]===""){tr_form.tracker_disable_form(this.rootInputField.fieldId,"All fields are required.");return false;}}}}
var slicedValues=this.sliceValues(values);if(typeof(additionalValues)=="undefined"||additionalValues===null){additionalValues=getAdditionalValues(this.fieldName);}
var slicedAdditionalValues=new Hash();var tomorrow=dateToString(new Date(tr_form.dateObj.getTime()+24*3600*1000));var yesterday=dateToString(new Date(tr_form.dateObj.getTime()-24*3600*1000));slicedAdditionalValues.set(tomorrow,this.sliceValues(additionalValues.get(tomorrow)));slicedAdditionalValues.set(yesterday,this.sliceValues(additionalValues.get(yesterday)));for(var i=0;i<this.containedFields.length;i++){var fieldAdditionalValues=new Hash();fieldAdditionalValues.set(tomorrow,slicedAdditionalValues.get(tomorrow)[i]);fieldAdditionalValues.set(yesterday,slicedAdditionalValues.get(yesterday)[i]);var valid=$inputFields.find(this.containedFields[i]).validate(slicedValues[i],fieldAdditionalValues);if(!valid){return false;}}
return true;};this.copy=function(newFieldId,rootFieldId){for(var i=0;i<this.containedFields.length;i++){$inputFields.find(this.containedFields[i]).copy(newFieldId+"_mf_"+i,rootFieldId);}
return $inputFields.create(MultiField,newFieldId,rootFieldId,this.options);};}
function SimpleSelector(fieldId,rootInputField,options){this.fieldId=fieldId;if(rootInputField===null){this.rootInputField=this;}else{this.rootInputField=rootInputField;}
this.options=options;this.inputType=options['format'];this.min=options['min'];if(typeof(this.min)=='undefined'){this.min=null;}
this.max=options['max'];if(typeof(this.max)=='undefined'){this.max=null;}
this.fieldName=options['field_name'];this.resetField=function(){this.populateField("");};this.populateField=function(value){if(this.inputType=='boolean'){$(this.fieldId).checked=value;}else{$(this.fieldId).value=value;}};this.validate=function(values,additionalValues){for(var i=0;i<values.length;i++){var validator=null;if(this.inputType=='float'){validator=validateFloatValue;}else if(this.inputType=='integer'){validator=validateIntegerValue;}
if(validator!==null&&!validator(values[i],this.min,this.max)){var message="";if(this.min===null){message=this.fieldName+" must be a number";}else{message=this.fieldName+" must be a number between "+this.min+" and "+this.max;}
tr_form.tracker_disable_form(this.rootInputField.fieldId,message);return false;}}
return true;};this.value=function(){if(this.inputType=='boolean'){return($(this.fieldId).checked);}else{return $(this.fieldId).value;}};this.copy=function(newFieldId,rootFieldId){return $inputFields.create(SimpleSelector,newFieldId,rootFieldId,this.options);};$(this.fieldId).observe('change',this.rootInputField.validate.bindAsEventListener(this.rootInputField));if(this.inputType=='float'||this.inputType=='integer'){$(this.fieldId).observe('blur',this.rootInputField.validate.bindAsEventListener(this.rootInputField));}}
function SliderSelector(fieldId,rootInputField,options){this.fieldId=fieldId;if(rootInputField===null){this.rootInputField=this;}else{this.rootInputField=rootInputField;}
this.options=options;this.userChanged=false;this.sliderChange=function(v){this.userChanged=true;this.rootInputField.validate();};$trSliders.set(this.fieldId+'_sldr',new Control.Slider(this.fieldId+'_sldr',this.fieldId+'_ctr',{range:$R(1,5),values:['1','2','3','4','5'],sliderValue:3,onChange:this.sliderChange.bind(this)}));this.resetField=function(){$(this.fieldId).value="";};this.populateField=function(value){if(value!==""){$trSliders.get(this.fieldId+'_sldr').setValue(value);}};this.copy=function(newFieldId,rootFieldId){return $inputFields.create(SliderSelector,newFieldId,rootFieldId,this.options);};this.value=function(){if(this.sliderValue===""){return"";}
var sliderValue=$trSliders.get(this.fieldId+'_sldr').value;$(this.fieldId).value=sliderValue;return sliderValue;};this.validate=function(values,additionalValues){return true;};}
var $fieldGroups=new Hash();function FieldGroup(name,fieldIds,fieldsHash){this.name=name;this.fieldsHash=new Hash(fieldsHash);this.fieldIds=fieldIds;this.availableFieldIds=this.fieldIds;this.selectedFieldId=null;$fieldGroups.set(name,this);this.resetField=function(){this.initializeGroup({});};this.resetInput=function(fieldId){var ctr=$(fieldId+'_input_ctr');if(ctr.descendants().length===0){var ibox=$(fieldId+'_input');ctr.insert({'bottom':ibox});}
ctr.hide();}
this.initializeGroup=function(values){for(var i=0;i<this.fieldIds.length;i++){this.resetInput(this.fieldIds[i]);}
this.availableFieldIds=this.fieldIds;$('fg_'+this.name+'_ibox_ctr').update("");var valuesHash=new Hash(values);for(var i=0;i<this.fieldIds.length;i++){if(valuesHash.get(this.fieldIds[i])!==undefined){this.addField(this.fieldIds[i],valuesHash.get(this.fieldIds[i]));}}
this.showSelector();};this.addField=function(fieldId,value){if(this.availableFieldIds.indexOf(fieldId)<0){return;}
var ibox=$(fieldId+'_input');var ibox_ctr=$('fg_'+this.name+'_ibox_ctr');ibox_ctr.insert({'bottom':ibox});$(fieldId+'_input_ctr').hide();if(value!==""){populateField($(fieldId),value);}
this.availableFieldIds=this.availableFieldIds.without(fieldId);};this.showSelector=function(){var sel_ctr=$('fg_'+this.name+'_sel_ctr');sel_ctr.update("");sel_ctr.hide();this.selectedFieldId=null;if(this.availableFieldIds.length===0){$('fg_'+this.name+'_add_another_link').hide();return;}
var selector="";selector+=("<select class='fg_selector' id='fg_"+this.name+"_sel'>");for(var i=0;i<this.fieldIds.length;i++){if(this.availableFieldIds.indexOf(this.fieldIds[i])>=0){selector+=("<option value='"+this.fieldIds[i]+"'>"+this.fieldsHash.get(this.fieldIds[i])+"</option>");}}
selector+="</select>"
sel_ctr.update(selector);$('fg_'+this.name+'_sel').observe("change",this.changeSelectedField.bindAsEventListener(this));this.moveSelector(this.availableFieldIds[0]);$('fg_'+this.name+'_add_another_link').show();};this.moveSelector=function(fieldId){if(this.availableFieldIds.indexOf(fieldId)<0){return;}
if(this.selectedFieldId!==null){$(this.selectedFieldId+'_input_ctr').hide();}
var sel_ctr=$('fg_'+this.name+'_sel_ctr');var input_ctr=$(fieldId+'_input_ctr');input_ctr.insert({'top':sel_ctr});sel_ctr.show();input_ctr.show();this.selectedFieldId=fieldId;};this.addAnotherField=function(){var fieldId=$('fg_'+this.name+"_sel").value;var fieldValue=$(fieldId).value;if(fieldValue!==""){if($inputFields.find(fieldId)){fieldValue=fieldValue.evalJSON();}}
this.addField(fieldId,fieldValue);this.showSelector();};this.deleteField=function(fieldId){this.resetInput(fieldId);this.availableFieldIds.push(fieldId);this.showSelector();};this.changeSelectedField=function(e){var fieldId=$('fg_'+this.name+"_sel").value;this.moveSelector(fieldId);};}
$bodyMapBorders=new Hash();function borderKeyAndPos(coords1,coords2){if(coords1[0]==coords2[0]){var x=coords1[0];if(coords1[1]>coords2[1]){var y=coords1[1];var y1=coords2[1];}else{var y=coords2[1];var y1=coords1[1];}
var borderKey=x+":"+[y1,y];}else{var y=coords1[1];if(coords1[0]>coords2[0]){var x=coords1[0];var x1=coords2[0];}else{var x=coords2[0];var x1=coords1[0];}
var borderKey=[x1,x]+":"+y;}
return[borderKey,x,y];}
function PixelBorder(coords1,coords2,bodyMap){var borderKey=borderKeyAndPos(coords1,coords2);if(coords1[0]==coords2[0]){var width=bodyMap.pixelSize;var height=1;}else{var width=1;var height=bodyMap.pixelSize;}
var x=borderKey[1];var y=borderKey[2];var border=$("bm_border_"+borderKey[0]);border.setStyle({zIndex:110,width:(width+"px"),fontSize:"0px",height:(height+"px"),position:"absolute",left:bodyMap.offsetLeft+(x*bodyMap.pixelSize)+"px",top:bodyMap.offsetTop+(y*bodyMap.pixelSize)+"px",backgroundColor:"#333333"});$bodyMapBorders.set(borderKey[0],border);border.hide();}
function createPixelBorders(coords,bodyMap){var borderingCoords=[[coords[0]-1,coords[1]],[coords[0]+1,coords[1]],[coords[0],coords[1]-1],[coords[0],coords[1]+1]];for(var i=0;i<borderingCoords.length;i++){var borderKey=borderKeyAndPos(coords,borderingCoords[i]);if($bodyMapBorders.get(borderKey)==null){new PixelBorder(coords,borderingCoords[i],bodyMap);}}}
$bodyPainPixels=new Hash();function painPixelByRegionId(regionId){return $bodyPainPixels.get("bm_pop_"+regionId);}
function PainPixel(regionId,bodyMap){this.bodyMap=bodyMap;this.regionId=regionId;this.pixelId='bm_pop_'+regionId;this.pixelDiv=$(this.pixelId);this.pixelDiv.setStyle({height:bodyMap.pixelSize+"px",width:bodyMap.pixelSize+"px",position:"absolute",zIndex:150});this.pixelDiv.addClassName("pt_pain_fx");$bodyPainPixels.set(this.pixelId,this);this.show=function(pixel){this.pixelDiv.setStyle({left:this.bodyMap.offsetLeft+(pixel.x*this.bodyMap.pixelSize)+"px",top:this.bodyMap.offsetTop+(pixel.y*this.bodyMap.pixelSize)+"px"});this.pixelDiv.show();}
this.hide=function(pixel){this.pixelDiv.hide();}
Event.observe(this.pixelId,"click",function(e){if(!$trBodyMap.editMode){tr_image_click(e);return;}
var pixel=$trBodyMap.regionPainPixels.get($bodyPainPixels.get(Event.element(e).id).regionId);$trBodyMap.togglePixel(pixel);});Event.observe(this.pixelId,"mouseover",function(e){var pixel=$trBodyMap.regionPainPixels.get($bodyPainPixels.get(Event.element(e).id).regionId);if(pixel!=null){$trBodyMap.pixelMouseOver(pixel);}});Event.observe(this.pixelId,"mouseout",function(e){var pixel=$trBodyMap.regionPainPixels.get($bodyPainPixels.get(Event.element(e).id).regionId);if(pixel!=null){$trBodyMap.pixelMouseOut(pixel);}});}
function centerPainPixel(e){var i=0;if($('pixel_o_pain')==null)return;$('pixel_o_pain').setStyle({left:(Event.pointerX(e)-14)+"px",top:(Event.pointerY(e)-14)+"px"});}
$bodyMapPixels=new Hash();function pixelIdByXY(x,y){return"bm_pixel["+x+","+y+"]";}
function pixelByCoords(coords){return $bodyMapPixels.get(pixelIdByXY(coords[0],coords[1]));}
function Pixel(location,bodyMap,regionId){if(location==null){return;}
this.x=location[0];this.y=location[1];this.regionId=regionId;this.value=null;this.pixelId=pixelIdByXY(this.x,this.y);this.bodyMap=bodyMap;this.repaint=function(value){if(this.value==value){return;}
this.pixelDiv.setStyle({background:"url(/RoR/images/body_maps/"+this.bodyMap.name+"_"+value+".png) -"+(this.x*this.bodyMap.pixelSize)+"px -"+(this.y*this.bodyMap.pixelSize)+"px"});this.value=value;}
this.reset=function(){this.repaint(this.bodyMap.zeroValue);}
this.hide=function(){this.pixelDiv.hide();}
this.show=function(){this.pixelDiv.show();}
this.highlight=function(){var coords=[this.x,this.y];var borderingCoords=[[coords[0]-1,coords[1]],[coords[0]+1,coords[1]],[coords[0],coords[1]-1],[coords[0],coords[1]+1]];for(var i=0;i<borderingCoords.length;i++){var borderKey=borderKeyAndPos(coords,borderingCoords[i])[0];$bodyMapBorders.get(borderKey).show();}}
this.deHighlight=function(){var coords=[this.x,this.y];var borderingCoords=[[coords[0]-1,coords[1]],[coords[0]+1,coords[1]],[coords[0],coords[1]-1],[coords[0],coords[1]+1]];for(var i=0;i<borderingCoords.length;i++){var borderKey=borderKeyAndPos(coords,borderingCoords[i])[0];$bodyMapBorders.get(borderKey).hide();}}
this.pixelDiv=$(this.pixelId);this.pixelDiv.setStyle({zIndex:100,height:bodyMap.pixelSize+"px",width:bodyMap.pixelSize+"px",position:"absolute",left:bodyMap.offsetLeft+(this.x*bodyMap.pixelSize)+"px",top:bodyMap.offsetTop+(this.y*bodyMap.pixelSize)+"px"});$bodyMapPixels.set(this.pixelId,this);this.repaint(bodyMap.zeroValue);createPixelBorders([this.x,this.y],bodyMap);Event.observe(this.pixelId,"click",function(e){if(!$trBodyMap.editMode){tr_image_click(e);return;}
var pixel=$bodyMapPixels.get(Event.element(e).id);$trBodyMap.togglePixel(pixel);});Event.observe(this.pixelId,"mouseover",function(e){var pixel=$bodyMapPixels.get(Event.element(e).id);$trBodyMap.pixelMouseOver(pixel);});Event.observe(this.pixelId,"mouseout",function(e){var pixel=$bodyMapPixels.get(Event.element(e).id);$trBodyMap.pixelMouseOut(pixel);});}
function painStripClick(clickInfo,e){var evElement=Event.element(e);if(clickInfo[3]>=tr_coords["pain"][1]&&clickInfo[3]<=(tr_coords["pain"][1]+15)||(evElement.id.indexOf("bm_pixel")==0)||evElement.id.indexOf("bm_pop")==0){image_coords=Position.cumulativeOffset($('chart_image'));clickInfo[0]="pain";clickInfo[3]=tr_coords["pain"][1];if((evElement.id.indexOf("bm_pixel")==0)||evElement.id.indexOf("bm_pop")==0){clickInfo[1]=(stringToDate($trBodyMap.currentDate)-start_date)/(24*60*60*1000);}else{clickInfo[1]=(Event.pointerX(e)-image_coords[0]-2-calculated_coords.active_area[0])/14;}}
return clickInfo;}
function BodyMap(fieldId,rootInputField,options){this.rootInputField=this;var options=options.evalJSON();this.resetField=function(){this.repaint();var regionIds=this.regionSliders.keys();for(var i=0;i<regionIds.length;i++){this.regionSliders.get(regionIds[i]).setValue(this.defaultValue);$(this.fieldId+"_sev"+regionIds[i]).hide();}
$(this.fieldId+"_ptpn_msg").hide();$(this.fieldId+"_def_msg").show();$(this.fieldId).value="";}
this.populateField=function(value){if(value==""){$(this.fieldId).value="";return;}
this.repaintWithValue(value);for(var j=0;j<value.length;j++){regionInfo=value[j];this.regionSliders.get(regionInfo[0]).setValue(regionInfo[1]);$(this.fieldId+"_pt_"+regionInfo[0]).value=regionInfo[2];$(this.fieldId+"_sev"+regionInfo[0]).show();}
$(this.fieldId+"_ptpn_msg").show();$(this.fieldId+"_def_msg").hide();$(this.fieldId).value=value.toJSON();}
this.validate=function(){var regionIds=this.regionSpec.keys();var fieldValue=new Array();for(var i=0;i<regionIds.length;i++){var regionId=parseInt(regionIds[i]);var regionSeverity=this.regionSliders.get(regionId).value;var regionPainType=$(this.fieldId+"_pt_"+regionId).value;var regionPixels=new Array();for(var j=0;j<this.regionSpec.get(regionId).length;j++){if(pixelByCoords(this.regionSpec.get(regionId)[j]).value>0){regionPixels.push(this.regionSpec.get(regionId)[j]);}}
if(regionPixels.length>0){var painPoint=(this.regionPainPixels.get(regionId)!=null)?[this.regionPainPixels.get(regionId).x,this.regionPainPixels.get(regionId).y]:null;fieldValue.push([regionId,regionSeverity,regionPainType,painPoint,regionPixels]);}}
if(fieldValue.length>0){$(this.fieldId).value=fieldValue.toJSON();}else{$(this.fieldId).value="";}}
this.copyLastEntry=function(){if(!this.editMode)return;var d=tr_form.date.split("-");for(var formDate=new Date(d[0],d[1]-1,d[2]);formDate>start_date;formDate-=24*60*60*1000){var pDate=dateToString(new Date(formDate));if(tr_values[pDate]&&(tr_values[pDate]["data"][this.trackerFieldId]!=null)){this.populateField(tr_values[pDate]["data"][this.trackerFieldId]);break;}}}
this.repaintWithValue=function(regions){for(var i=0;i<regions.length;i++){var regionValue=regions[i][1];var regionPixels=regions[i][4];var regionPainPoint=regions[i][3];var regionId=regions[i][0];if(regionPainPoint!=null){var pixel=$bodyMapPixels.get(pixelIdByXY(regionPainPoint[0],regionPainPoint[1]));painPixelByRegionId(regionId).show(pixel);this.regionPainPixels.set(regionId,pixel);}
for(var j=0;j<regionPixels.length;j++){pixelByCoords(regionPixels[j]).repaint(regionValue);}}}
this.repaint=function(date){$bodyMapPixels.values().each(function(pixel){pixel.reset();});this.regionPainPixels=new Hash();$bodyPainPixels.values().each(function(painPixel){painPixel.hide();});if(date==null)return;$('bm_pain_datebubble').update(getReadableDate(stringToDate(date)));if(tr_values[date]==null||tr_values[date]['data'][this.trackerFieldId]==null)return;this.repaintWithValue(tr_values[date]['data'][this.trackerFieldId]);}
this.togglePixel=function(pixel){if(!this.editMode)return;if(pixel.value==0){pixel.repaint(this.regionSliders.get(pixel.regionId).value);}else{pixel.repaint(0);if(this.regionPainPixels.get(pixel.regionId)!=null){painPixelByRegionId(pixel.regionId).hide();this.regionPainPixels.set(pixel.regionId,null);}}
this.toggleRegion(pixel);}
this.toggleRegion=function(pixel){var rpCount=0;for(var i=0;i<this.regionSpec.get(pixel.regionId).length;i++){if(pixelByCoords(this.regionSpec.get(pixel.regionId)[i]).value)rpCount++;}
if((pixel.value!=0)&&(rpCount==1)){this.addRegionControl(pixel.regionId);}
if(!pixel.value&&rpCount==0){this.removeRegionControl(pixel.regionId);}
this.validate();}
this.addRegionControl=function(regionId){if($(this.fieldId+"_def_msg").visible())$(this.fieldId+"_def_msg").hide();$(this.fieldId+"_ptpn_msg").show();$(this.fieldId+"_sev"+regionId).show();}
this.removeRegionControl=function(regionId){$(this.fieldId+"_sev"+regionId).hide();}
this.repaintRegion=function(regionId,value){this.regionSpec.get(regionId).each(function(pixel_coords){var pixel=pixelByCoords(pixel_coords);if(pixel.value)pixel.repaint(value);});}
this.highlightRegion=function(regionId){if(regionId==this.highlightedRegion)return;this.highlightedRegion=regionId;this.regionSpec.get(regionId).each(function(pixel_coords){var pixel=pixelByCoords(pixel_coords);pixel.highlight();});}
this.deHighlightRegion=function(regionId){if(this.highlightedRegion==null)return;this.highlightedRegion=null;this.regionSpec.get(regionId).each(function(pixel_coords){var pixel=pixelByCoords(pixel_coords);pixel.deHighlight();});}
this.pixelMouseOver=function(pixel){if(this.editMode==0)return;this.highlightRegion(pixel.regionId);}
this.pixelMouseOut=function(pixel){if(this.editMode==0)return;this.deHighlightRegion(pixel.regionId);}
this.startEditMode=function(date){$trBodyMap.editMode=1;}
this.endEditMode=function(){$trBodyMap.editMode=0;}
this.closeForm=function(){$trBodyMap.editMode=0;$trBodyMap.repaint($trBodyMap.currentDate);}
this.submitForm=function(){$trBodyMap.currentDate=tr_form.date;$trBodyMap.hideBodyMap();}
this.hideBodyMap=function(){$trBodyMap.active=false;$bodyMapPixels.values().each(function(pixel){pixel.hide();});}
this.showBodyMap=function(){this.active=true;if(this.currentDate==null||stringToDate(this.currentDate).getTime()>(start_date.getTime()+42*24*60*60*1000)){var d=new Date(start_date.getTime()+(39*24*60*60*1000));this.currentDate=dateToString(d);}
this.repaint(this.currentDate);$bodyMapPixels.values().each(function(pixel){pixel.show();});}
this.stripMove=function(e){if(!this.active||this.editMode==1||tr_form.visible)return;var d=dayToDate((Event.pointerX(e)-image_coords[0]-2-calculated_coords.active_area[0])/14);var date=dateToString(d);showDateHover(e,getReadableDate(d));if(this.currentDate!=null&&date==this.currentDate)return;if(tr_values[date]==null||tr_values[date]['data'][this.trackerFieldId]==null)return;this.currentDate=date;this.repaint(date);}
this.stripMouseOut=function(e){var d=dayToDate((Event.pointerX(e)-image_coords[0]-2-calculated_coords.active_area[0])/14);}
this.repositionAndShow=function(yOffset,refElement,sectionElement){var x=505;var y=30;Position.clone(refElement,sectionElement,{setHeight:false,setWidth:false,offsetTop:y+yOffset,offsetLeft:x-6});Element.hide('bx_r_arr');Element.hide('bx_l_arr');sectionElement.show();}
this.enableEditMode=function(){this.editEnabled=true;}
this.fieldId=fieldId;this.trackerFieldId=this.fieldId.match(/\user_tracker_data_([\w-]*)$/)[1];this.editMode=0;this.currentDate=null;this.active=true;this.pixelSize=options["pixel_size"];this.name=options["name"];this.width=options["width"];this.height=options["height"];this.zeroValue=options["zero_value"];this.defaultValue=options["default_value"];var ctrpos=Position.cumulativeOffset($('chart_container'));this.offsetTop=ctrpos[1]+110;this.offsetLeft=ctrpos[0]+120;this.highlightedRegion=null;this.regionPainPixels=new Hash();this.editEnabled=false;this.regionNames=new Hash();for(var i=0;i<options["regions"].length;i++){this.regionNames.set(i,options["regions"][i]);}
this.regionSpec=new Hash(options["regions_spec"]);var rSpecKeys=this.regionSpec.keys();for(var i=0;i<rSpecKeys.length;i++){var regionId=rSpecKeys[i];var regionPixels=this.regionSpec.get(regionId);for(var j=0;j<regionPixels.length;j++){new Pixel(regionPixels[j],this,regionId);}
new PainPixel(regionId,this);}
this.regionSliders=new Hash();var painStrip=$("bm_painstrip");var chartOffset=Position.cumulativeOffset($('chart_container'));painStrip.setStyle({background:"url(/RoR/images/blank.gif) repeat scroll 0 0",height:"15px",width:"603px",position:"absolute",left:(chartOffset["left"]+tr_coords["pain"][0])+"px",top:(chartOffset["top"]+tr_coords["pain"][1])+"px"});painStrip.id=this.fieldId+"_painstrip";painStrip.show();Event.observe(this.fieldId+"_painstrip","mousemove",function(e){$trBodyMap.stripMove(e);});Event.observe(this.fieldId+"_painstrip","click",function(e){if(!tr_form.visible)tr_image_click(e);});var pixelOPain=$('pixel_o_pain');pixelOPain.hide();pixelOPain.addClassName("pt_pain_mo");Event.observe('pixel_o_pain','mousemove',centerPainPixel);Event.observe('pixel_o_pain','mouseout',centerPainPixel);Event.observe('pixel_o_pain','click',function(e){$trBodyMap.unloadPixel(e)});pixelOPain.setStyle({height:(2*this.pixelSize)+"px",width:(2*this.pixelSize)+"px",position:"absolute",left:this.offsetLeft+"px",top:this.offsetTop+"px",zIndex:150});this.cursorLoaded=false;this.loadCursor=function(){if(!this.editMode||this.cursorLoaded)return;$(this.fieldId+"_ptpn_msg").hide();$('pixel_o_pain').show();this.cursorLoaded=true;}
this.moveLoadedCursor=function(e){if(!$trBodyMap.editMode||!$trBodyMap.cursorLoaded)return;var y=Event.pointerY(e)-$trBodyMap.offsetTop;if(y<0||y>($trBodyMap.height*$trBodyMap.pixelSize))return;centerPainPixel(e);}
this.unloadPixel=function(e){var x=parseInt((Event.pointerX(e)-$trBodyMap.offsetLeft)/14);var y=parseInt((Event.pointerY(e)-$trBodyMap.offsetTop)/14);var pixel=pixelByCoords([x,y]);$('pixel_o_pain').hide();$trBodyMap.cursorLoaded=false;if(pixel!=null){if($trBodyMap.regionPainPixels.get(pixel.regionId)==null){if(pixel.value==0){$trBodyMap.togglePixel(pixel);}
$trBodyMap.regionPainPixels.set(pixel.regionId,pixel);painPixelByRegionId(pixel.regionId).show(pixel);}
$trBodyMap.validate();}
$($trBodyMap.fieldId+"_ptpn_msg").show();}
Event.observe('chart_container','mouseover',this.moveLoadedCursor);$('bm_pain_datebubble').setStyle({left:(this.offsetLeft+415)+"px",top:(this.offsetTop+15)+"px"});$('bm_pain_datebubble').show();this.showBodyMap();}