/*
 * startupSQUARE Javascript library.
 * 
 * 2010. All rights reserved.
 */


/**
 * Sends an AJAX request to follow a user by the current user.
 * @param userId		The id of the current user.
 * @param followUserId	The id of the user to follow.
 * @param successCB		The function to call back if the call succeeded.
 * @param failedCB		The function to call back if the call failed.
 * @return	True if successful, false otherwise
 */
function followUser(userId, followUserId, successCB, failedCB, updatingCB){
	var ajaxUrl = "index.php?eID=ajax";
	if(updatingCB){
		updatingCB(true);
	}
	$.post(
		ajaxUrl,
		{
			update_profile	: userId,
			action			: 'followUser',
			uid				: followUserId
		},
		function(data) {
			if(updatingCB){
				updatingCB(false);
			}
			if( data.status=="OK"){
				try{
					_gaq.push(['_trackEvent', 'profile', 'follow', userId + ' follows '+followUserId]);
				}catch(e){}
				successCB(true);
			}else{
				failedCB(false);
			}
		},
		"json"
	);
}

/**
 * Sends an AJAX request to stop following a user by the current user.
 * @param userId		The id of the current user.
 * @param followUserId	The id of the user to stop following.
 * @param successCB		The function to call back if the call succeeded.
 * @param failedCB		The function to call back if the call failed.
 * @return	True if successful, false otherwise
 */
function stopFollowingUser(userId,followUserId, successCB, failedCB,updatingCB){
	var ajaxUrl = "index.php?eID=ajax";
	if(updatingCB){
		updatingCB(true);
	}
	$.post(
		ajaxUrl,
		{
			update_profile	: userId,
			action			: 'stopFollowUser',
			uid				: followUserId
		},
		function(data) {
			if(updatingCB){
				updatingCB(false);
			}
			if( data.status=="OK"){
				try{
					_gaq.push(['_trackEvent', 'profile', 'unfollow', userId + ' unfollows '+followUserId]);
				}catch(e){}
				successCB(true);
			}else{
				failedCB(false);
			}
		},
		"json"
	);
}

/*
 * Idea Scripts
 */
function deleteIdea(ideaId){
	var r = confirm('Are you certain you want to delete this idea?');
	if(r){
		try{
			_gaq.push(['_trackEvent', 'idea', 'delete', 'Idea '+ideaId + ' deleted.']);
		}catch(e){}
		window.location.assign('index.php?id=viewIdea&action=delete&idea='+ideaId);
	}else{}
}

/*
 * Administration
 */
var profilesUpdated;
var ideasUpdated;

/**
 * Cleans the search index by removing duplicate entries.
 * @param toUpdate	Text, should be 'profiles' or 'ideas'.
 */
function cleanSearchIndex(toUpdate){
	$('#progress').text('Cleaning index...');
	if(toUpdate=='profiles'){
		$.post(
				'index.php?eID=ajax',
				{
					'request'	: 'admin',
					'action'	: 'clean_search_index_profiles'
				},
				function(data){
					if(data.status=='OK'){
						$('#progress').text('Done. Removed ' + data.duplicates + ' duplicates');
					}else{
						$('#progress').text("Error: " + data.error);
					}
				},
				"json"
			);
	}
}
/**
 * Rebuild the search index by removing and adding back profiles/people and ideas.
 * @return
 */
function rebuildSearchIndex(toUpdate){
	if(toUpdate=='profiles'){
		profilesUpdated = 0;
		$.post(
				'index.php?eID=ajax',
				{
					'request'	: 'admin',
					'action'	: 'user_list'
				},
				function(data){
					if(data.status=='OK'){
						updateSearchIndexUserProfiles(data.users);
					}else{
						alert('Error getting user list. ' + data.error);
					}
				},
				"json"
			);
	}
	if(toUpdate=='ideas'){
		ideasUpdated = 0;
		$.post(
				'index.php?eID=ajax',
				{
					'request'	: 'admin',
					'action'	: 'idea_list'
				},
				function(data){
					if(data.status=='OK'){
						updateSearchIndexIdeas(data.ideas);
					}else{
						alert('Error getting idea list. ' + data.error);
					}
				},
				"json"
			);
	}
}
function updateSearchIndexUserProfiles(users){
	var numUsers = users.length;
	$('#progress').html('Updated <span id=\"profilesUpdated\">0</span> out of '+numUsers+' profiles.');
	var batch = 10;
	for(i=0;i<numUsers;i+=batch){
		fromUid = users[i][0];
		if(i+batch-1>numUsers){
			toUid = users[numUsers-1][0];
		}else{
			toUid = users[i+batch-1][0];
		}
		updateSearchIndexProfiles(fromUid,toUid);
	}
}
function updateSearchIndexProfiles(from,to){
	$.post(
		'index.php?eID=ajax',
		{
			'request'	: 'admin',
			'action'	: 'refresh_search_index_profiles',
			'pFrom'		: from,
			'pTo'		: to
		},
		function(data){
			if(data.status=='OK'){
				profilesUpdated += data.updated;
				$('#profilesUpdated').text(profilesUpdated);
			}else{
				alert("Error: " + data.error);
			}
		},
		"json"
	);
}
function updateSearchIndexIdeas(ideas){
	var num = ideas.length;
	$('#progress').html('Updated <span id=\"ideasUpdated\">0</span> out of '+num+' ideas.');
	var batch = 10;
	for(i=0;i<num;i+=batch){
		fromUid = ideas[i][0];
		if(i+batch-1>num){
			toUid = ideas[num-1][0];
		}else{
			toUid = ideas[i+batch-1][0];
		}
		updateSearchIndexIdeasRange(fromUid,toUid);
	}
}
function updateSearchIndexIdeasRange(from,to){
	$.post(
		'index.php?eID=ajax',
		{
			'request'	: 'admin',
			'action'	: 'refresh_search_index_ideas',
			'pFrom'		: from,
			'pTo'		: to
		},
		function(data){
			if(data.status=='OK'){
				ideasUpdated += data.updated;
				$('#ideasUpdated').text(ideasUpdated);
			}else{
				alert("Error: " + data.error);
			}
		},
		"json"
	);
}

/*	Idea Scripts	*/

// New Idea
var newIdeaHtmlLoaded = false;
function newIdeaDialog(dialogDivId){
	if(!newIdeaHtmlLoaded){
		$.get(
			'index.php?eID=ajax',
			{
				'request'	:	'idea',
				'action'	:	'NewIdeaDlg'
			},
			function(data){
				if(data.status=='OK'){
					$('#sq_dialog_modal_newIdea').html(data.html);
					newIdeaHtmlLoaded = true;
					showNewIdeaDialog();
				}else{
					alert("Error: Unable to load new idea dialog.");
				}
			},
			"json"
		);
	}else{
		showNewIdeaDialog();
	}
}
function showNewIdeaDialog(){
	$('#sq_dialog_modal_newIdea').dialog({
		autoOpen: true,
		height: 560,
		width: 480,
		title: 'Add a new idea',
		resizable: false,
		modal: true
	});
}
function showUpdatingDialog(){
	$('#sq_updating_dialog').dialog({
		autoOpen: true,
		height: 80,
		width: 220,
		title: '',
		resizable: false,
		modal: true
	});
}
function closeUpdatingDialog(){
	$('#sq_updating_dialog').dialog('close');
}
function doPostNewIdea(){
	var title		= $('#title').val();
	var visibility	= $('#visibility').val();
	var industry	= $('#industry').val();
	if(industry!=null){
		industry = industry.join(",");
	}else{
		industry = '';
	}
	var problem		= $('#problem').val();
	
	if(!title){
		alert("You must at least fill out a title.");
		return;
	}
	
	$('#sq_dialog_modal_newIdea').dialog('close');
	
	showUpdatingDialog();
	
	try{
		$.post(
			'index.php?eID=ajax',
			{
				'request'	: 'idea',
				'action'	: 'add',
				'title'		: title,
				'visibility': visibility,
				'industries': industry,
				'problem'	: problem
			},
			function(data){
				closeUpdatingDialog();
				if(data.status=='OK'){
					if(data.url){
						window.location.assign(data.url);
					}
				}else{
					alert("Error: " + data.error);
				}
			},
			"json"
		);
	}catch(e){
		closeUpdatingDialog();
		alert("Unable to post new idea.  Please try again.");
	}
}
 

/*
 * Comments
 */

function getCommentCounts(){
	$('#progress').html("Updating...");
	$.post(
			'index.php?eID=ajax',
			{
				'request'	: 'admin',
				'action'	: 'comment_count'
			},
			function(data){
				if(data.status=='OK'){
					updateCommentCount(data.count);
				}else{
					alert('Error getting idea list. ' + data.error);
				}
			},
			"json"
		);
}
function updateCommentCount(counts){
	var html = "<h3>Current comment counts:</h3>";
	for (var i=0; i<counts.length; i++) {
		var uid = counts[i][0];
		var count = counts[i][1];
		html += "Idea " + uid + " has " + count + " comments.<br/>";
	}
	$('#progress').html(html);
}

function sendDailyEmail(from,to){
	$('#progress').html("Sending emails...");
	$.post(
			'index.php?eID=ajax',
			{
				'request'	: 'admin',
				'action'	: 'daily_email',
				'from'		: from,
				'to'		: to
			},
			function(data){
				if(data.status=='OK'){
					$('#progress').html(data.html);
				}else{
					alert('Error getting idea list. ' + data.error);
				}
			},
			"json"
		);
}

/*
 * Resources LP
 */
function showResource(id){
	var what = "#dialogres"+id;
	var title = $("#resource_"+id+"_title").text();
	var category = $(what).attr("title");
	var link = $("#link"+id).attr("href");
	_gaq.push(['_trackEvent', 'resource','preview',category+":"+title]);
	$(what).dialog({
		autoOpen: true,
		height: 320,
		width: 480,
		title: title,
		resizable: true,
		modal: true,
		buttons: {
			'More Info': function() {
				_gaq.push(['_trackEvent', 'resource','affiliate_link',category+":"+title]);
				$(this).dialog('close');
				var newWindow = window.open(link, '_blank');
				if (newWindow) {
					if (newWindow.focus) {
						newWindow.focus();
					}
					return false;
				}
				return true;
			}
		}
	});
}

/*
 * Commenting
 */

function submitComment(author,subject,comment,list){
	$.post(
			'index.php?eID=ajax',
			{
				'request'	: 'comment',
				'action'	: 'submit',
				'subject'	: subject,
				'comment'	: comment.val()
			},
			function(data){
				if(data.status=='OK'){
					updateCommentListDisplay(list,data.comments);
				}else{
					alert('Error getting comment list. ' + data.error);
				}
			},
			"json"
		);
	comment.val('');
	list.append("<span class='notice'>Comment posted.  Updating list...</span><p/>");
}

function updateCommentList(subject,list){
	$.post(
			'index.php?eID=ajax',
			{
				'request'	: 'comment',
				'action'	: 'get_list',
				'subject'	: subject
			},
			function(data){
				if(data.status=='OK'){
					updateCommentListDisplay(list,data.comments);
				}else{
					alert('Error getting comment list. ' + data.error);
				}
			},
			"json"
		);
}

function updateCommentListDisplay(list,comments){

	list.html('<h3>Questions and Comments:</h3>');	
	for(var i=0;i<comments.length;i++){
		comment = comments[i].comment;
		author = comments[i].authorName;
		authorLink = comments[i].authorLink;
		time = comments[i].time;
		list.append( "<div class='commentWidget'><div class='commentAuthor'><a href='" + authorLink + "'>" + author + "</a></div><div class='commentDetails'>" + time + " (CST)</div><div class='commentText'>" + comment + "</div><a class='commentReply' href=#commentInputBox>reply</a></div>");
		$(".commentWidget").hover(
				function() { $(this).children(".commentReply").show(); },
				function() { $(this).children(".commentReply").hide(); }
		);
	}
}

/*
 *	Messages
 */
function submitMessage(msgid,receiver,subject,message,msgclass,sync){
	if(typeof sync == 'undefined'){
		var sync = false;
	}
	var temp = $.ajax({
			url: 'index.php?eID=ajax',
			data: {
				'request'	: 'message',
				'action'	: 'submit',
				'id'		: msgid,
				'receiver'	: receiver,
				'subject'	: subject,
				'message'	: message.val(),
				'class'		: msgclass
				},
			success: function(data){
						if(data.status=='OK'){
							message.val('');
							return true;
						}else{
							alert('Error sending message: ' + data.error);
							return false;
						}
				},
			error: function(){
					return false;
					},
			dataType: "json",
			async: !sync,
	});
	return temp;
}
function updateMessageItem(id,item,value){
	 return $.post(
			'index.php?eID=ajax',
			{
				'request'	: 'message',
				'action'	: 'update',
				'item'		: item,
				'value'		: value,
				'id'		: id,
			},
			function(data){
				if(data.status=='OK'){
					return true;
				}else{
					alert('FYI: We encountered a problem while updating the status of your message.');
					return false;
				}
			},
			"json"
		);
}
function messageSent(){
	$('#messagebox').hide();
	$('#messageboxnotice').html('<p>Your message was successfully sent.</p>');
	$('#messageboxnotice').show();
}

