
var solaceApi = {
	API_URL: "/answers/api/1.0",
	
	sendRequest: function(uri, options, callbacks){
		options["format"] = "json";
	
		dojo.xhrGet({
			url: solaceApi.API_URL + uri,
			content: options,
			handleAs: "json-comment-optional",
			load: callbacks.load,
			error: callbacks.error
		});
	}
};

var outright = {
	URL: "/answers",
	
	initialize: function()
	{
		dojo.query(".type-here-field").forEach(
			function(field){
				field.defaultText = field.value;
				dojo.connect(field, "onfocus", function(ev) {
					if(field.value == field.defaultText)
					{
						field.value = "";
					}
					dojo.addClass(field, "type-here-selected");
				});
				dojo.connect(field, "onblur", function(ev) {
					if(field.value == "")
					{
						field.value = field.defaultText;
					}
					setTimeout(
						function(){
							dojo.removeClass(field, "type-here-selected");
						},
						500);
				});
			}
		);
	},
	
	/*
	 * This function closes the box with messages and sends a command to remove them from the database 
	 */
	closeMessages: function(){
		dojo.byId('flash-messages').style.display='none';
		solaceApi.sendRequest("/_clear_messages/", {}, {load: function(){}, error: function(){}});
	},
	
	/*
	 * This function deletes SSO cookie and redirects the user to /logout page at outright.com
	 */
	signout: function()
	{
		document.cookie = OutrightConfig.SSOCookieName + "=; domain=" + OutrightConfig.SSOCookieDomain + "; path=/";
		var url = document.location.href;
		url += (url.indexOf("?") == -1 ? "?" : "&") + "ref";
		document.location = url;
	},
		
	/*
		This function returns an URL for a Solace object serialized to json.
	*/
	urlFor: function(obj, type)	{
		if(!type){
			type = obj["#type"];
		}
		switch(type){
			case "solace.question":
				return outright.URL + "/" + obj["slug"] + "-" + obj["id"];
			case "tag":
				return outright.URL + "/tags/" + obj;
		}
		return outright.URL;
	},
	
	/*
		Retrieves a list of member's questions using AJAX call to Solace API
	*/
	loadUserQuestions: function (data, offset, limit, order, callback){
		 solaceApi.sendRequest(
		 	"/questions/user/" + data["user"],
		 	{
		 		offset: offset, 
		 		limit: limit,
		 		order: order
		 	},
		 	{
		 		load: callback,
		 		error: function(err) {alert(err); outright.displayMessageBox("Data cannot be retrieved.");}
		 	}
		 );
	},
	
	/*
		Retrieves a list of member's answers using AJAX call to Solace API
	*/
	loadUserReplies: function (data, offset, limit, order, callback){
		 solaceApi.sendRequest(
		 	"/posts/user/" + data["user"],
		 	{
		 		offset: offset, 
		 		limit: limit,
		 		order: order
		 	},
		 	{
		 		load: callback,
		 		error: function(err) {alert(err); outright.displayMessageBox("Data cannot be retrieved.");}
		 	}
		 );
	},
	
	
	/*
	 * Hides main content on the page. This function is being called when the search results are displayed.
	 */
	hideContent: function()	{
		var cse = dojo.byId("cse");
		if(cse){
			var div = dojo.byId("outright-content");
			if(div) div.style.display = "none";
			
			cse.style.display = "block";
		}
	},
	
	/*
	 *   Those functions allow to submit vote using AJAX request. 
	 */
	voteUp: function(post) { outright.setVote(post, 1); },
	voteDown: function(post) { outright.setVote(post, -1); },
	clearVote: function(post) { outright.setVote(post, 0); },
	setVote: function (post, vote){
		solaceApi.sendRequest(
			"/_set_vote/" + post + "/" + vote,
			{},
			{
				load: function(result){
					if(result.result){
						dojo.byId("vote-up-" + post).style.display = vote == 1 ? "none" : "inline";
						dojo.byId("unvote-up-" + post).style.display = vote != 1 ? "none" : "inline";
						dojo.byId("vote-down-" + post).style.display = vote == -1 ? "none" : "inline";
						dojo.byId("unvote-down-" + post).style.display = vote != -1 ? "none" : "inline";
						dojo.byId("votes-" + post).innerHTML = result.votes;
					}
					else{
						outright.displayMessageBox(result.message);
					}
				}
			}
		);
	},
	
	/*
		Displays a message to user.
		TODO: Display it in DHTML box instead of the plain message box.
	*/
	displayMessageBox: function(message){
		alert(message);
	},
	
	/*
		Replaces placeholders with the actual values in the template.
	*/
	templatize: function(templateHtml, data){
		var value = templateHtml; 
		for(key in data)
		{
			value = value.replace("##" + key + "##", data[key]);
		}
		return value;
	},
	
	/*
		Formats a timespan retrieved from Solace. Timespan is a six-elements array that contains
		number of years, months, days, hours, munites and seconds passed between two dates. 
	*/
	format_timespan: function(ts)
	{
		var labels = ["year", "month", "day", "hour", "minute", "second"];
		var result = [];
		for(var i = 0; i < 6; i++)
		{
			if(ts[i] > 0)
			{
				result[result.length] = ts[i] + " " + labels[i] + (ts[i] > 1 ? "s" : "");
				if(result.length == 2) break;
			} 
		}
		
		return result.length ? result.join(" ") : "0 seconds";
	},
 
 	/*
 	 * Displays a given DOM element as a pop-up window on the top of the page.
 	 */
    showPopup: function(id)
    {
    	document.getElementById("popup-overlay").style.display = "block";    	
    	document.getElementById(id).style.display = "block";    	
    },

	/*
	 * Hides a pop-up window
	 */
    hidePopup: function(id)
    {
    	document.getElementById("popup-overlay").style.display = "none";    	
    	document.getElementById(id).style.display = "none";    	
    },
    
    /*
     * Sends feedback to the server.
     * TODO: Implement this function
     */
    sendFeedback: function()
    {
    	dojo.xhrPost({
    		url: "/scripts/send-feedback.php",
    		content: {
    			message: dojo.byId("feedback-message").value,
    			from: dojo.byId("feedback-from").value
    		},
    		load: function(data){
		    	outright.hidePopup("feedback");
    		}
    	});
    	return false;
    },
    
    toggleCommentBox: function(p)
    {
    	dojo.query(".new_reply", p.parentNode.parentNode)[0].style.display = "block";
    }
  }

/* Displays a list of objects with pagination. */

function PaginatedList(container, context, loadDataFunction, templateFunction, pageSize, defaultOrder){
	this.container = container;
	this.loadDataFunction = loadDataFunction;
	this.templateFunction = templateFunction;
	this.pageSize = pageSize;
	this.context = context;
	
	this.pageIndex = -1;
	this.order = defaultOrder;
	
	this.loadPage(0);
}  

PaginatedList.prototype.reorder = function(order)
{
	this.order = order;
	this.loadPage(0);
}

PaginatedList.prototype.loadPage = function(pageIndex){
	var loader = this;
	//this.container.innerHTML = "";
	this.loadDataFunction(this.context, this.pageSize * pageIndex, this.pageSize, this.order, function(response){
		loader.pageLoaded(pageIndex, response);
	});
}

PaginatedList.prototype.pageLoaded = function(pageIndex, data){
	this.container.innerHTML = this.templateFunction(data);
}

dojo.addOnLoad(outright.initialize);