var loaded = [];
var seen = [];
var log_line = 0;
var heavy_debug = true;
var min_content_height = 695;

$(function() {
	// fairly stolen.
	//$('#debug_switch').click(function() {
    //    $('#debug').toggle();
    //    $('#debug_switch').toggleClass("debug_on");
    //});
    
    /*
    if (!$.browser.msie) {
	    // dynamic height! -- now with minimum
	    var s_height = $(window).height() - 70;
	    $('#content').height(s_height);
	    $(window).resize(function() {
	        var s_height = $(window).height() - 70;
	    	$('#content').height(s_height);
	    });
    }
	*/
	
	// ajax loading     
	$('#modal_window div.loader_graphic').ajaxStart(function() {
        $(this).find('img').show();
	});
	
	$('#modal_window div.loader_graphic').ajaxStop(function() {
        $(this).find('img').hide();
	});
	
	// modalicious
	$('#modal_window').jqm({ 
	    onShow: function (h) {	        
            $(h.w).find('#modal_content').load($(h.t).attr('href'), {}, function () { 
                h.w.find('a.modal').click(follow_modal_href); 
                h.w.find('.modal_close').click(function () { h.w.jqmHide(); return false; });
                
                // make sure our javascript is properly evaluated.
                ensure_js_eval(h.w.find('#modal_content'));
                
                prepare_modal_forms();
                h.w.show();
                /*
                $(window).keydown(function(e) {
                    if (e.keyCode == 27) {
                        h.w.jqmHide();
                    }
                });
                */
                // so we focus on either the first input or the modal content area.
                modal_focus(); 
            });
	    },
	    onHide: function (h) {
	        h.w.fadeOut('fast', function () {
	            h.w.find('#modal_content').html(''); // put things back the way we found them...
	            h.o.remove(); // remove the overlay..
	            //$('#modal_content').unbind('keydown');
	        }); // hide the window
	    },
	    trigger: '.modal',
	    modal: false
	});

    // deed search Awesome!
    $('#deed_search_button').click(function() {
        if ($('input[@name=deed_search]').val()) {
            document.location = "/stats/deeds/" + escape($('input[@name=deed_search]').val()) + "/";
        }
    });

    $('form[@name=deed_search]').submit(function() {
        if ($('input[@name=deed_search]').val()) {
            document.location = "/stats/deeds/" + escape($('input[@name=deed_search]').val()) + "/";
        }
        return false;
    });

});

function ensure_js_eval (container) {
    // i hate having to do this
    if ($.browser.msie) {
        container.find('script').each( function() {
            if (window.execScript) {
                window.execScript($(this).html());
                debug_log("internet explorer is loading your javascript...");
            }
        });
    } else if ($.browser.safari) {
        container.find('script').each( function() {
            // I swore I'd never do this..
            window.setTimeout($(this).html(), 0);
            debug_log("safari is loading your javascript...");
        });
    } 
}

function modal_focus () {
    var input = $("#modal_window form:visible:first :input:visible:enabled:first");
    if (input.length >= 1) {
        input.focus();
    } else {
        // so the modal gets the keypress event!
        //$('#modal_window #modal_content a:first').focus();
    }
}

function follow_modal_href () {            
    load_modal_href($(this).attr('href'));
    return false;
}
             
function load_modal_href (href, args) {                      
    $('#modal_window #modal_content').load(href, args, function() {
        $('#modal_window a.modal').click(follow_modal_href);
        $('#modal_window .modal_close').click(function() { $('#modal_window').jqmHide(); return false; });
        prepare_modal_forms();
        modal_focus();                                       
    });
}

function remove_from_loaded (id) {
    var new_loaded = [];

    // iterate through the global loaded...
    $.each(loaded, function(i, n) {
        if (n != id) {
            new_loaded.push(n);
        }
    });

    // replace the loaded array.
    loaded = new_loaded;
}

function debug_log (data) {
    //$('#debug > p').prepend("[" + ++log_line + "] " + data + "<br/>");
    return;
}

function debug_replace (data) { 
    //$('#debug > p').html(data + "<br/>");
    return;
}

function bullshit () {
    var deedid = $(this).parents('div.vote_wrapper').attr('id').split('_')[1];
    $(this).blur();
    $(this).unbind('click');
    $.post(bs_url, {
        deedid  :   deedid,
        json    :   1
    }, function(json) {
        var info = $.parseJSON(json);

        $("#deed_" + deedid + " ul").animate(
            {
                opacity: 'hide'
            },
            'fast'
        ); 

        // animate
        $("#deed_" + deedid).animate(
            {
                opacity: 'hide',
                height: 'hide'
            },
            'normal',
            // load up the new deed!
            function() {
                if ($(this).is('#deed_' + deedid)) {
                    $.post(deed_url, {
                        loaded_deeds    :   loaded.join(','),
                        seen_deeds      :   seen.join(',')
                        }, function(html) {
                            // oops - i wasn't removing the actual html
                            $("#deed_" + deedid).remove();
                            var loaded_deedid = $(html).attr('id').split('_')[1];
                            $('#content').append(html);
                            ensure_js_eval($(html));
                        }
                    );
                }
            }
        );

        // once the dust settles.
        if (info.bs_calls_left == 0) {
            $('.bullshit').remove();
        } else {
            if (info.bs_calls_left > 1) {
                $('span.bs_call_info').html('(' + info.bs_calls_left + ' calls left!)');
            } else {
                $('span.bs_call_info').html('(' + info.bs_calls_left + ' call left!)');
            }
        }

    });

    return false;
}

function vote_handler () {
    var deedid = $(this).parents('div.vote_wrapper').attr('id').split('_')[1];
    var score = $(this).html();
    $(this).blur();
    
    // one click (vote) at a time ;)
    $(this).parents('div.vote_wrapper').find('li > a').unbind('click');
                          
    // vote
    $.post(vote_url, {
        deedid  :  deedid,
        score   :  score,
        json    :  1
        }, function(json) {
            var info = $.parseJSON(json);
            debug_log("got json: '" + json + "' back!");
            remove_from_loaded(info.deedid);

            // fade out the stars (for ie)
            $("#deed_" + info.deedid + " ul").animate(
                {
                    opacity: 'hide'
                }, 
                'fast'
            );

            // animate
			$("#deed_" + info.deedid).animate(
				{
					opacity: 'hide',
					height: 'hide'
				},
				'normal',
				// load up the new deed!
				function() {
                    if ($(this).is('#deed_' + info.deedid)) {
					    $.post(deed_url, {
					    	loaded_deeds    :   loaded.join(','),
                            seen_deeds      :   seen.join(',')
					    	}, function(html) {                
					    	    // oops - i wasn't removing the actual html
					    	    $("#deed_" + info.deedid).remove();
					    	    var loaded_deedid = $(html).attr('id').split('_')[1];
					    	    $('#content').append(html);
					    	    ensure_js_eval($(html));
					    	}
					    );
                    }
				}
			)
        }
    );

    return false;
}

function prepare_modal_forms () {
    $('#modal_window form').each(function() {
        var bn_extension = $(this).attr('action');
        
        if (!bn_extension.match("^\/")) {
            bn_extension = app_root + "/" + bn_extension;
        }
        
        debug_log("Preparing form with action " + bn_extension + " for submission");
        
        $(this).append('<input type="hidden" name="json" value="1"/>');
        
        // get rid of anything already here
        $(this).unbind('submit');
        
        $(this).submit(function() {
            var form_data = {};
            
            $(this).find('input:not([@type=submit]),textarea,select').each(function() {
                if ($(this).attr('type') && ($(this).attr('type').match("radio", "i") || $(this).attr('type').match("checkbox", "i"))) {
                    if ($(this).attr('checked')) {
                        // support for radio and checkbox
                        form_data[$(this).attr('name')] = $(this).val();
                    }
                } else {
                    // eval is bad!
                    form_data[$(this).attr('name')] = $(this).val();
                }
            });
            
            if (heavy_debug) {
                $.each(form_data, function(i, n) {
                    debug_log(i + " => " + n); 
                });
            }

            $.post(app_root + bn_extension, form_data,
                function(json) {
                    debug_log("Got json back! " + json);
                    var e_json = $.parseJSON(json);
                    debug_log("Success: " + e_json.success);
                    handle_json(e_json);
                }
            );
            return false;
        });
    });
}
