/**
 * Class Graph
 * @author - Dani Valentin
 */
function Graph(screenName, fCeleb) {
	this.screenName = screenName;
	this.fCeleb = fCeleb;
	
	//clear results
	$("#results").html("");
	
	this.getIds();
}

Graph.prototype.getIds = function() {
	var self = this;
	var call = "/rest/graph/" + this.screenName;
	
	if (this.fCeleb) {
		call += "/?filters=celeb";
	}
	
	if (this.validateScreenName()) {
		$.ajax({
			url: call,
			method: "GET",
			dataType: "json",
			beforeSend: function() {
				//disable submit button
				$("#bt-search").attr("disabled","disabled");
			
				//show loading
				$("#loading").css("visibility","visible");
				$("#msg").hide();
			},
			complete: function(xmlhttprequest) {
				$("#bt-search").attr("disabled","");
				
				//hide loading
				$("#loading").css("visibility","hidden");
			},
			success: function(data) {
				self.getInfo(data);
			},
			error: function(xmlhttprequest,status,errorthrown) {
				var result = jsonParse(xmlhttprequest.responseText);
				self.showError(result[0].message);
			}
		});
	}
};

Graph.prototype.validateScreenName = function() {
	if (this.screenName == "" || this.screenName == "your twitter username") {
		this.showError("Enter your twitter username.");
		return false;
	}
	return true;
};

Graph.prototype.getInfo = function(data) {
	var self = this;
	
	$.each(data, function(i,item) {
		self.renderInfo(item);
	});
};

Graph.prototype.renderInfo = function(user) {
	//get user informations
	var name = user.name;
	var screenName = user.screen_name;
	var description = (user.description != null)?user.description:"";
	var profileImage = user.profile_image_url;
	var profileFollowers = user.followers_count;
	var profileFriends = user.friends_count;
	
	//create html
	var profile = $("<div />").addClass("profile");
	profile.append($("<img src=\"" + profileImage + "\" width=\"48\" height=\"48\" />"));
	var info = $("<div />").addClass("info");
	info.append("<h3>" + name + " (" + screenName + ")</h3>");
	info.append("<small>Followers: " + profileFollowers + "</small><br />");
	info.append("<small>Following: " + profileFriends + "</small>");
	profile.append(info);
	profile.append("<p class=\"description\">" + description + "</p>");
	profile.append("<a href=\"http://www.twitter.com/" + screenName + "\" target=\"_blank\">see twitter</a>");
	
	
	//append to page
	$("#results").append(profile);
};

Graph.prototype.showError = function(msg) {
	$("#msg").html(msg).show();
};