// Generated by IcedCoffeeScript 1.2.0i
(function() {
  var BOOK, CHAPTER, SEARCHTERM, SLUG, all_books, all_chapters, data_callback, do_search, generate_hash, generate_url, gs_data_callback, iced, initialized, load_from_gdocs, loaded_data, onhashchange, process_data, search_term, select_item, selected_book, selected_chapter, selected_slug, show_watermark, skip_overview, update_history, wm_shown, __iced_k,
    __slice = [].slice;

  iced = {
    Deferrals: (function() {

      function _Class(_arg) {
        this.continuation = _arg;
        this.count = 1;
        this.ret = null;
      }

      _Class.prototype._fulfill = function() {
        if (!--this.count) return this.continuation(this.ret);
      };

      _Class.prototype.defer = function(defer_params) {
        var _this = this;
        ++this.count;
        return function() {
          var inner_params, _ref;
          inner_params = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
          if (defer_params != null) {
            if ((_ref = defer_params.assign_fn) != null) {
              _ref.apply(null, inner_params);
            }
          }
          return _this._fulfill();
        };
      };

      return _Class;

    })(),
    findDeferral: function() {
      return null;
    }
  };
  __iced_k = function() {};

  loaded_data = null;

  all_books = [];

  all_chapters = {};

  selected_book = "";

  selected_chapter = "";

  search_term = "";

  selected_slug = "";

  skip_overview = false;

  BOOK = 'b';

  CHAPTER = 'c';

  SLUG = 's';

  SEARCHTERM = 't';

  generate_hash = function(selected_book, selected_chapter, search_term, slug) {
    if (slug) {
      return "!z=" + BOOK + ":" + selected_book + "|" + CHAPTER + ":" + selected_chapter + "|" + SEARCHTERM + ":" + search_term + "|" + SLUG + ":" + slug;
    } else {
      return "!z=" + BOOK + ":" + selected_book + "|" + CHAPTER + ":" + selected_chapter + "|" + SEARCHTERM + ":" + search_term;
    }
  };

  generate_url = function(slug) {
    return "http://" + window.location.host + "/#" + (generate_hash("", "", "", slug));
  };

  update_history = function(slug) {
    var ___iced_passed_deferral, __iced_deferrals,
      _this = this;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    (function(__iced_k) {
      __iced_deferrals = new iced.Deferrals(__iced_k, {
        parent: ___iced_passed_deferral,
        filename: 'gov-watch.coffee',
        funcname: 'update_history'
      });
      setTimeout((__iced_deferrals.defer({
        assign_fn: (function() {
          return function() {
            return __iced_deferrals.ret = arguments[0];
          };
        })(),
        lineno: 27
      })), 0);
      __iced_deferrals._fulfill();
    })(function() {
      return window.location.hash = generate_hash(selected_book, selected_chapter, search_term, slug);
    });
  };

  onhashchange = function() {
    var chapter, hash, key, part, slug, splits, value, _i, _j, _len, _len2, _ref, _ref2;
    hash = window.location.hash;
    hash = hash.slice(4, hash.length);
    splits = hash.split("|");
    slug = null;
    selected_book = null;
    selected_chapter = null;
    search_term = "";
    for (_i = 0, _len = splits.length; _i < _len; _i++) {
      part = splits[_i];
      _ref = part.split(":"), key = _ref[0], value = _ref[1];
      if (key === BOOK) selected_book = value;
      if (key === SLUG) slug = value;
      if (key === CHAPTER) selected_chapter = value;
      if (key === SEARCHTERM) search_term = value;
    }
    if (!selected_book && !slug) {
      selected_book = all_books[0];
      selected_chapter = "";
      update_history();
      return;
    }
    $("#books option[value='" + selected_book + "']").attr('selected', 'selected');
    if (all_chapters[selected_book]) {
      $("#chapters").html("<option value=''>כל הפרקים</option>");
      _ref2 = all_chapters[selected_book];
      for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
        chapter = _ref2[_j];
        $("#chapters").append("<option value='" + chapter + "'>" + chapter + "</option>");
      }
    } else {
      $("#chapters").html("<option value=''>-</option>");
    }
    $("#chapters option[value='" + selected_chapter + "']").attr('selected', 'selected');
    if (search_term !== "") {
      show_watermark(false);
      $("#searchbox").val(search_term);
    }
    $(".item").removeClass("bigger");
    if (slug) {
      selected_slug = slug;
      $("body").addClass("detail-view");
      $("body").removeClass("list-view");
      select_item($(".item[rel=" + selected_slug + "]"));
      $(".item").removeClass("shown");
      $(".item[rel=" + selected_slug + "]").addClass("shown");
      $(".item[rel=" + selected_slug + "]").addClass("bigger");
      return $("#items").isotope({
        filter: ".shown"
      });
    } else {
      select_item(null);
      $("body").addClass("list-view");
      $("body").removeClass("detail-view");
      return do_search();
    }
  };

  wm_shown = false;

  show_watermark = function(show) {
    if (show) {
      $("#searchbox").val("חיפוש חופשי בתוך ההמלצות");
    } else {
      if (wm_shown) $("#searchbox").val("");
    }
    wm_shown = show;
    return $("#searchbox").toggleClass('watermark', show);
  };

  gs_data_callback = function(data) {
    var cell, col, contents, entries, entry, field, field_titles, idx, row, _i, _len;
    entries = data.feed.entry;
    field_titles = {};
    loaded_data = [];
    for (_i = 0, _len = entries.length; _i < _len; _i++) {
      entry = entries[_i];
      cell = entry.gs$cell;
      row = parseInt(cell.row);
      col = parseInt(cell.col);
      contents = cell.$t;
      if (!contents) contents = "";
      if (row === 1) {
        field_titles[col] = contents;
      } else {
        idx = row - 2;
        field = field_titles[col];
        if (col === 1) {
          loaded_data[idx] = {
            '_srcslug': "" + row
          };
        }
        loaded_data[idx][field] = contents;
      }
    }
    return data_callback(loaded_data);
  };

  window.gs_data_callback = gs_data_callback;

  data_callback = function(data) {
    var book, chapters, rec, _i, _len;
    all_books = {};
    for (_i = 0, _len = data.length; _i < _len; _i++) {
      rec = data[_i];
      if (!all_books[rec.book]) all_books[rec.book] = {};
      all_books[rec.book][rec.chapter] = true;
    }
    all_chapters = {};
    for (book in all_books) {
      chapters = all_books[book];
      all_chapters[book] = Object.keys(chapters);
    }
    all_books = Object.keys(all_books);
    if (localStorage) {
      localStorage.data = JSON.stringify(data);
      localStorage.all_books = JSON.stringify(all_books);
      localStorage.all_chapters = JSON.stringify(all_chapters);
    }
    return process_data();
  };

  initialized = false;

  process_data = function() {
    var book, do_list, html, list_template, modal_options, template, ___iced_passed_deferral, __iced_deferrals, _i, _len,
      _this = this;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    if (initialized) return;
    initialized = true;
    $("#books").html("<option value=''>\u05d4\u05db\u05dc</option>");
    for (_i = 0, _len = all_books.length; _i < _len; _i++) {
      book = all_books[_i];
      $("#books").append("<option value='" + book + "'>" + book + "</option>");
    }
    template = $("script[name=item]").html();
    list_template = $("script[name=list]").html();
    do_list = function(text) {
      return Mustache.to_html(list_template, {
        items: text,
        linkify: function() {
          return function(text, render) {
            text = render(text);
            return text = text.replace(/\[(.+)\]/, "<a href='$1'>\u05e7\u05d9\u05e9\u05d5\u05e8</a>");
          };
        }
      });
    };
    html = Mustache.to_html(template, {
      items: loaded_data,
      none_val: function() {
        return function(text, render) {
          text = render(text);
          if (text === "") {
            return "\u05d0\u05d9\u05df";
          } else {
            return text;
          }
        };
      },
      semicolon_list: function() {
        return function(text, render) {
          text = render(text);
          text = text.split(';');
          return text = do_list(text);
        };
      },
      urlforslug: function() {
        return function(text, render) {
          text = render(text);
          return generate_url(text);
        };
      }
    });
    $("#items").html(html);
    (function(__iced_k) {
      __iced_deferrals = new iced.Deferrals(__iced_k, {
        parent: ___iced_passed_deferral,
        filename: 'gov-watch.coffee',
        funcname: 'process_data'
      });
      setTimeout((__iced_deferrals.defer({
        assign_fn: (function() {
          return function() {
            return __iced_deferrals.ret = arguments[0];
          };
        })(),
        lineno: 214
      })), 50);
      __iced_deferrals._fulfill();
    })(function() {
      $.Isotope.prototype._positionAbs = function(x, y) {
        return {
          right: x,
          top: y
        };
      };
      $("#items").isotope({
        itemSelector: '.item',
        layoutMode: 'masonry',
        transformsEnabled: false,
        filter: ".shown",
        getSortData: {
          chapter: function(e) {
            return e.find('.chapter-text').text();
          },
          recommendation: function(e) {
            return e.find('.recommendation-text').text();
          },
          budget: function(e) {
            return -parseInt("0" + e.attr('cost'), 10);
          },
          comments: function(e) {
            return -parseInt("0" + e.find('.fb_comments_count').text(), 10);
          },
          oneitem: function(e) {
            if (e.attr("rel") === selected_slug) {
              return 0;
            } else {
              return 1;
            }
          }
        }
      });
      show_watermark(true);
      $("#searchbox").change(function() {
        if (wm_shown) {
          search_term = "";
        } else {
          search_term = $("#searchbox").val();
        }
        return update_history();
      });
      $("#searchbox").focus(function() {
        return show_watermark(false);
      });
      $("#searchbox").blur(function() {
        if ($(this).val() === "") return show_watermark(true);
      });
      $("#searchbar").submit(function() {
        return false;
      });
      $("#books").change(function() {
        selected_book = $("#books").val();
        selected_chapter = "";
        return update_history();
      });
      $("#chapters").change(function() {
        selected_chapter = $("#chapters").val();
        return update_history();
      });
      $("#sort").change(function() {
        var sort_measure;
        sort_measure = $("#sort").val();
        return $("#items").isotope({
          sortBy: sort_measure
        });
      });
      $(".item").click(function() {
        return update_history($(this).attr('rel'));
      });
      window.onhashchange = onhashchange;
      onhashchange();
      modal_options = {
        backdrop: true,
        keyboard: true,
        show: false
      };
      $("#overview").modal(modal_options);
      return $("#overview-close").click(function() {
        return $("#overview").modal('hide');
      });
    });
  };

  select_item = function(item) {
    var url, ___iced_passed_deferral, __iced_deferrals,
      _this = this;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    $('fb\\:comments').remove();
    $('fb\\:like').remove();
    $(".item").removeClass("bigger");
    (function(__iced_k) {
      if (item) {
        item.addClass("bigger");
        $("#items").isotope('reLayout', function() {});
        selected_slug = item.attr("rel");
        url = generate_url(selected_slug);
        item.append("<fb:like href='" + url + "' send='true' width='590' show_faces='true' action='recommend' font='tahoma'></fb:like>");
        item.append("<fb:comments href='" + url + "' num_posts='2' width='590'></fb:comments>");
        (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: 'gov-watch.coffee',
            funcname: 'select_item'
          });
          if (window.FB) {
            FB.XFBML.parse(item.get(0), (__iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  return __iced_deferrals.ret = arguments[0];
                };
              })(),
              lineno: 299
            })));
          } else {
            __iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  return __iced_deferrals.ret = arguments[0];
                };
              })(),
              lineno: 302
            });
          }
          __iced_deferrals._fulfill();
        })(function() {
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: 'gov-watch.coffee',
              funcname: 'select_item'
            });
            setTimeout((__iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  return __iced_deferrals.ret = arguments[0];
                };
              })(),
              lineno: 302
            })), 1000);
            __iced_deferrals._fulfill();
          })(function() {
            $(".item[rel=" + selected_slug + "]").scrollintoview();
            $("#items").isotope('reLayout');
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: 'gov-watch.coffee',
                funcname: 'select_item'
              });
              setTimeout((__iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    return __iced_deferrals.ret = arguments[0];
                  };
                })(),
                lineno: 305
              })), 1000);
              __iced_deferrals._fulfill();
            })(function() {
              return __iced_k($(".item[rel=" + selected_slug + "]").scrollintoview());
            });
          });
        });
      } else {
        return __iced_k();
      }
    })(function() {
      return $("#items").isotope('reLayout');
    });
  };

  do_search = function() {
    var field, found, re, rec, should_show, slug, ___iced_passed_deferral, __iced_deferrals, _i, _j, _len, _len2, _ref,
      _this = this;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    re = RegExp(search_term, "ig");
    for (_i = 0, _len = loaded_data.length; _i < _len; _i++) {
      rec = loaded_data[_i];
      slug = rec._srcslug;
      should_show = search_term === "";
      if (search_term !== "") {
        _ref = ["recommendation", "subject", "result_metric", "title", "execution_metric", "chapter", "responsible_authority"];
        for (_j = 0, _len2 = _ref.length; _j < _len2; _j++) {
          field = _ref[_j];
          if (rec[field]) {
            found = rec[field].search(search_term) !== -1;
          } else {
            found = false;
          }
          should_show = should_show || found;
        }
      }
      should_show = should_show && ((selected_book === "") || (rec.book === selected_book)) && ((selected_chapter === "") || (rec.chapter === selected_chapter));
      $(".item[rel=" + slug + "]").toggleClass("shown", should_show);
    }
    $("#items").isotope({
      filter: ".shown"
    });
    (function(__iced_k) {
      __iced_deferrals = new iced.Deferrals(__iced_k, {
        parent: ___iced_passed_deferral,
        filename: 'gov-watch.coffee',
        funcname: 'do_search'
      });
      setTimeout((__iced_deferrals.defer({
        assign_fn: (function() {
          return function() {
            return __iced_deferrals.ret = arguments[0];
          };
        })(),
        lineno: 352
      })), 1000);
      __iced_deferrals._fulfill();
    })(function() {
      return $(".item[rel=" + selected_slug + "]").scrollintoview();
    });
  };

  load_from_gdocs = function() {
    return $.get("https://spreadsheets.google.com/feeds/cells/0AurnydTPSIgUdE5DN2J5Y1c0UGZYbnZzT2dKOFgzV0E/od6/public/values?alt=json-in-script", gs_data_callback, "jsonp");
  };

  $(function() {
    try {
      loaded_data = JSON.parse(localStorage.data);
      all_books = JSON.parse(localStorage.all_books);
      all_chapters = JSON.parse(localStorage.all_chapters);
      process_data();
      return setTimeout(load_from_gdocs, 10000);
    } catch (error) {
      return load_from_gdocs();
    }
  });

}).call(this);

