(function(){
  var fnc, helper, methods, templateMedagliati, templateNazioni, templateNazioniDiscipline;
function stripHTML(oldString) {
   var newString = "";
   var inTag = false;
   for(var i = 0; i < oldString.length; i++) {
        if(oldString.charAt(i) == '<') inTag = true;
        if(oldString.charAt(i) == '>') {
              if(oldString.charAt(i+1)=="<")
              {
              		//dont do anything
	}
	else
	{
		inTag = false;
		i++;
	}
        }
        if(!inTag) newString += oldString.charAt(i);
   }
   return newString;
}
;
  _.composeR = function composeR() {
    var fns;
    fns = Array.prototype.slice.call(arguments, 0);
    return _.compose.apply(null, fns.reverse());
  };
  _.helper = {
  };
  helper = _.helper;
  fnc = Functional;
  helper.table_sort = function table_sort(options) {
    var __a, fn, on_resort, selector;
    __a = options;
    selector = __a.selector;
    on_resort = __a.on_resort;
    fn = function fn() {
      var iCnt, table, th;
      table = this;
      th = jQuery("th", table);
      iCnt = 0;
      th.each(function() {
        jQuery(this).data("index", iCnt++);
        jQuery(this).data("sort", "desc");
        return jQuery(this).unbind().bind("click", function() {
          var sort;
          //jQuery("#load_content").remove()
          (typeof on_resort !== "undefined" && on_resort !== null) ? on_resort() : null;
          sort = jQuery(this).data("sort");
          sort = sort === 'asc' ? 'desc' : 'asc';
          jQuery(this).data("sort", sort);
          th.removeClass("sort_asc").removeClass("sort_desc");
          jQuery(this).addClass("sort_" + sort);
          //console.log("td:eq(" + jQuery(this).data("index") + ")")
          return jQuery("tbody tr", table).tsort("td:eq(" + jQuery(this).data("index") + ")", {
            order: sort
          });
        });
      });
      return th.eq(0).addClass("sort_asc");
    };
    return (function() {
      return jQuery(selector).each(fn);
    });
  };
  helper.load_html = function load_html(url) {
    return (function() {
      var rt;
      rt = "";
      jQuery.ajax({
        url: url,
        async: false,
        dataType: 'html',
        success: function success(html) {
          //setTimeout( -> nielsenRefresh(document.location.href) )
          return rt = html;
        }
      });
      return rt;
    });
  };
  helper.load_json = function load_json(url) {
    return (function() {
      var rt;
      rt = "";
      jQuery.ajax({
        url: url,
        async: false,
        dataType: 'json',
        error: function error(json) {
          return rt = {
            items: []
          };
        },
        success: function success(json) {
          //setTimeout( -> nielsenRefresh(document.location.href) )
          return rt = json;
        }
      });
      return rt;
    });
  };
  helper.string2node = function string2node(selector) {
    return (function(s) {
      return jQuery(selector, s);
    });
  };
  helper.renderHTMLTo = function renderHTMLTo(selector) {
    return (function(html) {
      return jQuery(selector).html(html);
    });
  };
  methods = ["each", "map", "detect", "select", "reject", "all", "any"];
  _(methods).each(function(el) {
    return helper[el] = function(fn) {
      return (function(list) {
        return _(list)[el](fn);
      });
    };
  });
  methods = ["each", "map", "detect", "select", "reject", "all", "any"];
  _(methods).each(function(el) {
    return helper[el + "_if"] = function(options) {
      return options.cond() === true ? list(function() {
        return _(list)[el](options.fn);
      }) : function(list) {
        return list;
      };
    };
  });
  helper.nodeMap = function nodeMap(fn) {
    return (function(list) {
      return jQuery(list).map(fn).get();
    });
  };
  helper.nodeSelect = function nodeSelect(fn) {
    return (function(list) {
      return jQuery(list).map(function() {
        return fn.apply(this) === true ? this : null;
      }).get();
    });
  };
  helper.pass = function pass() {
    return (function(el) {
      return el;
    });
  };
  helper.template = function template(tpl) {
    var fn;
    fn = _.template(tpl);
    return (function(json) {
      return fn({
        items: json
      });
    });
  };
  templateMedagliati = ' \
 \
<table border="0" class="body"> \
<thead> \
<tr> \
<th class="colHeader col col_0" title=""> \
Disciplina  \
</th> \
<th class="colHeader col col_1" title=""> \
Specialita \
</th> \
<th class="colHeader col col_2" title=""> \
genere \
</th> \
<th class="colHeader col col_3" title=""> \
Naz. \
</th> \
<th class="colHeader col col_4" title=""> \
nome \
</th> \
<th class="colHeader col col_5" title=""> \
Oro \
</th> \
<th class="colHeader col col_6" title=""> \
argento \
</th> \
<th class="colHeader col col_7" title=""> \
bronzo \
</th> \
</tr> \
</thead> \
<tbody> \
<% _.each(items, function(item,index) { %>  \
<tr class="row_<%= index %> <%= index%2 ? "odd": "even" %>"> \
<td class="columnBody-sorted col col_0" > \
<ul> \
<li rel="<%= item.dis_id %>" class="discipline_<%= item.dis_id %>">  \
<span><%= item.dis_name %></span>   \
</li> \
</ul> \
</td> \
<td class="columnBody col col_1"> \
<%= item.spec_name %>  \
</td> \
<td class="columnBody col col_2"> \
<span style="display:none"><%= item.event_gender %></span> \
<img height="15" src="lib/images/icone/gender_<%= item.event_gender %>_active.png"/> \
</td> \
<td class="columnBody col col_3"> \
<span style="display:none"><%= item.image %></span> \
<img src="lib/images/bandiere/<%= item.image %>.gif"/> \
</td> \
<td class="columnBody col col_4"> \
<%= item.name %> \
</td> \
<td class="columnBody col col_5"> \
<% if (item.gold>0) { %> \
<img src="lib/images/icone/gold.png"/> \
<% } %> \
 \
</td> \
<td class="columnBody col col_6" > \
<% if (item.silver>0) { %> \
<img src="lib/images/icone/silver.png"/> \
<% } %> \
 \
</td> \
<td class="columnBody col col_7" > \
<% if (item.bronze>0) { %> \
<img src="lib/images/icone/bronze.png"/> \
<% } %> \
 \
</td> \
</tr>  \
<% }); %>         \
</tbody> \
</table> \
 \
';
  templateNazioni = ' \
 \
<table border="0" class="body"> \
<thead> \
<tr> \
<th class="colHeader col col_3" title=""> \
Naz. \
</th> \
<th class="colHeader col col_4" title=""> \
nome \
</th> \
<th class="colHeader col col_5" title=""> \
Oro \
</th> \
<th class="colHeader col col_6" title=""> \
argento \
</th> \
<th class="colHeader col col_7" title=""> \
bronzo \
</th> \
 \
<th class="colHeader col col_8" title=""> \
Totali \
</th> \
 \
</tr> \
</thead> \
<tbody> \
<% _.each(items, function(item,index) { %>  \
<tr class="row_<%= index %> <%= index%2 ? "odd": "even" %>" > \
 \
<td class="columnBody col col_3"> \
<span rel="<%= item.rel %>" style="display:none"><%= item.image %></span> \
<img src="lib/images/bandiere/<%= item.image %>.gif"/> \
</td> \
<td class="columnBody col col_4"> \
<%= item.name %> \
</td> \
<td class="columnBody col col_5"><%= item.gold %></td> \
<td class="columnBody col col_6" ><%= item.silver %></td> \
<td class="columnBody col col_7" ><%= item.bronze %></td> \
<td class="columnBody col col_8" ><%= item["won-medals"] %></td> \
 \
</tr>  \
<% }); %>         \
</tbody> \
</table> \
';
  templateNazioniDiscipline = ' \
 \
<table border="0" class="body"> \
<thead> \
<tr> \
<th class="colHeader col col_4" title=""> \
Disciplina \
</th> \
<th class="colHeader col col_5" title=""> \
Oro \
</th> \
<th class="colHeader col col_6" title=""> \
argento \
</th> \
<th class="colHeader col col_7" title=""> \
bronzo \
</th> \
 \
<th class="colHeader col col_8" title=""> \
Totali \
</th> \
 \
</tr> \
</thead> \
<tbody> \
<% _.each(items, function(item,index) { %>  \
<tr class="row_<%= index %> <%= index%2 ? "odd": "even" %>" > \
 \
<td class="columnBody col col_4" nowrap="true"> \
<img align="left" src="<%= base_href %>lib/images/icone/small/<%= item.discipline_id %>.png" border="0" /> \
<span> \
<%= item.discipline %> \
</span> \
</td> \
<td class="columnBody col col_5"><%= item.gold %></td> \
<td class="columnBody col col_6" ><%= item.silver %></td> \
<td class="columnBody col col_7" ><%= item.bronze %></td> \
<td class="columnBody col col_8" ><%= item["won_medals"] %></td> \
 \
</tr>  \
<% }); %>         \
</tbody> \
</table> \
 \
';
  (function($) {
    var attachEventNations, convertTableMedToJson, generateEvents, generateEventsForCheckBox, getActiveVal, loadDataByPage, page, populateDisciplineList, renderMedagliere;
    attachEventNations = function attachEventNations(selector) {
      return (function() {
        return $(selector).bind("click", function(e) {
          var disc_selected, nation_id, src, table, td, year;
          e.preventDefault();
          e.stopPropagation();
          disc_selected = $("ul.discipline_list li.active").size();
          if (disc_selected > 0) {
            return null;
          }
          td = $("td.col_3", this);
          table = $(this).parents("table:first");
          nation_id = $("span", td).attr("rel");
          $("#load_content", table).remove();
          year = $("#edition_year").val();
          src = year === 'Assoluto' ? "include/shared/oli/2010/json/historical-medal/prefix_" + nation_id + ".json" : "include/shared/oli/" + year + "/json/medal/" + nation_id + ".json";
          return fnc.sequence(helper.load_json(src), helper.template(templateNazioniDiscipline), function(html) {
            return "<tr id='load_content'><td colspan='10'>" + html + "</td></tr>";
          }, function(html) {
            return $(td).parents("tr").after(html);
          }, helper.table_sort({
            selector: "#load_content table:first"
          }))();
        });
      });
    };
    populateDisciplineList = function populateDisciplineList() {
      return (function(json) {
        var ls;
        ls = _(json).chain().pluck('dis_id');
        if (ls.filter(function(el) {
          return (typeof el !== "undefined" && el !== null);
        }).value().length > 0) {
          ls = ls.uniq().value();
          $(".discipline_medagliere li").show().map(function() {
            var val;
            val = $(this).attr("rel");
            return !_(ls).include(val) ? this : null;
          }).hide();
        }
        return json;
      });
    };
    convertTableMedToJson = function convertTableMedToJson(url) {
      return fnc.sequence(helper.load_html(url), function(html) {
        return $("tbody tr", html).map(function() {
          var list_td;
          list_td = $("td", this).map(function() {
            return $(this).html();
          }).get();
          //console.log("list_td",list_td)
          return {
            image: $(list_td[0])[0].src.toString().split("/").reverse()[0].replace(".gif", ""),
            name: $(list_td[0])[0].src.toString().split("/").reverse()[0].replace(".gif", "").replace(/_/gi, " "),
            rel: $(list_td[0]).attr("rel"),
            gold: new Number(stripHTML(list_td[2])),
            silver: new Number(stripHTML(list_td[3])),
            bronze: new Number(stripHTML(list_td[4])),
            "won-medals": new Number(stripHTML(list_td[5]))
          };
        }).get();
      })();
    };
    loadDataByPage = function loadDataByPage(page) {
      return (function() {      });
    };
    prepareOnLoad();
    $(".discipline_list li").each(function() {
      return $(this).removeClass("active");
    });
    page = document.location.href.split("/").reverse()[0];
    renderMedagliere = function renderMedagliere(options) {
      var __a, dis_id, gender, process, url, useFilter, useGender, year;
      __a = options;
      year = __a.year;
      url = __a.url;
      gender = __a.gender;
      dis_id = __a.dis_id;
      page = __a.page;
      useFilter = false;
      useGender = true;
      process = fnc.sequence(function() {
        var json;
        if (page === "medagliere.shtml") {
          if (year === "Assoluto") {
            useFilter = false;
            if (!(typeof dis_id !== "undefined" && dis_id !== null)) {
              _(gender).include("ALL") ? (json = {
                items: convertTableMedToJson("include/shared/oli/2010/editions/medals/total/all.shtml")
              }) : null;
              _(gender).include("M") ? (json = {
                items: convertTableMedToJson("include/shared/oli/2010/editions/medals/total/M.shtml")
              }) : null;
              _(gender).include("F") ? (json = {
                items: convertTableMedToJson("include/shared/oli/2010/editions/medals/total/F.shtml")
              }) : null;
              _(gender).include("MX") ? (json = {
                items: convertTableMedToJson("include/shared/oli/2010/editions/medals/total/MX.shtml")
              }) : null;
            } else {
              useFilter = true;
              json = helper.load_json("include/shared/oli/2010/json/historical-medal/discipline_" + dis_id + ".json")();
              useGender = false;
            }
          }
          if (year !== "Assoluto") {
            if (!(typeof dis_id !== "undefined" && dis_id !== null)) {
              useFilter = false;
              _(gender).include("ALL") ? (json = {
                items: convertTableMedToJson("include/shared/oli/2010/editions/year/medals/ALL/" + year + ".shtml")
              }) : null;
              _(gender).include("M") ? (json = {
                items: convertTableMedToJson("include/shared/oli/2010/editions/year/medals/M/" + year + ".shtml")
              }) : null;
              _(gender).include("F") ? (json = {
                items: convertTableMedToJson("include/shared/oli/2010/editions/year/medals/F/" + year + ".shtml")
              }) : null;
              _(gender).include("MX") ? (json = {
                items: convertTableMedToJson("include/shared/oli/2010/editions/year/medals/MX/" + year + ".shtml")
              }) : null;
            } else {
              useFilter = true;
              json = helper.load_json("include/shared/oli/" + year + "/json/medal/discipline_" + dis_id + ".json")();
              useGender = false;
            }
          }
        } else if (page === "medagliati.shtml") {
          useFilter = true;
          json = helper.load_json("include/shared/oli/" + year + "/json/podiums/general.json")();
        }
        return json;
      }, function(json) {
        return json.items;
      }, populateDisciplineList(), function(json) {
        dis_id !== "" && useFilter === true & page === "medagliati.shtml" ? (json = _(json).select(function(el) {
          return el.dis_id === dis_id;
        })) : null;
        return json;
      }, function(json) {
        if (useGender === false) {
          return json;
        }
        gender.length > 0 && useFilter === true && !_(gender).include("ALL") ? (json = _(json).select(function(el) {
          return _(gender).include(el.event_gender);
        })) : null;
        return json;
      }, function(json) {
        if (page === "medagliere.shtml") {
          return helper.template(templateNazioni)(json);
        } else if (page === "medagliati.shtml") {
          return helper.template(templateMedagliati)(json);
        }
      }, helper.renderHTMLTo("#all_medals"), helper.table_sort({
        selector: "#all_medals table:first",
        on_resort: function on_resort() {
          return jQuery("#load_content").remove();
        }
      }), attachEventNations("#all_medals table tbody tr"));
      return process();
    };
    getActiveVal = function getActiveVal(selector) {
      return $(selector).map(function() {
        return $(this).hasClass("active") === true ? this : null;
      }).eq(0).attr("rel");
    };
    generateEventsForCheckBox = function generateEventsForCheckBox(selector) {
      var selectAll, selectNotAll;
      selector = jQuery(selector);
      selectAll = function selectAll() {
        return $(this).val() === "ALL" ? this : null;
      };
      selectNotAll = function selectNotAll() {
        return ($(this).val() !== "ALL") === true ? this : null;
      };
      return jQuery("input:checkbox", selector).add("input:radio", selector).map(selectAll).bind("click", function() {
        var self;
        self = this;
        return _.defer(function() {
          $("input:checkbox", selector).add("input:radio", selector).map(selectNotAll).each(function() {
            return this.checked = !self.checked;
          });
          return $(document).trigger("medals.search");
        });
      }).end().map(selectNotAll).bind("click", function() {
        return $(document).trigger("medals.search");
      });
    };
    generateEvents = function generateEvents(selector) {
      $("div.reset").click(function() {
        $(".discipline_medagliere li").removeClass("active");
        $(".check_gender").show();
        return $(document).trigger("medals.search");
      });
      return $(selector).each(function() {
        var li, uls;
        li = this;
        uls = $("li", this);
        return $(uls).click(function() {
          if (page === "medagliere.shtml") {
            if ($(this).hasClass("active")) {
              //$(this).removeClass("active")
            } else {
              uls.removeClass("active");
              $(this).addClass("active");
            }
            $(this).hasClass("active") ? $(".check_gender").hide() : $(".check_gender").show();
          } else {
            uls.removeClass("active");
            $(this).addClass("active");
          }
          return $(document).trigger("medals.search");
        });
      });
    };
    $(document).bind("medals.search", function() {
      var discipline, gender, year;
      //console.log(json_editions)
      //fnc.sequence(
      // helper.load_json("http://verdi/staging_speciali/olimpiadi_invernali/2010/sky/include/shared/oli/2010/json/editions.json")
      //   (json) ->
      //      json:json.reverse()
      //      $(".medagliere").each ->
      //        $("#edition_year").html((->
      //          html:$(json).
      //          map(-> "<option value='" + this.year + "'>" + this.name + "</option>" ).
      //          get().
      //          join("")
      //
      //          return html
      //
      //        ()))
      //)()
      year = $("select[name='edition_year']:first").val();
      gender = jQuery(".check_gender input:checked").map(function() {
        return jQuery(this).val() !== "ALL " ? this : null;
      }).map(function() {
        return jQuery(this).val();
      }).get();
      discipline = getActiveVal("ul.discipline_list li");
      //link:"podium_edizione.html?" + s + "&json=http://verdi/Staging_Speciali/olimpiadi_invernali/2010/raisport/include/shared/oli/" + year +     "/json/podiums/general.json";
      return renderMedagliere({
        page: page,
        dis_id: discipline,
        gender: gender,
        year: year
      });
    });
    generateEvents("ul.edition_gender");
    generateEvents("ul.discipline_list");
    generateEventsForCheckBox(".check_gender");
    if (page === "medagliere.shtml") {
      //$(".discipline_medagliere").hide()
    }
    if (page === "medagliati.shtml") {
      $(".discipline_medagliere li").removeClass("active").eq(0).addClass("active");
      $(".discipline_medagliere li:visible").eq(0).addClass("active");
    }
    $("#edition_year").bind("change", function() {
      //if $(this).val()=="Assoluto"
      //  $(".discipline_medagliere").hide()
      //else
      //  $(".discipline_medagliere").show()
      return $(document).trigger("medals.search");
    });
    return $(document).trigger("medals.search");
  })(jQuery);
})();
