$(function(){
    var menu_objects;
    var movement_objects;
    var product_objects;
    
    var menu_chunks;
    var movement_chunks;
    var product_chunks;
    
    var menu_page = 1;
    
    function form_post(form, callback) {
        $form = $(form);
        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action') + '?flow_type=' + FLOW_TYPE,
            data: $form.serialize(),
            dataType: 'json',
            success: function(data){
                if (objectIsEmpty(data.objects)) {
                	$form.parent().parent().find('.error').css('display', 'block');
                } else {
                	$form.css('display', 'none');
                	$form.parent().parent().find('.go_label').toggle();
                }
                return callback(data);
            }
        });
        return false;
    }
    
    function menu_callback(data) {
        menu_objects = data.objects;
        $('#menu_list').empty();
        if (objectIsEmpty(data.objects)) {
            $("#menus-not-found").show();
        } else {
            $("#menus-found").show();
            $.each(data.objects, function(id, menu){
                $('<li/>').attr('id', 'menu-' + id).addClass('level' + menu.energy_level)
                          .append($('<img/>').addClass('photo').attr('src', menu.image),
                                  $('<div/>').text(menu.name)).appendTo('#menu_list');
            });
            menu_chunks = data.chunks;
            paginate(data, $('#menu_pagination'));
        }
    }

    function movement_callback(data) {
        movement_objects = data.objects;
        $('#movement_list').empty();
        $.each(data.objects, function(id, mov){
            $('<li/>').attr('id', 'energyfit-' + id).addClass('level' + mov.energy_level)
                      .append($('<img/>').addClass('photo').attr('src', mov.image),
                              $('<div/>').text(mov.name)).appendTo('#movement_list');
            
        });
        movement_chunks = data.chunks;
        paginate(data, $('#movement_pagination'));
    }
    
    function product_callback(data) {
        product_objects = data.objects;
        var products = $("#ingredient_dropdown");
        products.empty();
        $.each(data.objects, function(id, product){
            $('<li/>').attr('id', 'energyfit-' + id)
                      .addClass('level' + product.energy_level)
                      .text(product.name.toLowerCase()).appendTo(products);
        })
        product_chunks = data.chunks;
        select_product($('#ingredient_dropdown li:first'));

    }
   
    function select_movement(object, list, json_object) {
        var id = object.attr('id').split('-')[1];
        select_object(object, list, json_object, movement_chunks);
        //var energy_level = json_object[id].energy_level === null ? 0 : json_object[id].energy_level;
        //var duration_level = json_object[id].duration_level === null ? 0 : json_object[id].duration_level;
        //var intensity_level= json_object[id].intensity_level === null ? 0 : json_object[id].intensity_level;
        var cols = ['energy_level', 'duration_level', 'intensity_level'];
        var grid = $('.grid2');

        for (var i=0; i < cols.length; i++){
            // remove 'None' value 
            var level_value = json_object[id][cols[i]]=== null ? 0 : json_object[id][cols[i]];

            var src = grid.find('.'+cols[i]+' img').attr('src').
                replace(/\/\d*\.png/, '/'+ level_value + '.png');
        
            grid.find('.'+cols[i]+' img').
            attr({'src':src,'alt':level_value});

            var level = grid.find('.'+cols[i]).attr('class').replace(/\w+_level/,'').replace(' ','');
            grid.find('.'+cols[i]).
                removeClass(level).
                addClass('level'+level_value);
        } 
        return false;
    }

    function select_object(object, list, json_object, chunks) {
        var split_data = object.attr('id').split('-');
        var id = split_data[1];
        var object_info = list.parent().parent().parent().find('.guide');
        if (split_data[0] != 'energyfit') {
            build_table(object_info.find('.grid'), json_object[id]);
        }
        object_info.find('.picture img').attr('src', json_object[id].big_image);
        object_info.find('.guide-content').find('h2').html($('<a/>').attr('href', json_object[id].url)
                                                                .text(json_object[id].name))
                                                     .append($('<img />').attr('src', json_object[id].energy_image));
        object_info.find('.guide-content').find('p').html(chunks[json_object[id].energy_level])
        list.parent().parent().css('display', 'none');
        object_info.css('display', 'block');
        return false;
    }
    
    function select_product(object) {
        var id = object.attr('id').split('-')[1];
        $('#ingredient_dropdown_wrapper').parent().parent().find('.picture img').attr('src', product_objects[id].image);
        $('#ingredient_dropdown_wrapper #arrow').text(product_objects[id].name)
            .parent().attr('class', 'level' + product_objects[id].energy_level)
            .parent().parent().parent().find('p').html(product_chunks[product_objects[id].energy_level]);
        build_table($('#ingredient_details').find('.grid'), product_objects[id]);
        return false;
    }
    
    function paginate(object, element) {
        element.html($.map(object.pagination.pages,
            function(num){
                return num == menu_page ? '<a href="#" class="selected">'+num+'</a>' : '<a href="#">'+num+'</a>'
            }).join(' '));
    }
    
    function build_table(element, object) {
        var energy_level = object.energy_level === null ? 0 : object.energy_level;
        element.find('.energy_level img').attr('class', 'l' + energy_level)
                                         .attr('src', function(){
                                             return $(this).attr('src').replace(/\d*\.png/, energy_level + '.png')
                                          })
        var cols = ['sugar', 'vfats', 'fats', 'salt', 'fibres', 'cholestrol', 'carbon_footprint'];
        for (var i = 0; i < cols.length; i++) {
            var value = object[cols[i]] === null ? 0: object[cols[i]];
            element.find('.' + cols[i] +' img').attr('class', 'l' + value);

            // change icon for current energy level of element
            var img_name = '';
            if (value >= 0){
                img_name = 'icon_'+cols[i]+'.png';
            } else {
                img_name = 'icon_questionmark.png';
            }
            if (element.find('.' + cols[i] +' img').length > 0){
                element.find('.' + cols[i] +' img').attr('src',
                    element.find('.' + cols[i] +' img').attr('src').replace(/icon_(\w+)\.png/,img_name)
                );
            }
        }
    }
    
    function another_link(obj) {
        obj.parent().parent().css('display', 'none');
        obj.parent().parent().parent().find('.selector').css('display', 'block');
        return false;
    }
    
    $("#ingredient_dropdown_wrapper").hover(
        function(){
            $("#ingredient_dropdown").addClass('hover'); 
			$(".hover li:last").addClass("last");
        },
        function(){
            $("#ingredient_dropdown").removeClass('hover');
        }
    );
    
    $('#check_ingredients').click(function(){
        $('#product_go').submit();
        $('#ingredient_details').css('display', 'block');
        return false;
    });

    $("#menu_pagination").find('a').live('click', function(){
        if ($(this).hasClass('selected')) return false;
        menu_page = this.text;
        $('#product_page_id').val(this.text);
        $("#menu_go").submit();
        return false;
    })

    $("#movement_pagination").find('a').live('click', function(){
        if ($(this).hasClass('selected')) return false;
        menu_page = this.text;
        $('#movement_page_id').val(this.text);
        $("#movement_go").submit();
        return false;
    })
    
    $("#another_menu").click(function(){
        another_link($(this));
        $('#movements-containter').css('display', 'none');
        $('#ingredient_details').css('display', 'none');
        return false;
    });
    
    $("#another_movement").click(function(){return another_link($(this));});

    $("#menu_go").submit(function(){return form_post(this, menu_callback)});
    $("#movement_go").submit(function(){return form_post(this, movement_callback)});
    $("#product_go").submit(function(){return form_post(this, product_callback)});
    
    $("#menu_list").find('li').live('click', function menu_list_click(){
        
        var $this = $(this)
        var id = $this.attr('id').split('-')[1];
        //document.location.href = menu_objects[id].url;
        select_object($this, $("#menu_list"), menu_objects, menu_chunks);
        $("#menu_author").html(menu_objects[id].from);
        $("#menu_id").val(id);
        energy_level = menu_objects[id].energy_level
        // energylevel 0 is acceptable
        if (energy_level || energy_level === 0) {
            $('#energy_level').val(energy_level);
            $('#movements-containter').css('display', 'block');
        } else {
            $('#movements-containter').css('display', 'none');
        }
        $('#movement_go').submit();
    });
    $("#movement_list").find('li').live('click', function(){return select_movement($(this), $("#movement_list"), movement_objects)});
    $("#ingredient_dropdown").find('li').live('click', function(){ return select_product($(this))});
	
    $("#search_choices").find("input").click(function(){
        var active_choices = $("#search_choices").find("input:checked");
        categories = $.map(active_choices, function(el){ return el.name; }).join();
        if (active_choices.length == 5) {
            $("#id_category").val("all");
        }
        $("#id_category").val(categories);
        $('#options').children('li').removeClass('hidden');
        $('#selected_item').text(active_choices.length == 1 ? categories : "custom");
        if (active_choices.length == 1) $('#'+categories).addClass('hidden');
        $('#search_form').submit()
    })
})
