$(document).ready(function() 
{
 	$('span.timeago').timeago();
 	$('span.timeago').show();
 	
 	$("#publish_box form textarea").focus(function() { $(this).height("40px"); $(this).val(""); });
	//$("#publish_box form textarea").blur(function() { $(this).height("16px"); });
	
	$('#nav_login').click(
		function(event) { event.preventDefault(); $('#login_box').toggle(); $('#id_username').focus(); 
		
			$("body").bind("click", function (event) {
    			var outside = $(event.target).parents("#login_box").length === 0;
    			if (outside) {
        			$("#login_box").hide();
        			$("body").unbind("click");
    		}
		});
		return false; 
	});
	
	/* Options in lists _____*/
	$('.options').live("click",
		function() { $(this).children('ul').toggle(); return false;  });
	
	$('#fb').click(function() { FB.Connect.showPermissionDialog('read_stream'); });
	
	
	/* Behaviour on buttons */
	$('input.button').live("click", function() {
		if(!$(this).is('.static')) 
		{
			$(this).addClass('button_sending');
			$(this).val('Sending...');
		}
		//$(this).attr("disabled", true);
	});
	
	$('#filter li').hover(function() { $(this).find('.helptip').show(); }, function() { $(this).find('.helptip').hide(); });
	$(".helptip").hover(function() { console.log($(this).attr('title')); });
	

	$(".helptip").each(function() {                       // you have to use the .each() function to parse each element with its title
        var contentStr = $(this).attr("title");       // take the title and store in a variable
        $(this).attr({ title: "" });                          // empty the element title (now it's useless)
        $(this).simpletip({                             // apply the simpletip to the element
                content: contentStr                     // use the variable (which stores the title) as content
        });
	}); 

	$("#notifier a.close").click(function() { $("#notifier").hide(); });
	
	$("#button_save_email").click(function(){
		var email = $("#id_email").val();
		$.post(base_url+'ajax/validation/email_exists', { email: email }, function(data) {
			if(data == 'true'){
				$.post(base_url+'ajax/users/confirm_email', { email: email }, function(data) {
					message_JSON = eval("d="+data);
					if(message_JSON['result'] == 1){
						$("#button_save_email").removeClass('sending');
						$("#button_save_email").val('Save');
						dismissConfirmEmail();
					}
					else{
						$("#button_save_email").removeClass('button_sending');
						$("#button_save_email").val('Save');
						$("#status_conf_email").html("An error ocurred saving your email address. Try again later.");
						$("#status_conf_email").removeClass("none");
					}
				});
			}
			else{
				$("#button_save_email").removeClass('button_sending');
				$("#button_save_email").val('Save');
				$("#status_conf_email").html("That email address is not valid or it is already in use.");
				$("#status_conf_email").removeClass("none");
			}
		});
	});
	
});


function showLogin() {
	$.dialog(function() {
		$.get(base_url + "ajax/users/login", { }, function(data) {
			$.dialog(data);
		});
	});
	return false;
}


/* Comments
--------------------------------------*/
function sendComment(){ 
	var to_id = $("#to_id").val();
	var message = $("#id_message").val();
	var type = $("#type").val();
	
	$("input[type=submit]").hide();
	$("#prev_status").hide();
	$("#comment_sending").show();
	
	if(type == 'user' || type == 'location') 
	{
		$.post( base_url + "ajax/"+type+"s/post_comment", { to_id: to_id, message: message }, function(data) {
			message_JSON = eval("d="+data);
			$("#comment_sending").hide();
			$("#send_comment").find("input[type=submit]").show();
			$("#prev_status").show();
			$("#send_comment").find("textarea").val("");
			$("#stream_list").prepend(message_JSON['html']);
			$('.no_item').remove();
			$("input[type=submit]").show();
		});
	}

	

	return false; 
}

function updateStatus(){
    var text = $("#id_shortinfo").val();
    var type = $("#type").val();
    
    $("#publish_box input[type=submit]").hide();
	$("#prev_status").hide();
	$("#comment_sending").show();
	
    $.post(base_url+"ajax/users/edit_short_info", { text: text, type: type },
        function(data) {
            message_JSON = eval("d="+data);
            if(message_JSON['result'] == 1) {
            	if(type == 'home') {
            		$('#prev_text').html(text);
            		$('#posted_on').html("<span class='timeago' title="+message_JSON['date']+">"+message_JSON['date']+"</span> from nowntown");
            		$('#id_shortinfo').val('What are you doing now?');
            	} 
            	else if(type == 'profile') {
            		$("#stream_list").prepend(message_JSON['html']);
            		$('#id_shortinfo').val('Post a comment here');
            	}
            	$('span.timeago').timeago();
            	$("#comment_sending").hide();
				$("#update_status").find("input[type=submit]").show();

            } else {
                $("#comment_sending").hide();
				$("#update_status").find("input[type=submit]").show();
            	showNotifier(message_JSON['msg']);
            }
            $("input[type=submit]").show();
    });
    return false;
}
    
    
/* Locations
--------------------------------------*/

function checkIn(loc_id, lat, lon) {
	$.post( base_url + "ajax/locations/check_in", { loc_id: loc_id, lat: lat, lon: lon }, function(data) {
		message_JSON = eval("d="+data);
		showNotifier(message_JSON['msg']);
	});
    return false;
}	

function addToFavorites(location_id) {
	$.post( base_url + "ajax/locations/add_to_favorites", { loc_id: location_id }, function(data) {
		message_JSON = eval("d="+data);
		showNotifier(message_JSON['msg']);
	});
	return false;
}

function removeFromFavorites(location_id) {
	$.post( base_url + "ajax/locations/remove_from_favorites", { loc_id: location_id }, function(data) {
		message_JSON = eval("d="+data);
		showNotifier(message_JSON['msg']);
	});
	return false;
}
		
function deleteLocation(location_id) {
	$.post( base_url + "ajax/locations/delete_location", { loc_id: location_id }, function(data) {
		message_JSON = eval("d="+data);
		showNotifier(message_JSON['msg']);
	});
	return false;
}

/* Users
--------------------------------------*/
function addBuddy(user_id) {
	$.post( base_url + "ajax/users/add_buddy", { user_id: user_id }, function(data) {
		message_JSON = eval("d="+data);
		showNotifier(message_JSON['msg']);
	});
    return false;
}

function deleteBuddy(user_id) {
	$.post( base_url + "ajax/users/delete_buddy", { user_id: user_id }, function(data) {
		message_JSON = eval("d="+data);
		showNotifier(message_JSON['msg']);
	});
    return false;
}

function sendChatMessage(to) {
	$.dialog(function() {
		$.get(base_url + "ajax/chats/new_message", { to: to }, function(data) {
			if(data == 0) {
				showNotifier("You need an account to make this action. <a href='"+base_url+"login'>log in</a> or <a href='"+base_url+"signup'>register</a>");
				$.dialog.close();
			} else {
				$.dialog(data);
			}
			
		});
	});
	return false;
}

function setFriendshipStatus(fromId, toId, response)
{
	$.post( base_url + "ajax/users/invitation_response", { from_user_id: fromId, to_user_id: toId, response: response },
	    function(data) {
	        message_JSON = eval("d=" + data);
	        if(message_JSON['result'] == 1) { // success
	        	$('#add_'+toId+'_'+fromId).hide("slow").remove();
	        	showNotifier(message_JSON['msg']);
	        } else {
	        	$('#add_'+toId+'_'+fromId).hide("slow").remove();
	        	showNotifier(message_JSON['msg']);
	        }
    });
    return false;
}


/* Error messages and notifications
--------------------------------------*/
function showMessage(div, message, status)
{
	$(div).html('<div class="msg '+status+'">'+message+'</div>');
}

function showNotifier(message)
{	
	$("#notifier p").html(message);
	$("#notifier").slideDown("slow");
	setTimeout(function() { $("#notifier:visible").hide('blind', {}, 500)}, 5000);
}


function reportAbuse(item_id, type)
{
	$.dialog(function() {
		if(type == "location"){
			$.get(base_url + "ajax/locations/report_abuse", { to_id: item_id, type: type }, function(data) {
				$.dialog(data);
			});
		}
		else{
			$.get(base_url + "ajax/users/report_abuse", { to_id: item_id, type: type }, function(data) {
				$.dialog(data);
			});
		}
	});
	return false;
}


/* Star rating
--------------------------------------*/
$('#star_rating a.star').click(function() {
	rate(this);
});

$('#star_rating a.star').hover(function() {
	$("#star_rating a").removeClass('hover');
	var rating = $(this).attr('name');
	$("#star_rating a:lt("+rating+")").addClass('hover');
});

$('#star_rating').mouseout(function() {
	$("#star_rating a").removeClass('hover');
});


function rate(star)
{
	var rating = $(star).attr('name');
	var rate_type = $('#rate_type').val();
	var rate_to_id = $('#rate_to_id').val();
	if(rate_type == "location") {
		$.post(base_url + "ajax/locations/add_rating", { loc_id: rate_to_id, rating: rating }, function(data) {
			message_JSON = eval("d="+data);
			showNotifier(message_JSON['msg']);
		});
	}
	else if(rate_type == "user"){
		$.post(base_url + "ajax/users/add_rating", { user_id: rate_to_id, rating: rating }, function(data) {
			message_JSON = eval("d="+data);
			showNotifier(message_JSON['msg']);
		});
	}
}


/* Import contacts / Find friends
-----------------------------------------------*/
var count = 1;
	
function insertEmail() {
	$("#emails").append("<div id='email_counter_"+count+"'><label>Email:</label><input type='text' name='email_addr' id='email_addr' /><a class='x_delete' onclick=\"$('#email_counter_"+count+"').remove();\"> x</a></div>");
	count++;
}


function sendInvite() {
	var invites = [];
	var emailValues = $('#emails input[name=email_addr]');
	l = emailValues.length;
	
	if(!((l == 1) && (emailValues[0].value=='')))
	{
		var j = 0;
		for(i = 0; i<l; i++) {
			if(emailValues[i].value!='')
			{
				invites[j] = encodeURIComponent(emailValues[i].value);
				j++;
			}
		}
	invites = invites.join(';');
	$.post(base_url+"ajax/users/send_invite", { invites: invites },
		function(data) {
			message_JSON = eval("d="+data);
			showNotifier(message_JSON['msg']);
			$("#invite_submit_button").removeClass('button_sending');
			$("#invite_submit_button").val('Send invitation');
		});
	}	
}


function sendInviteImport() {
	var invites = [];
	var emailValues = $('.scrollable input:checked');
	l = emailValues.length;
	
	if(!((l == 1) && (emailValues[0].id=='')))
	{
		var j = 0;
		for(i = 0; i<l; i++) {
			if(emailValues[i].id!='')
			{
				invites[j] = encodeURIComponent(emailValues[i].id);
				j++;
			}
		}
	invites = invites.join(';');
	$.post(base_url+"ajax/users/send_invite", { invites: invites },
		function(data) {
			message_JSON = eval("d="+data);
			showNotifier(message_JSON['msg']);
			$("#import_contact_btn").removeClass('button_sending');
			$("#import_contact_btn").val('Send invite');
		});
	}	
}


function searchPeople() {
	var str = $("#people_str").val();
	$.post(base_url+"ajax/users/search_people", { str: str },
		function(data) {
			message_JSON = eval("d="+data);
			if(message_JSON['result'] == 0){
				showNotifier(message_JSON['msg']);	
			}else if(message_JSON['result'] == 1){
				showPeople(message_JSON['data']);
			}
			$("#search_submit_button").removeClass('button_sending');
			$("#search_submit_button").val('Search');
		});
}


function showPeople(people_ids)
{
	$.dialog(function() {
		$.get(base_url + "ajax/stream/get_common_friends", {ids: people_ids }, function(data) {
			$.dialog(data);
		});
	});
	return false;
}


/* Homepage
-----------------------------------------------*/
function dismissWelcome()
{
	$("#welcome").fadeOut('slow');
	$.cookie('nwntwn_welcome', null, { path: '/' });
}

function dismissConfirmEmail()
{
	$("#confirm_email").fadeOut('slow');
}

/* Helper functions
-----------------------------------------------*/

function trim(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

function urlencode(str) {
	str = (str+'').toString();
	return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
            replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}






