
// Track actions via Google Analytics
function track(path) {
    if (path.substr(0,1)!='/') path = '/'+path;
    if (pageTracker && pageTracker._trackPageview) {
        pageTracker._trackPageview('/actions'+path);
    }
}

function moveQuestion(id) {
	//If there is no answered container, make one
    if ($('#answered_container').size() == 0) {
        //check for profile v. inbox
        if ($('#pending.tab').size() == 0) {
            //We're on the profile page
            $('<div id="answered_container"><h3>Answered Questions</h3></div>').insertAfter('#pending_container');
        } else {
            //We're in the inbox
            $('<div id="answered" class="tab"><div id="answered_container"><h3>Answered Questions</h3></div></div>').insertAfter('#pending.tab');
            $('<li id="answered_tab" name="answered_show">Answered Questions</li>').insertAfter('#pending_tab');

            readyTabs();
        }

    }
    $('#question_container_' + id).insertAfter('#answered_container h3');
	$('#question_container_' + id + ' .show_answer').remove();
	$('#question_container_' + id + ' .delete_answer').remove();
    $('#question_container_' + id).fadeIn();
    if ($("#pending_container .question_container").size() == 0) {
        $("#pending_container").remove();
		$("#interview_blurb").show();
    }
}

function flashOut() {
	setTimeout("fadeFlash()", 2000);
}

function fadeFlash() {
	$('#flash_message').slideUp('slow');
}

function showTab(tab) {
	$('#person_menu ul li').removeClass('selected');
    $('#' + tab + '_tab').addClass('selected');

	$('.tab').hide();
	$('#' + tab).show();

	location.hash = tab + '_show';
}

$(document).ready(function() {

    twttr.anywhere(function (T) {
        T.hovercards();
        T("a.hovercard").hovercards({
            username: function(node) {
                return $(node).attr('username');
            }
        });
    });


    // Update tweet count once in case of auto-fill
    if(('#tweet').length && $('#tweet').val()) {
        $('#tweet_counter').text(140-$('#tweet').val().length);
    }

    $('#tweet').livequery('keyup', function(){
        if(this.value.length >= 140) {
            //handle the over the limit part here
            $('#tweet_counter').addClass('red');
        //this.value = this.value.substring(0, 140);
        } else {
            $('#tweet_counter').removeClass('red');
        }
        $('#tweet_counter').text(140-this.value.length);
    });

    $('.tweet').livequery('keyup', function() {
        var i = $(this).attr('name');
        if (this.value.length >= 1400) {
            $('#tweet_counter_' + i).addClass('red');
        } else {
            $('#tweet_counter_' + i).removeClass('red');
        }
        $('#tweet_counter_' + i).text(1400-this.value.length);
    });

    $('.show_answer').click(function() {
        var id = $(this).attr("name");
		$(".answer_box").hide();
        $("#answer_box_" + id).toggle();
    });

	$('.send_tweet').click(function() {
		var c = $(this).attr('checked');

		$('.send_tweet').attr('checked', c);

		var button = 'Reply';
		if (c) {
			button += ' & Tweet';
		}

		$('.answer_button').text(button);
	});

	$('.send_ask_tweet').click(function(){
		var c = $(this).attr('checked');

		var button = 'Ask';
		if(c) {
			button += ' & Tweet';
		}

		$('#ask').val(button);
	});

    //Ajax for answering questions
    $('.answer_button').click(function() {
        //Get id that is being answered
        var id = $(this).attr("name");
        var interview = $(this).hasClass('listorious_interview');

        //Grab answer
        var answer = $('#answer_' + id).val();
        if (answer.length > 1400) {
            alert("Your answer must be less than 1400 characters.");
            return;
        }

		//Add Paragraphs
		answer = "<p>" + answer.replace(/\n\n/gi, "</p><p> ") + "</p>";

		//Add breaklines (all the paragraphs are gone, any remaining newlines should be breaklines). Strike that, apparently paragraphs...
		answer = answer.replace(/\n/gi, " </p><p>");

		if ($.trim(answer).length == 0) {
			alert("Your answer cannot be blank.");
			return;
		}

		var send_tweet = $('#send_tweet_' + id).attr('checked');

		var status_message = "Tweeting out...";
		if (!send_tweet) {
			status_message = "Saving your answer...";
		}

        //Show Loading div
        var loading = '<div class="box" id="loading_div_' + id + '"><div style="padding:20px;font-size:18px;font-weight:bold;text-align:center" id="status_message_' + id +'"><img src="/images/ajax-loader.gif" style="vertical-align:-7px" /> ' + status_message + '</div></div>';
        if (!interview)
            $('#answer_box_' + id).replaceWith(loading);
        else {
            $('#listorious .answer_box').hide();
            $(loading).appendTo('#listorious .questions_list');
        }

        $.post('/' + current_user + '/answer/' + id, {
            answer: answer,
			send_tweet: send_tweet
        },
        function(data) {
            if (data == "Success") {
                if (!interview) {
					if (!send_tweet) {
						$('<div style="clear:both;background-color:#ffec73;padding:20px;margin-bottom:10px;color:#000;font-weight:bold;display:none" id="flash_message">Your Answer Has Been Saved.</div>').prependTo('#main-content').slideDown('slow');
						flashOut();
					}
					$('#question_container_' + id).hide();
                    $('#loading_div_' + id).replaceWith("<p>" + answer + "</p>");

                    moveQuestion(id);
                } else {
                    //Listorious interview question answered
                    $('#loading_div_' + id).remove();
					$('#question_container_' + id).clone().appendTo('body');

                    $('#listorious .answer_box').show();
                    $('#interview_count').text(listorious.length-1);
                    listorious_ids.splice(listorious_curr, 1);
                    listorious.splice(listorious_curr, 1);
                    if (listorious_curr >= listorious.length) {
                        listorious_curr = 0;
                    }

                    if (listorious.length == 0) {
                        $('#listorious .questions_list').html('<p>There are no more Listorious Interview Questions</p>');
                    } else {
                        showNextQuestion();
                    }

					$('<p>' + answer + '</p><p class="question_meta">Just Answered</p>').appendTo('#question_container_' + id);
					moveQuestion(id);
                }
            } else {
                alert(data);
                return;
            }
        }
        );
    });

    //Ajax for deleting questions
    $('.delete_question').click(function() {
        if (confirm("Are you sure you'd like to delete this question?")) {
            var id = $(this).attr("name");

            $.post('/inbox/delete/' + id,
                function(data) {
                    if (data == "Success") {
                        $('#question_container_' + id).remove();
                    } else {
                        alert(data);
                        return;
                    }
                }
                );
        }
    });

    $('img.profile-image-from-twitter').each(function() {
        var url = 'http://search.twitter.com/search.json?q=from%3A'+$(this).attr('title')+'&callback=?';
        var img = $(this);
        $.getJSON(url,  function(data){
            var url = data.results[0].profile_image_url;
            img.attr('src',url);
        });
    });

	if ($('#search').parent().attr('name') == 'homepage_search') {
		$('#search').example('Search over 2 million top Twitter users');
		$('#search_footer').example('The best Twitter people search')
	} else {
            $('#search, #search_footer').example('Find experts on Twitter');
	}

    $('.follow-person').click(function() {
        var elem = $(this);
        elem.unbind('click').click(function() {
            return false
        });
        var screen_name = elem.attr('id');
        if (!screen_name) return false;
        user.login(function() {
            var url = '/ajax/twitterapi/follow/'+encodeURIComponent(screen_name)+'.json';
            elem.html('Following... <img src="/images/ajax_fb.gif" /> ');
            $.getJSON(url,function(data) {
                elem.html('&#10003; OK, following!');
            });
        });
        return false;
    });
//$('.has-tweet-popup').tweetPopup();

});



// Functions that deal with users
user = new Object();
user.login = function(callback) {
    $.getJSON('/ajax/login.json',function(data) {
        if (!data.login) {
            var url= '/login?dest='+encodeURIComponent(window.location.pathname);
            window.location.href=url;
        } else {
            if (callback !== undefined) callback();
        }
    });
}

