
$(function()
{
    
    ////// GENERAL INITIALIZATION
    $('.tip_small_up').tooltip({ //note: input/widget events must include mouseover/out for accord form to work
            lazy: false,
            position: 'bottom center',
            tip: '#tip_small_up',
            predelay: 150,
            events: {
                input: 'mouseover,mouseout',
                widget:'mouseover,mouseout',
                tooltip: 'none'
            },
            offset: [5, 0]
        });
    $('.tip_small_down').tooltip({ 
            lazy: false,
            position: 'top center',
            tip: '#tip_small_down',
            predelay: 150,
            events: {
                widget:'mouseover,mouseout',
                tooltip: 'none'
            },
            offset: [-5, 0]
        });

    ////// ONREADY STYLING ACTION
        // Hide the optional form element blocks (and sign in) if javascript is turned on
        // Also for hiding the submit until the required fields are filled out
        
        $('#chamber #judgment_form fieldset.optional, #action_messages, .new_judgment_link').livequery(function() {
            $(this).css({ display: "none" }); 
        });
        
        if ( ($('#doc').hasClass('bonafide')) ) { //if we are logged in at page load so do what you need
            $('.judge_remember').css({ //don't show remember_judge checkbox
                display: "none"
            });
            $('#specialty').attr("disabled", true); //disable password field
            ////// FACEBOOK
            //initFB_authenticated(); //initialize facebook javascript
        } else {
            //initFB_unauthenticated(); //initialize facebook javascript
        }
        
        $('#edit_specialty').click( function(event) {
            $('.judge_remember').toggle(); //only show remember if there is a reason
            //enable/disable password field if they want to change it
            if ( $(this).attr("checked") ) {
                $('#specialty').removeAttr("disabled"); 
            } else {
                $('#specialty').attr("disabled", true);
                $('#specialty').val('');
            }
            return true;
        });

        
        // Some things need to be animated in place; use visibility instead of builtin show/hide functionality which use display
        $('div.show_all, #auth_stuff').css({
            visibility: 'hidden'
        });
        // IF JS do show
        $('#chamber #judgment_form').css({ display: 'block' });
        
        // Show JS specific stuff (if JS do otherwise ignore
         $('#show_specialty, #show_specialty_label').livequery(function() {
            $(this).css({ display: "inline" }); 
        });
    
    ////// AUTHENTICATION JUDGMENT

        //SET hidden input signin to be 1 because the default value is 0 for non-js visitors but it needs to start at 1
        //$('#signin').val(1); //this sucks
        
        //show the signin/up/edit/admin link flyout
        $('#chamber #judgment_form, #chamber .judge_auth, #chamber #auth_stuff')
        .mouseenter( function() {
            $('#auth_stuff').css({ visibility: 'visible' });
        })
        // HIDE the signin/up/edit/admin link flyout (if triggered on other elements it flickers or vanishes when it shouldn't
        $('#chamber #judgment_form')
        .mouseleave( function() {
            $('#auth_stuff').css({ visibility: 'hidden' });
        });
        
        // help them sign in
        $('.virtual_chamber_switch')
            .livequery('click', function(event) {
                chamberSwitcher();
                return false;
            });
            
        //we are in the form now signin or up?
        $('#signin_switch')
            .livequery('click', function(event) {
                //$('#signin').val(1); // 1 = sign in
                $('.judge_admin_only').slideUp("slow");
                $('#signup_switch').removeClass('active');
                $('#signin_switch').addClass('active');
                return false;
            });
            
            // initial state of sign in/up selectors
            if ( !( $('#doc').hasClass('bonafide') ) ) {
                $('#signup_switch').addClass('active');
            }
            
        $('#signup_switch')
            .livequery('click', function(event) {
                //$('#signin').val(0); // 0 = sign UP
                $('.judge_admin_only').slideDown("slow");
                $('#signup_switch').addClass('active');
                $('#signin_switch').removeClass('active');
                return false;
            });
           /* 
        $('a.signout')
            .livequery('click', function() {
                function signout() {
                    redirect = $('a.signout').attr("href");
                    window.location = "http://www.google.com/";
                }
                FB.Connect.ifUserConnected(
                        function() {
                            //redirect = $('a.signout').attr("href");
                            //FB.Connect.logout(function() {
                            FB.Connect.logout();

                            return false;
                        }
                    ,  
                        function() {
                            return true;
                        }
                        );
            });
*/
            
        
        // AUTH/EDIT show password
        $('#specialty').livequery(function() {
                $(this).showPassword('#show_specialty');
        });
        
        // FORCE OPEN VIRTUAL CHAMBER (e.g. on form error in virtual chamber submit we need it open)
        if ( $('#virtual_chamber').hasClass('force_open') ) {
            chamberSwitcher();
            if ( !($('#virtual_chamber').hasClass('edit')) ) {
                //this should really be a function as it is called like this several places
                //$('#signin').val(0); // 0 = sign UP
                $('.judge_admin_only').slideUp("slow");
                $('#signup_switch').removeClass('active');
                $('#signin_switch').addClass('active');
            }
        }
        
    
    ////// JUDGMENT FINITE STATE MACHINE 2000 initialize
        formInputText       = "input#judge, input#target, input#verdict, input#emotion";
        formTextArea        = "textarea#evidence, textarea#remedy";
        formOtherElements   = "#judgment_form submit, #judgment_form button";
        
        // this should be with the judgement form finite machine stuff
        // CLEAR DEFAULT FORM VALUES ON SUBMIT
        $("#judgment_form").submit(function(){
            
            theFields = formInputText + ',' + formTextArea;
            
            $(theFields).each(function() {
                    
                var selector = $(this);
                
                if ( !(selector.hasClass('hasUserInput')) ) {
                    selector.val("");
                }
                
            });
            return true;
            //$(":submit", this).attr("disabled","disabled").val("Please wait....");
        });
        
        // BIND EVENTS: general other 
        $(formOtherElements)
            .mouseover(function() {
                $(this).addClass('mouseover');
            })
            .mouseout(function() {
                $(this).removeClass('mouseover');
            });
            
            
        // BIND EVENTS: text inputs    
        $(formInputText)
            .mouseover(function() {
                $(this).addClass('mouseover');
            })
            .mouseout(function() {
                $(this).removeClass('mouseover');
            })
            .keyup(function() {
                checkState( $(this) );
                resizefieldfunction( $(this) );
            })
            .change(function() {
                $(this).removeClass('active').removeClass('active');
                checkState( $(this) );
                resizefieldfunction( $(this) );
            })
            .focus(function() {
                    if ( !($('#doc').hasClass('bonafide')) ) { 
                        //not signed in
                        chamberSwitcher();
                        defaultValue( $(this) );
                    } else {
                        //signed in
                        $(this).addClass('active');
                        activateJudgmentForm();
                        defaultValue( $(this) );
                        checkState( $(this) );
                        resizefieldfunction( $(this) );
                    }
            })
            .blur(function() {
                $(this).removeClass('active').removeClass('active');
                defaultValue( $(this) );
                checkState( $(this) );
                resizefieldfunction( $(this) );
            });
            
        // BIND EVENTS: textareas   
        $(formTextArea)
            .mouseover(function() {
                $(this).addClass('mouseover');
            })
            .mouseout(function() {
                $(this).removeClass('mouseover');
            })
            .keyup(function() {
                checkState( $(this) );
            })
            .change(function() {
                $(this).removeClass('active').removeClass('active');
                checkState( $(this) );
            })
            .focus(function() {
                $(this).addClass('active');
                activateJudgmentForm();
                defaultValue( $(this) );
                checkState( $(this) );
            })
            .blur(function() {
                $(this).removeClass('active').removeClass('active');
                defaultValue( $(this) );
                checkState( $(this) );
            });
        
        // START THE PROGRAM JUDGMENT FINITE STATE MACHINE 2000
        defaultValue(formInputText + ',' + formTextArea);
        checkState(formInputText + ',' + formTextArea);
        resizefieldfunction( formInputText ); 
    
    
    //grid features, functionality, and effects
    $('div.concept_1, div.concept_2')
        .mouseenter( function(event) {
                $(this)
                    .children('div.show_all').css({
                        visibility: 'visible'
                    })
                    .addClass('mouseover');
        })
        .mouseleave( function(event) {
                $(this)
                    .children('div.show_all').css({
                        visibility: 'hidden'
                    })
                    .removeClass('mouseover');
        });
        
        
    $('.columns .block, .columns .concept_1')
    .mouseenter( function(event) {
            $(this).addClass('mouseover');
    })
    .mouseleave( function(event) {
            $(this).removeClass('mouseover');
    });
    
    
    
    // AJAX RANDOM MASTHEAD JUDGMENT
    $('#showMeAJudgment')
        .click(function() {
            $('#masthead_announce').slideDown('slow');
            $('#masthead_announce div').load("/_application/ajax_show_one_random_judgment.php");
            return false;
        });
        
        
        
        
    // VARIABLE GRID
    if ( $('#columns').is('div') ) var vgrid_columns = $('#columns').vgrid({
                                                                        easeing: "easeOutQuint",
                                                                        time: 400,
                                                                        delay: 20,
                                                                        fadeIn: {
                                                                            time: 500,
                                                                            delay: 50
                                                                        }
              
    });
    if ( $('#comments').is('div') ) var vgrid_comments = $('#comments').vgrid({
                                                                            easeing: "easeOutQuint",
                                                                            time: 400,
                                                                            delay: 20,
                                                                            fadeIn: {
                                                                                time: 500,
                                                                                delay: 50
                                                                            }
    });
    
    // COMMENT GRID MANAGEMENT
    updateCommentsGrid = function() {
        //set width class depending on length of entered comment
        comment_div = $('#comment_new');
        comment_length = $('#comment_comment').val().length;

        if ( comment_length > 1500 && !(comment_div.hasClass('three')) ) {
            //console.log("addClass 'three'");
            comment_div.removeClass('one').removeClass('two').addClass('three');
            vgrid_comments.vgrefresh();
        } else if ( comment_length > 400 && comment_length <= 1500 && !(comment_div.hasClass('two')) ) {
            //console.log("addClass 'two'");
            comment_div.removeClass('one').removeClass('three').addClass('two');
            vgrid_comments.vgrefresh();
        } else if ( comment_length <= 400 && !(comment_div.hasClass('one')) ) {
            //console.log("addClass 'one'");
            comment_div.removeClass('two').removeClass('three').addClass('one');
            vgrid_comments.vgrefresh();
        }
        
        //redraw vgrid if it the textarea grows or shrinks(more than the starting size
        if ( comment_div.data( 'min_height' ) != comment_div.css('height') ) {
            comment_div.data( 'min_height', comment_div.css('height') );
            comment_div.css({ 'min_height': $('#comment_comment').parent('form').css('height') });
            vgrid_comments.vgrefresh();
        } else if ( comment_div.data( 'min_height' ) > eval($('#comment_comment').height() + 110) + 'px' ) {
            var h = 50 * Math.ceil( eval( ($('#comment_comment').height() + 100) / 50) ); //round up to nearest 50
            comment_div.css({ 'min-height': h  });
            vgrid_comments.vgrefresh();
            comment_div.data( 'min_height', comment_div.css('height') );
        }
    }
    // Minimize amount of updating that happens by putting a delay between keystrokes
    function updateCommentsGridHandler(do_turn_on) {
        if (do_turn_on == 1) {
            updateCommentsGridTimer = setTimeout ( "updateCommentsGrid()", 300 );
        } else {
            if(typeof(updateCommentsGridTimer) !== 'undefined') {
                clearTimeout(updateCommentsGridTimer);
            }
        }
    }
    // Here are the keystrokes to watch
    $('#comment_comment')
        .keypress( function() { // KEY down & up so try to update
                updateCommentsGridHandler(1);
        })
        .keydown( function() { // KEY down only so stop the update attempt before it happens
                updateCommentsGridHandler(0);
        });

        
    
    // ELASTIC TEXTAREAS
        $('textarea#evidence, textarea#remedy, textarea#about, textarea#comment_comment')
            .livequery( function() {
                    $(this).elastic();
        });
    
            
            
    // ACTION MESSAGES (animate if they exist)
    if ( $('.flash_message, .error_message').is('div') ) animateActionMessages(); // IF stops stupid sliding effect when no messages are there
    $('.flash_message_switch').livequery('click', function(event) {
            closeFlashMessage();
            return false;
    });
    $('.error_message_switch').livequery('click', function(event) {
            closeErrorMessage();
            return false;
    });
    
    
    
    // AUTOCOMPLETE
    $("#target").autocomplete('/_application/ajax_ac_targets.php', { width: "19em" });
    $("#verdict").autocomplete('/_application/ajax_ac_verdicts.php', { width: "19em" });
    $("#emotion").autocomplete('/_application/ajax_ac_emotions.php', { width: "19em" });
    
        
 });







// Show/hide the signin/up/edit virtual chamber and virtual courtroom (judgment form)
var chamberSwitcher = function() {
    $('#virtual_chamber').slideToggle( function() {
        if ( $('#doc').hasClass('bonafide') ) {
            loadJsonJudgeForm();
        }
        if ( $('#signup_switch').hasClass('active') ) {
            $('#display_name').focus();
        } else {
            $('#hobby').focus();
        }
    }); //.focus()
    $('#judgment_form').slideToggle();
    $('#auth_stuff').css({
        visibility: 'hidden'
    });
    
}
var loadJsonJudgeForm = function() {
    // AJAX call to load current data into virtual chamber 
    //(done directly on the signin page when no javascript

    $.getJSON("/_application/ajax_show_edit_virtual_chamber.php", function(data) {
        $('input#judge_judge_id').val(data.id);
        $('input#display_name').val(data.display_name);
        $('input#hobby').val(data.email);
        $('input#website').val(data.website);
        $('input#twitter_name').val(data.twitter_name);
        $('textarea#about').val(data.about);
        $('textarea#about').elastic();
        console.log("data.id " + data.id + "data.display_name" + data.display_name);
    });
    console.log('should have loaded edit json');
}

    
/*
JUDGMENT FINITE STATE MACHINE 2000
It uses class names for flags.

The default form state is set in the form itself to minimize the need to edit this file if the default states need changed.

**************
FLAGS
**************
.required       not a state; primarily used for non-js styling
.optional       not a state; primarily used for non-js styling
.mouseover      not a state; used for styling
.active         not a state; isActive; has focus and is presumably being edited

.not_ready      isNotReady; requisites not fulfilled           
.prompt         isPrombtable; no user input
.ready          isReady; has visitor input and is ready to submit

**************
STATES
form fields state informs fieldset state which informs overall completeness
**************
All fields and fieldsets start in .prompt (required) or .not_ready (optional)
judge.ready + target.ready + verdict.ready = fieldset.judgment.ready

*/
    
    var checkState = function(selectors) {
        
        // CHECK FIELD STATES; Fieldset state checking contingent on these results
        $(selectors).each(function() {
                
                var selector = $(this);
                var this_for_field = "label[for='" + selector.attr('id') + "']";
                
                if ($.trim(selector.val()) != '' && ( selector.hasClass('active') || selector.hasClass('ready')) ) {
                    // field is 'ACTIVE/READY' & has a value
                    selector.addClass('hasUserInput');
                    //hasUserInput = 1;
                } else {
                    // otherwise it doesn't have input (hopefully)
                    selector.removeClass('hasUserInput');
                    //hasUserInput = 0;
                }
                //used to check the variable hasUserInput trying to check now for NOT has defaultvalue
                if ( !( selector.hasClass('hasDefaultValue') ) && $.trim(selector.val()) != '' ) { // input has a value that is user input (not default) 
                    selector.removeClass('prompt').removeClass('not_ready').addClass('ready');
                    $(this_for_field).addClass('ready');//and it's label(s)
                } else  { // input is empty or has a default value
                    if ( (selector.parent('*').parent('fieldset').hasClass('prompt') || selector.parent('*').parent('fieldset').hasClass('ready')) ) {
                        // fieldset is 'prompt/ready' so it's fields cannot be not_ready
                        selector.removeClass('not_ready').removeClass('ready').addClass('prompt');
                    } else {
                        // fieldset is 'not_ready' so it's fields can't be
                        // NOTE: want to make it possible to show fieldsets out of order? What condition and where will allow this?
                        selector.removeClass('prompt').removeClass('ready').addClass('not_ready');
                    }
                    $(this_for_field).removeClass('ready');//and it's label(s)
                }
                
            })
        
        //FIELDSET STATES
        
        // judgment_fields fieldset is ready
        if (
            $('input#judge').hasClass('ready') 
            && $('input#target').hasClass('ready') 
            && ( 
                    ( $('input#verdict').hasClass('prompt') && $('input#verdict').hasClass('active') ) 
                    || $('input#verdict').hasClass('ready') 
                )
            ) { //if judge & target 'ready' && verdict is 'ready' OR is 'active' with 'prompt'
                $('#judgment_form fieldset#judgment_fields').removeClass('not_ready').removeClass('prompt').addClass('ready');
            } else { //since it is required and default it just goes back to 'prompt'
                $('#judgment_form fieldset#judgment_fields').removeClass('not_ready').removeClass('ready').addClass('prompt');
            }
        
        // other & action fieldset
        // how to only show if the form is active?
        if ($('#judgment_form fieldset#judgment_fields').hasClass('ready') && isJudgmentFormActivated()) {
            if (
                $('input#emotion').hasClass('ready') 
                ||  ( $('input#emotion').hasClass('prompt') && $('input#emotion').hasClass('active') )
                ) { //if emotion 'ready' OR emotion is 'active' with 'prompt'
                $('#judgment_form fieldset#other_fields').removeClass('not_ready').removeClass('prompt').addClass('ready');
                $('#judgment_form fieldset#evidence_fields').removeClass('not_ready').removeClass('prompt').addClass('ready');
            } else {
                $('#judgment_form fieldset#other_fields').removeClass('not_ready').removeClass('ready').addClass('prompt');
                $('#judgment_form fieldset#evidence_fields').removeClass('not_ready').removeClass('ready').addClass('prompt');
            }
            $('#judgment_form fieldset#action_fields').removeClass('not_ready').removeClass('prompt').addClass('ready');
        } else {
            $('#judgment_form fieldset#other_fields').removeClass('prompt').removeClass('ready').addClass('not_ready');
            $('#judgment_form fieldset#evidence_fields').removeClass('prompt').removeClass('ready').addClass('not_ready');
            $('#judgment_form fieldset#action_fields').removeClass('prompt').removeClass('ready').addClass('not_ready');
        }
    
        // show/hide (animate) fieldsets
        okayNowShowHide = function() {
            $('#judgment_form fieldset.prompt, #judgment_form fieldset.ready').slideDown("slow");
            $('#judgment_form fieldset.not_ready').slideUp("slow");
        }
        setTimeout(function(){okayNowShowHide();},150); //more graceful transition;
        
        // ECHO TARGET
        $('.target_echo').text($('input#target').val());
    }


    // RESIZE FIELDS 
    var resizefieldfunction = function(selectors) {
        
        fieldMinSize = 2;
        fieldMaxSize = 70;
        
        $(selectors).each(function() {
        
            currentValueLength = $(this).val().length;
            
            if (currentValueLength > 40) {
                currentExtraPadding = 3;
            } else if (currentValueLength > 20) {
                currentExtraPadding = 2;
            } else {
                currentExtraPadding = 1;
            }
            
            if (currentValueLength > fieldMinSize && currentValueLength <= fieldMaxSize - currentExtraPadding) {
                $(this).attr({
                    size: currentValueLength + currentExtraPadding
                });
            } else if (currentValueLength <= 5) {
                $(this).attr({
                    size: 2
                });
            }
        });
    }
    
    //conditional to prevent judgment form from expanding if we have prefilled enough values
    var activateJudgmentForm = function() {
        $('#judgment_form').addClass('active');
    }
    //test for condition
    var isJudgmentFormActivated = function() {
        return ( $('#judgment_form').hasClass('active') ) ? true : false;
        
    }

    // SET & TRACK JUDGMENT FORM DEFAULT VALUES (specific to judgment form
    function defaultValue(selectors) {
        
        $(selectors).each(function() {
                
            var selector = $(this);
            
            if ( selector.val() == selector.attr('title') && !(selector.hasClass('ready')) ) {
                selector.val("").removeClass('hasDefaultValue');
            } else if ( selector.val() == "" ) {
                selector.val(selector.attr('title')).addClass('hasDefaultValue');
            } 
        })
        checkState( $(selectors) );
    }

    // ECHO
    // I don't think this being used!!!!!!
    var echoTarget = function() {
        //$input = $(selector);
        if (echoselector != "" && $.trim($(selector).val()) == "" || echoselector != "" && $(selector).val() == defvalue) {
            $(echoselector).text(defvalue);
        } else if (echoselector != "") {
            
        }
    }


////// ACTION_MESSAGES SHOW & FLASH MESSAGES
    // ANIMATE THE APPEARANCE OF ACTION MESSAGES
    var animateActionMessages = function() {
        $('#action_messages').slideDown('slow');
        
            var flash_message = $('.flash_message');  
            //flash_message.slideDown('slow');
            
            setTimeout( function() {
                flash_message.slideUp('slow', function() {
                    flash_message.html("");
                })
            } , 10000 );
            //since the error messages stay they should just slide out with the action messages so they don't get special attention here
        
    }
    var closeFlashMessage = function() {
        $('.flash_message_switch').livequery('click', function(event) {
            $('.flash_message').slideUp('slow');
        });
    }
    var closeErrorMessage = function() {
        $('.error_message').slideUp('slow');
    }
        
    // JAVASCRIPT ACTION MESSAGES INTERACTION
        // ADD/CREATE from javascript
        var addFlashMessage = function(string) {
            // Send message to PHP function of same name
            //not real code that stuff is just for reference
            var post_fields = 
                                {
                                variable_name: "value"
                                , variable_name: "value"
                                };
        }
        var addErrorMessage = function() {
            // Send message to PHP function of same name
            //not real code that stuff is just for reference
            var post_fields = 
                                {
                                variable_name: "value"
                                , variable_name: "value"
                                };
        }
        // FORCE display before next page load
        var displayActionMessages = function() {
            // AJAX call PHP function of same name
            $.get('/_application/ajax_get_action_messages.php', function(data) { 
                        //make the action message div appear (just add water, er html?)
                        $('#action_messages').html(data);
                        animateActionMessages();
                }); 
        }
        
////// FACEBOOK
    
    //not used anymore
    function update_user_box() { 
        var user_box = document.getElementById("facebook_announce"); // add in some XFBML. note that we set useyou=false so it doesn't display "you" 
        user_box.innerHTML = "<span>" + "<fb:profile-pic uid=loggedinuser facebook-logo=true></fb:profile-pic>" + "Welcome, <fb:name uid=loggedinuser useyou=false></fb:name>. You are signed in with your Facebook account." + "</span>"; // because this is XFBML, we need to tell Facebook to re-process the document 
        FB.XFBML.Host.parseDomTree(); 
    }
    
    function initFB_unauthenticated() {
        //FB.init("e16936d0f2ab50d07c8c2e33e20e6fcc", "/_facebook/xd_receiver.htm");
        FB.init("e16936d0f2ab50d07c8c2e33e20e6fcc", "/_facebook/xd_receiver.htm", { "reloadIfSessionStateChanged":true });
    }
    
    function initFB_authenticated() {
        FB.init("e16936d0f2ab50d07c8c2e33e20e6fcc", "/_facebook/xd_receiver.htm", { "reloadIfSessionStateChanged":true });
    }

