/**
* This file will specify all utility functions for Todoroo, mostly
* dealing with API functions.
*/

// define the namespace
function Todoroo() {
}

/** The base url for api calls to Todoroo */
Todoroo.baseURL = "http://todoroo.appspot.com/api/";

/** Get Coaches (from market) with a callback (optional) */
Todoroo.getCoaches = function(callback, start, limit) {
    if (typeof callback == "undefined") // sync
	return Todoroo.getCoachesSync();
    
    // asynchronous
    Todoroo.getCoachesAsync(callback);
};

/** Construct a string of the form urlKey1=urlVal1&urlKey2=urlVal2... */
Todoroo.constructParamString = function(paramMap) {
    var paramArray = [];
    for (var index in paramMap)
	paramArray.push(index + "=" + escape(paramMap[index]));

    return paramArray.join('&');
};

/** Get the coaches from the server and then call the callback function
with the returned JSON data. */
Todoroo.getCoachesAsync = function(callback) {
    var url = Todoroo.baseURL + '?' + Todoroo.constructParamString({
	method: "getCoaches"
    });
    $.getJSON(url, null, callback);
};

// @TODO: implement
Todoroo.getCoachesSync = function(callback) {
    return "";
};


Todoroo.getRatingWordFromCoachObj = function(coachObj) {
	var ratingWord = "";
	if (coachObj.metaData == null)
		ratingWord = "four";
	else {
		// divide by one half to get the remainder of the rating
		// remember, we're restraining to increments of 0.5

		var coachRating = coachObj.metaData.averageRating;

		// figure out if we need a half star
		var andAHalf = false;

		// just the whole number component
		var coachRatingInt = Math.floor(coachRating);

		// only want to go up to next star if > 0.9
		var coachRatingFraction = coachRating - coachRatingInt;
		andAHalf = coachRatingFraction >= 0.5;
		if (coachRatingFraction > 0.9) {
			andAHalf = false;
			coachRatingInt++;
		}

		switch (coachRatingInt) {
		case 0:
		default:
			ratingWord = "zero";
		break;
		case 1:
			ratingWord = "one";
			break;
		case 2:
			ratingWord = "two";
			break;
		case 3:
			ratingWord = "three";
			break;
		case 4:
			ratingWord = "four";
			break;
		case 5:
			ratingWord = "five";
			break;
		}

		if (andAHalf)
			ratingWord += "AndAHalf";
	}

	return ratingWord;
};
