$(function() {
    if ($('#id_energy_level').attr('value') != '') { // show energy level after form submit
        var elevel = ($('#id_energy_level').attr('value') >= 4) ? "+" : $('#id_energy_level').attr('value');
        $('#selected_item').text(elevel);
    }
    $('#options-cookbook').children('li').click(function(){
        $('#options-cookbook').children('li').removeClass('hidden'); // show drop-down
        $('#id_energy_level').attr('value', $(this).attr('rel')); // set hidden input value
        $(this).addClass('hidden'); 
        $('#selected_item').text($(this).text());
        $('#options-cookbook').css('display', 'none');
        // apply energy level filter instantly after change (new behavior)
        $('#recipe-search').submit();
    });
    // recipe creation form, switching gram/portion
    $('#ingredient-in-portion').click(function(){
        $('.as-grams').hide();
        $('.as-portions').show();
    });
    $('#ingredient-in-gram').click(function(){
        $('.as-portions').hide();
        $('.as-grams').show();
    });
	$('.as-portions').hide();
    $('.as-grams').show();
        
    $("form.search #id_q").autocomplete("/cookbook/list-auto/", {
        delay: 10,
        minChars: 2,
        matchContains: 1,
        cacheLength: 0,
        formatItem: function (i) { return '<div style="float: left">'+i[0]+'</div>' },
        selectFirst: false,
        extraParams: {'energy_level': function(){ return $('#id_energy_level').val(); },
                      'course': function(){ return $('#id_course').children('[selected]').val(); },
                      'cuisine': function(){ return $('#id_cuisine').children('[selected]').val(); },
                      'cooktime': function(){ return $('#id_cooktime').children('[selected]').val(); } },
		width:606
    }).result(function(event, item) { location.href = item[1]; });

    // product autocomplete search params for reuse
    var product_search_params = {
        delay: 10,
        minChars: 2,
        matchContains: 1,
        cacheLength: 0,
        formatItem: function (i) { return '<div style="float: left">'+i[0]+'</div>' },
        selectFirst: false,
        extraParams: { 'category': 'product' },
		width:251};

    $("input.product,#product-name").autocomplete("/search/autocomplete/", product_search_params)
                        .result(function(event, item) { $(this).attr('value', item[0]); });


    // add recipe form dynamic fields
    function increment_formset_el(str) {
        return str.replace(/[0-9]+/, Number(str.match(/[0-9]+/)) + 1);
    }
    // increment formset fields row
    function add_field_for_recipe_form(fs_counter, last_row) {
        var formset_count = Number($(fs_counter).attr('value')) + 1;
        var cloned = $(last_row).clone(true).insertAfter($(last_row));
        $(cloned).find('input,select').each(function(i) {
            // clone element and set new name and id attributes for it
            $(this).attr('id', increment_formset_el($(this).attr('id')));
            $(this).attr('name', increment_formset_el($(this).attr('name')));
            $(this).attr('value', '');
        });
        $(fs_counter).attr('value', formset_count);
        return cloned;
    }
    // number of formsets for field incremention
    $('#add-ingredient-control').click(function() {
        var cloned = add_field_for_recipe_form('#id_product-TOTAL_FORMS', '.row.ingredient:last');
        console.log('Cloning product name field: '+ cloned);
        $(cloned).find('input.product').autocomplete("/search/autocomplete/", product_search_params)
                                        .result(function(event, item) { $(this).attr('value', item[0]); });
    });
    $('#add-fat-control').click(function() {
        add_field_for_recipe_form('#id_fat-TOTAL_FORMS', '.row.fat:last');
    });
    $('#add-step-control').click(function() {
        var cloned = add_field_for_recipe_form('#id_step-TOTAL_FORMS', '.row.step:last');
        var step = $(cloned).find('.small-label:first');
        step.text(increment_formset_el(step.text()));
    });
    
    // recipe page
    $('.ingridients.portion').hide(); // default show in gram
    $('.mesure input').click(function() { // switching between grams and portions
        if ($(this).val() == 'portion') {
            $('.ingridients.gram').hide();
            $('.ingridients.portion').show();
        }
        if ($(this).val() == 'gram') {
            $('.ingridients.portion').hide();
            $('.ingridients.gram').show();
        }
    });
    // check 'just commented status' from location url
    var comment_id = location.href.match(/c=[0-9]+$/);
    if (comment_id && comment_id.length) {
        comment_id = comment_id[0];
        location.href = location.href + '#' + comment_id.replace(/=/,'')
    };
    // add to shopping list control on recipe detail page
    $('#add-to-shopping-list').click(function() {
        $('#add-to-shopping-list-form').submit();
        return false;
    })
    // delete shopping list item via ajax post
    $('.delete-item-control').live('click', function() {
        var row = $(this).parent();
        $('#delete-shoplist-item').val($(this).attr('rel'));
        var del_data = $('#delete-shoplist').serialize();
        $.post($('#delete-shoplist').attr('action'), del_data,
                function(r) { if (r.success) $(row).slideUp(); },
                "json");
        return false;
    });
    // add new custom shopping list item
    $('#add-to-shoplist').submit(function(e) {
        e.preventDefault();
        var cur_row = $(this).parent();
        var add_data = $(this).serialize();
        $.post($(this).attr('action'), add_data, // send ajax to add new shopping list item
                function(r) {
                    if (!r.success) {console.log('Failed adding new shopping list item: '+ r); return 'error';}
                    // creating new item row
                    var new_row = $('#sl-template').clone();
                    new_row.find('strong').text(r.product_name);
                    new_row.find('a.delete-item-control').attr('rel', r.id);
                    new_row.find('input.item-value').attr({'value': r.value, 'id': 'amount-value-' + r.id});
                    cur_row.before(new_row); // add it to DOM
                    new_row.slideDown(); // show new row
                    // clear new item form and set focus
                    $('#product-name').val('');
                    $('#amount-value').val('');
                    $('#product-name').focus();
                }, "json");        
        return false;
    });
    // IE workaround for shopping list item submit
    if ($.browser.msie) {
        $('#amount-value,#product-name').keypress(function(e) {
            c = e.which ? e.which : e.keyCode;
            if (c == 13) $('#add-to-shoplist').submit();
        });
    };
    // delete all shopping list items
    $('#delete-all-items').click(function() {
        $('#delete-full-shoplist').submit();
        return false;
    });
    // run print dialog
    $('#print-shopping-list,#print-recipe').click(function() { print(); return false; });
    // upload recipe picture
    $('#upload-recipe-pict').jqm({modal:true});
    $('#upload-recipe-pict').prepend('<div id="close"><img src="' + media_url + 'images/bt-close.png"></div>');
    $('#upload-recipe-pict #close').click(function() {
        $('#upload-recipe-pict').jqmHide();
    });
    // show modal
    $('#show-recipe-pict-modal').click(function() {
        $('#upload-recipe-pict').jqm({modal:false, overlay:0});
        $('#upload-recipe-pict').jqmShow();
        return false;
    });
    // custom event from clicks.js
    // you may use 'ajax_click_sent' event to handle post-request actions on clicks
    // binding popup with clicks counter here
    $('a[id^="click_link"]').bind('ajax_click_sent', function(e, action) {
        var cur_count = Number($('#click-heart-count').text()); // cache current count of clicks
        if (action == 'added') { // show popup only if click added
            $('#click-heart-count').text(cur_count + 1); // increment click count
            $('#recipe-click-popup').jqm({modal:false, overlay:0});
            $('#recipe-click-popup').jqmShow();
            setTimeout(function() { // hide popup after timeout with fadeout effect and then popup destruction
                $('#recipe-click-popup').fadeOut(500, function() { $(this).jqmHide() });
            }, 600);
        }
        if (action == 'deleted') { // decrement of click count
            $('#click-heart-count').text(cur_count - 1);
        }
    });
    // reload recipe list on dropdown filter changes
    $('#recipe-search select').change(function() { $('#recipe-search').submit(); });
    // recipe deletion
    $('.recipe-del').click(function() {
        // set recipe id to confirmation link
        $('#recipe-confirmed-delete').attr('rel', $(this).attr('rel'));
        // show confirmation popup
        $('#recipe-delete-confirmation').jqm({modal:false, overlay:0});
        $('#recipe-delete-confirmation').jqmShow();
        return false;
    });
    // confirmation of recipe deletion
    $('#recipe-confirmed-delete').click(function() {
        var recipe_id = $(this).attr('rel'); // cached recipe id value
        // hiding confirmation popup after click
        $('#recipe-delete-confirmation').fadeOut(500, function() { $(this).jqmHide() });
        // sending ajax request for recipe deletion
        $.post(del_recipe_url, {'recipe_id': recipe_id},
                function(r) { 
                    if (r.success)
                        $('#recipe-' + recipe_id).fadeOut(600);
                }, "json");
        return false;
    });
    // don't confirm recipe deletion
    $('#no-recipe-delete').click(function() {
        $('#recipe-delete-confirmation').fadeOut(500, function() { $(this).jqmHide() });
    });
});
