var FACEBOOK_API_KEY = "ed8d27ebcdf041cd067db6d33cd69291";

function toggleFriendLayer( eventId ) {
    var layerId = "#friend-layer-" + eventId;
    $(layerId).slideToggle("slow");
}

function handleFBConnect( sessionKey ) {
    $.ajax({
        type: "GET",
        url: "getFBInfo",
        data: "fbSessionKey=" + sessionKey,
        dataType: "html",
        success : function( responseHtml ){
                        $('#signup').html(responseHtml);
                    }
    });
}

function doFacebookLogin( sessionKey, expires ) {
//    alert("expires: " + expires);
    $.ajax({
        type: "GET",
        url: "facebookLogin",
        data: "fbSessionKey=" + sessionKey,
        dataType: "html",
        success : function( responseText ){
                        if(responseText == "success") {
                            document.location.reload(true);
                        }
                        else {
                            $('#extra-login-text').text(responseText);
                            $('#extra-login-text').show();
                        }
                    }
    });
}

function findFacebookFriends( sessionKey ) {
    $.ajax({
        type: "GET",
        url: "findFBFriends",
        data: "fbSessionKey=" + sessionKey,
        dataType: "html",
        success : function( response ){
                        if(response == "success") {
                            document.location.reload(true);
                        }
                        else {
                            $('#friend-content').html(response);
                        }
                    }
    });
}

function requestFriend( friendId ) {
    $.ajax({
        type: "GET",
        url: "addFriend",
        data: "friendId=" + friendId,
        dataType: "html",
        success : function( responseHtml ){
                        if( requiresLogin(responseHtml) ) {
                            forceLogin();
                        }
                        else {
                            if(responseHtml == "success") {
                                switchButtons($("#request-friend-"+ friendId +"-button"), $("#request-pending-"+ friendId +"-button"))    
                            }
                        }
                    }
    });
}

function approveFriend( friendId ) {
    $.ajax({
        type: "GET",
        url: "approve",
        data: "friendId=" + friendId,
        dataType: "html",
        success : function( responseHtml ){
                        if( requiresLogin(responseHtml) ) {
                            forceLogin();
                        }
                        else {
                            if(responseHtml == "success") {
                                switchButtons($("#waiting-approval-"+ friendId +"-button"), $("#following-"+ friendId +"-button"))                                
                            }
                        }
                    }
    });
}


function followFeed( feedId, callback ) {
    $.ajax({
        type: "GET",
        url: "follow",
        data: "feedId=" + feedId,
        dataType: "html",
        success : function( responseHtml ){
                        if( requiresLogin(responseHtml) ) {
                            forceLogin();
                        }
                        else {
                            callback.call(null, responseHtml);
                        }
                    }
    });
}

function unFollowFeed( feedId, callback ) {
    $.ajax({
        type: "GET",
        url: "unFollow",
        data: "feedId=" + feedId,
        dataType: "html",
        success : function( responseHtml ){
                        if( requiresLogin(responseHtml) ) {
                            forceLogin();
                        }
                        else {
                            callback.call(null, responseHtml);
                        }
                    }
    });
}

function addUser( username, firstName, lastName, password, city, state, gender, birthday, birthMonth, birthYear, facebookId, picUrl) {
    $.ajax({
        type: "GET",
        url: "addUser",
        data: "username=" + username + "&firstName=" + firstName + "&lastName=" + lastName + "&password=" + password
                + "&city=" + city + "&state=" + state + "&gender=" + gender + "&birthday=" + birthday + "&birthMonth=" + birthMonth
                + "&birthYear=" + birthYear + "&facebookId=" + facebookId + "&picUrl="+picUrl,
        dataType: "html",
        success : function( responseText ){
                        if(responseText == "success") {
                            document.location.reload(true);
                        }
                        else {
                            $('#signup-error-text').text(responseText);
                            $('#signup-error-text').show();
                        }
                    }
    });
}

function addEvent( eventId ) {
    $.ajax({
        type: "GET",
        url: "addEvent",
        data: "id=" + eventId,
        dataType: "html",
        success :   function( eventHtml ){
                        if( requiresLogin(eventHtml) ) {
                            forceLogin();
                        }
                        else {
                            addToMyEvents(eventHtml);
                            switchAddButtons(eventId);
                        }
                    }
    });
}

function removeEvent( eventId ) {
    $.ajax({
        type: "GET",
        url: "removeEvent",
        data: "id=" + eventId,
        dataType: "html",
        success :   function( ){
                        removeFromMyEvents(eventId);
                        switchAddButtons(eventId);
                    }
    });
}

function deleteEvent( eventId ) {
	if (confirm("This event will be permanently deleted! Are you sure you want to do that?")) {
		$.ajax({
			type: "POST",
			url: "deleteEvent",
			data: "eventId=" + eventId,
			dataType: "html",
			success :   function( ){
							removeEventFromList(eventId);
							removeFromMyEvents(eventId);
						    var numCreatedEvents = parseInt($("#created-events-counter").text());
						    $("#created-events-counter").text(--numCreatedEvents);
						}
		});
	}
	
	return false;
}

function removeEventFromList(eventId) {
	var evt = $("#listing-event-" + eventId);
	evt.fadeOut('slow', function () { evt.remove(); });
}

function checkForCreateEvent() {
	if (location.href.match(/\?.*createEvent=true/))
		createNewEvent();
}

$(window).bind('load', checkForCreateEvent);
function createNewEvent() {
	var curListings = $(".listing:first");
//	if (curListings == null || curListings.size() < 1) {
	if (! location.href.match('/home(\\?.*)?$')) {
		location.href = '/home?createEvent=true'; //Not on the right page - take them to the homepage and then launch the create event dialog there.
		return;
	}

	var newListing = $("#CreateEventPanel");
	if (newListing == null || newListing.size() < 1) {
		newListing = $('<div id="CreateEventPanel"></div>');
		curListings.before(newListing);
		newListing.addClass("listing");
	}
	else
		newListing.slideUp('slow');
	
	newListing.hide();
	newListing.load("eventEntry", "ajax=1", function() {
		var closeButton = $('<a href="#" class="CloseLink"><img src="/uig/welcome_close_btn.png" alt="Close" /></a>');
		closeButton.bind('click', function() { newListing.slideUp('slow'); return false; });
		newListing.prepend(closeButton);
		newListing.slideDown('slow');
	});
}

function showVenueForm() {
	$.ajax({
		type: "GET",
		url: "venueEntry",
		data: "ajax=1",
		dataType: "html",
		success : function(responseText) {
			Shadowbox.init({enableKeys:false}); //Make sure enableKeys is false or it will disable the spacebar!
			Shadowbox.open({
				content: responseText,
				player: "html",
				title: "Create Venue",
				height: 450,
				width: 600
			});
			$("#sb-body").css("background-color", "#ffffff");
		}
	});	
}

function createVenue(formobj) {
    $.ajax({
        type: "POST",
        url: "createVenue",
        data: $(formobj).serialize(),
        dataType: "html",
        success : function( responseText ){
			responseText = $.trim(responseText);
			if(responseText.substring(0, 9) == "success: ") {
				if ($("#venueId").size() > 0) {
					$("#venueId").prepend($("<option value=\"" + responseText.substring(9) + "\">" + $("#venueName").val() + "</option>"));
					$("#venueId").attr("selectedIndex", 0);

					parent.Shadowbox.close();
				}
				else
					location.href="/";				
			}
			else {
				$('#venue-error-message').text(responseText);
				$('#venue-error-message').fadeIn('fast');
			}
		}
    });
}

function login(username, password) {
    $.ajax({
        type: "GET",
        url: "logon",
        data: "username=" + username + "&password=" + password,
        dataType: "html",
        success :   function( responseText ){
                        if(responseText == "success") {
                            document.location.reload(true);
                        }
                        else {
                            $('#extra-login-text').text(responseText);
                            $('#extra-login-text').show();
                        }
                    }
    });
}

function logout() {
    $.ajax({
        type: "GET",
        url: "logout",
        dataType: "html",
        success :   function(){
                        document.location = "home";
                    }
    });
}

function sendResetRequest(email) {
    $.ajax({
        type: "GET",
        url: "forgotPassword",
        data: "email=" + email,        
        dataType: "html",
        success :   function( responseText ){
                        if( responseText != "success") {
                            $('#forgot-password-response').text(responseText);
                            $('#forgot-password-response').show();
                            $('#forgot-password-sending').hide();
                            $('#forgot-password-form').show();

                        }
                    }
    });
}

function processResetRequest(password1, password2, hash) {
    $.ajax({
        type: "GET",
        url: "doPasswordReset",
        data: "password1=" + password1 + "&password2=" + password2 + "&hash=" + hash,
        dataType: "html",
        success :   function( responseText ){
                        if(responseText == "success") {
                            $('#password-reset-response').hide();
                            $('#password-reset-form').hide();
                            $('#password-reset-success').show();                                    
                        }
                        else{
                            $('#password-reset-response').html(responseText);
                            $('#password-reset-response').show();
                        }
                    }
    });
}

function followFromListing(feedId) {
    followFeed(feedId,
                function( feedHtml ){
                        if(feedHtml == null) feedHtml = this;
                        addFeedToStream(feedHtml);
                        switchFollowButtons(feedId);
                        removeFollowButtons(feedId);
                    });
}

function followFromFeed(feedId) {
    followFeed(feedId,
                function( feedHtml ){
                        if(feedHtml == null) feedHtml = this;                    
                        addFeedToStream(feedHtml);
                        switchFollowButtons(feedId);
                        removeFollowButtons(feedId);
                    });
}

function unFollowFromFeed(feedId) {
    unFollowFeed(feedId,
                function( ){
                        removeFeedFromStream(feedId);
                        switchFollowButtons(feedId);
                        addFollowButtons(feedId);
                    });
}


function followFromManage(feedId) {
    followFeed(feedId,
                function( feedHtml ){
                        if(feedHtml == null) feedHtml = this;
                    
                        addFeedToStream(feedHtml);
                        switchFollowButtons(feedId);
                    });
}

function unFollowFromManage(feedId) {
    unFollowFeed(feedId,
                function( ){
                        removeFeedFromStream(feedId);
                        switchFollowButtons(feedId);
                    });
}



function switchApproveButtons( friendId ) {
    var following = $("#approve-"+friendId+"-button");
    var follow = $("#follow-"+friendId+"-button");

    switchButtons(following, follow);
}

function switchFollowButtons(feedId) {
    var following = $("#following-"+feedId+"-button");
    var follow = $("#follow-"+feedId+"-button");

    switchButtons(following, follow);
}

function switchAddButtons(eventId) {
    var add = $("#add-" + eventId + "-button");
    var added = $("#added-" + eventId + "-button");

    switchButtons(add, added);
}

function switchButtons(first, second) {
    if(first.is(":visible")) {
        $(first).hide();
        $(second).show()
    }
    else {
        $(second).hide();
        $(first).show(); 
    }
}

function addToMyEvents( eventHtml ) {
    $("#my-events-header").slideDown("slow", function() { $(this).after(eventHtml) });
    var numEvents = parseInt($("#my-events-counter").text());
    $("#my-events-counter").children(":first").text(++numEvents);
}

function activateEventButton( eventId ) {
    var eventButtonId = "#event-" + eventId + "-btn";
    $(eventButtonId).addClass("added");
    $(eventButtonId).click(function() { removeEvent(eventId); return false;});
}

function removeFromMyEvents( eventId ) {
    $("#my-event-" + eventId).slideUp("slow");
    var numEvents = parseInt($("#my-events-counter").text());
    $("#my-events-counter").children(":first").text(--numEvents);
}

function deactivateEventButton( eventId ) {
    var eventButtonId = "#event-" + eventId + "-btn";
    $(eventButtonId).removeClass("added");
    $(eventButtonId).click(function() { addEvent(eventId); return false;});
}

function addFeedToStream(feedHtml) {
    $("#feed-items").slideDown("slow", function() { $(this).prepend(feedHtml); });
}

function removeFeedFromStream(feedId) {
    $("#feed-" + feedId + "-stream").slideUp("slow");
}

function removeFollowButtons(feedId) {
    $("a[onclick^='followFromListing(" + feedId +  ")']").each(
            function(){
                $(this).hide()
            });    
}

function addFollowButtons(feedId) {
    $("a[onclick^='followFromListing(" + feedId +  ")']").each(
            function(){
                $(this).show()
            });
}

function closeWelcome(callback) {
    $("#welcome").slideUp("300", callback);
}

function toggleLoginBox(callback) {
    if($('#login').is(':visible')) {
        $("#login").slideUp("slow");
        $("#login-link").removeClass("selected");
        $('#require-login').hide();
    }
    else {
        showLoginBox(callback);
    }
}

function showLoginBox(callback) {
    if( $("#welcome").is(":visible") ) {
        closeWelcome();
    }
    else if( $("#signup").is(":visible") ) {
        toggleSignupBox();
    }

    // clean up forgot password just in case
    $("#forgot-password").hide();
    $("#proper-login").show();

    $("#login").slideDown("slow", function() { if(callback) callback.call(); } );
    $("#login-link").addClass("selected");
}

function toggleSignupBox() {
    if($('#signup').is(':visible')) {
        $("#signup").slideUp("300");
        $("#signup-link").removeClass("selected");
        resetSignupForm();
    }
    else {
        if( $("#welcome").is(":visible") ) {
            closeWelcome();
        }
        else if( $("#login").is(":visible") ) {
            toggleLoginBox();
        }
        $("#signup").slideDown("300");
        $("#signup-link").addClass("selected");
    }
}

function submitLogin() {
    $('#extra-login-text').hide();
    login($('#userName').val(), $('#password').val())
}

function getRecentlyPosted(all) {
    if ( all == null ) {
        all = false;
    }

    $("#just-posted-listings").slideUp("slow");
    $.ajax({
        type: "GET",
        url: "recentlyPosted",
        data: "all=" + all,
        dataType: "html",
        success :   function( eventHtml ){
                        $('#just-posted-listings').html(eventHtml)
                        $("#just-posted-listings").slideDown("slow");
                    }
    });
}

function getUpcoming(all) {
    if ( all == null ) {
        all = false;
    }
    $("#upcoming-listings").slideUp("slow");
    $.ajax({
        type: "GET",
        url: "upcoming",
        data: "all=" + all,
        dataType: "html",
        success :   function( eventHtml ){
                        $('#upcoming-listings').html(eventHtml);
                        $("#upcoming-listings").slideDown("slow");
                    }
    });
}

function getMyStream() {
    getUpcoming(false);
    getRecentlyPosted(false);

    $("#submenu ul.feeds li a.selected").removeClass("selected");
    $("#event-stream").addClass("selected");
}

function getAll() {
    getUpcoming(true);
    getRecentlyPosted(true);

    $("#submenu ul.feeds li a.selected").removeClass("selected");
    $("#menu-all").addClass("selected");
}

function getMoreEvents(all, page, toDelete) {
    if ( all == null ) {
        all = false;
    }

    if (page == null) {
        page =2;
    }

    var url;
    var section;

    if( $("#upcoming-listings").is(":visible") ) {
        url = "upcoming";
        section = "#upcoming-listings";
    }
    else if( $("#just-posted-listings").is(":visible") ) {
        url = "recentlyPosted";
        section = "#just-posted-listings";
    }
    else if( $("#ongoing-listings").is(":visible") ) {
        url = "ongoing";
        section = "#ongoing-listings";
    }


    $.ajax({
        type: "GET",
        url: url,
        data: "all=" + all + "&page=" + page,
        dataType: "html",
        success :   function( eventHtml ){
                        $(section + " .more-btn").remove();
                        $(section).append(eventHtml);
                    }
    });
    
}

function getFriendsEvents(page) {

    if (page == null) {
        page = 2;
    }

    $.ajax({
        type: "GET",
        url: "moreFriendsEvents",
        data: "page=" + page,
        dataType: "html",
        success :   function( eventHtml ){
                        $("#upcoming-listings" + " .more-btn").remove();
                        $("#upcoming-listings").append(eventHtml);
                    }
    });
}

function initMap(elementId, latitude, longitude) {
	document.getElementById(elementId).style.display = "block";
	var gmap = google.maps; //Make it easy to redirect; Shadowbox was fooling with the variable earlier.
	var latlng = new gmap.LatLng(latitude, longitude);
    var newmap = new gmap.Map(document.getElementById(elementId), {zoom: 13, center: latlng, mapTypeId: gmap.MapTypeId.ROADMAP, disableDefaultUI: true});
	new gmap.Marker({position: latlng, map: newmap});
}

function populateAddress(inputname, addressField, cityField, stateField, zipField, latField, longField, mapcanvas) {
	var gmap = google.maps;
	
	var nybounds = new gmap.LatLngBounds(new gmap.LatLng(40.5162,-74.240341), new gmap.LatLng(41.061026,-71.871414));
	if (inputname.indexOf(",") < 0)
		inputname += ", New York";
	
	new gmap.Geocoder().geocode({'address': inputname, 'bounds': nybounds},
		function (results, status) {
			var addr = null;
			if (status == gmap.GeocoderStatus.OK && results.length > 0)
				addr = results;

/*			if (addr == null)
				$("#mapError").fadeIn('slow');
			else if (addr.length > 1)
				$(createAddressList(addrs, "#addressContainer")).bind("select", function () { targetfield.value = this.value });*/
			if (addr != null) {
				addressField.value = extractAddressComponent("street_address", addr[0]) || addressField.value;
				cityField.value = extractAddressComponent("locality", addr[0]) || extractAddressComponent("political", addr[0]);
				stateField.value = extractAddressComponent("administrative_area_level_1", addr[0]);
				zipField.value = extractAddressComponent("postal_code", addr[0]);
				latField.value = addr[0].geometry.location.lat() || "";
				longField.value = addr[0].geometry.location.lng() || "";
			}
	
			if (addr != null && mapcanvas != null && addr[0].geometry && addr[0].geometry.location)
				initMap(mapcanvas.id, addr[0].geometry.location.lat(), addr[0].geometry.location.lng());
		}
	);
}

function extractAddressComponent(component_name, addr) {
	for (var compidx = 0; compidx < addr.types.length; compidx++) {
		if (addr.types[compidx] == component_name)
			return addr.address_components[compidx].long_name;
	}
	return null;
}

function requiresLogin(response) {
    return "require login" == response;
}

function forceLogin() {
    $('#require-login').show();
    if(!$('#login').is(':visible')) {
        showLoginBox( function() {
			scrollToTop(function () { $('#userName').focus(); });
		} );
    }
    else {
        scrollToLogin();    
    }
}

function showForgotPassword() {
    $("#proper-login").hide();
    $("#forgot-password-response").hide();
    $("#forgot-password-sending").hide();
    $("#forgot-password-form").show();
    $("#forgot-password").show();
}

function forgotPassword() {
    sendResetRequest($('#forgot-email').val());
    $('#forgot-password-response').hide();
    $('#forgot-password-form').hide();
    $('#forgot-password-sending').show();

}

function resetSignupForm() {
    $('#signup-error-text').hide();    
    $("#signup-userName").val("");
    $("#signup-firstName").val("");
    $("#signup-password").val("");
    $("#signup-lastName").val("");    
    $("#signup-city").val("");
    $("#signup-state").val("");
    $("#signup-birthday").val("DD");
    $("#signup-birthMonth").val("MM");
    $("#signup-birthYear").val("YYYY");

    $("#signup-facebook").show();
    $("#signup-extra").hide();    
}

function resetPasswordResetForm() {
    $("#confirm-new-password").val("");
    $("#new-password").val("");
}

function resetPassword() {
    processResetRequest($('#new-password').val(), $('#confirm-new-password').val(), $('#reset-hash').val())
}

function closePasswordResetBox( ) {
    $("#password-reset").slideUp("slow");    
}

function scrollToLogin() {
    scrollToId("login-link", function () { $('#userName').focus(); });
}

function scrollToTop(callback) {
    scrollToId("frame", callback);
}

function scrollToId(scrollTo, callback) {
    $('html, body').animate({
            scrollTop: $("#"+scrollTo).offset().top
        }, 1000, null, callback);
}

function submitSignupForm() {
    var userName = encodeURI($("#signup-userName").val());
    var firstName = encodeURI($("#signup-firstName").val());
    var gender = "u";
    if($("#signup-isMale").is(":checked")) {
        gender = "m"
    }
    else if($("#signup-isFemale").is(":checked")) {
        gender = 'f';
    }
    var password = encodeURI($("#signup-password").val());
    var lastName = encodeURI($("#signup-lastName").val());
    var city = encodeURI($("#signup-city").val());
    var state = encodeURI($("#signup-state").val());
    var birthday = encodeURI($("#signup-birthday").val());
    var birthMonth = encodeURI($("#signup-birthMonth").val());
    var birthYear = encodeURI($("#signup-birthYear").val());
    var facebookId = encodeURI($("#facebook_id").val());
    var picUrl = encodeURI($("#facebook_pic_url").val());

    if( (birthday == "DD") || (birthMonth == "MM") || (birthYear == "YYYY") ) {
        birthday = 0;
        birthMonth = 0;
        birthYear = 0;
    }

    addUser(userName, firstName, lastName, password, city, state, gender, birthday, birthMonth, birthYear, facebookId, picUrl);

}

function isNumeric(input){
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}

function submitOnEnter(e, submit) {
    var keycode;
    if (window.event) {
        keycode = window.event.keyCode;
    }
    else if (e) {
         keycode = e.which;
    }
    else {
        return true;
    }

    if (keycode == 13) {
        submit.call();
        return false;
    }

    return true;
}


function pushToStream(message, eventName, eventUrl, startTime, description, imageUrl) {
    var attachment = {
        'name': eventName,
        'href': eventUrl,
        'caption': startTime,
        'description': description,
        'media': [{ 'type': 'image', 'src': imageUrl, 'href': eventUrl }]
        };

    if(pushToFB) {
        FB.Connect.requireSession(function() {
            FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(has) {
                if (has == 0) {
                  FB.Connect.showPermissionDialog('publish_stream', function(granted) {
                    if(granted) {
                        FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
                        FB.Connect.streamPublish(message, attachment, null, null, null, null, true);
                    }
                    else {
                        setPushToFB(false);
                        $.ajax({
                            type: "GET",
                            url: "setPublishFB",
                            data: "publish=false",
                            dataType: "html",
                            success : function( responseText ){}
                        });
                    }
                  });
                }
                else {
                    FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
                    FB.Connect.streamPublish(message, attachment, null, null, null, null, true);
                }

            });
        });
    }
}

var pushToFB = true;
function setPushToFB( doPush ) {
    pushToFB = doPush;
}
function canPushToFB() {
    return pushToFB;
}

function saveSettings() {
    $('#settings-response-message').html("Saving settings...");
    $('#settings-response-message').show();

    var firstName = encodeURI($("#firstName").val());
    var lastName = encodeURI($("#lastName").val());
    var city = encodeURI($("#city").val());
    var state = encodeURI($("#state").val());
    var birthday = encodeURI($("#bday").val());
    var shareOnFB = $("#share-on-fb").is(":checked");

    $.ajax({
        type: "GET",
        url: "saveSettings",
        data: "firstName=" + firstName + "&lastName=" + lastName + "&city=" + city + "&state=" + state + "&birthday=" + birthday + "&shareOnFB=" + shareOnFB,
        dataType: "html",
        success :   function( responseText ){
                        if(responseText == "success") {
                            $('#settings-response-message').html("Your settings have been saved");
                            $('#settings-response-message').show();
                        }
                        else{
                            $('#settings-response-message').html(responseText);
                            $('#settings-response-message').show();
                        }
                    }
    });
}

function disconnectFromFB() {
    $.ajax({
        type: "GET",
        url: "disconnectFromFB",
        data: "",
        dataType: "html",
        success :   function( responseHtml ){
                        $("#fb-connection").html(responseHtml);
                        FB.init(FACEBOOK_API_KEY, "xd_receiver.htm");
                    }
    });
}

function connectToFB(fbSessionKey) {
    $.ajax({
        type: "GET",
        url: "connectFBSettings",
        data: "fbSessionKey=" + fbSessionKey,
        dataType: "html",
        success :   function( responseHtml ){
                        $("#fb-connection").html(responseHtml);
                        FB.init(FACEBOOK_API_KEY, "xd_receiver.htm");
                    }
    });
}

function showPicUploadForm() {
    $('#upload-pic-form').show();
}

function doPicUpload() {
    $.ajax({
        type: "POST",
        url: "saveUserPic",
        data: "pic=" + $('#upload-pic').val(),
        dataType: "multipart/form-data",
        success :   function( response ){
                        alert(response)
                    }
    });
}

function toggleAllFeeds() {
    $('#extra-following').slideToggle();

    if( $('#sidemenu-all-feeds').is(":visible")) {
        $('#sidemenu-all-feeds').hide();
        $('#sidemenu-less-feeds').show();
    }
    else {
        $('#sidemenu-less-feeds').hide();
        $('#sidemenu-all-feeds').show();
    }
}

function getSearchedEvents(searchTerms, pageNum) {
    var section;

    if( $("#upcoming-listings").is(":visible") ) {
        section = "#upcoming-listings";
    }
    else if( $("#just-posted-listings").is(":visible") ) {
        section = "#just-posted-listings";
    }
    else if( $("#ongoing-listings").is(":visible") ) {
        section = "#ongoing-listings";
    }

    $.ajax({
        type: "GET",
        url: "search",
        data: "q=" + searchTerms + "&page=" + pageNum + "&ajax=true",
        dataType: "html",
        success :   function( eventHtml ){
                        $(section + " .more-btn").remove();
                        $(section).append(eventHtml);
                    }
    });
}

function getFeedEvents(feedId, listingHeader, page) {
    if(page == null) {
        page = 1;
    }

    $.ajax({
        type: "GET",
        url: "feedEvents",
        data: "id=" + feedId + "&page=" + page,
        dataType: "html",
        success :   function( listingHtml ){
                        changeListingsContent(listingHtml, listingHeader, page);
                    }
    });
}

function getFeedFollowers(feedId, listingHeader, page) {
    if(page == null) {
        page = 1;
    }

    $.ajax({
        type: "GET",
        url: "feedFollowers",
        data: "id=" + feedId + "&page=" + page,
        dataType: "html",
        success :   function( listingHtml ){
                        changeListingsContent(listingHtml, listingHeader, page);
                    }
    });
}

function getFriendsFollowing(feedId, listingHeader, page) {
    if(page == null) {
        page = 1;
    }

    $.ajax({
        type: "GET",
        url: "feedFriendFollowers",
        data: "id=" + feedId + "&page=" + page,
        dataType: "html",
        success :   function( listingHtml ){
                        changeListingsContent(listingHtml, listingHeader, page);
                    }
    });
}

function getUserAdded(userId, listingHeader, page) {
    if(page == null) {
        page = 1;
    }

    $.ajax({
        type: "GET",
        url: "userAdded",
        data: "id=" + userId + "&page=" + page,
        dataType: "html",
        success :   function( listingHtml ){
                        changeListingsContent(listingHtml, listingHeader, page);
                    }
    });
}

function getUserFollowing(userId, listingHeader, page) {
    if(page == null) {
        page = 1;
    }

    $.ajax({
        type: "GET",
        url: "userFollowing",
        data: "id=" + userId + "&page=" + page,
        dataType: "html",
        success :   function( listingHtml ){
                        changeListingsContent(listingHtml, listingHeader, page);
                    }
    });
}

function getUserFriends(userId, listingHeader, page) {
    if(page == null) {
        page = 1;
    }

    $.ajax({
        type: "GET",
        url: "userFriends",
        data: "id=" + userId + "&page=" + page,
        dataType: "html",
        success :   function( listingHtml ){
                        changeListingsContent(listingHtml, listingHeader, page);
                    }
    });
}

function changeListingsContent(listingHtml, listingHeader, page) {
    if(page == 1) {
        $('#listings-header').html(listingHeader);
        $('#listings-header').show();
        $('#listings-container').html(listingHtml);
    }
    else {
        $('#more-btn').remove();
        $('#listings-container').append(listingHtml);
    }
}

function enterEventDetails(feedId) {
    $("#listings-container").fadeTo("slow", 0.4);
    $(".listing:first").slideDown("slow", function() { $(this).prepend('<div class="listing" style="margin-right: 0pt; opacity: 0"></div>'); });

    $.ajax({
        type: "GET",
        url: "newInlineEvent",
        data: "feedId=" + feedId,
        dataType: "html",
        success : function( responseHtml ){
                        if( requiresLogin(responseHtml) ) {
                            forceLogin();
                        }
                        else {
			    $(".listing:first").html(responseHtml);
                        }
		        $("#listings-container").fadeTo("slow", 1);
                    }
    });
}


/** saved for venue entry */
function swapEntryField(entryId) {
    var preview = $("#entry_preview-" + entryId);
    var previewText = $("#entry_preview-" + entryId + " > span");
    var field = $("#entry_field-" + entryId);
    var fieldInput = $("#entry_field-" + entryId + " > input");

    if(preview.is(":visible")) {
        preview.hide();
        field.show()
    }
    else {
        previewText.text(fieldInput.val());
        field.hide();
        preview.show();
    }
}
