
my_console = {
    log: function(thing){
        if(window.console){
            console.log(arguments);
        }
    }
}

search = {
    basic_storage_model: function(options){
        new_object = {on:[],off:[]};
        new_object.display_area = options.display_area || 'search_facets';
        new_object.display_name = options.display_name || 'None';
        new_object.display_function = options.display_function || "standard_display";
        
         
        return new_object;  
    },
    page_by: 30,
    storage: {},
    scrollTop: 0,
    returned: 0,
    count: 0,
    settings: { append_to: "narrow_recipe" },
    add_item: function(type,item ) {
        item = jQuery.trim(item);
        my_console.log(type);
        my_console.log(this.storage);
        this.storage[type].on.push(item);
        this.storage[type].on = jQuery.unique(this.storage[type].on);
        this.storage[type].off = jQuery.unique(this.storage[type].off);
    },
    remove_item: function(type,item){
        item = jQuery.trim(item);
        A = this.storage[type].on.indexOf(item);
        B = this.storage[type].off.indexOf(item);
        my_console.log(A,B);
        if( A > -1 && B == -1){
            this.storage[type].on.splice(A,1 );
            this.storage[type].off.push(item);
        }else if( A > -1 && B > -1){
            this.storage[type].on.splice(A,1 );
        }
        an_object = JSON.stringify(search.storage);
        $.cookie("search_storage", an_object, { path: '/', expires: 10 });
        this.display();
        this.getRecipeList();
        search.returned = 0;
        search.count = 0;
    },
    search_toggle: function(type,key,el){
        on = this.storage[type]["on"];
        my_console.log($.inArray(key,on) );
        if ( $.inArray(key,on) > -1){
            var one_name = "on";
            var two_name = "off";
        } else {
            var one_name = "off";
            var two_name = "on";   
        }
        one = this.storage[type][one_name];
        one.splice($.inArray(one,key),1 );
        this.storage[type][one_name] = one;
        two = this.storage[type][two_name];
        two.push(key);
        this.storage[type][two_name] = two; 
        search.returned = 0;
        search.count = 0;
        this.display();
        this.getRecipeList();
    },
    displays: {},
    put_html: {},
    display_functions: { 
        standard_display: function(type,item_name,the_class) {
            text = "";
            text += "<a href=\"javascript:search.search_toggle('"+type+"','"+item_name+"');\">";
            if(the_class == "on"){
                text += "<img src='"+media_url+"/site_image/minus.gif'></img>";
            } else {
                text += "<img src='"+media_url+"/site_image/plus.gif'></img>";
            }
            text += "<span>"+item_name+"</span></a>";
            return text;
        },
        ingredient: function(type,item_name,the_class){
            text = "";
            text += "<a href=\"javascript:search.remove_item('"+type+"','"+item_name+"');\">";
            if(the_class == "on"){
                text += "<img src=\""+media_url+"/site_image/minus.gif\"></img>";
            } else {
                text += "<img src=\""+media_url+"/site_image/plus.gif\"></img>";
            }
            text += "<span>"+item_name+"</span></a>";
            return text;
        }
         
    },
    display: function (){
        /* All Filters Should be have in the same way. 
        
        <ul class="filter filter-list-top">
            <h3> Super Title </h3>
            <li class="filter-sub-list">
                <h4> Sub Title</h4> # if Sub-title thir could be no sub title
                <ul class="on"> # Sub List on 
                    <li> <a href="#"> action cick </a> Name of filter </li>
                    <li> <a href="#"> action cick </a> Name of filter </li>
                    <li> <a href="#"> action cick </a> Name of filter </li>
                    ...
                </ul>
                <ul class="off">
                    <li> <a href="#"> action cick </a> Name of filter </li>
                    ...
                </ul>
            </li>
            <li class="filter-sub-list">
                <h4> Sub Title Two</h4> # if Sub-title thir could be no sub title
                <ul class="on"> # Sub List on 
                    <li> <a href="#"> action cick </a> Name of filter </li>
                    <li> <a href="#"> action cick </a> Name of filter </li>
                    <li> <a href="#"> action cick </a> Name of filter </li>
                    ...
                </ul>
                <ul class="off">
                    <li> <a href="#"> action cick </a> Name of filter </li>
                    ...
                </ul>
            </li>
            .... 
        </ul>       
        */
        
        for(name in this.displays){
            this.displays[name].html = "";
            this.displays[name].html += "<ul class=\"filter filter-list-top\">";
            if(this.displays[name].title != ""){
                this.displays[name].html += "<h3>"+this.displays[name].title+"</h3>";
            }
            
        }
        for( name in this.storage){
            if(this.storage[name].on.length <= 0 &&  this.storage[name].off.length <= 0 ){ continue;}
            this.storage[name]["on"].sort();
            this.storage[name]["off"].sort();
            
            search.put_html = this.displays[this.storage[name].display_area].html;
            search.put_html += "<li class=\"filter-sub-list\">";
            if(this.storage[name].display_name !== "None"){
                search.put_html += "<h4>"+ this.storage[name].display_name +"</h4>";
            }
            on_off = ["on","off"];
            /*
            for (var x = 1; x <= 10; x++)
               {
               msg = msg + x + "\n";
               }
            */
            for(i = 0; i < on_off.length;i +=1){
                b = on_off[i];
                if(search.storage[name][b].length > 0){
                    search.put_html += "<ul class=\""+b+"\">";
                    for(x=0;x < search.storage[name][b].length; x += 1){
                        d = search.storage[name][b][x];
                        stuff = search.display_functions[search.storage[name].display_function](name,d,b);
                        search.put_html +=  "<li>"+stuff+"</li>";
                    }
                    search.put_html += "</ul>";
                    
                }
                
            }
            search.put_html += "</li>";
            this.displays[this.storage[name].display_area].html = search.put_html;
            search.put_html = "";
        }
        for(name in this.displays){
            this.displays[name].html += "</ul>";
            id = "#"+name;
            $(id).show().empty().html(this.displays[name].html);
        }
    },
    getNarrowSearchList: function(){
        get_string = "";
        $.postJSON(
            "/json/recipes/facets/", 
            { search: JSON.stringify(this.storage) },
            function(data){
                if(!data){ return false;}
                $.each(search.storage["ingredients"]["on"], function(i,val){
                    if(!$.inArray(data["ingredients"]["on"],val) ){
                        data["ingredients"]["on"].push(val);
                    }
                } );
                $.each(search.storage["ingredients"]["off"], function(i,val){
                    if(!$.inArray(data["ingredients"]["off"],val) ){
                        data["ingredients"]["off"].push(val);
                    }
                } );
                my_console.log(data);
                //search.storage = {};
                search.storage["filters"] = data["filters"];

                search.display();
                
            }
        );
    },
    getting: false,
    lastRecipeItem: "",
    getDisplayRecipeList:function(start,how_many){
        if(!(how_many)) how_many = search.page_by;
        $.postJSON(
            "/json/recipes/"+start+"/"+how_many+"/",
            { search: JSON.stringify(this.storage) },
            function(data){
                search.getDisplayMessage(data);
                my_console.log(data.recipes);
                search.getNarrowSearchList();
			    if(data.recipes === undefined){ 
			        $("#recipe_display").scrollTop();
			        search.returned = 0;
			        search.count = 0;
			        search.scrollTop = $("#recipe_display").scrollTop();
			        $("#search_display_message").empty();
			        $("#search_display").empty().html("<div class=\"error\"><h2>No Results</h2><h3>Try adding,or removing ingrdients.</h3></div>").show();
			        
			        search.display();
			        return false; 
			    }
		        $.each(
		            data.recipes, 
		            function(i,item){
		                if( (item.number_of_ingrdients - item.tags.length) > 0 ){
					        extra_info = ", plus " +(item.number_of_ingrdients - item.tags.length) + " more ingredient ";
					    } else {
					        extra_info = "";
					    }
					    li_thinh  = item.rendered; 
					    $("#search_display").append(li_thinh);
		            }
		        );
		        /*
		        $(".recipe_item").unbind("hover").unbind("click");
                $(".recipe_item").hover(
                  function () {
                    $(this).css("background-color","#ccccff");
                    $(this).css("cursor","pointer");
                    
                    
                  }, 
                  function () {
                    $(this).css("background-color","#ffffff");
                    $(this).css("cursor","auto");
                    
                  }
                );
                $(".recipe_item").toggle(
                  function (e) {
                      my_console.log("One Click",this);
                      $(".recipe_item").find(".hidden").hide();
                      $(this).find(".hidden").show();
                      
                  }, 
                  function (e) {
                      my_console.log("Two Click",this)
                      $(this).find(".hidden").hide();
                  }
                );
                */
                search.lastRecipeItem = $(".recipe_item:last");

                search.returned += data.returned;
                search.getting = false;
            } 
        
        );
    },
    getDisplayMessage:function(data){
        if ( search.returned == 0){
           returned = search.returned = data.returned;
        } else if(search.returned > data.count ) {
            returned = search.returned = data.count;
        } else {
            returned = search.returned;
        }
        message = "<h3>We are showing you <b>"+returned+"</b> of <b>" +data.count+ "</b> recipes total.</h3>";
        search.count = data.count;
        $("#search_display_message").empty().html(message).show();

    },
    getRecipeList: function(){
        $("#search_display").empty();
        this.getDisplayRecipeList(start = 0,how_many=search.page_by);

    },
    standard_display : function (type,item_name) {
        return "<a class=\"filter_item\" href=\"javascript:search.search_toggle('"+type+"','"+item_name+"');\"><span>*</span><b>"+item_name+"</b></a>";
    }
};


function rebuild_storage(){
    storage_items = [ 
        [ 
            "ingredients" , 
            {
                display_name:"",
                display_area:"narrow_recipe",
                display_function:"ingredient"
            }  
        ],
        [ "filters", {display_name:""} ]
    ];
    my_console.log(storage_items.length);
    jQuery.each(storage_items, function(i, item){
        search.storage[item[0]] = search.basic_storage_model(item[1]);
    });
    search.displays["narrow_recipe"] = {};
    search.displays["search_facets"] = {};
    search.displays["narrow_recipe"].title = "";
    search.displays["search_facets"].title = "";
}
rebuild_storage();
$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};



function InputEmpty() {

    $("#tag_input").val("");
    $("#tag_input").unbind("focus");
    $("#search_display_message").hide("slow").empty();
    
}

$("#tag_input").bind("focus",InputEmpty);


function action(action,id){

    url = "/json/recipes/"+action+"/"+id+"/";
    $.get(url,function(){
        if(action == "made"){
            message = "Made It";
        } else if (action == "save"){
            message = "Saved It";
        }
        $("#"+action+"_action").empty().html("<b>"+message+"</b>");
    })
}

/*
fancy cleaning javascirpt
D = function(a) {
    return a.replace(/&([^;]+);/g,
    function(b, c) {
        switch (c) {
        case "amp":
            return "&";
        case "lt":
            return "<";
        case "gt":
            return ">";
        case "quot":
            return '"';
        default:
            if (c.charAt(0) == "#") {
                var d = Number("0" + c.substr(1));
                if (!isNaN(d)) return String.fromCharCode(d)
            }
            return b
        }
    })
}

*/

function AddActionClick(){
    my_console.log("inside AddActionClick", $("#tag_input").val(), search.storage["ingredients"]["on"]);
    if(!$("#tag_input").val()){
        $("#tag_input").val("");
        return false;
    }
    spaces_removed = $("#tag_input").val().replace(/ /g,"");
    my_console.log("spaces removed",spaces_removed);
    if(!spaces_removed){
        $("#tag_input").val("");
        return false;
    }
    my_console.log($("#tag_input").val(),search.storage["ingredients"]["on"] );
    if( jQuery.inArray( $("#tag_input").val() , search.storage["ingredients"]["on"] ) != -1 ){
        my_console.log(jQuery.inArray( $("#tag_input").val(), search.storage["ingredients"]["on"] ) );
        $("#tag_input").val("");
        return false;
    }
    new_tag = $("#tag_input").val();
    search.add_item("ingredients",new_tag);
    //search.storage[0].iter.push(new_tag);
    an_object = JSON.stringify(search.storage);
    $.cookie("search_storage", an_object, { path: '/', expires: 10 });
    $("#pantry_clear").show();
    search.display();
    search.getRecipeList();
    $("#tag_input").val("");
    
    
}
function restart(){
    rebuild_storage();
    $("#pantry_clear").hide();
    
    an_object = JSON.stringify(search.storage);
    $.cookie("search_storage", an_object, { path: '/', expires: 10 });
    search.display();
    search.getRecipeList();
}
$("#add_action").click( function(event){ event.preventDefault();AddActionClick();  } );
$("#search_by_keyword").submit(function(event){event.preventDefault();AddActionClick();})
$(function() { $("#tag_input").suggest("/json/tag/suggest/",{ resultsClass: 'ac_results span-8', onSelect: function() { AddActionClick(); } }); });
$('#search_display').scroll(function() {
    more_to_get = false;
    get_more = false;
    // Down
    if(!(search.scrollTop) ) {search.scrollTop = $("#search_display").scrollTop(); }
    old_scroll = search.scrollTop;
    new_scroll = $("#search_display").scrollTop();
    my_console.log( search.count ,search.returned ,search.page_by);
    
    if( (search.count - search.returned) >= search.page_by ){ 
        more_to_get = search.page_by;
        get_more = true;
    }else if( (search.count - search.retruned) >= 1){
        more_to_get = search.count - search.retruned;
        get_more = true;
    } else{
        get_more = false;
    }
    difference = (search.lastRecipeItem.offset().top + $("#search_display").offset().top) - new_scroll; 
    my_console.log(document.getElementById("search_display"));   
    left = (search.lastRecipeItem.offset().top + search.lastRecipeItem.outerHeight() );
    right = ($("#search_display").offset().top + $("#search_display").innerHeight() + (6*search.lastRecipeItem.outerHeight() ));
    
    my_console.log( get_more ,!(search.getting) , (left < right));
    
    if( get_more && !(search.getting) && (left < right) ){
        search.getting = true;
        search.getDisplayRecipeList(start=search.returned,how_many = more_to_get);
        search.scrollTop = new_scroll;
    }
});

if($.cookie("search_storage")){
    var myObject = eval('(' + $.cookie("search_storage") + ')');
    if (myObject["ingredients"]["on"].length > 0){
        $("#pantry_clear").show();
        $("#expand_shrink").show();
        
    }
        
    search.storage = myObject;
    search.display();
    search.getRecipeList();
    my_console.log(myObject);
} else {
    my_console.log("you don't have a cooke");
}