<?php

/**
 *
 *  Displays pronos in grid
 *
 * @author flabadens
 * @version 1.0
 * @see MyBetsGrid.core.php
 * @todo
 * 
 *
 */
?>
<link rel="stylesheet" href="grille.css" />
<script src="Mobile/jqtouch/jqtouch/jquery.1.3.2.min.js" type="text/javascript" charset="utf-8"></script>

<script type="text/javascript">
    var arrayMatch=new Array();
    var arrayScore=new Array();
    var initialTotalAmount;
    var initialRemainingPoints;
    var initialPlayerPoints;
    var tempAmount;
    var cliquable = true;
    var nbError = 0;

    //calc the sum of the array
    function sumArray (array){
        var total=0;
        for (mise in array){
            total+=array[mise];
        }
        return total
    }

    //initialize array of amount
    $(document).ready(function() {
        $('.Mise').each(function() {
            id= $(this).attr('id');
            if ($('#'+id).val() == '')$('#'+id).val('0');
            arrayMatch[$(this).attr('id')]=parseInt($('#'+id).val());
        })
		
		$('.PronoScore').each(function() {
            id= $(this).attr('id');
			//if ($('#'+id).val() == '')$('#'+id).val('0');
            if ($('#'+id).val() == ''){
				arrayScore[$(this).attr('id')]='';
			}else{
				arrayScore[$(this).attr('id')]=$('#'+id).val();
			}
        })


        initialTotalAmount = sumArray(arrayMatch);
        initialPlayerPoints = parseInt($('#playerScore').val());
        initialRemainingPoints = initialPlayerPoints - parseInt($('#consumedScore').val())+initialTotalAmount;
        
    });

    //manage error
    function errorHandler ( id, oldAmount, message){
        if (id != -1) {
            arrayMatch[id+'Mise']=oldAmount;
            $('#'+id+'Mise').val(oldAmount);
        }
        nbError++;
        $('#errorMess').html(message);
               
    }

    //check if amount >= 0 and if it's an alphanumeric
    function validateAmount (val){

        return val >=0 && (typeof val == 'number');
        
    }
	
	function validateScore (val){

        return val >=0 && val <=99 && (typeof val == 'number');
        
    }

    //check if amount is inferior to  20% of global points 
    function checkAmount(val){
        //alert(val+" "+Math.floor(initialPlayerPoints*0.2)+" - "+initialRemainingPoints+" "+sumArray(arrayMatch));
        return val<=Math.round(initialPlayerPoints*0.2) && initialRemainingPoints>=sumArray(arrayMatch);
    }
    

	function format(valeur,decimal,separateur) {
		// formate un chiffre avec 'decimal' chiffres après la virgule et un separateur
		var deci=Math.round( Math.pow(10,decimal)*(Math.abs(valeur)-Math.floor(Math.abs(valeur)))) ; 
		var val=Math.floor(Math.abs(valeur));
		if ((decimal==0)||(deci==Math.pow(10,decimal))) {val=Math.floor(Math.abs(valeur)); deci=0;}
		var val_format=val+"";
		var nb=val_format.length;
		for (var i=1;i<4;i++) {
			if (val>=Math.pow(10,(3*i))) {
				val_format=val_format.substring(0,nb-(3*i))+separateur+val_format.substring(nb-(3*i));
			}
		}
		if (decimal>0) {
			var decim=""; 
			for (var j=0;j<(decimal-deci.toString().length);j++) {decim+="0";}
			deci=decim+deci.toString();
			val_format=val_format+"."+deci;
		}
		if (parseFloat(valeur)<0) {val_format="-"+val_format;}
		return val_format;
	}


    // update points display et calc amount
    function updatePoints (remaining){
            
            $('#errorMess').html('');
            $('#miseMax').html(format(Math.min(Math.round(initialPlayerPoints*0.2), remaining), 0, ' '));
            $('#consumed').html(format(initialPlayerPoints-remaining, 0, ' '));
            $('#remaining').html(format(remaining, 0, ' '));
        
    }

	function deleteSpaces(str){
		var spacePos = str.indexOf(" ",0);
		while(spacePos != -1){
			if(spacePos == 0){
				str = str.substr(spacePos+1, str.length-1);
			}else if(spacePos == str.length-1){
				str = str.substr(0, spacePos);
			}else{
				str = str.substr(0, spacePos)+str.substr(spacePos+1, str.length-1);
			}
			spacePos = str.indexOf(" ",0);
		}
		return str;
	}
	
    function onAmountChange(id) {
        nbError = 0;
        //getting amount by input id
        var id = parseInt(id.replace("Mise", ""));
		var amountString = $('#'+id+'Mise').val();
		//on supprime les éventuels espaces présents dans amountString
		amountString = deleteSpaces(amountString);
		//alert("Apres suppression d'espace : #"+amountString+"#");
        
		var amount = parseInt(amountString, 10);
        //alert("chaine testee : "+amount);
		
		//save the old value of the amount
        tempAmount=arrayMatch[id+'Mise'];

        if (validateAmount(amount)){

            arrayMatch[id+'Mise']=amount;
            
            if (checkAmount(amount)) {
               updatePoints(initialRemainingPoints-sumArray(arrayMatch));
			   $('#'+id+'Mise').val(amount);
            }
            else {
                errorHandler ( id, tempAmount, "Vous n'avez pas assez de points &agrave; miser. (Max : "+($('#miseMax').html())+")");
            }          
            
        }
        else {
            errorHandler ( id, tempAmount, "Votre mise doit &ecirc;tre un entier et sup&eacute;rieur ou &eacute;gal &agrave; 0");
        }
    }
	
	function onScoreChange(id, name){
        nbError = 0;
        //getting amount by input id
		var save = id;
        var id = parseInt(id.replace(name, ""));
        var score = parseInt($('#'+id+name).val(), 10);
		//alert("id appel fonction : "+save+", id apres parseInt : "+id+", chaine de recherche : "+"#"+id+name+", score : "+score);
		//save the old value of the amount
        tempScore=arrayScore[id+name];

        if (! validateScore(score)){
			$('#'+id+name).val(tempScore);
			$('#errorMess').html("Votre pronostic doit &ecirc;tre un entier compris entre 0 et 99");
        }else{
			arrayScore[id+name] = score; //mise à jour du tableau des pronostics
			$('#'+id+name).val(score);
			$('#errorMess').html('');
		}
	}

    function submitForm ()
    {
        $('#pronosForm').submit();
    }

    function onClickOnBaniere (url) {

        //url = "http://www.google.fr";
        if (cliquable && nbError == 0){
            cliquable = false;
            if(checkIt(navigator.userAgent.toLowerCase(),'chrome')||checkIt(navigator.userAgent.toLowerCase(),'safari')){
                window.open(url,'<?php echo $randomPopup; ?>','width=1024, height=768, toolbar=yes,location=yes,status=yes,menubar=yes,resizable=yes,');}
            else {
                window.open(url,'<?php echo $randomPopup; ?>','toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,');//'about:blank' width=100%, height=100%, 
            }
			window.focus();
            $('#pronosForm').submit();

            //setTimeout(function(){ cliquable=true; $(location).attr('href',url); }, 500 );
        }
        else {
            if (nbError != 0){
                alert($('#errorMess').html());
            }
        }

    }

    function checkIt(useragent,string)
    {
        return useragent.indexOf(string) + 1;
    }
    

</script>

<?php

if ( $nbResults == 0){
    echo "Aucun pronostic dans cette rubrique";
    echo '<br />';
    echo '<br />';
    echo '<table width="100%">
    <tr>
        <td align="center">
            <a style="margin:0 10px;color:rgba(0,0,0,.9)" href="'.$sess->link3($CHOOSE_BET_PAGE,"").'" ><img border=0 src='.$IMAGES_DIR.'boutons/bouton_GrandRetour.gif'.'></a>
        </td>
    </tr>
    </table>';
    return;
}

$nbBet = count($tabAllBets);

?>

<?php if ($betsChecked )	echo "<div align=center class=error>Vos pronostics ont &eacute;t&eacute ; valid&eacutes;.</div><br>"; ?>

<form action="<?php echo $DISPLAY_GRID_OF_BETS; ?>" method="GET" id="pronosForm"  > <!-- target="<?php //echo $randomPopup; ?>" -->

<?php
if($nbBet > 0)
{
    ?>
    <input type="hidden" name="update" value="yes">
    <?php
}


?>


<table width=98% border=0 align=center cellspacing="0" >
    <tr>
        <td colspan="8">
            <center>
            <?php
            echo "<img src=\"".$IMAGES_DIR.$category['ContainerImage']."\">&nbsp;<span class=\"titleGrille\"> ".formatString($category['CategoryName'])."</span>";
            ?>            
            </center>
        </td>
    </tr>
    <?php


    $currentDate='';
    $matchAPronostiquer = false;

    // run all matchs
    for($rPatch = 0; $rPatch < $nbResults; $rPatch++){
        $myMatch = $matchs[$rPatch];

        

        $once = db_fetch_array(main_db_query("SELECT * FROM Paris WHERE MatchId='".$myMatch['MatchId']."' AND PlayerId='".$player[Id]."'"));

        $betIsClosed = checkBetIsClosed($current_european_date , $myMatch["Date"], $once);
        $matchIsClosed = checkMatchIsClosed($current_european_date , $myMatch["Date"], $once);
        
        $playerBet = $tabAllBets[$myMatch[MatchId]];
        $playerAmount = $tabAllAmounts[$myMatch[MatchId]];
        $tabPlayerBet = explode("-",$playerBet);

        $matchTime = time_diff($date, $myMatch['Date']);


        // if match already bet, get back the prono
        if ($tabAllBets[$myMatch[MatchId]] != "")
        {
            $matchPronos = "(".$tabAllBets[$myMatch[MatchId]].")";
        }
        else
            $matchPronos = "";
        
        // waiting results
        if ($matchTime < -7200)
        {
            $couleurmatch = $WAITING_RESULTS;
            $messageDate = 'En attente';
        }
        // during the match (2h), display live
        elseif ($matchTime < 0){
            $couleurmatch = $LIVE_MATCH;
            $messageDate = 'Live';
        }
        else {
            $matchAPronostiquer = true;
            // day of the match
            if ($current_european_date==date_mysql($myMatch[Date])) {
                $couleurmatch = $TODAY_MATCH;
                $messageDate = "<b>".time_mysql($myMatch[Date])."</b>";
            }
            else {
                //var_dump($matchPronos);
                // waiting pronos
                if( $matchPronos != "" )
                    $couleurmatch = $ALREADY_BET;
                else
                    $couleurmatch = $NOT_ALREADY_BET_IN_GRID;

                $messageDate = time_mysql($myMatch['Date']);

            }
        }

        $colorStart = '<font color='.$couleurmatch.'>';
        $colorEnd = '</font>';

        //si la date est différente de l'enregistrement précédent on met un tr
        if ($currentDate != date("d/m", strtotime($myMatch['Date']))){
            $currentDate = date("d/m", strtotime($myMatch['Date']));
        
?>
        <tr>
            <td height="10"></td>
        </tr>
        <tr bgcolor="#eaeaea" cellspacing="0" cellpadding="0" >
            <td colspan="2"><table class='minibloc' id='black' style='width:100px'><th id='head1'></th><th id='head2'><span class="smallDarkLink" style='color:#f2c000;font-size: 10px;'><?php echo date("d/m/Y", strtotime($myMatch['Date'])); ?></span></th><th id='head3'></th></table></td>
            <td colspan="4" class="th_grille" bgcolor="#eaeaea">Vos pronostics</td>
            <td class="th_grille" bgcolor="#eaeaea">Votre mise</td>
            <td class="th_grille" bgcolor="#eaeaea">Les tendances</td>
        </tr>
        <tr>
            <td height="10"></td>
        </tr>
<?php
        }
?>

        <tr>
            <td align="left" class="smallDark" ><?php echo $colorStart.$messageDate.$colorEnd; ?></td>
            <td width=15% class="smallDark" align=right>
                <?php if ($containerId == 1 || $containerId == 2 ){
					$tooltip = $myMatch['Team1']."<br>";

					$tooltip .= $classement_club[$myMatch['Team1']]['Rank'];
					if ($classement_club[$myMatch['Team1']]['Rank'] == 1)
						$tooltip .= "er";
					else
						$tooltip .= "�me";
					$tooltip .= " de ".$category['ContainerName']."<br>";

					$tooltip .= $classement_club[$myMatch['Team1']]['Gagnes']." victoire(s), ";
					$tooltip .= $classement_club[$myMatch['Team1']]['Nuls']." nul(s),<br> ";
					$tooltip .= $classement_club[$myMatch['Team1']]['Perdus']." d�faite(s)";

					$tooltip .= $classement_club[$myMatch['Team1']]['ButsPour']." buts marqu�s,<br> ";
					$tooltip .= $classement_club[$myMatch['Team1']]['ButsContre']." buts encaiss�s";?>

                    <a class=smallDarkLink onMouseover='showtip(this,event,"<?php echo $tooltip ?>")' onMouseout="hidetip()" href="#" >
                    <?php echo $colorStart.formatString($myMatch['Team1']).$colorEnd;
                    echo '</a>';
                 }
                 else {
                     echo $colorStart.formatString($myMatch['Team1']).$colorEnd;
                 }
                 ?>
            </td>
            <td class="smallDark" align="right" width=65px>
                <IMG align=absmiddle SRC="<?php echo (flag($myMatch[Team1])=='flags/fruit_transp.gif' || flag($myMatch[Team1])=='x.gif')?$IMAGES_DIR.$FLAG_UNKNOWN:$IMAGES_DIR.flag($myMatch[Team1]); ?>" >&nbsp;
                <input class="inputBg2 PronoScore" type="text" size="2" id="<?php echo $myMatch['MatchId']."Team1"; ?>" name="<?php echo $myMatch['MatchId']."Team1"; ?>" onchange="onScoreChange(this.name, 'Team1')" maxlength="2" value="<?php echo $tabPlayerBet[0];  ?>" <?php echo ($myMatch['BetClosed'] ? "disabled readonly" : "") ?> style="width:20px;">
            </td>
            <td width=5 align="center" class="smallDark" valign=middle>
            -
            </td>
            <td class="smallDark" align="left" width=60px>
                <input class="inputBg2 PronoScore" type="text" size="2" id="<?php echo $myMatch['MatchId']."Team2"; ?>" name="<?php echo $myMatch['MatchId']."Team2"; ?>" onchange="onScoreChange(this.name, 'Team2')" maxlength="2" value="<?php echo $tabPlayerBet[1] ?>" <?php echo ($myMatch['BetClosed'] ? "disabled readonly" : "") ?> style="width:20px;" >&nbsp;<IMG align=absmiddle SRC="<?php echo (flag($myMatch[Team2])=='flags/fruit_transp.gif' || flag($myMatch[Team2])=='x.gif')?$IMAGES_DIR.$FLAG_UNKNOWN:$IMAGES_DIR.flag($myMatch[Team2]); ?>">
            </td>
            <td width=15% class=smallDark align=left>
                <?php if ($containerId == 1 || $containerId == 2 ){
					$tooltip = $myMatch['Team2']."<br>";

					$tooltip .= $classement_club[$myMatch['Team2']]['Rank'];
					if ($classement_club[$myMatch['Team2']]['Rank'] == 1)
						$tooltip .= "er";
					else
						$tooltip .= "�me";
					$tooltip .= " de ".$category['ContainerName']."<br>";

					$tooltip .= $classement_club[$myMatch['Team2']]['Gagnes']." victoire(s), ";
					$tooltip .= $classement_club[$myMatch['Team2']]['Nuls']." nul(s),<br> ";
					$tooltip .= $classement_club[$myMatch['Team2']]['Perdus']." d�faite(s)";

					$tooltip .= $classement_club[$myMatch['Team2']]['ButsPour']." buts marqu�s,<br> ";
					$tooltip .= $classement_club[$myMatch['Team2']]['ButsContre']." buts encaiss�s";?>

                    <a class=smallDarkLink onMouseover='showtip(this,event,"<?php echo $tooltip ?>")' onMouseout="hidetip()" href="#" >
                    <?php echo $colorStart.formatString($myMatch['Team2']).$colorEnd;
                    echo '</a>';
                 }
                 else {
                     echo $colorStart.formatString($myMatch['Team2']).$colorEnd;
                 }
                 ?>
            </td>
            <td class="smallDark" align="center" width=115px>
                <input class="inputBg2 Mise" type="text" size="15" id="<?php echo $myMatch['MatchId']."Mise"; ?>" name="<?php echo $myMatch['MatchId']."Mise"; ?>" onchange="onAmountChange(this.name)" value="<?php echo $playerAmount ?>" <?php echo ($myMatch['BetClosed'] ? "disabled readonly" : "") ?>>
            </td>

    <!-- Barre de tendance -->
    <?php
            // calcul des statistiques
            calcStats ($myMatch[MatchId], $victoire1, $victoire2, $matchNul);

            $link_tooltip1 = "onMouseover=\"showtip(this,event,'".number_format($victoire1,1)."%"."')\" onMouseout=\"hidetip()\"";
            $link_tooltipN = "onMouseover=\"showtip(this,event,'".number_format($matchNul,1)."%"."')\" onMouseout=\"hidetip()\"";
            $link_tooltip2 = "onMouseover=\"showtip(this,event,'".number_format($victoire2,1)."%"."')\" onMouseout=\"hidetip()\"";
    ?>
            <td width=100px align=right>
                <table width=100% border=0 cellspacing=0 cellpadding=0>
                    <tr>
                        <td align=center class=smallDark <?php echo $link_tooltip1 ?> bgcolor="<?php echo ($victoire1>=$victoire2)?$BG_COLOR_FOND_4:$BG_COLOR_FOND_15; ?>" height="10px" width="<?php echo round($victoire1)."%" ?>"></td>
                        <td align=center class=smallDark <?php echo $link_tooltipN ?> bgcolor=<?php echo $BG_COLOR_FOND_11?> align=center width="<?php echo (100-round($victoire1)-round($victoire2))."%" ?>"></td>
                        <td align=center class=smallDark <?php echo $link_tooltip2 ?> bgcolor="<?php echo ($victoire2>=$victoire1)?$BG_COLOR_FOND_4:$BG_COLOR_FOND_15; ?>" width="<?php echo round($victoire2)."%" ?>"></td>                        
                    </tr>
                </table>
            </td>
        </tr>
    <?php
    }
    ?>

    <!--#champs cache pour passer l'id du container-->
    <!--#permet de retourner dans CONTAINER_PAGE-->
    <input type="hidden" name="containerId" value="<?php echo $containerId; ?>">

    <!--#champs cache pour l id de la category-->
    <input type="hidden" name="categoryId" value="<?php echo $categoryId; ?>">

    <!--#champs cache pour la redirection de la page en cas d erreur-->
    <input type="hidden" name="valide" value="Valider">
    <tr align=center>
        <td colspan=8 align=center class=smallDark><div id="errorMess" style="color:red"><?php echo $error; ?></div></td>
    </tr>
    <tr align=center>
        <td colspan=8 align=center class=smallDark>
            <div >
                <center>
                    <br /><br />

                    <table width="40%" class="smallDarkLink" style="font-size:11px">
                        <tr>
                            <td align="left" class=smallDark >
                                Total Points :
                            </td>
                            <td align="right" class=smallDark >
                                <?php echo number_format( $player['Score'], 0 , "", " " ) ?>
                                <input type="hidden" id="playerScore" value="<?php echo $player['Score']; ?>">
                            </td>
                            <td class=smallDark>
                                pts
                            </td>
                        </tr>
                        <tr>
                            <td align="left" class=smallDark >
                                D&eacute;j&agrave; mis&eacute;s :
                            </td>
                            <td align="right" class=smallDark >
                                <div id="consumed"><?php echo number_format( $consumed_points, 0 , "", " " ); ?></div>
                                <input type="hidden" id="consumedScore" value="<?php echo $consumed_points; ?>">
                            </td>
                            <td class=smallDark>
                                pts
                            </td>
                        </tr>
                        <tr>
                            <td align="left" class=smallDark >
                                Reste &agrave; miser :
                            </td>
                            <td align="right" class=smallDark >
                                <div id="remaining"><?php echo number_format( $remaining_points, 0 , "", " " ); ?></div>
                            </td>
                            <td class=smallDark>
                                pts
                            </td>
                        </tr>
                        <tr>
                            <td align="center" colspan="3" class=smallDark >
                                Vous pouvez miser jusqu'&agrave; <span id="miseMax"><?php echo number_format( min($BET_MAX, $remaining_points), 0 , "", " " );?></span> pts.
                            </td>
                        </tr>
                    </table>
                </center>
            </div>
        </td>
    </tr>

    
    

</table>
</form>
