// This file depends on yummly-search-ui.js

var values = {'ingredient':[{}, {}], 'diet':[{}, {}], 'allergy':[{}, {}], 'source' : [{}, {}], 'cuisine':[{}, {}], 'course':[{}, {}],  'technique' : [{}, {}]};
// 0 for excluded, 1 for included

var pagination = {'max':10, 'skip':0};

var currentState = {};
var updateHashComplete = false;

// main intialization handler
$(document).ready(  function() {
    
    $("form[action='/search/index']").submit(function(event){
        event.preventDefault();
        GA.trackPageview('/search/index');
        updateHash();
    });

    $('#closeInstructionsLink').live('click', function(event) {
        GA.trackPageview('/search/closeinstructions');
        $.closeInstructions();
    });

    // set up initial bindings and load search
    $(window).bind('hashchange', function(e) {
        prepareAndSubmitSearch();
    });
    
    // trigger initial hashchange
    //$(window).trigger('hashchange');
    //populateFormElements();
    
    // perform the initial search the first time the user visits the foodfinder page.
    prepareAndSubmitSearch();
});

function prepareAndSubmitSearch() {
    var newstate = $.bbq.getState();
    
    // This hack is required for chrome.. If this is not present chrome submits two requests for any action after you go to the foodfinder page with no query parameters.
    // It looks like unless there is a # in the url, chrome tries to make two requests.. The hack below prevents the second call.
    if (typeof newstate != 'undefined' && typeof newstate['q'] == 'undefined') {
        newstate['q'] = '';
    }
    
    if (isEmpty(currentState) ||  !objectsAreEqual(newstate, currentState)) {
        //console.log(newstate);
        currentState = newstate;

        if (typeof currentState['q'] != 'undefined' && currentState['q'] != '') {
            $('#q').val(currentState['q']);
        }
        else if ((currentState['q'] == undefined || currentState['q'] == '') && $('#q').val() != searchBoxHint) // Use the old searchvalue in case there is no new one
        {
            currentState['q'] = $('#q').val();
        }
        else {
            if ($('#q').val() != searchBoxHint) {
                currentState['q'] = $('#q').val();
            }
            else {
                currentState['q'] = '';
            }

        }
        
        // now perform the actual search
        $.submitSearch(currentState);
    }  
}

// calls the search api and writes to the page
$.submitSearch = function(data) {
    scrolltotop.scrollup();
    //console.log('submit search');
    var dataNew = {};
    $.each(data, function(key, o) {
        // //console.log(key);
        if ($.inArray(key, ["allowedIngredient", 
                            "allowedDiet", 
                            "allowedAllergy", 
                            "excludedIngredient", 
                            "allowedSource", 
                            "excludedSource", 
                            "allowedCuisine", 
                            "excludedCuisine", 
                            "allowedCourse", 
                            "excludedCourse", 
                            "allowedTechnique", 
                            "excludedTechnique"]) != -1) {
            dataNew[key] = undoSerialize(o);
        } else {
            dataNew[key] = o;
        }
    });

    var foodfinderRecipes = $('#foodfinderRecipes');
    $.nui.waitStart({content:'Updating Recipes...', object:$('.yummly-body')});

    $.ajax({
        data: dataNew,
        url: "/searchAPI/search.html",
        dataType: "json",
        timeout : 60000,
        complete: function(req, status) {
            updateHashComplete = true;
        },
        success: function(data) {

            var s = "";
            var totalMatchCount = data["totalMatchCount"];
            
            // populate the form elements to reflect the search query
            populateFormElements($.bbq.getState());
            
            $.nui.waitStop({
                object:$('.yummly-body'),
                onStop:function() {
                    $(foodfinderRecipes).html(data["html"]);

                    // this will render like buttons and so on
                    if (typeof FB === 'object')
                        FB.XFBML.parse(document.getElementById($(foodfinderRecipes).attr('id')));
                }
            });
            
            if (typeof data['criteria']['maxResults'] != undefined) {
                pagination.max = data["criteria"]["maxResults"];
            } 
            pagination.skip = data["criteria"]["resultsToSkip"];

            $('#search_pagination').html("").pagination(totalMatchCount, {
                items_per_page: pagination.max,
                current_page: Math.round(pagination.skip / pagination.max),
                callback: function(new_index, jq) {
                    var currentState = $.bbq.getState();

                    if ( typeof currentState["restrictToMine"] != 'undefined' && currentState["restrictToMine"]) {
                        $('#recipeCountInfoSpan').html('Found ' + totalMatchCount.format('0,000') + ' recipes from your favorites.');
                    }
                    else if ( typeof currentState["restrictToUser"] != 'undefined' && currentState["restrictToUser"] != '') {
                        $('#recipeCountInfoSpan').html('Found ' + totalMatchCount.format('0,000') + ' recipes favorites from ' + currentState["restrictToUser"] + '\'s favorites.');
                    }
                    else {
                        if (isEmpty(currentState)) {
                            $('#recipeCountInfoSpan').html('Found ' + totalMatchCount.format('0,000') + ' recipes.');
                        }
                        else {
                            $('#recipeCountInfoSpan').html('Found ' + totalMatchCount.format('0,000') + ' recipes that meet your taste.');
                        }
                    }

                    
                    if ( new_index > 0 && typeof currentState['start'] != undefined && (new_index * pagination.max) != currentState["start"]) {
                        currentState['start'] = new_index * pagination.max;
                        $.bbq.pushState(currentState, 2);
                    } else if (new_index == 0 && typeof currentState['start'] != undefined) {
                        delete currentState['start'];
                        $.bbq.pushState(currentState, 2);
                    }
                    return false;
                }
            });
            
            if (typeof data.criteria.stemmedTerms == 'object') {
                for (var i = 0; i < data.criteria.stemmedTerms.length; i ++)
                    GA.trackEvent('foodfinder', 'search', 'keyword', data.criteria.stemmedTerms[i]);
            }
            
        }
    });

    return false;
};

// hash maintenance functions

// tells the hash to update itself using the current state of the form
function updateHash() {
    if (!updateHashComplete) { // This is to prevent hash from getting updated when we update form fields based on the url data
        return;
    }
    
    updateHashComplete = false; // once we start updating a hash, we need to wait until the page renders before updating the hash again.

    var output = serialize();

    // if the state hasn't change, reset the flag and return
    // $.param.fragment seraizes the state object into a string
    if ($.param.fragment('', output) == $.param.fragment('', $.bbq.getState())) {
        updateHashComplete = true;
        return;
    }

    // A new search has occurred. Reset pagination
    pagination.skip = 0;

    $.bbq.pushState(output, 2);
}


