$j(document).ready(function(){
    $j('.bogi_submit_button').hover(
        function() { //over
            $j(this).addClass('bogi_submit_button_hover hover');
        },
        function() { //out
            $j(this).removeClass('bogi_submit_button_hover hover');
        })

    $j('.bogi_cancel_button').hover(
        function() { //over
            $j(this).addClass('bogi_cancel_button_hover hover');
        },
        function() { //out
            $j(this).removeClass('bogi_cancel_button_hover hover');
        })

    // Date picking
    current_date=new Date();
    $j.datepicker.setDefaults($j.extend({
        showMonthAfterYear: false,
        changeMonth: true,
        changeYear: true,
        minDate: new Date(1910, 1 - 1, 1),
        maxDate: new Date(),
        stepMonths: 12
        }, $j.datepicker.regional['de']));
    $j("#gebdatum").datepicker();
    


    $j('.jFeedbackWidget textarea').elastic();
    

    $j("#wizard a[title]").tooltip('#big_tooltip').click(function(){return false;}); 
    
    
    var feedback_type = $j('#feedback_type').val();
    if (feedback_type=='kontakt') {
        feedback_type='meinung'
    }
    if (feedback_type=='club') {
        new_status_element_content='Kontaktdaten'
    } else {
        new_status_element_content='BOGI Club'
    }

    
    
    var update_status=function(argument){
        el=$j(this).next(':input');
        // console.log('hello %o', this, el.attr('name'));
        checked=el.attr('checked')
        target=undefined;
        switch (el.attr('name')) {
            case "club":
                // aktiviert, anzeigen
                if (checked && $j("#club_status").size()==0) {
                    new_el=$j('<li id="club_status">'+new_status_element_content+'</li>');
                    new_el.css({'display':'None'})
                    $j('#status').append(new_el);
                    $j('#gebdatum_span').html('*');
                    new_el.slideDown('slow');
                } else {
                    if (!checked) {
                        //do stuff
                        if (( $j(':checked').size()==0 )) {                            
                            $j('#gebdatum_span').html('&nbsp;');
                        }
                        new_el=$j("#club_status");
                        new_el.slideUp('slow').remove();
                    } //!checked
                }//checked&&$j
            case 'newsletter':
                if (checked) {
                    $j('#gebdatum_span').html('*');                    
                } else {
                    if (( $j(':checked').size()==0 )) {                            
                        $j('#gebdatum_span').html('&nbsp;');
                    }
                }
                break;
                
        }//switch
    } //func

    $j.fn.update_status = update_status;
    
    $j('#jFeedbackWidget_pane1 :checkbox').custCheckBox({hover:false,callback: update_status});//custCheckbox()
    $j('#jFeedbackWidget_pane1 .club_container span').update_status();

    
    var root = $j("#wizard").scrollable({size: 1, clickable: false, keyboard:false});
    var api = $j('#wizard').scrollable();
    // 
    var drawer = $j("#drawer");


    // make navigation
    api.onBeforeSeek(function(event, i){
        $j("#status li").removeClass("active").eq(i).addClass("active"); 
    });
    
    // validation logic is done the server, start by a click on my special buttons 
    var advance_pane=function (event){
            //remember the element where the event is coming from
            var calling_element = event.originalTarget || event.srcElement;

            //we are working on target_pane
            var target_pane = $j(calling_element).attr('rel');
            // console.log('target_pane ',target_pane);

            // api.onBeforeSeek(
            // // console.log('onBeforeSeek(): el=',element,' event=',event,' i=',i);

            // // we are going 1 step backwards so no need for validation 
            // if (api.getIndex() < i) { 

            // ... get current page 
            var page = root.find(".page").eq(api.getIndex());

            //  and all input fields (remove error from before) 
            var inputs = page.find(':input').add('.group').removeClass("error").removeClass('group_error');

            
            // is BOGI Club enabled?
            var go_to_bogiclub=$j('[name=club]:input').attr('checked');
            

            // will this bea submit? AKA are we done?
            
            // console.log('api.getIndex=',api.getIndex());
            var submit_run=(((go_to_bogiclub) && (api.getIndex()==1))||((!go_to_bogiclub)&&(api.getIndex()==0)))
            // console.log('submit_run=', submit_run);
            
            // final page, collect them all
            if (submit_run) {
                inputs=$j('#wizard :input').not('[name=termin]').not('[name=timeslot]');
                timeslot=$j('#wizard .hidden_timeslot_input').eq(0);
                termin=$j('#wizard [name=termin]').eq(0);
                // console.log('timeslot value',timeslot.val());
                var inputs=inputs.add(timeslot).add(termin).log('added stuff');

            };

            $j(calling_element).attr("disabled", 'disabled'); 
            $j('.wizards .progress').show();


            //prepare our json list
            var json_data={};

            json_data=inputs.serializeArray()

            // console.log('Serialized: %o', json_data);
            
            if (submit_run) {
                var url_prefix = 'save_'
            } else {
                var url_prefix = 'check_'
            }
            var json_url=__LOCATION_PREFIX+'/service/meinung/json_feedback_'+feedback_type+'_'+url_prefix+'pane_'+target_pane;
            // console.log('1');

            //make the call
            $j.getJSON(json_url,json_data, function(json_response){
                number_of_errors=$j(json_response.errors).length
                // console.log('json call just returned.. this=',this, 'json_response=',json_response, 'length of errors:', number_of_errors);
                _json_response=json_response;

                if (number_of_errors) {
                    // there are errors

                    // slide down the drawer 
                    drawer.slideDown(function()  { 

                    // colored flash effect 
                    drawer.css("backgroundColor", "#229"); 
                    setTimeout(function() { drawer.css("backgroundColor", "#fff"); }, 1000); 
                    }); 

                    // mark every field
                    $j(json_response.errors).each(function(index){
                        search_for=json_response.errors[index]
                        // console.log('Search_for=%o... error_equiv_list=%o.. in statement=%o', search_for, error_equiv_list, (search_for in error_equiv_list));
                        // search for the input field on this page and add Error
                        result=page.find('[name='+search_for+']').eq(0);
                        box_type=result.attr('type');
                        if (! ((box_type=='radio') || (box_type=='checkbox')) )  {
                            // not a radio box, proceed as normal
                            result.log('normal').addClass('error');
                        } else {
                            // it is a container, mark the parent 
                            result.parent().addClass('group_error');
                        }
                    }) //each

                } else {
                    // there are no errors


                    // hide the drawer 
                    drawer.slideUp(); 
                    
                    // check for things to do
                    switch (target_pane){
                        case "3":
                            update_timeslots(json_response.response);
                            break;
                        case "4":
                            update_pane5(json_response.response);
                            break;
                        case "7":
                            update_pane8(json_response.response);
                            break;
                    }

                    // json_response

                    // only if bogiclub is enabled
                    if (go_to_bogiclub && (target_pane=='1')) {
                        //next element
                        api.next();
                    };
                    if (submit_run) {
                        //disable next button on this page
                        $j(':button').eq(api.getIndex()).attr('disabled')
                        // console.log('finished?');
                        api.seekTo(2)
                    }

                } // IF number_of_errors
                $j(calling_element).attr("disabled", false); 
                $j('.wizards .progress').hide();

                // // console.log('result=', result);
                // $j(result).addClass('error');

            }) // getJson()

            // console.log('2');
            return false; 

            // } // direction

         // update status bar 
         // $j("#status li").removeClass("active").eq(i).addClass("active"); 

    } //advance pane
    $j('.my_next').removeAttr('disabled').click(advance_pane);
    $j(".my_next").keydown(function(e) { 
        if (e.keyCode == 9) { 
            // seeks to next tab by executing our validation routine 
            // // console.log('keydown event %o', e);
            // e.preventDefault(); 
            // advance_pane(e);
            $j("#gebdatum").datepicker();
            return false;
            
        } 
    });
    

});//ready()