var hscore=0
var ascore=0
var xml; var xmltext;
var ctryxml;
var groups=new Array(7);
var groupindex = new Array("A","B","C","D","E","F","G","H");
var outrightprobs;
var outrightranks;
var ctryindices;
var estbyprobs=0;
/*var slangid="EN";
var grtableth = "<tr><th> Country </th><th title=\"Matches played\"> MP </th><th title=\"Matches won\"> W </th><th  title=\"Number of draws\"> D </th><th  title=\"Matches lost\"> L </th><th  title=\"Goals scored\"> G+ </th><th  title=\"Goals received\"> G- </th><th title=\"Goal difference\"> Diff </th><th  title=\"Points\"> Pts </th></tr>";
var button_est_on = "Clear Estimated Results";
var button_est_loading = "Estimating ...";
var button_est_off = "Estimate Remaining Results";
var swinner1 = "Your Forecasted Champion:<br/>";
var swinner3 = "% Probability)"; */
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
function sortNumber(a,b) {return b - a;}

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


function loadCountries() {
$.get("key_countrynames.xml", function(data){
   ctryxml = $(data)
   nameallcountries()
   getoutrightprobs(); 
   doallmatchresults();
 }); 

}

function loadOdds() {
 $.get("../wm2010/odds2010.xml", function(data){
   xmltext = data; 
   xml = $(data)
   getoutrightprobs(); 
   doallmatchresults();
   
 }); 
}

function ctryName(ctryid) {
  if (ctryxml==null) { return(ctryid);};
  return($("#" + ctryid ,ctryxml).children("ctryname[lang='" + slangid + "']").text());
}
function nameallcountries() {
    $("tr:.match").each(function() {
       ogl=$(this).find("td:.ctryname");
       ogl.first().html(ctryName(ogl.first().attr("hdefaultid")));
       ogl.last().html(ctryName(ogl.last().attr("adefaultid")));
    });
    
    
 for (xx=0;xx<groups.length;xx++) {
    grid=groupindex[xx]; 
    grouphtml(grid);
}  

}

function updategrouptables() {
   
   for (xx=0;xx<groups.length;xx++) {
    grid=groupindex[xx]; 
    adjustgroup(grid);
    grouphtml(grid) ;
}
}

function getoutrightprobs() {
    

if ((ctryxml!=null) && (xml!=null)) {

    if (ctryindices==null) {
    
        ctryindices = new Array(31);
        var ccount=0
        
        $("ctryid",ctryxml).each( function() {
            ctryindices[ccount]=$(this).text();
            ccount = ccount+1
        });     
    }
    
    if (outrightprobs==null) {
    
        outrightranks = new Array(31);
        outrightprobs = new Array(31);
        var ctix=-1; var oodd=""; var ooddsum=0;
        var oodds = new Array(31)
        $("outright",xml).children().each( function() {
            ctix= ctryindices.indexOf($(this).children("countryid").first().text())
            outrightranks[ctix]=$(this).children("rankoutright").first().text()
            oodd = $(this).children("oddsoutright").first().text()
            if (isNumber(oodd)) {
                oodds[ctix] = 1/(parseFloat(oodd)-1);
                ooddsum = ooddsum + oodds[ctix];
            } else {
                oodds[ctix] =0;
            }
            
        }); 
        
        for (ctix=0;ctix<oodds.length;ctix++) {    
            
            outrightprobs[ctix] = oodds[ctix]/ooddsum
            
        } 
    }
} 

}

function outrightodds(cid) {
    getoutrightprobs();
    if (outrightprobs==null) { return(0) };
    var cix=ctryindices.indexOf(cid)
    if (cix>outrightprobs.length) { return(0) };
    return(parseFloat(outrightprobs[cix]));
}

function outrightrank(cid) {

    getoutrightprobs();
    if (outrightranks==null) { return(0) };
    return(parseInt(outrightranks[ctryindices.indexOf(cid)]));
}


function odds(mid) {

var outv=new Array(mnoodds,mnoodds, mnoodds)
var omatchnode =$("match:contains('" + mid + "')",xml)
oddscont=omatchnode.children("odds")
o1=oddscont.children("Odds1").text(); 
o2=oddscont.children("Odds2").text();
ox=oddscont.children("OddsX").text();


invo1=0; invo2=0; invox=0;
    if (isNumber(o1)&&isNumber(o2)) {
        invo1=1/(parseFloat(o1)-1);
        invo2=1/(parseFloat(o2)-1);
        if (isNumber(ox)) {
            invox=1/(parseFloat(ox)-1);
        }
        pconst=invo1+invo2+invox;
        outv=new Array(invo1/pconst,invox/pconst, invo2/pconst)
    }
    
    var score1=omatchnode.children("country1").children("score").text();
    if (isNumber(score1)) {
            var outv=0;
            var score2=omatchnode.children("country2").children("score").text();
            var pen1 = omatchnode.children("country1").children("penalty").text();
            var pen2 = omatchnode.children("country2").children("penalty").text();
            score1=parseInt(score1); score2=parseInt(score2);
            if (isNumber(pen1)) { pen1=parseInt(pen1) } else { pen1=0 };
            if (isNumber(pen2)) { pen1=parseInt(pen2) } else { pen2=0 };
            if (score1+pen1>score2+pen2) {outv=1}
            if (score1+pen1<score2+pen2) {outv=-1}
            outv=new Array("Complete",outv, outv)
            
    }
        
      
    


return(outv);
}






function matchresult(idmatch, context)  {
  if (!context) { context = $(document) }
  var omatch=$("#" + idmatch, context);
  hscore = omatch.find("input:.hteam").val();
  ascore = omatch.find("input:.ateam").val();
  
   var tipp=" "; var outvar=""; var prob="";
   var isfinal=(idmatch.substring(0,1)!="G")
   if (isfinal) {
        var openaltyrow=$("#" + idmatch + "p")
        var p1input = openaltyrow.find("input:.hpenalty",context);
        var p2input = openaltyrow.find("input:.apenalty",context);    
    }
if (isfinal && ((!isNumber(hscore)) || (!isNumber(ascore)))) { openaltyrow.attr("class", "penalty nonactive") }

if (isNumber(hscore) && isNumber(ascore)) {
   if (parseInt(hscore) > parseInt(ascore)) {
        tipp="1"; outvar=1;
        if (isfinal) { openaltyrow.attr("class", "penalty nonactive"); };
    } else if(parseInt(hscore) < parseInt(ascore)) {
        tipp="2"; outvar=-1;
        if (isfinal) { openaltyrow.attr("class", "penalty nonactive"); };
    } else {
        if (!isfinal) {
            tipp="X"; outvar=0; 
        } else {
            
            hpen = p1input.val();
            apen = p2input.val();
            if (isNumber(hpen) && isNumber(apen))  {
                tipp=" "; outvar=""; 
                if (parseInt(hpen)<parseInt(apen)) {
                    tipp="2"; outvar=-1; 
                }
                if (parseInt(hpen)>parseInt(apen)) {
                    tipp="1"; outvar=1; 
                }
            } 
            openaltyrow.attr("class", "penalty active");
            
        }
    };
    var myodds=odds(idmatch)
    if (isNumber(myodds[0])) {
        prob=parseInt(myodds[1-outvar]*1000)/10 +"%";
    } else {
        prob=myodds[0]
    }
    
} else if (estbyprobs==1) {
  
    var myodds=odds(idmatch); 
    var prbl=myodds[0]; 
    if (isNumber(prbl)) {
        var pr1=parseFloat(prbl); var pr2=parseFloat(myodds[2]); var prx=0
        if (isNumber(myodds[1])) { prx=parseFloat(myodds[1]) } 
        
        if ((pr1>=prx) && (pr1>=pr2) ) { tipp="1"; outvar=1; prbl=pr1; }
        if ((pr2>=prx) && (pr2>=pr1) ) { tipp="2"; outvar=-1; prbl=pr2; }
        if ((prx>=pr1) && (prx>=pr2) ) { tipp="X"; outvar=0; prbl=prx; }
        prob=parseInt(prbl*1000)/10 +"%";
    } else {
    
         if (prbl=="Complete") {
            tipp="X"; prob=mcompleted;
            outvar=parseInt(myodds[1])
            if (outvar>0) { tipp="1" }
            if (outvar<0) { tipp="2" }
            
         } else {
            
            prob=moutright;
            
            var rk1=outrightrank(omatch.find("input:.hteam").attr("countryid"))
            var rk2=outrightrank(omatch.find("input:.ateam").attr("countryid"))
            
            outvar=""; tipp="";
            if (rk1<rk2) { outvar=1; tipp="1"; }
            if (rk1>rk2) { outvar=-1; tipp="2"; } 
            
        }
    }
    

};
  omatch.children(".prob").html(prob);
  omatch.children(".result").html(tipp);
  omatch.children(".result").attr("outcome", outvar);
  
  
}

function popgroup() {
  // each row has the following elements: 
  // 0: MP, 1: W, 2: D, 3: L, 4: G+, 5: G-; 6: Diff; 7: Pts; 8: outright rank, 9: current rank
  // 10: current rank index, 15: potential points still available, 16: definitely in
  //groups = new Array(7);
  for (j=0;j<=7;j++) {
    groups[j] =new Array(3);
    
    for (i=0;i<=3;i++) {
        groups[j][i]=new Array(0,0,0,0,0,0,0,0,i+1,0,i+1,0,0,0,0,9,0);
    }
  }
  

}

function resetgroup(idgroup) {
    var j = groupindex.indexOf(idgroup); 
    for (i=0;i<=3;i++) {
        groups[j][i]=new Array(0,0,0,0,0,0,0,0,i+1,0,i+1,0,0,0,0,9,0);
    }
    
  
}


function adjustgroup(idgroup) {
    resetgroup(idgroup);
    var ainput; var hinput;
    var gix=groupindex.indexOf(idgroup);
    //group = groups[0]; //groups[];
    
    
    //alert($("table[id='G" + idgroup + "']").text());
     $("#G" + idgroup + " tr").each( function() {
      hinput = $(this).find("input:.hteam")
      ainput = $(this).find("input:.ateam")
      hid = hinput.attr("defaultid");
      hscore = parseInt(hinput.val());
      aid = ainput.attr("defaultid");
      ascore = parseInt(ainput.val());
      if (!isNumber(ascore)) {ascore=0;}; 
      if (!isNumber(hscore)) {hscore=0;}; 
    tipp=$(this).find(".result").attr("outcome");
    
    if (isNumber(tipp)) {
    
    tipp=parseInt(tipp);
    hidx=parseInt(hid.substring(1,2))-1;
    aidx=parseInt(aid.substring(1,2))-1;
    groups[gix][hidx][4]=groups[gix][hidx][4]+hscore;
    groups[gix][aidx][4]=groups[gix][aidx][4]+ascore;    
    groups[gix][hidx][5]=groups[gix][hidx][5]+ascore;
    groups[gix][aidx][5]=groups[gix][aidx][5]+hscore;       
    groups[gix][hidx][2-tipp]=groups[gix][hidx][2-tipp]+1;
    groups[gix][aidx][2+tipp]=groups[gix][aidx][2+tipp]+1;
    };
    
    });
    
    var totalmp=0;
    for (i=0;i<=3;i++) {
      groups[gix][i][0] = groups[gix][i][1] + groups[gix][i][2] + groups[gix][i][3] ;
      groups[gix][i][6] = groups[gix][i][4] - groups[gix][i][5] ;
      groups[gix][i][7] = 3*groups[gix][i][1] + groups[gix][i][2] ;
      groups[gix][i][9] = groups[gix][i][7] + groups[gix][i][6]/100 + groups[gix][i][4]/10000;
      groups[gix][i][15] = groups[gix][i][7] + (3-groups[gix][i][0])*3;
      totalmp = totalmp + groups[gix][i][0];
    };
    
    for (i=0;i<=3;i++) {
        if (groups[gix][i][0]==0) {
            groups[gix][i][9] = groups[gix][i][9] + (-groups[gix][i][8])/1000000;
            
        } else {
            groups[gix][i][9] = groups[gix][i][9] + (33-outrightrank(idgroup +(i+1)))/1000000;
        }
    }
    
    
    var rks = new Array(groups[gix][0][9], groups[gix][1][9], groups[gix][2][9], groups[gix][3][9]);
    
    rks.sort(sortNumber);
   
    var pts2nd=0; var pts3rdpot=0;
    for (i=0;i<=3;i++) {
        for (j=0;j<=3;j++) {
            if ( groups[gix][j][9]== rks[i]  ) { 
                groups[gix][j][10]=i+1; //store the rank for each country
                if (i+1 == 2) { pts2nd = groups[gix][j][7];  }; //store the points of 2nd and and potential points of 3rd for use below
                if (i+1 == 3) { pts3rdpot = groups[gix][j][15]; };
                
                if (totalmp == 12) { //if all matches are done, we know who is in and out
                    if (i+1 < 3) { groups[gix][j][16]=1; } else { groups[gix][j][16]=-1; };
                }
                
            };
            
        };
    };
    
    if (totalmp < 12) {
        for (i=0;i<=3;i++) {
            if ( groups[gix][i][7] > pts3rdpot ) { groups[gix][i][16]=1; };
            if ( groups[gix][i][15] < pts2nd ) { groups[gix][i][16]= -1; };
        };
    };
    
    
}

function winnerhtml(midwon) {

    if (midwon.substring(0,1)!="F") {return(0)};
    var omatch=$("#" + midwon);
    
    var outc = omatch.children("td.result").attr("outcome")
    
    var winnerid="";
    if (outc>0) {
         winnerid= omatch.find("input.hteam").first().attr("countryid");
    }
    if (outc<0) {
        winnerid= omatch.find("input.ateam").attr("countryid");
    }
    
    
    
    ishometeam="h";
    var otd2update=$("td[hdefaultid='W" + midwon.substring(2,4)  +"']:.ctryname");  
    
    if (otd2update.length==0) {
        otd2update=$("td[adefaultid='W" + midwon.substring(2,4)  + "']:.ctryname");
        ishometeam="a";
    }
    
    otd2update.attr("countryid", winnerid)
    
    var oinput2update=otd2update.parent().find("input:." + ishometeam + "team")
    oinput2update.attr("countryid",winnerid);
    
    if (winnerid=="") { winnerid= "W" + midwon.substring(2,4) }
    
    otd2update.html(ctryName(winnerid))

    championhtml();
    

}

function championhtml() {
    var sOut = " "
    var omatch = $("#F164")
    var outc = omatch.children("td.result").attr("outcome")
    
    var wid="";
    if (outc>0) {
         wid= omatch.find("input.hteam").first().attr("countryid");
    }
    if (outc<0) {
        wid= omatch.find("input.ateam").attr("countryid");
    }
    if (wid!="") { 
        sOut = swinner1 + ctryName(wid) + " (" + parseInt(outrightodds(wid)*1000)/10 + swinner3;
    };
    $("div.winnerresult").children("p").html(sOut);
}

function grouphtml(idgroup) {
  
  
  gix=groupindex.indexOf(idgroup); 
  var outhtml= grtableth ;
  var i=0; var gwinner=""; var gsecond="";
  
  for (j=0;j<=3;j++) {
  
    for (x=0;x<=3;x++) { 
     if (groups[gix][x][10] == (j+1)) { i=x;   };
    };
    var quali="";
    if (groups[gix][i][16]==1) { quali=" *"; } else if (groups[gix][i][16]==-1) { quali=" ~"; };
    
    outhtml = outhtml + "<tr><td class=\"grtablectry\">" + ctryName(idgroup + (i+1)) + quali + "</td><td class=\"grres\">" + groups[gix][i][0] + "</td><td class=\"grres\">" + groups[gix][i][1] + "</td><td class=\"grres\">" + groups[gix][i][2] + "</td><td class=\"grres\">" + groups[gix][i][3] + "</td><td class=\"grres\">" + groups[gix][i][4] + "</td><td class=\"grres\">" + groups[gix][i][5] + "</td><td class=\"grres\">" + groups[gix][i][6]  + "</td><td class=\"grres\">" + groups[gix][i][7]  + "</td></tr>" ;
    if ((groups[gix][i][16]==1) && (j==0)) { gwinner=(idgroup + (i+1)) }
    if ((groups[gix][i][16]==1) && (j==1)) { gsecond=(idgroup + (i+1)) }
  }
  
  $("table[groupres='" + idgroup + "']").html( outhtml);
  
  var wdinput=$("input[defaultid='W" + idgroup + "']")
  var wdtd=wdinput.parent().parent().find("td[hdefaultid='W" + idgroup + "']")
   
    wdinput.attr("countryid",gwinner);  
    wdtd.attr("countryid",gwinner);
    if (gwinner!="")  { wdtd.html(ctryName(gwinner)); } else { wdtd.html(ctryName("W" + idgroup)); }

    var wdinput=$("input[defaultid='R" + idgroup + "']")
    var wdtd=wdinput.parent().parent().find("td[adefaultid='R" + idgroup + "']")
    wdinput.attr("countryid",gsecond);  
    wdtd.attr("countryid",gsecond);
    if (gsecond!="")  { wdtd.html(ctryName(gsecond)); } else { wdtd.html(ctryName("R" + idgroup)); }
}

function doallmatchresults() {

    var mid=""
    if ((xml==null)||(ctryxml==null)) { return(null) }
    $("table.groupmatches tr.match").each(function() {
        matchresult($(this).attr("id"));
    });
    updategrouptables();
    $("#F8 tr.match").each(function() {
        mid=$(this).attr("id")
        matchresult(mid);
        winnerhtml(mid);
    });
    $("#FQ tr.match").each(function() {
        mid=$(this).attr("id")
        matchresult(mid);
        winnerhtml(mid);
    });
    $("#FS tr.match").each(function() {
        mid=$(this).attr("id")
        matchresult(mid);
        winnerhtml(mid);
    });
    $("#F1 tr.match").each(function() {
        mid=$(this).attr("id")
        matchresult(mid);
        winnerhtml(mid);
        
    });
}


function loadscores() {
    var score1=""; var score2=""; var pen1=""; var pen2=""; var mid="";
    var omatchnode; var omatchrow; var openrow;
    var scoresexist=0;
    $("match",xml).each( function() {
        omatchnode=$(this);
        score1=omatchnode.children("country1").children("score").text();
        if (isNumber(score1)) {
            scoresexist=1; 
            score2=omatchnode.children("country2").children("score").text();
            pen1=omatchnode.children("country1").children("penalty").text();
            pen2=omatchnode.children("country2").children("penalty").text();
            mid=omatchnode.children("matchid").text();
            omatchrow = $("#" + mid );
            omatchrow.find("input:.hteam").val(score1);
            omatchrow.find("input:.ateam").val(score2);
            if (isNumber(pen1)) {
                openrow = $("#" + mid + "p");
                openrow.find("input:.hpenalty").val(pen1);
                openrow.find("input:.apenalty").val(pen2);
            }
            
            matchresult(mid);
        }
    });
    if (scoresexist==0) {alert(noscoresmsg); } else { alert(scoresmsg); }
    
}

function manualadjust(mid) {
    matchresult(mid);
    if (mid.substring(0,1)=="G") {
        grid=mid.substring(1,2)
        adjustgroup(grid);
        grouphtml(grid);
    } else {
        winnerhtml(mid)
    }
}


$(document).ready(function(){


$("input").keyup( function() {  //keyup
    mid=$(this).parent().parent().attr("id").substr(0,4);    
    manualadjust(mid);
}); 

$("input").change( function() {  //change
    mid=$(this).parent().parent().attr("id").substr(0,4);    
    manualadjust(mid);
}); 


popgroup();
loadCountries();
loadOdds();


$("#toggleprob").click( function() {
 if (estbyprobs==0) {
    estbyprobs=1;
    $(this).html(button_est_loading);
  } else {
    estbyprobs=0;
    $(this).html(button_est_off);
  }
   doallmatchresults();  
   if (estbyprobs==1) {$(this).html(button_est_on);};
});


$("#clearall").click( function() {
   $("input[value!='']").each( function() { $(this).val(""); })
   estbyprobs=0;
   $("#toggleprob").html(button_est_off);
   doallmatchresults();  
});

$("#scoresb").click( function() {loadscores(); doallmatchresults();} );


});


