//<!-- begin variable declarations -->
/*
    THIS CODE IS KNOWN TO BE A HACK, CREATED AS A SERIES OF QUICK EXPERIMENTS.
    IT WAS BUILT IN A VERY PIECMEAL, HAPHAZARD, JUST-MAKE-SOMETHING-WORK KIND OF WAY.
    SO I RECOMMEND NOT LOOKING AT THE CODE. IN ANY CASE, YOU'VE BEEN WARNED. 
 */

 
//pads right
function fixed_width_str(s, length) {
	var str = s;
    var pad = " ";
    if (str.length > length) {
        str = substring(0,length)
    }
    else {
        while (str.length < length)
            str = str + pad;        
    }
    return str;
}


function make_fav_link (action, topic) {
    
    var link_class = "fav_add";
    var link_button = "<img src=\"fav_add_button.gif\" class=\"save_fav_button\"></img>";
    if (action == "remove") {
        link_class = "fav_remove";
        link_button = "<img src=\"fav_remove_button.gif\" class=\"remove_fav_button\"></img>"; 
    }
    
    link = '<a  title=\"Add to Faves list\" class=\"'+link_class+'\" href=\"javascript:\{update_faves(\'';
    link += action;
    link += '\',\'' + encodeURIComponent(topic.id);
    link += '\',\'' + encodeURIComponent(topic.name.replace(/\'/g, "\\\'"));
    link += '\',\'' + encodeURIComponent(topic.property.name);
    link += '\',\'' + encodeURIComponent(topic.property.day); // this is from topic so it includes year
    link += '\');\}\">'+link_button+'</a>';
    return link;
    
}


function sort_options(){

    var current_sortkey = get_dayhistory_args("sort").toLowerCase();
    var current_sortdir = current_sortkey.charAt(0) == "-" ? "" : "-";
    var sortdir = current_sortdir;
    current_sortkey = current_sortkey.charAt(0) == "-" ? current_sortkey.substring(1) : current_sortkey.substring(0);
    var sortkey = "";
    var sortbar = "";
    
    sortbar += "<table class='sortbar'>";
    sortbar += "<tr>";
    
    sortbar += "<td>";
    sortbar += "Sort by:"
    sortbar += "</td>";
    
    sortbar += "<td class='sort_item'>";
    sortkey = "rank";
    sortdir = current_sortdir;
    if ((current_sortkey != sortkey)) {
        sortdir = "-";
    }
    sortbar += "<a title='Reverse sort order' href='" + make_wb_url("set", {
        "sort": sortdir + sortkey,
        "pg": 1
    }) + "'>" + "Rank" + "</a>";
    sortbar += "</td>";
    
    sortbar += "<td class='sort_item'>";
    sortkey = "year";
    sortdir = current_sortdir;
    if ((current_sortkey != sortkey)) {
        sortdir = "";
    }
    sortbar += "<a href='" + make_wb_url("set", {
        "sort": sortdir + sortkey,
        "pg": 1
    }) + "'>" + "Year" + "</a>";
    sortbar += "</td>";
    
    sortbar += "<td class='sort_item'>";
    sortkey = "name";
    sortdir = current_sortdir;
    if ((current_sortkey != sortkey)) {
        sortdir = "";
    }
    sortbar += "<a title='Reverse sort order' href='" + make_wb_url("set", {
        "sort": sortdir + sortkey,
        "pg": 1
    }) + "'>" + "Name" + "</a>";
    sortbar += "</td>";
    
    sortbar += "</tr>";
    sortbar += "</table>";
    return sortbar;
    //        $(sortbar_id).html(sortbar);

}


function pagelinks(current_page, pagesize, total_topics){
    var paging_links = "";
    var link_start = "<a href='";
    var link_rollover = "' title='"; // end the href and start title
    var link_text_start = "'>";
    var link_end = "</a>";
    var first_topic = (((current_page - 1) * pagesize) + 1);
    var last_topic = (first_topic + pagesize) - 1;
    var previous_button = "<img class='paging_arrow' src='left_pg_arrow.gif'></img>";
    var next_button = "<img class='paging_arrow' src='right_pg_arrow.gif'></img>";
    var jump_dot = "<img class='jump_dot' src='jump_dot.gif'></img>";
    var total_pages = Math.ceil((total_topics) / pagesize);
    var page_jumpsize = 1;
    var max_page_jump = 5;
    var i = 0;
    current_page = parseInt(current_page) == NaN ? 1 : parseInt(current_page); // make sure it is an int
    if (last_topic > total_topics) {
        last_topic = total_topics;
    }
    
    paging_links += "<table class='topics_header'>";
    paging_links += "<tr>";
    
    paging_links += "<td>";
    paging_links += sort_options();
    paging_links += "</td>";
    
    paging_links += "<td>"; // wrap paging in a cell
    paging_links += "<table class='paging_table'>";
    paging_links += "<tr>";
    
    // first page
    paging_links += "<td class='pagelink_cell'>";
    if (current_page != 1) {
        paging_links += "<span>";
        paging_links += "" + link_start + make_wb_url("set", {
            "pg": 1
        }) + link_rollover+ "First page" + link_text_start;
        paging_links += "1" + link_end;
        paging_links += "</span>";
    }
    paging_links += "</td>";
    
    
    // page jumps backwards
    paging_links += "<td class='pagelink_cell'>";
    page_jumpsize = Math.floor((current_page) / 4);
    if ((page_jumpsize > 1) && (current_page - max_page_jump > 1)) {
        page_dotsize = 4;
        
        for (i = (page_jumpsize); i < current_page; i += page_jumpsize) {
            paging_links += "<span class='pg_jump" + page_dotsize + "'>";
            paging_links += "" + link_start + make_wb_url("set", {
                "pg": (i)
            }) + link_rollover+ "Jump to page "+ i + link_text_start;
            paging_links += "" + jump_dot + link_end;
            paging_links += "</span>";
            page_dotsize--;
        }
    }
    paging_links += "</td>";
    
    // previous page
    paging_links += "<td class='pagelink_cell'>";
    if (current_page > 1) {
        paging_links += link_start + make_wb_url("set", {
            "pg": (current_page - 1)
        }) + link_rollover+ "Previous page" + link_text_start;
        paging_links += previous_button + link_end;
    }
    paging_links += "</td>";
    
    // current page
    paging_links += "<td class='pagelink_cell'>";
    paging_links += "<div class='pg_current'>" + current_page + "</div>";
    paging_links += "</td>";
    
    // next page
    paging_links += "<td class='pagelink_cell'>";
    if (current_page < (total_pages)) {
        paging_links += "" + link_start + make_wb_url("set", {
            "pg": (current_page + 1)
        }) + link_rollover+ "Next page" + link_text_start;
        paging_links += "" + next_button + link_end;
    }
    paging_links += "</td>";
    
    
    // page jumps forward
    paging_links += "<td class='pagelink_cell'>";
    page_jumpsize = Math.floor((total_pages - current_page) / 4);
    if ((page_jumpsize > 1) && (current_page + max_page_jump < total_pages)) {
        page_dotsize = 1;
        
        for (i = (current_page + page_jumpsize); i < total_pages; i += page_jumpsize) {
            paging_links += "<span class='pg_jump" + page_dotsize + "'>";
            paging_links += "" + link_start + make_wb_url("set", {
                "pg": (i)
            }) + link_rollover+ "Jump to page " + i+ link_text_start;
            paging_links += "" + jump_dot + link_end;
            paging_links += "</span>";
            page_dotsize++;
        }
    }
    paging_links += "</td>";
    
    // last page
    paging_links += "<td class='pagelink_cell'>";
    if (current_page != total_pages) {
        paging_links += "<span>";
        paging_links += "" + link_start + make_wb_url("set", {
            "pg": total_pages
        }) + link_rollover+ "Last page" + link_text_start;
        paging_links += "" + total_pages + link_end;
        paging_links += "</span>";
    }
    paging_links += "&nbsp;&nbsp;pages";
    paging_links += "</td>";
    
    paging_links += "<td class='pagelink_cell'>";
    paging_links += "</td>";
    
    
    paging_links += "</tr>";
    paging_links += "</table>"; // paging
    paging_links += "</td>";
    paging_links += "</tr>";
    paging_links += "<table>";
    
    $(topic_paging_id).html(paging_links);
    $(footer_topic_paging_id).html(paging_links);
} // end pagelinks


function suggested_filters(filter_stats){
    var highlighted_filters = ""
    highlighted_filters += "<table class='best_filters'>";
    highlighted_filters += "";
    
    highlighted_filters += "<tr>";
    highlighted_filters += "<td class='filter_cell'>";
    highlighted_filters += "<a href='" +
    make_wb_url("set", {
        "property": "/people/person/date_of_birth",
        "types": "",
        "pg": 1,
        "domains": ""
    }) +
    "'>Birthdays</a>";
    highlighted_filters += "</td>";
    
    highlighted_filters += "<td class='filter_cell'>";
    highlighted_filters += "<a href='" +
    make_wb_url("set", {
        "property": "/people/person/date_of_birth",
        "types": "/film/actor,/tv/tv_actor",
        "pg": 1,
        "domains": ""
    }) +
    "'>Actors Birthdays</a>";
    highlighted_filters += "</td>";
        
    highlighted_filters += "</tr>";
    
    highlighted_filters += "<tr>";
    highlighted_filters += "<td class='filter_cell'>";
    highlighted_filters += "<a href='" +
    make_wb_url("set", {
        "property": "",
        "types": "/time/event",
        "pg": 1,
        "domains": ""
    }) +
    "'>Events</a>";
    highlighted_filters += "</td>";
    
    
    highlighted_filters += "<td class='filter_cell'>";
        highlighted_filters += "<a href='" +
        make_wb_url("set", {
            "property": "",
            "types": "",
            "pg": 1,
            "domains": "/royalty"
        }) +
        "'>Royalty/Nobility</a>";        
    highlighted_filters += "</td>";
    highlighted_filters += "</tr>";
    
    highlighted_filters += "<tr>";
    highlighted_filters += "<td class='filter_cell'>";
    highlighted_filters += "<a href='" +
    make_wb_url("set", {
        "property": "",
        "types": "/military/military_conflict",
        "pg": 1,
        "domains": ""
    }) +
    "'>Wars</a>";
    highlighted_filters += "</td>";
    highlighted_filters += "<td class='filter_cell'>";
        highlighted_filters += "<a href='" +
        make_wb_url("set", {
            "property": "",
            "domains": "",
            "pg": 1,
            "types": "/base/adultentertainment/adult_entertainer"
        }) +
        "'>Adult Entertainer</a>";
        
    highlighted_filters += "</td>";
    highlighted_filters += "</tr>";
    

    highlighted_filters += "<tr>";
    highlighted_filters += "<td class='filter_cell'>";
        highlighted_filters += "<a href='" +
        make_wb_url("set", {
            "property": "",
            "types": "",
            "pg": 1,
            "domains": "/book"
        }) +
        "'>Publishing</a>";        
    highlighted_filters += "</td>";   

    highlighted_filters += "<td class='filter_cell'>";
        highlighted_filters += "<a href='" +
        make_wb_url("set", {
            "property": "",
            "domains": "",
            "pg": 1,
            "types": "/book/author"
        }) +
        "'>Author</a>";        
    highlighted_filters += "</td>";   

    highlighted_filters += "</tr>";


    highlighted_filters += "<tr>";
    highlighted_filters += "<td class='filter_cell'>";
        highlighted_filters += "<a href='" +
//make_wb_url("add", {"domains": "/sports"})  +      
        make_wb_url("set", {"property": "","types": "","pg": 1,"domains": "/sports"}) +
        "'>Sports</a>";        
    highlighted_filters += "</td>";

    highlighted_filters += "<td class='filter_cell'>";
        highlighted_filters += "<a href='" +
        make_wb_url("set", {
            "property": "",
            "types": "",
            "pg": 1,
            "domains": "/business"
        }) +
        "'>Business</a>";        
    highlighted_filters += "</td>";

    highlighted_filters += "</tr>";


    highlighted_filters += "<tr>";
    
    highlighted_filters += "<td class='filter_cell'>";
        highlighted_filters += "<a href='" +
        make_wb_url("set", {
            "property": "",
            "types": "",
            "pg": 1,
            "domains": "/government"
        }) +
        "'>Government</a>";    
    highlighted_filters += "</td>";

    highlighted_filters += "<td class='filter_cell'>";
        highlighted_filters += "<a href='" +
        make_wb_url("set", {
            "property": "",
            "domains": "",
            "pg": 1,
            "types": "/government/politician"
        }) +
        "'>Politician</a>";    
    highlighted_filters += "</td>";

    highlighted_filters += "</tr>";

    highlighted_filters += "<tr>";
    highlighted_filters += "<td class='filter_cell'>";
        highlighted_filters += "<a href='" +
        make_wb_url("set", {
            "property": "",
            "types": "",
            "pg": 1,
            "domains": "/music"
        }) +
        "'>Music</a>";   
    highlighted_filters += "</td>";
    
    highlighted_filters += "<td class='filter_cell'>";
    highlighted_filters += "<a href='" +
    make_wb_url("set", {
        "property": "/people/deceased_person/date_of_death",
        "types": "",
        "pg": 1,
        "domains": ""
    }) +
    "'>Deaths</a>";
    highlighted_filters += "</td>";
    highlighted_filters += "</tr>";
    


    
    highlighted_filters += "</table>";
    $(area_best_filters_id).append(highlighted_filters);
} // end suggested_filters


function result_info(filter_stats, total_topics){
    var active_filters = "";
    var and = "<span class='and_filter'>and</span>";
    var pfilter = false;
    var tfilter = false;
    var dfilter = false;
    var f = "";
    var fa = get_dayhistory_args("property").split(',');
    var fi = 0;
    for (fi = 0; fi < fa.length; fi++) {
        f = fa[fi];
        if (f && filter_stats.props[f]) {
            if (pfilter) {
                active_filters += "<span class='or_filter'>or</span>";
            }
            pfilter = true;
            active_filters += "<a title='Remove from filter' href='" + make_wb_url("remove", {
                "property": f,
                "pg": null
            }) + "'>";
            active_filters += filter_stats.props[f][1] + "</a>";
        }
    }
    fa = get_dayhistory_args("types").split(',');
    for (fi = 0; fi < fa.length; fi++) {
        f = fa[fi];
        if (f && filter_stats.types[f]) {
            if (tfilter) {
                active_filters += "<span class='or_filter'>or</span>";
            }
            else 
                if (pfilter) {
                    active_filters += and;
                }
            tfilter = true;
            active_filters += "<a title='Remove from filter' href='" + make_wb_url("remove", {
                "types": f,
                "pg": null
            }) + "'>";
            active_filters += filter_stats.types[f][1] + "</a>";
        }
    }
    fa = get_dayhistory_args("domains").split(',');
    for (fi = 0; fi < fa.length; fi++) {
        f = fa[fi];
        if (f && filter_stats.domains[f]) {
            if (dfilter) {
                active_filters += "<span class='or_filter'>or</span>";
            }
            else 
                if (pfilter || tfilter) {
                    active_filters += and;
                }
            dfilter = true;
            active_filters += "<a title='Remove from filter' href='" + make_wb_url("remove", {
                "domains": f,
                "pg": null
            }) + "'>";
            active_filters += filter_stats.domains[f][1] + "</a>";
        }
    }
    var filter_header = "";
    if (active_filters != "") {
    
        filter_header = "<tr><td><div class='area_heading'>Filtered_by</div></td></tr>";
        active_filters = "<tr><td><div class='active_filters'>" + active_filters + "</div></td></tr>";
    }
    
    // result count
    var result_count = "<td class='result_count'>" + total_topics + "&nbsp;&nbsp;Results</td>";
    
    $(result_info_id).html("" + filter_header + active_filters + "<tr>" + result_count + "</tr>");
    
    
} //end result_info


function other_filters(show){
    
    if (!show) {
        show = "domains";
    }
    var filter_stats = DayData.stats();
    
    $(more_filters_id).html("<table><tr><td><div class='area_heading'>More Filters</div></td></tr></table>");    
    $(more_filters_id).append("<a class='filter_link_list' href=\"" + encodeURI("javascript:\{other_filters(\"domains\");}") + "\"> Categories</a>");
    $(more_filters_id).append("<a class='filter_link_list' href=\"" + encodeURI("javascript:\{other_filters(\"types\");}") + "\"> Types </a>");
    $(more_filters_id).append("<a class='filter_link_list' href=\"" + encodeURI("javascript:\{other_filters(\"attributes\");}") + "\"> Attributes </a>");
    
    
    var more_filter_options = "";
    var s;
    var tid = "";
    var k;
    switch (show) {
        case "attributes":
            s = "props";
            $(more_filters_id).append("<div class='title_filter_list'>Attributes</div>");
            $(more_filters_id).append("<table id='prop_table' class='table_filter_list'></table>");
            var table_filter_list_id = document.getElementById("prop_table");
            
            for (k in filter_stats[s]) {
                if ((k.substring(0, 5) != "/base") && (k.substring(0, 5) != "/user") && (filter_stats[s][k][0]) > 3) {
                    tid = k.substring(0, (k.lastIndexOf('/')));
                    
                    more_filter_options = "<tr>";
                    more_filter_options += "<td class='count_filter_list'>" + filter_stats[s][k][0] + "</td>";
                    more_filter_options += "<td class='name_filter_list'>" + "<a href='";
                    
                    more_filter_options += make_wb_url("add", {"property": k}) + "'>" + filter_stats[s][k][1] + "</a>";
                    more_filter_options += "&nbsp;&nbsp;" + "(" + filter_stats['types'][tid][1] + ")";
                    more_filter_options += "</td></tr>";
                    $(table_filter_list_id).append(more_filter_options);
                }
            }
            break;
            
        case "types":
            s = "types";
            $(more_filters_id).append("<div class='title_filter_list'>Types</div>");
            $(more_filters_id).append("<table id='type_table' class='table_filter_list'></table>");
            table_filter_list_id = document.getElementById("type_table");
            
            for (k in filter_stats[s]) {
                // removed min limit:  && (filter_stats[s][k][0]) > 3
                if ((k.substring(0, 5) != "/base") && (k.substring(0, 5) != "/user")) {
                    more_filter_options = "<tr>";
                    more_filter_options += "<td class='count_filter_list'>" + filter_stats[s][k][0] + "</td>";
                    more_filter_options += "<td class='name_filter_list'>" + "<a href='";
                    
                    more_filter_options += make_wb_url("add", {"types": k}) + "'>" + filter_stats[s][k][1] + "</a>";
                    
                    more_filter_options += "</td></tr>";
                    $(table_filter_list_id).append(more_filter_options);
                }
            }
            break;
        case "domains":
            s = "domains";
            $(more_filters_id).append("<div class='title_filter_list'>Categories</div>");
            $(more_filters_id).append("<table id='" + s + "_table' class='table_filter_list'></table>");
            table_filter_list_id = document.getElementById(s + "_table");
            for (k in filter_stats[s]) {
                if ((k.substring(0, 5) != "/base") && (k.substring(0, 5) != "/user") && (filter_stats[s][k][0]) > 3) {
                    more_filter_options = "<tr>";
                    more_filter_options += "<td class='count_filter_list'>" + filter_stats[s][k][0] + "</td>";
                    more_filter_options += "<td class='name_filter_list'>" + "<a href='";
                    more_filter_options += make_wb_url("add", {"domains": k}) + "'>" + filter_stats[s][k][1] + "</a>";
                    
                    more_filter_options += "</td></tr>";
                    $(table_filter_list_id).append(more_filter_options);
                }
            }
            break;
        default:
            break;
    } // switch
} // other_filters

function day_suffix(day_digits) {

    var suffix = "";
    if (day_digits in {11:"",12:"",13:""}) { // these days are a special case
            suffix = "th";
    }
    else {
        switch (day_digits.charAt(day_digits.length-1)) {        
            case "1":
                suffix = "st";
                break;
            case "2":
                suffix = "nd";
                break;
            case "3":
                suffix = "rd";
                break;
                
            default:
                suffix = "th";
                break;
        }        
    }
    return suffix;
    
}


function showfilters(response){
    
    var day_digits = get_day_str().format("d");
//    var day = "" + get_day_str().format("MMM") + " " + get_day_str().format("d");
    $(the_day_id).html("" + get_day_str().format("MMM") + " " + day_digits);  
    $(the_day_id).append("<span class='day_suffix'>"+ day_suffix(day_digits)+"</span></span>");

/*
    if (day_digits in {11:"",12:"",13:""}) { // these days are a special case
            $(the_day_id).append("<span class='day_suffix'>th</span></span>");        
    }
    else {
        switch (day_digits.charAt(day_digits.length-1)) {        
            case "1":
                $(the_day_id).append("<span class='day_suffix'>st</span></span>");
                break;
            case "2":
                $(the_day_id).append("<span class='day_suffix'>nd</span>");
                break;
            case "3":
                $(the_day_id).append("<span class='day_suffix'>rd</span>");
                break;
                
            default:
                $(the_day_id).append("<span class='day_suffix'>th</span>");
                break;
        }        
    }
*/
    var filter_stats = response.stats;
    result_info(filter_stats, response.count);
    suggested_filters(filter_stats);
    other_filters();
    
} // end showfilters


function show_day(resp){

    this.response = resp;
    DayData(resp);
    
    if (!this.response) {
        deb("<br> Whoops! There was an error. This should not happen.")
        return;
    }
    
    showfilters(this.response);
    
    var result = this.response.result;
    
    if (result.length == 0) {
        return;
    }
    
    
    var topic = {};
    var card_content = "";
    var i = 0;
    
    while ((i < result.length)) {

        topic = result[i];
        if (topic.name == null) {
            topic.name = "";
        }


        card_content = "";
        var card_row_id = card_table_id.insertRow(i);
        var break_page = "";
        var cardclass = "card";
        var card_date = new Date.parseString("" + topic.property.day);
        //				var card_date = new Date.parseString(""+topic['/type/reflect/any_value'][0].value);
        var property_name = topic.property.name;
        //	            var property_name = topic['/type/reflect/any_value'][0].link.master_property.name;
        if (property_name == null) {
            property_name = topic.property.id;
        }
        
        card_content = "<div class='card' >";
        card_content += "<div class='card_name' >" + make_freebase_link(topic) +"</div>";
        card_content += "<div class='card_attribute'>" + property_name + "</div>";
        card_content += "<div class='card_date'>";
        card_content += "<div class='card_day'>" + card_date.format("EE") + ", ";
        card_content +=  card_date.format("MMM") + " " + card_date.format("dd") + "</div>";
        card_content += "<div class='card_year'>" + card_date.getFullYear() + "</div>";
        card_content += "</div>";
        card_content += "<div class='card_image'>" + showTopicImage(topic) + "</div>";
        card_content += "</div>";
        
        $(card_row_id.insertCell(0)).html(card_content);
        card_content = "<div class='blurbcell'>";
        card_content += "<div class='card_types'>" + best_topic_types(topic);
//        card_content +=     make_fav_link("add",topic);
        card_content +=     "<div class=\"save_fav_position\">"+make_fav_link("add",topic) +"</div>";
        card_content += "</div>";
        card_content += "<div id='blurb" + i + "' class='card_blurb'></div>";
        card_content += "</div>";
        $(card_row_id.insertCell(1)).html(card_content);
        get_mw_blurb(topic, "blurb" + i); // send freebase request, put result in the blurb div
        i++;
        
    } // end while topics per page
    pagelinks(this.response.pg, get_dayhistory_args("pgsize"), this.response.count);
    
} // end show_page


function get_mw_blurb(topic, div_id_name){
    var blurb_id = document.getElementById(div_id_name);
    var blurburl = "" + "http://api.freebase.com/api/trans/blurb/%23";
    var blurbs = topic['/common/topic/article'];
    if (blurbs != null) {
        if (blurbs[0] != null) {
            blurburl += blurbs[0].guid.replace(/#/, "");
        }
        
        $.ajax({
            url: blurburl,
            dataType: "jsonp",
            cache: true,
            success: function(response){
                if (response.result != undefined) {
                    $(blurb_id).append(response.result.body);
                };
                            },
            data: {
                maxlength: 550
            }
        });
        
    }
}



function deb(str, linebreak){
    if (linebreak == undefined){
        $(debug_id).append("<br>");        
    }
    $(debug_id).append(str);     

}

function make_share_email_link(saved_faves, day) {
    
    var email_body = "&body=";
    var fav_count = 0;
    var birthdays = "";
    var other_props = "";
    for (f in saved_faves) {
        fav_count++;
        if (fav_count == 1) {
            var day_digits = make_day_str(day, "d");
            email_body += "Look at these things that happened on ";
            email_body += encodeURIComponent(make_day_str(day, "MMM")+", ")+ day_digits;
            email_body += day_suffix(day_digits)+":";
            email_body += crlf+crlf;            
        }

        var topic_date = new Date.parseString(""+saved_faves[f].prop_date);
        if (saved_faves[f].property == "Date of birth") {
            birthdays += "       "+encodeURIComponent(fixed_width_str(saved_faves[f].name, 30));
            birthdays += topic_date.getFullYear() + crlf;
        }
        else {
            other_props += "       "+encodeURIComponent(fixed_width_str(saved_faves[f].name, 30));
            other_props += topic_date.getFullYear()  + "  " + saved_faves[f].property;
            other_props += crlf;            
        }
    }
    if (birthdays != "") {
        email_body += "Birthdays" + crlf+crlf;
    }
    email_body += birthdays;
    if (other_props != "") {
        email_body += crlf + "Other things" + crlf+crlf;        
    }
    email_body += other_props;
    email_body += crlf+crlf;
    email_body += "http://www.wiggleback.com shows things that happened today, on your birthday, or any day.";        
    var email_link = "";
    email_link += "<a title=\"Launch email with the list below\" href=\"mailto:?subject="+encodeURIComponent("Hey, check out WIGGLEBACK!");
    email_link += email_body;
    email_link += "\" target=\"_blank\"><img src=\"share_button-red.gif\" class=\"share_button\"></img></a>";
    return email_link;
}

function update_faves (action, id, name, property, prop_date) {
    var saved_day = get_day_str().format("MM-dd");
    if (action == "add") {
        DayFaves.save_fav (
            saved_day,
            {"id": id, "name": name, "property":property, "prop_date": prop_date}
        );
    }
    else if (action == "remove") {
        DayFaves.remove_fav (
            saved_day,
            {"id": id}
        );
    }
    DayFaves.show(saved_day);
}

DayData = function (r) {

    var response = r;
    
//deb("DayData.response: "+formattedJSON(this.response));
    
    DayData.response = function () {
        return response;        
    }
    DayData.result = function () {
        return response.result;                
    }
    DayData.stats = function () {
        return response.stats;                
    }        
    DayData.count = function () {
        return response.daycount;
    }
    DayData.pg = function () {
        return response.pg;                
    }
     
}


// 
function Faves (day) {
    this.cookieOptions = {
//            domain: '*.wiggleback.com',
//            path: '/',
            expiresAt: new Date( 2061, 1, 1 ),
            secure: false
        }    
    $.cookies.setOptions(this.cookieOptions);
    this.topics = $.cookies.get("faves");
    
}

Faves.prototype.show = function (day) {

    var saved_faves = DayFaves.get_faves(day);
    var content = "";
    content += "<table class=\"fav_head\"><tr>";
    content +=   "<td><div              class=\"fav_title\">Faves</div></td>";
    content +=   "<td><div id=\"share\" class=\"share\"> </div></td>";
    content += "</tr></table>";
    $(faves_id).html(content);
    $(faves_id).append("<table id='fav_table' class='fav_list'></table>");
    crlf = "%0D%0A";

    var fav_count = 0;
    var fav_list = '';
    for (f in saved_faves) {
        fav_count++;
        fav_list += "<tr>";
        fav_list += "<td>"+ saved_faves[f].name+"</td>";
        fav_list += "<td class=\"remove_fav_position\">"+make_fav_link("remove", saved_faves[f])+"</td>";
        fav_list += "</tr>";
    }

    var share_id = document.getElementById("share");
    $(share_id).append(make_share_email_link(saved_faves,day));
    if (fav_count > 0) {
        var fav_table_id = document.getElementById("fav_table");
        $(fav_table_id).append(fav_list);    
    }
    else {
        content = "<div class=\"fav_help\">";
        content += "If you see things of interest, click the fav button next to it. ";
        content += " The topic will go into a list here. Then you can share it with others.";
        content += "</div>";
        $(faves_id).append(content);    
    }
        
}


Faves.prototype.get_faves = function (day) {
    this.topics = $.cookies.get("faves");
//deb('<br>get_fav:'+ formattedJSON(this.topics));

    if(this.topics && this.topics[day]) {
        return this.topics[day];
    }
    else {
        return null;        
    }
}

Faves.prototype.save_fav = function (day,topic) {

    if (!this.topics) {        
        this.topics = {};
    }
    
    if (!this.topics[day]) {
        this.topics[day] = {};
    }
  
    this.topics[day][topic.id] = topic;  
    $.cookies.set("faves",this.topics);
    return this.topics[day];

}

Faves.prototype.remove_fav = function (day,topic) {
//deb('<br>topics:'+ formattedJSON(this.topics));

// REMOVE ITEM FROM OBJECT
    if (this.topics && this.topics[day]) {    
        delete (this.topics[day][topic.id]);
        $.cookies.set("faves", this.topics);
        return this.topics[day];
    }
    else {
        return null;
    }
}


function get_dayhistory_args (a) {

    var args = {};
    args["day"]      = $(document).getUrlParam("day") != null ? decodeURIComponent($(document).getUrlParam("day")) : "";
    args["property"] = $(document).getUrlParam("property") != null ? decodeURIComponent($(document).getUrlParam("property")) : "";
    args["types"]    = $(document).getUrlParam("types") != null ? decodeURIComponent($(document).getUrlParam("types")) : "";
    args["domains"]  = $(document).getUrlParam("domains") != null ? decodeURIComponent($(document).getUrlParam("domains")) : "";
    args["sort"]     = ($(document).getUrlParam("sort") != null ? $(document).getUrlParam("sort") : "-rank");
    args["pgsize"]   = $(document).getUrlParam("pgsize") != null ? Number(decodeURIComponent($(document).getUrlParam("pgsize"))) : 10;
    args["pg"]       = $(document).getUrlParam("pg") != null ? Number(decodeURIComponent($(document).getUrlParam("pg"))) : 1;
        
    if (a != undefined) {
        return args[a];
    }
    else {
        return args;
    }        
} // end get_dayhistory_args

function get_day_str (format) {

    var arg_day = get_dayhistory_args("day");
    return make_day_str (arg_day, format);
}


function is_year () {

    var arg_day = get_dayhistory_args("day");
    if (arg_day && (arg_day != "")) {
        arg_day = $.trim(decodeURIComponent(arg_day).replace(/\//g, "-")); //normalize the string
        var day_parts = arg_day.split("-");
        if (day_parts.length > 2) { // the year is specified
            return true;
        }
    }    
   return false;
}


function get_day_results () {

    var daypage_location = "http://";
    var daypage_params = "";
    if (window.location.protocol == "file:") {
        daypage_location += "localhost";
        
    }
    else {
        daypage_location += window.location.hostname;
    }
    
    daypage_location += "/daypage.php";
    daypage_params += "&day=" + get_day_str().format("MM-dd");
    daypage_params += "&pgsize=" + get_dayhistory_args("pgsize");
    daypage_params += "&pg=" + get_dayhistory_args("pg");
    daypage_params += "&props=" + get_dayhistory_args("property");
    daypage_params += "&types=" + get_dayhistory_args("types");
    daypage_params += "&domains=" + get_dayhistory_args("domains");
    daypage_params += "&sort=" + get_dayhistory_args("sort");
    if (is_year()) {
        daypage_params += "&year=" + get_day_str("yyyy");        
    }
    
    
    $.ajax({
        url: daypage_location + "\?jsonp=?",
        data: daypage_params,
        type: "GET",
        cache: false,
        dataType: "jsonp",
        error: function(xobj, status, error){
            deb("<br>status: " + status);
            deb("<br>error: " + error);
        },
        success: show_day
    });
    
} // end get_day_results


    
//ff = Faves.get_faves();


DayFaves = new Faves(get_day_str().format("MM-dd"));
DayFaves.show(get_day_str().format("MM-dd"));
day_id.value = get_dayhistory_args("day") == "" ?  get_day_str().format("MM/dd") : get_dayhistory_args("day") ; // write exactly what the user entered
get_day_results();
