<?php

/**
 *
 *  Displays pronos in grid
 *
 * @author flabadens
 * @version 1.0
 * @see MyBetsGrid.core.php
 * @todo
 * 
 *
 */
?>

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

    //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

        $('.Mise').each(function() {
            id= $(this).attr('id');
            if ($('#'+id).val() == '')$('#'+id).val('0');
            arrayMatch[$(this).attr('id')]=parseInt($('#'+id).val());
        })

        initialTotalAmount = sumArray(arrayMatch);
        initialPlayerPoints = parseInt($('#playerScore').val());
        initialRemainingPoints = initialPlayerPoints - parseInt($('#consumedScore').val())+initialTotalAmount;
        //$('.miseMaxClass').html(Math.min(Math.round(initialPlayerPoints*0.2), initialRemainingPoints-initialTotalAmount));


        //alert(parseInt ($('#consumedScore').val()) - parseInt(initialTotalAmount)+" "+initialTotalAmount);


    //manage error
    function errorHandler ( id, oldAmount, message){

        if (id != -1) {
            arrayMatch[id+'Mise']=oldAmount;
            $('#'+id+'Mise').val(oldAmount);
        }

        $('#errorMess').html(message);
        alert(message);

    }

    //check if amount >= 0 and if it's an alphanumeric
    function validateAmount (val){
        
        return val >=0 && (typeof val == 'number');

    }

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

    function enleverZero(chaineAvecZeros) {
      var indice = 0;
      if (chaineAvecZeros.length != 1) {
          while (chaineAvecZeros.charAt(indice) == '0' && indice < chaineAvecZeros.length) {
            indice = indice + 1;
          }
          return chaineAvecZeros.substring(indice);
      }
      return chaineAvecZeros;
    }
	
	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('');
            //$('.miseMaxClass').html(Math.min(Math.round(initialPlayerPoints*0.2), remaining));
            $('#miseMax').html(format(Math.min(Math.round(initialPlayerPoints*0.2), remaining), 0, ' ')+' pts');
            $('#consumed').html(format(initialPlayerPoints-remaining, 0, ' ')+' pts.');
            $('#remaining').html(format(remaining, 0, ' ')+' pts.');

    }

    function onAmountChange(id) {
       
        //getting amount by input id
        var id = parseInt(id.replace("Mise", ""));
        var amount = $('#'+id+'Mise').val();
        amount = parseInt(enleverZero(amount));
        $('#'+id+'Mise').val(amount);

        //save the old value of the amount
        tempAmount=arrayMatch[id+'Mise'];

        if (validateAmount(amount)){

            arrayMatch[id+'Mise']=amount;

            if (checkAmount(amount)) {

                //alert(initialRemainingPoints+" - "+sumArray(arrayMatch));
                updatePoints(initialRemainingPoints-sumArray(arrayMatch));
            }
            else {
                errorHandler ( id, tempAmount, "Vous n'avez pas assez de points à miser. "); //(Max : "+parseInt($('#miseMax').html())+")
            }

        }
        else {
            errorHandler ( id, tempAmount, "Votre mise doit être un entier et supérieur à 0");
        }
    }







</script>
<?php
include_once($RACINE_DIR.$MOBILE_DIR."configMobile.php3");

if ( $nbResults == 0){
    echo "Aucun pronostics dans cette rubrique";
    exit();
}

$nbBet = count($tabAllBets);
?>

<form  method="POST" id="pronosForm" >

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


?>

<!---
<table style="width:100%; height:100%">
	<tr style="width:100%; height:10%;">
		<td style="width:100%;">
			TEST
		</td>
	</tr>
	<tr style="width:100%;">
		<td style="width:100%;">
			<div id="wrapper" style="position:relative; z-index:1;  height:350px; width:100%; overflow:auto;">
				<div id="scroller">
					<ul>
						<li>-->
							<div style="background-color:rgb(92,92,98);">
								<center>
									<table align="center" style="background-color:rgb(92,92,98);">
										<tr>
											<td align="left" class="smallBoldDark">
												Reste &agrave; miser
											</td>
											<td>
												:
											</td>
											<td align="right" class="smallBoldDark">
												<div id="remaining"><?php echo number_format($remaining_points ,0,""," ")?> pts.</div>
											</td>
										</tr>
										<tr>
											<td align="left" class="smallBoldDark">
												Mise max
											</td>
											<td>
												:
											</td>
											<td align="right" class="smallBoldDark">
												<span id="miseMax"><?php echo number_format(min($BET_MAX, $remaining_points) ,0,""," ")?> pts.</span>
											</td>
										</tr>
									</table>
								</center>
							</div>
							<ul class="edgetoedge">

							<?php


							$currentDate='';

							// 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 {
									// day of the match
									if ($current_european_date==date_mysql($myMatch[Date])) {
										$couleurmatch = $TODAY_MATCH;
										$messageDate = date("d/m", strtotime($myMatch[Date])).' &agrave; '.time_mysql($myMatch[Date]);
									}
									else {
										//var_dump($matchPronos);
										// waiting pronos
										if( $matchPronos != "" )
											$couleurmatch = $ALREADY_BET;
										else
											$couleurmatch = $NOT_ALREADY_BET;

										$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']));
								
						?>
							<li class="arrow" width="10%"><center><b>Le <?php echo date("d/m/Y", strtotime($myMatch['Date'])); ?></b></center></li>
								
						<?php
								}
						?>

								<li class="arrow" >
									<table width="100%">
										<tr>
											<td align="left" rowspan="3" width="10%"><em><?php echo $colorStart.$messageDate.$colorEnd; ?></em></td>
											<td width=15% class=smallBoldDark align=left>
												<b><?php echo $colorStart.formatString($myMatch['Team1']).$colorEnd; ?></b>
											</td>
											<td width=10% class="smallBoldDark" align="left">
												<!--<IMG align=absmiddle SRC="<?php echo $IMAGES_DIR.flag($myMatch[Team1]) ?>" >&nbsp;-->
												<!--<input class='edit rounded' type="text" size="2" name="<?php echo $myMatch['MatchId']."Team1"; ?>" maxlength="2" value="<?php echo $tabPlayerBet[0];  ?>" <?php echo ($myMatch['BetClosed'] ? "disabled readonly" : "") ?>>-->
												<ul class="rounded" style="margin: 2px 2px 2px 2px;">
													<li style="height: 7px; padding-top: 5px;">
														<select <?php if ($myMatch['BetClosed']) echo "DISABLED class=withoutChevron"; ?> id="<?php echo $myMatch['MatchId']."Team1"; ?>" name="<?php echo $myMatch['MatchId']."Team1"; ?>" style="height: 15px;padding: 0;margin: 0;vertical-align:top;font-size:12px">
															<?php
															for ($i=0; $i<=99; $i++){
																if ($tabPlayerBet[0] == $i)
																	echo '<option selected value ="'.$i.'">'.$i.'</option>';
																else
																	echo '<option value ="'.$i.'">'.$i.'</option>';
															}
															?>
														</select>
													</li>
												</ul>
											</td>
										</tr>
										<tr>
											<td width=15% class=smallBoldDark align=left>
												<b><?php echo $colorStart.formatString($myMatch['Team2']).$colorEnd; ?></b>
											</td>
											<td width=10% class="smallBoldDark" align="left">
												<!--<input class='edit rounded' type="text" size="2" name="<?php echo $myMatch['MatchId']."Team2"; ?>" maxlength="2" value="<?php echo $tabPlayerBet[1] ?>" <?php echo ($myMatch['BetClosed'] ? "disabled readonly" : "") ?>>&nbsp; <!--<IMG align=absmiddle SRC="<?php echo $IMAGES_DIR.flag($myMatch[Team2]) ?>">-->

												<ul class="rounded" style="margin: 2px 2px 2px 2px;">
													<li style="height: 7px;padding-top: 5px;">
														<select <?php if ($myMatch['BetClosed']) echo "DISABLED class=withoutChevron"; ?> id="<?php echo $myMatch['MatchId']."Team2"; ?>" name="<?php echo $myMatch['MatchId']."Team2"; ?>" style="height: 15px;padding: 0;margin: 0;vertical-align:top;font-size:12px">
															<?php
															for ($i=0; $i<=99; $i++){
																if ($tabPlayerBet[1] == $i)
																	echo '<option selected value ="'.$i.'">'.$i.'</option>';
																else
																	echo '<option value ="'.$i.'">'.$i.'</option>';
															}
															?>
														</select>
													</li>
												</ul>
											</td>
										<tr>
											<td>Mise </td><!--(max <span class="miseMaxClass"></span>)-->
											<td class="smallBoldDark" align="center" >
												<ul class="rounded" style="margin: 2px 2px 2px 2px;">
													<li style="height: 7px;padding-top: 5px;">
														<input class="Mise" type="text" size="2" 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" : "")  ?> style="height: 15px;padding: 0;margin: 0;vertical-align:top;font-size:12px">
													</li>
												</ul>
											</td>
										</tr>

									</table>
								</li>
							<?php
							}
							?>
							</ul>

							<table width="100%" >

							<!--#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="redirectPage" value="<?php echo $redirectPage; ?>">-->
							<tr align=center>
								<td  align=center class=smallDark><div id="errorMess" style="color:red"><?php echo $error; ?></div></td>
							</tr>
							<tr align=center>
								<td  align=center class=smallDark>
									<div >
										<center>
											<table >
												<tr>
													<td align="left">
														Total Points
													</td>
													<td>
														:
													</td>
													<td align="right">
														<?php echo number_format($player['Score'] ,0,""," ")?> pts.
														<input type="hidden" id="playerScore" value="<?php echo $player['Score']; ?>">
													</td>
												</tr>
												<tr>
													<td align="left">
														D&eacute;j&agrave; mis&eacute;s
													</td>
													<td>
														:
													</td>
													<td align="right">
														<div id="consumed"><?php echo number_format($consumed_points ,0,""," ")?> pts.</div>
														<input type="hidden" id="consumedScore" value="<?php echo $consumed_points; ?>">
													</td>
												</tr>
												<!--
												!! ATTENTION EN CAS DE SUPPRESSION DU COMMENTAIRE AU DOUBLON D'id
												<tr>
													<td align="left">
														Reste &agrave; miser :
													</td>
													<td align="right">
														<div id="remaining"><?php //echo $remaining_points; ?></div>
													</td>
												</tr>
												<tr>
													<td align="center" colspan="2">
														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>

							
							<?php
							//if (!$betIsClosed)
							//{
							?>
								<tr align=center>
									<td colspan=8 align=center class=smallDark>
										<br>
										<INPUT TYPE="hidden" NAME="valide" ID="valide" VALUE="Valider">
										<!--<input type=submit name=submit value="Valider" class="submit whiteButton" style="margin-top:-10px;color:rgba(0,0,0,.9)" >-->
										<input type="submit" name="submit" onclick="submitForm(<?php echo $containerId; ?>,<?php echo $categoryId; ?>);" value="Valider" class="submit whiteButton" style="color:rgba(0,0,0,.9);width:100%;height:50px;padding-top:-15px;background-color:#59595f;" >
										<br><br>
									</td>
								</tr>
							<?php
							/*}
							else
								echo "<tr><td><br><br><br></td></tr>";*/
							?>
					
							</table><!--
						</li>
					</ul>
				</div>
			</div>
		</td>
	</tr>
</table>-->

</form>

