var dropdownlist_timeout = 500;
var dropdownlist_timer = 0;
var dropdownlist_menuItem = 0;
var dropdownlist_name = "#dropdownlist";

function ddl_open() {
	ddl_canceltimer();
	ddl_close();
	dropdownlist_menuItem = $(this).find('ul').css('visibility', 'visible');
}

function ddl_close() {
	if(dropdownlist_menuItem)
		dropdownlist_menuItem.css('visibility', 'hidden');
}

function ddl_timer() {
	dropdownlist_timer = window.setTimeout(ddl_close, dropdownlist_timeout);
}

function ddl_canceltimer() {
	if(dropdownlist_timer) {
		window.clearTimeout(dropdownlist_timer);
		dropdownlist_timer = null;
	}
}

function ddl_init() {
	$("#dropdownlist > li").bind('mouseover', ddl_open);
	$(dropdownlist_name + " > li").bind('mouseout', ddl_timer);
}

var shoutbox_last_received = 0;

function shoutbox_init(html_el_id) {
	layout_and_bind(html_el_id);
	sync_messages();
}

function sync_messages() {
	$.ajax({
		type: 'POST',
		url: '/chat/sync/',
		dataType: 'json',
		success: function (json) {
			if(shoutbox_last_received != json.last_message_id) {
				get_messages();
			}
			shoutbox_last_received = json.last_message_id;
		}
	})

	setTimeout("sync_messages()", 3000);
}

//this function is actually responsible only for the shoutbox
//please rename accordingly
//rewrite so the form gets downloaded from the server
//then bind everything!
function update_shoutbox_form(html_el_id) {
    $(".field_wrapper textarea").each(function(i, el) {
        $(el).focus(function() {
            $(this).text("");
        });
    });

	$("#shout_form").submit(function() {
		var inputs = $("#shout_form > .field_wrapper").children("input, textarea");
		var values = {};

		el = inputs;
        if($(el).val() == "username" || $(el).val() == "type in your shout here") {
            return false;
        }

		inputs.each(function(i, el) {
			values[el.name] = $(el).val(); 
		});	

		$.ajax({
			data: values,
			dataType: 'html',
			type: 'post',
			url: '/chat/send/',
			success: function(form_data, text_status, request) {
				//get the data for the form which django has
				//pre-rendered for us
			
				if(form_data != "") {	
					$("#shout_form").remove();
					$("#form_wrapper").html(form_data);	
					update_shoutbox_form(html_el_id);
				}	
			}
		});
	
		return false;
	});
}

function get_messages() {
	$.ajax({
		type: 'POST', 
		data: {'offset': shoutbox_last_received},
		url: '/chat/receive/',
		dataType: 'json',
		success: function (json) {
			//var scroll = false;
			var container = $("#chat_messages_container");
			if(container.scrollTop() == container.attr("scrollHeight") - container.height()) {
				scroll = true;
			}

			$.each(json, function(i, m) {
				shoutbox_last_received = m.id;
				//console.log(m);
				html = "<p>" + m.content + 
				"&nbsp; <span class='shout_by'>posted by " + m.user 
				+ " at " + m.time_added + "</span>" + "</p>"; 
				new_div = $("<div>").attr("class", "shout").html(html);

				$("#chat_messages").append(new_div);
			});

			if(scroll)
				$("#chat_messages_container").animate({
					scrollTop: $("#chat_messages_container").attr("scrollHeight")}, 2000, "swing");
		}
	});
	//setTimeout("sync_messages()", 2000);
}
				
function audio_overlay_init() {
	$(".audio_overlay").css({'display': 'none'});
	$.each($(".recent_audio_item"), function (i, el) {	
	    //@TODO: should i use the class visible or is there a jquery way to know whether an object is visible?
		$(el).click(function() {		
            if($(this).hasClass("visible")) {
                $(this).children(".audio_overlay").fadeOut();
                $(this).removeClass("visible");
            } else {
                $(this).children(".audio_overlay").fadeIn();
                $(this).addClass("visible");
            }
		});
	});
}


function get_location() {
	navigator.geolocation.getCurrentPosition(function(coordinates) {	
		$.ajax({
			url: "/coordinates/",
			data: {"longitude": coordinates.coords.longitude,
			       "latitude": coordinates.coords.latitude},
			type: "POST",
			success: function(msg) { 
				//alert("O hai! Your timezone is GMT " +
				update_next_show($(msg).find('offset').text());
			}
		});
	},
    function(error) {
        //the user did not share his location, show GMT+0
        update_next_show("0");
    }, 
    {timeout: 30000}); 
}

function update_next_show(offset) {
    if(offset == 0) {
        $("#next_show .next_show_timezone").text("(GMT+0)");
    } else {
        $.ajax({
            url: "/convert_time/" + $("#next_show .full_date").text() + "/" + offset + "/",
            type: "GET",
            dataType: "json",
            success: function(new_date) { 
            $("#next_show .next_show_day").text(new_date.day);
            $("#next_show .next_show_time").html(new_date.time); 
            $("#next_show .next_show_timezone").text("(GMT+" + new_date.offset + ")");
            }   
        }); 
    }   
}

$(document).ready(function() {
		ddl_init();
		update_shoutbox_form();
		audio_overlay_init();
		sync_messages();
		get_location();
		$(".header").corner();
		$(".footer").corner();
        $("#audio div:first").click()
});

document.onclick = ddl_close;

