"use strict";

try {
    if (console.log) {;}
} catch (err) {
    console = {};
    console.log = function() {return;};
}

function flag_upto(id) {
    $("span.controls :checkbox").each(function (i, v) {
      $(v).attr("checked", true);
      if ($(v).attr("name")==id) 
                return false;
      return true;
    });
}

function unflag_all() {
    $(":checked").attr("checked", false);
}

function mark_read() {
    var post_data = {};
    var checked_items= [];

    var checked_dom = $(":checked");

    if (!checked_dom.length)
    {
	console.log("Nothing marked.");
	return;
    }
    
    checked_dom.parents(".item")
	.each(function (i, v) {checked_items.push(v);});


    checked_items.forEach(function (i) {
      var id =$(".header", i).attr('data-item-id');
      post_data['c'+id]='checked';
    });

    console.log("POSTing:");

    $.ajax({url: "/ajax/mark_read",
	    type: "POST",
	    data: post_data,
	    statusCode: {
		302: function(data) {
		    $(checked_items).remove();
		    console.log("updating");
		    feeds_update(data);
		},
		200: function(data) {
		    $(checked_items).remove();
		    console.log("updating");
		    feeds_update(data);
		}},
	    error: function(j, t, e) {
		console.log("post failed: " + t + " : " + e);
	    }
	   });
}

var feeds = new Feeds();
var page = new PageView({el: $(document), 
			 model: feeds});

function feeds_update(feedData) {
    if (!feedData) {
	console.log("Update_feed_list called without feedData");
	return;
    }

    console.log("Updated");

    _.each(feedData.feeds, function (d) { 
	var i = d.id; 
	console.log(d.title); 
	feeds.get(i).set({unread: d.unread}); 
    });
}

function size_up_window() {
    $('#view').height($(window).height() - $('.menu').height() - 5);
    $('#feeds').height($(window).height() - $('#leftHead').height() - 5);
}

$().ready(function() {
    page.render();

    $.get('/ajax/feeds', function(data) {
	_.each(data.feeds, function(f) { 
	    var nf = new Feed(f);
	    feeds.add(nf);
	});
	console.log("Got data.");
    }, "json");

    size_up_window();
    $(window).resize(size_up_window);
    
    setInterval(function() {
        console.log("Update interval");
	
	$.get('/ajax/feeds', function(data) {
	    feeds_update(data);
	}, "json");
	
    }, 60000 //60 seconds
	       );
});

