/*
 * startupSQUARE Javascript library.
 * 
 * 2010. All rights reserved.
 */
var ajaxUrl = "index?eID=ajax";
	
/**
 * 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){
	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){
	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(url){
	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(url);
	}else{}
}

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

function triggerCron(){
	$('#progress').text('Triggering process...');
		$.post(
				ajaxUrl,
				{
					'request'	: 'admin',
					'action'	: 'cron'
				},
				function(data){
					if (data.status == 'OK') {
						$('#progress').html(data.html);
					}else{
						$('#progress').html(data.error);
					}
				},
				"json"
			);
}

/*	Idea Scripts	*/

// New Idea
var newIdeaHtmlLoaded = false;
function newIdeaDialog(dialogDivId,url){
	if(!newIdeaHtmlLoaded){
		$.get(
			url,
			{},
			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: 490,
		width: 480,
		title: 'Add a new idea',
		resizable: true,
		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(url){
	var title		= $('#NewIdeaForm_title').val();
	var visibility	= $('#NewIdeaForm_visibility').val();
	var industry	= $('#NewIdeaForm_industries').val();
	var problem		= $('#NewIdeaForm_problem').val();
	
	if(!title){
		alert("You must at least fill out a title.");
		return;
	}
	
	$('#sq_dialog_modal_newIdea').dialog('close');
	
	showUpdatingDialog();
	
	try{
		$.post(
			url,
			{
				'request'	: 'idea',
				'action'	: 'add',
				'title'		: title,
				'visibility': visibility,
				'industries': industry,
				'problem'	: problem
			},
			function(data){
				closeUpdatingDialog();
				if(data==null){
					alert("An unknown error has occurred.");
					return;
				}
				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(
			ajaxUrl,
			{
				'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);
}


/*
 * 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: false,
		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;
			}
		}
	});
}

function showFlashMessage(text){
	showFlashMessage(text, 'success');
}
function showFlashMessage(text,type){
	$('#flash_message').removeClass();
	$('#flash_message').addClass(type);
	
	$('#flash_message').text(text);
	$('#flash_message').show();
	$("#flash_message").animate({opacity: 1.0}, 3000).fadeOut("slow");
}

/*
 * Commenting
 */

function submitComment(type,subject,comment,list, url){
	if(url==null)
		url = ajaxUrl;
	$.post(
			url,
			{
				'request'	: 'comment',
				'action'	: 'submit',
				'type'		: type,
				'subject'	: subject,
				'comment'	: comment.val()
			},
			function(data){
				if(data.status=='OK'){
					updateCommentListDisplay(list,data.comments,url);
					if(data.follow){
						$('#unfollow').show();
						$('#follow').hide();
						showFlashMessage(data.flash)
					}
				}else{
					alert('Error getting comment list. ' + data.error);
				}
			},
			"json"
		);
	comment.val('');
	list.append("<span class='notice'>Comment posted.  Updating list...</span><p/>");
}

function updateCommentList(type,subject,list,url){
	if(url==null)
		url=ajaxUrl;
	$.post(
			url,
			{
				'request'	: 'comment',
				'action'	: 'get_list',
				'type'		: type,
				'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){
	 $.post(
			ajaxUrl,
			{
				'request'	: 'message',
				'action'	: 'submit',
				'id'		: msgid,
				'receiver'	: receiver,
				'subject'	: subject,
				'message'	: message.val(),
				'class'		: msgclass
			},
			function(data){
				if(data.status=='OK'){
					message.val('');
					messageSuccess();
				}else{
					alert('Error sending message: ' + data.error);
					messageFailed();
				}
			},
			"json"
		);
}

function updateMessageItem(id,item,value){
	 return $.post(
			ajaxUrl,
			{
				'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>Message sent.</p>');
	$('#messageboxnotice').show();
}
function messageWait(){
	$('#messagebox').hide();
	$('#messageboxnotice').html('<p>Sending message, please wait ...</p>');
	$('#messageboxnotice').show();
}
function messageFailed(){
	$('#messagebox').hide();
	$('#messageboxnotice').html('<p>Failed sending Message!</p>');
	$('#messageboxnotice').show();
}
/*
 * Widgets
 */
function loadWidgets(){
	$('.skinnyWidget').hover( function() {
		$(this).children('.skinnyPopup').delay(600).fadeIn(300);
	});
	$('.skinnyWidget').mouseleave( function() {
		$(this).children('.skinnyPopup').stop(1,1).hide();
	});
}
