// JavaScript Document

var lastSort = null;
var lastSortBy = 0;

function show_options(id, obj)
{
    obj.style.display='none';
    document.getElementById('options_'+id).style.display='block';
}

function tableSort(obj,info){

    table = obj.parentNode.parentNode.parentNode;

    if(!info)
        index = obj.parentNode.cellIndex+2;
    else
        index = obj.parentNode.cellIndex;
    
    trs = table.getElementsByTagName("tr");
    //if(!info && index >8)
   //     index+=5;
	

    //zamiana szczalek BEGIN
    for(i=0; i<table.rows[2].cells.length;i++){
        if(table.rows[2].cells[i].getElementsByTagName("div").length > 0)
        {
            if(obj === table.rows[2].cells[i].getElementsByTagName("div").item(0))
            {
                sort_tmp = table.rows[2].cells[i].getElementsByTagName("div").item(0).className;

                if(sort_tmp == "sort1" || sort_tmp == "sort2")
                    tmp = "sort3";
                else
                    tmp = "sort2";

                table.rows[2].cells[i].getElementsByTagName("div").item(0).className = tmp;
            }else{
                table.rows[2].cells[i].getElementsByTagName("div").item(0).className = "sort1";
            }
        }
    }
    //zamina szczalek END
	
    if(tmp == "sort1" || tmp=="sort2")
        lastSortBy = 1;
    else
        lastSortBy = 0;
	
    for(i=4; i<table.rows.length;i++){
        for(j=3; j<table.rows.length-1;j++){
			
            if(table.rows[j].cells.length >= index && table.rows[j+1].cells.length >=index){
                if(lastSortBy == 1?parseInt(table.rows[j].cells[index].innerHTML)>parseInt(table.rows[j+1].cells[index].innerHTML):parseInt(table.rows[j].cells[index].innerHTML)<parseInt(table.rows[j+1].cells[index].innerHTML)){
                    x = trs[j].innerHTML;
                    trs[j].innerHTML = trs[j+1].innerHTML;
                    trs[j+1].innerHTML = x;
                }
            }
        }
    }
}

var box_moved=false;
function zwin_box(obj,id)
{
    if(box_moved)
        return false;

    box_moved=true;

    if($(id).style.display=='none'){
        
      					
		
        diwy = document.getElementById('boxNewsContainer').getElementsByTagName("div");
		
        index = 0;
        for(i=0; i<diwy.length; i++)
        {
            if(diwy[i].className ==  "boxNewsContent")
            {
                if(diwy[i].style.display!="none" && diwy[i].id!=id){
                    Effect.BlindUp(diwy[i],{
                        duration:1.5
                    });
                    document.getElementById('navi_'+index).className = "boxNewsExpand"
                    document.getElementById('navi_'+index).innerHTML = "Rozwin";
                }
                index++;
            }
        }
		
        setTimeout(function(){
            Effect.BlindDown(id,{
                duration:1.5
            });
            obj.className = "boxNewsCollapse";
            obj.innerHTML = "Zwin";
        },1500);
		
        box_moved=false;
    }else{
        Effect.BlindUp(id,{
            duration:1.5
        });
        obj.className = "boxNewsExpand";
        obj.innerHTML = "Rozwin";
        setTimeout(function(){
            box_moved=false;
        },0);
		
    }
    return true;
}

var last_form=null;
function forma_show_game(obj2, date, name,won, o1, ox, o2)
{
    if(!date || !name)
    {
        div = obj2.getElementsByTagName("div");
        if(div.length > 0)
        {
           div.item(0).innerHTML = "";
           div.item(0).parentNode.removeChild(div.item(0));
        }
        return false;
    }
    obj = document.createElement("div");

    if(o1 && ox && o2)
        html = " <div class=\"forma_ramka_game\" style=\"margin-top:-108px\">";
    else
        html = " <div class=\"forma_ramka_game\">";
    html += "        <div class=\"top\">";
    html += "            <div class=\"l\"></div>";
    html += "            <div class=\"r\"></div>";
    html += "        </div>";
    html += "<div class=\"text\">"+date;
    html += "          <div class=\"name\">"+name+"</div>";
    if(o1 && ox && o2)
        html += "        <br /><strong>Najwyższe kursy na spotkanie:</strong><table width=\"120\"><tr><td width=\"30\"><strong>1</strong></td><td width=\"30\"><strong>X</strong></td><td width=\"30\"><strong>2</strong></td></tr><tr><td>"+o1+"</td><td>"+Math.round(ox*100)/100+"</td><td>"+Math.round(o2*100)/100+"</td></tr></table>";
    
    html += "    </div> <div class=\"f\">";
    html += "    <div class=\"l\"></div>";
    html += "   <img class=\"strzalka\" src=\"http://www.tabelepilkarskie.com/images/strzalka_forma_game.gif\" alt=\"\" />";
    html += " <div class=\"r\"></div>";
    html += "</div></div>";


    obj.innerHTML = html;
    obj2.appendChild(obj);
        
    

}



var h2h_teams = new Array();
function h2h(id)
{
    ilosc = h2h_teams.length;
    if(h2h_teams[0]==id){
        h2h_teams[0] = null;
    }else if(h2h_teams[1]==id){
        h2h_teams[1] = null;
    }else if(ilosc==2 && h2h_teams[0] && h2h_teams[1]){
        return false;
    }else if(ilosc==0){
        h2h_teams[0] = id;
    }else if(ilosc==1){
        h2h_teams[1] = id;
    }else if(h2h_teams[0]==null){
        h2h_teams[0]= id;
    }else{
        h2h_teams[1]= id;
    }
    ilosc = h2h_teams.length;
    if(ilosc== 2 && h2h_teams[0] && h2h_teams[1]){
        $('porownaj_img').src="http://www.tabelepilkarskie.com/images/btnH2H_active.gif";
        $('porownaj_img').onclick= function(){window.location='/porownanie_druzyn/?h2h[0]='+h2h_teams[0]+"&h2h[1]="+h2h_teams[1]};
    }else{
        $('porownaj_img').src="http://www.tabelepilkarskie.com/images/btnH2H_disabled.gif";
        $('porownaj_img').onclick=function(){};
    }
    return true;

}

function remove_tr(object)
{
    for(i=0;i<object.rows.length;i++)
    {
        object.deleteRow(i);
    }
    
    if(object.rows.length>0)
        remove_tr(object);
}

function change_porownanie_class(o,c)
{
    o.id="boxLabel_"+c+"2";
    img = o.getElementsByTagName("img");
    img.item(0).src="http://www.tabelepilkarskie.com/images/box_"+c+"_cornerL2.gif";
    img.item(1).src="http://www.tabelepilkarskie.com/images/box_"+c+"_cornerR2.gif";
}

function other_stats(type,obj)
{
    
    divs = obj.parentNode.parentNode.parentNode.getElementsByTagName("div");
    for(i=0;i<divs.length;i++)
    {
        if(divs[i].id=="boxLabel_red2")
            change_porownanie_class(divs[i],"olive");
    }
     

    change_porownanie_class(obj.parentNode,'red');
    document.getElementById('other_stats_all').style.display='none';
    document.getElementById('other_stats_home').style.display='none';
    document.getElementById('other_stats_away').style.display='none';

    document.getElementById('other_stats_'+type).style.display='block';
}

var last_games_a_type=0;
var last_games_b_type=0;
function get_last_games(team_id,leagues_id,limit,type,object,object_div)
{
     if(object_div)
     {
        divs = object_div.parentNode.parentNode.getElementsByTagName("div");
        for(i=0;i<divs.length;i++)
        {
            if(divs[i].id=="boxLabel_red2")
                change_porownanie_class(divs[i],"olive");
        }
     }
     if(object_div)
        change_porownanie_class(object_div,'red');

      if(object.id=="last_games_a")
          last_games_a_type=type;
      else
          last_games_b_type=type;

     remove_tr(object);

     advAJAX.get({
             url: "/xml/tabele_last_games?limit="+limit+"&team_id="+team_id+"&leagues_id="+leagues_id+"&type="+type,
             timeout : 6000,
             onTimeout : function() { },
             retry: 1,
             retryDelay: 2000,
             onRetry : function() {},
             onRetryDelay : function() {},
             onFinalization: function(){},
             onInitialization: function(){},
             onSuccess : function(obj){


                games = obj.responseXML.getElementsByTagName("games");
                if(games.length > 0)
                    i = games.item(0).childNodes;
                
                for(k=0;k<i.length;k++)
                {
                    tr = object.insertRow(object.rows.length);
                    td = tr.insertCell(0);
                    td.innerHTML = k+1;

                    data = new Date(parseInt(i.item(k).getAttribute("game_date"))*1000).format('d-m-Y H:i')
                    td = tr.insertCell(1);
                    td.innerHTML = data;

                    teams_o = i.item(k).getElementsByTagName("teams");
                    if(teams_o.length > 0)
                        teams = teams_o.item(0).getElementsByTagName("i");
                    else
                        teams = new Array();
                    
                    td = tr.insertCell(2);
                    if(teams.length==2)
                    {
                        a = document.createElement("a");
                        a.href = "http://www.tabelepilkarskie.com/porownanie_druzyn/"+teams.item(0).getAttribute("team_item_url")+"/"+teams.item(1).getAttribute("team_item_url")+"/";
                        a.innerHTML = teams.item(0).getAttribute("team_item_name")+" - "+teams.item(1).getAttribute("team_item_name");
                        td.appendChild(a);
                    }

                    td = tr.insertCell(3);
                    td.innerHTML = i[k].getAttribute("game_score_o");

                    td = tr.insertCell(4);
                    td.innerHTML = "";

                    if (i.item(k).getAttribute("game_win")==1 && teams.item(1).getAttribute("team_id")==team_id || i[k].getAttribute("game_win")==3)
                        td.innerHTML = ' <div id="resoultBgGreen">+</div>';
                    else if(i.item(k).getAttribute("game_win")==3 && teams.item(1).getAttribute("team_id")==team_id || i[k].getAttribute("game_win")==1)
                        td.innerHTML = ' <div id="resoultBgRed">-</div>';
                    else if(i.item(k).getAttribute("game_win")==2)
                        td.innerHTML =' <div id="resoultBgOrange">o</div>';
                    else
                        td.innerHTML = '-';

                    /*
                {elseif $g.game_win==2} <div  onmouseover="forma_show_game(this,'{$g.game_date|date_format:"%d-%m-%Y %H:%M"}','{$g.teams.0.team_item_name} <strong>{$g.game_score_o}</strong> {$g.teams.1.team_item_name}','{$g.win}','{$g.odds.0.max_a}','{$g.odds.1.max_a}','{$g.odds.2.max_a}')" onmouseout="forma_show_game(this,false,false)" id="resoultBgOrange">◌</div>
                {elseif $g.game_win==3 && $g.teams.1.team_id==$team_a.team_id || $g.game_win==1} <div  onmouseover="forma_show_game(this,'{$g.game_date|date_format:"%d-%m-%Y %H:%M"}','{$g.teams.0.team_item_name} <strong>{$g.game_score_o}</strong> {$g.teams.1.team_item_name}','{$g.win}','{$g.odds.0.max_a}','{$g.odds.1.max_a}','{$g.odds.2.max_a}')" onmouseout="forma_show_game(this,false,false)" id="resoultBgRed">–</div>
                {else}-{/if}
                */
                 }
                   /* <tr>

           <td>{$key+1}</td>
           <td>{$g.game_date|date_format:"%d-%m-%Y %H:%M"}</td>
           <td><a href="http://{$smarty.server.HTTP_HOST}/porownanie_druzyn/{$params.2}/{$params.3}/{$g.teams.0.team_item_url}-{$g.teams.1.team_item_url}/">{if $g.game_win==1}<strong>{/if}{$g.teams.0.team_item_name}{if $g.game_win==1}</strong>{/if} {$g.game_score_o} {if $g.game_win==3}<strong>{/if}{$g.teams.1.team_item_name}{if $g.game_win==3}<strong>{/if}</a></td>
           <td>{$g.game_score_o}</td>
           <td> {if $g.game_win==1 && $g.teams.0.team_id==$team_a.team_id || $g.game_win==3} <div onmouseover="forma_show_game(this,'{$g.game_date|date_format:"%d-%m-%Y %H:%M"}','{$g.teams.0.team_item_name} <strong>{$g.game_score_o}</strong> {$g.teams.1.team_item_name}','{$g.win}','{$g.odds.0.max_a}','{$g.odds.1.max_a}','{$g.odds.2.max_a}')" onmouseout="forma_show_game(this,false,false)"  id="resoultBgGreen">+</div>
                {elseif $g.game_win==2} <div  onmouseover="forma_show_game(this,'{$g.game_date|date_format:"%d-%m-%Y %H:%M"}','{$g.teams.0.team_item_name} <strong>{$g.game_score_o}</strong> {$g.teams.1.team_item_name}','{$g.win}','{$g.odds.0.max_a}','{$g.odds.1.max_a}','{$g.odds.2.max_a}')" onmouseout="forma_show_game(this,false,false)" id="resoultBgOrange">◌</div>
                {elseif $g.game_win==3 && $g.teams.1.team_id==$team_a.team_id || $g.game_win==1} <div  onmouseover="forma_show_game(this,'{$g.game_date|date_format:"%d-%m-%Y %H:%M"}','{$g.teams.0.team_item_name} <strong>{$g.game_score_o}</strong> {$g.teams.1.team_item_name}','{$g.win}','{$g.odds.0.max_a}','{$g.odds.1.max_a}','{$g.odds.2.max_a}')" onmouseout="forma_show_game(this,false,false)" id="resoultBgRed">–</div>
                {else}-{/if}
           </td>

       </tr>*/
            },
             onError : function(obj) { }
         });
}
// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar])
			returnStr += replace[curChar].call(this);
		else
			returnStr += curChar;
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],

	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replace.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replace.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replace.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replace.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
	G: function() { return this.getHours(); },
	h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }

}

function getGamesAndTable(league_id,season_id)
{

       var date = new Date();
       var thisObjGameForCat = this;
  
       advAJAX.get({
             url: "/xml/tabela_xml/?league_id="+league_id+"&season_id="+season_id+"&sport_id=1&date=1",
             timeout : 10000,
             onTimeout : function() {thisObjGameForCat.getGamesAndTable(1) },
             retry: 1,
             retryDelay: 5000,
             onRetry : function() {},
             onRetryDelay : function() {},
             onFinalization: function(){},
             onInitialization: function(){},
             onSuccess : function(obj){
                //scorer
                var xml = obj.responseXML;
                //games
                var games = xml.getElementsByTagName("wyniki");
                for(i=0;i<games.length;i++)
                {
                    items = games[i].getElementsByTagName("i");
                    for(k=0;k<items.length;k++)
                    {

                        if(items[k].getAttribute("game_id"))
                        {
                           
                           /** g.game_id = items[k].getAttribute("game_id");
                            g.min = items[k].getAttribute("game_min");
                            g.game_score = items[k].getAttribute("game_score");
                            g.status_type = items[k].getAttribute("status_type");
                            g.game_status = items[k].getAttribute("status_id");
                            g.sport_id = parseInt(items[k].getAttribute("sport_id"));
                            g.game_date = items[k].getAttribute("game_date");
                            g.game_score_g = items[k].getAttribute("game_score_sg");
                            g.game_score_o = items[k].getAttribute("game_score_o");
                            g.game_score_p = items[k].getAttribute("game_score_sp");
                            g.info = items[k].getAttribute("info");
                            g.status_name = items[k].getAttribute("status_name");
*/
                           var obj_to_edit = document.getElementById('game_'+items[k].getAttribute("game_id"));
                           if(obj_to_edit)
                           {
                               if(items[k].getAttribute("status_type")==3)
                                  obj_to_edit.cells[0].innerHTML = 'Trwa <strong>'+items[k].getAttribute("game_min")+'\'</strong> '+items[k].getAttribute("status_name");
                               else
                                  obj_to_edit.cells[0].innerHTML = +items[k].getAttribute("status_name");

                               obj_to_edit.cells[1].getElementsByTagName("strong").item(0).innerHTML = items[k].getAttribute("game_score_o");
                           }
                        }
                    }


                }
                tabela_html = xml.getElementsByTagName("tabela");
                if(tabela_html.length > 0)
                {
                    if(document.getElementById('tabela_'+league_id))
                    {
                        document.getElementById('tabela_'+league_id).innerHTML = tabela_html.item(0).firstChild.nodeValue;
                    }
                }


            },
             onError : function(obj) { }
         });
    }
