/*
 * Copyright (C) 2009 WorkSmart Labs, Inc.
 */

/**
 * Abstracts away operations with the TrackStatistics that displays
 * statistics data and lets the user name the track.
 *
 * @author Vera Kern <vera@worksmartlabs.com>
 */

var NO_TRACK_NAME_COMMENT = 'click to enter name';
var DEFAULT_NAME = 'unspecified';
var SPACE = '\u00A0';

/**
 * Creates a new TrackStatistics object.
 * @param container DOMElement container where to put the statistics. 
 */
function TrackStatistics(container, background, mode, currentId, units) {
    this.container_ = container;
    this.background_ = background;
    this.currendId_ = currentId;
    this.units_ = units;
    this.mode_ = mode;
    this.trackNameTextView_ = new TextViewWithDefaultText(el('track_name'), NO_TRACK_NAME_COMMENT);
    if (this.mode_ == TracksPage.TracksPageType.shared || 
    	this.mode_ == TracksPage.TracksPageType.facebook) {
        displayNone(el('save_button'));   
    } else {       
        var saveButton = el('save_button');
        setClickHandler(saveButton, this, this.save);
    }
} 

/**
 * This function update the currentId
 *
 * @param int the current id from the trackspage.
 */
TrackStatistics.prototype.setCurrentId = function(currentId) {
    this.currentId_ = currentId;
}

/**
 * This function hides the statistics container
 *
 * @param DOM element container
 */
TrackStatistics.prototype.hide = function() {
    displayNone(this.container_);
    displayNone(this.background_);
}

/**
 * This function displays the statistics container
 *
 * @param DOM element container
 */
TrackStatistics.prototype.show = function(track) {
    this.setValues_(track);
    displayBlock(this.container_);
    displayBlock(this.background_);
}

/**
 * This function sets the values for the statistics and
 * shows the container
 *
 * @param integer trackId
 */
TrackStatistics.prototype.setValues_ = function(track) {
    if (this.mode_ == 0) {
        if (track['exercise_type'] == null) {
            el('exercise_type_unspecified').selected = true;
        } else {
            el(track['exercise_type']).selected = true;
        }
    } else {
        el('exerciseType').firstChild.nodeValue = this.getExerciseType_(track['exercise_type']);
    }
    this.trackNameTextView_.clear();
    if (track['track_name'] == null) {
        if (this.mode_ == TracksPage.TracksPageType.normal) {
            this.trackNameTextView_.setDefault();
        } else {
            el('track_name').firstChild.nodeValue = DEFAULT_NAME;
        }
    } else {
        if (this.mode_ == TracksPage.TracksPageType.normal) {
            el('track_name').value = track['track_name'];
        } else {
            el('track_name').firstChild.nodeValue = track['track_name'];
        }
    }
    this.setSpanValue_(el('climb'), track['climb'], SPACE + 'm');
    this.setSpanValue_(el('avgSpeed'), track['avgSpeed'], SPACE + this.units_ + '/h');
    this.setSpanValue_(el('calories'), track['calories'], SPACE + 'kcal');
    this.setSpanValue_(el('maxSpeed'), track['maxSpeed'], SPACE + this.units_ + '/h');
    this.setSpanValue_(el('minSpeed'), track['minSpeed'], SPACE + this.units_ + '/h');
    this.setSpanValue_(el('avgPace'), this.calcPace_(track['avgSpeed']), 
                       SPACE + 'min/' + this.units_);
}

/**
 * This function sets the value of the span element
 * to the passed string
 *
 * @param DOM element span Element
 * @param string
 */
TrackStatistics.prototype.setSpanValue_ = function(spanEl, value, units) {
    if (value == 0 || value == null) {
        value = '-';
        units = '';
    }
    spanEl.firstChild.nodeValue = (value + units);
}

/**
 * This function calculates the pace.
 *
 * @param number average speed value
 * @return number average pace
 */
TrackStatistics.prototype.calcPace_ = function(speed) {
    if(speed == null || speed == 0) {
        return 0;
    } else {
        pace = (60/speed);
        minutes = Math.floor(pace);
        seconds = Math.floor((pace - minutes) * 60);
        if(seconds < 10) {
            seconds = '0' + seconds;    
        }
        return minutes + ":" + seconds;
    }
}

/**
 * Returns the exercise type in English
 * 
 * @param string exercise_type from the database
 * @return string exercise type in English
 */

TrackStatistics.prototype.getExerciseType_ = function(exerciseType) {
    switch (exerciseType) {
	    case 'exercise_type_running':
	        return 'Running';
	    case 'exercise_type_biking':
	        return 'Biking';
	    case 'exercise_type_walking':
	        return 'Walking';
	    case 'exercise_type_skiing':
	        return 'Skiing';
	    case 'exercise_type_driving':
	        return 'Driving';
	    case 'exercise_type_horseback_riding':
	        return 'Horseback Riding';
	    case 'exercise_type_kayaking':
	        return 'Kayaking';
	    case 'exercise_type_skating':
	        return 'Skating';
	    case 'exercise_type_rollerblading':
	        return 'Rollerblading';
	    case 'exercise_type_snowboarding':
	        return 'Skating';
	    case 'exercise_type_hiking':
	        return 'Hiking';
	    case 'exercise_type_team_sports':
	        return 'Team Sports';
	    case 'exercise_type_aerobics':
	        return 'Aerobics';
	    case 'exercise_type_swimming':
	        return 'Swimming';
	    case 'exercise_type_dancing':
	        return 'Dancing';
	    case 'exercise_type_pilates':
	        return 'Pilates';
	    case 'exercise_type_weight_lifting':
	        return 'Weight Lifting';
	    case 'exercise_type_yoga':
	        return 'Yoga';
	    case 'exercise_type_elliptical':
	        return 'Elliptical';
	    case 'exercise_type_custom':
	        return 'Custom';
	    default:
	        return 'Unspecified';
    }
}

/**
 * This function saves the changed track details to the
 * trackData array and the database
 *
 * @param string name of the track
 * @param string exercise type
 */
TrackStatistics.prototype.save = function() {
    el('save_button').blur();
    var track_name = el('track_name').value;
    var exercise_type = el('exerciseType').value;
    
    // Change the values in the trackData array
    trackData[this.currentId_]['track_name'] = track_name;
    trackData[this.currentId_]['exercise_type'] = exercise_type;
    
    // Send the changes to the database
    var ajaxRequest = createAjaxRequestObject();
    var queryString = "?trackId=" + this.currentId_ + 
                      "&track_name=" + track_name + 
                      "&exercise_type=" + exercise_type +
                      "&type=update";                  
    ajaxRequest.open("GET", "update_track.php" + queryString, true);
    ajaxRequest.send(null);
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            // ...check whether the responseText equals 1 
            // -> the responseText has the number of affected rows
            if (ajaxRequest.responseText == 1){
                // Write saved instead of saved and set it back to save after 5 seconds
                saveValue = el('save_button').firstChild;
                saveValue.nodeValue = 'Saved';                    
                this.active = window.setInterval("tracksPage.setTextBack()", 5000);
            }
        }
    }
}

/**
 * This function sets 'saved' back to 'Save'
 * after a track has been changed.
 *
 */
TrackStatistics.prototype.setTextBack = function() {
    saveValue = el('save_button').firstChild;
    saveValue.nodeValue = 'Save';     
    window.clearInterval(this.active);
}