//type, id list, extra, debug
function nutr_ajax_request(a_type, a_ids, extra, debug){ var a_href = './nutrition_ajax.php?type=' + a_type + extra; for(var i = 0; i < a_ids.length; i++){ a_href += '&' + a_ids[i].replace(/[^\w].*$/, '') + '=' + escape($('#' + a_ids[i]).val( )); } a_href += '&rand=' + getRandStr(10); if(debug){alert(a_href);}b_xml.request(a_href); }

//type, param str, debug
function nutr_simple_request(a_type, param_str, debug ){ var a_href = './nutrition_ajax.php?type=' + a_type + param_str + '&rand=' + getRandStr(10); if(debug){alert(a_href);}b_xml.request(a_href); }


function init_nutrition( ){
    init_meal_plan( );
    init_activity_plan( );
    init_recipe( );
    init_meal( );
    init_activity_group( );
    init_mp_populate( );

    init_recipe_search( );

    $("#mp_stats_tabs_table td a").unbind('click').click(function( ){
        var day_index = escape($("#mp_day_index").html( ));
        window.location = this.href + '&day_index=' + day_index;
        return false;
    });
    $("#act_stats_tabs_table td a").unbind('click').click(function( ){
        var day_index = escape($("#act_day_index").html( ));
        window.location = this.href + '&day_index=' + day_index;
        return false;
    });
}

function init_meal_plan( ){
    init_nutrition_search('fs');

    //this function will initialize the day index/date nave links, and tools for individual items
    //along with anything else more meal plan specific (Calorie bar and stuff).

    $('.mp_item_update').unbind('click').click(update_mp_item);
    $('.mp_item_delete').unbind('click').click(delete_mp_item);

    $('.mp_item_approve').click(approve_mp_item);

    $('.mp_day_nav_a, .m_mp_day_nav_a').unbind('click').click(day_nav_change);

    $( "#mp_day_nav_date" ).datepicker({
        showOn: "button",
        showAnim: 'slideDown',
        dateFormat: 'yy-mm-dd',
        onSelect: function(dateText, inst) {
            day_nav_change2(dateText);
        }
    });

    $('.mp_t_info_a').unbind('click').click(function( ){
        nutrition_interface_open('meal_create_from_index', this.rel);
        skip_accordion_init = true;
        return false;
    });

    $('.mp_edit_item').unbind('click').click(function( ){
        nutrition_interface_open('edit_mp_item', this.rel);
        skip_accordion_init = true;
        return false;
    });

    $('.act_edit_item').unbind('click').click(function( ){
        nutrition_interface_open('edit_act_item', this.rel);
        return false;
    });

    $('.mp_t_custom_a').unbind('click').click(function( ){
        var mp_item_str = '4_0';
        var mp_meal_type = this.id.replace(/^[^\d]+/, '');
        var plan_id = escape($("#mp_plan_id").html( ));
        var day_index = escape($("#mp_day_index").html( ));
        if(b_xml.isCurrentRequest){ return false; }
        var a_href = './nutrition_ajax.php?type=mp_item_add&plan_id=' + plan_id + '&mp_day_index=' + day_index + '&mp_meal_type=' + mp_meal_type + '&mp_item_str=' + mp_item_str + '&rand=' + getRandStr(10);
        skip_accordion_init = false;
        b_xml.request(a_href);
        return false;
    });

    $('#mp_populate').unbind('click').click(function( ){
        nutrition_interface_open('mp_populate', false);
        return false;
    });

    $('.mp_meal_item_table tr').mouseenter(function( ){
        //$(this).find('.mp_item_approve').css({'display': 'block'});
        $(this).find('.mp_item_approve').mouseenter(function( ){
            $(this).css({'background-image': 'url(/images/icons/approve_plan_item.jpg)'});
        }).mouseleave(function( ){
            $(this).css({'background-image': 'url(/images/icons/approve_plan_item_inactive.jpg)'});
        });

        //$(this).find('.mp_item_delete').css({'display': 'block'});
        $(this).find('.mp_item_delete').mouseenter(function( ){
            $(this).css({'background-image': 'url(/images/icons/remove_plan_item.jpg)'});
        }).mouseleave(function( ){
            $(this).css({'background-image': 'url(/images/icons/remove_plan_item_inactive.jpg)'});
        });
    })/*.mouseleave(function( ){
        $(this).find('.mp_item_approve').css({'display': 'none'});
        $(this).find('.mp_item_delete').css({'display': 'none'});
    })*/;

    $('.mp_fav_recipe').unbind('click').click(function( ){
        var a_href = './nutrition_ajax.php?type=recipe_info&nutr=' + $(this).attr('rel') + '&r=' + getRandStr(10);
        b_xml.request(a_href);
        $.colorbox({inline: true, width: "900px", height: "600px", href:'#nutr_interface'});
        skip_accordion_init = true;
        return false;
    });

    $('#meal_plan_right .fav_details').unbind('click').click(function( ){
        nutrition_interface_open('nutr_info', this.rel);
        skip_accordion_init = true;
        return false;
    });

    init_meal_plan_accordion( );

    $('.mp_item_add_exit').unbind('click').click(function( ){
        $(this).parent( ).slideToggle( );
        return false;
    });

    $('.mp_item_add_button').unbind('click').click(function( ){
        $(this).next( ).css({top: Math.round($(this).position( ).top - $(this).height( ) / 2) - 4 + 'px', left: $(this).position( ).left + 'px'}).slideToggle( );
        return false;
    });

    $('.mp_item_add_ok').unbind('click').click(function( ){
        var mp_item_str = $(this).attr('title').replace(/^[^\d]+/, '');
        var mp_meal_type = $(this).prev( ).val( ).replace(/^[^\d]+/, '');
        var plan_id = escape($("#mp_plan_id").html( ));
        var day_index = escape($("#mp_day_index").html( ));
        if(b_xml.isCurrentRequest){ return false; }
        var a_href = './nutrition_ajax.php?type=mp_item_add&plan_id=' + plan_id + '&mp_day_index=' + day_index + '&mp_meal_type=' + mp_meal_type + '&mp_item_str=' + mp_item_str + '&rand=' + getRandStr(10);
        b_xml.request(a_href);

        $('.mp_item_add').each(function( ){
            if($(this).css('display') != 'none'){
                $(this).slideToggle( );
            }
        });

        mp_meal_index = mp_meal_type - 1;
        mp_meal_section = $('#mp_main_contain h4').get(mp_meal_index);
        mp_main_scroll_top = $(mp_meal_section).offset( ).top - $('#mp_main').offset( ).top;
        if($.inArray(mp_meal_index, opened_tabs) <= -1){
            opened_tabs.push(mp_meal_index);
        }

        return false;
    });

}

function init_activity_plan( ){
    init_activity_search('act_s');

    $('.act_item_update').unbind('click').click(update_act_item);
    $('.act_item_delete').unbind('click').click(delete_act_item);

    $('.act_item_approve').unbind('click').click(approve_act_item);

    $('.act_day_nav_a, .m_act_day_nav_a').unbind('click').click(act_day_nav_change);

    $( "#act_day_nav_date" ).datepicker({
        showOn: "button",
        showAnim: 'slideDown',
        dateFormat: 'yy-mm-dd',
        onSelect: function(dateText, inst) {
            act_day_nav_change2(dateText);
        }
    });

    $('#act_steps')
        .unbind('focus')
        .unbind('blur')
        .focus(function( ){ if($(this).val( ) == 0){ $(this).val(''); } })
        .blur(function( ){ if($(this).val( ) == ''){ $(this).val('0'); } })
    ;

    $('#act_update_steps').unbind('click').click(update_act_steps);

    $('.act_item_table tr').mouseenter(function( ){
        $(this).find('.act_item_approve').mouseenter(function( ){
            $(this).css({'background-image': 'url(/images/icons/approve_plan_item.jpg)'});
        }).mouseleave(function( ){
            $(this).css({'background-image': 'url(/images/icons/approve_plan_item_inactive.jpg)'});
        });
        //$(this).find('.act_item_delete').css({'display': 'block'});
        $(this).find('.act_item_delete').mouseenter(function( ){
            $(this).css({'background-image': 'url(/images/icons/remove_plan_item.jpg)'});
        }).mouseleave(function( ){
            $(this).css({'background-image': 'url(/images/icons/remove_plan_item_inactive.jpg)'});
        });
    });

    $('.act_item_add_button').unbind('click').click(function( ){
        var act_item_str = $(this).attr('rel').replace(/^[^\d]+/, '');
        var plan_id = escape($("#act_plan_id").html( ));
        var day_index = escape($("#act_day_index").html( ));
        if(b_xml.isCurrentRequest){ return false; }
        var a_href = './nutrition_ajax.php?type=act_item_add&plan_id=' + plan_id + '&act_day_index=' + day_index + '&act_item_str=' + act_item_str + '&rand=' + getRandStr(10);
        b_xml.request(a_href);

        $('.mp_item_add').each(function( ){
            if($(this).css('display') != 'none'){
                $(this).slideToggle( );
            }
        });

        return false;
    });

    $('.act_name_details, .act_details_link').unbind('click').click(function( ){
        nutrition_interface_open('act_details', $(this).attr('rel'));
        return false;
    });

    $('.act_save_plan').unbind('click').click(function( ){
        nutrition_interface_open('act_group_create_from_index', this.rel);
        return false;
    });

    if(window.load_cufon){
        Cufon.replace('#mp_stats_tabs table td a,.mp_plan_date',{
            fontFamily: 'league',
            fontSize: '30px'
        });

        Cufon.replace('#mp_cal_progress_text',{
            fontFamily: 'league',
            fontSize: '20px',
            textShadow: '-1px -1px 0 #939297,1px -1px 0 #939297,-1px 1px 0 #939297,1px 1px 0 #939297;'
        });
    }
}

function init_recipe( ){
    init_nutrition_search('fsr');

    $('.r_name_default').unbind('click').click(reset_recipe_item_desc);
    $('.recipe_item_update').unbind('click').click(update_recipe_item);
    $('.recipe_item_delete').unbind('click').click(delete_recipe_item);
    $('.recipe_nutr_info').unbind('click').click(function( ){
        nutrition_interface_open('nutr_info', '2_' + this.rel);
        return false;
    });


    $('#a_recipe_ingredients #recipe_item_table tbody').sortable({
        handle: ".r_drag",
        stop: function( ){ update_recipe_sort( ); }
    });
}

function init_meal( ){
    //will need to init_nutrition_search_popup on the meal creator popups.
    if(document.getElementById('meal_form_container')){
        init_meal_interface( );
    }
    else if(document.getElementById('meal_add_form')){
        init_meal_add_form( );
    }
}

function init_activity_group( ){
    //will need to init on the activity creator popup
    if(document.getElementById('group_add_form')){
        init_act_group_add_form( );
    }
}

function init_mp_populate( ){

    if(!$('#mp_populate_day_index')){ return; }

    $('#mp_populate_day_index').datepicker({
        dateFormat: 'yy-mm-dd'
    });

    $('#mp_populate_submit').unbind('click').click(mp_populate_meal_plan);
}

function init_meal_interface( ){
    init_nutrition_search('fsp');
    $('.meal_item_update').unbind('click').click(update_meal_item);
    $('.meal_item_delete').unbind('click').click(delete_meal_item);
    $('#meal_update').unbind('click').click(update_meal_record);

    $('#meal_custom_add').unbind('click').click(function( ){
        var m_item_str = '4_0';
        var meal_id = document.getElementById('meal_id').value;
        if(b_xml.isCurrentRequest){ return false; }
        var a_href = './nutrition_ajax.php?type=meal_item_add&meal_id=' + meal_id + '&m_item_str=' + m_item_str + '&rand=' + getRandStr(10);
        b_xml.request(a_href);

        return false;
    });

    if(window.load_cufon){

        Cufon.replace('#meal_form_container h2',{
            fontFamily: 'league',
            fontSize: '30px'
        });

        Cufon.replace('#fsp_main_nav a',{
            fontFamily: 'mpc',
            textTransform: 'uppercase',
            fontSize: '16px'
        });

        Cufon.replace('#meal_form_container h4',{
            fontFamily: 'mpc',
            textTransform: 'uppercase',
            fontSize: '24px',
            fontWeight: 'normal'
        });


        Cufon.replace('.mp_header_1, .mp_header_2, .mp_header_3, .mp_header_4',{
            fontFamily: 'pl'
        });






        /*Cufon.replace('.mp_body_container h4',{
            fontFamily: 'mpc',
            color: '#ffffff',
            textTransform: 'uppercase',
            fontSize: '24px',
            fontWeight: 'normal'
        });

        Cufon.replace('#mp_stats_tabs table td a,.mp_plan_date',{
            fontFamily: 'league',
            fontSize: '30px'
        });

        Cufon.replace('#mp_progress_caption',{
            fontFamily: 'mpc',
            fontSize: '16px'
        });

        Cufon.replace('#mp_cal_progress_text',{
            fontFamily: 'league',
            fontSize: '20px',
            textShadow: '-1px -1px 0 #939297,1px -1px 0 #939297,-1px 1px 0 #939297,1px 1px 0 #939297;'
        });

        Cufon.replace('.mp_meal_calories strong',{
            fontFamily: 'pl'
        });

        Cufon.replace('.meal_head_calorie_count',{
            fontFamily: 'mpc',
            fontSize: '18px'
        });

        Cufon.replace('.meal_head_calorie_count strong',{
            fontFamily: 'pl',
            fontSize: '20px'
        });*/
    }

    //init the rest of it here.
}


function init_recipe_search( ){

    var recipe_search_outer = document.getElementById('recipe_search_outer');
    if(!recipe_search_outer){ return; }

    $('#rsearch_form').submit(function( ){
        //update_recipe_search(0, false, '');
        //return false;
    });

    $('.rcat_switch').click( function( ){
        if($(this).hasClass('rcat_switch_cur')){
            $('.rcat_switch').removeClass('rcat_switch_cur');
        }
        else{
            $('.rcat_switch').removeClass('rcat_switch_cur');
            $(this).addClass('rcat_switch_cur');
        }

        update_recipe_search(false, true, $(this_jq_obj).attr('href'));
        return false;

    } );

    $('.r_skill_filter, .r_prep_filter, .r_cat_filter, #r_sort').change(function( ){
        update_recipe_search(0, true, '');
        return false;
    });

    $('#r_prev, #r_next').click(function( ){
        recipe_change_page(this, true);
        return false;
    });

}

function recipe_change_page(this_jq_obj, no_ajax){
    update_recipe_search($(this_jq_obj).attr('rel'), no_ajax, $(this_jq_obj).attr('href'));
    return false;
}

function update_recipe_search(page_mult, no_ajax, a_href){

    var search_var = $('#rsearch_input').val( );
    var r_catid = $('.rcat_switch_cur').attr('rel') ? $('.rcat_switch_cur').attr('rel') : '';

    var r_sort = $('#r_sort').val( );

    var skills = '';
    var preps = '';
    var cats = '';

    var mult = 0;

    if(page_mult && parseInt(page_mult) != NaN){
        mult = parseInt(page_mult);
    }

    var c = document.getElementById('r_filters_skill').getElementsByTagName('input');
    for(var i = 0; i < c.length; i++){
        if(c[i].className == 'r_skill_filter' && c[i].checked){ skills += skills != '' ? '_' : ''; skills += c[i].value; }
    }

    var c = document.getElementById('r_filters_prep').getElementsByTagName('input');
    for(var i = 0; i < c.length; i++){
        if(c[i].className == 'r_prep_filter' && c[i].checked){ preps += preps != '' ? '_' : ''; preps += c[i].value; }
    }

    c = document.getElementById('r_filters_cat').getElementsByTagName('input');
    for(var i = 0; i < c.length; i++){
        if(c[i].className == 'r_cat_filter' && c[i].checked){ cats += cats != '' ? '_' : ''; cats += c[i].value; }
    }

    var qstr = './nutrition_ajax.php?type=recipe_search';
    if(no_ajax){
        qstr = window.location.pathname;
    }

    if(qstr.match(/\?/)){
        qstr += '&search_var=' + escape(search_var);
    }
    else{
        qstr += '?search_var=' + escape(search_var);
    }

    if(a_href != undefined && a_href != '' && getVar('r_catid', a_href)){
        qstr += '&r_catid=' + getVar('r_catid', a_href);
    }
    /*else if(getVar('r_catid') != ''){
        qstr += '&r_catid=' + getVar('r_catid');
    }*/
    else{
        qstr += '&r_catid=' + escape(r_catid);
    }

    if(a_href != undefined && a_href != '' && getVar('r_sort', a_href)){
        qstr += '&r_sort=' + getVar('r_sort', a_href);
    }
    /*else if(getVar('r_sort') != ''){
        qstr += '&r_sort=' + getVar('r_sort');
    }*/
    else{
        qstr += '&r_sort=' + escape(r_sort);
    }

    if(a_href != undefined && a_href != '' && getVar('skills', a_href)){
        qstr += '&skills=' + getVar('skills', a_href);
    }
    /*else if(getVar('skills') != ''){
        qstr += '&skills=' + getVar('skills');
    }*/
    else{
        qstr += '&skills=' + escape(skills);
    }

    if(a_href != undefined && a_href != '' && getVar('preps', a_href)){
        qstr += '&preps=' + getVar('preps', a_href);
    }
    /*else if(getVar('preps') != ''){
        qstr += '&preps=' + getVar('preps');
    }*/
    else{
        qstr += '&preps=' + escape(preps);
    }

    if(a_href != undefined && a_href != '' && getVar('cats', a_href)){
        qstr += '&cats=' + getVar('cats', a_href);
    }
    /*else if(getVar('cats') != ''){
        qstr += '&cats=' + getVar('cats');
    }*/
    else{
        qstr += '&cats=' + escape(cats);
    }

    if(a_href != undefined && a_href != '' && getVar('mult', a_href)){
        qstr += '&mult=' + getVar('mult', a_href);
    }
    /*else if(getVar('mult') != ''){
        qstr += '&mult=' + getVar('mult');
    }*/
    else{
        qstr += '&mult=' + escape(mult);
    }

    if(no_ajax){
        page_id = parseInt(getVar('p'));
        if(page_id > 0){
            qstr += '&p=' + page_id;
        }

        window.location.href = window.location.protocol + '//' + window.location.hostname + qstr;
        return false;
    }

    b_xml.request(qstr);
    return false;
}


function create_new_meal( ){
    nutr_ajax_request('add_meal', Array('meal_name', 'default_meal_type'), '', false);
    window.setTimeout(display_meal_edit_from_add, 1000);
    return false;
}

function create_new_group( ){
    nutr_ajax_request('add_group', Array('group_name', 'group_id'), '', false);
    window.setTimeout(display_group_edit_from_add, 1000);
    return false;
}

function create_new_meal_from_index( ){
    document.getElementById('meal_add_status').innerHTML = '';
    if($('#plan_id').length > 0){
        nutr_ajax_request('add_meal_from_index', Array('meal_name', 'm_index', 'plan_id'), '', false);
    }
    else{
        nutr_ajax_request('add_meal_from_index', Array('meal_name', 'm_index'), '', false);
    }

    window.setTimeout(close_meal_add_form, 1000); return false;
}

function create_new_group_from_index( ){
    document.getElementById('group_status').innerHTML = '';
    if($('#plan_id').length > 0){
        nutr_ajax_request('add_group_from_index', Array('group_name', 'act_index', 'plan_id', 'group_id'), '', false);
    }
    else{
        nutr_ajax_request('add_group_from_index', Array('group_name', 'act_index', 'group_id'), '', false);
    }

    window.setTimeout(close_group_add_form, 1000); return false;
}

function update_meal_record( ){ nutr_ajax_request('update_meal', Array('meal_id', 'meal_name', 'default_meal_type', 'meal_published:checked'), '', false); return false; }


function mp_populate_meal_plan( ){
    if(confirm("If you click OK, all meal data for 7 days from the selected date will be replaced with the recommended meal plan of your choosing.  Click OK to continue, or cancel otherwise.")){
        nutr_ajax_request('mp_populate_meal_plan', Array('mp_populate_day_index', 'mp_meal_plan_id'), '', false);
        $.colorbox.close( );
    }
}

function day_nav_change( ){
    var plan_id = escape($("#mp_plan_id").html( ));
    var day_index = this.rel
    if(b_xml.isCurrentRequest){ return false; }

    skip_accordion_init = false;
    var a_href = './nutrition_ajax.php?type=day_nav_change&plan_id=' + plan_id + '&mp_day_index=' + day_index + '&rand=' + getRandStr(10);
    b_xml.request(a_href);

    $('.mp_day_nav_a').removeClass('mp_day_nav_a_active');
    $(this).addClass('mp_day_nav_a_active');

    return false;
}

function day_nav_change2(day_index){
    var plan_id = escape($("#mp_plan_id").html( ));
    if(b_xml.isCurrentRequest){ return false; }
    var a_href = './nutrition_ajax.php?type=day_nav_change&plan_id=' + plan_id + '&mp_day_index=' + day_index + '&rand=' + getRandStr(10);
    b_xml.request(a_href);
    return false;
}

function update_mp_item( ){
    var plan_id = escape($("#mp_plan_id").html( ));
    var day_index = escape($("#mp_day_index").html( ));

    var mp_item_id = this.rel;

    var mp_name = document.getElementById('mp_name_' + mp_item_id);
    if(mp_name){ mp_name = escape(mp_name.value); }
    else{ mp_name = ''; }

    var mp_cal = document.getElementById('mp_cal_' + mp_item_id);
    if(mp_cal){ mp_cal = escape(mp_cal.value); }
    else{ mp_cal = ''; }

    var mp_qty = document.getElementById('mp_qty_' + mp_item_id);
    if(mp_qty){ mp_qty = escape(mp_qty.value); }
    else{ mp_qty = ''; }

    var mp_unit = document.getElementById('mp_unit_' + mp_item_id);

    if(mp_unit && mp_unit.tagName.toLowerCase( ) == 'select'){ mp_unit = escape(mp_unit.options[mp_unit.selectedIndex].value); }
    else if(mp_unit){
        mp_unit = escape(mp_unit.value);
    }
    else{ mp_unit = ''; }

    var a_href = './nutrition_ajax.php?type=mp_item_update&plan_id=' + plan_id + '&mp_day_index=' + day_index + '&mp_item_id=' + mp_item_id + '&mp_qty=' + mp_qty + '&mp_unit=' + mp_unit + '&mp_name=' + mp_name + '&mp_cal=' + mp_cal + '&rand=' + getRandStr(10);
    b_xml.request(a_href);
    skip_accodion_init = true;
    return false;
}

function approve_mp_item( ){
    var plan_id = escape($("#mp_plan_id").html( ));
    var day_index = escape($("#mp_day_index").html( ));

    var mp_item_id = this.rel;

    var a_href = './nutrition_ajax.php?type=mp_item_approve&plan_id=' + plan_id + '&mp_day_index=' + day_index + '&mp_item_id=' + mp_item_id + '&rand=' + getRandStr(10);
    b_xml.request(a_href);
    return false;
}

function delete_mp_item( ){
    //if(confirm("Are you sure you want to delete this meal plan item?")){
        mp_main_scroll_top = $('#mp_main').scrollTop( );
        var plan_id = escape($("#mp_plan_id").html( ));
        var day_index = escape($("#mp_day_index").html( ));
        var a_href = './nutrition_ajax.php?type=mp_item_delete&plan_id=' + plan_id + '&mp_day_index=' + day_index + '&mp_item_id=' + this.rel + '&rand=' + getRandStr(10);
        b_xml.request(a_href);
    //}

    return false;
}

function update_meal_item( ){
    var meal_id = parseInt(document.getElementById('meal_id').value);
    var m_item_id = this.rel;

    var m_name = document.getElementById('meal_name_' + m_item_id);
    if(m_name){ m_name = escape(m_name.value); }
    else{ m_name = ''; }

    var m_cal = document.getElementById('meal_cal_' + m_item_id);
    if(m_cal){ m_cal = escape(m_cal.value); }
    else{ m_cal = ''; }

    var m_qty = document.getElementById('meal_qty_' + m_item_id);
    if(m_qty){ m_qty = escape(m_qty.value); }
    else{ m_qty = ''; }


    var m_unit = document.getElementById('meal_unit_' + m_item_id);

    if(m_unit && m_unit.tagName.toLowerCase( ) == 'select'){ m_unit = escape(m_unit.options[m_unit.selectedIndex].value); }
    else if(m_unit){
        m_unit = escape(m_unit.value);
    }
    else{ m_unit = ''; }

    var a_href = './nutrition_ajax.php?type=meal_item_update&meal_id=' + meal_id + '&m_item_id=' + m_item_id + '&m_qty=' + m_qty + '&m_unit=' + m_unit + '&m_name=' + m_name + '&m_cal=' + m_cal +'&rand=' + getRandStr(10);
    b_xml.request(a_href);
    return false;
}

function delete_meal_item( ){
    if(confirm("Are you sure you want to delete this meal item?")){
        var meal_id = parseInt(document.getElementById('meal_id').value);
        var a_href = './nutrition_ajax.php?type=meal_item_delete&meal_id=' + meal_id + '&m_item_id=' + this.rel + '&rand=' + getRandStr(10);
        b_xml.request(a_href);
    }

    return false;
}

function reset_recipe_item_desc( ){
    var recipe_id = parseInt(document.getElementById('recipe_id').value);
    var r_item_id = parseInt(this.id.replace(/r_name_default_/, ''));

    if(!r_item_id || r_item_id == NaN){
        $('#recipe_status').html('<span class="error">Ingredient id not valid</span>');
        return false;
    }

    var a_href = './nutrition_ajax.php?type=reset_recipe_item_desc&recipe_id=' + recipe_id + '&r_item_id=' + r_item_id + '&rand=' + getRandStr(10);
    b_xml.request(a_href);
    return false;
}

function update_recipe_item( ){
    var recipe_id = parseInt(document.getElementById('recipe_id').value);

    var r_item_id = this.rel;
    var r_qty = document.getElementById('r_qty_' + r_item_id);
    if(r_qty){ r_qty = escape(r_qty.value); }
    else{ r_qty = ''; }

    var r_unit = document.getElementById('r_unit_' + r_item_id);
    if(r_unit){
        if(r_unit.tagName && r_unit.tagName.toLowerCase( ) == 'select'){
            r_unit = escape(r_unit.options[r_unit.selectedIndex].value);
        }
        else{
            r_unit = escape(r_unit.value);
        }
    }
    else{ r_unit = ''; }

    var r_item_desc = document.getElementById('r_item_desc_' + r_item_id);
    if(r_item_desc){ r_item_desc = escape(r_item_desc.value); }
    else{ r_item_desc = ''; }


    var a_href = './nutrition_ajax.php?type=recipe_item_update&recipe_id=' + recipe_id + '&r_item_id=' + r_item_id + '&r_qty=' + r_qty + '&r_unit=' + r_unit + '&r_item_desc=' + r_item_desc + '&rand=' + getRandStr(10);
    b_xml.request(a_href);
    return false;
}

function delete_recipe_item( ){
    if(confirm("Are you sure you want to delete this recipe ingredient?")){
        var recipe_id = parseInt(document.getElementById('recipe_id').value);
        var a_href = './nutrition_ajax.php?type=recipe_item_delete&recipe_id=' + recipe_id + '&r_item_id=' + this.rel + '&rand=' + getRandStr(10);
        b_xml.request(a_href);
    }

    return false;
}


function update_recipe_sort( ){
    var recipe_id = parseInt(document.getElementById('recipe_id').value);
    var q_params = '';
    var trs = document.getElementById('recipe_item_table').getElementsByTagName('tr');
    for(var i = 0; i < trs.length; i++){
        var tr_id = parseInt(trs[i].id.toString( ).replace(/^r_item_tr_/, ''));
        q_params += q_params != '' ? '_' : '';
        q_params += tr_id && tr_id != NaN ? tr_id : '';
    }

    var a_href = './nutrition_ajax.php?type=recipe_item_sort&recipe_id=' + recipe_id + '&r_sort=' + q_params + '&rand=' + getRandStr(10);
    b_xml.request(a_href);
}

function init_meal_add_form( ){
    var meal_add_form = document.getElementById('meal_add_form');
    if(!meal_add_form){ return; }

    $('#m_add_meal_button').dblclick(function( ){ return false; });

    var m_index = document.getElementById('m_index');
    if(m_index){
        $('#m_add_meal_button').unbind('click').click(create_new_meal_from_index);
    }
    else{
        $('#m_add_meal_button').unbind('click').click(create_new_meal);
    }

    skip_accordion_init = true;
}

function init_act_group_add_form( ){
    var group_add_form = document.getElementById('group_add_form');
    if(!group_add_form){ return; }

    $('#m_add_act_group_button').dblclick(function( ){ return false; });

    $('#group_id').change(function( ){
        if($('option:selected', this).val( ) == '0'){
            $('#group_name').val('');
        }
        else{
            $('#group_name').val($('option:selected', this).text( ));
        }
    });

    var act_index = document.getElementById('act_index');
    if(act_index){
        $('#m_add_act_group_button').unbind('click').click(create_new_group_from_index);
    }
    else{
        $('#m_add_act_group_button').unbind('click').click(create_new_group);
    }
}

function display_meal_edit_from_add( ){
    meal_error = document.getElementById('meal_add_status').innerHTML;
    if(meal_error == ''){
        meal_id = parseInt(document.getElementById('meal_id').innerHTML);
        if(meal_id != NaN && meal_id > 0){
            nutrition_interface_open('meal_edit', meal_id);
        }
    }
}

function display_group_edit_from_add( ){
    group_error = document.getElementById('group_status').innerHTML;
    if(group_error == ''){
        group_id = parseInt(document.getElementById('group_id').innerHTML);
        if(group_id != NaN && group_id > 0){
            nutrition_interface_open('group_edit', group_id);
        }
    }
}

function close_meal_add_form( ){
    meal_error = document.getElementById('meal_add_status').innerHTML;
    if(meal_error == ''){
        $.colorbox.close( );
    }
}
function close_group_add_form( ){
    group_error = document.getElementById('group_status').innerHTML;
    if(group_error == ''){
        $.colorbox.close( );
    }
}

function display_meal_edit_from_link( ){
    var meal_id = this.rel;
    nutrition_interface_open('meal_edit', meal_id);
    skip_accordion_init = true;
    return false;
}

function init_nutrition_search(fs_prefix){
    nutr_interface = document.getElementById('nutr_interface');
    if(!nutr_interface){
        var nutr_interface = document.createElement('div');
        nutr_interface.id = 'nutr_interface';
        document.body.appendChild(nutr_interface);
    }

    var fs_container = document.getElementById(fs_prefix + '_container');
    if(!fs_container){ return; }

    fs_container.fs_prefix = fs_prefix;
    $('#' + fs_container.id).unbind('fs_refresh').bind('fs_refresh', fs_apply_results);

    var fs_main_nav = document.getElementById(fs_prefix + '_main_nav');
    var fs_search_form = document.getElementById(fs_prefix + '_search_form');
    var fs_search = document.getElementById(fs_prefix + '_search');
    var fs_search_var = document.getElementById(fs_prefix + '_search_var');
    var fs_search_button = document.getElementById(fs_prefix + '_search_button');

    var fs_config = document.getElementById(fs_prefix + '_config') ? document.getElementById(fs_prefix + '_config').value : 0;

    fs_search_form.fs_prefix = fs_prefix;
    fs_search_form.fs_config = fs_config;
    fs_search_form.onsubmit = fs_apply_results;

    var fs_recipe_cat_obj = document.getElementById(fs_prefix + '_recipe_cat');
    var fs_ndb_cat_obj = document.getElementById(fs_prefix + '_ndb_cat');

    if(fs_recipe_cat_obj){ fs_recipe_cat_obj.fs_prefix = fs_prefix;  fs_recipe_cat_obj.fs_config = fs_config; fs_recipe_cat_obj.onchange = fs_apply_results; }
    if(fs_ndb_cat_obj){ fs_ndb_cat_obj.fs_prefix = fs_prefix;  fs_ndb_cat_obj.fs_config = fs_config;  fs_ndb_cat_obj.onchange = fs_apply_results; }

    var links = fs_main_nav.getElementsByTagName('a');
    for(var i = 0; i < links.length; i++){
        links[i].fs_prefix = fs_prefix;
        links[i].fs_config = fs_config;
        links[i].onclick = function( ){
            if(this.className == 'fs_nav_a_active' || b_xml.isCurrentRequest){ return false; }

            var fs_main_nav = document.getElementById(this.fs_prefix + '_main_nav');

            var p_links = fs_main_nav.getElementsByTagName('a');
            var cur_tab = 0;
            for(var j = 0; j < p_links.length; j++){
                if(p_links.id != this.id && p_links[j].className == 'fs_nav_a_active'){
                    var cur_tab = p_links[j].rel;
                }
                if(p_links.id != this.id){p_links[j].className = 'fs_nav_a';}
            }
            this.className = 'fs_nav_a_active';

            var fs_fav_nav_str = '';
            if(this.rel == 0 && cur_tab > 0){
                fs_fav_nav_str = '&fs_fav_nav=' + cur_tab;
            }

            var a_href = './nutrition_ajax.php?type=fs_nav&fs_prefix=' + this.fs_prefix + '&fs_tab=' + this.rel + fs_fav_nav_str + '&search_var=' + escape(fs_search_var.value) + '&fs_config=' + this.fs_config + '&rand=' + getRandStr(10);

            b_xml.request(a_href);
            //fs_search.style.display = this.rel > 0 ? 'block' : 'none';
            skip_accordion_init = true;

            return false;
        }
    }

    init_fs_results(fs_prefix);
}

var food_item_dragging = false;
var mp_main_scroll_top = 0;
function init_fs_results(fs_prefix){
    var fs_contain = document.getElementById(fs_prefix + '_container');
    var fs_config = document.getElementById(fs_prefix + '_config') ? document.getElementById(fs_prefix + '_config').value : 0;

    if(!fs_contain){ return; }

    $(".food_item_block").draggable({
        revert: true,
        revertDuration: 1,
        opacity: .8,
        helper: "clone",
        //handle: ".food_item_drag",
        zIndex: 20000,
        refreshPositions: true,
        cursor: 'move',
        cursorAt: {right: -1},
        start: function(event, ui){
            food_item_dragging = true;
            $('.mp_item_add').each(function( ){
                if($(this).css('display') != 'none'){
                    $(this).hide( );
                }
            });
        },
        stop: function(event, ui){
            food_item_dragging = false;
        }
    });

    $( "#meal_plan_interface .mp_drop_zone" ).droppable({
        accept: "#meal_plan_interface .food_item_block",
        greedy: true,
        tolerance: 'pointer',
        activeClass: "mp_drop_zone_active",
        hoverClass: "mp_drop_zone_hover",
        drop: function( event, ui ) {
            mp_main_scroll_top = $('#mp_main').scrollTop( );
            $(".mp_drop_zone").removeClass('mp_drop_zone_active');
            $(".mp_drop_zone").removeClass('mp_drop_zone_hover');
            var drop_id = ui.draggable.context.id;
            var mp_item_str = drop_id.replace(/^[^\d]+/, '');
            var mp_meal_type = this.id.replace(/^[^\d]+/, '');
            var plan_id = escape($("#mp_plan_id").html( ));
            var day_index = escape($("#mp_day_index").html( ));
            if(b_xml.isCurrentRequest){ return false; }
            var a_href = './nutrition_ajax.php?type=mp_item_add&plan_id=' + plan_id + '&mp_day_index=' + day_index + '&mp_meal_type=' + mp_meal_type + '&mp_item_str=' + mp_item_str + '&rand=' + getRandStr(10);
            skip_accordion_init = false;
            b_xml.request(a_href);
        }
    });

    $( "#meal_form_container .mp_drop_zone" ).droppable({
        accept: "#meal_form_container .food_item_block",
        greedy: true,
        tolerance: 'pointer',
        activeClass: "mp_drop_zone_active",
        hoverClass: "mp_drop_zone_hover",
        drop: function( event, ui ) {
            $(".mp_drop_zone").removeClass('mp_drop_zone_active');
            $(".mp_drop_zone").removeClass('mp_drop_zone_hover');
            var drop_id = ui.draggable.context.id;
            var m_item_str = drop_id.replace(/^[^\d]+/, '');
            var meal_id = document.getElementById('meal_id').value;
            if(b_xml.isCurrentRequest){ return false; }
            var a_href = './nutrition_ajax.php?type=meal_item_add&meal_id=' + meal_id + '&m_item_str=' + m_item_str + '&rand=' + getRandStr(10);
            b_xml.request(a_href);
        }
    });


    $( "#recipe_ingredients .mp_drop_zone" ).droppable({
        accept: "#recipe_ingredients .food_item_block",
        greedy: true,
        tolerance: 'pointer',
        activeClass: "mp_drop_zone_active",
        hoverClass: "mp_drop_zone_hover",
        drop: function( event, ui ) {
            $(".mp_drop_zone").removeClass('mp_drop_zone_active');
            $(".mp_drop_zone").removeClass('mp_drop_zone_hover');
            var drop_id = ui.draggable.context.id;
            var r_item_str = drop_id.replace(/^[^\d]+/, '');
            var recipe_id = document.getElementById('recipe_id').value;
            if(b_xml.isCurrentRequest){ return false; }
            var a_href = './nutrition_ajax.php?type=recipe_item_add&recipe_id=' + recipe_id + '&r_item_str=' + r_item_str + '&rand=' + getRandStr(10);
            b_xml.request(a_href);
        }
    });


    var a_links = fs_contain.getElementsByTagName('a');
    var i = 0;

    for(i = 0; i < a_links.length; i++){
        var a = a_links[i];
        var rel = a.rel;
        var cname = a.className;

        switch(cname){
        case 'fav_add':
            a.fs_prefix = fs_prefix;
            a.onclick = function( ){
                if(b_xml.isCurrentRequest){ return false; }
                var a_href = './nutrition_ajax.php?type=fav_add&fs_prefix=' + this.fs_prefix + '&fav_str=' + this.rel;
                b_xml.request(a_href);
                $(this).replaceWith('<img src="/images/meal_plan_item_saved.jpg" alt="Saved" />');
                this.className = 'fav_added';
                skip_accordion_init = true;
                return false;
            }
            break;

        case 'fav_del':
            a.fs_prefix = fs_prefix;
            a.onclick = function( ){
                if(b_xml.isCurrentRequest){ return false; }
                var a_href = './nutrition_ajax.php?type=fav_del&fs_prefix=' + this.fs_prefix + '&fav_str=' + this.rel;
                b_xml.request(a_href);
                //$(this).replaceWith('Item Removed');
                //this.className = 'fav_removed';
                window.setTimeout(fs_apply_results, 200);
                skip_accordion_init = true;
                return false;
            }
            break;

        case 'fav_recipe':
            a.fs_prefix = fs_prefix;
            a.onclick = function( ){
                nutrition_interface_open('recipe_info', this.rel);
                skip_accordion_init = true;
                return false;
            }
            break;

        case 'fav_details':
            a.fs_prefix = fs_prefix;
            a.onclick = function( ){
                nutrition_interface_open('nutr_info', this.rel);
                skip_accordion_init = true;
                return false;
            }
            break;

        case 'fs_fav_nav_a':
            a.fs_config = fs_config;
            a.fs_prefix = fs_prefix;
            a.onclick = function( ){
                var fs_search_var = document.getElementById(this.fs_prefix + '_search_var');
                var a_href = './nutrition_ajax.php?type=fav_nav&fs_prefix=' + this.fs_prefix + '&fs_fav_nav=' + this.rel + '&fs_config=' + this.fs_config + '&search_var=' + escape(fs_search_var.value) + '&rand=' + getRandStr(10);
                b_xml.request(a_href);
                skip_accordion_init = true;
                return false;
            }
            break;

        case 'fs_mp_nav_a':
            if(a.rel == 0 || a.rel == 1){
                a.fs_config = fs_config;
                a.fs_prefix = fs_prefix;
                a.onclick = function( ){
                    var fs_search_var = document.getElementById(this.fs_prefix + '_search_var');
                    var a_href = './nutrition_ajax.php?type=mp_nav&fs_tab=1&fs_prefix=' + this.fs_prefix + '&fs_mp_nav=' + this.rel + '&fs_config=' + this.fs_config + '&search_var=' + escape(fs_search_var.value) + '&rand=' + getRandStr(10);
                    b_xml.request(a_href);
                    skip_accordion_init = true;
                    return false;
                }

            }
            else{
                a.fs_prefix = fs_prefix;
                a.onclick = function( ){
                    nutrition_interface_open('meal_create', false);
                    skip_accordion_init = true;
                    return false;
                }
            }
            break;

        case 'fs_mp_nav_a_active':
        case 'fs_fav_nav_a_active':
            a.onclick = function( ){ return false; }
            break;

        case 'fs_res_prev_active':
        case 'fs_res_next_active':
            a.fs_prefix = fs_prefix;
            a.fs_config = fs_config;
            a.onclick = fs_apply_results;
            break;

        case 'fs_res_prev_inactive':
        case 'fs_res_next_inactive':
            a.onclick = function( ){ return false; }
            break;

        case 'fs_edit_meal':
            a.onclick = display_meal_edit_from_link;
            break;

        case 'fs_details_meal':
            a.onclick = function( ){
                b_xml.request('./nutrition_ajax.php?type=meal_details&meal_id=' + this.rel + '&r=' + getRandStr(10));
                $.colorbox({inline: true, width: '500px', height: '300px', href:'#nutr_interface' } );
                skip_accordion_init = true;
                return false;
            }
            break;

        case 'fs_delete_meal':
            a.onclick = function( ){
                if(confirm('Are you sure you want to delete this meal record?  Existing meal plans will be unaffected.')){
                    b_xml.request('./nutrition_ajax.php?type=delete_meal&meal_id=' + this.rel + '&r=' + getRandStr(10));
                    window.setTimeout(fs_apply_results, 200);
                }

                skip_accordion_init = true;

                return false;
            }
            break;

        default:
            break;
        }
    }

}

function fs_apply_results( ){
    if(!this.fs_prefix){
        this.fs_prefix = 'fs';
    }

    var fs_contain = document.getElementById(this.fs_prefix + '_container');
    var fs_search_var = document.getElementById(this.fs_prefix + '_search_var');

    //these two won't always exist
    var fs_recipe_cat_obj = document.getElementById(this.fs_prefix + '_recipe_cat');
    var fs_ndb_cat_obj = document.getElementById(this.fs_prefix + '_ndb_cat');

    var fs_recipe_cat = 0;
    var fs_ndb_cat = 0;

    if(fs_recipe_cat_obj){
        fs_recipe_cat = fs_recipe_cat_obj.options[fs_recipe_cat_obj.selectedIndex].value;
    }
    if(fs_ndb_cat_obj){
        fs_ndb_cat = fs_ndb_cat_obj.options[fs_ndb_cat_obj.selectedIndex].value;
    }

    var db_page_num = 0;
    if(this.className == 'fs_res_prev_active' || this.className == 'fs_res_next_active'){ db_page_num = this.rel; }

    var a_links = fs_contain.getElementsByTagName('a');

    var fs_main = $('.fs_nav_a_active').first( ).attr('rel');
    var fs_fav = 0;
    var fs_mp = 0;

    for(var i = 0; i < a_links.length; i++){
        var a = a_links[i];
        var rel = a.rel;
        var cname = a.className;

        switch(cname){
        /*case 'fs_nav_a_active':
            fs_main = rel;
            break;*/

        case 'fs_fav_nav_a_active':
            fs_fav = rel;
            break;

        case 'fs_mp_nav_a_active':
            fs_mp = rel;
            break;

        //add the other ones here once we get to them.

        default:
            break;
        }
    }

    var fs_href = './nutrition_ajax.php?type=fs_nav&fs_prefix=' + this.fs_prefix + '&fs_tab=' + fs_main + '&fs_fav_nav=' + fs_fav + '&fs_mp_nav=' + fs_mp + '&fs_recipe_cat=' + fs_recipe_cat + '&fs_ndb_cat=' + fs_ndb_cat + '&fs_config=' + this.fs_config + '&search_var=' + escape(fs_search_var.value) + '&db_page_num=' + db_page_num + '&rand=' + getRandStr(10);
    b_xml.request(fs_href);
    skip_accordion_init = true;
    return false;
}

function nutrition_interface_open(i_type, param){

    var nutr_interface = document.getElementById('nutr_interface');

    param = escape(param);

    var i_href = '';
    switch(i_type){

    case 'meal_create':
        var a_href = './nutrition_ajax.php?type=create_meal&r=' + getRandStr(10);
        b_xml.request(a_href);

        var c_width = 500;
        var c_height = 300;

        c_width = c_width + 'px';
        c_height = c_height + 'px';

        $.colorbox({inline: true, width: c_width, height: c_height, href:'#nutr_interface', onCleanup: function( ){$("#fs_container").trigger('fs_refresh') } } );
        break;

    case 'meal_create_from_index':
        //m_index is in the form of (yyyy-mm-dd_{meal_type}
        //meal created from the meal on that particular day index.
        //If no items are there, default behavior is used.
        plan_str = '';
        if($('#mp_plan_id').length > 0){
            plan_id = $('#mp_plan_id').html( ).replace(/[^\d]/, '');
            plan_str = '&plan_id=' + escape(plan_id);
        }

        var a_href = './nutrition_ajax.php?type=create_meal&m_index=' + param + '&r=' + getRandStr(10) + plan_str;
        b_xml.request(a_href);

        var c_width = 500;
        var c_height = 300;

        c_width = c_width + 'px';
        c_height = c_height + 'px';

        $.colorbox({inline: true, width: c_width, height: c_height, href:'#nutr_interface', onCleanup: function( ){$("#fs_container").trigger('fs_refresh') } } );
        break;

    case 'act_group_create_from_index':
        plan_str = '';
        if($('#act_plan_id').length > 0){
            plan_id = $('#act_plan_id').html( ).replace(/[^\d]/, '');
            plan_str = '&plan_id=' + escape(plan_id);
        }

        var a_href = './nutrition_ajax.php?type=create_act_group&act_index=' + param + '&r=' + getRandStr(10) + plan_str;
        b_xml.request(a_href);

        var c_width = 500;
        var c_height = 300;

        c_width = c_width + 'px';
        c_height = c_height + 'px';

        $.colorbox({inline: true, width: c_width, height: c_height, href:'#nutr_interface', onCleanup: function( ){$("#act_s_container").trigger('act_refresh') } } );
        break;

    case 'meal_edit':
        var a_href = './nutrition_ajax.php?type=edit_meal&meal_id=' + param + '&r=' + getRandStr(10);
        b_xml.request(a_href);

        var c_width = 1000;
        var c_height = 800;

        var avail_width = document.body.clientWidth && document.body.clientWidth > 0 ? document.body.clientWidth : document.body.offsetWidth;
        var avail_height = document.body.clientHeight && document.body.clientHeight > 0 ? document.body.clientHeight : document.body.offsetHeight;

        if(avail_width - 20 < c_width){
            c_width = avail_width - 20;
        }
        if(avail_height - 20 < c_height){
            c_height = avail_height - 20;
        }

        c_width = c_width + 'px';
        c_height = c_height + 'px';

        $.colorbox({inline: true, width: c_width, height: c_height, href:'#nutr_interface', onCleanup: function( ){$("#fs_container").trigger('fs_refresh') } });
        break;

    case 'group_edit':
        var a_href = './nutrition_ajax.php?type=edit_group&group_id=' + param + '&r=' + getRandStr(10);
        b_xml.request(a_href);

        var c_width = 1000;
        var c_height = 800;

        var avail_width = document.body.clientWidth && document.body.clientWidth > 0 ? document.body.clientWidth : document.body.offsetWidth;
        var avail_height = document.body.clientHeight && document.body.clientHeight > 0 ? document.body.clientHeight : document.body.offsetHeight;

        if(avail_width - 20 < c_width){
            c_width = avail_width - 20;
        }
        if(avail_height - 20 < c_height){
            c_height = avail_height - 20;
        }

        c_width = c_width + 'px';
        c_height = c_height + 'px';

        $.colorbox({inline: true, width: c_width, height: c_height, href:'#nutr_interface', onCleanup: function( ){$("#act_s_container").trigger('act_refresh') } } );

        break;

    case 'recipe_info':
        var a_href = './nutrition_ajax.php?type=recipe_info&nutr=' + param + '&r=' + getRandStr(10);
        b_xml.request(a_href);
        $.colorbox({inline: true, width: "900px", height: "600px", href:'#nutr_interface'});
        skip_accordion_init = true;
        break;

    case 'nutr_info':
        var a_href = './nutrition_ajax.php?type=nutr_info&nutr=' + param + '&r=' + getRandStr(10);
        b_xml.request(a_href);
        $.colorbox({inline: true, width: "300px", height: "500px", href:'#nutr_interface'});
        skip_accordion_init = true;
        break;

    case 'mp_populate':
        var day_index = escape($("#mp_day_index").html( ));
        var a_href = './nutrition_ajax.php?type=mp_populate_form&mp_day_index=' + day_index + '&r=' + getRandStr(10);
        b_xml.request(a_href);
        $.colorbox({inline: true, width: "600px", height: "450px", href:'#nutr_interface'});
        skip_accordion_init = true;

        break;

    case 'act_details':
        if(b_xml.isCurrentRequest){ return false; }
        var a_href = './nutrition_ajax.php?type=act_details&act_id=' + param + '&rand=' + getRandStr(10);
        b_xml.request(a_href);

        $.colorbox({inline: true, width: "680px", height: "550px", href:'#nutr_interface'});
        skip_accordion_init = true;

        break;

    case 'edit_mp_item':
        var day_index = escape($("#mp_day_index").html( ));

        //var a_href = './nutrition_ajax.php?type=edit_mp_item&item_id=' + param + '&mp_day_index=' + day_index + '&r=' + getRandStr(10);;
        //$.colorbox({inline: true, width: '500px', height: '300px', href:'#nutr_interface', onCleanup: function( ){$("#fs_container").trigger('fs_refresh') } } );

        $.colorbox({
            width: '500px',
            height: '300px',
            iframe: true,
            href: './lb/mp_edit_item.php?mp_item_id=' + param + '&mp_day_index=' + day_index,
            onCleanup: function( ){
                b_xml.request('./nutrition_ajax.php?type=update_mp&mp_day_index=' + day_index + '&r=' + getRandStr(10));
                skip_accordion_init = false;
            }
        });

        break;

    case 'edit_act_item':
        var day_index = escape($("#act_day_index").html( ));

        //var a_href = './nutrition_ajax.php?type=edit_mp_item&item_id=' + param + '&mp_day_index=' + day_index + '&r=' + getRandStr(10);;
        //$.colorbox({inline: true, width: '500px', height: '300px', href:'#nutr_interface', onCleanup: function( ){$("#fs_container").trigger('fs_refresh') } } );

        $.colorbox({
            width: '500px',
            height: '300px',
            iframe: true,
            href: './lb/act_edit_item.php?act_item_id=' + param + '&act_day_index=' + day_index,
            onCleanup: function( ){
                b_xml.request('./nutrition_ajax.php?type=update_act&act_day_index=' + day_index + '&r=' + getRandStr(10));
            }
        });

        break;

    default:
        return;
    }

}

function display_nutr_interface( ){

}

function nutrition_interface_close( ){
    var nutr_interface = document.getElementById('nutr_interface');
    //hide lightbox (figure it out).
    //delete contents from nutrition_interface
    nutr_interface.innerHTML = '';
}




/* move this section to primary script */

function wlt_submit( ){

    var wlt_form = document.getElementById('wlt_form');

    var inputs = wlt_form.getElementsByTagName('input');

    var selects = wlt_form.getElementsByTagName('select');

    var sub_url = './ajax.php?type=wlt_submit';

    for(var i = 0; i < inputs.length; i++){

        var input = inputs[i];

        var i_type = input.type;
        var i_name = input.name;
        var i_val = escape(input.value);

        if(i_type == 'radio' || i_type == 'checkbox' ){
            if(input.checked){
                sub_url += '&' + i_name + '=' + i_val;
            }
        }
        else{
            sub_url += '&' + i_name + '=' + i_val;
        }

    }


    for(var i = 0; i < selects.length; i++){
        var sel = selects[i];
        var i_name = sel.name;
        var i_val = sel.options[sel.selectedIndex].value;
        if(i_val && i_val != ''){
            sub_url += '&' + i_name + '=' + i_val;
        }
    }


    //alert(sub_url);


    return false;


}


/* end move this to primary section */



/* activity related functionality */

function init_activity_search(act_prefix){
    //just share this same div between the two search sub-systems, it's only for lightboxes
    nutr_interface = document.getElementById('nutr_interface');
    if(!nutr_interface){
        var nutr_interface = document.createElement('div');
        nutr_interface.id = 'nutr_interface';
        document.body.appendChild(nutr_interface);
    }

    var act_container = document.getElementById(act_prefix + '_container');
    if(!act_container){ return; }

    act_container.act_prefix = act_prefix;
    $('#' + act_container.id).unbind('act_refresh').bind('act_refresh', act_apply_results);

    var act_main_nav = document.getElementById(act_prefix + '_main_nav');
    var act_search_form = document.getElementById(act_prefix + '_search_form');
    var act_search = document.getElementById(act_prefix + '_search');
    var act_search_var = document.getElementById(act_prefix + '_search_var');
    var act_search_button = document.getElementById(act_prefix + '_search_button');

    act_search_form.act_prefix = act_prefix;
    act_search_form.onsubmit = act_apply_results;

    var links = act_main_nav.getElementsByTagName('a');
    for(var i = 0; i < links.length; i++){
        links[i].act_prefix = act_prefix;
        links[i].onclick = function( ){
            if(this.className == 'act_nav_a_active' || b_xml.isCurrentRequest){ return false; }

            var act_main_nav = document.getElementById(this.act_prefix + '_main_nav');

            var p_links = act_main_nav.getElementsByTagName('a');
            var cur_tab = 0;
            for(var j = 0; j < p_links.length; j++){
                if(p_links.id != this.id && p_links[j].className == 'act_nav_a_active'){
                    var cur_tab = p_links[j].rel;
                }
                if(p_links.id != this.id){p_links[j].className = 'act_nav_a';}
            }
            this.className = 'act_s_nav_a_active';
            var day_index = escape($("#act_day_index").html( ));

            var a_href = './nutrition_ajax.php?type=act_nav&act_prefix=' + this.act_prefix + '&act_tab=' + this.rel + '&search_var=' + escape(act_search_var.value) + '&day_index=' + day_index + '&rand=' + getRandStr(10);

            //alert(a_href);
            b_xml.request(a_href);

            return false;
        }
    }

    init_act_results(act_prefix);
}

function init_act_results(act_prefix){
    var act_contain = document.getElementById(act_prefix + '_container');

    if(!act_contain){ return; }

    $(".act_item_block").draggable({
        revert: true,
        revertDuration: 1,
        opacity: .8,
        helper: "clone",
        //handle: ".act_item_drag",
        zIndex: 20000,
        cursor: 'move',
        cursorAt: {right: -1}
    });

    $( "#activity_plan_interface .act_drop_zone" ).droppable({
        accept: "#activity_plan_interface .act_item_block",
        greedy: true,
        tolerance: 'pointer',
        activeClass: "act_drop_zone_active",
        hoverClass: "act_drop_zone_hover",
        drop: function( event, ui ) {
            $(".act_drop_zone").removeClass('act_drop_zone_active');
            $(".act_drop_zone").removeClass('act_drop_zone_hover');
            var drop_id = ui.draggable.context.id;
            var act_item_str = drop_id.replace(/^[^\d]+/, '');
            var plan_id = escape($("#act_plan_id").html( ));
            var day_index = escape($("#act_day_index").html( ));
            if(b_xml.isCurrentRequest){ return false; }
            var a_href = './nutrition_ajax.php?type=act_item_add&plan_id=' + plan_id + '&act_day_index=' + day_index + '&act_item_str=' + act_item_str + '&rand=' + getRandStr(10);
            b_xml.request(a_href);
        }
    });

    var a_links = act_contain.getElementsByTagName('a');
    var i = 0;

    for(i = 0; i < a_links.length; i++){
        var a = a_links[i];
        var rel = a.rel;
        var cname = a.className;

        switch(cname){
        case 'act_fav_add':
            a.act_prefix = act_prefix;
            a.onclick = function( ){
                if(b_xml.isCurrentRequest){ return false; }
                var a_href = './nutrition_ajax.php?type=act_fav_add&act_prefix=' + this.act_prefix + '&fav_str=' + this.rel + '&rand=' + getRandStr(10);
                b_xml.request(a_href);
                $(this).replaceWith('<img src="/images/meal_plan_item_saved.jpg" alt="Saved" />');
                this.className = 'fav_added';
                return false;
            }
            break;

        case 'act_fav_del':
            a.act_prefix = act_prefix;
            a.onclick = function( ){
                if(b_xml.isCurrentRequest){ return false; }
                var a_href = './nutrition_ajax.php?type=act_fav_del&act_prefix=' + this.act_prefix + '&fav_str=' + this.rel + '&rand=' + getRandStr(10);
                b_xml.request(a_href);
                //$(this).replaceWith('Item Removed');
                //this.className = 'fav_removed';
                window.setTimeout(act_apply_results, 200);
                return false;
            }
            break;

        case 'act_s_res_prev_active':
        case 'act_s_res_next_active':
            a.act_prefix = act_prefix;
            a.onclick = act_apply_results;
            break;

        case 'act_s_res_prev_inactive':
        case 'act_s_res_next_inactive':
            a.onclick = function( ){ return false; }
            break;

        case 'act_details_group':
            a.onclick = function( ){
                var day_index = escape($("#act_day_index").html( ));
                b_xml.request('./nutrition_ajax.php?type=act_group_details&group_id=' + this.rel + '&day_index=' + day_index + '&r=' + getRandStr(10));
                $.colorbox({inline: true, width: '500px', height: '300px', href:'#nutr_interface' } );
                skip_accordion_init = true;
                return false;
            }
            break;

        case 'act_delete_group':
            a.onclick = function( ){
                if(confirm('Are you sure you want to delete this activity plan?  Existing activity plans will be unaffected.')){
                    b_xml.request('./nutrition_ajax.php?type=delete_activity_plan&group_id=' + this.rel + '&r=' + getRandStr(10));
                    window.setTimeout(act_apply_results, 200);
                }

                return false;
            }
            break;

        default:
            break;
        }
    }

}

function act_apply_results( ){
    if(!this.act_prefix){
        this.act_prefix = 'act_s';
    }

    var act_contain = document.getElementById(this.act_prefix + '_container');
    var act_search_var = document.getElementById(this.act_prefix + '_search_var');

    var db_page_num = 0;
    if(this.className == 'act_s_res_prev_active' || this.className == 'act_s_res_next_active'){ db_page_num = this.rel; }

    var a_links = act_contain.getElementsByTagName('a');

    var act_main = $('.act_s_nav_a_active').first( ).attr('rel');
    var act_fav = 0;
    var act_mp = 0;

    for(var i = 0; i < a_links.length; i++){
        var a = a_links[i];
        var rel = a.rel;
        var cname = a.className;

        switch(cname){
        case 'act_s_nav_a_active':
            act_main = rel;
            break;

        default:
            break;
        }
    }

    var day_index = escape($("#act_day_index").html( ));

    b_xml.isCurrentRequest = false;
    var act_href = './nutrition_ajax.php?type=act_nav&act_prefix=' + this.act_prefix + '&act_tab=' + act_main + '&search_var=' + escape(act_search_var.value) + '&db_page_num=' + db_page_num + '&day_index=' + day_index + '&rand=' + getRandStr(10);
    b_xml.request(act_href);
    return false;
}

function act_day_nav_change( ){
    var plan_id = escape($("#act_plan_id").html( ));
    var day_index = this.rel
    if(b_xml.isCurrentRequest){ return false; }

    var a_href = './nutrition_ajax.php?type=act_day_nav_change&plan_id=' + plan_id + '&act_day_index=' + day_index + '&rand=' + getRandStr(10);
    b_xml.request(a_href);

    $('.act_day_nav_a').removeClass('act_day_nav_a_active');
    $(this).addClass('act_day_nav_a_active');

    return false;
}
function act_day_nav_change2(day_index){
    var plan_id = escape($("#act_plan_id").html( ));
    if(b_xml.isCurrentRequest){ return false; }
    var a_href = './nutrition_ajax.php?type=act_day_nav_change&plan_id=' + plan_id + '&act_day_index=' + day_index + '&rand=' + getRandStr(10);
    b_xml.request(a_href);
    return false;
}


function update_act_item( ){
    var plan_id = escape($("#act_plan_id").html( ));
    var day_index = escape($("#act_day_index").html( ));

    var act_item_id = this.rel;
    var act_qty = document.getElementById('act_qty_' + act_item_id);
    if(act_qty){ act_qty = escape(act_qty.value); }
    else{ act_qty = ''; }

    var a_href = './nutrition_ajax.php?type=act_item_update&plan_id=' + plan_id + '&act_day_index=' + day_index + '&act_item_id=' + act_item_id + '&act_qty=' + act_qty + '&rand=' + getRandStr(10);
    b_xml.request(a_href);
    return false;
}

function delete_act_item( ){
    //if(confirm("Are you sure you want to delete this activity plan item?")){
        var plan_id = escape($("#act_plan_id").html( ));
        var day_index = escape($("#act_day_index").html( ));
        var a_href = './nutrition_ajax.php?type=act_item_delete&plan_id=' + plan_id + '&act_day_index=' + day_index + '&act_item_id=' + this.rel + '&rand=' + getRandStr(10);
        b_xml.request(a_href);
    //}

    return false;
}

function approve_act_item( ){
    var plan_id = escape($("#act_plan_id").html( ));
    var day_index = escape($("#act_day_index").html( ));

    var act_item_id = this.rel;

    var a_href = './nutrition_ajax.php?type=act_item_approve&plan_id=' + plan_id + '&act_day_index=' + day_index + '&act_item_id=' + act_item_id + '&rand=' + getRandStr(10);
    b_xml.request(a_href);
    return false;
}

function update_act_steps( ){
    if($('#manual_steps_loaded').length > 0 || confirm('Entering steps manually will disable any future automatic step updates to this day from Achieve-Life pedometers. Click OK to continue.')){
        var day_index = escape($("#act_day_index").html( ));

        var num_steps = $('#act_steps').val( );

        var a_href = './nutrition_ajax.php?type=act_update_steps&act_day_index=' + day_index + '&num_steps=' + num_steps + '&rand=' + getRandStr(10);

        b_xml.request(a_href);
    }

    return false;
}

var skip_accordion_init = false;
var mp_accordion_init = false;
var opened_tabs = [];
function init_meal_plan_accordion( ){
    if(mp_accordion_init && (skip_accordion_init || $('#mp_error').length > 0)){
        skip_accordion_init = false;
        return;
    }

    if($('#meal_plan_interface').length > 0){
        $('#mp_main_contain')
        .addClass("ui-accordion ui-widget ui-helper-reset ui-accordion-icons")
        .find('h4')
            .addClass("ui-accordion-header ui-helper-reset ui-corner-top ui-state-default")
            .prepend('<span class="ui-icon ui-icon-triangle-1-e"/>')
        .unbind('click')
        .click(function( ) {
            handleAccordionClick(this);
            return false;
        })
        .unbind('mouseenter')
        .mouseenter(function( ){
            if(!$(this).hasClass('ui-accordion-header-active') && food_item_dragging){
                handleAccordionClick(this);
            }
        })
        .next( )
            .removeClass("ui-accordion-content ui-helper-reset")
            .addClass("ui-accordion-content ui-helper-reset")
            .hide( )
        ;

        if(mp_accordion_init){
            $('#mp_main_contain h4').each(function(index){
                if($.inArray(index, opened_tabs) < 0){
                    return true;
                }

                $(this)
                    .toggleClass("ui-accordion-header-active")
                    .toggleClass("ui-state-active")
                    .toggleClass("ui-state-default")
                    .find("> .ui-icon")
                        .toggleClass("ui-icon-triangle-1-e")
                        .toggleClass("ui-icon-triangle-1-s")
                    .end( )
                    .next( )
                        .toggle( )
                        .toggleClass("ui-accordion-content-active")
                    .parent( )
                        .children('.save_this_meal,.meal_head_calorie_count')
                            .toggle( );
                    ;
            });

            init_meal_plan_cufon( );

            //$('#mp_main').animate({scrollTop:mp_main_scroll_top}, 1200); //animated (cool) but annoying
            $('#mp_main').scrollTop(mp_main_scroll_top);
        }
        else{
            $('#mp_main_contain h4').first( ).delay(2500).click( );
            mp_accordion_init = true;
        }
    }
}

function handleAccordionClick(obj){
    t_index = $('#mp_main_contain h4').index(obj);
    if($.inArray(t_index, opened_tabs) > -1){
        //it's a max 4, not a big deal
        for(i = 0; i < opened_tabs.length; i++){
            val = opened_tabs[i];
            if(t_index == val){
                opened_tabs.remove(i);
                break;
            }
        }
    }
    else{
        opened_tabs.push(t_index);
    }


    $(obj)
        .toggleClass("ui-accordion-header-active")
        .toggleClass("ui-state-active")
        .toggleClass("ui-state-default")
        .find("> .ui-icon")
            .toggleClass("ui-icon-triangle-1-e")
            .toggleClass("ui-icon-triangle-1-s")
        .end( )
        .next( )
            .slideToggle( )
            .toggleClass("ui-accordion-content-active")
        .parent( )
            .children('.save_this_meal,.meal_head_calorie_count')
                .toggle( );
        ;
}

function init_meal_plan_cufon( ){
    if(window.load_cufon){
        Cufon.replace('.mp_body_container h4',{
            fontFamily: 'mpc',
            color: '#ffffff',
            textTransform: 'uppercase',
            fontSize: '24px',
            fontWeight: 'normal'
        });

        Cufon.replace('#fs_main_nav a',{
            fontFamily: 'mpc',
            textTransform: 'uppercase',
            fontSize: '16px'
        });

        Cufon.replace('#mp_stats_tabs table td a,.mp_plan_date',{
            fontFamily: 'league',
            fontSize: '30px'
        });

        Cufon.replace('#mp_progress_caption',{
            fontFamily: 'mpc',
            fontSize: '16px'
        });

        Cufon.replace('#mp_cal_progress_text',{
            fontFamily: 'league',
            fontSize: '20px',
            textShadow: '-1px -1px 0 #939297,1px -1px 0 #939297,-1px 1px 0 #939297,1px 1px 0 #939297;'
        });

        Cufon.replace('.mp_meal_calories strong',{
            fontFamily: 'pl'
        });

        Cufon.replace('.meal_head_calorie_count',{
            fontFamily: 'mpc',
            fontSize: '18px'
        });

        Cufon.replace('.meal_head_calorie_count strong',{
            fontFamily: 'pl',
            fontSize: '20px'
        });
    }
}

function edit_custom_item( ){
    last_obj = false;
    $('.mp_edit_item').each(function( ){
        if(!last_obj || $(last_obj).length == 0){
            last_obj = $(this);
            return true;
        }

        if($(this).attr('rel') > $(last_obj).attr('rel')){
            last_obj = $(this);
        }
    });

    if(last_obj && $(last_obj).length > 0){
        $(last_obj).trigger('click');
    }
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};
