if (!console) {
    var console = {
        log: function(){},
        info: function(){},
        warn: function(){},
        error: function(){},
        trace: function(){}
    };
}

var slide_list = function(direction, callback) {
    if(callback===null) { callback = function(){}; }
    var padding = 10;
    if(direction===null) { direction = '-'; }
    var delta = $('ul.slider li:eq('+(current_index - 1)+')').height();
    delta += padding;
    // Remove or add 90px from the UL's 'top' value (slide it up out of the frame)




    $(".slider").animate({top: direction + '=' + delta + 'px'}, "slow", "easeOutCubic", callback);
};

var get_lectures = function(start, limit, end, slide_function, url, filter) {
    slide_function();

    if(start===null || start===undefined) { start = 0; }
    if(limit===null) { limit = 1; }
    if(end===null) { end = 'bottom'; }
    if(url===null || url===undefined) { 
        if(results_type=='current') {
            url = '/lecture/api/get/date/';
        } else if (results_type == 'alphabetical') {
            url = '/lecture/api/get/alphabetical/';
        } else if (results_type == 'speaker') {
            url = '/lecture/api/get/speaker/';
		} else if (results_type == 'popularity') {
			url = '/lecture/api/get/popularity';
        } else {
            url = '/lecture/api/get/date/';
        }
    }
	if(slide_function===null || slide_function===undefined) { slide_function = function() {}; }
	if(filter===null || filter===undefined) { 
		if(filter_value=='' || filter_value===null || filter_value===undefined){
			filter = ''; 
		} else {

			filter = filter_value;
		}
	}

    // Short circuit if current index is > 8 from the bottom of the list
    //  as it doesn't make sense to preload more if they are that far outside
    //  the scope of the mask.
    var slider_len = $('ul.slider li').length;
    var distance = slider_len - current_index;
    if(distance > max_slide_items_shown) {
        slide_lock = false;
        return false;
    }

    // If there are `max_slide_items_shown` or less items between our current 
    //  position and the bottom of the list, we should preload another batch 
    //  if possible
    var items_missing = max_slide_items_shown - distance;
    limit = items_missing ? items_missing : limit;

    // check if this is a search for a speaker, if so add a mode of 'speaker'
    var mode = '';
    if (is_speaker = filter.match(/^speaker:(.+)/)) {
        mode = 'speaker'
        filter = is_speaker[1];
    }

    $.get(url, {'start': start, 'limit': limit, 'tagquery': filter, 'mode': mode }, function(data,textStatus) {
        if(end=='bottom') {
            // Currently this is the only possible action
            $('ul.slider').append(data);
            ending_id += limit;
        }
        if(end=='top') {
            $('ul.slider').prepend(data);
        }
        // only unlock the slider if we are still getting data
        // it will have some blank lines so i am testing against
        // a length of 10... random but works.
        if (data.length > 10) {
            slide_lock = false;
        }
    });
};

var slide_up = function() {
    // Index increment must be done before sliding
	current_index++;
    if(current_index > 0) {

		$('#up').removeClass('disabled');
	}
	return slide_list('-');
};

var slide_down = function () {
    if(current_index > 0) {
        return slide_list('+', function() {
            // Index needs to be decremented AFTER the sliding
            //  calculations and sliding is completed
            current_index--;
			if(current_index == 0) {

				$('#up').addClass('disabled');
			}
        });
    }
};

var slide_list_up = function() {

    get_lectures(ending_id, 1, 'bottom', slide_up);
    // Prevent link from doing its normal linky stuff
    return false;
};

var slide_list_down = function() {

    slide_down();
    // Prevent link from doing its normal linky stuff

    return false;    
};

var preload_image = function(url) {

    $('<img>').attr('src', url).css({'display':'none'}).appendTo($('body'));
};

var clear_list = function(callback) {
    if(callback===null){callback=function(){};}
    // Fade out all of the slide items


    $('ul.slider li').fadeOut(250, function(){
        // Remove all slider items from the DOM
        $(this).remove();
    });

    // Reset any of the state variables
    current_index = 0;
    starting_id = 0;
    ending_id = 0;
    // Slide UL back to starting position

    $("ul.slider").css({'top': '0px'}).oneTime("275ms", function() { 
        callback();
    });
}



var get_current_lectures = function(slide_function) {
    if(slide_function===null || slide_function===undefined) { slide_function = function(){};}
    return get_lectures(ending_id, 1, 'bottom', slide_function, '/lecture/api/get/date/');  
};
var get_alphabetical_lectures = function(slide_function) {
    if(slide_function===null || slide_function===undefined) { slide_function = function(){};}
    return get_lectures(ending_id, 1, 'bottom', slide_function, '/lecture/api/get/alphabetical/');  
};
var get_speaker_lectures = function(slide_function) {
    if(slide_function===null || slide_function===undefined) { slide_function = function(){};}
    return get_lectures(ending_id, 1, 'bottom', slide_function, '/lecture/api/get/speaker/');  
};
var get_popularity_lectures = function(slide_function) {
    if(slide_function===null || slide_function===undefined) { slide_function = function(){};}
    return get_lectures(ending_id, 1, 'bottom', slide_function, '/lecture/api/get/popularity/');  
};
var get_filtered_lectures = function(slide_function, filter) {
	if(slide_function===null || slide_function===undefined) { slide_function = function(){};}
    return get_lectures(ending_id, 1, 'bottom', slide_function, undefined, filter);  
}

var deactivate_topics = function() {
    $('ul#topic li').removeClass('active');
};

var get_current_topics = function() {
    deactivate_topics();
    $('ul#topic li.current').addClass('active');
    clear_list(function(){
        initialize_filters();
        get_current_lectures();
    });
    results_type = 'current';
    return false;
};

var get_alphabetical_topics = function() {
    deactivate_topics();
    $('ul#topic li.alphabetical').addClass('active');
    clear_list(function(){
        initialize_filters();
        get_alphabetical_lectures();
    });
    results_type = 'alphabetical';
    return false;
};

var get_speaker_topics = function() {
    deactivate_topics();
    $('ul#topic li.speaker').addClass('active');
    clear_list(function(){
        initialize_filters();
        get_speaker_lectures();
    });
    results_type = 'speaker';
    return false;
};

var get_popularity_topics = function() {
    deactivate_topics();
    $('ul#topic li.popularity').addClass('active');
    clear_list(function(){
        initialize_filters();
        get_popularity_lectures();
    });
    results_type = 'popularity';
    return false;
};

var get_filtered_topics = function() {
	var query = $('input#tagquery').val();

	filter_value = query;
    clear_list(function(){
        get_filtered_lectures(null, query);
    });
    return false;
};

var initialize_filters = function() {
    var current_button = $('ul#topic li.current');
    var alphabetical_button = $('ul#topic li.alphabetical');
    var speaker_button = $('ul#topic li.speaker');
    var popularity_button = $('ul#topic li.popularity');

	var current_link = $('ul#topic li.current a');
    var alphabetical_link = $('ul#topic li.alphabetical a');
    var speaker_link = $('ul#topic li.speaker a');
    var popularity_link = $('ul#topic li.popularity a');

    if(current_button.hasClass('active')) {
		current_link.unbind('click').click(function(){return false;});
    } else {
        current_link.click(get_current_topics);
    }
    if(alphabetical_button.hasClass('active')) {
		alphabetical_link.unbind('click').click(function(){return false;});
    } else {
        alphabetical_link.click(get_alphabetical_topics);
    }
    if(speaker_button.hasClass('active')) {
		speaker_link.unbind('click').click(function(){return false;});
    } else {
        speaker_link.click(get_speaker_topics);
    }
    if(popularity_button.hasClass('active')) {
		popularity_link.unbind('click').click(function(){return false;});
    } else {
        popularity_link.click(get_popularity_topics);
    }

	var search_form = $('form#searchform');
	search_form.submit(get_filtered_topics);
};

var initialize_sidebar = function() {

    // Preload rollover button for the filter buttons
    preload_image('/static/img/bullet1-a.gif');
    // Set the default states and set up click actions
    initialize_filters();
};

var on_page_load = function() {
    setup_slider();
    setup_bios();
//$("#down").click(slide_list_up);
//$("#up").click(slide_list_down);
    initialize_sidebar();
//$('#tagquery').focus();
};

function setup_bios () {
	$('div.title h2 a').each(function() {
		this.onclick = function () {
			$("div.bios").slideToggle();
			return false;
		};
	});
}

function setup_slider () {
    setInterval(function() {check_slider("timer")}, 1000);
    $('div.ajax').scroll(function () {check_slider("scroll")});
}

function setup_tooltips () {
    $('div.related ul li a').each(function () {
        $(this).mouseover(function(e){
            $('#tooltip').text($('img',this).attr("rel"));
            $('#tooltip').css({
                left : e.pageX - 50,
                top : e.pageY - 50,
                display: 'block'
            });
        }).mouseout(function(){
            $('#tooltip').css({display:'none'});
        });
    });
}

function check_slider (callerr) {
    if (slide_lock)
        return;
    slide_lock = true;
    var ul = $('div.ajax ul');
    var uloffset = ul.offset();
    var ulbottom = uloffset.top + ul.height();

    var div = $('div.ajax');
    var divoffset = div.offset();
    var divbottom = divoffset.top + div.height();

    var diff = Math.abs(ulbottom - divbottom) / ul.height();
    
    if (diff < 0.2) {
        get_lectures(ending_id, 2, 'bottom', function () { current_index++ });
        return;
    }
    slide_lock = false;
}

var slide_lock = false;
$(document).ready(on_page_load);
window.onload = function () {
    setup_tooltips();
};

