var current_event = 0;
var live_host = 'http://www.eventvue.com';
var conditional_params;
var since;
update_count = 0;
tweet_limit = 1;
var data = '';
var create_modal_html;

// get the event items
function update_feed(init) {
	if(init) {
		var url = live_host+'/stream/ajax/latest.php?event_id='+events[current_event]+conditional_params;
	} else {
		var url = live_host+'/stream/ajax/latest.php?event_id='+events[current_event]+'&since='+since+conditional_params;
	}
	$.getJSON(url, function(json) {
		count = 0;
		$.each(json.items, function(i,item) {
			if(count >= tweet_limit && !init){
				return false;
			}
			if(!is_dupe(item.guid)) {
				add_item(item,init);
				count++;
			}
		});
		since = json.timestamp;
	});
	update_count++;
	if(update_count >= 1) {
		// get the number of events
		num_events = events.length;
		if(current_event+1 == num_events){
			current_event = 0;
			update_count = 0;
		} else {
			current_event++;
			update_count = 0;
		}
	}
	setTimeout("update_feed()", 2000);
}

function add_item(item,init) {
	new_item = $('#template_item').clone();
	new_item.attr('id',item.guid);
	new_item.find('.author_avatar').attr('src',item.avatar).attr('title', '@'+item.ext_username);
	new_item.find('.author_link').attr('href','http://twitter.com/'+item.ext_username).html(item.ext_username);
	new_item.find('.status').html(item.content);
	$('#conversation ul').prepend(new_item);
	if(init) {
		new_item.show();
	} else {
		new_item.css('margin-top','-60px').show().blindToggle();
	}
}

function is_dupe(guid) {
	if($("#"+guid).length == 0)
		return false;
	return true;
}

function show_modal(html, size) {
    if (size == "small") {
        width = 430;
        height = 300; 
    } else {
        width = 724;
        height = 594;
    }
    top_offset = (($(window).height() - height)/2 - 80);
    // adjust for windows that aren't as tall as our modal window
    top_offset = (top_offset < 0) ? 12 : top_offset;
    $("#modal").css("marginTop",top_offset+'px').width(width+"px");
	if(html)
    	$("#modal div").html(html);
    $("#overlay").show();
}
function hide_modal() {
    $("#overlay").hide();
}

function show_create_modal() {
	show_modal(create_modal_html,'small');
}

function clear_refill_form(element,input,clear_value) {
	if(!clear_value)
		clear_value = '';
	if(element.val() == input) {
		element.val(clear_value);
	} else if(element.val() == clear_value) {
		element.val(input);
	}
}
$(document).ready( function() {
    
    create_modal_html = $("#create_modal").html();
    
    show_modal($("#letter").html(),"large");
	
	// only add the JSONP callback if we are not on eventvue.com (performance tweak)
	conditional_params = (window.location.host != "www.eventvue.com" || window.location.host != "eventvue.com") ? "&callback=?" : "";

	// initial update
	update_feed(true);

	// search form
	$('#search_field').focus(function () { clear_refill_form($('#search_field'),'Search for an event...');});
	$('#search_field').blur(function () { clear_refill_form($('#search_field'),'Search for an event...');});
	
	$("#search_field").autocomplete('/stream/ajax/search_list.php',{delay:0});
	$('#search_field').result(function(event, data, formatted) {
		window.location = '/'+data[1];
	});
	
	$('#search_form').submit(function (){ 
		var search_term = $('#search_field').val();
		var content = search_term.split(" ");
		$.each(content, function(){
			if(this.match(/^#[-\w]+$/)) {
				search_term = search_term.replace(this,"");
				$('#create_hashtag').val(this);
			}
		});
		if(!search_term.match(/^#[-\w]+$/) && search_term != '') {
			$('#create_name').val($.trim(search_term));
		}
		show_create_modal();
		return false;
	});
	
	$('#create_event_btn').click(function(){
		show_create_modal();
		return false;
	});
	
	$('#create_hashtag').focus(function() { $(this).val('#')});
	
	// put the create handling in a function until we can figure out the css button issue
	function create() {
		var event_name = $('#create_name').val();
		var event_hashtag = $('#create_hashtag').val();
		
		if(event_name == 'Name of Event') {
			$('.error_message').html('Please enter an event name.').fadeIn();
			return false;
		}
		if(!event_hashtag.match(/^#[-\w]+$/)) {
			$('.error_message').html('Please enter a Twitter hashtag.').fadeIn();
			return false;
		}
		// if there were no errors, create the event and forward the user to the stream
		var data = {
					"event_hashtag" : event_hashtag,
					"event_name" : event_name
					};

        $.ajax({
            url: '/stream/ajax/create_event.php',
        	type: 'POST',
        	data: data,
        	dataType: 'json',
            success: function(json){
                
                // trigger backfill for the specified event hashtag (don't wait for response)
                $.get("http://www.eventvue.com/stream/ajax/backfill.php", { hashtag: event_hashtag, event_id: json.event_id });
                
                if(!json.error) {
					setTimeout(function() { 
						window.location = '/'+json.hashtag;
					}, 1000);
                } else {
                    $('.error_message').html('There was an error creating the event.').fadeIn();
                }
            }
        });
	}
	$('#create_form').submit(function (){
		create();
		return false;
	});
	$('#create_btn').click(function (){
        create();
	});	
});
jQuery.fn.blindToggle = function(speed, easing, callback) {
  var h = this.height() + parseInt(this.css('paddingTop')) + parseInt(this.css('paddingBottom'));
  return this.animate({marginTop: parseInt(this.css('marginTop')) <0 ? 0 : +h}, speed, easing, callback);
};