jQuery.noConflict();
if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return - 1;
    }
};

/*
* jQuery TinySort - A plugin to sort child nodes by (sub) contents or attributes.
*
* Version: 1.0.2
*
* Copyright (c) 2008 Ron Valstar
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* description
*   - A plugin to sort child nodes by (sub) contents or attributes.
*
* Usage:
*   $("ul#people>li").tsort();
*   $("ul#people>li").tsort("span.surname");
*   $("ul#people>li").tsort("span.surname",{order:"desc"});
*   $("ul#people>li").tsort({place:"end"});
*
* Change default like so:
*   $.tinysort.defaults.order = "desc";
*
* Changes in 1.0.2
*   - matching numerics did not work for trailing zero's, replaced with regexp (which should now work for + and - signs as well)
*
* Todos
*   - fix mixed literal/numeral values
*   - determine if I have to use setArray or pushStack
*
*/
; (function($) {
    // default settings
    $.tinysort = {
        id: "TinySort"
        ,
        version: "1.0.2"
        ,
        defaults: {
            order: "asc"
            // order: asc, desc or rand
            ,
            attr: ""
            // order by attribute value
            ,
            place: "start"
            // place ordered elements at position: start, end, org (original position), first
            ,
            returns: false
            // return all elements or only the sorted ones (true/false)
        }
    };
    $.fn.extend({
        tinysort: function(_find, _settings) {
            if (_find && typeof(_find) != "string") {
                _settings = _find;
                _find = null;
            }

            var oSettings = $.extend({},
            $.tinysort.defaults, _settings);

            var oElements = {};
            // contains sortable- and non-sortable list per parent
            this.each(function(i) {
                // element or sub selection
                var mElm = (!_find || _find == "") ? $(this) : $(this).find(_find);
                // text or attribute value
                var sSort = oSettings.order == "rand" ? "" + Math.random() : (oSettings.attr == "" ? mElm.text() : mElm.attr(oSettings.attr));
                // to sort or not to sort
                var mParent = $(this).parent();
                if (!oElements[mParent]) oElements[mParent] = {
                    s: [],
                    n: []
                };
                // s: sort, n: not sort
                if (mElm.length > 0) oElements[mParent].s.push({
                    s: sSort,
                    e: $(this),
                    n: i
                });
                // s:string, e:element, n:number
                else oElements[mParent].n.push({
                    e: $(this),
                    n: i
                });
            });
            //
            // sort
            for (var sParent in oElements) {
                var oParent = oElements[sParent];
                oParent.s.sort(
                function zeSort(a, b) {
                    var x = a.s.toLowerCase ? a.s.toLowerCase() : a.s;
                    var y = b.s.toLowerCase ? b.s.toLowerCase() : b.s;
                    if (isNum(a.s) && isNum(b.s)) {
                        x = parseFloat(a.s);
                        y = parseFloat(b.s);
                    }
                    return (oSettings.order == "asc" ? 1: -1) * (x < y ? -1: (x > y ? 1: 0));
                }
                );
            }
            //
            // order elements and fill new order
            var aNewOrder = [];
            for (var sParent in oElements) {
                var oParent = oElements[sParent];
                var aOrg = [];
                // list for original position
                var iLow = $(this).length;
                switch (oSettings.place) {
                case "first":
                    $.each(oParent.s,
                    function(i, obj) {
                        iLow = Math.min(iLow, obj.n)
                    });
                    break;
                case "org":
                    $.each(oParent.s,
                    function(i, obj) {
                        aOrg.push(obj.n)
                    });
                    break;
                case "end":
                    iLow = oParent.n.length;
                    break;
                default:
                    iLow = 0;
                }
                var aCnt = [0, 0];
                // count how much we've sorted for retreival from either the sort list or the non-sort list (oParent.s/oParent.n)
                for (var i = 0; i < $(this).length; i++) {
                    var bSList = i >= iLow && i < iLow + oParent.s.length;
                    if (contains(aOrg, i)) bSList = true;
                    var mEl = (bSList ? oParent.s: oParent.n)[aCnt[bSList ? 0: 1]].e;
                    mEl.parent().append(mEl);
                    if (bSList || !oSettings.returns) aNewOrder.push(mEl.get(0));
                    aCnt[bSList ? 0: 1]++;
                }
            }
            //
            return this.setArray(aNewOrder);
            // setArray or pushStack?
        }
    });
    // is numeric
    function isNum(n) {
        return /^[\+-]?\d*\.?\d*$/.exec(n);
    };
    // array contains
    function contains(a, n) {
        var bInside = false;
        $.each(a,
        function(i, m) {
            if (!bInside) bInside = m == n;
        });
        return bInside;
    };
    // set functions
    $.fn.TinySort = $.fn.Tinysort = $.fn.tsort = $.fn.tinysort;
})(jQuery);




 (function($) {

    $(".expandible_content").each(function() {
        var table = this;
        var th = $("th", table);
        var iCnt = 0;
        th.each(function() {
            $(this).data("index", iCnt++);
            $(this).data("sort", "desc");
            $(this).unbind().bind("click",
            function() {

                $("#load_content").remove();

                var sort = $(this).data("sort");
                sort = sort == 'asc' ? 'desc': 'asc';
                $(this)
                .data("sort", sort);

                th.removeClass("sort_asc")
                .removeClass("sort_desc");

                $(this).addClass("sort_" + sort);

                $(".expandible_content tbody tr")
                .tsort("td:eq(" + $(this).data("index") + ")", {
                    order: sort
                });

            });
        });

        th.eq(0).addClass("sort_asc");

    });

})(jQuery);


 (function($) {

    fnCheckGender = function() {



    	var list_disciplines = $("#event_list table.expandible_content tbody tr").map(function() {
  			return $("span.nome_disciplina", this).attr("rel");
  		}).get();

  		$(".discipline_medagliere:first").show().find("ul.discipline_list li").map(function() {
  		  return (list_disciplines.indexOf($(this).attr("rel")) >= 0)==true ? null : this;
  		}).remove();
  		
  		/*
  		.map(function() {
  			console.log(list_disciplines.indexOf($(this).attr("rel")) >= 0);
  			return null;
  			//return (list_disciplines.indexOf($(this).attr("rel")) >= 0)==true ? this : null;
  		})
  		.show()
  		.end()
  		.end()
  		.show();
      */

        $(".discipline_medagliere:first")
        .find("ul.discipline_list li")
        .bind("click",
        function() {

            var self = this;



            if ($(this).hasClass("discipline_selected")) {

                $(this).removeClass("discipline_selected");

                $("#event_list table.expandible_content tbody")
                .find("tr")
                .show();

            } else {

                $(".discipline_medagliere:first li").removeClass("discipline_selected");
                $(this).addClass("discipline_selected");

                $("#event_list table.expandible_content tbody")
                .find("tr")
                .hide()
                .end()
                .find("tr")
                .map(function() {
                    return $("span.nome_disciplina", this).attr("rel") == $(self).attr("rel") ? this: null;
                })
                .show();

            };

        });

        var fn = Functional;
        var generateGender = function(g) {
            var fn = "a -> jQuery(this).attr('type')=='" + g + "' ? this : null";
            return fn.lambda();
        }

        var isM = generateGender("M");
        var isF = generateGender("F");
        var isMX = generateGender("MX");
        var isChecked = "a -> (this.checked==true) ? this : null".lambda();
        var getValue = "this.value".lambda()

        jQuery("div.check_gender").each(function() {
            var iCnt = 0;
            var chk = jQuery("input[type='checkbox']", this);
            chk.each(function() {
                jQuery(this).bind("click",
                function() {

                    if (jQuery(chk).map(isChecked).size() == 0) {
                        this.checked = true;
                        return;
                    }

                    var fnMap = [];
                    jQuery(chk).map(isChecked).each(function() {
                        if (this.value == "isM") fnMap.push(isM);
                        if (this.value == "isF") fnMap.push(isF);
                        if (this.value == "isMX") fnMap.push(isMX);
                    });

                    jQuery("tr#expand_content").remove();
                    jQuery('td span.open_button').removeClass('close_button');
                    jQuery(".expandible_content tr[type]").hide().map(fn.or.apply(null, fnMap)).show();
                });
                iCnt++;
            });
        });

    };




    prepareOnLoad = function() {



  		jQuery("table.expandible_content tbody tr[data='match']").each(function() {
  			var girone = jQuery("td.col4", this).html().toLowerCase();
  			var disciplina = jQuery("span.nome_disciplina", this).attr("rel");
  			var gender = jQuery("td.col5 span", this).html().toLowerCase();

  			var lnk = "",
  				fase = "";
  			if (/(.+)girone(.+)/.test(girone)) {
  				fase = "prima_fase";
  			} else {
  				fase = "seconda_fase";
  			} 

  			lnk = "risultati_" + disciplina + "_" + gender + "_" + fase + ".shtml";
  			jQuery(this).attr("link_to", lnk);

  		});

            

            jQuery('.expandible_content tr').click(function() {
            
            
            	if (jQuery(this).attr("link_to") != undefined) {
        				document.location = jQuery(this).attr("link_to");
        				return;
        			};
              
              
            if ($("span.tobeplayed", this).size() > 0) return;  
              
              
              
              
            var rel = jQuery(this).attr("rel").split("-");

            if (rel[1] == "") {
                rel[1] = rel[0];
            }


            var mono = $("span.mono", this).size() > 0 ? true: false;
            var gender = $(this).attr("type");
            var dis_id = $(".nome_disciplina:first", this).attr("rel");

            var res_id = $(this).attr("rel").split("-")[0];

            if (/108734|108735|108999/.test(res_id)) {
                document.location = "risultati_60_f_prima_fase.shtml";
                return
            }

            if (/108736|109000|109001|108737|108738/.test(res_id)) {
                document.location = "risultati_60_f_seconda_fase.shtml";
                return
            }


            if (/108728|108729/.test(res_id)) {
                document.location = "risultati_60_m_prima_fase.shtml";
                return
            }

            if (/108730|108731|108732|108733/.test(res_id)) {
                document.location = "risultati_60_m_seconda_fase.shtml";
                return
            }



            if (/108716/.test(res_id)) {
                document.location = "risultati_72_f_prima_fase.shtml";
                return
            }

            if (/108717|108718|108719/.test(res_id)) {
                document.location = "risultati_72_f_seconda_fase.shtml";
                return
            }


            if (/108712/.test(res_id)) {
                document.location = "risultati_72_m_prima_fase.shtml";
                return
            }


            if (/108713|108714|108715/.test(res_id)) {
                document.location = "risultati_72_m_seconda_fase.shtml";
                return
            }

/*
            if (mono == true) {
                var href = gender + "/" + dis_id;
                document.location = "risultati_a_gironi.shtml?" + href;
                return;
            }
*/
            if ($("span.startlist", this).size() > 0) {
                document.location = "risultati.shtml?" + $(this).attr("rel").split("-")[0] + "#"+ rel[1];
                return;
            }

            if ($("span.inprogress", this).size() > 0) {
                document.location = "risultati.shtml?" + $(this).attr("rel").split("-")[0] + "#"+ rel[1];
                return;
            }

            if ($("td.expand_button span:first", this).hasClass("match") == true) {
                document.location = "risultati.shtml?" + $(this).attr("rel").split("-")[0] + "#"+ rel[1];
                return;
            }

            var event_final = $(this).attr("final");
            var event_type = $(this).attr("data");


            jQuery('div#load_content').slideUp(1500);
            jQuery('td span.open_button').removeClass('close_button');
            jQuery('td span.open_button', this).addClass('close_button');

            jQuery('tr#expand_content').remove();
            jQuery(this).after('<tr id="expand_content" class="' + jQuery(this).attr('class') + '"><td style="padding:0" colspan="10"><div id="load_content"></div></td></tr>');




            if ($("span.ended", this).size() > 0) {
              
                jQuery.ajax({
                    url: 'include/shared/oli/2010/calendar/result/' + rel[0] + '.shtml',
                    dataType: 'html',
                    success: function(data) {
                      
                        data = data.replace(/src="\(none\)/g, "src=\"" + base_href);
                        data = data.replace(/href="\(none\)/gi, "href=\"" + base_href_link);

                        jQuery('div#load_content').html((function() {

                            var sel;
							if (event_final == "yes" && mono == false) {
								sel = "div.result_container[rel='" + rel[0] + "'] div.result_content table:first";
							} else {
								sel = "div.result_container[rel='" + rel[1] + "'] div.result_content table:first";

							};
 
 
                            var chkQualificato = jQuery(sel, data).find("tr").map(function() {
                                return (jQuery.trim(jQuery("td:eq(6)", this).html()) == "Qualificato") ? this: null
                            }).size() > 0 ? true: false;

                            if (event_final == "" && chkQualificato == true) {

                                return jQuery(sel, data).find("tr").map(function() {
                                    return (jQuery.trim(jQuery("td:eq(6)", this).html()) != "Qualificato") ? this: null
                                }).each(function() {
                                    jQuery(this).css("display", "none");
                                }).end().end();

                            } else {

                                //console.log(sel);
                                return jQuery(sel, data).find("tr").map(function(i) {
                                    var img = $("img:first", this)[0].src;
                                    var rg = /italia/gi;
                                    return (rg.test(img) || i <= 2) ? null: this;
                                }).each(function() {
                                    $(this).css("display", "none");
                                }).end().end();

                            }

                        })());


                        jQuery("div#load_content")
                        .find("img")
                        .map(function() {
                            return (/blank/gi).test(this.src) == true ? this: null
                        })
                        .remove()
                        .end()
                        .end()
                        .find("td.result_detail a")
                        .each(function() {

                            var href = $(this).attr('href').split("?");
                            href = href[0] + "?" + rel[0] + "#" + rel[1];
                            $(this).attr('href', href);
                            
                        });


                        jQuery('div#load_content').slideDown(1500);

                    }
                });

            }

        });





        jQuery('#tabs').tabs();
        jQuery('#tabs-2').tabs();

        jQuery("img").map(function() {
            return (/blank/gi).test(this.src) == true ? this: null
        }).remove();


        jQuery(".stabs").bind("click click_handler",
        function() {
            var el = jQuery(this);

            var type = (el.attr("type") == "") ? "tabs": el.attr("type");

            el.parent().find(".tabs").removeClass(type + "_on").addClass(type + "_off");
            el.addClass(type + "_on");

            var subClass = el.find("span:first").attr("data");
            var lnk = el.find("span:first").attr("rel");

            jQuery("." + subClass).hide();
            jQuery("#" + lnk).show();



            jQuery("body").trigger("tabs/selected", {
                tab: el
            })

        });


        jQuery('tr.ico_container th span').each(function(i) {
            jQuery(this).attr('title', jQuery(this).html());
        });


        jQuery("div.cls_maglie").each(function() {
            var div_maglia = jQuery(this);

            jQuery("table.maglia", div_maglia).map(function(n, i) {
                return n > 0 ? this: null;
            }).hide();

            jQuery("span.maglia", div_maglia).each(function() {
                var maglia = jQuery(this);

                maglia.parents("li:first").bind("click",
                function() {
                    jQuery("table.maglia", div_maglia).hide();
                    jQuery("table.maglia", div_maglia).map(function() {
                        return jQuery(this).attr("rel") == maglia.attr("rel") ? this: null;
                    }).show();
                });
            });
            jQuery("span.maglia:first", div_maglia).parents("li:first").triggerHandler("click");

        });

        jQuery('#calendar_list').find('a').each(function() {

            var urlString = jQuery(this).attr('href');

            if ((new RegExp(urlString)).test(window.location)) {
                jQuery(this).addClass('selected');
            }

        })
		
		
		jQuery('#CurrentChampionship').find('a').each(function() {

            var urlString = jQuery(this).attr('href');

            if ((new RegExp(urlString)).test(window.location)) {
                jQuery(this).addClass('selected');
            }

        })



    };

})(jQuery);

