  google.load('search', '1');

  $(document).ready(function(){

    $(window).scroll(showData); 

    $('#search-query').keypress(function(e) {
        if(e.which == 13) {
            jQuery(this).blur();
            jQuery('#search-submit').focus().click();
        }
    });

    $("#search-submit").click(function () {
	var cse = new google.search.CustomSearchControl('010722013183089041389:eham33culno');
	var drawOptions = new google.search.DrawOptions();
        
        var trackURL = '/search/' + $.trim($('#search-query').val());
        _gaq.push(['_trackPageview', trackURL]);

        	cse.draw(document.getElementById("cse"), drawOptions);
         	cse.execute(document.getElementById("search-query").value);
		cse.setSearchCompleteCallback(this, function() {
	                 $('html, body').animate({scrollTop:0}, 'slow');
       		         $('#loading').attr('title', 'cse');
       		         $("#posts").empty();
	        });
	});


     $('.topics a').click(function(e){
     	e.preventDefault();
	$('#pleasewait').show();   

	var $this = $(this);
        var trackURL = '/topic/' + $this.attr('rel');
        _gaq.push(['_trackPageview', trackURL]);
		$.ajax({
		url: "yui.php?t=" + $this.attr('rel'),
			success: function(html){
				if(html){
					$('#pleasewait').hide();   
					$("#posts").fadeOut('fast', function() {
						$("#cse").empty(); 
						$("#posts").empty(); 
						$("#posts").append(html);
						$("#posts").show();
					   	$('html, body').animate({scrollTop:0}, 'slow');
						$('#loading').attr('title', $this.attr('rel'));
					});
				}
			}
			});
			});
			
});

        function isBottom(){
		return ((($(document).height() - $(window).height()) - $(window).scrollTop()) <= 150) ? true : false;
	}

        function showData(){
	 if(($('#loading').attr('title') != 'cse') && ($('#loading').attr('title') != 'nomore') && isBottom()) {
		fetchData();
	 }
	}

        function fetchData(){
                $("#cse").empty();
		$(window).unbind('scroll');
                $('#loading').show();
        var page = $(".item:last").attr("id") /  12;
        var trackURL = '/topic/' + $('#loading').attr('title') + '/page-' + page;
        _gaq.push(['_trackPageview', trackURL]);
                $.ajax({
                        url: "yui.php?p=" + $(".item:last").attr("id") + "&t=" + $('#loading').attr('title'),
                        success: function(html){
                                $('#loading').hide();
                                if(html){
                                                $("#posts").append(html);
                                }else{
                                                $('#posts').append("<center>We are done. Please try another topic!</center>");
                                                $('#loading').attr('title', 'nomore');
                                }
				$(window).scroll(showData);
                        }
                });
    }


